@tangle-network/agent-runtime 0.7.0 → 0.9.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.
@@ -1,326 +0,0 @@
1
- # Product Runtime Kernel
2
-
3
- Status: complete. Implemented in `@tangle-network/agent-runtime@0.5.0`;
4
- validated, documented, and hardened through `0.5.2`.
5
-
6
- This document is the completion record for the production runtime kernel: what
7
- it is for, what is done, how it was validated, what is intentionally outside the
8
- public package, and how product repos should adopt it.
9
-
10
- ## Purpose
11
-
12
- `agent-runtime` exists to make agent execution consistent across products and
13
- eval harnesses. It should own the contract for:
14
-
15
- - readiness gating before execution;
16
- - session create/resume for long-running coding harnesses;
17
- - backend-agnostic streaming;
18
- - sanitized product/eval telemetry;
19
- - durable evidence that can feed reports, failure classification, and
20
- optimization.
21
-
22
- It should not be a decorative event logger around unrelated product code. If a
23
- product route still calls a backend directly, hand-rolls SSE, and only emits
24
- `start/end`, it is not getting the full value.
25
-
26
- ## Runtime Flow
27
-
28
- ```txt
29
- TaskSpec
30
- -> knowledge readiness
31
- -> optional ask/acquire/refresh
32
- -> readiness decision
33
- -> session create/resume
34
- -> execution backend stream
35
- -> normalized RuntimeStreamEvent
36
- -> sanitized SSE / persisted session event history
37
- -> final task status
38
- ```
39
-
40
- ## Definition of Done
41
-
42
- The kernel is complete when these are true:
43
-
44
- - A product route can call one runtime entry point, `runAgentTaskStream`, rather
45
- than hand-rolling readiness + backend execution + SSE framing.
46
- - A coding harness can continue an existing workspace by passing `sessionId` and
47
- `resume: true`.
48
- - A backend can be swapped without changing product stream consumers.
49
- - A failed backend emits structured failure events and gets a `stop()` callback
50
- when available.
51
- - All UI/report telemetry has a safe sanitized representation by default.
52
- - Eval and optimization systems can distinguish missing context/runtime failure
53
- from prompt/model reasoning failure.
54
-
55
- All kernel-side criteria are satisfied in `0.5.2`. Durable storage and UI
56
- rollout are product adoption tasks, not core package blockers.
57
-
58
- Completion verdict: passed. There are no open kernel blockers in this document.
59
-
60
- ## Completed API Surface
61
-
62
- ### Execution
63
-
64
- - `runAgentTaskStream(options)`
65
- - Applies readiness before backend execution.
66
- - Emits `task_start`, `readiness_start`, `readiness_end`.
67
- - Stops before backend execution when blocking gaps remain.
68
- - Creates or resumes a backend session.
69
- - Normalizes backend output into `RuntimeStreamEvent`.
70
- - Emits `backend_start`, `backend_end`, `task_end`, and `final`.
71
- - Records backend stream events into an optional `RuntimeSessionStore`.
72
- - Calls `backend.stop(session, reason)` on stream failure when a backend
73
- supplies the hook.
74
-
75
- - `runAgentTask(options)`
76
- - Existing control-loop path for eval-oriented agents.
77
- - Still useful for deterministic eval/optimization harnesses that model
78
- observe/validate/decide/act directly.
79
-
80
- ### Stream Contract
81
-
82
- - `RuntimeStreamEvent`
83
- - Readiness: `readiness_start`, `readiness_end`.
84
- - Context collection: `questions_start`, `questions_end`,
85
- `acquisition_start`, `acquisition_end`.
86
- - Session: `session_created`, `session_resumed`.
87
- - Backend lifecycle: `backend_start`, `backend_end`, `backend_error`.
88
- - Product stream: `text_delta`, `reasoning_delta`, `tool_call`,
89
- `tool_result`, `artifact`.
90
- - Completion: `task_end`, `final`.
91
-
92
- ### Sessions
93
-
94
- - `RuntimeSession`
95
- - Stable `id`, backend kind, status, timestamps, optional `resumeToken`, and
96
- metadata.
97
-
98
- - `RuntimeSessionStore`
99
- - Minimal persistence contract: `get`, `put`, `appendEvent`, `listEvents`.
100
- - Product repos should back this with D1/Postgres/Redis/etc. for real resume.
101
-
102
- - `InMemoryRuntimeSessionStore`
103
- - Useful for tests, local demos, and short-lived worker processes.
104
- - Not durable enough for production resume by itself.
105
-
106
- ### Backend Abstraction
107
-
108
- - `AgentExecutionBackend`
109
- - `start`, `resume`, `stream`, optional `stop`.
110
- - SDK-agnostic: the package owns the contract, callers own concrete clients
111
- and auth.
112
-
113
- - `createIterableBackend`
114
- - Escape hatch for custom harnesses, browser agents, and test doubles.
115
-
116
- - `createSandboxPromptBackend`
117
- - Wraps sandbox/sidecar clients that expose `streamPrompt`.
118
- - Supports caller-provided session IDs and resume via backend `resume`.
119
- - Maps common sandbox events to `text_delta`, `tool_call`, and `tool_result`.
120
-
121
- - `createOpenAICompatibleBackend`
122
- - Wraps TCloud/OpenAI-compatible `/chat/completions` streaming APIs.
123
- - Normalizes streamed content deltas into `text_delta`.
124
- - Also covers [cli-bridge](https://github.com/drewstone/cli-bridge) and any
125
- other OpenAI-compatible HTTP gateway — point `baseUrl` at the bridge's
126
- `/v1` and use a `<harness>/<model>` string as `model`.
127
-
128
- ### Sanitization and SSE
129
-
130
- - `sanitizeRuntimeStreamEvent(event, options)`
131
- - Redacts task inputs, user answers, control payloads, metadata, artifact
132
- URIs, and evidence IDs by default.
133
- - Reveals payloads only through explicit diagnostic options.
134
-
135
- - `runtimeStreamServerSentEvent(event, options)`
136
- - Encodes any sanitized runtime stream event as SSE.
137
- - Prevents every product route from hand-rolling inconsistent framing.
138
-
139
- - Existing helpers remain:
140
- - `sanitizeAgentRuntimeEvent`
141
- - `createRuntimeEventCollector`
142
- - `readinessServerSentEvent`
143
- - `encodeServerSentEvent`
144
-
145
- ## Validation Matrix
146
-
147
- Implemented test coverage in `tests/runtime.test.ts`:
148
-
149
- - Ready task runs through the existing control lifecycle.
150
- - Missing blocking knowledge stops before action.
151
- - Knowledge question/acquisition hooks refresh readiness before control.
152
- - Sanitized runtime telemetry redacts secrets by default.
153
- - Readiness decisions return stable `ready`, `blocked`, and `caveat` states.
154
- - SSE encoding strips unsafe control-field newlines.
155
- - Readiness SSE payloads use sanitized reports.
156
- - `runAgentTaskStream` blocks backend execution when readiness is missing.
157
- - Streaming backend creates a session, persists events, and resumes by
158
- `sessionId`.
159
- - Sanitized tool-call stream events hide payloads by default and reveal them
160
- only with `includeControlPayloads`.
161
- - Sandbox prompt events map to text/tool runtime stream events.
162
- - OpenAI-compatible streaming chat completions parse token deltas and produce a
163
- final completed event.
164
- - Knowledge question preflight emits exactly one `questions_end`.
165
- - CLI bridge streams parse NDJSON events and include session/message payloads in
166
- bridge requests.
167
- - Backend stream failure calls `backend.stop`, emits `backend_error`, and
168
- returns a failed `final` event with partial text preserved.
169
-
170
- Release verification:
171
-
172
- - `pnpm test`
173
- - `pnpm typecheck`
174
- - `pnpm build`
175
- - Published to npm as `@tangle-network/agent-runtime@0.5.0`.
176
- - Documentation validation published in `@tangle-network/agent-runtime@0.5.1`.
177
- - Hardening validation published in `@tangle-network/agent-runtime@0.5.2`.
178
-
179
- ## Completion Scorecard
180
-
181
- | Area | Status | Evidence |
182
- | --- | --- | --- |
183
- | Readiness gate | Complete | `runAgentTaskStream` blocks before backend execution when readiness is blocked. |
184
- | Stream contract | Complete | `RuntimeStreamEvent` covers readiness, session, backend, text, reasoning, tool, artifact, error, task end, final. |
185
- | Session resume contract | Complete | `RuntimeSession`, `RuntimeSessionStore`, `session_created`, `session_resumed`, `resumeToken`. |
186
- | Backend abstraction | Complete | `AgentExecutionBackend` with `start`, `resume`, `stream`, optional `stop`. |
187
- | Sandbox adapter | Complete | `createSandboxPromptBackend`; product proof in `agent-builder` PR #61. |
188
- | TCloud/OpenAI-compatible adapter | Complete | `createOpenAICompatibleBackend`; tested with streamed chat completions. Also serves cli-bridge (OpenAI-compatible) and any HTTP gateway. |
189
- | SSE framing | Complete | `runtimeStreamServerSentEvent`, newline-safe SSE encoder. |
190
- | Sanitization | Complete | Default redaction for task inputs, answers, payloads, metadata, URIs, evidence IDs. |
191
- | Failure handling | Complete | Backend exceptions produce `backend_error`, failed `task_end`, failed `final`, and call `stop` when supplied. |
192
- | Durable persistence | Contract complete, product-owned | `RuntimeSessionStore` interface exists; product repos must provide D1/Postgres/Redis implementations. |
193
- | UI rollout | Product-owned | Runtime emits stable events; product UIs decide rendering. |
194
-
195
- ## Completion Boundaries
196
-
197
- The package is done when the reusable contract is complete. The package is not
198
- responsible for product-specific state, credentials, databases, or UX. Those are
199
- adoption responsibilities.
200
-
201
- ### Complete in `agent-runtime`
202
-
203
- - Public task and stream contracts.
204
- - Readiness-gated streamed execution.
205
- - Session create/resume contract.
206
- - Backend abstraction and adapter factories.
207
- - Safe stream sanitization.
208
- - SSE encoding.
209
- - Failure normalization and backend stop hook.
210
- - Unit tests for the contract and shipped adapters.
211
- - NPM package publication.
212
-
213
- ### Not Part of the Public Kernel
214
-
215
- - Product database migrations.
216
- - Product-specific session persistence.
217
- - Product-specific auth, secrets, billing, and rate limits.
218
- - UI components for resume/readiness.
219
- - Domain-specific knowledge requirements and tool policies.
220
- - Concrete private SDK client construction.
221
-
222
- These are not deferred kernel tasks. They are downstream integration tasks.
223
-
224
- ## Critique
225
-
226
- The runtime kernel is now materially useful, but it is not magic. The most
227
- important limitations are deliberate:
228
-
229
- - It does not construct TCloud, sandbox, or CLI bridge clients. Product repos
230
- own credentials and client lifecycle.
231
- - It does not persist sessions durably unless a product supplies a durable
232
- `RuntimeSessionStore`.
233
- - It does not enforce all budgets/approvals/tool policies by itself yet. Those
234
- still live in product adapters or `agent-eval` control loops.
235
- - It does not guarantee backend resume works if the underlying backend cannot
236
- resume. It passes stable session IDs/resume tokens and records history; the
237
- backend must honor them.
238
- - It does not replace domain-specific wrappers. Tax/legal/GTM/creative still
239
- need their own requirements, tools, prompts, and report semantics.
240
-
241
- These constraints are correct for a public package. The core should define the
242
- contract and provide high-quality adapters, not absorb private product code.
243
-
244
- The main remaining architectural risk is misuse: product teams can still bypass
245
- the kernel and directly call sandbox/TCloud/CLI streams. Reviews should treat
246
- new hand-rolled readiness + stream loops as a smell unless the route has a
247
- specific reason to avoid runtime normalization.
248
-
249
- ## Downstream Adoption Checklist
250
-
251
- For product routes:
252
-
253
- - Replace direct sandbox/CLI/TCloud stream loops with `runAgentTaskStream`.
254
- - Forward `runtimeStreamServerSentEvent(event)` to UI.
255
- - Preserve legacy UI events only as compatibility shims.
256
- - Store `RuntimeSession` and `RuntimeStreamEvent[]` in the product database.
257
- - Pass `sessionId` and `resume: true` for continuation.
258
- - Persist `final.status`, readiness decision, and backend kind in run records.
259
- - Assert in tests that blocked readiness does not call the backend.
260
-
261
- For coding harnesses:
262
-
263
- - Use `createSandboxPromptBackend`, `createOpenAICompatibleBackend` (also
264
- covers cli-bridge and other OpenAI-compatible HTTP gateways), or a custom
265
- `AgentExecutionBackend`.
266
- - Require a stable `sessionId` for any long-running workspace.
267
- - Surface `session_resumed` in telemetry so product/debug views can distinguish
268
- continuation from a fresh run.
269
- - Treat missing session state as a recoverable backend/runtime failure, not a
270
- prompt failure.
271
- - Implement `stop(session, reason)` for expensive or long-lived backends.
272
-
273
- For eval and optimization:
274
-
275
- - Attach readiness decisions and stream session metadata to `RunRecord.raw`.
276
- - Classify missing knowledge/runtime/session failures separately from prompt or
277
- reasoning failures.
278
- - Do not optimize prompts when dominant failures are missing context, bad
279
- retrieval, missing credentials, or broken backend resume.
280
- - Add report slices by `backend`, `session_resumed`, `backend_error`, and
281
- `readiness_end.decision.status`.
282
-
283
- ## Completed Downstream Proof
284
-
285
- `agent-builder` has a product-path proof in PR #61:
286
-
287
- - Bumps `@tangle-network/agent-runtime` to `^0.5.0`.
288
- - Routes sandbox chat through `runAgentTaskStream`.
289
- - Uses `createSandboxPromptBackend`.
290
- - Emits sanitized runtime stream SSE.
291
- - Adds runtime session IDs to the compatibility `done` event.
292
-
293
- That validates the package against a real sandbox-backed product route, not only
294
- unit tests.
295
-
296
- ## Review Notes
297
-
298
- Validation found and fixed two issues before marking this complete:
299
-
300
- - The control-loop preflight path needed explicit coverage that
301
- `questions_end` is emitted exactly once.
302
- - The CLI bridge parser claim needed hardening. `0.5.2` tested NDJSON bridge
303
- streams instead of only SSE-style `data:` frames. `0.6.0` then removed the
304
- bespoke `createCliBridgeBackend` entirely after confirming cli-bridge is
305
- purely OpenAI-compatible at `/v1/chat/completions`; consumers now use
306
- `createOpenAICompatibleBackend`.
307
-
308
- The doc now matches shipped behavior.
309
-
310
- ## Downstream Rollout Plan
311
-
312
- This is downstream adoption work, not missing kernel work:
313
-
314
- 1. Add durable `RuntimeSessionStore` implementations in product repos.
315
- 2. Convert CLI bridge routes/harnesses to `createOpenAICompatibleBackend`
316
- pointed at the bridge's `/v1` URL (cli-bridge is OpenAI-compatible).
317
- 3. Convert simple TCloud chat routes to `createOpenAICompatibleBackend` where
318
- useful.
319
- 4. Store runtime stream events in product trace/run-record tables.
320
- 5. Add UI affordances for session resume/continuation and readiness blockers.
321
- 6. Extend failure classifiers to consume `RuntimeStreamEvent` evidence directly.
322
-
323
- The kernel is complete and ready for broad adoption. The next value comes from
324
- removing bespoke product stream loops and using the same runtime contract across
325
- product routes, coding harnesses, CLI bridge runs, evals, and optimization
326
- reports.