deepclause-sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/README.md +57 -0
  2. package/dist/agent.d.ts +2 -0
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +5 -0
  5. package/dist/agent.js.map +1 -1
  6. package/dist/cli/agent-inbox.d.ts +25 -0
  7. package/dist/cli/agent-inbox.d.ts.map +1 -0
  8. package/dist/cli/agent-inbox.js +46 -0
  9. package/dist/cli/agent-inbox.js.map +1 -0
  10. package/dist/cli/config.d.ts +28 -28
  11. package/dist/cli/index.d.ts +1 -1
  12. package/dist/cli/index.js +7 -2
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/cli/repl.d.ts +7 -0
  15. package/dist/cli/repl.d.ts.map +1 -1
  16. package/dist/cli/repl.js +181 -13
  17. package/dist/cli/repl.js.map +1 -1
  18. package/dist/cli/run.d.ts +1 -0
  19. package/dist/cli/run.d.ts.map +1 -1
  20. package/dist/cli/run.js +3 -1
  21. package/dist/cli/run.js.map +1 -1
  22. package/dist/cli/serve.d.ts +3 -0
  23. package/dist/cli/serve.d.ts.map +1 -0
  24. package/dist/cli/serve.js +131 -0
  25. package/dist/cli/serve.js.map +1 -0
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/judge/llm.d.ts.map +1 -1
  30. package/dist/judge/llm.js +9 -4
  31. package/dist/judge/llm.js.map +1 -1
  32. package/dist/judge/types.d.ts +10 -0
  33. package/dist/judge/types.d.ts.map +1 -1
  34. package/dist/judge/types.js.map +1 -1
  35. package/dist/prolog-src/deepclause_mi.pl +370 -54
  36. package/dist/repl/agent-inbox.d.ts +73 -0
  37. package/dist/repl/agent-inbox.d.ts.map +1 -0
  38. package/dist/repl/agent-inbox.js +168 -0
  39. package/dist/repl/agent-inbox.js.map +1 -0
  40. package/dist/repl/agent.d.ts +14 -1
  41. package/dist/repl/agent.d.ts.map +1 -1
  42. package/dist/repl/agent.js +25 -6
  43. package/dist/repl/agent.js.map +1 -1
  44. package/dist/repl/backend.d.ts +6 -0
  45. package/dist/repl/backend.d.ts.map +1 -1
  46. package/dist/repl/backend.js +17 -2
  47. package/dist/repl/backend.js.map +1 -1
  48. package/dist/repl/event-history.d.ts.map +1 -1
  49. package/dist/repl/event-history.js +3 -0
  50. package/dist/repl/event-history.js.map +1 -1
  51. package/dist/repl/harness-tools.d.ts +9 -2
  52. package/dist/repl/harness-tools.d.ts.map +1 -1
  53. package/dist/repl/harness-tools.js +38 -14
  54. package/dist/repl/harness-tools.js.map +1 -1
  55. package/dist/repl/history.d.ts +14 -3
  56. package/dist/repl/history.d.ts.map +1 -1
  57. package/dist/repl/history.js +62 -5
  58. package/dist/repl/history.js.map +1 -1
  59. package/dist/repl/index.d.ts +11 -0
  60. package/dist/repl/index.d.ts.map +1 -1
  61. package/dist/repl/index.js +6 -2
  62. package/dist/repl/index.js.map +1 -1
  63. package/dist/repl/process-backend.d.ts +1 -0
  64. package/dist/repl/process-backend.d.ts.map +1 -1
  65. package/dist/repl/process-executor.d.ts +4 -0
  66. package/dist/repl/process-executor.d.ts.map +1 -1
  67. package/dist/repl/process-executor.js +36 -1
  68. package/dist/repl/process-executor.js.map +1 -1
  69. package/dist/repl/process-worker.d.ts.map +1 -1
  70. package/dist/repl/process-worker.js +33 -8
  71. package/dist/repl/process-worker.js.map +1 -1
  72. package/dist/repl/processes.d.ts +14 -1
  73. package/dist/repl/processes.d.ts.map +1 -1
  74. package/dist/repl/processes.js +8 -2
  75. package/dist/repl/processes.js.map +1 -1
  76. package/dist/repl/reference.d.ts.map +1 -1
  77. package/dist/repl/reference.js +4 -3
  78. package/dist/repl/reference.js.map +1 -1
  79. package/dist/repl/render.d.ts.map +1 -1
  80. package/dist/repl/render.js +13 -0
  81. package/dist/repl/render.js.map +1 -1
  82. package/dist/repl/session.d.ts +72 -5
  83. package/dist/repl/session.d.ts.map +1 -1
  84. package/dist/repl/session.js +595 -42
  85. package/dist/repl/session.js.map +1 -1
  86. package/dist/repl/toolset.d.ts +8 -0
  87. package/dist/repl/toolset.d.ts.map +1 -1
  88. package/dist/repl/toolset.js +53 -4
  89. package/dist/repl/toolset.js.map +1 -1
  90. package/dist/repl/tui/renderer.d.ts.map +1 -1
  91. package/dist/repl/tui/renderer.js +3 -1
  92. package/dist/repl/tui/renderer.js.map +1 -1
  93. package/dist/repl/work-hooks.d.ts +29 -0
  94. package/dist/repl/work-hooks.d.ts.map +1 -0
  95. package/dist/repl/work-hooks.js +117 -0
  96. package/dist/repl/work-hooks.js.map +1 -0
  97. package/dist/repl/worker-host.d.ts +2 -0
  98. package/dist/repl/worker-host.d.ts.map +1 -1
  99. package/dist/repl/worker-host.js +48 -4
  100. package/dist/repl/worker-host.js.map +1 -1
  101. package/dist/repl/worker-protocol.d.ts +23 -2
  102. package/dist/repl/worker-protocol.d.ts.map +1 -1
  103. package/dist/repl/worker-protocol.js +1 -1
  104. package/dist/runner.d.ts +2 -2
  105. package/dist/runner.d.ts.map +1 -1
  106. package/dist/runner.js +19 -3
  107. package/dist/runner.js.map +1 -1
  108. package/dist/runtime-identity.json +6 -6
  109. package/dist/serve/agent-broadcast.d.ts +29 -0
  110. package/dist/serve/agent-broadcast.d.ts.map +1 -0
  111. package/dist/serve/agent-broadcast.js +28 -0
  112. package/dist/serve/agent-broadcast.js.map +1 -0
  113. package/dist/serve/agent-preferences.d.ts +16 -0
  114. package/dist/serve/agent-preferences.d.ts.map +1 -0
  115. package/dist/serve/agent-preferences.js +42 -0
  116. package/dist/serve/agent-preferences.js.map +1 -0
  117. package/dist/serve/api-docs.d.ts +61 -0
  118. package/dist/serve/api-docs.d.ts.map +1 -0
  119. package/dist/serve/api-docs.js +122 -0
  120. package/dist/serve/api-docs.js.map +1 -0
  121. package/dist/serve/backend.d.ts +12 -0
  122. package/dist/serve/backend.d.ts.map +1 -0
  123. package/dist/serve/backend.js +52 -0
  124. package/dist/serve/backend.js.map +1 -0
  125. package/dist/serve/capabilities.d.ts +6 -0
  126. package/dist/serve/capabilities.d.ts.map +1 -0
  127. package/dist/serve/capabilities.js +21 -0
  128. package/dist/serve/capabilities.js.map +1 -0
  129. package/dist/serve/example-agent.d.ts +5 -0
  130. package/dist/serve/example-agent.d.ts.map +1 -0
  131. package/dist/serve/example-agent.js +5 -0
  132. package/dist/serve/example-agent.js.map +1 -0
  133. package/dist/serve/files.d.ts +55 -0
  134. package/dist/serve/files.d.ts.map +1 -0
  135. package/dist/serve/files.js +249 -0
  136. package/dist/serve/files.js.map +1 -0
  137. package/dist/serve/harness.d.ts +3 -0
  138. package/dist/serve/harness.d.ts.map +1 -0
  139. package/dist/serve/harness.js +53 -0
  140. package/dist/serve/harness.js.map +1 -0
  141. package/dist/serve/previews.d.ts +40 -0
  142. package/dist/serve/previews.d.ts.map +1 -0
  143. package/dist/serve/previews.js +240 -0
  144. package/dist/serve/previews.js.map +1 -0
  145. package/dist/serve/protocol.d.ts +228 -0
  146. package/dist/serve/protocol.d.ts.map +1 -0
  147. package/dist/serve/protocol.js +2 -0
  148. package/dist/serve/protocol.js.map +1 -0
  149. package/dist/serve/schedules.d.ts +85 -0
  150. package/dist/serve/schedules.d.ts.map +1 -0
  151. package/dist/serve/schedules.js +249 -0
  152. package/dist/serve/schedules.js.map +1 -0
  153. package/dist/serve/server.d.ts +50 -0
  154. package/dist/serve/server.d.ts.map +1 -0
  155. package/dist/serve/server.js +1696 -0
  156. package/dist/serve/server.js.map +1 -0
  157. package/dist/serve/session-worker.d.ts +2 -0
  158. package/dist/serve/session-worker.d.ts.map +1 -0
  159. package/dist/serve/session-worker.js +291 -0
  160. package/dist/serve/session-worker.js.map +1 -0
  161. package/dist/serve/sessions.d.ts +178 -0
  162. package/dist/serve/sessions.d.ts.map +1 -0
  163. package/dist/serve/sessions.js +905 -0
  164. package/dist/serve/sessions.js.map +1 -0
  165. package/dist/serve/storage.d.ts +41 -0
  166. package/dist/serve/storage.d.ts.map +1 -0
  167. package/dist/serve/storage.js +211 -0
  168. package/dist/serve/storage.js.map +1 -0
  169. package/dist/serve/ui/api-docs.html +17 -0
  170. package/dist/serve/ui/api-docs.js +36 -0
  171. package/dist/serve/ui/app.js +958 -0
  172. package/dist/serve/ui/authoring.js +92 -0
  173. package/dist/serve/ui/deepclause-logo.png +0 -0
  174. package/dist/serve/ui/deepclause-mark.svg +1 -0
  175. package/dist/serve/ui/diff.js +16 -0
  176. package/dist/serve/ui/dompurify-LICENSE.txt +202 -0
  177. package/dist/serve/ui/features.css +15 -0
  178. package/dist/serve/ui/files.js +13 -0
  179. package/dist/serve/ui/ibm-plex-mono-latin.woff2 +0 -0
  180. package/dist/serve/ui/ibmplexmono-OFL.txt +93 -0
  181. package/dist/serve/ui/icons.js +30 -0
  182. package/dist/serve/ui/index.html +68 -0
  183. package/dist/serve/ui/manrope-OFL.txt +93 -0
  184. package/dist/serve/ui/manrope-latin.woff2 +0 -0
  185. package/dist/serve/ui/markdown.js +38 -0
  186. package/dist/serve/ui/marked-LICENSE.txt +44 -0
  187. package/dist/serve/ui/marked.js +88 -0
  188. package/dist/serve/ui/purify.js +2454 -0
  189. package/dist/serve/ui/style.css +249 -0
  190. package/dist/serve/ui/web-work.css +247 -0
  191. package/dist/serve/ui/web.css +1848 -0
  192. package/dist/serve/workflow-bundles.d.ts +8 -0
  193. package/dist/serve/workflow-bundles.d.ts.map +1 -0
  194. package/dist/serve/workflow-bundles.js +78 -0
  195. package/dist/serve/workflow-bundles.js.map +1 -0
  196. package/dist/serve/workflow-calls.d.ts +6 -0
  197. package/dist/serve/workflow-calls.d.ts.map +1 -0
  198. package/dist/serve/workflow-calls.js +13 -0
  199. package/dist/serve/workflow-calls.js.map +1 -0
  200. package/dist/serve/workflows.d.ts +93 -0
  201. package/dist/serve/workflows.d.ts.map +1 -0
  202. package/dist/serve/workflows.js +219 -0
  203. package/dist/serve/workflows.js.map +1 -0
  204. package/dist/system/assets/docs/AGENT_PROMPT.md +6 -6
  205. package/dist/system/assets/docs/DML_AUTHORING.md +80 -2
  206. package/dist/system/assets/docs/DML_PROCESSES.md +24 -0
  207. package/dist/system/assets/docs/DML_REFERENCE.md +98 -10
  208. package/dist/system/assets/docs/DML_SHELL.md +149 -7
  209. package/dist/system/assets/docs/DML_TASKS.md +10 -3
  210. package/dist/system/assets/docs/LOCAL_AGENT_PROMPT.md +6 -6
  211. package/dist/system/environment.d.ts +5 -1
  212. package/dist/system/environment.d.ts.map +1 -1
  213. package/dist/system/environment.js +14 -8
  214. package/dist/system/environment.js.map +1 -1
  215. package/dist/system/runtime/agentvm-manager.d.ts +12 -1
  216. package/dist/system/runtime/agentvm-manager.d.ts.map +1 -1
  217. package/dist/system/runtime/agentvm-manager.js +136 -20
  218. package/dist/system/runtime/agentvm-manager.js.map +1 -1
  219. package/dist/system/runtime/shell-manager.d.ts +3 -0
  220. package/dist/system/runtime/shell-manager.d.ts.map +1 -1
  221. package/dist/system/runtime/shell-manager.js +1 -1
  222. package/dist/system/runtime/shell-manager.js.map +1 -1
  223. package/dist/system/timezone.d.ts +20 -0
  224. package/dist/system/timezone.d.ts.map +1 -0
  225. package/dist/system/timezone.js +37 -0
  226. package/dist/system/timezone.js.map +1 -0
  227. package/dist/types.d.ts +37 -1
  228. package/dist/types.d.ts.map +1 -1
  229. package/dist/work/index.d.ts +13 -3
  230. package/dist/work/index.d.ts.map +1 -1
  231. package/dist/work/index.js +80 -15
  232. package/dist/work/index.js.map +1 -1
  233. package/docs/DEEP_RESEARCH_EXAMPLE.md +127 -0
  234. package/docs/SERVE.md +664 -0
  235. package/docs/WORK_AGENT_HOOKS_PLAN.md +416 -0
  236. package/docs/WORK_AGENT_INBOX.md +140 -0
  237. package/docs/WORK_AGENT_INBOX_PLAN.md +91 -0
  238. package/docs/WORK_MODE.md +269 -0
  239. package/package.json +24 -2
  240. package/sdk-examples/deep-research.dml +144 -0
  241. package/sdk-examples/deep-research.py +502 -0
  242. package/sdk-examples/hooked-agent.dml +49 -0
  243. package/sdk-examples/subagent-inbox.dml +66 -0
  244. package/src/prolog-src/deepclause_mi.pl +370 -54
@@ -0,0 +1,416 @@
1
+ # Work agent DML hooks — implementation plan
2
+
3
+ Status: **phases A/B implemented locally** on `feat/work-agent-hooks`: `on_start`
4
+ and `on_message`, state/lifecycle persistence, and mutable effective DML memory.
5
+ Tool/result/response hooks (phases C/D) remain proposed and are rejected if declared.
6
+ Hooks were introduced in Work contract 2; the current contract is version 3
7
+ (inboxes and process-only consume). See `docs/WORK_MODE.md` and
8
+ `sdk-examples/hooked-agent.dml` for the implemented surface.
9
+
10
+ Baseline: local `main`, after merge `07005b3` of `feat/serve-work-http`
11
+ (including conversation restoration, separate workflow runs, and AgentVM fixes).
12
+
13
+ ## 1. Goal and core decisions
14
+
15
+ Keep `shell/1` with `kind: agent` and the existing SDK conversation lifecycle,
16
+ but let explicitly declared DML hooks control selected agent decisions. Do not
17
+ introduce `kind: agent(Predicate)`, infer `agent_main/0`, or keep an indefinitely
18
+ running DML input loop alive.
19
+
20
+ **Hooks must be able to change the agent's model-facing messages through normal
21
+ DML memory operations such as `system/1` and `user/1`.** Running a predicate with
22
+ a read-only copy of history is insufficient. Successful hook memory changes must
23
+ be visible both to subsequent calls inside that hook and to the outer Work agent.
24
+
25
+ Other decisions:
26
+
27
+ - No hooks means unchanged behavior and no extra model calls.
28
+ - Hooks are host-invoked DML predicates, not tools offered to the model.
29
+ - A message hook can answer directly, bypassing the default assistant entirely.
30
+ - Optional explicit application state is threaded through hook arguments, separate
31
+ from conversation memory. No second agent/session owner or database is added.
32
+ - Work restrictions, host approvals, sandbox selection, cancellation, streaming,
33
+ usage accounting, and snapshot compatibility continue to apply.
34
+ - Implement the reusable behavior in the SDK, not separately in serve, TUI, and web.
35
+
36
+ ## 2. Proposed declaration and predicate contract
37
+
38
+ Add an optional `hooks` dictionary to an agent shell. Keys name lifecycle events;
39
+ values name backing predicates, e.g. `on_message: "route_message"`. Preserve the
40
+ existing `system`, `welcome`, `tools`, `host_tools`, and `workflows` fields.
41
+
42
+ Use one signature for every hook:
43
+
44
+ `Hook(Context, StateIn, StateOut, Decision)`
45
+
46
+ `Context` is a versioned tagged DML dict containing the event-specific data and
47
+ read-only session/turn identifiers. Active message memory is supplied through the
48
+ DML frame, not a second mutable `Context.messages` copy. Hooks inspect it with
49
+ `get_memory/1` and modify it through the normal memory predicates.
50
+
51
+ Initial state is an empty tagged dict (`state{}`). Without `on_start`, that remains
52
+ the initial application state. A hook that does not need state returns it unchanged.
53
+
54
+ | Hook | When it runs | Valid decisions |
55
+ | --- | --- | --- |
56
+ | `on_start` | Once, on the first user turn of a new logical agent conversation | `continue` |
57
+ | `on_message` | After staging a user message, before default assistant execution | `continue`, `reply(Text)`, `reject(Reason)` |
58
+ | `on_tool_call` | Before an actual top-level Work assistant tool invocation | `allow`, `deny(Reason)` |
59
+ | `on_tool_result` | After recording an actual tool result, before the next model call | `continue` |
60
+ | `on_response` | Before publishing the final assistant response | `continue`, `reply(Text)` |
61
+
62
+ Start with the first two hooks; tool and response hooks are later phases below.
63
+ Unknown hook keys are validation errors, not silently ignored extension points.
64
+ Use the canonical spelling `on_tool_call`, not several equivalent aliases.
65
+
66
+ Validate names, arity 4, existence in the pinned harness, and one predicate per
67
+ hook key. Reject closures, executable query strings, unknown decisions, unbound
68
+ results, and hooks on workflow-only shells. Declaration parsing, normalization,
69
+ rendering, editing, export, and restore must preserve hooks losslessly.
70
+
71
+ ## 3. Message semantics: one effective context, preserved provenance
72
+
73
+ ### 3.1 Separate the transcript from effective model context
74
+
75
+ The original user submissions, actual tool execution records, and published
76
+ assistant replies remain the truthful session transcript. Hook-authored context
77
+ must not impersonate an additional human submission or silently rewrite that audit
78
+ record. Maintain provenance and stable identity for context entries:
79
+
80
+ - Original user/assistant transcript entries.
81
+ - Harness-authored memory entries, including `system/1` and `user/1` additions.
82
+ - Internal hook task memory, distinct from a public assistant response.
83
+ - Structured provider/tool protocol records, preserved without lossy conversion.
84
+
85
+ The effective context may differ from the original transcript. Both must restore
86
+ coherently; the event journal remains a presentation/execution record, not the
87
+ sole source of truth for model memory. Do not create independent competing Work
88
+ and hook conversation stores that drift after a turn.
89
+
90
+ ### 3.2 Execute hooks against staged effective memory
91
+
92
+ 1. Stage the incoming user message exactly once in effective conversation memory.
93
+ 2. Seed a dedicated foreground hook frame from that memory.
94
+ 3. Run the declared hook with the current explicit application state.
95
+ 4. Collect the successful frame's resulting memory and validated outputs.
96
+ 5. Commit the memory/state transition at the documented boundary, then act on the
97
+ decision. The next outer model call must use the committed effective memory.
98
+
99
+ The bridge must not leave changes solely in the existing DML `harness` memory
100
+ slot while `HarnessAgent.messages` continues using an old copy. Likewise, do not
101
+ permanently overwrite unrelated manual-workflow memory as a side effect of
102
+ preparing a disposable hook frame.
103
+
104
+ ### 3.3 Preserve existing DML memory meanings
105
+
106
+ - `system(Text)` appends harness-authored system context. It does not replace all
107
+ previous system messages or modify the immutable host policy.
108
+ - `user(Text)` appends harness-authored user-role context. It does not generate
109
+ another visible human turn or recursively invoke `on_message`.
110
+ - `get_memory/1` reads the hook's current logical memory, including earlier
111
+ successful changes in that frame.
112
+ - Memory-bearing `task/N` sees that memory; its accumulated memory is subject to
113
+ the same successful-hook commit. Internal task text is not automatically a
114
+ public assistant reply.
115
+ - Isolated `prompt/N` and `with_fresh_memory/1` retain their existing isolation and
116
+ do not leak their scratch memory back to the Work agent.
117
+ - `clear_memory` clears the hook-editable effective context, not the session
118
+ journal or protected host instructions. A hook may use it followed by `system/1`
119
+ and `user/1` to deliberately rebuild the text context for subsequent requests.
120
+ - `with_model/2` and `with_tools/2` remain scoped to the enclosed DML computation;
121
+ they do not permanently change the outer agent's model or tool grants.
122
+
123
+ Split the existing combined Work prompt into a protected host policy/environment
124
+ layer and an initially seeded, hook-editable harness/persona layer. Shell-authored
125
+ `system` content belongs to the latter. Policy enforcement is still in host code;
126
+ no arrangement of system messages can bypass tool registration or approval.
127
+
128
+ ### 3.4 Protect structured model protocol
129
+
130
+ `LLMBackendMessage` contains tool IDs, media references, and opaque provider data
131
+ that `MemoryMessage` and `HarnessAgent.getMessages()` do not retain. Do **not**
132
+ flatten the entire live provider conversation through those text-only APIs and
133
+ then rebuild it after a hook.
134
+
135
+ Use a lossless context bridge with host-owned identities/opaque segments. DML
136
+ gets a documented text projection for opaque provider/tool groups, not writable
137
+ provider blobs or credentials. Memory edits affect editable entries; any removal
138
+ of completed protocol context must omit whole eligible groups, never leave an
139
+ orphan tool result or mutate a signed/native provider object in place. An active
140
+ assistant tool-call batch and its required results remain protected until closed,
141
+ even if a tool hook calls `clear_memory`.
142
+
143
+ Prototype this bridge before implementing later hooks. If a provider record
144
+ cannot safely be transformed, preserve its opaque group and report unsupported
145
+ edits rather than silently corrupting the request. Exercise multi-system-message
146
+ normalization and media handling through the actual backend adapters. Model or
147
+ provider switching must use the current adapter's compatibility rules, not replay
148
+ foreign native records merely because a saved hook context contains them.
149
+
150
+ ## 4. Control flow and commit boundaries
151
+
152
+ ### New user turn
153
+
154
+ - `on_start`, if needed, initializes state/context before the first message hook.
155
+ Its context does not expose the staged user message; the first `on_message`
156
+ receives that message after initialization.
157
+ - `on_message` runs once per accepted top-level user message.
158
+ - `continue`: commit the validated state and effective memory, then invoke the
159
+ existing assistant against that context without appending the request again.
160
+ - `reply(Text)`: commit the hook transition and pass the text to common response
161
+ finalization; make zero outer assistant calls. Publish/persist one final reply.
162
+ - `reject(Reason)`: retain the original submission and rejection in the transcript,
163
+ commit validated application state (e.g. an attempt counter), but discard staged
164
+ message edits and omit that rejected submission from future model context.
165
+ - A failed/exceptional/cancelled hook discards its staged memory and state, reports
166
+ a turn error, and never silently falls through to the default assistant.
167
+
168
+ A successful hook transition is a commit point, not a transaction around the
169
+ whole remaining turn. A later provider failure does not undo an already accepted
170
+ state transition. Never promise rollback of files, commands, model usage, DML
171
+ non-backtrackable facts, or external side effects.
172
+
173
+ ### Tool invocation and result
174
+
175
+ Tool hooks cover the actual top-level Work assistant tool loop: declared typed
176
+ tools, available host helpers, and `run_workflow`. A manual workflow invocation
177
+ is not a synthetic user message and does not invoke these agent hooks.
178
+
179
+ - Validate tool existence/schema before invoking `on_tool_call`; invalid requests
180
+ remain truthful tool errors and are not passed to the tool body.
181
+ - `allow` commits the hook transition and proceeds through the original execution
182
+ wrapper, including a fresh policy/approval check. It is not a permission grant.
183
+ - `deny` records a paired error result for the original call ID; the tool body
184
+ never runs. The assistant can explain or choose another permitted action.
185
+ - No argument rewriting, tool substitution, or fabricated successful results in
186
+ the initial contract.
187
+ - Record a real tool result before `on_tool_result`. That hook may update memory
188
+ for the next model call but cannot overwrite the actual execution record.
189
+ - On hook failure/cancellation mid-batch, terminate the turn, preserve completed
190
+ results, and close outstanding protocol calls with truthful not-executed/error
191
+ results. Do not leave incomplete tool pairs or retry already executed effects.
192
+
193
+ ### Response and streaming
194
+
195
+ Both direct hook replies and default assistant replies use common finalization.
196
+ `on_response`, once introduced, sees the candidate reply and can replace it without
197
+ requesting another outer model turn. Its message edits affect subsequent context.
198
+
199
+ When that hook is declared, buffer each outer model response's text until its
200
+ final/tool-call status and response hook outcome are known. Do not first stream a
201
+ raw final answer and then replace it invisibly. Unhooked agents retain existing
202
+ live streaming. Hook-internal streams/reasoning are tagged nested activity, not
203
+ unconditionally appended to the public assistant message. Direct replies must not
204
+ be duplicated by intermediate DML task output.
205
+
206
+ ## 5. Explicit state and lifecycle persistence
207
+
208
+ Use a bounded, versioned, data-only codec for `StateIn`/`StateOut`: ground tagged
209
+ dicts, lists, strings, atoms, finite numbers, and booleans. Preserve term types;
210
+ reject open variables, cyclic terms, executable closures, handles, and unsupported
211
+ values rather than printing and later executing arbitrary Prolog source. Set
212
+ explicit size/depth limits and avoid silent numeric truncation.
213
+
214
+ Persist application state, effective context, and lifecycle markers together in
215
+ the existing SDK session snapshot. Do not store a Prolog execution stack or a
216
+ separate DeepClause conversation. State is supplied to hooks, not automatically
217
+ copied into every model prompt.
218
+
219
+ - `on_start` is lazy: shell validation, deployment probes, history reads, diagram
220
+ generation, and session listing must not execute it.
221
+ - With persistent history, record initialization as in-progress before running it,
222
+ then atomically checkpoint the completed marker with its state/context. Refuse
223
+ execution if required lifecycle persistence fails; do not swallow that failure
224
+ as a cosmetic history warning.
225
+ - Restoring a completed session restores its state/context without rerunning
226
+ `on_start`. An interrupted initialization is surfaced as interrupted and is not
227
+ automatically retried; initially offer starting a new conversation rather than
228
+ silently repeating initialization effects.
229
+ - An interrupted later hook/turn is not automatically replayed. Resume from the
230
+ last committed state/context and expose the interrupted operation honestly.
231
+ - Viewing an archive never runs a hook. Sending to a compatible restored agent
232
+ retains normal send-to-reopen semantics without reviving old processes/forms.
233
+ - Pinned program/script identity includes hook declarations and implementations;
234
+ current model/tool policy still applies on restore. New conversations have fresh
235
+ state. Follow the SDK's existing fork/copy semantics explicitly in tests.
236
+ - Old snapshots without hook metadata remain valid for unhooked shells. Never
237
+ guess that a legacy session with newly added hooks has completed initialization.
238
+
239
+ No claim of exactly-once external effects across crashes is made. Initialization
240
+ markers prevent silent replay; they are not a transaction with an external tool.
241
+
242
+ ## 6. Execution boundaries and limits
243
+
244
+ - Execute hooks as foreground Work frames under the current session's exclusive
245
+ operation. Do not call a public executor that tries to reacquire that same
246
+ operation lock, and do not use Develop scratch authoring transactions.
247
+ - Charge nested model calls to the enclosing turn budget; use current backend,
248
+ credential resolution, cancellation, provider concurrency, gas, and timeout
249
+ limits. Keep hook-specific sub-bounds within the parent limits.
250
+ - Commit one successful solution only; do not enumerate additional solutions or
251
+ backtrack to repeat side effects. Hook authors must make effectful branches
252
+ deterministic. A rejected decision is not an invitation to try another solution.
253
+ - Hook-originated tasks, prompts, capabilities, and replies do not recursively
254
+ invoke the same outer hooks. Tag origin and active hook scope explicitly.
255
+ - No hooks for Develop authoring, background process inboxes, title generation,
256
+ compaction model calls, or hook-internal LLM/tool calls in this initial feature.
257
+ - Hook DML uses only existing runtime capabilities and nested tool scopes. Shell
258
+ assistant tools do not automatically become tools for every nested task.
259
+ - AgentVM selection and all existing approval/tool wrappers remain intact. Allowing
260
+ a tool via a hook never enables an unavailable capability.
261
+ - Do not let steering inject messages around the message hook. Initially reject
262
+ steering for hook-enabled active turns with a clear unsupported-operation error;
263
+ normal new turns remain serialized. Add steering semantics separately.
264
+ - No persistent custom loop, new REST raw-goal endpoint, automatic process restart,
265
+ compiler, or dynamic hook/authoring tool exposure.
266
+
267
+ ## 7. Implementation seams
268
+
269
+ 1. **Contract:** `src/types.ts`, `src/work/index.ts`, and the shell normalization/
270
+ JSON export predicates in `src/prolog-src/deepclause_mi.pl`. Extend validation,
271
+ canonical rendering, snapshot identity, and round-trip tests together.
272
+ 2. **Memory/frame bridge:** a small SDK module such as `src/repl/work-hooks.ts`,
273
+ with narrow MI/runner helpers for seeding staged memory and returning successful
274
+ frame memory. Reuse existing execution infrastructure without granting authoring.
275
+ 3. **Coordinator:** `src/repl/session.ts` owns hook state, lifecycle, serialized
276
+ dispatch, persistence, and event forwarding. `src/repl/agent.ts` exposes safe
277
+ message staging/finalization and tool-loop interception seams; do not overwrite
278
+ private messages via casts or reuse lossy history projections as a live codec.
279
+ 4. **History:** extend `src/repl/history.ts` snapshot types/validation for state,
280
+ effective context provenance, and initialization status. Keep old readers from
281
+ silently ignoring semantically required hook state.
282
+ 5. **Hosts:** use the same SDK path through `src/repl/index.ts`, serve's session
283
+ worker, CLI/TUI Work, and sibling web runtime/RPC. No serve-only semantics.
284
+ 6. **Presentation:** add bounded hook activity/failure events with hook name, turn,
285
+ and origin. Keep intermediate routing output out of the final assistant reply;
286
+ preserve usage attribution and redaction. Hook failures are visible errors.
287
+ 7. **Versioning:** bump the Work contract/runtime identity for the new required
288
+ behavior; bump worker/RPC or persisted schemas where their payloads change.
289
+ Old hosts must reject hook-bearing deployments they cannot execute, not silently
290
+ fall back to a plain agent. Do not bump unrelated journal protocols by habit.
291
+
292
+ ## 8. Delivery phases
293
+
294
+ ### A. Contract and lossless memory bridge
295
+
296
+ Specify event/decision/state codecs, memory provenance, protected protocol groups,
297
+ commit boundaries, and initialization lifecycle. Prove successful `system/1` and
298
+ `user/1` edits reach the next actual backend request; prove failed/fresh-memory
299
+ edits do not. This is the gating prototype, not an optional enhancement.
300
+
301
+ ### B. `on_start` and `on_message`
302
+
303
+ Implement validation, lazy initialization, explicit state, direct replies,
304
+ rejection, cancellation, persistence/restore, and unchanged unhooked behavior.
305
+ Add a reviewed math/text/other routing example using the user's existing
306
+ `triage`/`handle` helpers, without an input loop or an unnecessary outer LLM call.
307
+
308
+ ### C. Tool hooks
309
+
310
+ Implement allow/deny interception, result-context updates, protocol-safe batch
311
+ failure handling, approval preservation, and recursion guards. Scope interception
312
+ to the standard Work assistant tool loop.
313
+
314
+ ### D. Response hook and host parity
315
+
316
+ Implement response transformation with consistent buffered streaming, then verify
317
+ serve, TUI, and sibling web behavior, shell-editor round trips, event replay, and
318
+ compatible/incompatible host handshakes. Do not advertise a hook a host ignores.
319
+ Update authoring documentation alongside each shipped phase.
320
+
321
+ Deferred: `on_resume`/`on_error`, background event hooks, tool argument rewriting,
322
+ synthetic tool results, configurable hook chains, generic per-LLM-call hooks,
323
+ steering, state migrations, and execution-continuation/process recovery.
324
+
325
+ ## 9. Acceptance and regression matrix
326
+
327
+ - Existing unhooked Work shells retain request order, tool grants, streaming,
328
+ workflow behavior, and model-call counts. Develop is unaffected.
329
+ - Contract decode/render/export/editor round trips preserve every hook; invalid
330
+ names, arities, keys, decisions, and state fail before action dispatch.
331
+ - `on_start` runs once on first chat, not on validation/read/probe/restore. Failed
332
+ or crash-interrupted initialization never silently repeats effects.
333
+ - `system/1` and `user/1` additions appear in a captured outer backend request in
334
+ order, including after save/restore; the incoming user message is not duplicated.
335
+ - `get_memory/1`, memory-bearing tasks, isolated prompts/fresh-memory scopes, and
336
+ `clear_memory` follow the specified semantics. Branch failure/cancellation does
337
+ not leak uncommitted edits; protected host policy remains present.
338
+ - Rebuilding effective context does not alter the original transcript, fabricate
339
+ human messages, expose secrets/provider blobs, lose media, or invalidate tool
340
+ call IDs/native reasoning data. Test real adapter serialization, not just text.
341
+ - The routing example returns math/text replies with zero outer assistant calls;
342
+ `continue` uses edited context with the standard assistant. Scoped model/tool
343
+ selection still works, and hook usage is accounted to the owning turn.
344
+ - State advances across hooks/turns, stays isolated across sessions, and survives
345
+ compatible restores/forks. Unsupported/oversized/cyclic state is rejected.
346
+ - Denied or invalid tool calls cause zero body executions. Allowed calls still
347
+ require normal approval/current registration. Result hooks cannot rewrite facts
348
+ about executed side effects. Multi-call batches remain protocol-valid on failure.
349
+ - Hook-internal calls do not recurse through outer hooks or gain authoring tools.
350
+ Manual workflows, background work, titles, and compaction do not trigger hooks.
351
+ - Cancellation, timeout, gas/model budget exhaustion, and persistence failure
352
+ terminate the correct owner without silent fallback, auto-retry, or process
353
+ recovery; another session remains responsive.
354
+ - A transformed final response is the same in live UI, persisted transcript, and
355
+ future model context. No raw-answer flash or duplicate direct reply occurs.
356
+ - Browser disconnection/session switching does not cancel server-owned work.
357
+ Archived history remains read-only until an actual user action requests work.
358
+ - Build, full SDK tests, focused hook/Work/serve tests, real Chrome smoke, runtime
359
+ identity checks, and sibling web build/tests pass. Tests use fake backends where
360
+ possible and do not require new credentials, releases, or a Git push.
361
+
362
+ ## 10. Documentation to update when implemented
363
+
364
+ Update `docs/WORK_MODE.md`, bundled `DML_SHELL.md`, `DML_TASKS.md`,
365
+ `DML_REFERENCE.md`, `HARNESS_EXAMPLES.md`, the SDK embedding API, and serve API/UI
366
+ notes. Explain the new opt-in Work hook memory bridge without falsely claiming
367
+ that all existing authoring, Work, and DML memory stores have always been shared.
368
+ Include the routing example, stateful staged intake, context augmentation/rebuild,
369
+ and a tool-denial example, plus initialization/restore and streaming caveats.
370
+
371
+ ## 11. Planning baseline validation
372
+
373
+ The clean merged source (excluding unrelated working-tree edits) built successfully
374
+ and passed the full SDK suite: **136 files passed, 2 skipped; 1,166 tests passed,
375
+ 1 expected fail, 26 skipped**. Evidence: local
376
+ `/tmp/dc-hooks-merge-validation.Y4EjMd/build.log` and `tests.log`.
377
+
378
+ The pre-existing judge/runtime edits were excluded from feature commits and
379
+ restored afterward; their binary Git diff was verified byte-for-byte identical.
380
+ This validates the merged baseline, not the later hooks implementation. The
381
+ acceptance matrix above remains the phased implementation checklist. Nothing was
382
+ pushed or released.
383
+
384
+ ## 12. Initial implementation notes
385
+
386
+ - Added explicit shell decoding/validation/rendering for start/message hook names;
387
+ the SDK coordinator invokes owned foreground frames and commits one solution.
388
+ - DML message projection references preserve whole native provider/tool groups and
389
+ media; successful message-memory changes affect the outer agent. The host policy
390
+ stays separate, and temporary hook memory cannot overwrite workflow memory in a
391
+ saved snapshot, even during teardown.
392
+ - Versioned state/context and initialization markers use temp-and-rename SDK
393
+ snapshot writes (atomic on native filesystems; the browser OPFS shim currently
394
+ emulates rename). Metadata marks sessions requiring hook state: a missing or
395
+ unreadable required snapshot fails closed rather than reinitializing. Required
396
+ checkpoint failures prevent dispatch; interrupted initialization is not replayed.
397
+ State is data-only, depth 32 / 64 KiB; context is bounded at 8 MiB.
398
+ - Hook-internal output is technical activity. Direct replies publish once. Hooks
399
+ share the turn budget, cancel with their owner, and have a 30-second sub-bound.
400
+ - Ordinary assistant workflow tools remain intact. SDK and serve regressions cover
401
+ actual `run_workflow` invocation, memory-bearing hook tasks, state restoration,
402
+ and send-to-reopen. The shipped routing example is exercised with a fake model
403
+ resolver/backend; no provider credentials are needed for the tests.
404
+ - No tool/result/response hook interception or response-stream transformation is
405
+ advertised in this initial phase. No hooks run for manual workflows, background
406
+ work, Develop, title generation, or compaction calls.
407
+
408
+ ### Initial phase validation
409
+
410
+ - SDK build/runtime identity checks passed (Work contract **2**).
411
+ - Full SDK suite: **137 files passed, 2 skipped; 1,189 tests passed,
412
+ 1 expected fail, 26 skipped**. This includes the pre-existing judge changes.
413
+ - Sibling web production build passed; **26 files / 113 tests passed**.
414
+ - Real Chrome serve smoke covers direct hook replies without an outer model call,
415
+ effective context changes, initialization once, and state retention across a
416
+ real server restart, alongside the existing workflow/process/security checks.
@@ -0,0 +1,140 @@
1
+ # Work-agent inboxes
2
+
3
+ A Work conversation can receive explicitly posted process results and run another
4
+ agent turn without another human submission. This is opt-in and requires Work
5
+ contract **3**. It does not require `agent_main/0` or a suspended input loop.
6
+
7
+ ```prolog
8
+ shell(_{kind:agent, system:"Coordinate background work.", host_tools:[],
9
+ tools:[], workflows:[], inbox:_{sources:[process]},
10
+ hooks:_{on_message:"intake"}}).
11
+
12
+ start(Task, Pid) :- agent_self(Main), spawn(worker(Main, Task), Pid).
13
+ worker(Main, Task) :-
14
+ with_tools([], prompt("Complete this task: {Task}", string(Result))),
15
+ agent_post(Main, message{text:Result, data:result{task:Task}}, _Id).
16
+
17
+ intake(Context, State, State, continue).
18
+ ```
19
+
20
+ For a complete assistant-callable launch tool, explicit result handling and scoped
21
+ worker limits, see `sdk-examples/subagent-inbox.dml`. From this checkout:
22
+
23
+ ```sh
24
+ deepclause serve sdk-examples/subagent-inbox.dml
25
+ ```
26
+
27
+ Ask it to run one or several self-contained subagent tasks. Workers have no host
28
+ or browsing tools. The selected model/credentials/provider concurrency still come
29
+ from the host. Their results are summarized with a tool-free prompt; the result
30
+ path cannot launch more workers. The example does not claim external verification.
31
+
32
+ ## Language and context
33
+
34
+ - `agent_self(Agent)` obtains an owning foreground Work-agent reference. Pass it
35
+ explicitly to a child. A child cannot obtain it implicitly with agent_self.
36
+ - `agent_post(Agent, Message, MessageId)` accepts a data dictionary with a nonempty
37
+ `text` string, optional `data` dictionary, and optional `key` string. It returns
38
+ after the queue checkpoint succeeds, not after the assistant replies. Do not
39
+ wait for a reply as part of posting: the parent may be waiting for the child.
40
+ - Data is finite, depth-limited JSON-compatible DML data; dict tags may be
41
+ anonymous. Variables, executable compounds, cycles and capabilities are not
42
+ message data. Reference terms are not persistable hook application state.
43
+ - References are incarnation-scoped `agent_ref/1` capabilities, not process pids,
44
+ user-supplied session IDs or global names. Cross-session/stale references fail.
45
+ `send/2` and process mailboxes retain their existing meanings.
46
+
47
+ `on_message/4` receives `source: user` or `source: process` (atoms), `message`
48
+ (text), and, for process deliveries, `message_id`, `sender` (pid/name data), and
49
+ `data`. Provenance comes from the process broker, not a sender-supplied field.
50
+ The first dispatched input initializes on_start once; viewing history does not.
51
+
52
+ Normal continue/reply/reject decisions apply. Process-only `consume` commits
53
+ state/effective memory but makes no outer model call and publishes no assistant
54
+ reply. It still records the input. Using consume for human input is an error.
55
+ Incoming process text/payload is staged once as an explicitly labelled user-role
56
+ data envelope, never a system instruction or fabricated tool response. Hooks can
57
+ use the existing system/user/get_memory bridge; host policy stays protected.
58
+
59
+ ## Dispatch, limits and controls
60
+
61
+ One session lock serializes human operations and inbox deliveries. Posting while
62
+ a turn/tool/input/approval is active queues the message; it never steers or
63
+ recursively invokes the agent. FIFO applies to accepted process messages. Human
64
+ requests retain the existing busy behavior. Manual workflow runs do not become
65
+ conversation input unless a delegated process explicitly posts a result.
66
+
67
+ Defaults/hard caps: 32 pending/running deliveries, 16 KiB per message, depth 32,
68
+ 32 new messages per minute and 10 autonomous turns between human requests or
69
+ explicit resumes. A background turn gets at most 10 model calls (or the smaller
70
+ configured turn budget). Existing execution/provider/process limits also apply.
71
+ The shell may lower max_pending/max_auto_turns; host agentInboxPolicy can disable
72
+ or tighten them further. A full queue, bad data, rate rejection or failed durable
73
+ write is an explicit post error. Sending again is not an automatic runtime retry.
74
+
75
+ Failure/cancellation pauses draining. The failed/interrupted delivery is terminal;
76
+ resume processes later pending messages, not that delivery again. Quota exhaustion
77
+ also pauses. A new human message or explicit resume resets the autonomous-turn
78
+ counter, not the one-minute acceptance rate. Pause stops subsequent draining; it
79
+ does not cancel an already active response. Stop/cancel still controls that turn.
80
+ Human input/approval never auto-approves while the browser is absent.
81
+
82
+ Serve shows a background-labelled message, normal response, inbox status and
83
+ pause/resume buttons. Per-browser read counts mark unread background messages.
84
+ Authenticated control: POST `/api/sessions/{id}/inbox` with
85
+ `{"action":"pause"}` or `{"action":"resume"}` on a live session.
86
+ There is deliberately no public arbitrary-session posting endpoint.
87
+
88
+ ## Host API and lifetime
89
+
90
+ `HarnessReplOptions` accepts `agentInboxPolicy`, an optional `agentInboxStore`,
91
+ `onAgentInboxEvent`, and `onAgentInboxReady`. Without a ready callback the SDK
92
+ pumps accepted inputs when idle and emits asynchronous events to the event sink.
93
+ History remains the durable presentation source; hosts should wire that sink to
94
+ their live UI. With a ready callback the host owns scheduling: drain one input
95
+ using `session.processAgentInbox({signal})`. Additional session methods are
96
+ `agentInboxStatus`, `pauseAgentInbox`, `resumeAgentInbox`, and
97
+ `cancelAgentInboxTurn`. Ready callbacks are notifications, not delivery receipts.
98
+
99
+ Serve uses its existing server-owned operations, deadlines, cancellation and
100
+ journal, so tab closure or SSE disconnection has no effect. The CLI Work REPL
101
+ also owns scheduling: TUI, plain readline and piped-input loops wake while idle
102
+ and render `Background · <sender>` plus the normal response. Deliveries wait for
103
+ foreground turns, forms and pickers; human input entered during a background turn
104
+ is queued, not steered or discarded. Foreground agents with hooks or inboxes likewise
105
+ queue subsequent human messages rather than attempting unsupported steering.
106
+ Unsent editor text survives delivery and
107
+ explicit background input prompts. TUI Escape cancels the active background turn;
108
+ Ctrl-C exits. History/usage still come from the same SDK turn, with no duplicate
109
+ transcript or synthetic human submission.
110
+
111
+ Browser-only embeddings still require a live page/worker; an always-on host is
112
+ required after page closure. The CLI likewise cannot execute after its process
113
+ exits (or after piped stdin reaches EOF). Restored pending messages remain paused
114
+ until ordinary human input or an explicit SDK resume; opening the REPL does not
115
+ replay or restart them.
116
+
117
+ ## Persistence and recovery
118
+
119
+ The SDK requires history or an explicit durable store for an enabled inbox. Its
120
+ bounded `agent-inbox.json` checkpoint lives beside harness/session history; queue
121
+ writes are serialized independently of conversation snapshots. Messages/statuses
122
+ also enter the normal event journal (SDK event tracing must be enabled when the
123
+ SDK owns that journal; serve owns its own JSONL journal).
124
+
125
+ Acceptance follows a successful write; claiming follows another write, before
126
+ hook/model dispatch. No exactly-once external-effect guarantee is made. A lost
127
+ acknowledgement may mean the message was accepted. An optional sender-pid-scoped
128
+ key deduplicates identical retransmissions while its entry is retained; changing
129
+ the payload under the same key is an error. Terminal retention is bounded (128
130
+ recent entries, up to 160 records including active messages), not permanent global
131
+ idempotency. Native storage uses temporary-file/rename commits; power-loss and
132
+ browser virtual-filesystem durability follow the host filesystem's guarantees.
133
+
134
+ On restoration, running messages become interrupted and are never replayed;
135
+ pending messages remain held until a new user message or explicit resume. A
136
+ missing, corrupt or incompatible required inbox fails closed. Restoring history does not
137
+ restart workers, services, approvals, forms, or execution stacks. References are
138
+ always replaced on a new runtime incarnation. Closing disables posting/draining
139
+ and stops processes; an explicit later continuation can inspect/handle saved
140
+ pending data. Merely visiting a saved conversation never starts execution.
@@ -0,0 +1,91 @@
1
+ # Work-agent inbox implementation plan
2
+
3
+ ## Contract
4
+
5
+ Opt-in `shell/1` agent declaration: `inbox: _{sources:[process]}`. Add
6
+ `agent_self(Agent)` (owning foreground only) and `agent_post(Agent, Message, Id)`.
7
+ Message is a bounded data dictionary with `text`, optional `data` and optional
8
+ `key` (sender-scoped deduplication). References are opaque, incarnation-scoped
9
+ `agent_ref/1` capabilities passed explicitly to children, never restored handles.
10
+ No cross-conversation addressing. Existing process send/receive stays unchanged.
11
+
12
+ Messages enter the existing on_message/4 pipeline with source, sender, data and
13
+ message_id. Human messages get source=user. Background payload is untrusted data,
14
+ never system policy or a synthetic tool result. Add process-only `consume`:
15
+ commit state/effective memory, but do not call the outer model or publish a reply.
16
+ Inbox-only agents use the same lossless memory bridge even without declared hooks.
17
+
18
+ ## Ownership and dispatch
19
+
20
+ Implement the queue, codec and serial turn dispatch in the SDK. Background input
21
+ never steers or recursively invokes an active turn. SDK hosts may drain through
22
+ `processAgentInbox`; a wake callback lets serve schedule ordinary server-owned
23
+ operations, with its existing cancellation/deadline/approval/usage machinery.
24
+ Without a host dispatcher the SDK drains when idle and publishes session events
25
+ through a callback. Human operations retain their existing busy behavior.
26
+
27
+ Serve does not depend on SSE clients. Root workers proxy child posts through the
28
+ existing capability broker. Foreground self-reference acquisition does not grant
29
+ children implicit access: children must receive the reference as a goal argument.
30
+ Update Work and worker protocols so stale hosts reject incompatible builds.
31
+
32
+ ## Persistence and failure semantics
33
+
34
+ Use a bounded atomic queue snapshot beside SDK history (no database); actual
35
+ messages/statuses/responses also enter normal JSONL session history and the serve
36
+ journal. Acknowledge a post only after its queue write succeeds. Serialize queue
37
+ mutations independently of turn snapshot writes. A claim is written before hook
38
+ or model dispatch. Interruption/failure/cancellation is terminal for that delivery;
39
+ never automatically retry external effects. Deduplicate optional keys, not model
40
+ execution, and make no exactly-once side-effect claim.
41
+
42
+ On restore, running deliveries become interrupted; pending deliveries are held
43
+ until explicit user activity/resume. No process or service recovery. References
44
+ change on every runtime incarnation. Closing stops dispatch and processes.
45
+ Browser disconnect does nothing. Browser-only execution still requires the page;
46
+ headless operation requires serve or another always-on SDK host.
47
+
48
+ ## Limits and presentation
49
+
50
+ Conservative caps: 32 pending messages, 16 KiB per message, 32 accepted messages
51
+ per minute, 10 autonomous turns between human messages; host policy can disable
52
+ or tighten limits. Preserve bounded deduplication/status history. Refuse full,
53
+ closed, unauthorized, invalid and over-rate posts explicitly. Pause on autonomous
54
+ budget exhaustion/failure rather than spinning. Surface queue status and process
55
+ provenance in history/UI. Stop cancels a current turn, not an approval grant.
56
+
57
+ ## Work items
58
+
59
+ 1. Contract parsing/rendering/validation, process primitives and broker transport.
60
+ 2. Bounded persistent SDK inbox and hook/context/consume integration.
61
+ 3. Serve wake/dispatch, truthful background transcript and queue status controls.
62
+ 4. Generic subagent harness: declared typed launch tool, isolated bounded workers,
63
+ explicit post-back, on_message processing and no custom conversation loop.
64
+ 5. Tests: isolated sessions, L1/L2 transport, no-browser HTTP delivery, FIFO/busy,
65
+ failed writes, malformed payloads, stale references, bounds, deduplication,
66
+ consume, restore without replay, cancellation and regression suite/build.
67
+
68
+ Implementation preserves all pre-existing uncommitted hook/judge/runtime work.
69
+ No push or release is part of this task.
70
+
71
+ ## Implemented status
72
+
73
+ All five work items are implemented locally. Work contract is 3, SDK process-worker
74
+ protocol is 4, and serve-worker protocol is 3. The complete generic harness is
75
+ `sdk-examples/subagent-inbox.dml`; usage and recovery semantics are documented in
76
+ [WORK_AGENT_INBOX.md](./WORK_AGENT_INBOX.md).
77
+
78
+ Validation includes actual L2 worker provenance/delegation, FIFO and isolated
79
+ sessions, bounded autonomous model calls (including unlimited-human-budget hosts),
80
+ fault-injected acceptance/claim/final checkpoints, idle recovery without replay,
81
+ server restart with held data, and the example's real typed launch-tool path.
82
+ Chrome smoke unloads the UI, waits for headless delivery, then verifies persisted
83
+ background provenance, unread-on-scroll behavior and pause/resume controls. Native
84
+ metadata/snapshot commits use temporary-file/rename; filesystem durability caveats
85
+ and lack of exactly-once effects are explicit.
86
+
87
+ Final validation: SDK build/runtime identity and package inclusion passed; SDK
88
+ regression suite **138 files passed, 2 skipped; 1,213 tests passed, 1 expected
89
+ failure, 26 skipped**. Focused inbox/hook suites passed **37 tests**. Sibling web
90
+ production build and **26 files / 113 tests** passed without working-tree changes.
91
+ The Chrome serve smoke passed with the UI actually unloaded during delivery.