@archmax-ai/harness 0.0.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 (351) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -0
  3. package/dist/agent.d.ts +174 -0
  4. package/dist/agent.js +140 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/assembly/compose.d.ts +170 -0
  7. package/dist/assembly/compose.js +391 -0
  8. package/dist/assembly/compose.js.map +1 -0
  9. package/dist/assembly/delegation-registry.d.ts +5 -0
  10. package/dist/assembly/delegation-registry.js +118 -0
  11. package/dist/assembly/delegation-registry.js.map +1 -0
  12. package/dist/assembly/index.d.ts +192 -0
  13. package/dist/assembly/index.js +265 -0
  14. package/dist/assembly/index.js.map +1 -0
  15. package/dist/assembly/plain.d.ts +7 -0
  16. package/dist/assembly/plain.js +41 -0
  17. package/dist/assembly/plain.js.map +1 -0
  18. package/dist/authoring-skill/archmax-harness/README.md +76 -0
  19. package/dist/authoring-skill/archmax-harness/SKILL.md +241 -0
  20. package/dist/authoring-skill/archmax-harness/references/backend-integration.md +626 -0
  21. package/dist/authoring-skill/archmax-harness/references/cases.md +41 -0
  22. package/dist/authoring-skill/archmax-harness/references/diagnostics.md +51 -0
  23. package/dist/authoring-skill/archmax-harness/references/hook-and-test-scripts.md +1070 -0
  24. package/dist/authoring-skill/archmax-harness/references/hooks-and-scripts.md +82 -0
  25. package/dist/authoring-skill/archmax-harness/references/wiring.md +101 -0
  26. package/dist/authoring-skill/archmax-harness/references/workflow-schema.md +1631 -0
  27. package/dist/authoring-skill/archmax-harness/references/workflow-yaml.md +241 -0
  28. package/dist/behaviour/support.d.ts +232 -0
  29. package/dist/behaviour/support.js +339 -0
  30. package/dist/behaviour/support.js.map +1 -0
  31. package/dist/cli/banner.d.ts +11 -0
  32. package/dist/cli/banner.js +29 -0
  33. package/dist/cli/banner.js.map +1 -0
  34. package/dist/cli/bootstrap.d.ts +33 -0
  35. package/dist/cli/bootstrap.js +153 -0
  36. package/dist/cli/bootstrap.js.map +1 -0
  37. package/dist/cli/command.d.ts +39 -0
  38. package/dist/cli/command.js +97 -0
  39. package/dist/cli/command.js.map +1 -0
  40. package/dist/cli/state-flow.d.ts +46 -0
  41. package/dist/cli/state-flow.js +268 -0
  42. package/dist/cli/state-flow.js.map +1 -0
  43. package/dist/cli/style.d.ts +41 -0
  44. package/dist/cli/style.js +64 -0
  45. package/dist/cli/style.js.map +1 -0
  46. package/dist/cli/turn.d.ts +41 -0
  47. package/dist/cli/turn.js +161 -0
  48. package/dist/cli/turn.js.map +1 -0
  49. package/dist/cli.d.ts +10 -0
  50. package/dist/cli.js +426 -0
  51. package/dist/cli.js.map +1 -0
  52. package/dist/core/code-description.d.ts +22 -0
  53. package/dist/core/code-description.js +38 -0
  54. package/dist/core/code-description.js.map +1 -0
  55. package/dist/core/deepagents.d.ts +183 -0
  56. package/dist/core/deepagents.js +128 -0
  57. package/dist/core/deepagents.js.map +1 -0
  58. package/dist/core/events.d.ts +350 -0
  59. package/dist/core/events.js +205 -0
  60. package/dist/core/events.js.map +1 -0
  61. package/dist/core/frontmatter.d.ts +15 -0
  62. package/dist/core/frontmatter.js +32 -0
  63. package/dist/core/frontmatter.js.map +1 -0
  64. package/dist/core/listing-redact.d.ts +37 -0
  65. package/dist/core/listing-redact.js +88 -0
  66. package/dist/core/listing-redact.js.map +1 -0
  67. package/dist/core/match.d.ts +26 -0
  68. package/dist/core/match.js +75 -0
  69. package/dist/core/match.js.map +1 -0
  70. package/dist/core/message-readers.d.ts +84 -0
  71. package/dist/core/message-readers.js +159 -0
  72. package/dist/core/message-readers.js.map +1 -0
  73. package/dist/core/messages.d.ts +49 -0
  74. package/dist/core/messages.js +85 -0
  75. package/dist/core/messages.js.map +1 -0
  76. package/dist/core/mount-prompt.d.ts +28 -0
  77. package/dist/core/mount-prompt.js +55 -0
  78. package/dist/core/mount-prompt.js.map +1 -0
  79. package/dist/core/mount-redact.d.ts +28 -0
  80. package/dist/core/mount-redact.js +32 -0
  81. package/dist/core/mount-redact.js.map +1 -0
  82. package/dist/core/mounts.d.ts +88 -0
  83. package/dist/core/mounts.js +147 -0
  84. package/dist/core/mounts.js.map +1 -0
  85. package/dist/core/path-mapping.d.ts +52 -0
  86. package/dist/core/path-mapping.js +113 -0
  87. package/dist/core/path-mapping.js.map +1 -0
  88. package/dist/core/platform-prompt.generated.d.ts +2 -0
  89. package/dist/core/platform-prompt.generated.js +4 -0
  90. package/dist/core/platform-prompt.generated.js.map +1 -0
  91. package/dist/core/prompt.d.ts +42 -0
  92. package/dist/core/prompt.js +75 -0
  93. package/dist/core/prompt.js.map +1 -0
  94. package/dist/core/session-id.d.ts +38 -0
  95. package/dist/core/session-id.js +61 -0
  96. package/dist/core/session-id.js.map +1 -0
  97. package/dist/core/session-store.d.ts +85 -0
  98. package/dist/core/session-store.js +149 -0
  99. package/dist/core/session-store.js.map +1 -0
  100. package/dist/core/session-zone.d.ts +54 -0
  101. package/dist/core/session-zone.js +82 -0
  102. package/dist/core/session-zone.js.map +1 -0
  103. package/dist/core/skill-prompt.d.ts +31 -0
  104. package/dist/core/skill-prompt.js +54 -0
  105. package/dist/core/skill-prompt.js.map +1 -0
  106. package/dist/core/skill-redact.d.ts +15 -0
  107. package/dist/core/skill-redact.js +27 -0
  108. package/dist/core/skill-redact.js.map +1 -0
  109. package/dist/core/skills.d.ts +172 -0
  110. package/dist/core/skills.js +214 -0
  111. package/dist/core/skills.js.map +1 -0
  112. package/dist/core/tool-mocks.d.ts +23 -0
  113. package/dist/core/tool-mocks.js +39 -0
  114. package/dist/core/tool-mocks.js.map +1 -0
  115. package/dist/core/tool-telemetry.d.ts +16 -0
  116. package/dist/core/tool-telemetry.js +40 -0
  117. package/dist/core/tool-telemetry.js.map +1 -0
  118. package/dist/core/usage.d.ts +114 -0
  119. package/dist/core/usage.js +226 -0
  120. package/dist/core/usage.js.map +1 -0
  121. package/dist/core/workspace-context.d.ts +136 -0
  122. package/dist/core/workspace-context.js +178 -0
  123. package/dist/core/workspace-context.js.map +1 -0
  124. package/dist/core/workspace-prompt.d.ts +7 -0
  125. package/dist/core/workspace-prompt.js +102 -0
  126. package/dist/core/workspace-prompt.js.map +1 -0
  127. package/dist/core/workspace-router.d.ts +61 -0
  128. package/dist/core/workspace-router.js +145 -0
  129. package/dist/core/workspace-router.js.map +1 -0
  130. package/dist/core/workspace.d.ts +85 -0
  131. package/dist/core/workspace.js +193 -0
  132. package/dist/core/workspace.js.map +1 -0
  133. package/dist/core/zones.d.ts +181 -0
  134. package/dist/core/zones.js +202 -0
  135. package/dist/core/zones.js.map +1 -0
  136. package/dist/env.d.ts +99 -0
  137. package/dist/env.js +271 -0
  138. package/dist/env.js.map +1 -0
  139. package/dist/index.d.ts +265 -0
  140. package/dist/index.js +197 -0
  141. package/dist/index.js.map +1 -0
  142. package/dist/kernel/kernel.d.ts +192 -0
  143. package/dist/kernel/kernel.js +751 -0
  144. package/dist/kernel/kernel.js.map +1 -0
  145. package/dist/lifecycle/hook-shape.d.ts +44 -0
  146. package/dist/lifecycle/hook-shape.js +66 -0
  147. package/dist/lifecycle/hook-shape.js.map +1 -0
  148. package/dist/lifecycle/runner.d.ts +177 -0
  149. package/dist/lifecycle/runner.js +372 -0
  150. package/dist/lifecycle/runner.js.map +1 -0
  151. package/dist/lifecycle/transcript.d.ts +27 -0
  152. package/dist/lifecycle/transcript.js +43 -0
  153. package/dist/lifecycle/transcript.js.map +1 -0
  154. package/dist/machine/allow.d.ts +65 -0
  155. package/dist/machine/allow.js +107 -0
  156. package/dist/machine/allow.js.map +1 -0
  157. package/dist/machine/delegation.d.ts +9 -0
  158. package/dist/machine/delegation.js +10 -0
  159. package/dist/machine/delegation.js.map +1 -0
  160. package/dist/machine/diagnostic.d.ts +14 -0
  161. package/dist/machine/diagnostic.js +2 -0
  162. package/dist/machine/diagnostic.js.map +1 -0
  163. package/dist/machine/lint-spec.d.ts +4 -0
  164. package/dist/machine/lint-spec.js +266 -0
  165. package/dist/machine/lint-spec.js.map +1 -0
  166. package/dist/machine/load-spec.d.ts +90 -0
  167. package/dist/machine/load-spec.js +120 -0
  168. package/dist/machine/load-spec.js.map +1 -0
  169. package/dist/machine/machine.d.ts +273 -0
  170. package/dist/machine/machine.js +551 -0
  171. package/dist/machine/machine.js.map +1 -0
  172. package/dist/machine/mount-grants.d.ts +25 -0
  173. package/dist/machine/mount-grants.js +24 -0
  174. package/dist/machine/mount-grants.js.map +1 -0
  175. package/dist/machine/slug.d.ts +14 -0
  176. package/dist/machine/slug.js +17 -0
  177. package/dist/machine/slug.js.map +1 -0
  178. package/dist/machine/spec-schema.d.ts +662 -0
  179. package/dist/machine/spec-schema.js +717 -0
  180. package/dist/machine/spec-schema.js.map +1 -0
  181. package/dist/machine/tool-names.d.ts +98 -0
  182. package/dist/machine/tool-names.js +144 -0
  183. package/dist/machine/tool-names.js.map +1 -0
  184. package/dist/machine/triggers.d.ts +114 -0
  185. package/dist/machine/triggers.js +165 -0
  186. package/dist/machine/triggers.js.map +1 -0
  187. package/dist/machine/types.d.ts +186 -0
  188. package/dist/machine/types.js +12 -0
  189. package/dist/machine/types.js.map +1 -0
  190. package/dist/machine/validate-spec.d.ts +42 -0
  191. package/dist/machine/validate-spec.js +29 -0
  192. package/dist/machine/validate-spec.js.map +1 -0
  193. package/dist/machine/variables.d.ts +196 -0
  194. package/dist/machine/variables.js +415 -0
  195. package/dist/machine/variables.js.map +1 -0
  196. package/dist/public/cli.d.ts +15 -0
  197. package/dist/public/cli.js +14 -0
  198. package/dist/public/cli.js.map +1 -0
  199. package/dist/public/messages.d.ts +33 -0
  200. package/dist/public/messages.js +33 -0
  201. package/dist/public/messages.js.map +1 -0
  202. package/dist/public/sandbox.d.ts +99 -0
  203. package/dist/public/sandbox.js +32 -0
  204. package/dist/public/sandbox.js.map +1 -0
  205. package/dist/public/spec.d.ts +147 -0
  206. package/dist/public/spec.js +149 -0
  207. package/dist/public/spec.js.map +1 -0
  208. package/dist/public/testing.d.ts +71 -0
  209. package/dist/public/testing.js +39 -0
  210. package/dist/public/testing.js.map +1 -0
  211. package/dist/rubrics/rubrics.d.ts +135 -0
  212. package/dist/rubrics/rubrics.js +145 -0
  213. package/dist/rubrics/rubrics.js.map +1 -0
  214. package/dist/runtime/contract.d.ts +73 -0
  215. package/dist/runtime/contract.js +96 -0
  216. package/dist/runtime/contract.js.map +1 -0
  217. package/dist/sandbox/assets/parts/core.js +22 -0
  218. package/dist/sandbox/assets/parts/lifecycle-hook.js +47 -0
  219. package/dist/sandbox/bridge.d.ts +16 -0
  220. package/dist/sandbox/bridge.js +95 -0
  221. package/dist/sandbox/bridge.js.map +1 -0
  222. package/dist/sandbox/executor.d.ts +46 -0
  223. package/dist/sandbox/executor.js +119 -0
  224. package/dist/sandbox/executor.js.map +1 -0
  225. package/dist/sandbox/imports.d.ts +33 -0
  226. package/dist/sandbox/imports.js +67 -0
  227. package/dist/sandbox/imports.js.map +1 -0
  228. package/dist/sandbox/prelude.d.ts +12 -0
  229. package/dist/sandbox/prelude.js +51 -0
  230. package/dist/sandbox/prelude.js.map +1 -0
  231. package/dist/sandbox/ptc-gateway.d.ts +104 -0
  232. package/dist/sandbox/ptc-gateway.js +167 -0
  233. package/dist/sandbox/ptc-gateway.js.map +1 -0
  234. package/dist/sandbox/runtime.d.ts +59 -0
  235. package/dist/sandbox/runtime.js +51 -0
  236. package/dist/sandbox/runtime.js.map +1 -0
  237. package/dist/sandbox/tools.d.ts +34 -0
  238. package/dist/sandbox/tools.js +147 -0
  239. package/dist/sandbox/tools.js.map +1 -0
  240. package/dist/sessions/operations.d.ts +79 -0
  241. package/dist/sessions/operations.js +121 -0
  242. package/dist/sessions/operations.js.map +1 -0
  243. package/dist/sessions/resolve.d.ts +97 -0
  244. package/dist/sessions/resolve.js +145 -0
  245. package/dist/sessions/resolve.js.map +1 -0
  246. package/dist/sessions/resume.d.ts +242 -0
  247. package/dist/sessions/resume.js +288 -0
  248. package/dist/sessions/resume.js.map +1 -0
  249. package/dist/sessions/scope.d.ts +99 -0
  250. package/dist/sessions/scope.js +145 -0
  251. package/dist/sessions/scope.js.map +1 -0
  252. package/dist/sessions/summary.d.ts +65 -0
  253. package/dist/sessions/summary.js +56 -0
  254. package/dist/sessions/summary.js.map +1 -0
  255. package/dist/testing/assertions.d.ts +30 -0
  256. package/dist/testing/assertions.js +231 -0
  257. package/dist/testing/assertions.js.map +1 -0
  258. package/dist/testing/case-document.d.ts +141 -0
  259. package/dist/testing/case-document.js +51 -0
  260. package/dist/testing/case-document.js.map +1 -0
  261. package/dist/testing/case-schema.d.ts +29 -0
  262. package/dist/testing/case-schema.js +519 -0
  263. package/dist/testing/case-schema.js.map +1 -0
  264. package/dist/testing/discovery.d.ts +10 -0
  265. package/dist/testing/discovery.js +24 -0
  266. package/dist/testing/discovery.js.map +1 -0
  267. package/dist/testing/driver.d.ts +78 -0
  268. package/dist/testing/driver.js +117 -0
  269. package/dist/testing/driver.js.map +1 -0
  270. package/dist/testing/grade.d.ts +116 -0
  271. package/dist/testing/grade.js +261 -0
  272. package/dist/testing/grade.js.map +1 -0
  273. package/dist/testing/interpreter.d.ts +55 -0
  274. package/dist/testing/interpreter.js +103 -0
  275. package/dist/testing/interpreter.js.map +1 -0
  276. package/dist/testing/mock-middleware.d.ts +5 -0
  277. package/dist/testing/mock-middleware.js +33 -0
  278. package/dist/testing/mock-middleware.js.map +1 -0
  279. package/dist/testing/runner.d.ts +205 -0
  280. package/dist/testing/runner.js +266 -0
  281. package/dist/testing/runner.js.map +1 -0
  282. package/dist/testing/target.d.ts +27 -0
  283. package/dist/testing/target.js +21 -0
  284. package/dist/testing/target.js.map +1 -0
  285. package/dist/validate/validate.d.ts +41 -0
  286. package/dist/validate/validate.js +669 -0
  287. package/dist/validate/validate.js.map +1 -0
  288. package/dist/workflow/agent-tools.d.ts +10 -0
  289. package/dist/workflow/agent-tools.js +10 -0
  290. package/dist/workflow/agent-tools.js.map +1 -0
  291. package/dist/workflow/checkpointer.d.ts +52 -0
  292. package/dist/workflow/checkpointer.js +200 -0
  293. package/dist/workflow/checkpointer.js.map +1 -0
  294. package/dist/workflow/control-tools.d.ts +174 -0
  295. package/dist/workflow/control-tools.js +468 -0
  296. package/dist/workflow/control-tools.js.map +1 -0
  297. package/dist/workflow/governance.d.ts +104 -0
  298. package/dist/workflow/governance.js +546 -0
  299. package/dist/workflow/governance.js.map +1 -0
  300. package/dist/workflow/middleware.d.ts +85 -0
  301. package/dist/workflow/middleware.js +283 -0
  302. package/dist/workflow/middleware.js.map +1 -0
  303. package/dist/workflow/on-error.d.ts +25 -0
  304. package/dist/workflow/on-error.js +58 -0
  305. package/dist/workflow/on-error.js.map +1 -0
  306. package/dist/workflow/parks.d.ts +46 -0
  307. package/dist/workflow/parks.js +513 -0
  308. package/dist/workflow/parks.js.map +1 -0
  309. package/dist/workflow/paths.d.ts +67 -0
  310. package/dist/workflow/paths.js +108 -0
  311. package/dist/workflow/paths.js.map +1 -0
  312. package/dist/workflow/prompt-cache.d.ts +70 -0
  313. package/dist/workflow/prompt-cache.js +103 -0
  314. package/dist/workflow/prompt-cache.js.map +1 -0
  315. package/dist/workflow/prompt-pruning.d.ts +20 -0
  316. package/dist/workflow/prompt-pruning.js +83 -0
  317. package/dist/workflow/prompt-pruning.js.map +1 -0
  318. package/dist/workflow/render-prompt.d.ts +45 -0
  319. package/dist/workflow/render-prompt.js +140 -0
  320. package/dist/workflow/render-prompt.js.map +1 -0
  321. package/dist/workflow/runtime-config.d.ts +7 -0
  322. package/dist/workflow/runtime-config.js +9 -0
  323. package/dist/workflow/runtime-config.js.map +1 -0
  324. package/dist/workflow/session-artifacts.d.ts +90 -0
  325. package/dist/workflow/session-artifacts.js +134 -0
  326. package/dist/workflow/session-artifacts.js.map +1 -0
  327. package/dist/workflow/session-view.d.ts +31 -0
  328. package/dist/workflow/session-view.js +94 -0
  329. package/dist/workflow/session-view.js.map +1 -0
  330. package/dist/workflow/snapshot.d.ts +14 -0
  331. package/dist/workflow/snapshot.js +97 -0
  332. package/dist/workflow/snapshot.js.map +1 -0
  333. package/dist/workflow/state.d.ts +347 -0
  334. package/dist/workflow/state.js +322 -0
  335. package/dist/workflow/state.js.map +1 -0
  336. package/dist/workflow/sub-workflow.d.ts +174 -0
  337. package/dist/workflow/sub-workflow.js +392 -0
  338. package/dist/workflow/sub-workflow.js.map +1 -0
  339. package/dist/workflow/tool-service.d.ts +48 -0
  340. package/dist/workflow/tool-service.js +291 -0
  341. package/dist/workflow/tool-service.js.map +1 -0
  342. package/dist/workflow/turn-boundary.d.ts +39 -0
  343. package/dist/workflow/turn-boundary.js +128 -0
  344. package/dist/workflow/turn-boundary.js.map +1 -0
  345. package/dist/workflow/turn-runner.d.ts +40 -0
  346. package/dist/workflow/turn-runner.js +122 -0
  347. package/dist/workflow/turn-runner.js.map +1 -0
  348. package/dist/workflow/workflow-tools.d.ts +46 -0
  349. package/dist/workflow/workflow-tools.js +90 -0
  350. package/dist/workflow/workflow-tools.js.map +1 -0
  351. package/package.json +119 -0
@@ -0,0 +1,626 @@
1
+ # Wiring @archmax-ai/harness into a backend — integration reference
2
+
3
+ How to embed the `@archmax-ai/harness` package in a service so a worker can
4
+ **execute** workflows and an API/frontend can **visualize** run state. All names
5
+ below are the real public API (`src/index.ts`); confirm against the installed
6
+ package's `dist/index.d.ts`.
7
+
8
+ ## Contents
9
+
10
+ - [Install (registry & local tarball)](#install)
11
+ - [Public exports](#public-exports)
12
+ - [createAgent options](#createworkflowagent-options)
13
+ - [Agent](#workflowruntime)
14
+ - [Running a workflow](#running-a-workflow)
15
+ - [Human-in-the-loop](#human-in-the-loop)
16
+ - [Lifecycle events (live visualization)](#lifecycle-events)
17
+ - [Session artifacts (historical visualization)](#run-artifacts)
18
+ - [Model configuration](#model-configuration)
19
+ - [Custom backends](#custom-backends)
20
+ - [Cases against your agent](#cases-against-your-agent)
21
+ - [Suggested worker / API / frontend split](#suggested-split)
22
+
23
+ ---
24
+
25
+ ## Install
26
+
27
+ **Registry** (once published): `npm i @archmax-ai/harness`.
28
+
29
+ **Local / pre-publish** — install exactly what the registry would ship (a real copy
30
+ in `node_modules`, not a symlink), so behavior matches production:
31
+
32
+ ```bash
33
+ # in the harness repo
34
+ npm run build
35
+ npm pack --pack-destination /tmp # → /tmp/archmax-ai-harness-<version>.tgz
36
+
37
+ # in the consuming service
38
+ npm add /tmp/archmax-ai-harness-<version>.tgz
39
+ # or pnpm --filter <pkg> add /tmp/archmax-ai-harness-<version>.tgz
40
+ ```
41
+
42
+ The published tarball contains only `dist/` + `README.md` (the package `files`
43
+ allowlist), so `dist/index.d.ts` types travel with it — a shared types package can
44
+ re-export the run-artifact/event shapes for an API/frontend without importing the
45
+ runtime. Because the version rarely changes during development, `remove` then `add`
46
+ (or prune the store) so a repack of the same version actually reinstalls.
47
+
48
+ **This skill ships inside the package** (staged into `dist/authoring-skill/archmax-harness/`):
49
+ resolve it from the install via the `BUNDLED_AUTHORING_SKILL_DIR` export — the
50
+ `dist/authoring-skill` directory holding `archmax-harness/`, so this file is
51
+ `<BUNDLED_AUTHORING_SKILL_DIR>/archmax-harness/SKILL.md` — e.g.
52
+ `npx skills add ./node_modules/@archmax-ai/harness/dist/authoring-skill/archmax-harness`.
53
+ (`BUNDLED_SKILLS_DIR` is a deprecated alias with the same value, kept one
54
+ release.) Prefer this over
55
+ syncing a copy from a source checkout, so the skill can never drift from the
56
+ installed SDK's validator. Tooling that needs the install root without importing
57
+ the runtime can use `require.resolve("@archmax-ai/harness/package.json")` (exposed in the
58
+ `exports` map).
59
+
60
+ ## Public exports
61
+
62
+ From `@archmax-ai/harness` (`src/index.ts`):
63
+
64
+ | Export | Kind | Purpose |
65
+ | --- | --- | --- |
66
+ | `createAgent` | fn | Assemble a runnable workflow-governed agent |
67
+ | `Agent` | type | Returned runtime (`graph`, `decide`, `deliver`, `resolveSession`, `runs`, `emitRunArtifacts`, `dispose`, `resolveTrigger`) |
68
+ | `CreateAgentParams` | type | Assembly options |
69
+ | `DecideOutcome` | type | Return of `decide()` |
70
+ | `DeliverOutcome`, `TriggerDelivery` | type | Argument / return of `deliver()` |
71
+ | `WorkflowLoadError` | class | Thrown when the workflow spec (`workflow.yaml`) is missing/invalid (fails closed) |
72
+ | `DEFAULT_WORKFLOW` | const | `"order-lookup"` |
73
+ | `BUNDLED_AUTHORING_SKILL_DIR` | const | The packaged `dist/authoring-skill` directory holding `archmax-harness/` (`<dir>/archmax-harness/SKILL.md`). `BUNDLED_SKILLS_DIR` is a deprecated alias with the same value. The example workspace is not shipped in `dist/`; clone the repo to use it. |
74
+ | `WORKFLOW_STATUSES` | const | `running` \| `completed` \| `rejected` \| `awaiting_decision` (`awaitingDecision`) \| `awaiting_input` (`awaitingInput`) |
75
+ | `isFinished`, `classifyStatus` | fn | The open/finished partition — a parked session is **open** |
76
+ | `WorkflowLifecycleEvent`, `WorkflowEventHandler` | type | Event stream types |
77
+ | `createWorkflowEventEmitter`, `renderEventLine` | fn | Event emitter + console formatter |
78
+ | `createWorkspaceContext` | fn | Compose the workspace backends (session zone + mounts + authoring backend) |
79
+ | `createFilesystemSessionStore`, `createBackendSessionStore`, `createMemorySessionStore` | fn | Run-store factories (physical storage for the session zone) |
80
+ | `SessionStoreRequiredError`, `SessionStoreCapabilityError` | class | Assembly / capability errors for run storage |
81
+ | `workflowStateSchema`, `workflowPaths`, `sessionPaths`, `runArtifactPaths` | schema/fn | State schema + path helpers |
82
+ | `runTests`, `RunTestsOptions`, `CaseResult` | fn/type | Run a workflow's cases — [against your own agent](#cases-against-your-agent) |
83
+
84
+ ## createAgent options
85
+
86
+ All optional (`CreateAgentParams`, `src/assembly/index.ts`):
87
+
88
+ | Option | Type | Notes |
89
+ | --- | --- | --- |
90
+ | `rootDir` | `string` | Workspace root for the default filesystem backend. Defaults to cwd. |
91
+ | `workflow` | `string` | Named workflow under `workflows/<name>/`. |
92
+ | `trigger` | `TriggerInput` | `{ id, args? }`; defaults to `{ id: "manual" }`. Selects the start state. |
93
+ | `model` | `BaseChatModel` | Defaults to the env-configured OpenAI-compatible model. Inject your own to bypass env. |
94
+ | `backend` | `BackendProtocolV2` | Serves the authored workspace. Defaults to a `FilesystemBackend` over `rootDir`. |
95
+ | `authoring` | `BackendProtocolV2` | Serves the **authoring plane** — `workflows/**` (machine specs including the rubrics their states declare, `WORKFLOW.md`, `hooks/`, `tests/`) — to the runtime only. Never a route in the agent's workspace, so no tool call or PTC call can reach it. Defaults to `backend` when you supply one, else a `FilesystemBackend` over the resolved root. Handing it to a **writable** mount throws `AuthoringBackendExposedError`; a read-only mount may share it. |
96
+ | `mounts` | `Record<string, MountSpec>` | Authored mounts as a `CompositeBackend` route table: key → backend, or `{ backend, readOnly, governed, searchable }`. Trailing slash = directory mount; no slash = exact-path file mount (`"/AGENTS.md"`). Read-only unless declared otherwise. `governed: true` hands the spec's `mounts` block the decision of **which states** may reach it (closed by default, like a skill bundle) and whether each may write there; a mount not so declared is visible in every state exactly as today, so a table that marks nothing behaves unchanged. `readOnly` is a **ceiling** the spec cannot lift: a grant may narrow a writable mount to reads in a state, never open a read-only one. A key may be several segments deep (`"/catalogs/eu/"`); its **first** segment is what is reserved, so `/workflows/x/` fails as `/workflows/` does. Omitted on the default backend: `defaultMounts(rootDir)` (the conventional table — `/skills/`, `/.platform/`, `/AGENTS.md`, none governed — extend with `{ ...defaultMounts(root), "/templates/": … }`). Omitted with a custom `backend`: nothing authored is served; expose subtrees with `mountSubtree(backend, "skills")`. A key colliding with a run area — or naming the authoring-plane prefix (`/workflows/`) — throws `MountCollisionError`. `searchable: false` declares a mount the runtime never searches on its own initiative: a root-wide `grep`/`glob` fans out over the other mounts only, while a search the agent addresses at the mount (or a path inside it) still reaches its backend and returns the backend's own answer — matches or `{ error }` — verbatim. Use it for a backend that must refuse searches (a remote folder served live). Listing and reading are unchanged, the prompt marks it "browse only", names arrive as `MountPrefixes.unsearchable`, and it is ignored on a file mount. |
97
+ | `sessionStore` | `SessionStore` | Physical storage for run state (checkpoints, artifacts, the per-session `scratchpad/`). Zero-config default: `createFilesystemSessionStore({ dir: "<rootDir>/sessions" })`. Required with a custom `backend` (else `SessionStoreRequiredError`). Build with `createBackendSessionStore({ backend, prefix? })` for S3-style storage or `createMemorySessionStore()` for ephemeral runs. |
98
+ | `systemPrompt` | `string` | Appended after workspace `AGENTS.md`. |
99
+ | `checkpointer` | `BaseCheckpointSaver` | Custom-adapter escape hatch; takes precedence over the session store for checkpoint persistence. Defaults to a durable `BackendCheckpointSaver` writing through the session store. Use `MemorySaver` for ephemeral runs. |
100
+ | `middleware` | `AgentMiddleware[]` | Extra middleware appended after workflow instrumentation. |
101
+ | `onEvent` | `WorkflowEventHandler` | Subscribe to all lifecycle diagnostics; suppresses console output when set. |
102
+ | `promptCache` | `PromptCacheOptions` | `{ enabled?, ttl?: "5m" \| "1h" }`. Provider prompt caching for the stable prefix; on by default. Falls back to `settings.prompt_cache`, then `ARCHMAX_PROMPT_CACHE`/`_TTL`. |
103
+ | `pricing` | `PricingTable` | USD per 1M tokens, keyed by model id (`default` matches any): `{ input?, output?, cacheRead?, cacheWrite? }`. Looked up by the id the response reported, else the id the runtime was configured to run — so a keyed table prices a workload behind a proxy that echoes no model back. Input rate applies to the input tokens the cache did not serve. Makes `costUsd` appear on usage events, run metadata, and the CLI footer. Falls back to `ARCHMAX_PRICE_*`. Unpriced → tokens only. |
104
+
105
+ Fails closed: throws `WorkflowLoadError` if the named workflow's `workflow.yaml`
106
+ is missing or has no valid machine spec (never silently runs ungoverned; a
107
+ `WORKFLOW.md` carrying frontmatter with no `workflow.yaml` — the removed
108
+ single-file layout — is a load error with migration guidance).
109
+
110
+ ## Agent
111
+
112
+ ```ts
113
+ interface Agent {
114
+ graph: /* LangGraph runnable */;
115
+ workflow: string;
116
+ runtimeContract: ResolvedRuntimeContract;
117
+ resolveTrigger(trigger?: TriggerInput): ResolvedTrigger;
118
+ emitRunArtifacts(runId: string, trajectory: Trajectory): Promise<string | null>;
119
+ runs: { // run handles over the configured session store
120
+ list(): Promise<SessionSummary[]>; // [] when the store/checkpointer can't list
121
+ get(sessionId: string): Promise<SessionSummary | null>;
122
+ delete(sessionId: string): Promise<boolean>; // throws SessionStoreCapabilityError
123
+ };
124
+ decide(sessionId: string, resolution: DecisionResolution): Promise<DecideOutcome>;
125
+ dispose(sessionId: string): void;
126
+ }
127
+ ```
128
+
129
+ ## Running a workflow
130
+
131
+ ```ts
132
+ import { createAgent, WORKFLOW_STATUSES } from "@archmax-ai/harness";
133
+
134
+ const agent = await createAgent({ workflow, onEvent, workspace: { rootDir } });
135
+ const sessionId = `run-${runId}`;
136
+
137
+ try {
138
+ const result = await agent.invoke(
139
+ { messages: [{ role: "user", content: prompt }] },
140
+ { configurable: { thread_id: sessionId }, recursionLimit: 50 },
141
+ );
142
+ // result: { messages, status?, workflowState?, pendingDecision? }
143
+ if (result.status === WORKFLOW_STATUSES.awaitingDecision) {
144
+ // parked — see Human-in-the-loop
145
+ } else {
146
+ return lastAssistantText(result.messages);
147
+ }
148
+ } finally {
149
+ agent.dispose(sessionId); // cleans up sandbox/PTC state for the session
150
+ }
151
+ ```
152
+
153
+ Use `agent.stream(...)` instead of `invoke` when you want to record a
154
+ trajectory or push incremental updates.
155
+
156
+ `lastAssistantText` walks `result.messages` from the end and returns the last
157
+ assistant/AI message's text.
158
+
159
+ ## Multi-turn conversations (chat history)
160
+
161
+ `agent.invoke` accepts an **array of role-tagged messages**, not just one user
162
+ string — the `messages` channel is a LangChain `add_messages` channel, so
163
+ whatever you pass is appended to the session's transcript. There is no need to
164
+ concatenate a prior chat into one giant user prompt; give the model real turns.
165
+
166
+ **Preferred — session persistence.** Sessions are durable by default (the
167
+ `BackendCheckpointSaver` writes each turn to the session store). Drive a live
168
+ conversation by re-invoking the **same `thread_id`** once per user message,
169
+ sending only the new message each time — prior turns are already in the
170
+ checkpoint:
171
+
172
+ ```ts
173
+ // turn 1
174
+ await agent.invoke(
175
+ { messages: [{ role: "user", content: "Look up order 1234" }] },
176
+ { configurable: { thread_id: "chat-42" }, recursionLimit: 50 },
177
+ );
178
+ // turn 2 — SAME thread_id; only the new message
179
+ await agent.invoke(
180
+ { messages: [{ role: "user", content: "And when did it ship?" }] },
181
+ { configurable: { thread_id: "chat-42" }, recursionLimit: 50 },
182
+ );
183
+ ```
184
+
185
+ The `init` state re-runs on each turn, resetting `workflowState` to the trigger's
186
+ start state while **preserving the accumulated messages** — exactly right for
187
+ chat: each user message re-enters the workflow with full history retained.
188
+
189
+ **Alternative — seed prior history on the first invoke.** When the transcript
190
+ lives in your own store (not a harness session), pass it as the initial `messages`
191
+ array with the newest user turn last:
192
+
193
+ ```ts
194
+ await agent.invoke(
195
+ {
196
+ messages: [
197
+ { role: "user", content: "Test" },
198
+ { role: "assistant", content: "Test complete…" },
199
+ { role: "user", content: "who are you?" },
200
+ { role: "assistant", content: "I'm an agent that…" },
201
+ { role: "user", content: "what was my first message?" }, // the new turn
202
+ ],
203
+ },
204
+ { configurable: { thread_id: "chat-42" }, recursionLimit: 50 },
205
+ );
206
+ ```
207
+
208
+ Gotchas:
209
+
210
+ - **A hook reads the transcript from `messages`, newest last.** A hook that keys
211
+ off "the current request" should take the *last* `user` entry, not the first —
212
+ the first is the message that opened the session. (A grading rubric still
213
+ receives the compact `userRequest`/`history` payload its rubric is written
214
+ against; there `userRequest` is the *first* user message.)
215
+ - **A definition edit is adopted, not refused.** A session takes its next turn
216
+ under the `workflow.yaml` in force now; the recorded `specHash` says which
217
+ definition each turn ran under but gates nothing. A turn positioned in a state
218
+ the edit removed reopens at its trigger's entry state rather than failing.
219
+ - **Seed assistant turns as text only.** Don't fabricate dangling `tool_calls`
220
+ in seeded history, or the provider may reject the turn.
221
+ - **Not every message in a session's transcript is a person's.** The runtime
222
+ writes **runtime notes** of its own — `[decision]`, `[event]`, `[error]`,
223
+ `[after]`, `[sub-workflow: …]` — carried as a synthetic `archmax_note` tool call
224
+ and its result, so a model cannot read them as a person speaking. Ask
225
+ `isRuntimeNote(message)` / `runtimeNoteKind(message)` rather than inferring
226
+ authorship from role or a `[bracket]` prefix: a turn's lower bound is a human
227
+ message **or** a note, and a transcript renderer should draw a note as a
228
+ runtime line, not as the user's own bubble. The one message a person really
229
+ sends into a running session — a reply to a run parked at a human state — is an
230
+ ordinary human message with no marker.
231
+
232
+ ```ts
233
+ import { isRuntimeNote, runtimeNoteKind } from "@archmax-ai/harness";
234
+
235
+ const opensTurn = (m: unknown) => isRuntimeNote(m) || m.role === "user";
236
+ const label = (m: unknown) => runtimeNoteKind(m); // "decision" | "event" | … | null
237
+ ```
238
+
239
+ ## Human-in-the-loop
240
+
241
+ ```ts
242
+ if (result.status === WORKFLOW_STATUSES.awaitingDecision && result.pendingDecision) {
243
+ const { state, transitions, evidence } = result.pendingDecision;
244
+ // Present `transitions` (each { to, description?, type? }) + evidence to a human.
245
+ // `evidence` is the state's declared paths followed by whatever the advancing
246
+ // agent attached via `archmax_advance({ evidence })` — one merged list, no
247
+ // host-side assembly, and no need to re-read the spec.
248
+ // When they pick:
249
+ const outcome = await agent.workflow.decide(sessionId, { target: chosenTo, comment });
250
+ // DecideOutcome: { status?, workflowState?, reparked, state?, messages }
251
+ if (outcome.reparked) { /* parked again at another human state */ }
252
+ }
253
+ ```
254
+
255
+ `decide` throws `SessionNotParkedError` if the session isn't awaiting a decision, and
256
+ `InvalidDecisionTargetError` if `target` isn't a declared transition of the parked
257
+ state. `sessions.list()` enumerates durable sessions (empty with a `MemorySaver` or a non-listable session store).
258
+
259
+ ## Event-in-the-loop: a run that parked itself
260
+
261
+ The agent can park the run with `archmax_wait({ reason })` — in any state, terminal
262
+ ones included — when the work cannot continue without something from outside. The
263
+ session's status becomes `awaiting_input` (classified **open**, never finished) and
264
+ `result.pendingInput` carries `{ state, title?, reason, parkedAt }`: the state it
265
+ stopped in and, in its own words, what it is waiting for.
266
+
267
+ ```ts
268
+ if (result.status === WORKFLOW_STATUSES.awaitingInput && result.pendingInput) {
269
+ const { state, reason } = result.pendingInput; // show "waiting in <state>: <reason>"
270
+ }
271
+
272
+ // When the event arrives, deliver it. The run continues in the state it parked in;
273
+ // the trigger id becomes its current trigger and the variables arrive locked.
274
+ const outcome = await agent.workflow.deliver(sessionId, {
275
+ trigger: { id: "email_reply" },
276
+ variables: { reply_body: "It's ORD-1001." },
277
+ });
278
+ // DeliverOutcome: DecideOutcome + { variables, parkedChannel? }
279
+ if (outcome.reparked) { /* parked again — outcome.parkedChannel says which channel */ }
280
+ ```
281
+
282
+ ### Waking a scheduled park
283
+
284
+ A park may declare when it wants to be resumed (`archmax_wait({ reason, until: "1d" })`),
285
+ which lands on the record, the summary, and the park event as an absolute
286
+ `resumeAt`. **The SDK schedules nothing** — no timer, no cron — so this is your
287
+ job, and it is a query:
288
+
289
+ ```ts
290
+ const now = new Date().toISOString();
291
+ for (const t of await agent.sessions.list()) {
292
+ if (t.status === WORKFLOW_STATUSES.awaitingInput && t.resumeAt && t.resumeAt <= now) {
293
+ await agent.workflow.deliver(t.sessionId, { trigger: { id: "timer" }, variables: { now } });
294
+ }
295
+ }
296
+ ```
297
+
298
+ A duplicate firing is safe: `deliver` refuses a session that is no longer parked. A
299
+ `resumeAt` gates nothing — an event arriving earlier resumes the park normally — and
300
+ a state that polls can cap its own retry loop with `budget.maxParks`, whose overrun
301
+ routes through the state's `on_error`.
302
+
303
+ `deliver` throws `SessionNotAwaitingInputError` if the session isn't parked awaiting
304
+ an event and `MissingDeliveryTriggerError` if no id is supplied. The id is
305
+ **recorded, never matched**: any trigger resumes a park, so there is no awaited-id
306
+ list to check against — an id no state declares is deliverable exactly like a
307
+ declared one. `resolveSession({ trigger, variables })` tells you which of
308
+ the two a firing is — a `turn` to invoke, or a `resume` to deliver into — always on
309
+ the conversation's own id.
310
+
311
+ An event that must **never start** a run is therefore declared nowhere in the spec:
312
+ every trigger a state declares starts a session at that state. Name the session
313
+ yourself — `send(sessionId, { delivery })` / `deliver(sessionId, …)` — or pass
314
+ `sessionPath` with the firing (`resolveSession({ trigger, variables, sessionPath })`)
315
+ and let the runtime read the id out of the firing's own variables. A firing that
316
+ names neither, on a trigger no state declares, throws
317
+ `UnknownSessionTriggerError`: there is nowhere for it to go.
318
+
319
+ One turn per invoke, on **one** session. A finished session re-invoked with a new
320
+ message takes its next turn on the same id, continuing in the state the previous
321
+ turn ended in — the position, variables, transcript and files are already there, so
322
+ **never seed a previous transcript into the `messages` channel**. Pass only the new
323
+ message.
324
+
325
+ The runtime does not reposition a later turn, so nothing is injected into the
326
+ transcript to explain a jump. When a turn needs a path the current state cannot
327
+ reach, the agent calls `archmax_reset` to return to the state the conversation began
328
+ in (available in every state). To continue *mid-state* instead — inside the state
329
+ that stopped, with the arrival in its transcript — the turn must park rather than
330
+ finish.
331
+
332
+ ## Lifecycle events
333
+
334
+ Pass `onEvent`; every `WorkflowLifecycleEvent` carries a `level`
335
+ (`info`/`warn`/`error`) plus a typed payload. Map these to a live run UI:
336
+
337
+ | Event `type` | Meaning |
338
+ | --- | --- |
339
+ | `state-enter` / `state-leave` | state entered / left (`{ state, next? }`) |
340
+ | `advance` | transition committed (`{ from, to, reason?, callId? }` — `callId` names the `archmax_advance` call that drove it; absent on the turn's opening arrival) |
341
+ | `hook-start` / `hook-output` / `hook-passed` / `hook-verdict` / `hook-rejected` | lifecycle hook activity + verdict (`ok`/`correct`/`veto`) |
342
+ | `parked` / `decided` | human state parked / resolved (`{ state, sessionId, awaiting, to? }` — a human park carries no `callId`, since no call asked for it) |
343
+ | `parked` (`awaiting: "input"`) / `delivered` | the agent parked the run (`{ state, sessionId, reason, resumeAt?, callId }` — the `archmax_wait` call) / an event resumed it (`{ state, trigger, to }`, where `to` is the same state) |
344
+ | `agent-text` | complete assistant message in a state (`{ state, text, messageId }` — always the id the message is stored under; absent only on a `partial: true` event from a failed turn) |
345
+ | `agent-text-delta` | streaming text chunk (`{ state, text, messageId? }`) — flows for every run, even when the graph is driven with `invoke` |
346
+ | `tool-called` / `tool-result` / `tool-blocked` | tool passed governance (`callId`, `args`) / settled (`callId`, `status`, `durationMs`, `output` preview) / denied. **Every** governed call, `archmax_advance` included — so a UI drawing a row per call draws one per transition; filter it if you already draw transitions from `advance`/`state-leave` |
347
+ | `rubric-start` / `rubric-result` | grading-rubric dispatch bracketed by `dispatchId`, with the rubric's `name` |
348
+ | `model-usage` | per model call provider token usage: `inputTokens` (the total, of which the cache counts are a breakdown), `outputTokens`, `cacheReadTokens`, `cacheCreationTokens`, `model?` (the id the call was priced against), `costUsd?` |
349
+ | `prompt-shaping` | assembly-time payload summary: resolved `profile`, prompt-cache mechanism, `withheld` built-ins |
350
+ | `skills-loaded`, `hooks-summary`, `graph-topology`, `workflow-reset`, `warning` | assembly-time diagnostics |
351
+
352
+ For a browser client, forward these over SSE/WebSocket keyed by `sessionId`. To
353
+ render a live chat transcript: accumulate `agent-text-delta` into a bubble
354
+ keyed by `messageId`, replace it with the final `agent-text` bearing the same
355
+ `messageId`, and interleave tool cards from `tool-called`/`tool-result` paired
356
+ by `callId` (order everything by `seq`).
357
+
358
+ Building a **durable record** rather than a live view? The ids join the stream to
359
+ the stored messages exactly: `callId` equals the issuing AI message's
360
+ `tool_calls[].id` and the settling `ToolMessage.tool_call_id`, and
361
+ `agent-text.messageId` equals the assistant message's `id`. Every event a call
362
+ *causes* carries that call's id too (`advance`, `parked`, `variables-set`,
363
+ `title-set`, and the sub-workflow pair's `toolCallId`), so the events one call
364
+ produced group from ids alone — no scanning back to a message boundary. An event
365
+ of those types with no `callId` is one the runtime caused, not a call: a turn
366
+ opening, a human park, run-start seeding.
367
+
368
+ `title-set` is the one event carrying a variable's **value** — the reserved
369
+ `title`, whenever it changes. `variables-set` still carries names only; the value
370
+ rides its own event so that rule needs no exception, and it is safe there because
371
+ a title is bounded to one short line by its write check. Indexing a run's title on
372
+ your own record is a handler for this event and nothing else — no checkpoint read,
373
+ which matters when you install your own checkpointer.
374
+
375
+ ### Reading tokens and cost
376
+
377
+ Usage figures are the **provider's own** (LangChain `usage_metadata`), not
378
+ estimates — including how many input tokens were served from the prompt cache.
379
+ Use the exported tracker instead of summing events yourself:
380
+
381
+ ```ts
382
+ import { createAgent, createUsageTracker } from "@archmax-ai/harness";
383
+
384
+ // Wrap your own subscriber, or omit `onEvent` if you have none.
385
+ const usage = createUsageTracker({ onEvent: forwardToClient });
386
+ const agent = await createAgent({ onEvent: usage.handler, /* … */ });
387
+
388
+ await agent.invoke(input, { configurable: { thread_id: sessionId } });
389
+
390
+ const totals = usage.totals(sessionId);
391
+ // { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUsd? }
392
+ usage.bySession(); // Map<sessionId, UsageSummary> for concurrent runs
393
+ usage.reset(sessionId); // drop a finished run's totals
394
+ ```
395
+
396
+ Rising `cacheReadTokens` is how you confirm prompt caching is actually working;
397
+ `costUsd` is present only when pricing is configured — report tokens rather than a
398
+ guessed cost when it is absent. `formatUsage`, `addSummaries`, `emptyUsage` and
399
+ `hasUsage` are exported for rendering and combining summaries; the extraction and
400
+ pricing internals are not part of the public surface.
401
+
402
+ ### Reading a run's cost
403
+
404
+ A run's usage is **checkpointed**, so a session handle answers it for a run that
405
+ parked and resumed — including in another process:
406
+
407
+ ```ts
408
+ const summary = await agent.sessions.get(sessionId);
409
+ summary?.usage;
410
+ // { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUsd? }
411
+ ```
412
+
413
+ `costUsd` appears only when pricing is configured; without it, tokens are
414
+ reported and cost is omitted, never guessed. A parked run reports what it has
415
+ spent so far and keeps accumulating on resume. The same totals land in
416
+ `sessions/<sessionId>/artifacts/metadata.json` as `usage`, and `createUsageTracker()`
417
+ gives the same figure live in process.
418
+
419
+ ### Measuring anything else — fold the stream
420
+
421
+ The SDK keeps no metrics ledger. Tool calls, governance refusals, the path a run
422
+ took, corrections and vetoes, rubric dispatches, and how long a session
423
+ sat waiting for a person are all already on the typed event stream, and a backend
424
+ counts what it needs:
425
+
426
+ ```ts
427
+ const tally = { toolCalls: 0, toolBlocks: 0, path: [] as string[] };
428
+ const agent = await createAgent({
429
+ onEvent: (e) => {
430
+ forwardToClient(e);
431
+ if (e.type === "tool-called") tally.toolCalls++;
432
+ if (e.type === "tool-blocked") tally.toolBlocks++;
433
+ if (e.type === "state-enter") tally.path.push(e.state);
434
+ },
435
+ /* … */
436
+ });
437
+ ```
438
+
439
+ Two properties make this the right home for it: the events are the ones the
440
+ runtime acts on, so a fold cannot drift from behavior the way a parallel ledger
441
+ can; and a backend counts what it cares about — a per-tenant tool budget, a
442
+ per-state SLA — rather than what the SDK guessed.
443
+
444
+ A fold is a **live view**: it sees only events this process observed. Cost is the
445
+ deliberate exception, because it is checkpointed.
446
+
447
+ ## Session artifacts
448
+
449
+ Each run persists under its own folder in the session store — which is also the
450
+ agent's workspace root for that run (`sessions/<sessionId>/` on the filesystem default):
451
+
452
+ ```
453
+ sessions/<sessionId>/
454
+ checkpoints/ # LangGraph checkpoint records (durable resume; also
455
+ # the sole record of a parked human decision)
456
+ scratchpad/ # the run's working area — intermediate files AND the
457
+ # artifacts a state produces (agent-visible as
458
+ # `scratchpad/…`; the only such area)
459
+ large_tool_results/ # runtime-offloaded oversized tool results (agent reads only)
460
+ conversation_history/ # runtime-offloaded history (agent reads only)
461
+ artifacts/
462
+ graph.json # SerializedGraph (topology; includes mermaid)
463
+ graph.mmd # Mermaid diagram
464
+ trajectory.json # Trajectory (per-state messages + tool calls)
465
+ trail.json # Audit trail (committed transitions + rationale)
466
+ variables.json # The run's variables: name -> { value, locked }.
467
+ # `locked` is the attribution: locked = host-established
468
+ # (variables, a delivery's seeds, the built-in
469
+ # `trigger`), unlocked = set by the agent. Written for a
470
+ # governed run; an empty store still writes `{}`.
471
+ metadata.json # RunMetadata (runtime contract, package version,
472
+ # specHash, and the run's `usage` summary — tokens
473
+ # by kind plus costUsd when priced)
474
+ ```
475
+
476
+ Schemas:
477
+
478
+ ```ts
479
+ interface SerializedGraph {
480
+ nodes: string[];
481
+ edges: { source: string; target: string; conditional: boolean; label?: string }[];
482
+ entry?: string; finals: string[]; mermaid: string;
483
+ }
484
+ interface Trajectory {
485
+ runId: string; workflow: string; prompt?: string; finalAnswer: string;
486
+ segments: { node: string; enteredState?: string; exitedState?: string;
487
+ items: (MessageItem | ToolCallItem)[] }[];
488
+ }
489
+ // MessageItem: { kind:"message", role, content }
490
+ // ToolCallItem: { kind:"tool_call", name, args, result: string|null }
491
+ interface RunMetadata { runId: string; workflow: string;
492
+ runtimeContract: ResolvedRuntimeContract; packageVersion: string; }
493
+ // trail.json: { runId, workflow, steps: TrailStep[] } — the audit trail,
494
+ // re-derived from checkpointed state on every artifact write.
495
+ // TrailStep: { to, kind: "trigger"|"agent"|"human"|"reset"|"on_error",
496
+ // reason?, ts }
497
+ ```
498
+
499
+ An **API** reads these files (through the same session store, or via `runArtifactPaths(sessionId)`
500
+ path helpers) to render historical runs: `graph.json`/`graph.mmd` for the diagram,
501
+ `trajectory.json` for the step-by-step timeline, `trail.json` for the decision
502
+ path (which edges committed, by whom, and why), `variables.json` for the run's
503
+ inputs and established facts (also what a test author reads to reproduce a real
504
+ firing's payload — see
505
+ [hook-and-test-scripts.md](hook-and-test-scripts.md#recovering-a-cases-inputs-from-previous-runs)).
506
+ Note it holds whatever the run's variables held, verbatim: a host that must not
507
+ persist an input should not seed it. To persist artifacts yourself,
508
+ stream the run and call `agent.emitRunArtifacts(runId, trajectory)`.
509
+
510
+ ## Model configuration
511
+
512
+ Env (loaded from the workspace root `.env`, real process env wins):
513
+ `ARCHMAX_API_BASE_URL`, `ARCHMAX_API_KEY`, `ARCHMAX_MODEL`, optional
514
+ `ARCHMAX_TEMPERATURE`, `ARCHMAX_MAX_TOKENS` — any OpenAI-compatible endpoint.
515
+ Or inject a model directly:
516
+
517
+ ```ts
518
+ import { ChatOpenAI } from "@langchain/openai";
519
+ const model = new ChatOpenAI({
520
+ model: "claude-sonnet-5",
521
+ apiKey: process.env.MY_KEY,
522
+ configuration: { baseURL: "https://api.example.com/v1" },
523
+ });
524
+ const agent = await createAgent({ model });
525
+ ```
526
+
527
+ ## Custom backends
528
+
529
+ `BackendProtocolV2` (from `deepagents`) decouples storage — implement
530
+ `readRaw`/`write`/`edit`/`ls` over filesystem, a store, a sandbox, S3, or a remote.
531
+ Pass it as `backend` (authored workspace); run state goes through a `sessionStore`
532
+ (e.g. `createBackendSessionStore({ backend: s3Backend, prefix: "tenants/a/runs" })`).
533
+ A custom `backend` **requires** an explicit `sessionStore` — assembly throws
534
+ `SessionStoreRequiredError` instead of inferring storage. The SDK owns the logical
535
+ `sessions/<sessionId>/…` namespace; the store owns where it physically lives.
536
+ Persisting the session zone off-box (an S3-backed session store) is how you share run
537
+ state across a worker fleet and an API.
538
+
539
+ ## Cases against your agent
540
+
541
+ `runTests` runs a workflow's cases — declarative YAML documents
542
+ under `workflows/<name>/tests/*.test.yaml`, interpreted host-side — with the
543
+ same discovery, case interpretation, judge, and verdicts `archmax test` uses.
544
+ By default it builds its own agent, which is *not* your agent: no connection
545
+ tools, no mounts, no session store, no checkpointer — and it reads the suite off
546
+ the local filesystem under `rootDir`, which is *not* your authored tree if that
547
+ tree lives in a store. Supply both:
548
+
549
+ ```ts
550
+ import { runTests, createAgent, createToolMockMiddleware } from "@archmax-ai/harness";
551
+
552
+ const { results, exitCode } = await runTests({
553
+ workflow,
554
+ rootDir,
555
+ // Where the spec, the case documents and their `from:` fixtures are read
556
+ // from. Omit it only when they really are files under `rootDir`.
557
+ authoring,
558
+ createTarget: async ({ workflow, rootDir, onEvent }) =>
559
+ createAgent({
560
+ workflow,
561
+ onEvent,
562
+ backend,
563
+ tools: await resolveConnectionTools(tenant),
564
+ checkpointer,
565
+ middleware: [createToolMockMiddleware()],
566
+ // REQUIRED — see below,
567
+ workspace: { rootDir, sessionStore },
568
+ }),
569
+ sessionIdForCase: (file) => `${hostRunId}/${file}`,
570
+ });
571
+ ```
572
+
573
+ | Option | Why |
574
+ | --- | --- |
575
+ | `authoring` | The backend the **suite itself** is read from: the machine spec, `workflows/<name>/tests/*.test.yaml`, and the fixtures their `from:` entries name. The same option `createAgent` takes, and normally the same backend — the agent under test runs the authored tree the cases were read from. Defaults to a filesystem backend over the resolved root, so a host whose authored tree lives in a store and omits it discovers **no cases at all** and gets an empty run rather than a failure. |
576
+ | `createTarget` | The agent under test — an already-built runtime, or a factory that builds one. Must be **workflow-governed** — a plain agent is refused before any case runs. In the factory form, `rootDir` in the context is the resolved workspace root. |
577
+ | `sessionIdForCase` | Names the *agent* session the case runs on — a case is one conversation on one session (default `test-default-<runId>-<file>`), invoked once per case file — so its checkpoints, `scratchpad/…` files, and token usage join your own run record. |
578
+
579
+ **Your target owns its mocks — and the runtime checks.** A case's `mocks:`
580
+ list intercepts agent-initiated tool calls through
581
+ `createToolMockMiddleware()`, which the default target wires for you.
582
+ `createAgent` stamps `capabilities.toolMocks` from the middleware
583
+ actually wired; a case that declares mocks against a target without the
584
+ capability **fails loudly before the agent runs**, naming the fix — never run
585
+ with partial interception (scripts' PTC calls mocked, the agent's own calls
586
+ real). A bespoke target that intercepts by other means sets
587
+ `capabilities.toolMocks` itself. Mockless cases run against any
588
+ workflow-governed target.
589
+
590
+ **Sub-workflows inherit the assembly.** When a workflow delegates (by advancing
591
+ an `archmax_workflow_<slug>` tool), the child runtime is
592
+ composed from the *same* resolved inputs as the parent — model and
593
+ `modelFactory`, `backend` and `mounts`, `sessionStore` and `checkpointer`, host
594
+ `tools` and `essentialTools`, `sandboxRuntime`, `hookExecutors`,
595
+ `policyRules`, `promptCache` and `pricing` — differing only in
596
+ the machine that governs it and the system prompt that machine renders. So a
597
+ custom backend serves the child's spec too, and a `modelFactory` supplies its
598
+ model. Composition is **lazy and memoized per workflow slug**: a workflow that is
599
+ never delegated to is never loaded, and one delegated from many places is
600
+ composed once. A child whose spec is broken surfaces as a *dispatch* failure, not
601
+ an assembly failure — a parent still assembles.
602
+
603
+ The child runs on the parent's **session id** (which is what gives it the same
604
+ run zone) under a nested checkpoint namespace, so `sessions.list()` reports one
605
+ session and the parent session's metrics include the child's tokens.
606
+ `capabilities.subWorkflows` is stamped `true` for a governed assembly and `false`
607
+ for the plain one.
608
+
609
+ Omit both options and behavior is identical to `archmax test`. Cases run
610
+ sequentially (`tests.maxConcurrency` above 1 is rejected, not silently
611
+ serialized) and there is no cancellation signal: call `runTests` once per file
612
+ (`filter`) if you need to interrupt between cases; a single case is bounded by
613
+ `tests.caseTimeoutMs`.
614
+
615
+ ## Suggested split
616
+
617
+ - **Worker**: `createAgent` + `agent.invoke`/`stream`; `agent.workflow.decide` for
618
+ approvals. Owns execution and the durable session store/checkpointer.
619
+ - **API**: reads `sessions/<sessionId>/artifacts/*` (shared session store) and/or relays
620
+ the `onEvent` stream; exposes `sessions.list()`, run detail, and a decide endpoint.
621
+ - **Frontend**: renders `graph.json`/`graph.mmd`, the `trajectory.json` timeline,
622
+ the `variables.json` inputs, and the live event stream; posts human decisions
623
+ back to the API.
624
+
625
+ Keep the heavy runtime import (LangChain/LangGraph) in the worker; the API/frontend
626
+ only need the artifact/event *types*, which ship in `dist/index.d.ts`.