@markus-global/cli 0.11.2 → 0.11.3-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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-C-niUbUY.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-rzRUDj8T.js → ContentRenderer-DxsnJJRX.js} +2 -2
- package/dist/web-ui/assets/{DeliverableShareModal-BvfmqTNG.js → DeliverableShareModal-DV3TiZx0.js} +1 -1
- package/dist/web-ui/assets/{Deliverables-DKTLnaF8.js → Deliverables-tlLsJnxZ.js} +1 -1
- package/dist/web-ui/assets/{Notifications-CWaO9onn.js → Notifications-4KXYRdkr.js} +1 -1
- package/dist/web-ui/assets/{Search-D_C5Eyed.js → Search-CPFwZv1U.js} +1 -1
- package/dist/web-ui/assets/{Settings-B5Ib6SFf.js → Settings-DIa-_qre.js} +6 -6
- package/dist/web-ui/assets/{Store-D__pfqoc.js → Store-JWjwXfTU.js} +1 -1
- package/dist/web-ui/assets/Team-COBxn96h.js +84 -0
- package/dist/web-ui/assets/{Work-BJ7kXixx.js → Work-BScJUqWL.js} +1 -1
- package/dist/web-ui/assets/{arc-BN0GMYN6.js → arc-DPZmpo1U.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BP5Nnl2Y.js → architectureDiagram-3BPJPVTR-DlOs02JO.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-nKHUCU_z.js → blockDiagram-GPEHLZMM-C7qsXNUe.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-DoS0wcHh.js → c4Diagram-AAUBKEIU-Drwp-rtM.js} +1 -1
- package/dist/web-ui/assets/channel-DCChB-1T.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-CP54_XNl.js → chunk-2J33WTMH-VgR09Mqk.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-DMvJaJb7.js → chunk-4BX2VUAB-CuwDpBRL.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-DQnZgoOO.js → chunk-55IACEB6-nC7YWJ_i.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-B5_3LI53.js → chunk-727SXJPM-Dw6mBsRE.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-B5Mh5bI_.js → chunk-AQP2D5EJ-CPhNJbHl.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-mjYTpuBm.js → chunk-FMBD7UC4-AyhQakG8.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-BxTrseJg.js → chunk-ND2GUHAM-DgYemv8I.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-C1do5brE.js → chunk-QZHKN3VN-CLdqxrFB.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-CrNiYfSI.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-CrNiYfSI.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DMn7aSDK.js → cose-bilkent-S5V4N54A-DrOgwDIH.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-CE-tTagY.js → dagre-BM42HDAG-DhoJiA83.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-BwyvxbJa.js → diagram-2AECGRRQ-BDILSgqK.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-Nopndxl0.js → diagram-5GNKFQAL-CeXywd1i.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-CGTjHHnD.js → diagram-KO2AKTUF-Bi4RlMT0.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-DhC3AqLA.js → diagram-LMA3HP47-Cw1yxk8b.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-BIuzyWJO.js → diagram-OG6HWLK6-Bl857da2.js} +1 -1
- package/dist/web-ui/assets/{docx-preview-ClO_djcO.js → docx-preview-CjoUhrMq.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-Nmfi9Wv0.js → erDiagram-TEJ5UH35-DEiaMhuV.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BVAM5QzO.js → flowDiagram-I6XJVG4X-BgKZhO0h.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-BGdTbY0A.js → ganttDiagram-6RSMTGT7-Dkx-EaS8.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BMfug5mp.js → gitGraphDiagram-PVQCEYII-DXaQwA0y.js} +1 -1
- package/dist/web-ui/assets/{index-1X1Ykov8.js → index-C_QhfMcC.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-Dpx9IOkx.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-Bro4RrlG.js → ishikawaDiagram-YF4QCWOH-BWqWgitQ.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-CdRHOaID.js → journeyDiagram-JHISSGLW-BBwIZ4k9.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-9iLNl-rB.js → kanban-definition-UN3LZRKU-C_MRWV8R.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-BRHCbDDt.js → mermaid.core-BMAh3nnq.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BLm-XQ6W.js → mindmap-definition-RKZ34NQL-B6vJQcat.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-ith90T5A.js → pieDiagram-4H26LBE5-BxdEttqt.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-Cb08oHG7.js → quadrantDiagram-W4KKPZXB-gsNs2VfP.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-DzMKi4w8.js → requirementDiagram-4Y6WPE33-BSC9KvC2.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-C0Wv4A7m.js → sankeyDiagram-5OEKKPKP-DktAZfe_.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-C_HL9WB0.js → sequenceDiagram-3UESZ5HK-BIPt8kGU.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-BFfTVEYQ.js → stateDiagram-AJRCARHV-DiXmJWB0.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-COOgTXIX.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-cyPnAADn.js → timeline-definition-PNZ67QCA-LRi7H35g.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-Cb82-9OZ.js → vennDiagram-CIIHVFJN-DWQ1I022.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-BTW1NXXR.js → wardley-L42UT6IY-BUb6dYqN.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-C_F_dT6n.js → wardleyDiagram-YWT4CUSO-BYE1B3xT.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-clcfplhG.js → xychartDiagram-2RQKCTM6-D-pS2-Sa.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,83 @@
|
|
|
1
|
+
# State Ownership Contract
|
|
2
|
+
|
|
3
|
+
> **Status: living contract.** This describes how the code must behave today — update it in the same
|
|
4
|
+
> change that moves an owner.
|
|
5
|
+
|
|
6
|
+
> Why this document exists: pushing state down from "agent-level singleton" to "per-worker workspace"
|
|
7
|
+
> is the right direction, but it **legitimately changes** an implicit premise found all over the repo
|
|
8
|
+
> ("reading `currentSessionId` gives you this request's session").
|
|
9
|
+
> Changes of this kind don't throw errors, they compile, and all the old tests stay green — they only
|
|
10
|
+
> show up in production as "the agent has amnesia".
|
|
11
|
+
> So "who owns which state, who may read it, and in which context it may be read" has to be written down
|
|
12
|
+
> as a contract and enforced by machine.
|
|
13
|
+
|
|
14
|
+
**Applies to**: any change that touches session identity / history / concurrency / workspace state.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 1. The three execution contexts (first, figure out where you are)
|
|
19
|
+
|
|
20
|
+
| Context | When it occurs | `sessionWorkspaceStore.getStore()` | Default workspace |
|
|
21
|
+
|---|---|---|---|
|
|
22
|
+
| **HTTP thread** | `api-server` handling a request, SSE callbacks, route validation | `undefined` | `rootWorkspace` |
|
|
23
|
+
| **worker workspace** | an attention worker pool processing a mailbox item | that worker's workspace | that worker's workspace |
|
|
24
|
+
| **background timers / bare callbacks** | backstop timeouts, `setTimeout`, external events | `undefined` | `rootWorkspace` |
|
|
25
|
+
|
|
26
|
+
> The test: `private workspace() { return sessionWorkspaceStore.getStore() ?? this.rootWorkspace; }`
|
|
27
|
+
> Under concurrent mode (3 workers by default), **the HTTP thread and a worker do not see the same thing**.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## 2. State ownership matrix (writer / reader / context)
|
|
32
|
+
|
|
33
|
+
| State | Ownership | Who writes | Who reads | Implicit reads allowed? |
|
|
34
|
+
|---|---|---|---|---|
|
|
35
|
+
| `currentSessionId` (in-memory session `sess_*`) | **per-worker** | the worker handling that item (restore / startNewSession / handle*) | the turn logic inside that same worker | ❌ **forbidden** to read across threads |
|
|
36
|
+
| `dbSessionMap` (`cs_*` → `sess_*` binding) | agent-level (shared across workers) | **written only in the worker handling that message** | anyone (looked up by DB id) | ✅ allowed (this is the only cross-thread-safe session bridge) |
|
|
37
|
+
| `MemoryStore.sessions` (the history itself) | agent-level singleton | `appendMessage` (inside a worker) | `getRecentMessages` / `getSession` | ✅ allowed (but an unknown id must warn — never silently return empty) |
|
|
38
|
+
| `chatSessionRepo` (`cs_*` persistence layer) | storage (out of process) | api-server (persist) | api-server / restore | ✅ allowed |
|
|
39
|
+
| `activeScenario` / `currentTaskId` / `turnModelOverride` / `currentInteractingUserId` | **per-worker** | same worker | same worker | ❌ forbidden to read across threads |
|
|
40
|
+
| `workerWorkspaces` / `workerStates` / `inFlightProcessing` | attention controller | attention itself | attention / targeted cancellation (**must carry workerId explicitly**) | ⚠️ only for targeted APIs that take a workerId |
|
|
41
|
+
| `session.summary` / fragments / slots | MemoryStore (singleton) | compactor | context assembly | ✅ allowed |
|
|
42
|
+
|
|
43
|
+
**In one sentence**: **per-worker things can never be obtained by "reading a global pointer"; they must be passed explicitly.**
|
|
44
|
+
The only session bridge that may be shared across threads is `dbSessionMap` (`cs_*` ↔ `sess_*`).
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 3. Hard rules
|
|
49
|
+
|
|
50
|
+
1. **DB ids and in-memory ids are never mixed**. `cs_*` is the request identity, `sess_*` is the internal cache key;
|
|
51
|
+
never use a `cs_*` directly as a `MemoryStore` key (that causes split-brain: one conversation splits into two stores).
|
|
52
|
+
2. **Passing session identity across threads must be explicit**. For the HTTP thread to hand a session to a worker,
|
|
53
|
+
it may only go through the mailbox item's `extra.sessionHint` (normalized from the legacy `extra.sessionId` /
|
|
54
|
+
`extra.sessionRestore`), never through any shared pointer.
|
|
55
|
+
3. **Session context is applied only in the workspace that handles that item**. "Eager restore" in the HTTP thread
|
|
56
|
+
is forbidden (it only writes `rootWorkspace`, which the worker never sees).
|
|
57
|
+
4. **Failures must be visible**. Distinguish `found | missing | notLoaded`: the latter two must at minimum `log.warn`
|
|
58
|
+
with `dbSessionId / memorySessionId / agentId`. "Not found → return empty / create new / swallow the exception" is forbidden.
|
|
59
|
+
5. **The binding may be written in exactly one place**: in the workspace that actually handles that message.
|
|
60
|
+
6. **Targeted operations must carry a workerId** (cancellation, status queries, hot updates); inferring it from ALS is not allowed.
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 4. Enforcement mechanisms already in place
|
|
65
|
+
|
|
66
|
+
| Mechanism | Location | What it protects |
|
|
67
|
+
|---|---|---|
|
|
68
|
+
| Streaming path carries the DB session id explicitly | `agent.ts` `sendMessageStream` → `extra.sessionHint` | rule R2 |
|
|
69
|
+
| Session resolution order "DB-bound in-memory session > workspace pointer > create new" | `resolveTurnSession` (single resolution point, called from `processMailboxItemCore`) | rule R1 |
|
|
70
|
+
| restore / binding executed in the workspace handling that item | `processMailboxItemCore` | rules R3/R5 |
|
|
71
|
+
| Lazy loading for history reads + warning on unknown id | `memory/store.ts` `getRecentMessages` | rule R4 |
|
|
72
|
+
| Invariant test suite | `packages/core/test/conversation-session-invariants.test.ts` | all of the above |
|
|
73
|
+
| Architecture gate | `scripts/architecture-guard.mjs` (must pass in CI) | bans `console.*`, bans empty `catch` |
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## 5. Checklist for adding/changing state
|
|
78
|
+
|
|
79
|
+
1. Does this state belong to **agent level** or is it **per-worker**? (per-worker ⇒ it must be passed explicitly)
|
|
80
|
+
2. Who writes it, who reads it, in which context? (fill it into the matrix in section 2 — **a blank cell is a risk**)
|
|
81
|
+
3. What happens when it can't be read? Does it silently degrade? (it must be observable)
|
|
82
|
+
4. Add an **invariant test** (not an assertion over an implementation snapshot), and do mutation validation (revert the fix → the case must go red).
|
|
83
|
+
5. Does it affect the `worker=1` serial-equivalence contract? (equivalence must hold)
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
# Streaming & Reattach
|
|
2
|
+
|
|
3
|
+
> Last updated: 2026-09
|
|
4
|
+
|
|
5
|
+
How Markus streams an agent turn to the browser over SSE, how a **client refresh or
|
|
6
|
+
navigation reattaches** to an in-flight generation without killing it, and how the agent
|
|
7
|
+
surfaces **structured lifecycle events** (including failures) to the client.
|
|
8
|
+
|
|
9
|
+
Related docs: [mailbox-system.md](./mailbox-system.md) (the attention loop and interrupt/
|
|
10
|
+
preempt semantics that a stream must honor), [tool-system.md](./tool-system.md) (tool
|
|
11
|
+
progress and tool-result events), [state-machines.md](./state-machines.md) (mailbox-item
|
|
12
|
+
terminal states, including "completed without marker").
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 1. Components
|
|
17
|
+
|
|
18
|
+
| Component | File | Responsibility |
|
|
19
|
+
|-----------|------|----------------|
|
|
20
|
+
| `SSEHandler` | [`org-manager/src/sse-handler.ts`](../../packages/org-manager/src/sse-handler.ts) | Owns one HTTP SSE response; drives `agent.sendMessageStream`; buffers + persists |
|
|
21
|
+
| `SSEBuffer` | `org-manager/src/sse-*` | Batches writes, heartbeats the connection |
|
|
22
|
+
| `ActiveStreamRegistry` / `ActiveStreamSession` | [`org-manager/src/active-stream-registry.ts`](../../packages/org-manager/src/active-stream-registry.ts) | Tracks in-flight generations for reattach; ring buffer + UI snapshot |
|
|
23
|
+
| `cancelToken` | in `SSEHandler` | `{ cancelled, userStopped }` — the single source of truth for stopping the agent |
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 2. Soft-Disconnect (refresh does not kill the agent)
|
|
28
|
+
|
|
29
|
+
When the SSE client disconnects (`SSEBuffer.onClose`) **before** completion:
|
|
30
|
+
|
|
31
|
+
1. `sseDisconnected = true`; partial output is persisted.
|
|
32
|
+
2. The agent is **not** cancelled — writers detach, the agent keeps running, and events
|
|
33
|
+
keep accumulating in the `ActiveStreamSession` ring buffer.
|
|
34
|
+
3. A **force-stop grace timer** (`SSE_DISCONNECT_FORCE_STOP_MS`) starts. If the turn is
|
|
35
|
+
still running when it fires and the user did not explicitly stop, the agent is
|
|
36
|
+
force-stopped (`cancelToken.cancelled = userStopped = true`, stream cancelled).
|
|
37
|
+
|
|
38
|
+
Only an explicit user **Stop** or the grace-timer force-stop sets `cancelToken`. This is
|
|
39
|
+
the key difference from naive SSE agents, which abort the model the moment the socket drops.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 3. Reattach
|
|
44
|
+
|
|
45
|
+
A generation is registered per `(agentId, sessionId)`. On reconnect the client calls the
|
|
46
|
+
reattach endpoint and `ActiveStreamSession.attach(res, afterSeq)` replays state:
|
|
47
|
+
|
|
48
|
+
1. Emit a `reattach` event (`streamId`, `lastSeq`, `status`, `hasSnapshot`).
|
|
49
|
+
2. If a **UI snapshot** exists and this is a full rebuild (`afterSeq <= 0`), emit a
|
|
50
|
+
`snapshot` event (authoritative `content` + tool `segments` + `thinking`) — this is the
|
|
51
|
+
correct prior UI even if the ring dropped early events.
|
|
52
|
+
3. Live-tail subsequent events; on terminal (`done` / `error`) end the response.
|
|
53
|
+
|
|
54
|
+
Finished streams are retained for `DONE_TTL_MS` (90s) so a late refresh still drains the
|
|
55
|
+
terminal event. Status probes treat `streaming | done(<TTL) | error(<TTL)` as attachable.
|
|
56
|
+
|
|
57
|
+
### 3.1 Ring buffer & the snapshot invariant
|
|
58
|
+
|
|
59
|
+
The ring is capped at `RING_CAP = 2500` events; older events are dropped. The UI snapshot
|
|
60
|
+
exists precisely so a reattach does not depend on the (lossy) ring.
|
|
61
|
+
|
|
62
|
+
- **Invariant**: after a reattach, the client's rendered state (text + tool cards) must be
|
|
63
|
+
reconstructable from `snapshot` + post-snapshot tail alone — never from ring replay of
|
|
64
|
+
early events (which may have been truncated).
|
|
65
|
+
- **Client contract**: a reattaching client **must** consume the `snapshot` event when
|
|
66
|
+
`hasSnapshot` is true and treat it as authoritative, rather than replaying only ring
|
|
67
|
+
deltas.
|
|
68
|
+
- **Testing** (`packages/org-manager/test/sse-buffer.test.ts` + registry tests): with a
|
|
69
|
+
ring overflow, reattach still yields complete tool/text UI via snapshot.
|
|
70
|
+
- **Status**: implemented (snapshot); the client-contract assertion is the durable guard.
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## 4. Structured Lifecycle Events
|
|
75
|
+
|
|
76
|
+
The stream currently emits: `session_start`, `reattach`, `snapshot`, `text_delta`,
|
|
77
|
+
tool progress events, and terminal `done` / `error`.
|
|
78
|
+
|
|
79
|
+
### 4.1 Spec: surface incomplete / tool failure (P0)
|
|
80
|
+
|
|
81
|
+
- **Behavior**: three currently near-silent conditions become **visible** structured
|
|
82
|
+
events (and activity-log entries), without changing retry semantics:
|
|
83
|
+
- a turn that produced nothing and exhausted its retries (or a user-interaction turn whose
|
|
84
|
+
reply was empty) → `incomplete`
|
|
85
|
+
(see [state-machines.md](./state-machines.md) mailbox-item terminal states),
|
|
86
|
+
- a tool returning a structured failure (`isToolErrorResult`) → `tool_error`,
|
|
87
|
+
- a `knowledge.md` write refused for exceeding its limits → surfaced (see
|
|
88
|
+
[memory-system.md](./memory-system.md) §8.8).
|
|
89
|
+
- **Invariants**:
|
|
90
|
+
- Each condition is surfaced without being mistaken for success.
|
|
91
|
+
- No **additional** retries are triggered by making these visible (visibility only).
|
|
92
|
+
- **Design rationale**: Hermes makes tool execution observable via callbacks; a failure or
|
|
93
|
+
an unfinished turn should never look like success to the user.
|
|
94
|
+
- **Testing** (`packages/core/test/attention.test.ts` "A3:", `packages/core/test/tool-result.test.ts`
|
|
95
|
+
"B1:", `packages/core/test/memory-store.test.ts` "B1:"): the incomplete event fires exactly
|
|
96
|
+
once with no extra retry; tool-error and memory-refusal classification are covered.
|
|
97
|
+
- **Status**: implemented, surfaced across layers (visibility only, no new retries):
|
|
98
|
+
- *incomplete* — `AttentionController.emitIncomplete` emits one `agent:incomplete` event on
|
|
99
|
+
the agent bus (empty-reply / max-retries terminals); see
|
|
100
|
+
[mailbox-system.md](./mailbox-system.md) and [state-machines.md](./state-machines.md).
|
|
101
|
+
- *tool failure* — the SSE handler marks the tool segment `status: 'error'` when
|
|
102
|
+
`event.success === false` and persists `success:false`, so a failed tool never renders as
|
|
103
|
+
a green result (`sse-handler.ts`).
|
|
104
|
+
- *MEMORY.md refusal* — `addLongTermMemory` returns `{ ok:false, reason }` and the memory
|
|
105
|
+
tools return a structured `{ status:'error', ok:false }` (recognized by
|
|
106
|
+
`isToolErrorResult`), see [memory-system.md](./memory-system.md).
|
|
107
|
+
- Remaining (roadmap): a *dedicated* SSE `incomplete` frame forwarded from the agent bus to
|
|
108
|
+
the client (today the bus event + activity log carry it; the streamed reply is still
|
|
109
|
+
delivered).
|
|
110
|
+
|
|
111
|
+
### 4.2 Spec: interruptible streaming (P1)
|
|
112
|
+
|
|
113
|
+
Streaming chat is human-facing and **non-preemptable by design** (a human is awaiting the
|
|
114
|
+
reply; see the `isPreemptable = scenario !== 'chat'` rule and `agent-loop.test.ts`). B3
|
|
115
|
+
narrows the gap without breaking that principle by distinguishing **revocation** from
|
|
116
|
+
**preemption** at the stream yield point:
|
|
117
|
+
|
|
118
|
+
- **Behavior**:
|
|
119
|
+
- **Explicit cancel** (the attention judge decides the new message *revokes* the work —
|
|
120
|
+
e.g. "stop / cancel that") → **abort the in-flight stream** via the `AbortController`
|
|
121
|
+
already threaded through `llmRouter.chatStream` and **drop** the item (`[cancelled]`).
|
|
122
|
+
- **Preempt** (a higher-priority item arrived, but the work is not revoked) → the interrupt
|
|
123
|
+
signal is **restored** so the higher-priority item runs immediately *after* the current
|
|
124
|
+
turn, rather than truncating the human's answer.
|
|
125
|
+
- The backstop-timeout path (A1 `cancelProcessing` → `cancelActiveStream`) also aborts an
|
|
126
|
+
in-flight stream, so a stuck stream is bounded.
|
|
127
|
+
- **Invariants**:
|
|
128
|
+
- An explicit cancel aborts the in-flight model call promptly and drops the item.
|
|
129
|
+
- A preempt never silently truncates a waiting human's reply; it is serviced next.
|
|
130
|
+
- Cancel/abort reuses the shared token/`AbortController` infrastructure (no new mechanism).
|
|
131
|
+
- **Design rationale**: Hermes favors interruptible API calls; Markus keeps human chat
|
|
132
|
+
responsive while still cutting work the user has explicitly revoked.
|
|
133
|
+
- **Testing** (`packages/core/test/agent-loop.test.ts`, `attention.test.ts`): the
|
|
134
|
+
chat-non-preemptable mapping is retained; A1's `cancelProcessing` aborts the active stream.
|
|
135
|
+
- **Status**: implemented (yield-point `cancel` → abort + `[cancelled]`; `preempt` → restore;
|
|
136
|
+
shared abort via `cancelActiveStream`).
|
|
137
|
+
|
|
138
|
+
### 4.3 Spec: directed cancel under concurrency (Scheme B)
|
|
139
|
+
|
|
140
|
+
Under concurrent processing ([concurrent-processing.md](./concurrent-processing.md)) a stop
|
|
141
|
+
request can no longer target "the agent" — several workers may have in-flight streams. The
|
|
142
|
+
cancel API is therefore **directed**:
|
|
143
|
+
|
|
144
|
+
- `cancelActiveStream(target?)` accepts `target = { itemId?, sessionId? }`.
|
|
145
|
+
- The HTTP/SSE caller has **no** `AsyncLocalStorage` context of its own, so it resolves the
|
|
146
|
+
owning worker via `AttentionController.findWorkerByItemId()` / `findWorkerBySessionId()`,
|
|
147
|
+
then runs the abort **inside that worker's workspace** via
|
|
148
|
+
`sessionWorkspaceStore.run(ws, () => cancelActiveStreamCore())`.
|
|
149
|
+
- Frontend **Stop** and **Retry** always pass a stable `sessionId` target, so stopping a
|
|
150
|
+
stream in one session tab never aborts another tab's in-flight turn.
|
|
151
|
+
|
|
152
|
+
- **Status**: implemented (`packages/core/test/attention-directed-cancel.test.ts`,
|
|
153
|
+
`agent-concurrent-activity.test.ts`). In serial mode `target` is optional and cancel falls
|
|
154
|
+
back to the instance-level stream token.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 5. Client-Side Streaming Resilience
|
|
159
|
+
|
|
160
|
+
How the **web frontend** consumes the stream and keeps a long-lived turn alive across
|
|
161
|
+
flaky networks. (Long-lived audit → distilled design contract, 2026-09.)
|
|
162
|
+
|
|
163
|
+
### 5.1 Consumption model
|
|
164
|
+
|
|
165
|
+
- The client consumes the SSE stream via **`fetch` + `ReadableStream`** (not `EventSource`) —
|
|
166
|
+
this is what allows structured lifecycle events and controlled reconnection.
|
|
167
|
+
- The server **must send a heartbeat frame every 15 s**; the client watchdog relies on it.
|
|
168
|
+
|
|
169
|
+
### 5.2 Watchdog & dead-loop prevention
|
|
170
|
+
|
|
171
|
+
- Client-side **idle watchdog default 60 s** (>4× the 15 s server heartbeat). If no bytes
|
|
172
|
+
arrive within the window, the client considers the stream stalled and tears down.
|
|
173
|
+
- Combined with poll fallback so a stalled stream never looks like an infinite spinner.
|
|
174
|
+
|
|
175
|
+
### 5.3 Reconnect & retry
|
|
176
|
+
|
|
177
|
+
- **Exponential backoff reconnect** for disconnect + **25 s reconnect heartbeat** +
|
|
178
|
+
`since`-incremental resume (replay only what was missed).
|
|
179
|
+
- **1.5 s reattach debounce** — bursts of navigation/refresh collapse into one reattach.
|
|
180
|
+
- `pollForReply` backoff: **2 s → 8 s, 5 attempts** before falling back to an explicit
|
|
181
|
+
stop/retry path. This bounds worst-case waiting without hammering the server.
|
|
182
|
+
|
|
183
|
+
### 5.4 Design invariants
|
|
184
|
+
|
|
185
|
+
- A client refresh or a brief network blip **never kills the agent turn** (see §2).
|
|
186
|
+
- Every long-lived request has a **bounded worst case** (watchdog + poll cap + backstop),
|
|
187
|
+
so no user-facing hang is unbounded.
|
|
188
|
+
- Reattach always recovers state from **snapshot + tail**, never from lossy ring replay (§3.1).
|
|
189
|
+
|
|
190
|
+
### 5.5 Remaining roadmap items
|
|
191
|
+
|
|
192
|
+
- Provider single-timer consolidation; fallback-failure alerting; visible stall indicator
|
|
193
|
+
in the chat UI (when to show "still working" vs "connection lost").
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
# Tool System
|
|
2
|
+
|
|
3
|
+
> Last updated: 2026-07
|
|
4
|
+
|
|
5
|
+
How Markus decides **which tools an agent can see**, how tool results are shaped and
|
|
6
|
+
returned, how the **tool-execution loop** drives the model until it is done, and how
|
|
7
|
+
**subagents** are spawned with budget guardrails.
|
|
8
|
+
|
|
9
|
+
Related docs: [agent-runtime.md](./agent-runtime.md) (SSOT for packs/budgets),
|
|
10
|
+
[prompt-engineering.md](./prompt-engineering.md) (how tool definitions and
|
|
11
|
+
results are packed into context), [mailbox-system.md](./mailbox-system.md) (the attention
|
|
12
|
+
loop that owns each turn), [streaming-and-reattach.md](./streaming-and-reattach.md) (how
|
|
13
|
+
tool progress and tool errors reach the client), [coding-tools.md](../guides/coding-tools.md)
|
|
14
|
+
(external coding CLIs, a distinct concern from the general tool loop).
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 1. Tool Selection
|
|
19
|
+
|
|
20
|
+
Not every registered tool is sent to the model on every call. Sending the full registry
|
|
21
|
+
would inflate the system/tool prefix (token tax) and dilute the model's attention. The
|
|
22
|
+
[`ToolSelector`](../../packages/core/src/tool-selector.ts) chooses a working set per call
|
|
23
|
+
**within a Scenario Capability Pack** ([agent-runtime.md](./agent-runtime.md) §2).
|
|
24
|
+
|
|
25
|
+
### 1.0 Spec: Scenario Capability Packs
|
|
26
|
+
|
|
27
|
+
MUST: Each scenario maps to exactly one pack: `reflex` | `converse` | `execute` | `govern`.
|
|
28
|
+
|
|
29
|
+
| Pack | Scenarios | `toolDefTokens` budget |
|
|
30
|
+
|------|-----------|------------------------|
|
|
31
|
+
| `reflex` | heartbeat, memory_consolidation, memory_flush, dream | 3_000 |
|
|
32
|
+
| `converse` | chat, a2a, group_chat, comment_response, requirement_action | 8_000 |
|
|
33
|
+
| `execute` | task_execution | 10_000 |
|
|
34
|
+
| `govern` | review, deliberation | 8_000 |
|
|
35
|
+
|
|
36
|
+
MUST: `reflex` default allowlist MUST be the slim core in AGENT-RUNTIME §2.2
|
|
37
|
+
(MUST NOT include `package_install`, `goal_*`, `spawn_subagent(s)`, `deliverable_create`, …).
|
|
38
|
+
|
|
39
|
+
MUST: Default `converse` MUST NOT include `spawn_subagents` or `deliverable_create`
|
|
40
|
+
(available via `discover_tools` only).
|
|
41
|
+
|
|
42
|
+
MUST: `execute` MUST include code/shell/coding capability groups.
|
|
43
|
+
|
|
44
|
+
Test IDs: `A-pack-reflex-tools`, `A-pack-converse-no-spawn`, `A-pack-execute-has-code`.
|
|
45
|
+
|
|
46
|
+
### 1.0.1 Spec: ToolDef budget eviction
|
|
47
|
+
|
|
48
|
+
MUST: Boot/create/restore MUST **register** skill/MCP/Feishu tools without `activateTools`.
|
|
49
|
+
LIVE schemas enter only via `discover_tools`. Sticky `recentToolNames` MUST NOT re-activate
|
|
50
|
+
skill/MCP namespaces.
|
|
51
|
+
|
|
52
|
+
MUST: After selection, if estimated tool-definition tokens exceed the pack budget, keep
|
|
53
|
+
`TOOL_DEF_CORE_KEEP` + `discover_tools` + HITL, then evict skill/MCP (LRU among activated)
|
|
54
|
+
and other extras until under budget.
|
|
55
|
+
|
|
56
|
+
MUST (§Afford.S2): Evicted names MUST appear in a compact catalog (in the volatile `[Live
|
|
57
|
+
context]` tail, keyed for rediscovery via `discover_tools`; name-only or name + ≤40 chars, total ≤
|
|
58
|
+
`DEFERRED_CATALOG_MAX_CHARS` ≈ 1500 chars).
|
|
59
|
+
|
|
60
|
+
MUST NOT: Append the eviction catalog into `discover_tools.description` (inflates
|
|
61
|
+
`toolDefTokens` and defeats the pack budget). This is enforced as a *cache*
|
|
62
|
+
invariant too: the description MUST be a pure function of the tool registry and
|
|
63
|
+
the skill catalog — never of the per-turn selection — because `tools` serialises
|
|
64
|
+
ahead of `system` + `messages`, so any per-turn drift there invalidates the whole
|
|
65
|
+
cached prefix. Regression guard:
|
|
66
|
+
`packages/core/test/tool-selector.test.ts` → `CACHE: discover_tools description is
|
|
67
|
+
byte-stable regardless of per-turn recentToolNames`.
|
|
68
|
+
|
|
69
|
+
MUST: Activated skill bodies inject as `## Activated Skills` (not under the converse
|
|
70
|
+
`dynamicContext` 800-char cap).
|
|
71
|
+
|
|
72
|
+
Test IDs: `A-tooldef-budget`, `A-tooldef-sticky-capped`, `S-catalog-not-in-tooldef`.
|
|
73
|
+
|
|
74
|
+
### 1.1 Selection inputs
|
|
75
|
+
|
|
76
|
+
`selectTools()` unions the following sources into the working set **for the active pack**:
|
|
77
|
+
|
|
78
|
+
| Source | What it adds | Notes |
|
|
79
|
+
|--------|--------------|-------|
|
|
80
|
+
| **Pack core** | Pack-specific always-on tools | Replaces unbounded global BASE for converse/reflex |
|
|
81
|
+
| **Role tools** | `isManager` / `isTaskExecution` / `isReview` within pack rules | e.g. execute unions `code` + `shell` + `coding` |
|
|
82
|
+
| **Keyword groups** (`TOOL_GROUPS`) | Accelerator when message matches | MUST respect toolDef budget |
|
|
83
|
+
| **Recent tools** (`recentToolNames`) | Session reactivation | Sticky but budget-capped |
|
|
84
|
+
| **`discover_tools`** | Always appended | Progressive disclosure entry point |
|
|
85
|
+
| **`notify_user` / `request_user_input`** | Always appended (non-dream) | Human communication + HITL |
|
|
86
|
+
|
|
87
|
+
### 1.2 Design rationale (Pi / Hermes)
|
|
88
|
+
|
|
89
|
+
- **Pi** ships ~4 default tools and leans on `bash` + progressive discovery, keeping the
|
|
90
|
+
tool tax near zero. **Hermes** registers a large registry (~70 tools) but keeps the
|
|
91
|
+
active toolset stable per session.
|
|
92
|
+
- Markus sits between: a small always-on core + on-demand discovery + keyword acceleration.
|
|
93
|
+
The core-plus-discover shape is the right one; the weakness is relying on **keyword
|
|
94
|
+
matching** as the *only* path to many groups.
|
|
95
|
+
|
|
96
|
+
### 1.3 Spec: core-always-on + discover (keyword as accelerator only)
|
|
97
|
+
|
|
98
|
+
- **Behavior**: A fixed **core tool set** is present on every call regardless of message
|
|
99
|
+
content. Long-tail tools are reachable via `discover_tools`. Keyword-group matching only
|
|
100
|
+
*accelerates* (pre-loads likely tools); it is never the sole gate for a core capability.
|
|
101
|
+
Session-aware reactivation (`recentToolNames`) is retained.
|
|
102
|
+
- **Invariants**:
|
|
103
|
+
- Core tools are present for *any* input, including empty, synthetic-continuation, and
|
|
104
|
+
short follow-up messages.
|
|
105
|
+
- A previously-used tool remains available for the rest of the session.
|
|
106
|
+
- `discover_tools` is always present.
|
|
107
|
+
- **Design rationale**: Fixes historical misses where a short follow-up or a
|
|
108
|
+
synthetic `[Continue…]` continuation message failed to re-match keywords and
|
|
109
|
+
dropped tools the turn actually needed (e.g. multimodal).
|
|
110
|
+
- **Testing** (`packages/core/test/tool-selector.test.ts` — the "B2:" cases):
|
|
111
|
+
- Core tools + `discover_tools` present for empty / whitespace / synthetic / short input,
|
|
112
|
+
and a missing message does not throw.
|
|
113
|
+
- Historical multimodal-continuation case keeps `generate_image` via `recentToolNames`.
|
|
114
|
+
- **Status**: implemented (base/core + `discover_tools` + `notify_user`/`request_user_input`
|
|
115
|
+
are added unconditionally; keyword matching is now explicitly an accelerator and a
|
|
116
|
+
blank/undefined message is handled safely).
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
## 2. Tool Result Envelope
|
|
121
|
+
|
|
122
|
+
Tool results are strings the model reads back as `tool` messages. A consistent envelope
|
|
123
|
+
lets the model, the tool loop (loop detection, error handling), and the activity UI agree
|
|
124
|
+
on success vs failure. Canonical helpers live in
|
|
125
|
+
[`tools/result.ts`](../../packages/core/src/tools/result.ts):
|
|
126
|
+
|
|
127
|
+
```
|
|
128
|
+
toolOk(data) → {"...data", "status":"success", "success":true}
|
|
129
|
+
toolErr(msg) → {"...extra", "status":"error", "error":"<msg>"}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`isToolErrorResult(result)` recognizes the failure conventions currently in use:
|
|
133
|
+
`status: 'error' | 'denied' | 'rejected'`, `success: false`, or a truthy top-level
|
|
134
|
+
`error` without `success: true`.
|
|
135
|
+
|
|
136
|
+
### 2.1 Spec: strict, uniform failure detection
|
|
137
|
+
|
|
138
|
+
- **Behavior**: `isToolErrorResult` must classify a genuine failure as an error even when
|
|
139
|
+
the tool returned a **non-JSON plain-text** error string (e.g. `"Error: ..."`), not only
|
|
140
|
+
structured JSON. New tools use `toolOk` / `toolErr`; legacy shapes remain recognized but
|
|
141
|
+
emit a one-time `warn` to drive migration.
|
|
142
|
+
- **Invariants**:
|
|
143
|
+
- Plain-text error strings are detected as failures (not silently treated as success).
|
|
144
|
+
- `{ success: true, error: null }` is still success (defensive).
|
|
145
|
+
- Canonical `toolOk` / `toolErr` round-trip correctly.
|
|
146
|
+
- **Design rationale**: A failure mis-read as success corrupts the loop detector and the
|
|
147
|
+
activity UI (shows a failed step as done). Mirrors Pi's "errors are values" discipline.
|
|
148
|
+
- **Testing** (`packages/core/test/tool-result.test.ts` — "B1: recognises non-JSON
|
|
149
|
+
plain-text errors" / "…does not misclassify ordinary plain text"):
|
|
150
|
+
- Plain-text errors (`Error:`, `Failed…`, `TypeError:`, `Traceback…`, `Cannot…`,
|
|
151
|
+
`Unable to…`, `Fatal…`) → `isToolErrorResult === true`.
|
|
152
|
+
- Ordinary prose (including mid-sentence "error") and success strings → `false`.
|
|
153
|
+
- Legacy `{error}` / `{success:false}` still detected.
|
|
154
|
+
- **Status**: implemented (anchored `PLAIN_TEXT_ERROR_RE` fallback in
|
|
155
|
+
`isToolErrorResult`).
|
|
156
|
+
|
|
157
|
+
### 2.2 Large tool-result offload
|
|
158
|
+
|
|
159
|
+
Results larger than `TOOL_RESULT_OFFLOAD_CHARS` (12,000 chars) are written to
|
|
160
|
+
`{dataDir}/tool-outputs/…` and replaced with a **preview + file path** so the model can
|
|
161
|
+
`file_read` the rest in chunks (browser snapshots get a larger 30k preview;
|
|
162
|
+
`file_read` output is exempt to avoid an offload loop). See
|
|
163
|
+
[`Agent.offloadLargeResult`](../../packages/core/src/agent.ts).
|
|
164
|
+
|
|
165
|
+
- **Spec**: The offload replacement is a clearly-marked, machine-recognizable envelope
|
|
166
|
+
carrying the full-content **path**, so downstream summarization never drops the pointer.
|
|
167
|
+
When a tool cannot complete because output was offloaded/omitted, it returns an explicit
|
|
168
|
+
`{ ok:false, path, reason }`-style result rather than an optimistic success.
|
|
169
|
+
- **Testing** (`packages/core/test/memory-store.test.ts` — "addLongTermMemory result (B1)"):
|
|
170
|
+
a normal `MEMORY.md` write returns `{ ok: true }`; an over-cap write is refused with
|
|
171
|
+
`{ ok: false, reason }`, and the `memory_update` / `memory_update_longterm` tools return a
|
|
172
|
+
structured `status:'error', ok:false` result (recognized by `isToolErrorResult`). Offload
|
|
173
|
+
returns a result containing the file path.
|
|
174
|
+
- **Status**: implemented for the MEMORY.md refusal path (`MemoryStore.addLongTermMemory`
|
|
175
|
+
now returns a structured result surfaced by the memory tools). Offload envelope with path
|
|
176
|
+
is unchanged (already machine-recognizable).
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
## 3. Tool-Execution Loop
|
|
181
|
+
|
|
182
|
+
A "turn" runs the model, executes any tool calls it emits, appends the results, and calls
|
|
183
|
+
the model again — until the model stops requesting tools (or a safety cap is hit). Markus
|
|
184
|
+
runs this loop in several entry points in [`agent.ts`](../../packages/core/src/agent.ts):
|
|
185
|
+
streaming chat (`handleMessageStream`), non-streaming chat (`handleMessage`), task
|
|
186
|
+
execution (`executeTask` / `executeTaskConcurrent`), and respond-in-session
|
|
187
|
+
(`respondInSession`). (The old completion-marker continuation path — `ensureCompletionMarker` —
|
|
188
|
+
was removed with the retire of the text protocol; completion is now the typed `end_turn` signal.)
|
|
189
|
+
|
|
190
|
+
Shared safety behavior across paths:
|
|
191
|
+
|
|
192
|
+
- **Iteration cap** `DEFAULT_MAX_TOOL_ITERATIONS = 200` (task execution is uncapped by
|
|
193
|
+
design; heartbeat runs with smaller caps).
|
|
194
|
+
- **Tool arg casing aliases** so snake_case vs camelCase never causes an infinite retry.
|
|
195
|
+
- **Loop detection** to break repeated identical tool calls.
|
|
196
|
+
- **`max_tokens` continuation** via a synthetic `[Continue…]` user message.
|
|
197
|
+
- **Parallel tool execution** on the streaming path; interrupt-aware sequential execution
|
|
198
|
+
where preemption matters.
|
|
199
|
+
|
|
200
|
+
### 3.1 Spec: shared turn helper (incremental consolidation)
|
|
201
|
+
|
|
202
|
+
- **Behavior**: The common sub-steps of the loop — tool execution, error classification
|
|
203
|
+
(`isToolErrorResult`), loop termination, and the `max_tokens` continuation
|
|
204
|
+
decision — are extracted into shared helpers invoked by all paths, so behavior does not
|
|
205
|
+
diverge between entry points. This is an **incremental** consolidation, not a rewrite of
|
|
206
|
+
the ~7k-line file. The first extraction covers the two loop-control decisions that were
|
|
207
|
+
copy-pasted at every loop site: `shouldContinueToolLoop(response)` (keep iterating
|
|
208
|
+
while the model still wants tools or was cut off by `max_tokens`) and
|
|
209
|
+
`needsMaxTokensContinuation(response)` (a `max_tokens` cutoff without tool calls needs a
|
|
210
|
+
"continue" nudge). Error classification (`isToolErrorResult`) was already shared, and loop
|
|
211
|
+
termination now reads the typed `end_turn` signal (`endTurnRequested`) instead of a text
|
|
212
|
+
completion marker — see [mailbox-system.md](./mailbox-system.md) "Completion protocol".
|
|
213
|
+
- **Invariants**: all paths produce identical decisions for the same
|
|
214
|
+
(tool result, finishReason, `end_turn`) inputs; existing loop/casing/`max_tokens` behavior is
|
|
215
|
+
preserved (regression-guarded by the agent-loop tests). The helpers are pure and always
|
|
216
|
+
return a `boolean` (never a truthy `toolCalls.length`).
|
|
217
|
+
- **Design rationale**: aligns with Pi's `pi-agent-core` and Hermes's single
|
|
218
|
+
`conversation_loop` — one authoritative loop, many entry points.
|
|
219
|
+
- **Testing** (`packages/core/test/agent-loop.test.ts` — the "B5:" cases): unit tests for
|
|
220
|
+
`shouldContinueToolLoop` / `needsMaxTokensContinuation`; the full loop suites
|
|
221
|
+
(`agent-loop`, `agent-core`, `agent-extended`) run green as an equivalence guard.
|
|
222
|
+
- **Status**: implemented (pure `shouldContinueToolLoop` / `needsMaxTokensContinuation`
|
|
223
|
+
exported from `agent.ts`, wired at all five loop sites). Further sub-step extraction
|
|
224
|
+
(unified tool-execution/error-append) remains incremental future work.
|
|
225
|
+
|
|
226
|
+
---
|
|
227
|
+
|
|
228
|
+
## 4. Subagents
|
|
229
|
+
|
|
230
|
+
`spawn_subagent` and `spawn_subagents` run focused child agents with a **fresh, isolated
|
|
231
|
+
message history** that inherits the parent's tools and returns synchronously as a
|
|
232
|
+
`tool_result`. See [`tools/subagent.ts`](../../packages/core/src/tools/subagent.ts).
|
|
233
|
+
|
|
234
|
+
Current guardrails:
|
|
235
|
+
|
|
236
|
+
- `SUBAGENT_MAX_PARALLEL = 10` caps concurrent children per `spawn_subagents` call.
|
|
237
|
+
- Each child has its own `maxIterations` (defaults to the parent's tool-iteration cap; the
|
|
238
|
+
hard default is otherwise unbounded).
|
|
239
|
+
|
|
240
|
+
### 4.1 Design rationale (Hermes)
|
|
241
|
+
|
|
242
|
+
Hermes treats subagents as **processes**: independent iteration budgets, and it documents
|
|
243
|
+
that parent + child total iterations can exceed the parent cap — but bounds delegation with
|
|
244
|
+
`delegation.max_iterations`. Markus has per-child caps and a parallel-count cap but **no
|
|
245
|
+
aggregate budget** across a fan-out.
|
|
246
|
+
|
|
247
|
+
### 4.2 Spec: aggregate fan-out budget
|
|
248
|
+
|
|
249
|
+
- **Behavior**: A `spawn_subagents` fan-out enforces an **aggregate** iteration/cost ceiling
|
|
250
|
+
across all children (in addition to per-child caps and `SUBAGENT_MAX_PARALLEL`). Exceeding
|
|
251
|
+
it returns a structured error result rather than launching unbounded work.
|
|
252
|
+
- **Invariants**:
|
|
253
|
+
- Total child iterations/cost for one fan-out cannot exceed the aggregate ceiling.
|
|
254
|
+
- Under the ceiling, parallel execution behaves as today.
|
|
255
|
+
- Over the ceiling, the tool returns `{ status:'error', … }` (recognized by
|
|
256
|
+
`isToolErrorResult`).
|
|
257
|
+
- **Design rationale**: 10 parallel children × a large per-child cap can silently multiply
|
|
258
|
+
CU/token spend; an explicit aggregate budget makes the cost bounded and observable.
|
|
259
|
+
- **Testing** (`packages/core/test/subagent-tools.test.ts` — the "B4:" cases):
|
|
260
|
+
`runSubagentLoop` with a shared budget stops after exactly `remaining` iterations and marks
|
|
261
|
+
its result; `spawn_subagents` with looping children returns `budgetExceeded: true` and the
|
|
262
|
+
aggregate ceiling.
|
|
263
|
+
- **Status**: implemented (`SUBAGENT_MAX_AGGREGATE_ITERATIONS`; a `sharedBudget` threaded
|
|
264
|
+
through `runSubagentLoop`, created per fan-out in `spawn_subagents`, surfaced as
|
|
265
|
+
`budgetExceeded` in the aggregate result and an inline note in each truncated child).
|
|
266
|
+
Per-child `maxIterations` and `SUBAGENT_MAX_PARALLEL` still apply.
|