@markus-global/cli 0.11.2 → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/start.js +5 -2
- package/dist/commands/start.js.map +1 -1
- package/dist/markus.mjs +1254 -1121
- package/dist/web-ui/assets/{CommentInput-Cgu8208h.js → CommentInput-DN3Cichs.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-rzRUDj8T.js → ContentRenderer-CjHOyYgJ.js} +2 -2
- package/dist/web-ui/assets/{DeliverableShareModal-BvfmqTNG.js → DeliverableShareModal-CBSvxB-X.js} +1 -1
- package/dist/web-ui/assets/{Deliverables-DKTLnaF8.js → Deliverables-BaAF4-w0.js} +1 -1
- package/dist/web-ui/assets/{Notifications-CWaO9onn.js → Notifications-CCsdBfdg.js} +1 -1
- package/dist/web-ui/assets/{Search-D_C5Eyed.js → Search-BiBdevAU.js} +1 -1
- package/dist/web-ui/assets/{Settings-B5Ib6SFf.js → Settings-CawBnWuy.js} +6 -6
- package/dist/web-ui/assets/{Store-D__pfqoc.js → Store-BWi97VP9.js} +1 -1
- package/dist/web-ui/assets/Team-CfUDkdc3.js +84 -0
- package/dist/web-ui/assets/{Work-BJ7kXixx.js → Work-DrIXOW-P.js} +1 -1
- package/dist/web-ui/assets/{arc-BN0GMYN6.js → arc-Cg0-C295.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BP5Nnl2Y.js → architectureDiagram-3BPJPVTR-BctEHNLp.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-nKHUCU_z.js → blockDiagram-GPEHLZMM-hxr2ZwOV.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-DoS0wcHh.js → c4Diagram-AAUBKEIU-CfIRo1GE.js} +1 -1
- package/dist/web-ui/assets/channel-DAQ2Rbxq.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-CP54_XNl.js → chunk-2J33WTMH-T0bENsqX.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-DMvJaJb7.js → chunk-4BX2VUAB-ChLLkyYx.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-DQnZgoOO.js → chunk-55IACEB6-BD3ENYp9.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-B5_3LI53.js → chunk-727SXJPM-BAes4atE.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-B5Mh5bI_.js → chunk-AQP2D5EJ-FymM7gfT.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-mjYTpuBm.js → chunk-FMBD7UC4-N5sRT0m9.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-BxTrseJg.js → chunk-ND2GUHAM-BSjS3JyS.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-C1do5brE.js → chunk-QZHKN3VN-Dkwitdbr.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BZyCVtJb.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BZyCVtJb.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DMn7aSDK.js → cose-bilkent-S5V4N54A-BLuYATCK.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-CE-tTagY.js → dagre-BM42HDAG-DGLiqiH2.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-BwyvxbJa.js → diagram-2AECGRRQ-Cq_GnNKs.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-Nopndxl0.js → diagram-5GNKFQAL-CHNz-2dA.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-CGTjHHnD.js → diagram-KO2AKTUF-D8eKa7jh.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-DhC3AqLA.js → diagram-LMA3HP47-RkDgQcLr.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-BIuzyWJO.js → diagram-OG6HWLK6-LqxQrIwa.js} +1 -1
- package/dist/web-ui/assets/{docx-preview-ClO_djcO.js → docx-preview-Be-Qo_ag.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-Nmfi9Wv0.js → erDiagram-TEJ5UH35-BX0zZgYQ.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BVAM5QzO.js → flowDiagram-I6XJVG4X-DKnfIFA4.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-BGdTbY0A.js → ganttDiagram-6RSMTGT7-DjBURmY-.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BMfug5mp.js → gitGraphDiagram-PVQCEYII-BvSi7SvS.js} +1 -1
- package/dist/web-ui/assets/{index-1X1Ykov8.js → index-D8vskks7.js} +72 -72
- package/dist/web-ui/assets/index-DEN_qReg.css +1 -0
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-DAqSLNMU.js → infoDiagram-5YYISTIA-CwtIgim2.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-Bro4RrlG.js → ishikawaDiagram-YF4QCWOH-CWhXJfSa.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-CdRHOaID.js → journeyDiagram-JHISSGLW-DN9rorlL.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-9iLNl-rB.js → kanban-definition-UN3LZRKU-Burf5FE8.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-BRHCbDDt.js → mermaid.core-Dx4rzlyC.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BLm-XQ6W.js → mindmap-definition-RKZ34NQL-DqZ21Siw.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-ith90T5A.js → pieDiagram-4H26LBE5-C_4ksu-T.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-Cb08oHG7.js → quadrantDiagram-W4KKPZXB-Dl6Rjg1X.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-DzMKi4w8.js → requirementDiagram-4Y6WPE33-CzmWi02d.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-C0Wv4A7m.js → sankeyDiagram-5OEKKPKP-D8K7e8we.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-C_HL9WB0.js → sequenceDiagram-3UESZ5HK-1z9rqtVx.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-BFfTVEYQ.js → stateDiagram-AJRCARHV-nneYkkHa.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-C-hpzcms.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-cyPnAADn.js → timeline-definition-PNZ67QCA-D6GmLlRi.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-Cb82-9OZ.js → vennDiagram-CIIHVFJN-TVefhiCa.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-BTW1NXXR.js → wardley-L42UT6IY-BgUuAeiM.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-C_F_dT6n.js → wardleyDiagram-YWT4CUSO-CyJ_l94o.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-clcfplhG.js → xychartDiagram-2RQKCTM6-kajbbx7a.js} +1 -1
- package/dist/web-ui/index.html +2 -2
- package/docs/README.md +93 -0
- package/docs/api/api.md +353 -0
- package/docs/architecture/agent-runtime.md +341 -0
- package/docs/architecture/architecture-fragility.md +184 -0
- package/docs/architecture/architecture.md +938 -0
- package/docs/architecture/cognitive-architecture.md +322 -0
- package/docs/architecture/concurrent-processing.md +550 -0
- package/docs/architecture/frontend/team-chat.md +312 -0
- package/docs/architecture/learning-loop.md +340 -0
- package/docs/architecture/llm-provider-timeouts.md +60 -0
- package/docs/architecture/mailbox-system.md +1635 -0
- package/docs/architecture/memory-system.md +533 -0
- package/docs/architecture/prompt-engineering.md +1377 -0
- package/docs/architecture/state-machines.md +665 -0
- package/docs/architecture/state-ownership.md +83 -0
- package/docs/architecture/streaming-and-reattach.md +193 -0
- package/docs/architecture/tool-system.md +266 -0
- package/docs/design/deliverable-sharing.md +238 -0
- package/docs/guides/coding-tools.md +765 -0
- package/docs/guides/community.md +104 -0
- package/docs/guides/development.md +179 -0
- package/docs/guides/guide.md +362 -0
- package/docs/guides/release-and-distribution.md +165 -0
- package/docs/guides/remote-access.md +286 -0
- package/docs/guides/skill-ecosystem.md +129 -0
- package/docs/records/agent-platform-friction-2026-10.md +98 -0
- package/docs/records/animation-budget-focus-vs-visibility-2026-10-08.md +110 -0
- package/docs/records/audit-fixes-2026-09.md +173 -0
- package/docs/records/branch-consolidation.md +597 -0
- package/docs/records/file-edit-literal-replacement-fix.md +132 -0
- package/docs/records/message-stop-cancel-fix-plan.md +209 -0
- package/docs/records/platform-hardening-2026-10.md +1365 -0
- package/docs/records/session-identity-plan.md +130 -0
- package/docs/records/settings-model-routing-first-visit-fix.md +101 -0
- package/docs/records/team-chat-stream-transport-vs-turn-2026-10-08.md +152 -0
- package/package.json +2 -1
- package/templates/roles/HANDBOOK.md +12 -7
- package/dist/web-ui/assets/Team-FFbGLcXj.js +0 -84
- package/dist/web-ui/assets/channel-C_kHFvaW.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-UF2PuXCi.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-UF2PuXCi.js +0 -1
- package/dist/web-ui/assets/index-3PQIqBtv.css +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DuO1A2q2.js +0 -1
|
@@ -0,0 +1,1635 @@
|
|
|
1
|
+
# Mailbox & Attention System
|
|
2
|
+
|
|
3
|
+
> Last updated: 2026-07
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Design Philosophy
|
|
8
|
+
|
|
9
|
+
Markus agents are modelled as **entities that focus on one thing at a time**. Like a human employee, an agent must not hold two conflicting beliefs about the same piece of work. When multiple stimuli arrive concurrently — chat messages, task assignments, status updates, review requests — the agent must make deliberate decisions about what to attend to and in what order.
|
|
10
|
+
|
|
11
|
+
This is implemented through two core abstractions:
|
|
12
|
+
|
|
13
|
+
- **Agent Mailbox** — A priority queue that serialises all incoming stimuli.
|
|
14
|
+
- **Attention Controller** — An event-driven focus manager that processes mailbox items one at a time, with interrupt handling at safe yield points.
|
|
15
|
+
|
|
16
|
+
**Concurrent processing (default on, opt-out).** The attention loop can instead run as a pool of N isolated **worker loops** so the agent handles several *independent* entities at once — see [concurrent-processing.md](./concurrent-processing.md). Serialisation is preserved **per entity**: an entity-affinity lock in the mailbox guarantees a given task / requirement / conversation / user is never processed by two workers simultaneously, and each worker holds its own `SessionWorkspace`, so the "one thing at a time" guarantee still holds for any single line of work. Setting `agent.concurrent.enabled = false` (or `maxWorkers = 1`) restores a strictly single-worker loop with identical behaviour to the original design.
|
|
17
|
+
|
|
18
|
+
### Why was processing originally serialised?
|
|
19
|
+
|
|
20
|
+
Early Markus let an agent handle multiple messages simultaneously, which caused:
|
|
21
|
+
- **Memory contamination** — Concurrent conversations polluted each other's session context.
|
|
22
|
+
- **Cognitive interference** — An agent composing a code review could be mid-thought when a chat message hijacked its attention.
|
|
23
|
+
- **Non-deterministic behaviour** — Race conditions in shared state made debugging nearly impossible.
|
|
24
|
+
|
|
25
|
+
The mailbox model fixed this by treating the agent's attention as a scarce, serial resource. Concurrent processing re-introduces parallelism **only *between* entities**, and addresses each of these three failures directly:
|
|
26
|
+
|
|
27
|
+
- **Memory contamination** → per-worker [`SessionWorkspace`](../../packages/core/src/session-workspace.ts) isolation via `AsyncLocalStorage`.
|
|
28
|
+
- **Cognitive interference** → concurrent worker loops are pure consumers; triage / deliberation / preempt logic runs only in the serial loop.
|
|
29
|
+
- **Non-deterministic races** → entity-affinity lock in the mailbox + an agent-level tool write-lock.
|
|
30
|
+
|
|
31
|
+
See [concurrent-processing.md](./concurrent-processing.md) for the full guarantees, configuration, and known limitations.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## 2. Architecture
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
External Events Agent Internals
|
|
39
|
+
───────────── ───────────────
|
|
40
|
+
human_chat ──┐
|
|
41
|
+
a2a_message ──┤ ┌──────────────┐
|
|
42
|
+
task_status ──┤ enqueue() │ AgentMailbox │ priority queue + dedup
|
|
43
|
+
task_comment ──┼────────────────►│ (per agent) │ sorted by priority + FIFO
|
|
44
|
+
req_comment ──┤ └──────┬───────┘
|
|
45
|
+
review_req ──┤ │ dequeueAsync()
|
|
46
|
+
system_event──┤ ▼
|
|
47
|
+
heartbeat ────┤ ┌──────────────────┐
|
|
48
|
+
session_reply──┤ │ AttentionController│ event-driven loop
|
|
49
|
+
daily_report ──┤ │ state: idle → │
|
|
50
|
+
callback_result┤ │ focused → idle │
|
|
51
|
+
memory_consol──┘ └──────┬───────────┘
|
|
52
|
+
│ delegate.processMailboxItem()
|
|
53
|
+
▼
|
|
54
|
+
┌──────────────┐
|
|
55
|
+
│ Agent Core │ handleMessage / executeTask
|
|
56
|
+
│ (internal) │ handleHeartbeat / respondInSession
|
|
57
|
+
└──────────────┘
|
|
58
|
+
|
|
59
|
+
PendingCallbackRegistry ──enqueue('callback_result')──► AgentMailbox (async op completions)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
> **Concurrent mode:** `AttentionController` may run `N` worker loops instead of one
|
|
63
|
+
> (`launchWorkerPool()`), each dequeuing its own item and mounting an isolated
|
|
64
|
+
> `SessionWorkspace`. The mailbox skips any item whose *entity key* is already locked by
|
|
65
|
+
> another worker, so a single entity is still processed one item at a time. The diagram
|
|
66
|
+
> above shows the single-worker (serial) shape; the concurrent shape is
|
|
67
|
+
> `AttentionController → N × (dequeueAsync → lockEntities → processFocusedItem → unlockEntities)`.
|
|
68
|
+
> See [concurrent-processing.md](./concurrent-processing.md).
|
|
69
|
+
|
|
70
|
+
<!-- verified-against-code: 2026-09-11, packages/core/src/attention.ts:798-806 -->
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## 3. Mailbox Item Types — Centralised Type Registry
|
|
75
|
+
|
|
76
|
+
### 3.1 Single Source of Truth
|
|
77
|
+
|
|
78
|
+
All mailbox item types, their metadata, and their processing behaviour are defined in **one place**: `MAILBOX_TYPE_REGISTRY` in `@markus/shared`. Every other module (core routing, attention heuristics, default priorities, frontend filters/labels/icons) reads from this registry.
|
|
79
|
+
|
|
80
|
+
> **Target — not yet enforced: no string literals for type values outside the registry and the shared type union.** At present some consumers still hardcode type values as literals, e.g. the attention heuristics in `packages/core/src/attention.ts:1532-1580` (`'human_chat'`, `'task_comment'`, `'requirement_update'`, `'requirement_comment'`) and the `USER_INTERACTION_TYPES` / `PEER_INTERACTION_TYPES` sets at `packages/core/src/attention.ts:1493-1500`. The goal is to converge these onto registry-driven predicates; until then this constraint is aspirational, **not** a completed invariant.
|
|
81
|
+
|
|
82
|
+
<!-- verified-against-code: 2026-09-11, packages/core/src/attention.ts:1493-1500,1532-1580 -->
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
// @markus/shared — packages/shared/src/types/mailbox.ts
|
|
86
|
+
|
|
87
|
+
export const MAILBOX_TYPE_REGISTRY: Record<MailboxItemType, MailboxTypeDescriptor> = {
|
|
88
|
+
system_event: { label: 'System Event', defaultPriority: 1, category: 'system', icon: '⚙', activityType: 'internal', createsActivity: true, invokesLLM: true },
|
|
89
|
+
human_chat: { label: 'Chat', defaultPriority: 0, category: 'interaction', icon: '💬', activityType: 'chat', createsActivity: true, invokesLLM: true },
|
|
90
|
+
task_comment: { label: 'Task Comment', defaultPriority: 2, category: 'task', icon: '💬', activityType: null, createsActivity: false, invokesLLM: false },
|
|
91
|
+
mention: { label: 'Mention', defaultPriority: 1, category: 'interaction', icon: '@', activityType: 'chat', createsActivity: true, invokesLLM: true },
|
|
92
|
+
session_reply: { label: 'Session Reply', defaultPriority: 1, category: 'task', icon: '↩', activityType: 'respond_in_session', createsActivity: true, invokesLLM: true },
|
|
93
|
+
task_status_update: { label: 'Task Status', defaultPriority: 1, category: 'task', icon: '📋', activityType: null, createsActivity: true, invokesLLM: false },
|
|
94
|
+
a2a_message: { label: 'Agent Message', defaultPriority: 2, category: 'interaction', icon: '🔗', activityType: 'a2a', createsActivity: true, invokesLLM: true },
|
|
95
|
+
review_request: { label: 'Review Request', defaultPriority: 1, category: 'task', icon: '👀', activityType: 'chat', createsActivity: true, invokesLLM: true },
|
|
96
|
+
requirement_comment: { label: 'Requirement Comment', defaultPriority: 2, category: 'task', icon: '💬', activityType: null, createsActivity: false, invokesLLM: false },
|
|
97
|
+
requirement_update: { label: 'Requirement Update', defaultPriority: 1, category: 'notification', icon: '📝', activityType: 'internal', createsActivity: true, invokesLLM: false },
|
|
98
|
+
daily_report: { label: 'Daily Report', defaultPriority: 2, category: 'system', icon: '📊', activityType: 'internal', createsActivity: true, invokesLLM: true },
|
|
99
|
+
heartbeat: { label: 'Heartbeat', defaultPriority: 3, category: 'system', icon: '♡', activityType: 'heartbeat', createsActivity: true, invokesLLM: true },
|
|
100
|
+
memory_consolidation: { label: 'Memory Consolidation', defaultPriority: 4, category: 'system', icon: '🧠', activityType: 'internal', createsActivity: true, invokesLLM: true },
|
|
101
|
+
workflow_update: { label: 'Workflow Update', defaultPriority: 2, category: 'task', icon: '🔄', activityType: 'internal', createsActivity: true, invokesLLM: true },
|
|
102
|
+
callback_result: { label: 'Callback Result', defaultPriority: 1, category: 'system', icon: '↩', activityType: 'internal', createsActivity: true, invokesLLM: true },
|
|
103
|
+
};
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
<!-- verified-against-code: 2026-09-11, packages/shared/src/types/mailbox.ts:3-18,102-118 -->
|
|
107
|
+
|
|
108
|
+
### 3.2 Type Descriptor Schema
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
export interface MailboxTypeDescriptor {
|
|
112
|
+
label: string; // Human-readable display name
|
|
113
|
+
defaultPriority: MailboxPriority; // 0=critical, 1=high, 2=normal, 3=low, 4=background
|
|
114
|
+
category: MailboxCategory; // Filter group for UI
|
|
115
|
+
icon: string; // Emoji/icon for UI display
|
|
116
|
+
activityType: string | null; // Derived agent_activities.type (null = set at runtime)
|
|
117
|
+
createsActivity: boolean; // Whether processing normally creates an activity record
|
|
118
|
+
invokesLLM: boolean; // Whether processing invokes an LLM call
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type MailboxCategory = 'interaction' | 'task' | 'notification' | 'system';
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### 3.3 Filter Categories
|
|
125
|
+
|
|
126
|
+
The frontend uses `category` for filtering. Users can also filter by individual `sourceType`.
|
|
127
|
+
|
|
128
|
+
| Category | Types | Description |
|
|
129
|
+
|----------|-------|-------------|
|
|
130
|
+
| `interaction` | `human_chat`, `a2a_message`, `mention` | Direct conversations with humans or agents |
|
|
131
|
+
| `task` | `task_status_update`, `task_comment`, `requirement_comment`, `review_request`, `session_reply`, `workflow_update` | Task & requirement lifecycle events (including execution triggers) |
|
|
132
|
+
| `notification` | `requirement_update` | Status change notifications |
|
|
133
|
+
| `system` | `system_event`, `heartbeat`, `daily_report`, `memory_consolidation`, `callback_result` | Internal agent processes |
|
|
134
|
+
|
|
135
|
+
<!-- verified-against-code: 2026-09-11, packages/shared/src/types/mailbox.ts:121-126 -->
|
|
136
|
+
|
|
137
|
+
### 3.4 Special Processing Rules
|
|
138
|
+
|
|
139
|
+
**`task_status_update` — Execution vs. Informational**
|
|
140
|
+
|
|
141
|
+
`task_status_update` serves as the **unified trigger for all task lifecycle events**. It operates in two modes:
|
|
142
|
+
|
|
143
|
+
1. **Execution mode** (`extra.triggerExecution = true`): When a task transitions to `in_progress` and needs execution, `TaskService.runTask()` sends a `task_status_update` with execution context (onLog, cancelToken, workspace, executionRound) via `agent.sendTaskExecution()`. The agent processes this by calling `executeTask()` — the full task execution loop. Priority is set to 1 (high).
|
|
144
|
+
|
|
145
|
+
2. **Informational mode** (default, `invokesLLM: false`): For non-execution status changes (e.g., cancelled, blocked, completed), the item is **auto-completed without LLM invocation**. The agent logs the status change for awareness but does not spend tokens processing it. These transitions are handled by the system (FSM side-effects) and need no agent action.
|
|
146
|
+
|
|
147
|
+
When `updateTaskStatus()` triggers auto-start execution, the separate notification is **skipped** to avoid redundant processing. The execution-mode `task_status_update` serves as both trigger and notification.
|
|
148
|
+
|
|
149
|
+
Similarly, when a task transitions from `in_progress` to `review` (via `task_submit_review`), the assignee notification is skipped — the assignee itself initiated the submission and already knows the state change. Only the reviewer receives a `review_request` notification.
|
|
150
|
+
|
|
151
|
+
**Silent Transitions**: Certain system-managed transitions never produce a `task_status_update` notification because the real mechanism (cancel token or auto-start) already handles the work:
|
|
152
|
+
|
|
153
|
+
| Transition | Reason suppressed |
|
|
154
|
+
|-----------|-------------------|
|
|
155
|
+
| `blocked -> in_progress` | Auto-start fires a separate execution-mode item |
|
|
156
|
+
| `in_progress -> blocked` | Cancel token stops execution; notification is redundant |
|
|
157
|
+
|
|
158
|
+
These are defined in `TaskService.SILENT_TRANSITIONS` and checked early in `maybeNotifyAssignee()`.
|
|
159
|
+
|
|
160
|
+
**`requirement_update` — Conditional LLM Processing**
|
|
161
|
+
|
|
162
|
+
`requirement_update` is `invokesLLM: false` by default. Most requirement status transitions are informational — the agent is auto-notified without an LLM call.
|
|
163
|
+
|
|
164
|
+
There are three exceptions where `extra.actionRequired = true` triggers an LLM call with `scenario: 'requirement_action'`:
|
|
165
|
+
|
|
166
|
+
1. **Approval** (`priority: 1`): When a requirement is approved, the creator agent is prompted to create tasks to fulfill it. This is high priority because the user expects immediate follow-up.
|
|
167
|
+
2. **Rejection** (`priority: 1`): When a requirement is rejected, the agent decides whether to resubmit with updates via `requirement_resubmit` or abandon the requirement.
|
|
168
|
+
3. **All tasks done — review needed** (`priority: 2`): When all linked tasks reach terminal state, instead of auto-completing the requirement, the system notifies the creator agent. The agent reviews results and decides whether to mark the requirement as `completed` or create additional tasks.
|
|
169
|
+
|
|
170
|
+
**`requirement_comment` — Direct Discussion on Requirements**
|
|
171
|
+
|
|
172
|
+
`requirement_comment` is dedicated to threaded comments on requirements (analogous to `task_comment` for tasks). Unlike `requirement_update` (which covers status/decision notifications), `requirement_comment` represents interactive dialogue — questions, feedback, coordination.
|
|
173
|
+
|
|
174
|
+
Processing follows the same pattern as `task_comment`: `createsActivity: false`, `invokesLLM: false`. If the requirement has an active agent context, the comment is injected; otherwise it falls back to `handleMessage` with `scenario: 'comment_response'`, following the context-first protocol (§3.5).
|
|
175
|
+
|
|
176
|
+
**`task_comment` — Live Session Injection**
|
|
177
|
+
|
|
178
|
+
`task_comment` has a unique behaviour: when the referenced task is **actively being executed**, the comment is **injected into the running LLM session** (`injectUserMessage`) rather than creating a new activity. This means:
|
|
179
|
+
- `createsActivity: false` — it does not always create an activity (but the merge decision IS recorded)
|
|
180
|
+
- `invokesLLM: false` — it does not invoke a new LLM call; the injected text becomes part of the current task's next LLM turn
|
|
181
|
+
- If the task is NOT active, it falls back to `handleMessage` and DOES create an activity
|
|
182
|
+
|
|
183
|
+
### 3.5 Context-First Protocol for Comments
|
|
184
|
+
|
|
185
|
+
When processing `task_comment` (on inactive tasks) or `requirement_comment`, the agent uses `scenario: 'comment_response'`. This instructs the LLM to follow a mandatory context-gathering protocol **before** replying:
|
|
186
|
+
|
|
187
|
+
1. **Fetch the full item** — call `task_get` or `requirement_list` to get the complete current state
|
|
188
|
+
2. **Read ALL previous comments** — understand the full conversation thread
|
|
189
|
+
3. **Identify the commenter's intent** — question, request, feedback, objection, etc.
|
|
190
|
+
4. **Check related context** — look up referenced tasks, requirements, or files
|
|
191
|
+
|
|
192
|
+
Only after completing these steps does the agent formulate its reply. This prevents superficial responses that ignore important context already discussed in the comment thread.
|
|
193
|
+
|
|
194
|
+
The notification text sent to agents also includes explicit MANDATORY instructions reinforcing this protocol.
|
|
195
|
+
|
|
196
|
+
**Structural reply-to**: Both `task_comment` and `requirement_comment` tools support a `reply_to_comment_id` parameter that creates a structural link to the parent comment. The `task_comments` and `requirement_comments` tables have a `reply_to_id` column; when queried, a LEFT JOIN returns the parent comment's author and content snippet (`replyToAuthor`, `replyToContent`). The notification payload also injects an agent streak count (consecutive agent-only comments) to help agents decide whether further replies are warranted.
|
|
197
|
+
|
|
198
|
+
**Batch awareness**: The `comment_response` scenario prompt instructs agents to handle multiple bundled comments (separated by `---`) as a single consolidated reply, using `reply_to_comment_id` for the most important one and quoting others inline.
|
|
199
|
+
|
|
200
|
+
Priorities can be overridden per-item when enqueuing.
|
|
201
|
+
|
|
202
|
+
### 3.6 Review Comment Cascade Suppression
|
|
203
|
+
|
|
204
|
+
When a reviewer (agent or human) posts `task_comment` during an active review (`task.status === 'review'` and `authorId === task.reviewerId`), the automatic `task_comment` notifications to the worker and creator agents are suppressed. Only explicit `@mention` notifications are delivered.
|
|
205
|
+
|
|
206
|
+
**Rationale**: Without this guard, the reviewer's intermediate comments trigger a notification cascade:
|
|
207
|
+
1. Reviewer posts comment → worker/creator receive `task_comment`
|
|
208
|
+
2. Worker processes notification with full LLM → may send A2A message back to reviewer
|
|
209
|
+
3. Reviewer processes A2A message → posts redundant second review
|
|
210
|
+
|
|
211
|
+
The review outcome is properly communicated through the status transition (`completed` or `in_progress` revision), not intermediate comments.
|
|
212
|
+
|
|
213
|
+
**`callback_result` — Async Operation Completions**
|
|
214
|
+
|
|
215
|
+
`callback_result` delivers the outcome of asynchronous operations back to the originating agent through the mailbox (priority **1 — high**). It replaces the legacy pattern of injecting results directly into an active LLM session via `injectUserMessage`, ensuring completions enter the attention loop like any other stimulus.
|
|
216
|
+
|
|
217
|
+
Typical sources:
|
|
218
|
+
|
|
219
|
+
1. **`background_exec` completion** — When a background shell process finishes, the agent receives a `callback_result` with exit code, duration, and stdout/stderr tail.
|
|
220
|
+
2. **In-session A2A reply** — When an agent sends `agent_send_message` with `reply_in_session: true` (deprecated alias: `await_in_session`), an `a2a_reply` callback is registered (correlated by `conversation_id`). The peer's reply is routed back into the **origin session** instead of a separate a2a session.
|
|
221
|
+
|
|
222
|
+
**Two delivery forms.** A resolved callback is delivered one of two ways, selected by `deliveryMode`:
|
|
223
|
+
|
|
224
|
+
- **`in_session`** → enqueues a `callback_result` bound to `originSessionId`, resuming the current conversation (used for `background_exec` completions and `reply_in_session` A2A replies).
|
|
225
|
+
- **`mailbox`** → enqueues a `system_event`, a fresh attention cycle (used for `schedule_wakeup` firings and autonomous follow-ups).
|
|
226
|
+
|
|
227
|
+
Payload shape (`payload.extra`):
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
{
|
|
231
|
+
callbackId: string; // Registry ID (matches pending callback)
|
|
232
|
+
originSessionId: string; // Session to resume context in (in_session mode)
|
|
233
|
+
callbackType: 'background_exec' | 'wakeup' | 'a2a_reply';
|
|
234
|
+
correlationId?: string; // conversation_id for a2a_reply
|
|
235
|
+
exitCode?: number; // For background_exec
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Processing: `in_session` callbacks route to `handleMessage()` with the **originating session** (`originSessionId`) so the agent continues where it left off. Falls back to a fresh system session if origin is unknown. `invokesLLM: true`, `createsActivity: true`.
|
|
240
|
+
|
|
241
|
+
Registration flow: when an agent starts an async operation the completion is registered as a `PendingCallback` in `PendingCallbackRegistry` and persisted to SQLite:
|
|
242
|
+
|
|
243
|
+
- `background_exec` — the `background_exec` tool path calls `registerBackgroundSession()` (from `Agent.executeTool`, keyed by the returned bg session id, `originSessionId = active session`).
|
|
244
|
+
- `agent_send_message` with `reply_in_session` (alias `await_in_session`) — registers an `a2a_reply` callback keyed by `conversation_id`.
|
|
245
|
+
- `schedule_wakeup` — registers a `wakeup` callback with a `wakeAt` timestamp (and optional `recurringMs`).
|
|
246
|
+
|
|
247
|
+
On completion/firing the registry entry is resolved and delivered via the shared `Agent.deliverCallback()` helper according to its `deliveryMode`.
|
|
248
|
+
|
|
249
|
+
See §11.3 for the full `PendingCallbackRegistry` specification.
|
|
250
|
+
|
|
251
|
+
---
|
|
252
|
+
|
|
253
|
+
## 4. Attention Controller
|
|
254
|
+
|
|
255
|
+
### States
|
|
256
|
+
|
|
257
|
+
```
|
|
258
|
+
idle ──► focused ──► idle
|
|
259
|
+
│ ▲
|
|
260
|
+
▼ │
|
|
261
|
+
deciding
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
- **idle** — Waiting for mail. Blocks on `mailbox.dequeueAsync()`.
|
|
265
|
+
- **focused** — Processing a single mailbox item. All new mail triggers an interrupt signal.
|
|
266
|
+
- **deciding** — Evaluating whether to continue, preempt, cancel, merge, or defer (at a yield point).
|
|
267
|
+
|
|
268
|
+
### Event-Driven Interrupts
|
|
269
|
+
|
|
270
|
+
There is **no polling**. When a new item arrives while the agent is focused:
|
|
271
|
+
|
|
272
|
+
1. The mailbox emits `mailbox:new-item` via the EventBus.
|
|
273
|
+
2. The `AttentionController` sets an **interrupt signal**.
|
|
274
|
+
3. At the next **safe yield point** (between LLM turns in the tool loop), the agent calls `checkYieldPoint()`.
|
|
275
|
+
4. The controller evaluates the pending item using **heuristics first** (fast, no LLM call), then optionally falls back to an **LLM interrupt judge** for ambiguous cases where heuristics return `continue`. The LLM judge sees both the current work context and the full content of the new message, enabling it to understand semantic intent (e.g., "stop publishing" → cancel, "hold off for now" → preempt).
|
|
276
|
+
|
|
277
|
+
### Decision Types
|
|
278
|
+
|
|
279
|
+
| Decision | Effect |
|
|
280
|
+
|----------|--------|
|
|
281
|
+
| `pick` | Item dequeued from idle state (initial selection) |
|
|
282
|
+
| `continue` | New item not urgent enough — keep working on current focus |
|
|
283
|
+
| `preempt` | **Pause** current work — session is **deferred for later resumption**. The agent switches to the new item. When the agent becomes idle, `resurfaceDue()` automatically re-queues the deferred item for continued processing. |
|
|
284
|
+
| `cancel` | **Permanently stop** current work — the item is **dropped and will NOT be resumed**. Used when the new message explicitly revokes or contradicts the current work (e.g., "cancel that task", "don't publish this"). |
|
|
285
|
+
| `merge` | Absorb new item into current work (e.g., comment on current task) |
|
|
286
|
+
| `defer` | Explicitly postpone the new item |
|
|
287
|
+
| `delegate` | Hand off to another agent (future) |
|
|
288
|
+
| `drop` | Discard the item |
|
|
289
|
+
|
|
290
|
+
### Preempt vs Cancel Semantics
|
|
291
|
+
|
|
292
|
+
These two decisions handle fundamentally different situations:
|
|
293
|
+
|
|
294
|
+
- **Preempt (pause)**: "暂停" — The current work is saved. The mailbox item is moved to `deferred` status and will automatically resurface when the agent is idle. Session context (conversation history) is preserved by `sessionId`, so processing continues from where it left off.
|
|
295
|
+
- **Cancel (stop)**: "取消" — The current work is permanently abandoned. The mailbox item is marked as `completed` and will NOT be resumed. Used when the incoming message explicitly revokes or invalidates the current work.
|
|
296
|
+
|
|
297
|
+
The heuristic interrupt rules (`heuristicDecision`) never produce `cancel` — only the **LLM interrupt judge** can make this semantic distinction, since it requires understanding message content (e.g., distinguishing "wait before deploying" from "cancel the deployment entirely").
|
|
298
|
+
|
|
299
|
+
### Priority Invariant: User Interactions First
|
|
300
|
+
|
|
301
|
+
Only user chat (`human_chat`) is assigned **priority 0 (critical)** — the highest possible level. `task_comment` and `requirement_comment` are **priority 2 (normal)**, not critical. The heuristic rules enforce:
|
|
302
|
+
|
|
303
|
+
1. **R0**: If a new `human_chat` arrives from the **same user** while the agent is already processing that user's previous message, the new message is **merged** (injected into the active session as a follow-up). This avoids unnecessary preemption and allows natural multi-message conversations.
|
|
304
|
+
2. **R1**: If a new `human_chat` arrives while the agent is focused on any non-user work, the agent **always preempts** to handle it immediately. Only `human_chat` is in `USER_INTERACTION_TYPES`, so comments do **not** preempt this way — a `task_comment` / `requirement_comment` on the focused task/requirement is **merged** into context instead (R2 / R3).
|
|
305
|
+
3. When idle with multiple items queued, the priority queue ensures user interactions are dequeued first.
|
|
306
|
+
4. The agent's system prompt includes the **full mailbox queue** (not a truncated view), so the agent is always aware of everything waiting for its attention.
|
|
307
|
+
5. **Deliberation abort**: If a `human_chat` arrives during active deliberation, the deliberation is aborted immediately and the user message is processed first. Deliberation results are discarded; items remain in queue for next cycle.
|
|
308
|
+
|
|
309
|
+
<!-- verified-against-code: 2026-09-11, packages/shared/src/types/mailbox.ts:105-112, packages/core/src/attention.ts:1493-1495,1555-1585 -->
|
|
310
|
+
|
|
311
|
+
### Safe Yield Points
|
|
312
|
+
|
|
313
|
+
Yield points are inserted at natural pauses in the agent's processing pipeline:
|
|
314
|
+
|
|
315
|
+
- **Task execution** (`_executeTaskInternal`): After all tool calls complete and before the next LLM turn. Both `preempt` and `cancel` decisions are honoured:
|
|
316
|
+
- **Preempt** → task session state is saved, mailbox item deferred. When the agent is idle, the deferred item resurfaces and execution resumes with full session context.
|
|
317
|
+
- **Cancel** → mailbox item is dropped permanently. The task may need separate status updates (e.g., `cancelTask`) depending on the cancelling message's intent.
|
|
318
|
+
- **Chat/message handling** (`handleMessage`): After tool results are recorded. Interrupt behaviour depends on the **scenario**:
|
|
319
|
+
- **Non-preemptable** (`chat` only): Only merge decisions are honoured (no preemption/cancellation), since a human user is awaiting a direct response. If a preempt/cancel decision is returned, the interrupt signal is **restored** (not consumed) so the high-priority item is processed immediately after the chat completes.
|
|
320
|
+
- **Preemptable** (all other scenarios: `a2a`, `comment_response`, `requirement_action`, `review`, `heartbeat`, `memory_consolidation`): Full preemption/cancellation is allowed. These either have no real-time human caller waiting, or the caller (another agent, a system process) can tolerate the interruption.
|
|
321
|
+
- **Streaming chat** (`handleMessageStream`): After tool results are recorded. Only merge is honoured (same as non-preemptable `handleMessage`), since a human is receiving a streamed response. Preempt/cancel decisions restore the interrupt signal for immediate processing after the stream completes.
|
|
322
|
+
|
|
323
|
+
### Agent Stop/Pause Behaviour
|
|
324
|
+
|
|
325
|
+
When an agent is stopped (`Agent.stop()`) or paused (`Agent.pause()`):
|
|
326
|
+
1. **Active LLM stream is cancelled** via `cancelActiveStream()` — any in-flight LLM response is aborted immediately.
|
|
327
|
+
2. **Attention loop stops** — `AttentionController.stop()` sets `running = false` and wakes any blocked `dequeueAsync()`.
|
|
328
|
+
3. **In-flight item is preserved** — if processing was in progress, the item is **requeued** (not lost) so it can be picked up when the agent resumes.
|
|
329
|
+
4. **Deferred items survive** — items deferred by preemption remain in the database and will be resurfaced when the agent restarts.
|
|
330
|
+
|
|
331
|
+
### Spec: processing backstop — cancel-on-timeout + single-flight (P0)
|
|
332
|
+
|
|
333
|
+
The attention loop wraps `processMailboxItem` in a generous backstop
|
|
334
|
+
(`MAILBOX_PROCESSING_TIMEOUT_MS`, or `APPROVAL_WAIT_TIMEOUT_MS` while awaiting approval)
|
|
335
|
+
via `Promise.race` in `processFocusedItem`. On timeout the item is **requeued**. Today the
|
|
336
|
+
original processing promise is **not cancelled** — it may still be running, so a requeue can
|
|
337
|
+
re-run tools and double side effects.
|
|
338
|
+
|
|
339
|
+
- **Behavior**: when the backstop fires, the in-flight processing is **cancelled**
|
|
340
|
+
(`AbortController`/cancelToken shared with the LLM/tool path), and a **single-flight
|
|
341
|
+
generation guard** ensures that if the original processing resolves *after* the timeout, its
|
|
342
|
+
result is **discarded** (not persisted, not streamed, not re-completing the item).
|
|
343
|
+
- **Invariants**:
|
|
344
|
+
- After a timeout-requeue, the tool side effects and persistence of the *timed-out*
|
|
345
|
+
attempt happen **at most once** (the orphaned late result is dropped).
|
|
346
|
+
- Requeue still occurs so the item is not lost.
|
|
347
|
+
- Normal (non-timeout) completion is unaffected.
|
|
348
|
+
- **Design rationale (Hermes)**: an interrupted/aborted API call must not inject a
|
|
349
|
+
half-finished result; discard in-flight work rather than racing two writers.
|
|
350
|
+
- **Testing** (`packages/core/test/attention.test.ts` — "A1: cancels in-flight processing
|
|
351
|
+
on backstop timeout…"): a slow turn hits the backstop → `cancelProcessing` is invoked and
|
|
352
|
+
the item is requeued; the original turn resolving late is dropped (no extra
|
|
353
|
+
requeue/complete). The backstop is injectable via `setProcessingTimeoutMs` for
|
|
354
|
+
deterministic testing.
|
|
355
|
+
- **Status**: implemented (`AttentionController.processFocusedItem` cancel-on-timeout +
|
|
356
|
+
`AttentionDelegate.cancelProcessing`, wired in `Agent.createAttentionDelegate`).
|
|
357
|
+
|
|
358
|
+
### Spec: interruptible streaming chat (P1)
|
|
359
|
+
|
|
360
|
+
The **Streaming chat** yield point (above) is non-preemptable by design (a human awaits the
|
|
361
|
+
reply). B3 keeps that principle but distinguishes revocation from preemption: an explicit
|
|
362
|
+
**cancel** decision aborts the in-flight stream and drops the item (`[cancelled]`), while a
|
|
363
|
+
**preempt** restores the signal so the higher-priority item runs right after the turn (no
|
|
364
|
+
mid-answer truncation). Backstop-timeout abort is shared with A1's `cancelProcessing`.
|
|
365
|
+
|
|
366
|
+
- **Status**: implemented. Full behavior/invariants/tests live in
|
|
367
|
+
[streaming-and-reattach.md §4.2](./streaming-and-reattach.md).
|
|
368
|
+
|
|
369
|
+
---
|
|
370
|
+
|
|
371
|
+
## 5. External API
|
|
372
|
+
|
|
373
|
+
### Entry Points
|
|
374
|
+
|
|
375
|
+
All external code MUST interact with agents through the mailbox API. Direct calls to internal methods like `handleMessage()`, `executeTask()`, or `respondInSession()` are forbidden — those are private implementation details of the attention loop.
|
|
376
|
+
|
|
377
|
+
#### `agent.enqueueToMailbox(sourceType, payload, options?)` — Fire-and-forget
|
|
378
|
+
Used for notifications that don't need a response:
|
|
379
|
+
```typescript
|
|
380
|
+
agent.enqueueToMailbox('task_comment', {
|
|
381
|
+
summary: 'Comment on task X',
|
|
382
|
+
content: notificationText,
|
|
383
|
+
taskId: 'task_123',
|
|
384
|
+
}, {
|
|
385
|
+
metadata: { senderName: 'Alice', senderRole: 'user' },
|
|
386
|
+
});
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
#### `agent.sendMessage(text, senderId?, senderInfo?, options?)` — Awaitable chat
|
|
390
|
+
Used when the caller needs a text response:
|
|
391
|
+
```typescript
|
|
392
|
+
const reply = await agent.sendMessage(
|
|
393
|
+
userText, senderId, senderInfo,
|
|
394
|
+
{ sourceType: 'human_chat', images, toolEventCollector }
|
|
395
|
+
);
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
#### `agent.sendMessageStream(text, onEvent, senderId?, ...)` — Streaming chat
|
|
399
|
+
Used for SSE/streaming chat where events are streamed back via callback:
|
|
400
|
+
```typescript
|
|
401
|
+
const reply = await agent.sendMessageStream(
|
|
402
|
+
userText, onEvent, senderId, senderInfo, cancelToken, images
|
|
403
|
+
);
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
#### `agent.sendTaskExecution(taskId, description, onLog, ...)` — Task execution
|
|
407
|
+
Used to run a task through the mailbox. Internally enqueues a `task_status_update` with `extra.triggerExecution = true`. Fire-and-forget with streaming log callback:
|
|
408
|
+
```typescript
|
|
409
|
+
void agent.sendTaskExecution(
|
|
410
|
+
taskId, taskDescription, onLog, cancelToken, taskProjectContext, executionRound
|
|
411
|
+
);
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
#### `agent.sendSessionReply(sessionId, text, onLog, ...)` — Session reply
|
|
415
|
+
Used for post-task comment replies within an existing session:
|
|
416
|
+
```typescript
|
|
417
|
+
const reply = await agent.sendSessionReply(
|
|
418
|
+
taskSessionId, prompt, onLog, senderId, senderInfo
|
|
419
|
+
);
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
Internally, all awaitable methods create a promise, store its resolve/reject in the mailbox item's metadata, enqueue, and return the promise. The attention controller processes the item, and `processMailboxItemInternal` resolves the promise with the reply.
|
|
423
|
+
|
|
424
|
+
### Invariant: Every LLM Call Goes Through the Mailbox
|
|
425
|
+
|
|
426
|
+
This is a critical design invariant. The following internal methods invoke the LLM but must NEVER be called from outside `agent.ts`:
|
|
427
|
+
|
|
428
|
+
| Internal method | Routed through | Mailbox type |
|
|
429
|
+
|----------------|----------------|--------------|
|
|
430
|
+
| `handleMessage()` | `sendMessage()` | `human_chat`, `a2a_message`, `system_event`, etc. |
|
|
431
|
+
| `handleMessageStream()` | `sendMessageStream()` | `human_chat` (with `extra.stream`) |
|
|
432
|
+
| `executeTask()` | `sendTaskExecution()` | `task_status_update` (with `extra.triggerExecution`) |
|
|
433
|
+
| `respondInSession()` | `sendSessionReply()` | `session_reply` |
|
|
434
|
+
| `handleHeartbeat()` | heartbeat:trigger → `mailbox.enqueue('heartbeat')` | `heartbeat` |
|
|
435
|
+
| `generateDailyReport()` | internally calls `sendMessage()` | `daily_report` |
|
|
436
|
+
| `dreamConsolidateMemory()` | internally calls `sendMessage()` | `memory_consolidation` |
|
|
437
|
+
| async op completion handler | `PendingCallbackRegistry.resolve()` → `enqueueToMailbox('callback_result')` | `callback_result` |
|
|
438
|
+
|
|
439
|
+
### REST API Endpoints
|
|
440
|
+
|
|
441
|
+
| Method | Path | Description |
|
|
442
|
+
|--------|------|-------------|
|
|
443
|
+
| GET | `/api/agents/:id/mind` | Current mind state (attention, focus, queue snapshot) |
|
|
444
|
+
| GET | `/api/agents/:id/mailbox` | Mailbox timeline — enriched history (see below) |
|
|
445
|
+
| GET | `/api/agents/:id/decisions` | Decision timeline (recent + persisted) |
|
|
446
|
+
|
|
447
|
+
#### `GET /api/agents/:id/mailbox` — Enriched Timeline
|
|
448
|
+
|
|
449
|
+
Query params: `limit`, `offset`, `type` (filter by `source_type`, comma-separated), `category` (filter by category from registry).
|
|
450
|
+
|
|
451
|
+
Response shape:
|
|
452
|
+
|
|
453
|
+
```json
|
|
454
|
+
{
|
|
455
|
+
"queued": [ /* items currently in queue */ ],
|
|
456
|
+
"queueDepth": 3,
|
|
457
|
+
"history": [
|
|
458
|
+
{
|
|
459
|
+
"id": "mbx_...",
|
|
460
|
+
"sourceType": "human_chat",
|
|
461
|
+
"priority": 1,
|
|
462
|
+
"status": "completed",
|
|
463
|
+
"summary": "What's the status of...",
|
|
464
|
+
"queuedAt": "2026-04-10T...",
|
|
465
|
+
"startedAt": "2026-04-10T...",
|
|
466
|
+
"completedAt": "2026-04-10T...",
|
|
467
|
+
"decisions": [
|
|
468
|
+
{ "id": "dec_...", "decisionType": "pick", "reasoning": "Idle — picked from queue" }
|
|
469
|
+
],
|
|
470
|
+
"activity": {
|
|
471
|
+
"id": "act-...",
|
|
472
|
+
"type": "chat",
|
|
473
|
+
"label": "Chat with Owner",
|
|
474
|
+
"totalTokens": 1234,
|
|
475
|
+
"totalTools": 3,
|
|
476
|
+
"success": true,
|
|
477
|
+
"startedAt": "...",
|
|
478
|
+
"endedAt": "..."
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
]
|
|
482
|
+
}
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
Each history item is self-contained: the mailbox stimulus, the decision(s) made, and the resulting activity summary. Activity logs are fetched separately on demand via `GET /api/agents/:id/activity-logs?activityId=...`.
|
|
486
|
+
|
|
487
|
+
### WebSocket Events
|
|
488
|
+
|
|
489
|
+
| Event Type | Payload | When |
|
|
490
|
+
|------------|---------|------|
|
|
491
|
+
| `agent:mailbox` | `{ agentId, item }` | New item enqueued |
|
|
492
|
+
| `agent:decision` | `{ agentId, decision }` | Attention decision made |
|
|
493
|
+
| `agent:attention` | `{ agentId, state, currentFocus }` | Attention state changed |
|
|
494
|
+
| `agent:focus` | `{ agentId, focus, mailboxDepth }` | Focus target changed |
|
|
495
|
+
|
|
496
|
+
---
|
|
497
|
+
|
|
498
|
+
## 6. Persistence & Data Model
|
|
499
|
+
|
|
500
|
+
### 6.1 Entity Relationships
|
|
501
|
+
|
|
502
|
+
```
|
|
503
|
+
mailbox_items (1) ──────┬──── (0..N) agent_decisions (what the agent decided)
|
|
504
|
+
│
|
|
505
|
+
└──── (0..1) agent_activities (what the agent did)
|
|
506
|
+
│
|
|
507
|
+
└── (0..N) agent_activity_logs (LLM turns, tool calls)
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
`mailbox_items` is the **primary timeline**. Everything else hangs off it. The frontend queries mailbox history, and for each item can look up its decision(s) and execution log.
|
|
511
|
+
|
|
512
|
+
### 6.2 SQLite Tables
|
|
513
|
+
|
|
514
|
+
```sql
|
|
515
|
+
CREATE TABLE mailbox_items (
|
|
516
|
+
id TEXT PRIMARY KEY,
|
|
517
|
+
agent_id TEXT NOT NULL,
|
|
518
|
+
source_type TEXT NOT NULL, -- MailboxItemType enum value
|
|
519
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
520
|
+
status TEXT NOT NULL DEFAULT 'queued',
|
|
521
|
+
payload TEXT NOT NULL DEFAULT '{}', -- JSON (summary, content, taskId, etc.)
|
|
522
|
+
metadata TEXT DEFAULT '{}', -- JSON (senderId, senderName, etc.)
|
|
523
|
+
queued_at TEXT NOT NULL,
|
|
524
|
+
started_at TEXT,
|
|
525
|
+
completed_at TEXT,
|
|
526
|
+
deferred_until TEXT,
|
|
527
|
+
merged_into TEXT
|
|
528
|
+
);
|
|
529
|
+
CREATE INDEX idx_mailbox_agent_status ON mailbox_items(agent_id, status);
|
|
530
|
+
CREATE INDEX idx_mailbox_agent_queued ON mailbox_items(agent_id, queued_at DESC);
|
|
531
|
+
CREATE INDEX idx_mailbox_agent_type ON mailbox_items(agent_id, source_type, queued_at DESC);
|
|
532
|
+
|
|
533
|
+
CREATE TABLE agent_decisions (
|
|
534
|
+
id TEXT PRIMARY KEY,
|
|
535
|
+
agent_id TEXT NOT NULL,
|
|
536
|
+
decision_type TEXT NOT NULL, -- DecisionType enum value
|
|
537
|
+
mailbox_item_id TEXT NOT NULL, -- FK → mailbox_items.id
|
|
538
|
+
context TEXT NOT NULL DEFAULT '{}',
|
|
539
|
+
reasoning TEXT NOT NULL DEFAULT '',
|
|
540
|
+
outcome TEXT,
|
|
541
|
+
created_at TEXT NOT NULL
|
|
542
|
+
);
|
|
543
|
+
CREATE INDEX idx_decisions_agent ON agent_decisions(agent_id, created_at DESC);
|
|
544
|
+
CREATE INDEX idx_decisions_mailbox_item ON agent_decisions(mailbox_item_id);
|
|
545
|
+
|
|
546
|
+
CREATE TABLE agent_activities (
|
|
547
|
+
id TEXT PRIMARY KEY,
|
|
548
|
+
agent_id TEXT NOT NULL,
|
|
549
|
+
mailbox_item_id TEXT, -- FK → mailbox_items.id (the causal link)
|
|
550
|
+
type TEXT NOT NULL, -- derived from mailbox source_type (see §6.3)
|
|
551
|
+
label TEXT NOT NULL,
|
|
552
|
+
task_id TEXT,
|
|
553
|
+
started_at TEXT NOT NULL,
|
|
554
|
+
ended_at TEXT,
|
|
555
|
+
total_tokens INTEGER DEFAULT 0,
|
|
556
|
+
total_tools INTEGER DEFAULT 0,
|
|
557
|
+
success INTEGER DEFAULT 1,
|
|
558
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
559
|
+
);
|
|
560
|
+
CREATE INDEX idx_activities_agent ON agent_activities(agent_id, started_at DESC);
|
|
561
|
+
CREATE INDEX idx_activities_mailbox_item ON agent_activities(mailbox_item_id);
|
|
562
|
+
|
|
563
|
+
CREATE TABLE agent_activity_logs (
|
|
564
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
565
|
+
activity_id TEXT NOT NULL REFERENCES agent_activities(id) ON DELETE CASCADE,
|
|
566
|
+
seq INTEGER NOT NULL,
|
|
567
|
+
type TEXT NOT NULL, -- 'status' | 'text' | 'tool_start' | 'tool_end' | 'error' | 'llm_request'
|
|
568
|
+
content TEXT NOT NULL DEFAULT '',
|
|
569
|
+
metadata TEXT DEFAULT '{}',
|
|
570
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
571
|
+
);
|
|
572
|
+
CREATE INDEX idx_activity_logs_activity ON agent_activity_logs(activity_id, seq);
|
|
573
|
+
```
|
|
574
|
+
|
|
575
|
+
### 6.3 Activity Type Derivation
|
|
576
|
+
|
|
577
|
+
The `agent_activities.type` field is **not an independent enum**. It is deterministically derived from `mailbox_items.source_type` using the mapping in `@markus/shared`:
|
|
578
|
+
|
|
579
|
+
| `mailbox_items.source_type` | `agent_activities.type` | Notes |
|
|
580
|
+
|-----------------------------|------------------------|-------|
|
|
581
|
+
| `human_chat` | `chat` | |
|
|
582
|
+
| `a2a_message` | `a2a` | |
|
|
583
|
+
| `task_comment` | *(none or `chat`)* | Active task → inject only (no activity); inactive → `chat` |
|
|
584
|
+
| `requirement_comment` | *(none or `chat`)* | Same pattern as `task_comment`: inject or fallback to `chat` |
|
|
585
|
+
| `task_status_update` | `task` or *(none)* | Execution mode → `task`; informational → auto-completed (no activity) |
|
|
586
|
+
| `requirement_update` | `internal` or *(none)* | `actionRequired` → LLM call; otherwise auto-completed (no activity) |
|
|
587
|
+
| `mention` | `chat` | |
|
|
588
|
+
| `review_request` | `chat` | |
|
|
589
|
+
| `session_reply` | `respond_in_session` | Has `task_id` |
|
|
590
|
+
| `heartbeat` | `heartbeat` | |
|
|
591
|
+
| `callback_result` | `internal` | Resumes originating session |
|
|
592
|
+
| `system_event` | `internal` | |
|
|
593
|
+
| `daily_report` | `internal` | |
|
|
594
|
+
| `memory_consolidation` | `internal` | |
|
|
595
|
+
|
|
596
|
+
The `activityType` is set to `null` in the registry for `task_comment`, `requirement_comment`, and `task_status_update` because it depends on the processing mode. `Agent.startActivity()` sets the type explicitly: `executeTask()` creates a `task` activity, while `handleMessage()` creates the appropriate type based on scenario.
|
|
597
|
+
|
|
598
|
+
### 6.4 Migration Plan
|
|
599
|
+
|
|
600
|
+
The key schema change is adding `mailbox_item_id` to `agent_activities`. Since `mailbox_item_id` is nullable (historical activities predate the mailbox system), this is a non-breaking additive migration:
|
|
601
|
+
|
|
602
|
+
```sql
|
|
603
|
+
ALTER TABLE agent_activities ADD COLUMN mailbox_item_id TEXT;
|
|
604
|
+
CREATE INDEX IF NOT EXISTS idx_activities_mailbox_item ON agent_activities(mailbox_item_id);
|
|
605
|
+
```
|
|
606
|
+
|
|
607
|
+
Historical activities without `mailbox_item_id` remain valid but lack the causal link. All new activities created after the migration will have the link set.
|
|
608
|
+
|
|
609
|
+
### 6.5 Persistence Lifecycle
|
|
610
|
+
|
|
611
|
+
1. **Enqueued** → `mailbox_items` row with `status = 'queued'`
|
|
612
|
+
2. **Dequeued** by attention controller → `status = 'processing'`, `started_at` set
|
|
613
|
+
3. **Decision made** → `agent_decisions` row referencing `mailbox_item_id`
|
|
614
|
+
4. **Activity started** → `agent_activities` row with `mailbox_item_id` set
|
|
615
|
+
5. **LLM turns / tool calls** → `agent_activity_logs` rows referencing `activity_id`
|
|
616
|
+
6. **Completed** → `mailbox_items.status = 'completed'`, `completed_at` set; activity `ended_at` set
|
|
617
|
+
7. If **deferred** → `status = 'deferred'` with optional `deferred_until`
|
|
618
|
+
8. If **merged** → `status = 'merged'` with `merged_into` pointing to the absorbing item
|
|
619
|
+
|
|
620
|
+
---
|
|
621
|
+
|
|
622
|
+
## 7. Integration with State Machines
|
|
623
|
+
|
|
624
|
+
Every task and requirement status transition generates a `task_status_update` or `requirement_update` mailbox notification to the assigned/creator agent. This ensures:
|
|
625
|
+
|
|
626
|
+
- The agent is **always aware** of state changes, even those initiated externally (human approval, timeout, cascade cancellation).
|
|
627
|
+
- State transitions are **recorded in the mailbox timeline**, providing full traceability.
|
|
628
|
+
- The agent can **react** to state changes (e.g., start working when approved, reflect when rejected).
|
|
629
|
+
|
|
630
|
+
See [state-machines.md](./state-machines.md) for the full FSM specifications.
|
|
631
|
+
|
|
632
|
+
---
|
|
633
|
+
|
|
634
|
+
## 8. Relationship to Memory System
|
|
635
|
+
|
|
636
|
+
The mailbox system feeds into the agent's memory layers:
|
|
637
|
+
|
|
638
|
+
| Layer | Source | Cadence |
|
|
639
|
+
|-------|--------|---------|
|
|
640
|
+
| **Episodic** | Every mailbox item processed becomes an activity in `agent_activities` — searchable via `recall_activity` | Per interaction |
|
|
641
|
+
| **Semantic** | Patterns extracted from decision history via consolidation → MEMORY.md | Periodic (Dream Cycle) |
|
|
642
|
+
| **Procedural** | Recurring patterns may inform ROLE.md evolution | Rare |
|
|
643
|
+
|
|
644
|
+
The full stimulus/response record (`mailbox_items` + `agent_decisions`) and the action/outcome record (`agent_activities` + `agent_activity_logs`) together form the agent's **episodic memory** — retrievable via the `recall_activity` tool.
|
|
645
|
+
|
|
646
|
+
See [memory-system.md](./memory-system.md) for details.
|
|
647
|
+
|
|
648
|
+
---
|
|
649
|
+
|
|
650
|
+
## 9. Frontend — Agent Mind View
|
|
651
|
+
|
|
652
|
+
The Agent Mind tab provides a unified view of the agent's cognitive state and history. There are **no sub-tabs** — it is a single scrollable view.
|
|
653
|
+
|
|
654
|
+
### Layout
|
|
655
|
+
|
|
656
|
+
```
|
|
657
|
+
┌─────────────────────────────────────────────────────┐
|
|
658
|
+
│ [IDLE/FOCUSED/DECIDING] Focused on: [type] label │ ← Attention state header
|
|
659
|
+
│ Queue: 3 items waiting ↻ │
|
|
660
|
+
├─────────────────────────────────────────────────────┤
|
|
661
|
+
│ Filter: [All] [Interaction] [Task] [Notification] │ ← Category filters from registry
|
|
662
|
+
│ [System] + type dropdown for fine filter │
|
|
663
|
+
├─────────────────────────────────────────────────────┤
|
|
664
|
+
│ ● human_chat "What's the status of..." completed │ ← Mailbox timeline
|
|
665
|
+
│ └─ [pick] Idle — picked from queue │ (each item expandable)
|
|
666
|
+
│ └─ Activity: Chat with Owner 1.2k tokens 3 tools│
|
|
667
|
+
│ └─ (click to load activity logs) │
|
|
668
|
+
│ │
|
|
669
|
+
│ ● task_status_update "Implement feature X" completed │
|
|
670
|
+
│ ● heartbeat "Heartbeat check-in" completed │
|
|
671
|
+
│ ● task_comment "Comment on task..." merged │
|
|
672
|
+
│ └─ [merge] Comment on active task — merged │
|
|
673
|
+
│ │
|
|
674
|
+
│ [Load Earlier...] │
|
|
675
|
+
└─────────────────────────────────────────────────────┘
|
|
676
|
+
```
|
|
677
|
+
|
|
678
|
+
### Design Principles
|
|
679
|
+
|
|
680
|
+
1. **Mailbox is the primary timeline** — not activities, not decisions. Those are detail views within each mailbox item.
|
|
681
|
+
2. **Filters use `category` from the registry** — adding a new mailbox type automatically makes it filterable without frontend changes.
|
|
682
|
+
3. **Labels, icons, and colors all come from the registry** — the frontend reads `MAILBOX_TYPE_REGISTRY` at render time.
|
|
683
|
+
4. **Expandable detail** — clicking a mailbox item shows: (a) decision badge(s), (b) activity summary, (c) lazy-loaded activity logs.
|
|
684
|
+
5. **Status indicators**: `completed` (green), `processing` (blue pulse), `merged` (blue), `deferred` (purple), `dropped` (red), `queued` (amber).
|
|
685
|
+
|
|
686
|
+
---
|
|
687
|
+
|
|
688
|
+
## 10. Completeness Guarantee
|
|
689
|
+
|
|
690
|
+
All paths that invoke the LLM are routed through the mailbox:
|
|
691
|
+
|
|
692
|
+
- **Human chat** (HTTP / WebUI / gateway) → `sendMessage` / `sendMessageStream`
|
|
693
|
+
- **Task execution** (runTask / runTaskFresh) → `sendTaskExecution`
|
|
694
|
+
- **Post-task comment reply** → `sendSessionReply`
|
|
695
|
+
- **Daily report** (API trigger) → `generateDailyReport` → `sendMessage(sourceType: 'daily_report')`
|
|
696
|
+
- **Heartbeat** (periodic timer) → `heartbeat:trigger` event → `mailbox.enqueue('heartbeat')` — includes active goals review and timed-out callback checks (§11.4)
|
|
697
|
+
- **Memory consolidation** (dream cycle) → `dreamConsolidateMemory` → `sendMessage(sourceType: 'memory_consolidation')`
|
|
698
|
+
- **Cross-agent messages** (A2A / delegation) → DM channel → `enqueueToMailbox('a2a_message')` (§11)
|
|
699
|
+
- **Async operation completions** (`background_exec`, etc.) → `PendingCallbackRegistry` → `enqueueToMailbox('callback_result')`
|
|
700
|
+
- **Notifications** (task status, requirement, comments) → `enqueueToMailbox`
|
|
701
|
+
|
|
702
|
+
No LLM call is made outside this architecture.
|
|
703
|
+
|
|
704
|
+
---
|
|
705
|
+
|
|
706
|
+
## 11. Agent-to-Agent Communication (A2A via Mailbox)
|
|
707
|
+
|
|
708
|
+
Inter-agent messaging is fully consolidated into the Mailbox system. The legacy `A2ABus` class has been retired — it added a redundant routing layer when the mailbox already provides serialised attention handling.
|
|
709
|
+
|
|
710
|
+
### 11.1 A2A DM Channels
|
|
711
|
+
|
|
712
|
+
A2A messages now route through **deterministic DM channels** that reuse the group-chat infrastructure for persistence, WebSocket delivery, and mailbox enqueue:
|
|
713
|
+
|
|
714
|
+
```
|
|
715
|
+
Channel key: dm:a2a:{sorted_id_1}:{sorted_id_2}
|
|
716
|
+
(agent IDs sorted lexicographically — one channel per pair)
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
```
|
|
720
|
+
Agent A Agent B
|
|
721
|
+
──────── ────────
|
|
722
|
+
tool: agent_send_message ──► AgentManager.sendMessage()
|
|
723
|
+
│
|
|
724
|
+
▼
|
|
725
|
+
ensureDmChannel(dm:a2a:...)
|
|
726
|
+
│
|
|
727
|
+
▼
|
|
728
|
+
sendGroupMessage(channelKey, ...)
|
|
729
|
+
├─ persist to channel_messages
|
|
730
|
+
├─ WebSocket broadcast
|
|
731
|
+
└─ enqueueToMailbox('a2a_message', { extra: { channelKey } })
|
|
732
|
+
│
|
|
733
|
+
▼
|
|
734
|
+
AttentionController picks it up
|
|
735
|
+
(stable session: channel_{channelKey}_{agentId})
|
|
736
|
+
```
|
|
737
|
+
|
|
738
|
+
Benefits over ephemeral session IDs:
|
|
739
|
+
|
|
740
|
+
- **Persistent history** — both agents recall past exchanges via `recall_context` with `scope: "channel"` and `channel_key`. Personal user↔agent DM **chat sessions** (`chat_sessions` table) use `recall_context` with `scope: "chat_session"` and `session_id` (pagination via `before` / `limit`) — see [learning-loop.md](./learning-loop.md) §9.3.
|
|
741
|
+
- **Stable sessions** — all messages in a pair share one session ID derived from the channel key
|
|
742
|
+
- **Enqueue-time dedup** — messages from the same `channelKey` coalesce (§14)
|
|
743
|
+
- **Group chat parity** — DM channels use the same `groupChatRepo`, member resolution, and API paths as custom group chats
|
|
744
|
+
|
|
745
|
+
When `groupChatHandlers` are not wired (e.g., unit tests), A2A falls back to direct `sendMessage()` with `sourceType: 'a2a_message'` and the same `channelKey` in `extra`.
|
|
746
|
+
|
|
747
|
+
### 11.2 Tools & Transport
|
|
748
|
+
|
|
749
|
+
- **`agent_send_message`**: Always asynchronous — returns immediately with `conversation_id` and `channel_key`. Messages are tagged `[conversation:...]` for multi-turn correlation.
|
|
750
|
+
- **`agent_delegate_task`**: Uses `DelegationManager` for protocol orchestration; transport goes through the DM channel path above.
|
|
751
|
+
- **`agent_broadcast_status`**: Lightweight path — writes to target agent's daily log without an LLM call. Does not use DM channels.
|
|
752
|
+
- **`agent_send_group_message`**: Team/custom group channels (`group:<teamId>`, `group:custom:<id>`). @mentions control which peer agents receive `a2a_message` mailbox items.
|
|
753
|
+
|
|
754
|
+
The `@markus/a2a` package retains `DelegationManager` and protocol types. `A2ABus` is exported with a `@deprecated` annotation for backward compatibility only.
|
|
755
|
+
|
|
756
|
+
### 11.3 PendingCallbackRegistry
|
|
757
|
+
|
|
758
|
+
`PendingCallbackRegistry` (`packages/core/src/pending-callback.ts`) tracks async operations that must report results back through the mailbox rather than injecting directly into an active session.
|
|
759
|
+
|
|
760
|
+
```typescript
|
|
761
|
+
type CallbackType = 'background_exec' | 'wakeup' | 'a2a_reply';
|
|
762
|
+
type CallbackDelivery = 'in_session' | 'mailbox';
|
|
763
|
+
|
|
764
|
+
interface PendingCallback {
|
|
765
|
+
id: string; // Unique callback ID (e.g., background session ID, a2a_<conversation_id>)
|
|
766
|
+
agentId: string; // Originating agent
|
|
767
|
+
originSessionId: string; // Session to resume on completion (in_session mode)
|
|
768
|
+
type: CallbackType; // Operation type
|
|
769
|
+
deliveryMode?: CallbackDelivery; // in_session (default) → callback_result; mailbox → system_event
|
|
770
|
+
command?: string; // Optional context (shell command, etc.)
|
|
771
|
+
note?: string; // Free-text label (wakeup reason, delegation goal)
|
|
772
|
+
correlationId?: string; // Correlates an external event (conversation_id)
|
|
773
|
+
wakeAt?: number; // Scheduled wakeups: epoch ms when due
|
|
774
|
+
recurringMs?: number; // Recurring wakeups: re-arm interval
|
|
775
|
+
registeredAt: number; // Epoch ms
|
|
776
|
+
timeoutMs: number; // 10 min for background_exec; 30 min for a2a_reply; effectively ∞ for wakeup
|
|
777
|
+
}
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
**Lifecycle:**
|
|
781
|
+
|
|
782
|
+
1. **Register** — An async operation is registered as a `PendingCallback` and persisted via `SqlitePendingCallbackRepo`:
|
|
783
|
+
- `background_exec` → `registerBackgroundSession()` (called from `Agent.executeTool` on the tool result).
|
|
784
|
+
- `agent_send_message` with `reply_in_session` (alias `await_in_session`) → an `a2a_reply` callback keyed by `conversation_id`.
|
|
785
|
+
- `schedule_wakeup` → a `wakeup` callback with `wakeAt` (+ optional `recurringMs`).
|
|
786
|
+
2. **Complete / fire** — On completion (`background_exec`, `a2a_reply`) or when a wakeup is due, the entry is resolved and delivered via the shared `Agent.deliverCallback()` helper: `in_session` → `callback_result` (bound to `originSessionId`); `mailbox` → `system_event`. Recurring wakeups re-arm.
|
|
787
|
+
3. **Timeout** — Heartbeat calls `getTimedOut()` to find expired callbacks, then `expireTimedOut(id)` removes each from the registry. Timed-out operations are surfaced in the heartbeat prompt (§11.4) for agent investigation — they do not silently disappear. (Wakeups use an effectively infinite timeout and are never flagged.)
|
|
788
|
+
|
|
789
|
+
**Wakeup scheduler:** each agent runs a coarse (~1-minute) sweep (`Agent.sweepDueWakeups`) that fires any `wakeup` callbacks whose `wakeAt` has passed. This lets an agent register precise time-based follow-ups (`schedule_wakeup`) and stay idle in between, rather than relying on the periodic heartbeat.
|
|
790
|
+
|
|
791
|
+
**Heartbeat as coarse safety-net:** the periodic heartbeat is a fallback patrol (`DEFAULT_HEARTBEAT_INTERVAL_MS`, 6h), not the primary timing mechanism — `schedule_wakeup` is. The interval is configurable live by the user (Heartbeat tab / `PATCH /api/agents/:id/config`) and by the agent itself via the `set_heartbeat_interval` tool (clamped 5min–24h). Both paths go through `Agent.setHeartbeatInterval()`, which restarts the scheduler immediately; agent-initiated changes persist via the `agent:heartbeat-interval-changed` event → `agentRepo.updateConfig`.
|
|
792
|
+
|
|
793
|
+
The registry is a process singleton (`pendingCallbackRegistry`), restored from SQLite on startup so callbacks survive server restarts.
|
|
794
|
+
|
|
795
|
+
### 11.4 Heartbeat Integration
|
|
796
|
+
|
|
797
|
+
Periodic heartbeat items (`priority: 3 — low`) drive proactive agent patrol. Beyond the standard checklist, heartbeat now integrates:
|
|
798
|
+
|
|
799
|
+
**Active goals review** — When `goalFetcher` is wired (from org-manager requirement service), the heartbeat prompt includes an **Active Goals** section listing each goal's title, status, iteration count (`currentIteration` / `maxIterations`), and completion criteria. The agent is instructed to:
|
|
800
|
+
|
|
801
|
+
1. Check linked tasks for progress
|
|
802
|
+
2. Create follow-up tasks if needed
|
|
803
|
+
3. Mark requirements complete when criteria are met
|
|
804
|
+
4. Escalate or adjust approach if stuck
|
|
805
|
+
|
|
806
|
+
**Callback timeout handling** — Before building the heartbeat prompt, `handleHeartbeat()` calls `pendingCallbackRegistry.getTimedOut()`. For each expired callback:
|
|
807
|
+
|
|
808
|
+
1. `expireTimedOut(id)` removes it from the registry (and persistence)
|
|
809
|
+
2. Details are injected into the heartbeat prompt under **Timed-Out Async Operations** (background exec or an awaited A2A delegation whose reply never arrived)
|
|
810
|
+
3. The agent investigates and takes corrective action during the heartbeat LLM session
|
|
811
|
+
|
|
812
|
+
This ensures orphaned async operations are surfaced even when the completion handler never fires (process crash, hung command, etc.).
|
|
813
|
+
|
|
814
|
+
Background process completions that *do* finish normally are still routed as separate `callback_result` mailbox items (priority 1) — the heartbeat section only handles the timeout case.
|
|
815
|
+
|
|
816
|
+
### 11.5 Async-Only A2A (Deadlock Prevention)
|
|
817
|
+
|
|
818
|
+
The `wait_for_reply=true` parameter is **deprecated and ignored**. All A2A messaging is non-blocking. This eliminates deadlocks that occurred when two agents simultaneously awaited each other's reply.
|
|
819
|
+
|
|
820
|
+
**Correlation pattern**: Each message carries a `conversation_id` (auto-generated UUID). Agents record pending questions in working memory and recognize replies by the `[conversation:...]` tag prepended to the message content. Multi-turn exchanges use the same `conversation_id` for context continuity.
|
|
821
|
+
|
|
822
|
+
---
|
|
823
|
+
|
|
824
|
+
## 12. User Notifications (Human Mailbox)
|
|
825
|
+
|
|
826
|
+
Just as agents have a mailbox for incoming stimuli, users have a **persistent notification system** for events that require their attention. This is the user-facing counterpart to the agent mailbox.
|
|
827
|
+
|
|
828
|
+
### 12.1 Storage
|
|
829
|
+
|
|
830
|
+
```sql
|
|
831
|
+
CREATE TABLE user_notifications (
|
|
832
|
+
id TEXT PRIMARY KEY,
|
|
833
|
+
user_id TEXT NOT NULL,
|
|
834
|
+
type TEXT NOT NULL, -- UserNotificationType
|
|
835
|
+
title TEXT NOT NULL,
|
|
836
|
+
body TEXT DEFAULT '',
|
|
837
|
+
priority TEXT DEFAULT 'normal', -- 'low' | 'normal' | 'high' | 'urgent'
|
|
838
|
+
read INTEGER DEFAULT 0,
|
|
839
|
+
action_type TEXT, -- 'navigate' | 'open_chat' | null
|
|
840
|
+
action_target TEXT, -- JSON: { path } or { agentId, sessionId }
|
|
841
|
+
metadata TEXT DEFAULT '{}',
|
|
842
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
843
|
+
);
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
### 12.2 Notification Type Registry
|
|
847
|
+
|
|
848
|
+
Analogous to `MAILBOX_TYPE_REGISTRY`, user notification types are defined in `USER_NOTIFICATION_TYPE_REGISTRY` in `@markus/shared`:
|
|
849
|
+
|
|
850
|
+
| Type | Label | Icon | Default Priority | Action | Category |
|
|
851
|
+
|------|-------|------|-----------------|--------|----------|
|
|
852
|
+
| `approval_request` | Approval Request | 🔐 | high | navigate | approval |
|
|
853
|
+
| `task_created` | Task Created | 📋 | normal | navigate | task |
|
|
854
|
+
| `task_completed` | Task Completed | ✅ | normal | navigate | task |
|
|
855
|
+
| `task_review` | Task Review | 👁️ | normal | navigate | task |
|
|
856
|
+
| `task_failed` | Task Failed | ❌ | high | navigate | task |
|
|
857
|
+
| `requirement_created` | Requirement Proposed | 📝 | high | navigate | task |
|
|
858
|
+
| `requirement_decision` | Requirement Decision | ⚖️ | normal | navigate | task |
|
|
859
|
+
| `agent_report` | Agent Report | 📊 | normal | none | agent |
|
|
860
|
+
| `system` | System | ⚙️ | normal | none | system |
|
|
861
|
+
|
|
862
|
+
### 12.3 Action Types
|
|
863
|
+
|
|
864
|
+
Notifications can be **actionable** — clicking them navigates the user to the relevant context:
|
|
865
|
+
|
|
866
|
+
| `action_type` | `action_target` format | Behaviour |
|
|
867
|
+
|---------------|----------------------|-----------|
|
|
868
|
+
| `navigate` | `{ "path": "/work?task=T123" }` | Navigate to the specified route |
|
|
869
|
+
| `open_chat` | `{ "agentId": "...", "sessionId": "..." }` | Open chat with agent, resume session |
|
|
870
|
+
| `none` | — | Notification only, no navigation |
|
|
871
|
+
|
|
872
|
+
### 12.4 REST API
|
|
873
|
+
|
|
874
|
+
| Method | Path | Description |
|
|
875
|
+
|--------|------|-------------|
|
|
876
|
+
| GET | `/api/notifications?type=...&limit=...&offset=...` | List notifications with filtering, returns `totalCount` and `unreadCount` |
|
|
877
|
+
| POST | `/api/notifications/:id/read` | Mark single notification as read |
|
|
878
|
+
| POST | `/api/notifications/mark-all-read` | Mark all notifications as read |
|
|
879
|
+
|
|
880
|
+
### 12.5 Real-Time Delivery
|
|
881
|
+
|
|
882
|
+
When a notification is created (via `HITLService.notify()`), a WebSocket `notification` event is broadcast. The frontend `App.tsx` listens for this and dispatches a `markus:notifications-changed` custom DOM event, which triggers the `NotificationBell` component to refresh.
|
|
883
|
+
|
|
884
|
+
---
|
|
885
|
+
|
|
886
|
+
## 13. Agent-to-User Communication
|
|
887
|
+
|
|
888
|
+
Agents have two distinct modes for communicating with users, reflecting different conversational intents:
|
|
889
|
+
|
|
890
|
+
### 13.1 `notify_user` — Proactive Chat Message + Notification
|
|
891
|
+
|
|
892
|
+
Proactive messages that appear in the agent's chat **and** the user's notification bell. The user can reply in chat, and the agent has full context of what it sent.
|
|
893
|
+
|
|
894
|
+
```typescript
|
|
895
|
+
// Tool schema
|
|
896
|
+
{
|
|
897
|
+
name: 'notify_user',
|
|
898
|
+
parameters: {
|
|
899
|
+
title: string, // Short headline (1 line)
|
|
900
|
+
body: string, // Full message content (visible in chat)
|
|
901
|
+
priority: 'low' | 'normal' | 'high' | 'urgent', // optional, default 'normal'
|
|
902
|
+
related_task_id?: string, // deep-link to task if applicable
|
|
903
|
+
target_user_id?: string // target specific user (defaults to currentInteractingUserId)
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
```
|
|
907
|
+
|
|
908
|
+
**When to use**: Status updates, task completion notices, FYI messages, findings, alerts — any proactive communication where the user may want to reply.
|
|
909
|
+
|
|
910
|
+
**Flow**: `agent.executeTool('notify_user')` → builds formatted message with embedded context → `memory.appendMessage()` (in-memory session) → `eventBus.emit('agent:notify-user')` → `start.ts` handler: `chatSessionRepo.appendMessage()` (with `notifyUser` metadata) + `ws.broadcastProactiveMessage()` (with metadata) + `hitlService.notify()`
|
|
911
|
+
|
|
912
|
+
**Notification routing**: With `related_task_id` → `actionType: 'navigate'` to Work page. Without task → `actionType: 'open_chat'` with `sessionId` to agent's chat.
|
|
913
|
+
|
|
914
|
+
#### Message Metadata & Context Embedding
|
|
915
|
+
|
|
916
|
+
Every `notify_user` message is persisted with **two layers of context**:
|
|
917
|
+
|
|
918
|
+
1. **DB metadata** (`metadata` column): `{ notifyUser: true, priority, taskId?, requirementId? }` — used by the frontend to display context links and badges.
|
|
919
|
+
|
|
920
|
+
2. **Embedded context comment** (appended to message content): `<!-- notify_context: task_id=xxx, requirement_id=yyy -->` — survives through `restoreSessionFromHistory()` (which only reads `role` + `content`), ensuring the agent retains context about what it notified the user about when the user replies.
|
|
921
|
+
|
|
922
|
+
The agent's `chat` scenario system prompt instructs it to parse these `notify_context` references and use tools like `recall_activity` or `search_tasks` to retrieve full context before responding to user follow-ups.
|
|
923
|
+
|
|
924
|
+
> **Referencing resources in the body**: `notify_user` bodies (and any chat/comment/report markdown) should reference Markus resources using the conventions in [prompt-engineering.md §2.2 "Referencing Markus Resources"](./prompt-engineering.md#referencing-markus-resources) — bare IDs (`tsk_…`, `dlv_…`, …), titled links `[Title](task:tsk_…)`, or a reference alone on its own line to render a card. This is separate from the `related_task_id` metadata (which drives the notification's deep-link badge).
|
|
925
|
+
|
|
926
|
+
#### Real-time Visibility
|
|
927
|
+
|
|
928
|
+
All `notify_user` messages are buffered in the frontend for every agent conversation immediately upon WebSocket receipt — regardless of whether the user is currently viewing that agent's chat. This ensures messages are visible as soon as the user navigates to the agent, without requiring a page reload.
|
|
929
|
+
|
|
930
|
+
### 13.2 `request_user_approval` — Blocking Decision Request
|
|
931
|
+
|
|
932
|
+
Requests a decision or approval from the user. The tool **blocks** until the user responds — no timeout. Supports default Approve/Reject options, custom options, and optional freeform text input.
|
|
933
|
+
|
|
934
|
+
```typescript
|
|
935
|
+
// Tool schema
|
|
936
|
+
{
|
|
937
|
+
name: 'request_user_approval',
|
|
938
|
+
parameters: {
|
|
939
|
+
title: string, // Short headline
|
|
940
|
+
description: string, // Detailed context
|
|
941
|
+
options?: Array<{ // Custom options (defaults to Approve/Reject)
|
|
942
|
+
id: string,
|
|
943
|
+
label: string,
|
|
944
|
+
description?: string
|
|
945
|
+
}>,
|
|
946
|
+
allow_freeform?: boolean, // Allow user to type custom text
|
|
947
|
+
related_task_id?: string,
|
|
948
|
+
priority?: 'normal' | 'high' | 'urgent'
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
// Returns: { status: 'ok', approved: boolean, selected_option: string, comment: string }
|
|
952
|
+
```
|
|
953
|
+
|
|
954
|
+
**When to use**: Approval requests, design decisions, choosing between approaches, anything requiring user input or decision.
|
|
955
|
+
|
|
956
|
+
**Flow**: `agent.executeTool('request_user_approval')` → `attentionController.setWaitingForApproval(true)` → `HITLService.requestApprovalAndWait(options)` → notification + WebSocket → NotificationBell renders options → user responds → `HITLService.respondToApproval(selectedOption)` → promise resolves → agent receives result
|
|
957
|
+
|
|
958
|
+
The attention controller uses `APPROVAL_WAIT_TIMEOUT_MS` (24h) instead of the normal 45-minute backstop (`MAILBOX_PROCESSING_TIMEOUT_MS`) while waiting for approval, preventing the mailbox item from being requeued prematurely.
|
|
959
|
+
|
|
960
|
+
### 13.3 Prompt Guidance
|
|
961
|
+
|
|
962
|
+
The system prompt includes scenario-specific guidance on which tool to use:
|
|
963
|
+
|
|
964
|
+
| Situation | Tool |
|
|
965
|
+
|-----------|------|
|
|
966
|
+
| Status report, progress update, FYI alert | `notify_user` (appears in chat, user may reply) |
|
|
967
|
+
| Task completed notification | `notify_user` with `related_task_id` |
|
|
968
|
+
| Need user to approve/reject something | `request_user_approval` (default options) |
|
|
969
|
+
| Need user to choose between approaches | `request_user_approval` with custom `options` |
|
|
970
|
+
| Need user freeform input | `request_user_approval` with `allow_freeform: true` |
|
|
971
|
+
| Want to discuss interactively | Mention user via task/requirement comment |
|
|
972
|
+
| Need to review past execution details | `recall_activity` (list activities or get logs) |
|
|
973
|
+
|
|
974
|
+
---
|
|
975
|
+
|
|
976
|
+
## 14. Enqueue-Time Deduplication
|
|
977
|
+
|
|
978
|
+
When multiple messages for the same entity arrive before the agent can process them, the mailbox merges them at enqueue time to prevent redundant processing:
|
|
979
|
+
|
|
980
|
+
### Dedup Groups
|
|
981
|
+
|
|
982
|
+
| Group | Dedup Key | Eligible Types |
|
|
983
|
+
|-------|-----------|---------------|
|
|
984
|
+
| Task comments | `payload.taskId` | `task_comment` |
|
|
985
|
+
| Requirement comments | `payload.requirementId` | `requirement_comment` |
|
|
986
|
+
| Channel messages | `payload.extra.channelKey` | `a2a_message` (includes `dm:a2a:*` DM channels and `group:*` channels) |
|
|
987
|
+
|
|
988
|
+
**Why status updates are excluded**: `task_status_update` and `requirement_update` represent distinct state transitions with different processing semantics. Merging a "task blocked" notification with a "task resumed" notification would lose critical state information. Only comments — which are additive human/agent text — are safe to merge.
|
|
989
|
+
|
|
990
|
+
### Merge Behaviour
|
|
991
|
+
|
|
992
|
+
When a new item matches an existing **queued** (not yet processing) item in the same dedup group:
|
|
993
|
+
|
|
994
|
+
1. The new item's `content` is appended to the existing item (separated by `\n\n---\n\n`)
|
|
995
|
+
2. The existing item's `summary` gains a `(+1)` suffix
|
|
996
|
+
3. The new item is **not** inserted into the queue — the existing item serves both
|
|
997
|
+
4. The merge is logged for traceability
|
|
998
|
+
5. For channel messages: the `messages` array in the payload is populated with structured per-sender entries
|
|
999
|
+
|
|
1000
|
+
This prevents scenarios where 5 rapid-fire comments on the same task each trigger separate LLM calls. Instead, the agent sees one consolidated item with all 5 comments.
|
|
1001
|
+
|
|
1002
|
+
### Channel Coalescing
|
|
1003
|
+
|
|
1004
|
+
Group chat and A2A messages from the same `channelKey` are coalesced both at enqueue time and during pre-triage consolidation. The merged item carries a `messages` array providing structured context:
|
|
1005
|
+
|
|
1006
|
+
```typescript
|
|
1007
|
+
payload.messages: Array<{
|
|
1008
|
+
senderId?: string;
|
|
1009
|
+
senderName: string;
|
|
1010
|
+
content: string;
|
|
1011
|
+
timestamp: string;
|
|
1012
|
+
}>
|
|
1013
|
+
```
|
|
1014
|
+
|
|
1015
|
+
### Burst Coalescing Window
|
|
1016
|
+
|
|
1017
|
+
After dequeuing a non-user item, the attention loop pauses for `MAILBOX_COALESCE_WINDOW_MS` (default 200ms) before starting triage. This gives rapid-fire messages time to arrive and merge via enqueue-time dedup, reducing redundant processing for burst scenarios (e.g., multiple agents posting to the same group chat within milliseconds).
|
|
1018
|
+
|
|
1019
|
+
**Execution-trigger safety**: Items with `extra.triggerExecution` (task execution triggers) are **never merged** — neither as the incoming item nor as the merge target. Execution items carry critical callbacks (`onLog`, `cancelToken`, `taskProjectContext`) in their `extra` field that would be lost during a content merge. They must always remain standalone queue entries.
|
|
1020
|
+
|
|
1021
|
+
### Complementary: Attention Controller Merge (R2/R3)
|
|
1022
|
+
|
|
1023
|
+
Enqueue-time dedup handles items that arrive while the queue is idle. The attention controller's R2 (same-task comment merge) and R3 (same-requirement comment/update merge) handle items that arrive **while the agent is focused** — merging them into the current work if they relate to the same entity.
|
|
1024
|
+
|
|
1025
|
+
---
|
|
1026
|
+
|
|
1027
|
+
## 15. Comment Activity Traceability
|
|
1028
|
+
|
|
1029
|
+
Agent-generated comments on tasks and requirements carry an `activityId` linking them to the execution context that produced them. This enables users to expand a comment in the UI and see the full execution log — every tool call, LLM turn, and reasoning step that led to the comment.
|
|
1030
|
+
|
|
1031
|
+
### Data Flow
|
|
1032
|
+
|
|
1033
|
+
```
|
|
1034
|
+
Agent executing activity (activityId = "act-agent1-1234...")
|
|
1035
|
+
└─ calls task_comment / requirement_comment tool
|
|
1036
|
+
└─ tool reads getCurrentActivityId() → "act-agent1-1234..."
|
|
1037
|
+
└─ passes activityId to postTaskComment() / postRequirementComment()
|
|
1038
|
+
└─ persisted in task_comments.activity_id / requirement_comments.activity_id
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
### Schema
|
|
1042
|
+
|
|
1043
|
+
Both `task_comments` and `requirement_comments` tables have an `activity_id` column (nullable, TEXT). Human-authored comments have `activity_id = NULL`.
|
|
1044
|
+
|
|
1045
|
+
### Frontend
|
|
1046
|
+
|
|
1047
|
+
The `CommentBubble` component checks for `activityId` on agent comments. When present, a "View log" button appears on hover. Clicking it fetches execution logs via `GET /api/agents/:id/activity-logs?activityId=...` and renders them inline using the `FullExecutionLog` component.
|
|
1048
|
+
|
|
1049
|
+
---
|
|
1050
|
+
|
|
1051
|
+
## 16. Mailbox Status Filters
|
|
1052
|
+
|
|
1053
|
+
The frontend Agent Mind view supports filtering by both **category** and **status**:
|
|
1054
|
+
|
|
1055
|
+
| Status | Color Indicator | Description |
|
|
1056
|
+
|--------|----------------|-------------|
|
|
1057
|
+
| `queued` | Amber | Waiting in queue |
|
|
1058
|
+
| `processing` | Blue (pulse) | Currently being processed |
|
|
1059
|
+
| `completed` | Green | Successfully processed |
|
|
1060
|
+
| `merged` | Blue | Absorbed into another item |
|
|
1061
|
+
| `deferred` | Purple | Postponed for later |
|
|
1062
|
+
| `dropped` | Red | Discarded |
|
|
1063
|
+
|
|
1064
|
+
Both category and status filters are passed as query parameters to the mailbox API endpoint.
|
|
1065
|
+
|
|
1066
|
+
---
|
|
1067
|
+
|
|
1068
|
+
## 17. Restart Recovery
|
|
1069
|
+
|
|
1070
|
+
After a server crash or restart, mailbox items that were in `processing` status at the time of shutdown become stale — the in-flight LLM call and callbacks are lost. These items appear as permanent zombies in the mailbox history.
|
|
1071
|
+
|
|
1072
|
+
### Recovery Mechanism
|
|
1073
|
+
|
|
1074
|
+
On agent startup, `AgentMailbox.recoverStaleItems()` is called immediately after persistence is wired. It delegates to `MailboxPersistence.markStaleProcessingAsDropped(agentId)`, which executes:
|
|
1075
|
+
|
|
1076
|
+
```sql
|
|
1077
|
+
UPDATE mailbox_items SET status = 'dropped' WHERE agent_id = ? AND status = 'processing'
|
|
1078
|
+
```
|
|
1079
|
+
|
|
1080
|
+
This is safe because:
|
|
1081
|
+
- `resumeInProgressTasks()` already re-creates execution items for any tasks that need to continue.
|
|
1082
|
+
- The stale items' callbacks (`onLog`, `cancelToken`, etc.) are garbage-collected references that cannot be resumed.
|
|
1083
|
+
- Marking as `dropped` (not `completed`) preserves the audit trail — these items did not complete successfully.
|
|
1084
|
+
|
|
1085
|
+
### Post-Recovery Deduplication
|
|
1086
|
+
|
|
1087
|
+
After all queued items are restored from the database, `recoverStaleItems()` runs `deduplicateQueue()` to collapse redundant entries that accumulated before the restart:
|
|
1088
|
+
|
|
1089
|
+
1. **Heartbeat collapse**: Multiple queued heartbeats are reduced to a single entry (the most recent). Older heartbeats are marked `dropped`.
|
|
1090
|
+
2. **Comment merging**: `task_comment` items with the same `taskId` are merged (content appended, summary updated with `(+1)`). Same for `requirement_comment` by `requirementId`.
|
|
1091
|
+
3. **Priority escalation**: When merging, the survivor inherits the highest priority of all merged items.
|
|
1092
|
+
4. **Execution-trigger safety**: Items with `extra.triggerExecution` are never merged — they carry critical callbacks that must remain standalone.
|
|
1093
|
+
|
|
1094
|
+
This prevents scenarios where a restart causes the agent to process 10 redundant heartbeats or 5 separate comment notifications for the same task.
|
|
1095
|
+
|
|
1096
|
+
### Startup Sequence
|
|
1097
|
+
|
|
1098
|
+
```
|
|
1099
|
+
1. wireMailboxPersistence(agentId) — sets save/updateStatus/markStaleProcessingAsDropped/loadQueued
|
|
1100
|
+
2. mailbox.recoverStaleItems() — drops stale processing, restores queued, deduplicates
|
|
1101
|
+
3. resumeInProgressTasks() — re-creates execution items for active tasks
|
|
1102
|
+
```
|
|
1103
|
+
|
|
1104
|
+
---
|
|
1105
|
+
|
|
1106
|
+
## 18. Retry Cleanup
|
|
1107
|
+
|
|
1108
|
+
When a task is retried (`retryTaskFresh`) or a scheduled task is reset for rerun (`resetTaskForRerun`), any queued informational `task_status_update` items for that task are dropped from the mailbox. This prevents stale notifications (e.g., "Task blocked" from before the retry) from being processed alongside the fresh execution.
|
|
1109
|
+
|
|
1110
|
+
### What is dropped
|
|
1111
|
+
|
|
1112
|
+
Only `task_status_update` items that meet **all** conditions:
|
|
1113
|
+
- Status is `queued` (not yet processing)
|
|
1114
|
+
- `sourceType` is `task_status_update`
|
|
1115
|
+
- `extra.triggerExecution` is **not** set (execution-trigger items are real work, never dropped)
|
|
1116
|
+
- `taskId` matches the retried task
|
|
1117
|
+
|
|
1118
|
+
### What is preserved
|
|
1119
|
+
|
|
1120
|
+
- `task_comment` — genuine human/agent interactions
|
|
1121
|
+
- `mention` — explicit @mention notifications
|
|
1122
|
+
- `a2a_message` — inter-agent messages
|
|
1123
|
+
- All items already in `processing` state
|
|
1124
|
+
|
|
1125
|
+
### Implementation
|
|
1126
|
+
|
|
1127
|
+
`AgentMailbox.dropStatusUpdatesByTaskId(taskId)` iterates the queue in reverse, splicing matching items and marking them as `dropped` in persistence. Called from `retryTaskFresh()` and `resetTaskForRerun()` in `TaskService`, before the fresh execution is enqueued.
|
|
1128
|
+
|
|
1129
|
+
---
|
|
1130
|
+
|
|
1131
|
+
## 19. EventBus Architecture
|
|
1132
|
+
|
|
1133
|
+
Each `Agent` creates its own private `EventBus` instance. The `AgentManager` has a separate manager-level `EventBus`. External listeners (e.g., WebSocket broadcast handlers in `start.ts`) register on the **manager's** EventBus.
|
|
1134
|
+
|
|
1135
|
+
### Event Forwarding
|
|
1136
|
+
|
|
1137
|
+
To bridge the gap, `AgentManager.forwardAgentEvents()` is called when each agent is created or restored. It subscribes to key events on the agent's private bus and re-emits them on the manager's bus:
|
|
1138
|
+
|
|
1139
|
+
```
|
|
1140
|
+
Agent's Private EventBus Manager's EventBus start.ts (WS broadcast)
|
|
1141
|
+
───────────────────── ────────────────── ───────────────────────
|
|
1142
|
+
agent:activity-log ──────────► agent:activity-log ──────► Persist to main session DB
|
|
1143
|
+
agent:activity_log ──────────► agent:activity_log ──────► Stream to frontend Activity tab
|
|
1144
|
+
agent:started ──────────► agent:started ──────► agent:started WS event
|
|
1145
|
+
agent:stopped ──────────► agent:stopped ──────► agent:stopped WS event
|
|
1146
|
+
agent:paused ──────────► agent:paused ──────► agent:paused WS event
|
|
1147
|
+
agent:resumed ──────────► agent:resumed ──────► agent:resumed WS event
|
|
1148
|
+
agent:focus-changed ──────────► agent:focus-changed ──────► agent:focus WS event
|
|
1149
|
+
agent:message ──────────► agent:message
|
|
1150
|
+
task:completed ──────────► task:completed ──────► task update WS event
|
|
1151
|
+
task:failed ──────────► task:failed ──────► task update WS event
|
|
1152
|
+
mailbox:new-item ──────────► mailbox:new-item ──────► agent:mailbox WS event
|
|
1153
|
+
attention:decision ──────────► attention:decision ──────► agent:decision WS event
|
|
1154
|
+
attention:state-changed ──────► attention:state-changed ──► agent:attention WS event
|
|
1155
|
+
attention:triage ──────────► attention:triage ──────► agent:triage WS event
|
|
1156
|
+
```
|
|
1157
|
+
|
|
1158
|
+
Events emitted directly on the manager's bus (no forwarding needed):
|
|
1159
|
+
- `agent:created` — emitted by `AgentManager.createAgent()` / `restoreFromDB()`
|
|
1160
|
+
- `agent:removed` — emitted by `AgentManager.removeAgent()`
|
|
1161
|
+
- `system:*` — emitted by `AgentManager` global operations
|
|
1162
|
+
|
|
1163
|
+
### Why Two Buses?
|
|
1164
|
+
|
|
1165
|
+
The agent's private bus provides internal encapsulation — the agent, its mailbox, and its attention controller communicate without coupling to the manager. The manager's bus provides a single subscription point for infrastructure concerns (persistence, WS broadcast, monitoring).
|
|
1166
|
+
|
|
1167
|
+
---
|
|
1168
|
+
|
|
1169
|
+
## 20. Main Session Activity Injection
|
|
1170
|
+
|
|
1171
|
+
Each agent has a **main session** — a persistent chat session that serves as the agent's chronological activity log. Every mailbox item the agent processes (except `human_chat`) generates a concise activity summary in this session.
|
|
1172
|
+
|
|
1173
|
+
### Purpose
|
|
1174
|
+
|
|
1175
|
+
Without the main session, the agent loses narrative continuity across processing contexts. For example: a user creates a task via chat, the task completes via heartbeat-triggered execution, but the agent's chat session has no record of the completion. The main session bridges this gap by recording all mailbox-driven activity.
|
|
1176
|
+
|
|
1177
|
+
### Data Flow
|
|
1178
|
+
|
|
1179
|
+
```
|
|
1180
|
+
Agent processes mailbox item
|
|
1181
|
+
└─ finally block in processMailboxItemInternal()
|
|
1182
|
+
└─ buildActivityOutcome(item) → outcome string
|
|
1183
|
+
└─ injectActivityToMainSession({type, summary, outcome, mailboxItemId})
|
|
1184
|
+
├─ memory.appendMessage() → in-memory context for next LLM turn
|
|
1185
|
+
└─ eventBus.emit('agent:activity-log', {agentId, sessionId, message, metadata})
|
|
1186
|
+
└─ [forwarded to manager's EventBus]
|
|
1187
|
+
└─ start.ts listener:
|
|
1188
|
+
├─ chatSessionRepo.getOrCreateMainSession(agentId)
|
|
1189
|
+
├─ chatSessionRepo.appendMessage() → DB persistence
|
|
1190
|
+
├─ chatSessionRepo.updateLastMessage() → session sort order
|
|
1191
|
+
└─ ws.broadcastProactiveMessage() → real-time frontend update
|
|
1192
|
+
```
|
|
1193
|
+
|
|
1194
|
+
### Message Format
|
|
1195
|
+
|
|
1196
|
+
```
|
|
1197
|
+
[ACTIVITY: <sourceType>] <summary> → <outcome>
|
|
1198
|
+
```
|
|
1199
|
+
|
|
1200
|
+
Examples:
|
|
1201
|
+
- `[ACTIVITY: heartbeat] Heartbeat check-in → heartbeat processed`
|
|
1202
|
+
- `[ACTIVITY: callback_result] Background process succeeded: npm test → callback processed`
|
|
1203
|
+
- `[ACTIVITY: review_request] Review task "Fix login bug" → reviewed`
|
|
1204
|
+
- `[ACTIVITY: task_status_update] Task assigned: implement API → executed`
|
|
1205
|
+
|
|
1206
|
+
### Frontend Rendering
|
|
1207
|
+
|
|
1208
|
+
Activity log entries (marked with `activityLog: true` metadata) are hidden from the chat interface and visible only in the Agent Profile Mind tab. This reduces noise in the chat while keeping full traceability in the agent's profile.
|
|
1209
|
+
|
|
1210
|
+
**Exception — `notify_user` and escalation**: These messages bypass `injectActivityToMainSession` entirely and are instead injected as regular chat messages via their own `agent:notify-user` and `agent:escalation` event handlers. `notify_user` messages carry `{ notifyUser: true, priority, taskId?, requirementId? }` metadata (not `activityLog`), and their content includes an embedded `<!-- notify_context -->` comment with task/requirement references. They render as normal agent chat bubbles, allowing users to see and reply to them directly. The embedded context ensures the agent retains awareness of the notification's origin when processing the user's reply.
|
|
1211
|
+
|
|
1212
|
+
When the user opens an agent's chat, the frontend loads sessions via `getSessionsByAgent()`, which returns the main session first (sorted by `is_main DESC`). The main session's messages include both user conversations and notify/escalation messages, displayed chronologically.
|
|
1213
|
+
|
|
1214
|
+
### Completion protocol (typed `end_turn`)
|
|
1215
|
+
|
|
1216
|
+
There is **no** text completion marker any more. An agent ends a turn by **calling the
|
|
1217
|
+
`end_turn` tool** (unconditionally injected, budget-protected); the reply is then empty on
|
|
1218
|
+
purpose, and the mailbox/attention layer receives the typed sentinel `[end_turn]`
|
|
1219
|
+
(`END_TURN_REPLY_SENTINEL`). A tool call cannot be paraphrased into prose, cannot leak into a
|
|
1220
|
+
reply, and needs no detection heuristic or cleanup — the old `<<HANDLE_COMPLETE>>` string, its
|
|
1221
|
+
prompt injection, its `<think>`-aware detector and its leak regex were all deleted (see
|
|
1222
|
+
[platform-hardening-2026-10.md](../records/platform-hardening-2026-10.md) §6).
|
|
1223
|
+
|
|
1224
|
+
`detectAbnormalCompletion()` now judges exactly one thing: **did the turn produce any output at
|
|
1225
|
+
all?** `[preempted]`, `[cancelled]` and `[end_turn]` are deliberate typed signals → normal. An
|
|
1226
|
+
empty/undefined reply → abnormal:
|
|
1227
|
+
|
|
1228
|
+
- background types are **requeued** (up to `MAILBOX_ITEM_MAX_RETRIES`); once the budget is
|
|
1229
|
+
exhausted the item is marked **dropped** (visible, no silent loss), and
|
|
1230
|
+
- user-interaction types are marked **dropped** without retry (the user already saw partial
|
|
1231
|
+
output and tool calls may have had side effects — restarting would duplicate them).
|
|
1232
|
+
|
|
1233
|
+
### Spec: unfinished/refused work is visible (P0)
|
|
1234
|
+
|
|
1235
|
+
The two "complete without retry" cases above (and tool failures / `MEMORY.md` write
|
|
1236
|
+
refusals) currently resolve near-silently — the user has no clear signal the turn did not
|
|
1237
|
+
finish cleanly.
|
|
1238
|
+
|
|
1239
|
+
- **Behavior**: when a turn completes without a marker after continuation (or a tool returns
|
|
1240
|
+
a structured error, or a memory write is refused), the agent emits a **structured event**
|
|
1241
|
+
(`incomplete` / `tool_error`) and an activity-log entry. Retry semantics are **unchanged** —
|
|
1242
|
+
this adds visibility only.
|
|
1243
|
+
- **Invariants**: each condition emits exactly one corresponding event; no additional retries
|
|
1244
|
+
are triggered by making it visible. See the mailbox-item terminal states in
|
|
1245
|
+
[state-machines.md](./state-machines.md) and the event contract in
|
|
1246
|
+
[streaming-and-reattach.md §4.1](./streaming-and-reattach.md).
|
|
1247
|
+
- **Testing** (`packages/core/test/attention.test.ts` — "A3: emits agent:incomplete…"):
|
|
1248
|
+
a marker-missing completion emits exactly one `agent:incomplete` event, adds no retry, and
|
|
1249
|
+
completes the item.
|
|
1250
|
+
- **Status**: implemented (`AttentionController.emitIncomplete`, emitted from the
|
|
1251
|
+
complete-without-retry and max-retries-exhausted terminals; consumers can forward it to the
|
|
1252
|
+
activity log / SSE per [streaming-and-reattach.md §4.1](./streaming-and-reattach.md)).
|
|
1253
|
+
|
|
1254
|
+
---
|
|
1255
|
+
|
|
1256
|
+
## 21. Mailbox Triage System
|
|
1257
|
+
|
|
1258
|
+
When an agent dequeues a mailbox item and additional items remain in the queue, the Attention Controller triggers an LLM-driven **triage phase** before processing. This ensures the agent considers all pending work holistically rather than blindly following priority order.
|
|
1259
|
+
|
|
1260
|
+
### Pre-Triage Entity Consolidation
|
|
1261
|
+
|
|
1262
|
+
Before triage (or processing), the system automatically consolidates queued items that share the same `taskId` or `requirementId` — regardless of `sourceType`. This is a cross-type merge: a `task_status_update`, `a2a_message`, `mention`, and `task_comment` all referencing `tsk_abc123` are collapsed into a single rich-context item.
|
|
1263
|
+
|
|
1264
|
+
This differs from enqueue-time dedup (which only merges same-type comments):
|
|
1265
|
+
- **Enqueue-time**: `task_comment` + `task_comment` for same task → merged (fast, prevents accumulation)
|
|
1266
|
+
- **Pre-triage**: `task_comment` + `a2a_message` + `task_status_update` for same task → consolidated (comprehensive, gives agent full entity context)
|
|
1267
|
+
|
|
1268
|
+
The headItem is temporarily put back into the queue so it participates in consolidation, then re-dequeued.
|
|
1269
|
+
|
|
1270
|
+
### Three-Tier Cognitive Model
|
|
1271
|
+
|
|
1272
|
+
The triage system implements a three-tier cognitive model inspired by Dual Process Theory (Kahneman, 2011):
|
|
1273
|
+
|
|
1274
|
+
- **Tier 0 (Reflexive / System 1)**: Queue depth = 0 after consolidation, or priorities clearly separate items → no LLM call needed. Process immediately.
|
|
1275
|
+
- **Tier 1 (Quick Classification / System 1+)**: Interrupt arrives during focused work, heuristic says "continue" but LLM may disagree → single LLM call returning one word (`continue`/`preempt`/`cancel`/`merge`/`defer`).
|
|
1276
|
+
- **Tier 2 (Full Deliberation / System 2)**: Multiple items with overlapping priorities AND `performDeliberation` configured → full agent session with complete tool access and memory.
|
|
1277
|
+
|
|
1278
|
+
### Triage Flow
|
|
1279
|
+
|
|
1280
|
+
```
|
|
1281
|
+
dequeueAsync() → headItem
|
|
1282
|
+
│
|
|
1283
|
+
├─ queue empty? → TIER 0: record 'pick' → process(headItem)
|
|
1284
|
+
│
|
|
1285
|
+
└─ queue non-empty?
|
|
1286
|
+
├─ CONSOLIDATION: putBack(headItem) → consolidateByEntity() → dequeue()
|
|
1287
|
+
│ (items sharing same taskId/requirementId merged cross-type)
|
|
1288
|
+
│
|
|
1289
|
+
├─ queue empty after consolidation? → TIER 0
|
|
1290
|
+
│
|
|
1291
|
+
└─ priorities clearly separate? → TIER 0
|
|
1292
|
+
│
|
|
1293
|
+
└─ ambiguous priorities AND (performDeliberation OR triageJudge)?
|
|
1294
|
+
│
|
|
1295
|
+
├─ performDeliberation available?
|
|
1296
|
+
│ → TIER 2: Full-session deliberation (scenario='deliberation')
|
|
1297
|
+
│ ├─ Agent deliberates AS ITSELF with full identity
|
|
1298
|
+
│ ├─ Access to memory, recall_activity, task tools
|
|
1299
|
+
│ ├─ Can handle simple items INLINE (notify, comment, message)
|
|
1300
|
+
│ ├─ Calls complete_deliberation tool with decision
|
|
1301
|
+
│ ├─ Apply inline-completed / defer / drop / choose
|
|
1302
|
+
│ └─ Working memory updated (`deliberation` key from situational awareness)
|
|
1303
|
+
│
|
|
1304
|
+
└─ triageJudge only (fallback)?
|
|
1305
|
+
→ Mini triage loop (up to TRIAGE_MAX_TOOL_ITERATIONS rounds)
|
|
1306
|
+
├─ Build prompt with candidates + context
|
|
1307
|
+
├─ LLM calls read-only tools to gather context
|
|
1308
|
+
├─ Returns JSON: { processItemId, deferItemIds, dropItemIds }
|
|
1309
|
+
└─ Apply decisions
|
|
1310
|
+
```
|
|
1311
|
+
|
|
1312
|
+
### Full-Session Deliberation (Tier 2)
|
|
1313
|
+
|
|
1314
|
+
When `delegate.performDeliberation` is available (always in production), the attention controller delegates triage to a full agent session:
|
|
1315
|
+
|
|
1316
|
+
1. The agent receives all queued items formatted as a `[DELIBERATION MODE]` prompt.
|
|
1317
|
+
2. It uses `handleMessage()` with `scenario: 'deliberation'` — the same code path as chat/task but with restricted tool access (`DELIBERATION_ALLOWED_TOOLS`).
|
|
1318
|
+
3. The agent deliberates **as itself** (full system prompt, identity, memory access).
|
|
1319
|
+
4. It can handle simple items **inline** (e.g., send a quick notification, post a comment).
|
|
1320
|
+
5. It calls `complete_deliberation` with its structured decision.
|
|
1321
|
+
6. The attention controller applies the decision: mark inline items completed, defer/drop others, choose the focus item.
|
|
1322
|
+
|
|
1323
|
+
**Deliberation is atomic**: yield points are suppressed during deliberation (new mail sets the interrupt signal but is not evaluated until deliberation completes).
|
|
1324
|
+
|
|
1325
|
+
**Strict state items are excluded from deliberation (critical safety)**:
|
|
1326
|
+
|
|
1327
|
+
Items carrying formal task/requirement/workflow state transitions — collectively **strict state items** (predicate `isStrictStateItem` in `@markus/shared`):
|
|
1328
|
+
- `task_status_update` with `extra.triggerExecution` (formal task execution)
|
|
1329
|
+
- `review_request` (review request)
|
|
1330
|
+
- `requirement_update` / `workflow_update` with `extra.actionRequired` (closure action)
|
|
1331
|
+
|
|
1332
|
+
are **filtered out of the deliberation view entirely**:
|
|
1333
|
+
|
|
1334
|
+
1. **They are invisible to the LLM during deliberation** — `performDeliberation` receives only non-strict items; the optionality prompt (`[DELIBERATION MODE]`) and tool docs instruct the agent that `isStrictState: true` items seen via `check_mailbox` may only be reordered, never deferred/dropped/batched/inline-completed.
|
|
1335
|
+
2. **They never trigger deliberation** — `needsLLMTriage` returns false when the head or any queued item is strict, so tasks/reviews are processed by the normal single-item execution path with the full tool set (including `task_update` / `task_submit_review` / shell / file).
|
|
1336
|
+
3. **Yield-point defer is refused** — if the interrupt evaluator returns `defer` for a strict item, it falls back to the heuristic (high-priority task execution → `preempt` → executed as its own item).
|
|
1337
|
+
4. **Mailbox tools refuse them** — `defer_mailbox_item` / `drop_mailbox_item` return an error for strict items (defense in depth), and `complete_deliberation` rejects results that list strict items in `defer/drop/inline/batch`. The orphan-completeness check **excludes** strict items (they are not part of the deliberation view).
|
|
1338
|
+
5. **Lost-closure recovery** — if a task execution item ever resurfaces from persistence **without its callback closures** (e.g. deferred before start, then resurfaced after restart), the agent no longer silently completes it: it emits an `agent:incomplete` event with `reason: resurfaced-task-execution-lost-closures`, and the org-manager `TaskService` subscribes to that event and calls `recoverLostTaskExecution(taskId)` — re-dispatches the task via `runTask` (with proper closures) if it is still `in_progress` and has no active execution. This prevents tasks from hanging in `in_progress` forever.
|
|
1339
|
+
|
|
1340
|
+
Why this matters: task execution, review, and requirement/workflow finalization must run through their dedicated state machines (`executeTask(taskId, onLog)` with live `onLog`/`cancelToken`/`responsePromise` closures). If they were deferred/dropped/merged/batched by deliberation, the closures are lost with persistence, task logs never land under the task, and the task can remain `in_progress` with nobody working it.
|
|
1341
|
+
|
|
1342
|
+
### Tool Access During Deliberation
|
|
1343
|
+
|
|
1344
|
+
Defined by `DELIBERATION_ALLOWED_TOOLS` in `@markus/shared`:
|
|
1345
|
+
|
|
1346
|
+
| Category | Tools |
|
|
1347
|
+
|----------|-------|
|
|
1348
|
+
| Context gathering | `task_list`, `task_get`, `requirement_list`, `requirement_get`, `list_projects`, `team_list`, `team_status`, `recall_activity`, `memory_search` |
|
|
1349
|
+
| Inline communication | `notify_user`, `task_comment`, `requirement_comment`, `agent_send_message`, `agent_send_group_message`, `agent_create_group_chat`, `agent_list_group_chats` |
|
|
1350
|
+
| Mailbox management | `check_mailbox`, `defer_mailbox_item`, `drop_mailbox_item`, `prioritize_mailbox_item` |
|
|
1351
|
+
| Working memory | `notebook_upsert`, `notebook_clear`, `notebook_read` |
|
|
1352
|
+
| Memory | `memory_save`, `memory_update`, `memory_update_longterm` |
|
|
1353
|
+
| Decision output | `complete_deliberation` |
|
|
1354
|
+
|
|
1355
|
+
**Excluded**: `task_create`, `task_update`, `requirement_propose`, code/shell tools, `spawn_subagent`. These are heavy side-effect tools that belong in the processing phase.
|
|
1356
|
+
|
|
1357
|
+
### Agent Mailbox Management Tools
|
|
1358
|
+
|
|
1359
|
+
In addition to the batch decision via `complete_deliberation`, agents can manage
|
|
1360
|
+
individual mailbox items using dedicated tools:
|
|
1361
|
+
|
|
1362
|
+
| Tool | Available In | Purpose |
|
|
1363
|
+
|------|-------------|---------|
|
|
1364
|
+
| `check_mailbox` | All scenarios | Read-only queue inspection |
|
|
1365
|
+
| `defer_mailbox_item` | Deliberation + focused processing | Postpone an item |
|
|
1366
|
+
| `drop_mailbox_item` | Deliberation + focused processing | Discard stale item |
|
|
1367
|
+
| `prioritize_mailbox_item` | Deliberation only | Re-prioritize item |
|
|
1368
|
+
| `notebook_upsert` | All scenarios | Update situational awareness |
|
|
1369
|
+
| `notebook_clear` | All scenarios | Clear stale awareness |
|
|
1370
|
+
|
|
1371
|
+
**Safety**: `human_chat` items are protected — they cannot be deferred, dropped,
|
|
1372
|
+
or reprioritized by tool calls. **Strict state items** (formal task execution / review /
|
|
1373
|
+
requirement·workflow closure actions — see above) are protected too: `defer_mailbox_item` /
|
|
1374
|
+
`drop_mailbox_item` return an error, and only `prioritize_mailbox_item` may change their priority;
|
|
1375
|
+
they are ultimately executed one at a time by the normal dequeue path.
|
|
1376
|
+
|
|
1377
|
+
**Relationship to `complete_deliberation`**: The individual tools take immediate
|
|
1378
|
+
effect. `complete_deliberation` handles remaining items in bulk. They are additive.
|
|
1379
|
+
|
|
1380
|
+
### DeliberationResult
|
|
1381
|
+
|
|
1382
|
+
```typescript
|
|
1383
|
+
interface DeliberationResult {
|
|
1384
|
+
processItemId: string; // Primary item (backward compat)
|
|
1385
|
+
processItemIds?: string[]; // Batch: multiple items to process together
|
|
1386
|
+
batchContext?: string; // Synthesis/instruction for batch processing
|
|
1387
|
+
deferItemIds: string[]; // Postpone for later
|
|
1388
|
+
dropItemIds: string[]; // Discard (stale/redundant)
|
|
1389
|
+
inlineCompletedIds: string[]; // Already handled during deliberation
|
|
1390
|
+
reasoning: string;
|
|
1391
|
+
situationalAwareness?: string; // Agent-authored metacognitive summary
|
|
1392
|
+
memoryUpdates?: Array<{ // Memory operations applied after deliberation
|
|
1393
|
+
type: 'working' | 'longterm';
|
|
1394
|
+
key: string;
|
|
1395
|
+
content: string;
|
|
1396
|
+
}>;
|
|
1397
|
+
}
|
|
1398
|
+
```
|
|
1399
|
+
|
|
1400
|
+
### Batch Processing
|
|
1401
|
+
|
|
1402
|
+
When `processItemIds` contains more than one item, the attention controller dequeues all of them and composes their content into a single LLM session. This is efficient for:
|
|
1403
|
+
- Multiple `a2a_message` items from the same channel (already partially merged by dedup)
|
|
1404
|
+
- Related notifications about the same project/topic
|
|
1405
|
+
- Multiple low-priority items that can be acknowledged together
|
|
1406
|
+
|
|
1407
|
+
All batch items share one LLM call. If processing is interrupted (preempt/cancel/timeout), all batch items are requeued.
|
|
1408
|
+
|
|
1409
|
+
### Memory Updates During Deliberation
|
|
1410
|
+
|
|
1411
|
+
Deliberation can produce `memoryUpdates` — both working memory (volatile, per-session) and long-term memory (curated, persisted to MEMORY.md). This enables the agent to:
|
|
1412
|
+
- Record team decisions observed in merged messages
|
|
1413
|
+
- Note user preferences inferred from multiple interactions
|
|
1414
|
+
- Build context continuity across processing cycles
|
|
1415
|
+
|
|
1416
|
+
Tools `memory_save` and `memory_update_longterm` are also available during deliberation for immediate effect.
|
|
1417
|
+
```
|
|
1418
|
+
|
|
1419
|
+
### Working Memory Injection
|
|
1420
|
+
|
|
1421
|
+
The agent maintains a **keyed working memory store** (`workingMemory` Map) that
|
|
1422
|
+
replaces the former `currentCognition` string. Each entry has:
|
|
1423
|
+
- A key (agent-chosen label, e.g., "deliberation", "task-priorities")
|
|
1424
|
+
- Content text
|
|
1425
|
+
- Update timestamp
|
|
1426
|
+
|
|
1427
|
+
Working memory is populated from three sources:
|
|
1428
|
+
1. **Deliberation**: `situationalAwareness` → key `"deliberation"`
|
|
1429
|
+
2. **Triage**: reasoning → key `"triage-decision"`
|
|
1430
|
+
3. **Agent tools**: `notebook_upsert` / `notebook_clear`
|
|
1431
|
+
|
|
1432
|
+
All entries are injected into every system prompt as `## Working Memory` with
|
|
1433
|
+
age labels per entry. The agent decides what to keep, update, or expire.
|
|
1434
|
+
|
|
1435
|
+
### Mini Triage Loop (Fallback)
|
|
1436
|
+
|
|
1437
|
+
When `performDeliberation` is unavailable, the system falls back to the legacy mini triage loop:
|
|
1438
|
+
- Triage LLM uses the agent's name and role in its system prompt.
|
|
1439
|
+
- Can call tools from `TRIAGE_ALLOWED_TOOLS` (including `recall_activity`, `memory_search`) up to `TRIAGE_MAX_TOOL_ITERATIONS` (6) rounds.
|
|
1440
|
+
- Returns a structured JSON decision (same as `TriageResult`).
|
|
1441
|
+
|
|
1442
|
+
### Key Methods
|
|
1443
|
+
|
|
1444
|
+
| Method | Location | Purpose |
|
|
1445
|
+
|--------|----------|---------|
|
|
1446
|
+
| `performDeliberation()` | `agent.ts` | Full-session deliberation via handleMessage(scenario='deliberation') |
|
|
1447
|
+
| `applyDeliberationResult()` | `attention.ts` | Applies inline/defer/drop/choose from deliberation |
|
|
1448
|
+
| `complete_deliberation` (tool) | `agent.ts` executeTool | Captures structured decision during deliberation |
|
|
1449
|
+
| `applyTriageResult()` | `attention.ts` | Applies defer/drop/choose from mini triage (fallback) |
|
|
1450
|
+
| `performTriage()` | `attention.ts` | Mini triage loop (fallback path) |
|
|
1451
|
+
| `buildTriagePrompt()` | `attention.ts` | Constructs the triage prompt with candidates + context |
|
|
1452
|
+
| `consolidateByEntity()` | `mailbox.ts` | Merges items sharing same taskId/requirementId (cross-type) |
|
|
1453
|
+
| `updateCognitionFromDeliberation()` | `agent.ts` | Writes deliberation `situationalAwareness` into `workingMemory` under key `"deliberation"` |
|
|
1454
|
+
| `evaluateWithLLMFallback()` | `attention.ts` | Heuristic-first interrupt decision with optional LLM fallback |
|
|
1455
|
+
|
|
1456
|
+
### Triage Prompt Identity
|
|
1457
|
+
|
|
1458
|
+
Both deliberation (Tier 2) and the mini triage loop (fallback) use first-person perspective: "You are {agentName}." The agent deliberates **as itself** with its role context, not as an external "attention manager."
|
|
1459
|
+
|
|
1460
|
+
---
|
|
1461
|
+
|
|
1462
|
+
## 22. Deferred Item Auto-Resume
|
|
1463
|
+
|
|
1464
|
+
Deferred mailbox items are automatically resurfaced when the agent is idle:
|
|
1465
|
+
|
|
1466
|
+
- `resurfaceDue()` is called at the top of each attention loop idle cycle (before `dequeueAsync`) and after `recoverStaleItems` on startup.
|
|
1467
|
+
- Items where `deferredUntil <= now` or `deferredUntil` is undefined (deferred without a time = resume on next idle) are re-enqueued.
|
|
1468
|
+
- Deferred items are loaded from persistence via `loadDeferred(agentId)`.
|
|
1469
|
+
|
|
1470
|
+
## 23. Task Status Update Processing
|
|
1471
|
+
|
|
1472
|
+
`task_status_update` items are **informational by default** (`invokesLLM: false`); execution-mode items (`extra.triggerExecution`) run as a full task execution (§3.4). The side-effect system in `updateTaskStatus()` handles all real actions automatically:
|
|
1473
|
+
- **→ `in_progress`**: Auto-starts task execution
|
|
1474
|
+
- **Leaving `in_progress`**: Cancels running execution
|
|
1475
|
+
- **→ `review`**: Notifies reviewer (agent via mailbox, or human via approval request)
|
|
1476
|
+
- **Terminal states**: Checks and unblocks dependent tasks
|
|
1477
|
+
|
|
1478
|
+
Agents do NOT need to take action on these notifications — they serve as episodic memory and triage decision context. Agents should NOT send A2A messages to duplicate what the side-effect system already does.
|
|
1479
|
+
|
|
1480
|
+
## 24. Cognitive Science Foundation
|
|
1481
|
+
|
|
1482
|
+
The three-tier triage model (§21) is grounded in established cognitive science:
|
|
1483
|
+
|
|
1484
|
+
| Theory | Application in Markus |
|
|
1485
|
+
|--------|----------------------|
|
|
1486
|
+
| **Dual Process Theory** (Kahneman, 2011) | Tier 0/1 = System 1 (fast, automatic); Tier 2 = System 2 (slow, deliberative) |
|
|
1487
|
+
| **Situational Awareness** (Endsley, 1995) | Full deliberation achieves Level 2+3 SA (comprehension + projection) via memory access |
|
|
1488
|
+
| **Working Memory / Episodic Buffer** (Baddeley, 2000) | `recall_activity` and `memory_search` serve as the episodic buffer linking current stimuli to long-term memory |
|
|
1489
|
+
| **Metacognition** (Flavell, 1979) | `situationalAwareness` field in `DeliberationResult` enables agent self-monitoring |
|
|
1490
|
+
| **Prospective Memory** (Einstein & McDaniel, 2005) | During deliberation, agents can check pending commitments and proactively notify users |
|
|
1491
|
+
| **Cognitive Load Theory** (Sweller, 1988) | Unified identity in deliberation eliminates task-switching cost between "triage assistant" and "agent self" |
|
|
1492
|
+
|
|
1493
|
+
### Design Rationale
|
|
1494
|
+
|
|
1495
|
+
- **Why not always use Tier 2?** Cost and latency. Tier 2 deliberation costs 5-15K tokens vs 0 for Tier 0. Now with `TRIAGE_BACKLOG_THRESHOLD = 2`, deliberation fires whenever 2+ items are queued (non-user head). The cost increase is acceptable because:
|
|
1496
|
+
- (a) most single-item processing still takes the fast path,
|
|
1497
|
+
- (b) deliberation with 2-3 items is much cheaper than with 5+, and
|
|
1498
|
+
- (c) the agent can now use `drop_mailbox_item` during deliberation to clean up before committing to expensive processing.
|
|
1499
|
+
- **Why allow inline handling?** Cognitive science shows humans handle simple items (quick email replies) during triage rather than queuing them separately. This reduces total cognitive load and latency.
|
|
1500
|
+
- **Why suppress yield points during deliberation?** Deliberation is a metacognitive process — interrupting it would break the agent's reasoning coherence (analogous to interrupting someone mid-thought during planning).
|
|
1501
|
+
- **Why inject working memory into future prompts?** This implements **metacognitive regulation** — keyed summaries (deliberation, triage, agent-authored entries) persist across processing contexts, maintaining behavioral consistency.
|
|
1502
|
+
|
|
1503
|
+
---
|
|
1504
|
+
|
|
1505
|
+
## 25. Proactive Messaging Capabilities
|
|
1506
|
+
|
|
1507
|
+
### Can agents proactively send messages?
|
|
1508
|
+
|
|
1509
|
+
**Yes.** Agents can initiate communication across multiple channels, including targeted user notifications.
|
|
1510
|
+
|
|
1511
|
+
### 25.1 User DM (1:1 Chat)
|
|
1512
|
+
|
|
1513
|
+
**Tool**: `notify_user`
|
|
1514
|
+
|
|
1515
|
+
| Capability | Status |
|
|
1516
|
+
|-----------|--------|
|
|
1517
|
+
| Send proactive message to user | **Yes** — appears in agent's main chat session |
|
|
1518
|
+
| Message shows in chat UI | **Yes** — as regular assistant message (not hidden as activity log) |
|
|
1519
|
+
| User can reply in chat | **Yes** — reply triggers `human_chat` mailbox item |
|
|
1520
|
+
| Notification bell | **Yes** — `HITLService.notify()` creates persistent notification |
|
|
1521
|
+
| Target specific user by ID | **Yes** — `target_user_id` parameter (optional) |
|
|
1522
|
+
| Fallback when no target specified | Uses `currentInteractingUserId` (last human who chatted), then team owner |
|
|
1523
|
+
| Initiate first-ever conversation with user | **Yes** — via `target_user_id` during deliberation or heartbeat |
|
|
1524
|
+
|
|
1525
|
+
**Flow**:
|
|
1526
|
+
```
|
|
1527
|
+
Agent calls notify_user(title, body, target_user_id?)
|
|
1528
|
+
→ Build context suffix: <!-- notify_context: task_id=xxx, requirement_id=yyy -->
|
|
1529
|
+
→ memory.appendMessage(formattedMsg + contextSuffix) — in-memory session
|
|
1530
|
+
→ eventBus.emit('agent:notify-user', { targetUserId, taskId, requirementId, ... })
|
|
1531
|
+
→ start.ts handler:
|
|
1532
|
+
→ chatSessionRepo.getOrCreateMainSession(agentId, targetUserId ?? ownerId)
|
|
1533
|
+
→ chatSessionRepo.appendMessage(msg, metadata: { notifyUser, priority, taskId, requirementId })
|
|
1534
|
+
→ ws.broadcastProactiveMessage(metadata: { notifyUser, taskId, requirementId }) — scoped to target user
|
|
1535
|
+
→ hitlService.notify() — notification bell entry
|
|
1536
|
+
```
|
|
1537
|
+
|
|
1538
|
+
**Context preservation**: When the user replies to a notification, `restoreSessionFromHistory()` loads the message content (including the `<!-- notify_context -->` comment). The agent's `chat` scenario prompt instructs it to use these references to retrieve full context before responding.
|
|
1539
|
+
|
|
1540
|
+
### 25.2 Group Chat
|
|
1541
|
+
|
|
1542
|
+
**Tool**: `agent_send_group_message`
|
|
1543
|
+
|
|
1544
|
+
| Capability | Status |
|
|
1545
|
+
|-----------|--------|
|
|
1546
|
+
| Send message to team group | **Yes** — `channel_key: "group:<teamId>"` |
|
|
1547
|
+
| Send message to custom group | **Yes** — `channel_key: "group:custom:<id>"` |
|
|
1548
|
+
| Message visible to all channel members | **Yes** — persisted + WebSocket broadcast |
|
|
1549
|
+
| Triggers other agents in channel | **Yes** — enqueues `a2a_message` to peer agents |
|
|
1550
|
+
| Create new group chat | **Yes** — `agent_create_group_chat` tool |
|
|
1551
|
+
| Available during deliberation | **Yes** — in `DELIBERATION_ALLOWED_TOOLS` |
|
|
1552
|
+
|
|
1553
|
+
### 25.3 Agent-to-Agent (A2A)
|
|
1554
|
+
|
|
1555
|
+
A2A messages route through persistent DM channels (`dm:a2a:{sorted_ids}`) — see §11.1.
|
|
1556
|
+
|
|
1557
|
+
| Tool | Capability |
|
|
1558
|
+
|------|-----------|
|
|
1559
|
+
| `agent_send_message` | Direct message to another agent via DM channel |
|
|
1560
|
+
| `agent_broadcast_status` | Status update to all colleagues (lightweight, no LLM) |
|
|
1561
|
+
| `agent_delegate_task` | Formal task delegation with protocol |
|
|
1562
|
+
|
|
1563
|
+
### 25.4 Proactive Messaging During Deliberation
|
|
1564
|
+
|
|
1565
|
+
During full-session deliberation (Tier 2), agents can handle simple items inline by calling communication tools directly:
|
|
1566
|
+
|
|
1567
|
+
```
|
|
1568
|
+
Deliberation session starts (5 items queued)
|
|
1569
|
+
→ Agent calls memory_search to check commitments
|
|
1570
|
+
→ Agent calls notify_user(target_user_id="usr_alice", ...) — handles item #3 inline
|
|
1571
|
+
→ Agent calls task_comment(...) — handles item #5 inline
|
|
1572
|
+
→ Agent calls complete_deliberation({
|
|
1573
|
+
process_item_id: "item_1",
|
|
1574
|
+
inline_completed_ids: ["item_3", "item_5"],
|
|
1575
|
+
defer_item_ids: ["item_4"],
|
|
1576
|
+
drop_item_ids: ["item_2"],
|
|
1577
|
+
reasoning: "Item 1 is an urgent review request; handled notifications inline"
|
|
1578
|
+
})
|
|
1579
|
+
```
|
|
1580
|
+
|
|
1581
|
+
This collapses what would have been 5 separate triage+process cycles into a single deliberation + 1 processing cycle.
|
|
1582
|
+
|
|
1583
|
+
---
|
|
1584
|
+
|
|
1585
|
+
## 26. Future Work
|
|
1586
|
+
|
|
1587
|
+
- **Proactive messaging scheduler** *(implemented)*: Agents schedule time-based follow-ups via `schedule_wakeup` (one-shot or recurring); a coarse per-agent sweep fires due wakeups into the mailbox. See §11.3.
|
|
1588
|
+
- **Cross-agent priority coordination**: Allow a manager agent to influence subordinate agents' mailbox priorities.
|
|
1589
|
+
- **Decision pattern learning**: Use long-term decision history to adaptively tune heuristic thresholds.
|
|
1590
|
+
- **Deliberation cost optimization**: Implement adaptive deliberation depth — use cheaper models or shorter budgets for simple multi-item scenarios, full budget only for genuinely complex triage.
|
|
1591
|
+
- **Working memory persistence**: Persist keyed working memory across agent restarts (currently volatile).
|
|
1592
|
+
- **Adaptive deliberation model selection**: Use cheaper models for simple 2-item queues; reserve fuller budgets for genuinely complex triage.
|
|
1593
|
+
- **Recursive deliberation**: Allow deliberation to trigger sub-deliberation for complex multi-step planning (with depth limits).
|
|
1594
|
+
|
|
1595
|
+
---
|
|
1596
|
+
|
|
1597
|
+
## 27. Scheduling-Link Blocking Protection
|
|
1598
|
+
|
|
1599
|
+
> Last updated: 2026-09. Distilled from the scheduler-blocking audit (feat/context-os).
|
|
1600
|
+
> Question the audit answered: **can a single provider call permanently block the agent
|
|
1601
|
+
> main loop / event queue / scheduling chain?** Answer: no for errors, bounded for hangs,
|
|
1602
|
+
> with a small set of known no-timeout gaps.
|
|
1603
|
+
|
|
1604
|
+
### 27.1 Layered protection (error → hang → blocking)
|
|
1605
|
+
|
|
1606
|
+
| Layer | Mechanism | Bound |
|
|
1607
|
+
|-------|-----------|-------|
|
|
1608
|
+
| Error isolation | Multi-layer `try/catch` around every provider call; a thrown error never stalls the loop | immediate |
|
|
1609
|
+
| Hang backstop | In-flight work watchdog — longest possible stall is **45 min** (bounded outage) | 45 min |
|
|
1610
|
+
| Retry cap | Provider retries capped at **2 attempts** | finite |
|
|
1611
|
+
| Watchdog sweep | Attention/watchdog sweeps at **30 s** granularity | 30 s |
|
|
1612
|
+
|
|
1613
|
+
### 27.2 Known gaps (no-timeout awaits)
|
|
1614
|
+
|
|
1615
|
+
- **GAP-A — triage deliberation is NOT inside the backstop**: `deliberate` (Tier-2 full
|
|
1616
|
+
deliberation) can await the model with no timeout — the **closest existing path to a
|
|
1617
|
+
permanent block**. Mitigation today: only reachable with a non-empty queue; still, it
|
|
1618
|
+
deserves a timeout + fail-loud.
|
|
1619
|
+
- **GAP-B — task-queue has no per-task timeout**: a task execution waiting on the model
|
|
1620
|
+
is bounded only by the global backstop, not by per-task limits.
|
|
1621
|
+
- **GAP-C — dream semaphore may leak**: the dream/concurrency semaphore lacks a
|
|
1622
|
+
release-on-error guarantee in all exit paths (double-check & harden).
|
|
1623
|
+
|
|
1624
|
+
### 27.3 Fail-loud chain (the intended design)
|
|
1625
|
+
|
|
1626
|
+
Provider errors propagate **loudly** (no silent swallow): error → `requeue` (with retry
|
|
1627
|
+
count) → exhausted → `emitIncomplete` (visible structured event). This is the same
|
|
1628
|
+
visibility-first invariant as §4.1 — a failure must never look like success.
|
|
1629
|
+
|
|
1630
|
+
### 27.4 Design intent
|
|
1631
|
+
|
|
1632
|
+
The chain is allowed to **stall (bounded) but never to block silently forever**. Any new
|
|
1633
|
+
`await` inserted into the main loop or attention/triage path must be either (a) bounded by
|
|
1634
|
+
a timeout/backstop, or (b) explicitly justified as blocking by design. Watchdog + backstop
|
|
1635
|
+
values are single-source constants in `packages/core/src/` — do not fork them per caller.
|