@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,339 @@
1
+ /**
2
+ * Shared support for the behaviour-level suite.
3
+ *
4
+ * Everything here drives the runtime through the **public API only** — the
5
+ * `../index.js` barrel and `../public/testing.js` — so that an internal
6
+ * restructuring can be verified against these tests without touching them. No
7
+ * test in this directory imports from `src/workflow/*`, `src/machine/*`,
8
+ * `src/kernel/*` or any other internal module.
9
+ *
10
+ * Three pieces:
11
+ *
12
+ * - {@link ScriptedModel}: a fake chat model that replays a queue of turns —
13
+ * tool calls (`archmax_advance`, `archmax_wait`, `write_file`, a delegation
14
+ * tool, …) and final text replies — and records what it was bound with.
15
+ * - {@link makeWorkspace}: writes an authored workspace (workflow.yaml, hooks,
16
+ * skills) into a temp directory, cleaned up by {@link cleanupWorkspaces}.
17
+ * - {@link assemble} / {@link turn}: assemble a governed agent over a memory
18
+ * session store with an event sink, and drive one conversational turn.
19
+ */
20
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
21
+ import { tmpdir } from "node:os";
22
+ import { dirname, join, resolve } from "node:path";
23
+ import { stringify as toYaml } from "yaml";
24
+ import { AIMessage } from "@langchain/core/messages";
25
+ import { BaseChatModel } from "@langchain/core/language_models/chat_models";
26
+ import { contentToString, createAgent, createMemorySessionStore, isAiMessage, } from "../index.js";
27
+ /**
28
+ * A model that replays a fixed script of turns. `bindTools` returns the same
29
+ * instance so the cursor is shared across every binding the agent performs —
30
+ * the script is the run's plan, not one binding's. When the script runs out the
31
+ * model replies with a final `done`, so every turn terminates.
32
+ */
33
+ export class ScriptedModel extends BaseChatModel {
34
+ turns;
35
+ cursor = 0;
36
+ lastBound = [];
37
+ seq = 0;
38
+ /** Tool calls the script actually issued, in order. */
39
+ issued = [];
40
+ /** Every model invocation, in order. */
41
+ calls = [];
42
+ /** What to say when the script is exhausted. */
43
+ fallbackReply;
44
+ /**
45
+ * The id this model was configured to run, as a real client exposes it — what
46
+ * `modelIdOf` reads and what the runtime prices against when a response names
47
+ * no model. Left undefined by default so an existing case is unchanged.
48
+ */
49
+ model;
50
+ constructor(turns, opts = {}) {
51
+ super({});
52
+ this.turns = turns;
53
+ this.fallbackReply = opts.fallbackReply ?? "done";
54
+ if (opts.model !== undefined)
55
+ this.model = opts.model;
56
+ }
57
+ _llmType() {
58
+ return "archmax-behaviour-scripted";
59
+ }
60
+ /** How many scripted turns are still unplayed. */
61
+ get remaining() {
62
+ return Math.max(0, this.turns.length - this.cursor);
63
+ }
64
+ /** Append turns to the script — for a later conversational turn on the same agent. */
65
+ enqueue(...turns) {
66
+ this.turns.push(...turns);
67
+ }
68
+ bindTools(tools) {
69
+ this.lastBound = tools.map((t) => String(t?.name ?? ""));
70
+ return this;
71
+ }
72
+ async _generate(messages) {
73
+ const system = messages.find((m) => m.getType() === "system");
74
+ this.calls.push({
75
+ tools: [...this.lastBound],
76
+ systemPrompt: system ? contentToString(system.content) : "",
77
+ messageTypes: messages.map((m) => m.getType()),
78
+ });
79
+ // The cursor only moves past a scripted turn: a fallback reply consumes
80
+ // nothing, so turns enqueued later are still played in order.
81
+ const scripted = this.turns[this.cursor];
82
+ if (scripted)
83
+ this.cursor += 1;
84
+ const turn = scripted ?? { reply: this.fallbackReply };
85
+ const usage = turn.usage
86
+ ? {
87
+ usage_metadata: {
88
+ input_tokens: turn.usage.input,
89
+ output_tokens: turn.usage.output,
90
+ total_tokens: turn.usage.input + turn.usage.output,
91
+ },
92
+ ...(turn.reports ? { response_metadata: { model_name: turn.reports } } : {}),
93
+ }
94
+ : {};
95
+ if ("reply" in turn) {
96
+ const message = new AIMessage({ content: turn.reply, ...usage });
97
+ return { generations: [{ text: turn.reply, message }] };
98
+ }
99
+ const calls = "batch" in turn ? turn.batch : [{ tool: turn.tool, args: turn.args }];
100
+ const toolCalls = calls.map((c) => {
101
+ this.issued.push({ name: c.tool, args: c.args });
102
+ return { id: `call-${++this.seq}`, name: c.tool, args: c.args };
103
+ });
104
+ const message = new AIMessage({ content: "", tool_calls: toolCalls, ...usage });
105
+ return { generations: [{ text: "", message }] };
106
+ }
107
+ }
108
+ // --- Temp workspaces ----------------------------------------------------------
109
+ const tmpRoots = [];
110
+ /**
111
+ * Write an authored workspace into a fresh temp directory. Values are file
112
+ * contents; a non-string value is serialized as YAML (handy for `workflow.yaml`
113
+ * declared as an object). Returns the root path.
114
+ */
115
+ export function makeWorkspace(files) {
116
+ const root = mkdtempSync(join(tmpdir(), "archmax-behaviour-"));
117
+ tmpRoots.push(root);
118
+ for (const [rel, contents] of Object.entries(files)) {
119
+ const full = resolve(root, rel);
120
+ mkdirSync(dirname(full), { recursive: true });
121
+ writeFileSync(full, typeof contents === "string" ? contents : toYaml(contents));
122
+ }
123
+ return root;
124
+ }
125
+ /** Remove every workspace {@link makeWorkspace} created. Call from `afterEach`. */
126
+ export function cleanupWorkspaces() {
127
+ while (tmpRoots.length)
128
+ rmSync(tmpRoots.pop(), { recursive: true, force: true });
129
+ }
130
+ /** A `SKILL.md` body with the frontmatter the skill loader requires. */
131
+ export function skillMarkdown(name, description = `The ${name} skill.`) {
132
+ return `---\nname: ${name}\ndescription: ${description}\n---\n\n# ${name}\n`;
133
+ }
134
+ /**
135
+ * One inline rubric, as the value of a `{ rubric: … }` hook. A rubric is
136
+ * declared on the hook that applies it, so a fixture builds the declaration and
137
+ * drops it straight into a state's `before`/`after`.
138
+ */
139
+ export function rubricDeclaration(opts = {}) {
140
+ return {
141
+ instructions: opts.instructions ?? "Judge the reply. Reply with a JSON verdict.",
142
+ ...(opts.maxIterations !== undefined ? { max_iterations: opts.maxIterations } : {}),
143
+ ...(opts.model !== undefined ? { model: opts.model } : {}),
144
+ ...(opts.metadata !== undefined ? { metadata: opts.metadata } : {}),
145
+ };
146
+ }
147
+ /** The default persona file every workspace here carries. */
148
+ export const AGENTS_MD = "# Agent\n\nDo what the workflow says.\n";
149
+ /** Assemble a governed agent over `root` with an event sink and memory storage. */
150
+ export async function assemble(root, opts = {}) {
151
+ const model = opts.model ?? new ScriptedModel(opts.turns ?? []);
152
+ const events = [];
153
+ const store = opts.store ?? createMemorySessionStore();
154
+ const rubricModel = opts.rubricModel;
155
+ const agent = await createAgent({
156
+ workflow: opts.workflow ?? "w",
157
+ ...(opts.modelFactory
158
+ ? { modelFactory: opts.modelFactory }
159
+ : rubricModel
160
+ ? {
161
+ modelFactory: (role) => (role === "agent" ? model : rubricModel),
162
+ }
163
+ : { model: model }),
164
+ onEvent: (event) => events.push(event),
165
+ workspace: { rootDir: root, sessionStore: store },
166
+ ...opts.params,
167
+ });
168
+ if (!agent.workflow)
169
+ throw new Error("expected a governed assembly");
170
+ return { agent: agent, model, events, store, root };
171
+ }
172
+ /** Drive one conversational turn on `sessionId`. */
173
+ export async function turn(agent, sessionId, text, opts = {}) {
174
+ const input = {
175
+ messages: [{ role: "user", content: text }],
176
+ ...(opts.trigger ? { trigger: opts.trigger } : {}),
177
+ };
178
+ const result = (await agent.invoke(input, {
179
+ configurable: { thread_id: sessionId },
180
+ }));
181
+ const messages = result.messages ?? [];
182
+ return { messages, reply: lastAgentText(messages) };
183
+ }
184
+ /** The final assistant message carrying text, skipping tool results. */
185
+ export function lastAgentText(messages) {
186
+ for (let i = messages.length - 1; i >= 0; i--) {
187
+ const message = messages[i];
188
+ if (!isAiMessage(message))
189
+ continue;
190
+ const text = contentToString(message.content).trim();
191
+ if (text)
192
+ return text;
193
+ }
194
+ return "";
195
+ }
196
+ /** The type of a message (`ai`, `human`, `tool`, `system`), read across shapes. */
197
+ export function messageType(message) {
198
+ const msg = message;
199
+ const t = msg._getType?.call(msg) ??
200
+ msg.getType?.call(msg) ??
201
+ msg.type ??
202
+ msg.role ??
203
+ "";
204
+ return String(t);
205
+ }
206
+ /** Tool results in a transcript: `{ name, content, status }`. */
207
+ export function toolResults(messages) {
208
+ return messages
209
+ .filter((m) => messageType(m) === "tool")
210
+ .map((m) => {
211
+ const msg = m;
212
+ return {
213
+ name: String(msg.name ?? ""),
214
+ content: contentToString(msg.content),
215
+ ...(msg.status ? { status: msg.status } : {}),
216
+ };
217
+ });
218
+ }
219
+ // --- Event selectors ----------------------------------------------------------
220
+ /** Events of one type, narrowed. */
221
+ export function eventsOf(events, type) {
222
+ return events.filter((e) => e.type === type);
223
+ }
224
+ /** The states entered, in order. */
225
+ export function statesEntered(events) {
226
+ return eventsOf(events, "state-enter").map((e) => e.state);
227
+ }
228
+ /** The agent-driven transitions (`from -> to`), in order — the opening arrival excluded. */
229
+ export function advances(events) {
230
+ return eventsOf(events, "advance")
231
+ .filter((e) => e.from !== "__start__")
232
+ .map((e) => ({ from: e.from, to: e.to, ...(e.reason ? { reason: e.reason } : {}) }));
233
+ }
234
+ /** Names of the tools governance refused, in order. */
235
+ export function blockedTools(events) {
236
+ return eventsOf(events, "tool-blocked").map((e) => e.tool);
237
+ }
238
+ /** Events emitted for one session only. */
239
+ export function forSession(events, sessionId) {
240
+ return events.filter((e) => e.sessionId === sessionId);
241
+ }
242
+ // --- Spec builders ------------------------------------------------------------
243
+ /**
244
+ * A two-state linear machine: `start` (manual) → `done` (terminal), with the
245
+ * runtime contract pinned. Extra keys are merged into the spec root.
246
+ */
247
+ export function linearSpec(extra = {}) {
248
+ return {
249
+ runtime: { engine: "archmax-harness", version: "2" },
250
+ states: {
251
+ start: { triggers: { manual: null }, transitions: [{ to: "done", description: "Test edge to done." }] },
252
+ done: {},
253
+ },
254
+ ...extra,
255
+ };
256
+ }
257
+ /** The scripted turn that advances `to` with a reason. */
258
+ export function advanceTo(to, reason = `moving to ${to}`) {
259
+ return { tool: "archmax_advance", args: { to, reason } };
260
+ }
261
+ /** A workspace with a persona and one workflow spec under `workflows/w/`. */
262
+ export function workspaceWith(spec, extraFiles = {}) {
263
+ return makeWorkspace({
264
+ "AGENTS.md": AGENTS_MD,
265
+ "workflows/w/workflow.yaml": spec,
266
+ ...extraFiles,
267
+ });
268
+ }
269
+ /**
270
+ * A fake model for the `rubric` role that answers each dispatch with the next
271
+ * scripted verdict. When the framework binds a structured-output tool
272
+ * (`extract-*`) it is called with the verdict; otherwise the verdict is the reply
273
+ * text as JSON — both reach the lifecycle runner as a parseable verdict.
274
+ */
275
+ export class JudgeModel extends BaseChatModel {
276
+ verdicts;
277
+ fallback;
278
+ failWith;
279
+ cursor = 0;
280
+ lastBound = [];
281
+ seq = 0;
282
+ /** How many times the judge was asked. */
283
+ get dispatches() {
284
+ return this.calls;
285
+ }
286
+ calls = 0;
287
+ constructor(verdicts, fallback = { verdict: "ok", reason: "fine" },
288
+ /**
289
+ * Fail every dispatch instead of answering — how an unusable `model` id
290
+ * surfaces, since a bad id is refused at invocation, not construction.
291
+ */
292
+ failWith) {
293
+ super({});
294
+ this.verdicts = verdicts;
295
+ this.fallback = fallback;
296
+ this.failWith = failWith;
297
+ }
298
+ _llmType() {
299
+ return "archmax-behaviour-judge";
300
+ }
301
+ bindTools(tools) {
302
+ this.lastBound = tools.map((t) => String(t?.name ?? ""));
303
+ return this;
304
+ }
305
+ async _generate() {
306
+ this.calls += 1;
307
+ if (this.failWith)
308
+ throw new Error(this.failWith);
309
+ const verdict = this.verdicts[this.cursor++] ?? this.fallback;
310
+ const extract = this.lastBound.find((name) => name.startsWith("extract-"));
311
+ if (extract) {
312
+ const message = new AIMessage({
313
+ content: "",
314
+ tool_calls: [{ id: `judge-${++this.seq}`, name: extract, args: { ...verdict } }],
315
+ });
316
+ return { generations: [{ text: "", message }] };
317
+ }
318
+ const text = JSON.stringify(verdict);
319
+ return { generations: [{ text, message: new AIMessage(text) }] };
320
+ }
321
+ }
322
+ // --- Store access -------------------------------------------------------------
323
+ /** Read one file from a session store by store-relative path, or `undefined`. */
324
+ export async function storeFile(store, path) {
325
+ const result = await store.backend.readRaw(path);
326
+ const data = result.data;
327
+ return typeof data?.content === "string" ? data.content : undefined;
328
+ }
329
+ // --- Session ids ---------------------------------------------------------------
330
+ let sessionSeq = 0;
331
+ /**
332
+ * A session id no other test in this process has used. Sandbox REPL sessions
333
+ * and other per-session resources are keyed by session id for the life of the
334
+ * process, so tests that run hooks or scripts must not share one.
335
+ */
336
+ export function freshSessionId(prefix = "s") {
337
+ return `${prefix}-${process.pid}-${++sessionSeq}`;
338
+ }
339
+ //# sourceMappingURL=support.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"support.js","sourceRoot":"","sources":["../../src/behaviour/support.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,SAAS,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,6CAA6C,CAAC;AAG5E,OAAO,EACL,eAAe,EACf,WAAW,EACX,wBAAw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AAC;IACjD,MAAM,IAAI,GAAI,MAA0C,CAAC,IAAI,CAAC;IAC9D,OAAO,OAAO,IAAI,EAAE,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AACtE,CAAC;AAED,kFAAkF;AAElF,IAAI,UAAU,GAAG,CAAC,CAAC;AAEnB;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,MAAM,GAAG,GAAG;IACzC,OAAO,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,IAAI,EAAE,UAAU,EAAE,CAAC;AACpD,CAAC"}
@@ -0,0 +1,11 @@
1
+ export declare const BANNER_TEXT = "\n __ __\n ___ _________/ / __ _ ___ ___ __ / / ___ ________ ___ ___ ___\n/ _ `/ __/ __/ _ \\/ ' \\/ _ `/\\ \\ / / _ \\/ _ `/ __/ _ \\/ -_|_-<(_-<\n\\_,_/_/ \\__/_//_/_/_/_/\\_,_//_\\_\\ /_//_/\\_,_/_/ /_//_/\\__/___/___/\n";
2
+ export interface BannerContext {
3
+ /** Env to check for `ARCHMAX_CLI_NO_BANNER` (defaults to `process.env`). */
4
+ env?: NodeJS.ProcessEnv;
5
+ /** Whether `stderr` is a TTY (defaults to `process.stderr.isTTY`). */
6
+ isTTY?: boolean;
7
+ }
8
+ /** True when the startup banner should be printed for the given context. */
9
+ export declare function shouldShowBanner(ctx?: BannerContext): boolean;
10
+ /** Print the banner to `stderr` when {@link shouldShowBanner} allows it for the live process context. */
11
+ export declare function printBanner(): void;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Startup banner: the archmax harness ASCII wordmark, in the spirit of oh-my-zsh's
3
+ * startup art. The banner is written to `stderr` only, never `stdout`, so it
4
+ * can never pollute piped/redirected output.
5
+ */
6
+ import { createStyle } from "./style.js";
7
+ export const BANNER_TEXT = `
8
+ __ __
9
+ ___ _________/ / __ _ ___ ___ __ / / ___ ________ ___ ___ ___
10
+ / _ \`/ __/ __/ _ \\/ ' \\/ _ \`/\\ \\ / / _ \\/ _ \`/ __/ _ \\/ -_|_-<(_-<
11
+ \\_,_/_/ \\__/_//_/_/_/_/\\_,_//_\\_\\ /_//_/\\_,_/_/ /_//_/\\__/___/___/
12
+ `;
13
+ /** True when the startup banner should be printed for the given context. */
14
+ export function shouldShowBanner(ctx = {}) {
15
+ const env = ctx.env ?? process.env;
16
+ const isTTY = ctx.isTTY ?? Boolean(process.stderr.isTTY);
17
+ if (env.ARCHMAX_CLI_NO_BANNER !== undefined && env.ARCHMAX_CLI_NO_BANNER !== "")
18
+ return false;
19
+ if (!isTTY)
20
+ return false;
21
+ return true;
22
+ }
23
+ /** Print the banner to `stderr` when {@link shouldShowBanner} allows it for the live process context. */
24
+ export function printBanner() {
25
+ if (shouldShowBanner()) {
26
+ console.error(createStyle().cyan(BANNER_TEXT));
27
+ }
28
+ }
29
+ //# sourceMappingURL=banner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"banner.js","sourceRoot":"","sources":["../../src/cli/banner.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,MAAM,CAAC,MAAM,WAAW,GAAG;;;;;CAK1B,CAAC;AASF,4EAA4E;AAC5E,MAAM,UAAU,gBAAgB,CAAC,MAAqB,EAAE;IACtD,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC;IACnC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,IAAI,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEzD,IAAI,GAAG,CAAC,qBAAqB,KAAK,SAAS,IAAI,GAAG,CAAC,qBAAqB,KAAK,EAAE;QAAE,OAAO,KAAK,CAAC;IAC9F,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IACzB,OAAO,IAAI,CAAC;AACd,CAAC;AAED,yGAAyG;AACzG,MAAM,UAAU,WAAW;IACzB,IAAI,gBAAgB,EAAE,EAAE,CAAC;QACvB,OAAO,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IACjD,CAAC;AACH,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { GovernedAgent } from "../agent.js";
2
+ import { type TriggerInput } from "../machine/triggers.js";
3
+ import { type UsageTracker } from "../core/usage.js";
4
+ import { type Style } from "./style.js";
5
+ import { type Invocation } from "./command.js";
6
+ /**
7
+ * The `<workflow>` slot: given, or inferred when the workspace holds exactly
8
+ * one workflow — the common single-workflow workspace needs no repetition.
9
+ */
10
+ export declare function resolveWorkflow(given: string | undefined, rootDir: string | undefined): string;
11
+ /** `--variables` must be a JSON object; anything else is an argument error before any assembly. */
12
+ export declare function parseVariablesJson(raw: string | undefined): Record<string, unknown> | undefined;
13
+ /** The one session header every command prints to stderr. Loads `.env` first so the model line is the effective one. */
14
+ export declare function printSessionHeader(style: Style, workflow: string, rootDir: string | undefined, showModel?: boolean): void;
15
+ /** Wire the state flow (and `--verbose` raw lines) behind a usage tracker whose handler the agent receives. */
16
+ export declare function createEventSink(style: Style, verbose: boolean, view?: import("./state-flow.js").StateFlowRenderer): UsageTracker;
17
+ export declare const isKnown: (e: unknown) => e is Error;
18
+ /** Assemble the governed agent for a CLI command; a known load failure becomes a one-line `CliError`. */
19
+ export declare function bootstrap(workflow: string, rootDir: string | undefined, usage: UsageTracker, extra?: {
20
+ trigger?: TriggerInput;
21
+ variables?: Record<string, unknown>;
22
+ }): Promise<GovernedAgent>;
23
+ /**
24
+ * Everything a session command shares: the id is validated before anything is
25
+ * assembled, the agent is bootstrapped under the (given or inferred) workflow,
26
+ * the body runs, known runtime refusals become one-line errors, and the
27
+ * session is disposed however the body ended.
28
+ */
29
+ export declare function withSession(inv: Invocation, sessionId: string | undefined, body: (ctx: {
30
+ agent: GovernedAgent;
31
+ style: Style;
32
+ usage: UsageTracker;
33
+ }) => Promise<number>): Promise<number>;
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Assembling an agent for a CLI command: which workflow (given, or inferred
3
+ * from a single-workflow workspace), the `.env`-backed session header, the
4
+ * event sink behind the state flow and the usage tracker, and the one
5
+ * `withSession` wrapper every session command runs its body inside.
6
+ */
7
+ import { existsSync, readdirSync } from "node:fs";
8
+ import { resolve } from "node:path";
9
+ import { createAgent } from "../assembly/index.js";
10
+ import { UnknownTriggerError } from "../machine/triggers.js";
11
+ import { WorkflowDisabledError, WorkflowLoadError } from "../machine/load-spec.js";
12
+ import { EmptyMessageError, InvalidDecisionTargetError, MissingDeliveryTriggerError, SessionNotAwaitingInputError, SessionNotParkedError, } from "../sessions/resume.js";
13
+ import { SessionNotResumableError, UnknownSessionTriggerError } from "../sessions/resolve.js";
14
+ import { sessionIdRejection } from "../core/session-store.js";
15
+ import { UnsupportedRuntimeContractError } from "../runtime/contract.js";
16
+ import { loadDotenv, resolveWorkspaceRoot } from "../env.js";
17
+ import { createUsageTracker } from "../core/usage.js";
18
+ import { originLabel, renderEventLine } from "../core/events.js";
19
+ import { createStyle, icons } from "./style.js";
20
+ import { createStateFlowRenderer } from "./state-flow.js";
21
+ import { CliError, UsageError, err } from "./command.js";
22
+ /**
23
+ * The `<workflow>` slot: given, or inferred when the workspace holds exactly
24
+ * one workflow — the common single-workflow workspace needs no repetition.
25
+ */
26
+ export function resolveWorkflow(given, rootDir) {
27
+ if (given)
28
+ return given;
29
+ const dir = resolve(resolveWorkspaceRoot(rootDir), "workflows");
30
+ const slugs = existsSync(dir)
31
+ ? readdirSync(dir, { withFileTypes: true })
32
+ .filter((e) => e.isDirectory() && existsSync(resolve(dir, e.name, "workflow.yaml")))
33
+ .map((e) => e.name)
34
+ : [];
35
+ if (slugs.length === 1)
36
+ return slugs[0];
37
+ if (slugs.length === 0)
38
+ throw new UsageError(`a workflow is required and none was found under ${dir}`);
39
+ throw new UsageError(`a workflow is required; this workspace has several: ${slugs.sort().join(", ")}`);
40
+ }
41
+ /** `--variables` must be a JSON object; anything else is an argument error before any assembly. */
42
+ export function parseVariablesJson(raw) {
43
+ if (raw === undefined)
44
+ return undefined;
45
+ let value;
46
+ try {
47
+ value = JSON.parse(raw);
48
+ }
49
+ catch {
50
+ throw new UsageError("--variables is not valid JSON");
51
+ }
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
53
+ throw new UsageError('--variables must encode a JSON object (e.g. \'{"from_email":"a@b.com"}\')');
54
+ }
55
+ return value;
56
+ }
57
+ /** The raw event line for `--verbose`, including the two events the default console output skips. */
58
+ function rawEventLine(event) {
59
+ switch (event.type) {
60
+ case "agent-text":
61
+ return `[agent:${event.state}] ${event.text}`;
62
+ case "tool-called":
63
+ return (`[workflow:${event.state}] tool ${event.tool}${event.detail ? ` ${event.detail}` : ""}` +
64
+ `${event.origin ? ` (from a ${originLabel(event.origin)})` : ""}`);
65
+ default:
66
+ return renderEventLine(event) ?? "";
67
+ }
68
+ }
69
+ /** The one session header every command prints to stderr. Loads `.env` first so the model line is the effective one. */
70
+ export function printSessionHeader(style, workflow, rootDir, showModel = false) {
71
+ loadDotenv(rootDir);
72
+ err(style.cyan(style.bold(`${icons.diamond} ${workflow}`)));
73
+ err(` ${style.dim("directory")} ${resolveWorkspaceRoot(rootDir)}`);
74
+ if (showModel)
75
+ err(` ${style.dim("model")} ${process.env.ARCHMAX_MODEL ?? "(unset — see .env)"}`);
76
+ err("");
77
+ }
78
+ /** Wire the state flow (and `--verbose` raw lines) behind a usage tracker whose handler the agent receives. */
79
+ export function createEventSink(style, verbose, view = createStateFlowRenderer(process.stderr, style)) {
80
+ return createUsageTracker({
81
+ onEvent: (event) => {
82
+ if (verbose) {
83
+ const line = rawEventLine(event);
84
+ if (line)
85
+ err(line);
86
+ }
87
+ view.onEvent(event);
88
+ },
89
+ });
90
+ }
91
+ const KNOWN_ERRORS = [
92
+ UnsupportedRuntimeContractError,
93
+ WorkflowLoadError,
94
+ UnknownTriggerError,
95
+ WorkflowDisabledError,
96
+ SessionNotParkedError,
97
+ InvalidDecisionTargetError,
98
+ EmptyMessageError,
99
+ SessionNotAwaitingInputError,
100
+ MissingDeliveryTriggerError,
101
+ SessionNotResumableError,
102
+ UnknownSessionTriggerError,
103
+ ];
104
+ export const isKnown = (e) => KNOWN_ERRORS.some((cls) => e instanceof cls);
105
+ /** Assemble the governed agent for a CLI command; a known load failure becomes a one-line `CliError`. */
106
+ export async function bootstrap(workflow, rootDir, usage, extra = {}) {
107
+ try {
108
+ const agent = await createAgent({
109
+ workflow,
110
+ ...(rootDir !== undefined ? { workspace: { rootDir } } : {}),
111
+ onEvent: usage.handler,
112
+ ...(extra.trigger ? { trigger: extra.trigger } : {}),
113
+ ...(extra.variables ? { variables: extra.variables } : {}),
114
+ });
115
+ if (!agent.workflow)
116
+ throw new CliError(`workflow '${workflow}' assembled without a machine.`);
117
+ return agent;
118
+ }
119
+ catch (e) {
120
+ if (isKnown(e))
121
+ throw new CliError(e.message);
122
+ throw e;
123
+ }
124
+ }
125
+ /**
126
+ * Everything a session command shares: the id is validated before anything is
127
+ * assembled, the agent is bootstrapped under the (given or inferred) workflow,
128
+ * the body runs, known runtime refusals become one-line errors, and the
129
+ * session is disposed however the body ended.
130
+ */
131
+ export async function withSession(inv, sessionId, body) {
132
+ const rejection = sessionId === undefined ? null : sessionIdRejection(sessionId);
133
+ if (rejection)
134
+ throw new UsageError(`invalid session id '${sessionId}' - ${rejection}. Use one from 'archmax sessions'.`);
135
+ const workflow = resolveWorkflow(inv.values.workflow, inv.root);
136
+ const style = createStyle();
137
+ printSessionHeader(style, workflow, inv.root);
138
+ const usage = createEventSink(style, inv.values.verbose === true);
139
+ const agent = await bootstrap(workflow, inv.root, usage);
140
+ try {
141
+ return await body({ agent, style, usage });
142
+ }
143
+ catch (e) {
144
+ if (isKnown(e))
145
+ throw new CliError(e.message);
146
+ throw e;
147
+ }
148
+ finally {
149
+ if (sessionId !== undefined)
150
+ agent.dispose(sessionId);
151
+ }
152
+ }
153
+ //# sourceMappingURL=boot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E,KAAK,EAAE,CAAC,CAAC;IAC7C,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,OAAO,CAAC,CAAC,CAAC;YAAE,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QAC9C,MAAM,CAAC,CAAC;IACV,CAAC;YAAS,CAAC;QACT,IAAI,SAAS,KAAK,SAAS;YAAE,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;AACH,CAAC"}
@@ -0,0 +1,39 @@
1
+ export interface Positional {
2
+ name: string;
3
+ required: boolean;
4
+ description: string;
5
+ /** Joins every remaining positional with spaces (a prompt or message needs no quoting). */
6
+ rest?: boolean;
7
+ }
8
+ export interface OptionSpec {
9
+ type: "string" | "boolean";
10
+ description: string;
11
+ placeholder?: string;
12
+ short?: string;
13
+ }
14
+ export type Values = Record<string, string | boolean | undefined>;
15
+ export interface Invocation {
16
+ positionals: string[];
17
+ values: Values;
18
+ root: string | undefined;
19
+ }
20
+ export interface Command {
21
+ name: string;
22
+ summary: string;
23
+ description?: string;
24
+ positionals: Positional[];
25
+ options: Record<string, OptionSpec>;
26
+ run(inv: Invocation): Promise<number>;
27
+ }
28
+ /** A failure of the invocation itself: exit 2, one line, a `--help` hint — never a usage dump. */
29
+ export declare class UsageError extends Error {
30
+ }
31
+ /** A failure the command established after parsing: exit 1, one line. */
32
+ export declare class CliError extends Error {
33
+ }
34
+ export declare const GLOBAL_OPTIONS: Record<string, OptionSpec>;
35
+ export declare const out: (line: string) => void;
36
+ export declare const err: (line: string) => void;
37
+ export declare function parseInvocation(cmd: Command, args: string[]): Invocation;
38
+ export declare function commandHelp(cmd: Command): string;
39
+ export declare function topLevelHelp(commands: Command[]): string;