@arnilo/prism-hosts 0.0.0-stage → 0.13.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 (322) hide show
  1. package/CHANGELOG.md +394 -0
  2. package/LICENSE +21 -0
  3. package/README.md +34 -2
  4. package/acp/README.md +87 -0
  5. package/acp/src/capabilities.ts +184 -0
  6. package/acp/src/errors.ts +24 -0
  7. package/acp/src/host.ts +36 -0
  8. package/acp/src/index.ts +25 -0
  9. package/acp/src/limits.ts +49 -0
  10. package/acp/src/mapper.ts +419 -0
  11. package/acp/src/permission.ts +37 -0
  12. package/acp/src/projection.ts +39 -0
  13. package/acp/src/prompt.ts +170 -0
  14. package/acp/src/serve.ts +345 -0
  15. package/acp/src/session-map.ts +49 -0
  16. package/ag-ui/README.md +56 -0
  17. package/ag-ui/src/a2ui.ts +570 -0
  18. package/ag-ui/src/ag-ui-mapper.ts +507 -0
  19. package/ag-ui/src/encrypted-value.ts +40 -0
  20. package/ag-ui/src/errors.ts +29 -0
  21. package/ag-ui/src/handler.ts +642 -0
  22. package/ag-ui/src/index.ts +177 -0
  23. package/ag-ui/src/input.ts +190 -0
  24. package/ag-ui/src/limits.ts +279 -0
  25. package/ag-ui/src/mcp-apps.ts +256 -0
  26. package/ag-ui/src/mcp.ts +94 -0
  27. package/ag-ui/src/projection.ts +201 -0
  28. package/ag-ui/src/projectors.ts +272 -0
  29. package/ag-ui/src/renderer/bind.ts +152 -0
  30. package/ag-ui/src/renderer/core.ts +270 -0
  31. package/ag-ui/src/renderer/index.ts +165 -0
  32. package/ag-ui/src/replay.ts +189 -0
  33. package/ag-ui/src/types.ts +66 -0
  34. package/channels/README.md +139 -0
  35. package/channels/src/admission.ts +8 -0
  36. package/channels/src/approvals.ts +262 -0
  37. package/channels/src/checkpoint-contract.ts +97 -0
  38. package/channels/src/delivery.ts +116 -0
  39. package/channels/src/host-ui.ts +356 -0
  40. package/channels/src/identity.ts +46 -0
  41. package/channels/src/index.ts +82 -0
  42. package/channels/src/limits.ts +49 -0
  43. package/channels/src/memory-stores.ts +112 -0
  44. package/channels/src/pairing.ts +178 -0
  45. package/channels/src/runtime-admit.ts +389 -0
  46. package/channels/src/runtime-core.ts +621 -0
  47. package/channels/src/runtime-reconcile.ts +299 -0
  48. package/channels/src/runtime-turn.ts +664 -0
  49. package/channels/src/runtime-types.ts +95 -0
  50. package/channels/src/runtime.ts +86 -0
  51. package/channels/src/secret-ref.ts +42 -0
  52. package/channels/src/signal.ts +790 -0
  53. package/channels/src/state.ts +355 -0
  54. package/channels/src/telegram.ts +1317 -0
  55. package/channels/src/types.ts +442 -0
  56. package/devtools/README.md +92 -0
  57. package/devtools/bin/prism-devtools.ts +63 -0
  58. package/devtools/src/args.ts +71 -0
  59. package/devtools/src/bun.d.ts +27 -0
  60. package/devtools/src/compare.ts +190 -0
  61. package/devtools/src/errors.ts +15 -0
  62. package/devtools/src/index.ts +25 -0
  63. package/devtools/src/replay.ts +36 -0
  64. package/devtools/src/security.ts +80 -0
  65. package/devtools/src/serve.ts +259 -0
  66. package/devtools/src/ui/assets.ts +108 -0
  67. package/devtools/src/ui/inspector.ts +182 -0
  68. package/driver-process/README.md +197 -0
  69. package/driver-process/src/abort.ts +74 -0
  70. package/driver-process/src/adapter.ts +211 -0
  71. package/driver-process/src/driver.ts +303 -0
  72. package/driver-process/src/errors.ts +17 -0
  73. package/driver-process/src/extend.ts +72 -0
  74. package/driver-process/src/index.ts +5 -0
  75. package/driver-process/src/inspect.ts +33 -0
  76. package/driver-process/src/session.ts +72 -0
  77. package/driver-process/src/testing.ts +394 -0
  78. package/driver-process/src/transports/json-rpc.ts +147 -0
  79. package/driver-process/src/transports/jsonl-stream.ts +12 -0
  80. package/driver-process/src/transports/types.ts +11 -0
  81. package/driver-process/src/turn.ts +106 -0
  82. package/evals/README.md +843 -0
  83. package/evals/src/calibration.ts +179 -0
  84. package/evals/src/citation-integrity.ts +98 -0
  85. package/evals/src/citations.ts +45 -0
  86. package/evals/src/compare-experiments.ts +153 -0
  87. package/evals/src/comparison.ts +230 -0
  88. package/evals/src/curate.ts +257 -0
  89. package/evals/src/dataset.ts +81 -0
  90. package/evals/src/erp-invariants.ts +163 -0
  91. package/evals/src/errors.ts +23 -0
  92. package/evals/src/experiment.ts +537 -0
  93. package/evals/src/failure-injection.ts +77 -0
  94. package/evals/src/feedback.ts +53 -0
  95. package/evals/src/index.ts +198 -0
  96. package/evals/src/injection.ts +247 -0
  97. package/evals/src/judge-panel.ts +109 -0
  98. package/evals/src/judge.ts +89 -0
  99. package/evals/src/limits.ts +50 -0
  100. package/evals/src/report-record.ts +47 -0
  101. package/evals/src/rubric-judge.ts +334 -0
  102. package/evals/src/scenario-runner.ts +317 -0
  103. package/evals/src/scenarios.ts +81 -0
  104. package/evals/src/score.ts +328 -0
  105. package/evals/src/scorer.ts +21 -0
  106. package/evals/src/state-match.ts +130 -0
  107. package/evals/src/stats.ts +635 -0
  108. package/evals/src/threshold.ts +117 -0
  109. package/evals/src/timeline.ts +38 -0
  110. package/evals/src/toolless-session.ts +33 -0
  111. package/evals/src/trace.ts +80 -0
  112. package/evals/src/trajectory.ts +623 -0
  113. package/evals/src/types.ts +672 -0
  114. package/evals/src/user-simulator.ts +101 -0
  115. package/evals/src/util.ts +207 -0
  116. package/headless/README.md +172 -0
  117. package/headless/src/answers.ts +91 -0
  118. package/headless/src/authority.ts +32 -0
  119. package/headless/src/errors.ts +36 -0
  120. package/headless/src/index.ts +17 -0
  121. package/headless/src/limits.ts +11 -0
  122. package/headless/src/pending.ts +16 -0
  123. package/headless/src/policy.ts +36 -0
  124. package/headless/src/resume.ts +103 -0
  125. package/headless/src/route.ts +153 -0
  126. package/headless/src/scheduler/clock.ts +22 -0
  127. package/headless/src/scheduler/cron.ts +19 -0
  128. package/headless/src/scheduler/firing.ts +58 -0
  129. package/headless/src/scheduler/index.ts +399 -0
  130. package/headless/src/scheduler/lease.ts +38 -0
  131. package/headless/src/scheduler/missed.ts +12 -0
  132. package/headless/src/scheduler/state.ts +132 -0
  133. package/host-builder/README.md +251 -0
  134. package/host-builder/bin/prism-host-builder.ts +169 -0
  135. package/host-builder/data/api.json +6167 -0
  136. package/host-builder/data/errors.json +546 -0
  137. package/host-builder/data/examples/acp.ts +63 -0
  138. package/host-builder/data/examples/adapters/conformance.ts +34 -0
  139. package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
  140. package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
  141. package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
  142. package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
  143. package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
  144. package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
  145. package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
  146. package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
  147. package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
  148. package/host-builder/data/examples/advisor.ts +94 -0
  149. package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
  150. package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
  151. package/host-builder/data/examples/ag-ui-server.ts +118 -0
  152. package/host-builder/data/examples/agent-durable-approval.ts +43 -0
  153. package/host-builder/data/examples/api-key-auth.ts +23 -0
  154. package/host-builder/data/examples/approval.ts +92 -0
  155. package/host-builder/data/examples/attention-compiler.ts +81 -0
  156. package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
  157. package/host-builder/data/examples/behavior-evaluation.ts +303 -0
  158. package/host-builder/data/examples/build-workflow.ts +334 -0
  159. package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
  160. package/host-builder/data/examples/caveman-ponytail.ts +197 -0
  161. package/host-builder/data/examples/cli.ts +31 -0
  162. package/host-builder/data/examples/coding-approval.ts +115 -0
  163. package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
  164. package/host-builder/data/examples/coding-compaction.ts +30 -0
  165. package/host-builder/data/examples/coding-goal-verify.ts +121 -0
  166. package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
  167. package/host-builder/data/examples/compaction.ts +36 -0
  168. package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
  169. package/host-builder/data/examples/context.ts +29 -0
  170. package/host-builder/data/examples/custom-adapter.ts +256 -0
  171. package/host-builder/data/examples/custom-builders.ts +66 -0
  172. package/host-builder/data/examples/custom-loop.ts +89 -0
  173. package/host-builder/data/examples/custom-provider.ts +70 -0
  174. package/host-builder/data/examples/custom-session-store.ts +72 -0
  175. package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
  176. package/host-builder/data/examples/decision-models.ts +98 -0
  177. package/host-builder/data/examples/define-package.ts +188 -0
  178. package/host-builder/data/examples/delegate.ts +200 -0
  179. package/host-builder/data/examples/discover-skills.ts +65 -0
  180. package/host-builder/data/examples/drive-rag-sync.ts +44 -0
  181. package/host-builder/data/examples/durable-approval.ts +139 -0
  182. package/host-builder/data/examples/durable-investigation.ts +93 -0
  183. package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
  184. package/host-builder/data/examples/enterprise-identity.ts +21 -0
  185. package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
  186. package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
  187. package/host-builder/data/examples/eval-injection.ts +73 -0
  188. package/host-builder/data/examples/eval-judges.ts +145 -0
  189. package/host-builder/data/examples/evals.ts +86 -0
  190. package/host-builder/data/examples/evaluation-gate.ts +40 -0
  191. package/host-builder/data/examples/execution-timeline.ts +173 -0
  192. package/host-builder/data/examples/external-agent.ts +541 -0
  193. package/host-builder/data/examples/external-app-db-backed.ts +344 -0
  194. package/host-builder/data/examples/governance-deny.ts +122 -0
  195. package/host-builder/data/examples/guardrail-packs.ts +240 -0
  196. package/host-builder/data/examples/headless-host.ts +245 -0
  197. package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
  198. package/host-builder/data/examples/hooks-json.ts +87 -0
  199. package/host-builder/data/examples/host-builder-agent.ts +150 -0
  200. package/host-builder/data/examples/host-hooks.ts +71 -0
  201. package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
  202. package/host-builder/data/examples/hosted-sandbox.ts +48 -0
  203. package/host-builder/data/examples/instruction-injection.ts +127 -0
  204. package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
  205. package/host-builder/data/examples/long-term-memory.ts +158 -0
  206. package/host-builder/data/examples/manifest.ts +112 -0
  207. package/host-builder/data/examples/mcp-server.ts +48 -0
  208. package/host-builder/data/examples/mcp-trust.ts +173 -0
  209. package/host-builder/data/examples/memory-and-wiki.ts +315 -0
  210. package/host-builder/data/examples/memory-lifecycle.ts +302 -0
  211. package/host-builder/data/examples/memory-system.ts +252 -0
  212. package/host-builder/data/examples/messaging-agent.ts +70 -0
  213. package/host-builder/data/examples/minimal-host-app.ts +41 -0
  214. package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
  215. package/host-builder/data/examples/model-router.ts +106 -0
  216. package/host-builder/data/examples/obscura.ts +48 -0
  217. package/host-builder/data/examples/observability.ts +116 -0
  218. package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
  219. package/host-builder/data/examples/openai-compatible.ts +70 -0
  220. package/host-builder/data/examples/package-skills.ts +85 -0
  221. package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
  222. package/host-builder/data/examples/provider-registration.ts +29 -0
  223. package/host-builder/data/examples/provider-resolver.ts +39 -0
  224. package/host-builder/data/examples/rag.ts +40 -0
  225. package/host-builder/data/examples/remote-agent-server.ts +45 -0
  226. package/host-builder/data/examples/remote-agent.ts +124 -0
  227. package/host-builder/data/examples/research-ledger.ts +79 -0
  228. package/host-builder/data/examples/revocation-propagation.ts +287 -0
  229. package/host-builder/data/examples/run-feedback.ts +93 -0
  230. package/host-builder/data/examples/scanned-document-rag.ts +48 -0
  231. package/host-builder/data/examples/sdk-basics.ts +21 -0
  232. package/host-builder/data/examples/secure-agent.ts +55 -0
  233. package/host-builder/data/examples/semantic-memory.ts +52 -0
  234. package/host-builder/data/examples/serve-tools.ts +495 -0
  235. package/host-builder/data/examples/session-memory.ts +317 -0
  236. package/host-builder/data/examples/session-search.ts +131 -0
  237. package/host-builder/data/examples/session.ts +52 -0
  238. package/host-builder/data/examples/side-call.ts +64 -0
  239. package/host-builder/data/examples/signal-agent.ts +9 -0
  240. package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
  241. package/host-builder/data/examples/skills.ts +19 -0
  242. package/host-builder/data/examples/sqlite-resume.ts +147 -0
  243. package/host-builder/data/examples/system-project-prompts.ts +74 -0
  244. package/host-builder/data/examples/system-prompts.ts +19 -0
  245. package/host-builder/data/examples/telegram-agent.ts +30 -0
  246. package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
  247. package/host-builder/data/examples/tools.ts +29 -0
  248. package/host-builder/data/examples/validator.ts +67 -0
  249. package/host-builder/data/examples/web-no-key.ts +85 -0
  250. package/host-builder/data/examples/web-research.ts +35 -0
  251. package/host-builder/data/examples/workflow-event-sink.ts +114 -0
  252. package/host-builder/data/examples/workflow-loop.ts +93 -0
  253. package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
  254. package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
  255. package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
  256. package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
  257. package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
  258. package/host-builder/data/examples.json +130 -0
  259. package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
  260. package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
  261. package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
  262. package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
  263. package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
  264. package/host-builder/skills/prism-host-builder/references/security.md +52 -0
  265. package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
  266. package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
  267. package/host-builder/src/check/child.ts +108 -0
  268. package/host-builder/src/check/conformance.ts +13 -0
  269. package/host-builder/src/check/inspect.ts +20 -0
  270. package/host-builder/src/check/manifest.ts +23 -0
  271. package/host-builder/src/check/runner.ts +181 -0
  272. package/host-builder/src/check/targets.ts +65 -0
  273. package/host-builder/src/errors.ts +35 -0
  274. package/host-builder/src/index.ts +25 -0
  275. package/host-builder/src/indexes.ts +145 -0
  276. package/host-builder/src/install/install.ts +400 -0
  277. package/host-builder/src/install/targets.ts +50 -0
  278. package/host-builder/src/lookup/api.ts +127 -0
  279. package/host-builder/src/lookup/bound.ts +38 -0
  280. package/host-builder/src/lookup/docs.ts +238 -0
  281. package/host-builder/src/lookup/errors.ts +92 -0
  282. package/host-builder/src/lookup/examples.ts +117 -0
  283. package/host-builder/src/lookup/text.ts +60 -0
  284. package/host-builder/src/server.ts +300 -0
  285. package/host-builder/src/version.ts +38 -0
  286. package/mcp-server/README.md +219 -0
  287. package/mcp-server/src/bounds.ts +23 -0
  288. package/mcp-server/src/host.ts +31 -0
  289. package/mcp-server/src/index.ts +27 -0
  290. package/mcp-server/src/serve-tools.ts +408 -0
  291. package/mcp-server/src/serve.ts +329 -0
  292. package/mcp-server/src/server.ts +331 -0
  293. package/mcp-server/src/session-map.ts +47 -0
  294. package/mcp-server/src/skill-resources.ts +85 -0
  295. package/mcp-server/src/types.ts +215 -0
  296. package/package.json +130 -4
  297. package/remote/README.md +244 -0
  298. package/remote/src/attribution.ts +22 -0
  299. package/remote/src/auth.ts +30 -0
  300. package/remote/src/bun-module.d.ts +34 -0
  301. package/remote/src/channel.ts +86 -0
  302. package/remote/src/connect.ts +212 -0
  303. package/remote/src/dispatcher.ts +282 -0
  304. package/remote/src/errors.ts +59 -0
  305. package/remote/src/host-ui.ts +152 -0
  306. package/remote/src/http-gate.ts +43 -0
  307. package/remote/src/index.ts +53 -0
  308. package/remote/src/jsonl.ts +69 -0
  309. package/remote/src/limits.ts +43 -0
  310. package/remote/src/mirror.ts +90 -0
  311. package/remote/src/pending.ts +22 -0
  312. package/remote/src/protocol.ts +107 -0
  313. package/remote/src/serve.ts +560 -0
  314. package/remote/src/session-proxy.ts +219 -0
  315. package/remote/src/sse.ts +38 -0
  316. package/remote/src/stdio-client.ts +41 -0
  317. package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
  318. package/remote/src/testing.ts +230 -0
  319. package/remote/src/transport.ts +139 -0
  320. package/remote/src/transports/client.ts +126 -0
  321. package/remote/src/transports/network.ts +268 -0
  322. package/remote/src/wire.ts +244 -0
@@ -0,0 +1,17 @@
1
+ export type { AnswerQuery, RoutedAnswer } from "./answers.js";
2
+ export { createResumeAuthority, type ResumeAuthority } from "./authority.js";
3
+ export { HeadlessError, type HeadlessErrorCode } from "./errors.js";
4
+ export { DEFAULT_MAX_ANSWERS, HARD_MAX_ANSWERS } from "./limits.js";
5
+ export { type PolicyAnswers, policyDefault } from "./policy.js";
6
+ export type { ResumeWhenAnsweredOptions, ResumeWhenAnsweredResult } from "./resume.js";
7
+ export { type HostUiRoute, type RoutedHostUi, type RouteHostUiOptions, routeHostUi } from "./route.js";
8
+ export {
9
+ createScheduler,
10
+ type ScheduleInput,
11
+ type Scheduler,
12
+ type SchedulerClock,
13
+ type SchedulerFiring,
14
+ type SchedulerOptions,
15
+ type SchedulerTarget,
16
+ type ScheduleState,
17
+ } from "./scheduler/index.js";
@@ -0,0 +1,11 @@
1
+ import type { HostUiRequestKind } from "@arnilo/prism";
2
+ import { HeadlessError } from "./errors.js";
3
+
4
+ export const DEFAULT_MAX_ANSWERS = 1_000;
5
+ export const HARD_MAX_ANSWERS = 100_000;
6
+ export const HOST_UI_KINDS: readonly HostUiRequestKind[] = ["confirm", "select", "input", "secret", "open-url", "notify", "terminal"];
7
+
8
+ export function answerLimit(value = DEFAULT_MAX_ANSWERS): number {
9
+ if (!Number.isSafeInteger(value) || value < 1 || value > HARD_MAX_ANSWERS) throw new HeadlessError("invalid_limit");
10
+ return value;
11
+ }
@@ -0,0 +1,16 @@
1
+ import { type PendingDecision, parseSuspendedRunEntry, type SessionEntry } from "@arnilo/prism";
2
+
3
+ export function pendingDecisionsOf(branch: readonly SessionEntry[]): readonly PendingDecision[] {
4
+ for (let index = branch.length - 1; index >= 0; index--) {
5
+ const entry = branch[index];
6
+ if (!entry) continue;
7
+ if (entry.kind === "package_state") continue;
8
+ if (entry.kind !== "suspended_run") return [];
9
+ try {
10
+ return parseSuspendedRunEntry(entry).interruption.pendingDecisions ?? [];
11
+ } catch {
12
+ return [];
13
+ }
14
+ }
15
+ return [];
16
+ }
@@ -0,0 +1,36 @@
1
+ import type { HostUiRequestKind } from "@arnilo/prism";
2
+ import { HeadlessError } from "./errors.js";
3
+ import { HOST_UI_KINDS } from "./limits.js";
4
+ import type { HostUiRoute } from "./route.js";
5
+
6
+ export type PolicyAnswers = Partial<{
7
+ readonly [K in HostUiRequestKind]: "unavailable" | "dismiss" | (K extends "notify" ? "ack" : never);
8
+ }>;
9
+
10
+ /** A policy can decline or acknowledge a notification, but can never approve. */
11
+ export function policyDefault(answers: PolicyAnswers = {}): HostUiRoute {
12
+ for (const [kind, action] of Object.entries(answers as Record<string, unknown>)) {
13
+ if (kind === "confirm" && action === "allow") throw new HeadlessError("policy_allow_refused");
14
+ if (
15
+ !HOST_UI_KINDS.includes(kind as HostUiRequestKind) ||
16
+ !(action === "unavailable" || action === "dismiss" || (kind === "notify" && action === "ack"))
17
+ )
18
+ throw new HeadlessError("invalid_policy");
19
+ }
20
+ const policy = { ...answers };
21
+ return {
22
+ name: "policy",
23
+ ui: {
24
+ async request(request) {
25
+ switch (policy[request.kind]) {
26
+ case "dismiss":
27
+ return { status: "dismissed" };
28
+ case "ack":
29
+ return { status: "answered", value: undefined } as never;
30
+ default:
31
+ return { status: "unavailable" };
32
+ }
33
+ },
34
+ },
35
+ };
36
+ }
@@ -0,0 +1,103 @@
1
+ import type { AgentEvent, Decision, HostUiRequest, HostUiResponse, JsonObject, PendingDecision, Session } from "@arnilo/prism";
2
+ import type { ResumeAuthority } from "./authority.js";
3
+ import { HeadlessError } from "./errors.js";
4
+ import { pendingDecisionsOf } from "./pending.js";
5
+
6
+ export type ResumeWhenAnsweredResult =
7
+ | { readonly status: "resumed"; readonly events: AsyncIterable<AgentEvent> }
8
+ | { readonly status: "aborted" | "already_resolved" | "unavailable" };
9
+
10
+ export interface ResumeWhenAnsweredOptions {
11
+ readonly signal?: AbortSignal;
12
+ }
13
+
14
+ /** Select only a single required enum property; complex object schemas use JSON input. */
15
+ function requestFor(sessionId: string, pending: PendingDecision): { request: HostUiRequest; property?: string } {
16
+ if (pending.kind !== "elicitation") return { request: { kind: "confirm", sessionId, title: pending.reason } };
17
+ const schema = pending.elicitationSchema;
18
+ const required = schema?.required;
19
+ const properties = schema?.properties;
20
+ if (
21
+ Array.isArray(required) &&
22
+ required.length === 1 &&
23
+ typeof required[0] === "string" &&
24
+ properties &&
25
+ typeof properties === "object" &&
26
+ !Array.isArray(properties) &&
27
+ Object.keys(properties).length === 1
28
+ ) {
29
+ const property = required[0];
30
+ const field = properties[property];
31
+ if (
32
+ field &&
33
+ typeof field === "object" &&
34
+ !Array.isArray(field) &&
35
+ Array.isArray(field.enum) &&
36
+ field.enum.length > 0 &&
37
+ field.enum.every((value) => typeof value === "string")
38
+ ) {
39
+ return {
40
+ property,
41
+ request: { kind: "select", sessionId, title: pending.reason, options: field.enum.map((value) => ({ value: value as string })) },
42
+ };
43
+ }
44
+ }
45
+ return { request: { kind: "input", sessionId, title: pending.reason, ...(schema ? { detail: JSON.stringify(schema) } : {}) } };
46
+ }
47
+
48
+ function decisionFrom(pending: PendingDecision, answer: HostUiResponse, route: string, property?: string): Decision | undefined {
49
+ if (answer.status === "dismissed") return { approvalId: pending.approvalId, outcome: "reject_once", reason: `dismissed via ${route}` };
50
+ if (answer.status !== "answered") return;
51
+ if (pending.kind !== "elicitation") {
52
+ if (typeof answer.value !== "boolean") return;
53
+ return { approvalId: pending.approvalId, outcome: answer.value ? "allow_once" : "reject_once" };
54
+ }
55
+ if (typeof answer.value !== "string") return;
56
+ let value: unknown;
57
+ try {
58
+ value = property ? { [property]: answer.value } : JSON.parse(answer.value);
59
+ } catch {
60
+ return;
61
+ }
62
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
63
+ return { approvalId: pending.approvalId, outcome: "allow_once", elicitation: value as JsonObject };
64
+ }
65
+
66
+ export async function resumeWhenAnswered(
67
+ authority: ResumeAuthority,
68
+ supplied: Pick<Session, "id">,
69
+ pending: readonly PendingDecision[] | undefined,
70
+ options: ResumeWhenAnsweredOptions,
71
+ offer: (
72
+ request: HostUiRequest,
73
+ approvalId: string,
74
+ signal?: AbortSignal,
75
+ accept?: (answer: HostUiResponse, route: string) => boolean,
76
+ ) => Promise<{ answer: HostUiResponse; route: string } | undefined>,
77
+ ): Promise<ResumeWhenAnsweredResult> {
78
+ const signal = options.signal;
79
+ if (signal?.aborted) return { status: "aborted" };
80
+ const session = await authority.session(supplied.id);
81
+ const current = pendingDecisionsOf(await session.entries());
82
+ if (!current.length) return { status: "already_resolved" };
83
+ // Caller-provided descriptors never supply prompts or schemas; they must match this suspension.
84
+ if (pending && (pending.length !== current.length || pending.some((item, i) => item.approvalId !== current[i]?.approvalId)))
85
+ throw new HeadlessError("stale_decisions");
86
+ const decisions: Decision[] = [];
87
+ for (const item of current) {
88
+ const { request, property } = requestFor(session.id, item);
89
+ const response = await offer(
90
+ request,
91
+ item.approvalId,
92
+ signal,
93
+ (answer, route) => decisionFrom(item, answer, route, property) !== undefined,
94
+ );
95
+ if (signal?.aborted) return { status: "aborted" };
96
+ if (!response) return { status: "unavailable" };
97
+ const decision = decisionFrom(item, response.answer, response.route, property);
98
+ if (!decision) return { status: "unavailable" };
99
+ decisions.push(decision);
100
+ }
101
+ if (signal?.aborted) return { status: "aborted" };
102
+ return { status: "resumed", events: authority.resume(session.id, decisions, { signal }) };
103
+ }
@@ -0,0 +1,153 @@
1
+ import type { HostUi, HostUiRequest, HostUiRequestKind, HostUiResponse, OwnershipScope, PendingDecision, Session } from "@arnilo/prism";
2
+ import type { CheckpointStore } from "@arnilo/prism-extensions/workflows";
3
+ import { type AnswerQuery, createAnswerLog, type RoutedAnswer } from "./answers.js";
4
+ import type { ResumeAuthority } from "./authority.js";
5
+ import { HeadlessError } from "./errors.js";
6
+ import { answerLimit, HOST_UI_KINDS } from "./limits.js";
7
+ import { type ResumeWhenAnsweredOptions, type ResumeWhenAnsweredResult, resumeWhenAnswered } from "./resume.js";
8
+
9
+ export interface HostUiRoute {
10
+ readonly name: string;
11
+ readonly ui: HostUi;
12
+ /** Absent: every kind except secret and terminal. */
13
+ readonly kinds?: readonly HostUiRequestKind[];
14
+ readonly timeoutMs?: number;
15
+ }
16
+
17
+ export interface RouteHostUiOptions {
18
+ readonly resumeAuthority?: ResumeAuthority;
19
+ readonly answerLog?: CheckpointStore;
20
+ readonly ownership?: OwnershipScope;
21
+ readonly limits?: { readonly maxAnswers?: number };
22
+ }
23
+
24
+ export interface RoutedHostUi extends HostUi {
25
+ resumeWhenAnswered(
26
+ session: Session,
27
+ pending?: readonly PendingDecision[],
28
+ options?: ResumeWhenAnsweredOptions,
29
+ ): Promise<ResumeWhenAnsweredResult>;
30
+ answers(query?: AnswerQuery): Promise<readonly RoutedAnswer[]>;
31
+ }
32
+
33
+ export function routeHostUi(routes: readonly HostUiRoute[], options: RouteHostUiOptions = {}): RoutedHostUi {
34
+ if (!routes.length) throw new HeadlessError("no_routes");
35
+ const names = new Set<string>();
36
+ for (const route of routes) {
37
+ if (typeof route.name !== "string" || !route.name.trim() || typeof route.ui?.request !== "function")
38
+ throw new HeadlessError("invalid_route");
39
+ if (names.has(route.name)) throw new HeadlessError("duplicate_route");
40
+ names.add(route.name);
41
+ if (route.kinds?.some((kind) => !HOST_UI_KINDS.includes(kind))) throw new HeadlessError("unknown_kind");
42
+ if (route.timeoutMs !== undefined && (!Number.isSafeInteger(route.timeoutMs) || route.timeoutMs < 1 || route.timeoutMs > 600_000))
43
+ throw new HeadlessError("invalid_timeout");
44
+ }
45
+ const authority = options.resumeAuthority;
46
+ const ownership = { ...options.ownership };
47
+ const configured = routes.map((route) => ({ ...route, kinds: route.kinds === undefined ? undefined : [...route.kinds] }));
48
+ const log = createAnswerLog(answerLimit(options.limits?.maxAnswers), options.answerLog, options.ownership);
49
+ const offering = new Set<string>();
50
+ const offer = async (
51
+ request: HostUiRequest,
52
+ approvalId?: string,
53
+ signal?: AbortSignal,
54
+ accept?: (answer: HostUiResponse, route: string) => boolean,
55
+ ) => {
56
+ for (const route of configured) {
57
+ if (signal?.aborted) return;
58
+ if (route.kinds ? !route.kinds.includes(request.kind) : request.kind === "secret" || request.kind === "terminal") continue;
59
+ const metadata = {
60
+ route: route.name,
61
+ kind: request.kind,
62
+ ...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }),
63
+ ...(approvalId === undefined ? {} : { approvalId }),
64
+ };
65
+ let expired = false;
66
+ let timer: ReturnType<typeof setTimeout> | undefined;
67
+ let abort: (() => void) | undefined;
68
+ const result = Promise.resolve()
69
+ .then(() => route.ui.request(request))
70
+ .then(
71
+ (answer) => {
72
+ if (expired) log.recordLate({ ...metadata, status: "late", at: new Date().toISOString() });
73
+ return {
74
+ answer,
75
+ status: validAnswer(request.kind, answer) && (!accept || accept(answer, route.name)) ? answer.status : "unavailable",
76
+ } as const;
77
+ },
78
+ () => {
79
+ if (expired) log.recordLate({ ...metadata, status: "error", at: new Date().toISOString() });
80
+ return { answer: { status: "unavailable" } as const, status: "error" } as const;
81
+ },
82
+ );
83
+ const waiting = [result];
84
+ // Resume offers have no route timeout; only the host's signal bounds their wait.
85
+ if (approvalId === undefined && route.timeoutMs !== undefined)
86
+ waiting.push(
87
+ new Promise((resolve) => {
88
+ timer = setTimeout(() => {
89
+ expired = true;
90
+ resolve({ answer: { status: "unavailable" }, status: "unavailable" });
91
+ }, route.timeoutMs);
92
+ }),
93
+ );
94
+ if (signal)
95
+ waiting.push(
96
+ new Promise((resolve) => {
97
+ abort = () => {
98
+ expired = true;
99
+ resolve({ answer: { status: "unavailable" }, status: "unavailable" });
100
+ };
101
+ signal.addEventListener("abort", abort, { once: true });
102
+ if (signal.aborted) abort();
103
+ }),
104
+ );
105
+ const outcome = await Promise.race(waiting);
106
+ clearTimeout(timer);
107
+ if (abort) signal?.removeEventListener("abort", abort);
108
+ await log.record({ ...metadata, status: outcome.status, at: new Date().toISOString() });
109
+ if (signal?.aborted) return;
110
+ if (outcome.status === "answered" || outcome.status === "dismissed") return { answer: outcome.answer, route: route.name };
111
+ }
112
+ };
113
+ return {
114
+ answers: log.answers,
115
+ async request<K extends HostUiRequestKind>(request: Extract<HostUiRequest, { kind: K }>): Promise<HostUiResponse<K>> {
116
+ return ((await offer(request))?.answer ?? { status: "unavailable" }) as HostUiResponse<K>;
117
+ },
118
+ async resumeWhenAnswered(session, pending, resumeOptions = {}) {
119
+ if (!authority) throw new HeadlessError("resume_authority_required");
120
+ for (const key of ["tenantId", "accountId", "userId"] as const) {
121
+ if (ownership[key] !== undefined && ownership[key] !== authority.ownership[key]) throw new HeadlessError("session_not_found");
122
+ }
123
+ if (offering.has(session.id)) throw new HeadlessError("resume_busy");
124
+ offering.add(session.id);
125
+ try {
126
+ return await resumeWhenAnswered(authority, session, pending, resumeOptions, offer);
127
+ } finally {
128
+ offering.delete(session.id);
129
+ }
130
+ },
131
+ };
132
+ }
133
+
134
+ function validAnswer(kind: HostUiRequestKind, answer: HostUiResponse): boolean {
135
+ if (!answer || typeof answer !== "object") return false;
136
+ if (answer.status === "dismissed" || answer.status === "unavailable") return true;
137
+ if (answer.status !== "answered") return false;
138
+ const value = answer.value;
139
+ switch (kind) {
140
+ case "confirm":
141
+ return typeof value === "boolean";
142
+ case "input":
143
+ return typeof value === "string";
144
+ case "select":
145
+ return typeof value === "string" || (Array.isArray(value) && value.every((item) => typeof item === "string"));
146
+ case "secret":
147
+ return value === undefined || typeof value === "string";
148
+ case "terminal":
149
+ return value !== null && typeof value === "object" && "exitCode" in value && Number.isInteger(value.exitCode);
150
+ default:
151
+ return value === undefined;
152
+ }
153
+ }
@@ -0,0 +1,22 @@
1
+ export interface SchedulerClock {
2
+ now(): number;
3
+ /** Must settle promptly on abort and release its timer/listener. */
4
+ sleep(ms: number, signal: AbortSignal): Promise<void>;
5
+ }
6
+
7
+ export const systemClock: SchedulerClock = {
8
+ now: Date.now,
9
+ sleep(ms, signal) {
10
+ return new Promise((resolve) => {
11
+ const done = () => {
12
+ clearTimeout(timer);
13
+ signal.removeEventListener("abort", done);
14
+ resolve();
15
+ };
16
+ // Platform timers overflow beyond 2^31-1 ms; re-arm long waits at that boundary.
17
+ const timer = setTimeout(done, Math.min(ms, 2147483647));
18
+ signal.addEventListener("abort", done, { once: true });
19
+ if (signal.aborted) done();
20
+ });
21
+ },
22
+ };
@@ -0,0 +1,19 @@
1
+ import { HeadlessError } from "../errors.js";
2
+
3
+ export function nextCron(expression: string, now: number, tz = "UTC"): string {
4
+ const { Bun } = globalThis as unknown as {
5
+ Bun: { cron: { parse(expression: string, after: number, options: { tz: string }): Date | null } };
6
+ };
7
+ try {
8
+ Bun.cron.parse("* * * * *", now, { tz });
9
+ } catch {
10
+ throw new HeadlessError("invalid_timezone");
11
+ }
12
+ try {
13
+ const next = Bun.cron.parse(expression, now, { tz });
14
+ if (!next || !Number.isFinite(next.getTime()) || next.getTime() <= now) throw new Error();
15
+ return next.toISOString();
16
+ } catch {
17
+ throw new HeadlessError("invalid_cron");
18
+ }
19
+ }
@@ -0,0 +1,58 @@
1
+ import type { JsonObject } from "@arnilo/prism";
2
+ import type { RunResultStatus } from "@arnilo/prism";
3
+ import { HeadlessError } from "../errors.js";
4
+ import type { SchedulerFiring, SchedulerTarget } from "./state.js";
5
+
6
+ /** Statuses a command may report; anything else is a completed call, and a defect is a failure. */
7
+ const COMMAND_STATUSES: readonly string[] = ["completed", "stopped", "suspended", "failed", "aborted", "succeeded", "denied"];
8
+
9
+ /**
10
+ * A command reports its own outcome in the result: a `status` from the run vocabulary or `ok: false`.
11
+ * The result itself is never persisted (it can hold note ids or text), only the status.
12
+ */
13
+ function commandStatus(result: unknown): SchedulerFiring["status"] {
14
+ if (result === null || typeof result !== "object" || Array.isArray(result)) return "completed";
15
+ const value = (result as { status?: unknown; ok?: unknown }).status;
16
+ if (typeof value === "string" && COMMAND_STATUSES.includes(value)) return value as RunResultStatus;
17
+ return (result as { ok?: unknown }).ok === false ? "failed" : "completed";
18
+ }
19
+
20
+ export async function runFiring(
21
+ target: SchedulerTarget,
22
+ input: string | JsonObject,
23
+ parentId: string,
24
+ firingId: string,
25
+ ): Promise<SchedulerFiring> {
26
+ const base = { firingId };
27
+ const session = await target.agent.session(
28
+ target.kind === "agent" ? { parent: { sessionId: parentId, agentId: target.agent.id } } : { id: parentId },
29
+ );
30
+ try {
31
+ if (target.kind === "agent") {
32
+ const result = await session.run(input as string, target.runOptions);
33
+ return { ...base, sessionId: session.id, status: result.status };
34
+ }
35
+ if (target.kind === "command") {
36
+ // No model call: the command runs on the schedule session, which is already durable.
37
+ const result = await target.agent.commands.run(target.command, input as JsonObject, { session });
38
+ return { ...base, sessionId: session.id, status: commandStatus(result) };
39
+ }
40
+ const result = (await target.agent.commands.run(target.command, input as JsonObject, { session })) as {
41
+ workflowRunId?: unknown;
42
+ status?: unknown;
43
+ };
44
+ if (
45
+ !result ||
46
+ typeof result.workflowRunId !== "string" ||
47
+ !result.workflowRunId ||
48
+ !["succeeded", "failed", "aborted", "suspended", "denied"].includes(result.status as string)
49
+ )
50
+ throw new HeadlessError("invalid_workflow_result");
51
+ return { ...base, workflowRunId: result.workflowRunId, status: result.status as SchedulerFiring["status"] };
52
+ } catch {
53
+ // Persist status only; arbitrary target errors can contain secrets or input values.
54
+ return { ...base, ...(target.kind === "agent" || target.kind === "command" ? { sessionId: session.id } : {}), status: "failed" };
55
+ } finally {
56
+ await session.close();
57
+ }
58
+ }