@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30

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 (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,130 @@
1
+ import { type Agent, type AgentStore, type NewRevision, type Revision, type RevisionPlace, type RevisionRow } from "@parcha/pi-durable-agent";
2
+ import { ApiError } from "./errors.js";
3
+ import { type DefinitionBody, type Json } from "./validate.js";
4
+ import type { SignInView } from "./sign-ins.js";
5
+ /** One agent as the routes show it: its row, its current revision and that revision's number (the oldest is 1). */
6
+ export type AgentEntry = {
7
+ agent: Agent;
8
+ revision: Revision | null;
9
+ version: number;
10
+ revisions: number;
11
+ runs: {
12
+ count: number;
13
+ live: number;
14
+ };
15
+ sizes: Map<string, number>;
16
+ };
17
+ /** SQLITE_BUSY or SQLITE_LOCKED: another connection holds the database. */
18
+ export declare const sqliteBusy: (error: unknown) => boolean;
19
+ /** How long a request waits for a busy agent store, step by step: short first, so a reader's overlap costs
20
+ * milliseconds; about 2 s in all, then the request answers home_busy. */
21
+ export declare const REQUEST_BUSY_MS: readonly number[];
22
+ /** `act` again while another connection holds the store: after busy `attempt`, `onBusy` hears of it and the next of
23
+ * `delaysMs` is waited out without blocking the event loop. Past the last, the busy error is thrown. */
24
+ export declare function whenFree<T>(act: () => T | Promise<T>, delaysMs: readonly number[], onBusy?: (attempt: number, delayMs: number | undefined) => void): Promise<T>;
25
+ /** A store another writer holds: SQLite's busy or locked, or the agent home's own `busy` (a home held past its deadline, or a
26
+ * store a stopped writer left mid-write). Every answer of the server maps it the same way: home_busy. */
27
+ export declare const storeBusy: (error: unknown) => boolean;
28
+ /** The answer to a request the agent store stayed busy for. */
29
+ export declare const homeBusy: () => ApiError;
30
+ /** A store error as the request's answer: a busy store is retryable, a refusal names the field it refused. */
31
+ export declare function storeError(error: unknown, field?: string): never;
32
+ export declare class Agents {
33
+ readonly dir: string;
34
+ /** Never waits for another connection synchronously: what touches it goes through `request` or `whenFree`. */
35
+ readonly store: AgentStore;
36
+ /** Read-only, for the store's skill texts, which its reads do not return. */
37
+ private readonly skills;
38
+ constructor(dir: string);
39
+ /** A read or write of the store for a request: a busy store is waited for about 2 s (REQUEST_BUSY_MS). */
40
+ request<T>(act: () => T | Promise<T>): Promise<T>;
41
+ private closed;
42
+ close(): void;
43
+ /** Skill texts by their SHA-256. */
44
+ private texts;
45
+ /** The revision a checked definition makes; `files` are its skill files by path. */
46
+ private revisionOf;
47
+ /** `definition.version`, when given, is the number of the revision the request leaves current. */
48
+ private checkVersion;
49
+ /** A workflow revision is checked before anything is written, so a refusal makes no agent. */
50
+ private checked;
51
+ /** A new agent and its first revision, current. A definition id already here is `409 agent_exists`. `check` sees the
52
+ * revision before anything is written, and may refuse it. */
53
+ /** `fresh`: the place a new agent that names none is saved with, and the tools it gets when it names none (place.ts
54
+ * newAgentPlace); an agentic definition alone takes them, and only where it leaves them out. */
55
+ create({ definition, skills, note }: DefinitionBody, check?: (revision: NewRevision) => Promise<void>, fresh?: {
56
+ place: RevisionPlace;
57
+ tools: readonly string[];
58
+ }): Promise<AgentEntry>;
59
+ /** An edit: a new revision of the agent, its parent the current one, made current. Without `skills` the current
60
+ * revision's skill files carry over. An edit that is the current revision writes nothing, so a PUT sent twice makes
61
+ * one revision. The store keeps an agent's id, name and description from its creation. `ifCurrent` (from If-Match)
62
+ * is the current revision the caller read, null for none: the store compares it in the commit's own transaction.
63
+ * `check` sees the revision, the current one's included, before anything is written, and may refuse it. */
64
+ /** `contract`: the contract's edit, whose version the caller has checked is past the current one. It always makes a new
65
+ * revision, the same definition included, numbered as this store numbers them (the next), whatever version it named. */
66
+ commit(read: AgentEntry, { definition, skills, note }: DefinitionBody, { ifCurrent, check, contract }?: {
67
+ ifCurrent?: string | null;
68
+ check?: (revision: NewRevision) => Promise<void>;
69
+ contract?: boolean;
70
+ }): Promise<AgentEntry>;
71
+ /** Makes `revision`, one of the agent's own, its current one. */
72
+ setCurrent(entry: AgentEntry, revision: string): Promise<AgentEntry>;
73
+ /** Archives or unarchives an agent or a run. */
74
+ setArchived(kind: "agent" | "run", id: string, archived: boolean): Promise<void>;
75
+ /** The agent's revisions, newest first, each with its number. */
76
+ revisions(id: string): Promise<Array<RevisionRow & {
77
+ version: number;
78
+ }>>;
79
+ /** Revision `id` and its number, or null when it is not one of `agent`'s. */
80
+ revision(agent: string, id: string): Promise<{
81
+ revision: Revision;
82
+ version: number;
83
+ } | null>;
84
+ /** The agent `id`, or null. `runs` saves a read when the caller holds every run already. */
85
+ get(id: string): Promise<AgentEntry | null>;
86
+ private entry;
87
+ /** Every agent here, newest first. */
88
+ list(): Promise<AgentEntry[]>;
89
+ }
90
+ /** The agent's ETag: its current revision, which only an edit or `POST .../current` moves. */
91
+ export declare const etagOf: (entry: AgentEntry) => string;
92
+ /** A revision as a definition, as `POST /agents` takes one, numbered. */
93
+ export declare function definitionOf(agent: Agent, revision: Revision, version: number): Json;
94
+ /** `Agent` as the contract shows it, with its current revision and its saved sign-ins (sign-ins.ts view: never a ref). */
95
+ export declare function agentView(entry: AgentEntry, signIns?: readonly SignInView[]): {
96
+ agent_id: string;
97
+ definition: Json | null;
98
+ kind: "workflow" | "agentic" | null;
99
+ revision: string | null;
100
+ revisions: number;
101
+ source: null;
102
+ skills: {
103
+ path: string;
104
+ sha256: string;
105
+ size_bytes: number | null;
106
+ }[];
107
+ sign_ins: readonly SignInView[];
108
+ runs: {
109
+ count: number;
110
+ live: number;
111
+ };
112
+ region: string;
113
+ home_etag: string;
114
+ archived_at: string | null;
115
+ created_at: string;
116
+ updated_at: string;
117
+ };
118
+ /** One revision as `GET .../revisions` lists it. */
119
+ export declare function revisionView(agent: Agent, row: RevisionRow & {
120
+ version: number;
121
+ }, revision: Revision): {
122
+ revision: string;
123
+ version: number;
124
+ parent: string | null;
125
+ kind: import("@parcha/pi-durable-agent").RevisionKind;
126
+ current: boolean;
127
+ note: string | null;
128
+ created_at: string;
129
+ definition: Json;
130
+ };
package/dist/agents.js ADDED
@@ -0,0 +1,308 @@
1
+ // The agents this server holds: one agent store of @parcha/pi-durable-agent in the data directory (`store.sqlite`), many
2
+ // agents in it, each with revisions written once. A definition is one revision; an edit commits the next, its parent
3
+ // the current one, and makes it current.
4
+ import { createHash } from "node:crypto";
5
+ import { join } from "node:path";
6
+ import { DatabaseSync } from "node:sqlite";
7
+ import { AgentHomeError, openStore, STORE_FILE } from "@parcha/pi-durable-agent";
8
+ import { ApiError, invalid } from "./errors.js";
9
+ import { DEFAULT_HARNESS, harnessOfBody } from "./harness.js";
10
+ import { isObject, skillIssues, skillNames, stable } from "./validate.js";
11
+ /** SQLITE_BUSY or SQLITE_LOCKED: another connection holds the database. */
12
+ export const sqliteBusy = (error) => isObject(error) && error.code === "ERR_SQLITE_ERROR" && typeof error.errcode === "number" && [5, 6].includes(error.errcode & 0xff);
13
+ /** How long a request waits for a busy agent store, step by step: short first, so a reader's overlap costs
14
+ * milliseconds; about 2 s in all, then the request answers home_busy. */
15
+ export const REQUEST_BUSY_MS = [10, 20, 50, 100, 200, 400, 600, 600];
16
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
17
+ /** `act` again while another connection holds the store: after busy `attempt`, `onBusy` hears of it and the next of
18
+ * `delaysMs` is waited out without blocking the event loop. Past the last, the busy error is thrown. */
19
+ export async function whenFree(act, delaysMs, onBusy) {
20
+ for (let attempt = 0;; attempt++) {
21
+ try {
22
+ return await act();
23
+ }
24
+ catch (error) {
25
+ if (!sqliteBusy(error))
26
+ throw error;
27
+ const delay = delaysMs[attempt];
28
+ onBusy?.(attempt, delay);
29
+ if (delay === undefined)
30
+ throw error;
31
+ await sleep(delay);
32
+ }
33
+ }
34
+ }
35
+ /** A store another writer holds: SQLite's busy or locked, or the agent home's own `busy` (a home held past its deadline, or a
36
+ * store a stopped writer left mid-write). Every answer of the server maps it the same way: home_busy. */
37
+ export const storeBusy = (error) => sqliteBusy(error) || (error instanceof AgentHomeError && error.code === "busy");
38
+ /** The answer to a request the agent store stayed busy for. */
39
+ export const homeBusy = () => new ApiError("home_busy", "the agent store is busy with another write; try again", { retry_after_ms: 500 });
40
+ /** A store error as the request's answer: a busy store is retryable, a refusal names the field it refused. */
41
+ export function storeError(error, field = "definition") {
42
+ if (storeBusy(error))
43
+ throw homeBusy();
44
+ if (error instanceof AgentHomeError && error.code === "invalid") {
45
+ // A workflow's refusal carries every issue, each at its path under the field.
46
+ const issues = error.issues;
47
+ if (issues?.length)
48
+ throw invalid(issues.map((issue) => ({ field: `${field}${issue.path}`, reason: "invalid", code: issue.code, message: issue.message })), error.message);
49
+ throw invalid([{ field, reason: "invalid", message: error.message }]);
50
+ }
51
+ if (error instanceof AgentHomeError && error.code === "missing")
52
+ throw new ApiError("not_found", error.message);
53
+ if (error instanceof AgentHomeError && error.code === "stale")
54
+ throw new ApiError("precondition_failed", "the agent's current revision moved since the If-Match it was read at: read the agent again");
55
+ throw error;
56
+ }
57
+ export class Agents {
58
+ dir;
59
+ /** Never waits for another connection synchronously: what touches it goes through `request` or `whenFree`. */
60
+ store;
61
+ /** Read-only, for the store's skill texts, which its reads do not return. */
62
+ skills;
63
+ constructor(dir) {
64
+ this.dir = dir;
65
+ this.store = openStore(dir, { busyTimeoutMs: 0 });
66
+ this.skills = new DatabaseSync(join(dir, STORE_FILE), { readOnly: true, timeout: 0 });
67
+ }
68
+ /** A read or write of the store for a request: a busy store is waited for about 2 s (REQUEST_BUSY_MS). */
69
+ request(act) {
70
+ return whenFree(act, REQUEST_BUSY_MS);
71
+ }
72
+ closed = false;
73
+ close() {
74
+ if (this.closed)
75
+ return;
76
+ this.closed = true;
77
+ this.skills.close();
78
+ this.store.close();
79
+ }
80
+ /** Skill texts by their SHA-256. */
81
+ texts(shas) {
82
+ const out = new Map();
83
+ const read = this.skills.prepare("SELECT content FROM skills WHERE sha256 = ?");
84
+ for (const sha of shas) {
85
+ const row = read.get(sha);
86
+ if (typeof row?.content === "string")
87
+ out.set(sha, row.content);
88
+ }
89
+ return out;
90
+ }
91
+ /** The revision a checked definition makes; `files` are its skill files by path. */
92
+ revisionOf(definition, files, note) {
93
+ const issues = skillIssues(definition.skills, Object.keys(files));
94
+ if (issues.length)
95
+ throw invalid(issues);
96
+ // The default harness is never stored: naming pi and naming none are one revision.
97
+ const harness = typeof definition.harness === "string" && definition.harness !== DEFAULT_HARNESS ? { harness: definition.harness } : {};
98
+ // Unlike the harness, a place is kept when it is runner: the default is the host's, so naming runner says something.
99
+ const place = isObject(definition.place) ? { place: definition.place } : {};
100
+ // A capability with nothing set is none: `{web_search: {}}` and no settings are one revision.
101
+ const kept = Object.entries(isObject(definition.tool_settings) ? definition.tool_settings : {}).filter(([, setting]) => isObject(setting) && Object.keys(setting).length);
102
+ const set = kept.length ? { toolSettings: Object.fromEntries(kept) } : {};
103
+ const common = { skills: files, tools: definition.tools ?? [], ...harness, ...place, ...set, ...(note !== undefined ? { note } : {}) };
104
+ if (isObject(definition.workflow))
105
+ return { kind: "workflow", workflow: definition.workflow, ...common };
106
+ // The learning switch is kept whenever a definition sets it, false included; a definition that leaves it out keeps
107
+ // none, and its revision id is the one it had before the switch.
108
+ const learning = typeof definition.learning === "boolean" ? { learning: definition.learning } : {};
109
+ return { kind: "agentic", instructions: definition.instructions, ...(typeof definition.model === "string" ? { model: definition.model } : {}), ...(typeof definition.thinking === "string" ? { thinking: definition.thinking } : {}), ...common, ...learning, ...(typeof definition.max_cost_usd === "number" && definition.max_cost_usd > 0 ? { maxCostUsd: definition.max_cost_usd } : {}) };
110
+ }
111
+ /** `definition.version`, when given, is the number of the revision the request leaves current. */
112
+ checkVersion(definition, version) {
113
+ if (definition.version !== undefined && definition.version !== version)
114
+ throw invalid([{ field: "definition.version", reason: "not_an_option", message: `definition.version is ${version} here: the number of the revision this definition leaves current` }]);
115
+ }
116
+ /** A workflow revision is checked before anything is written, so a refusal makes no agent. */
117
+ async checked(revision) {
118
+ if (revision.kind !== "workflow")
119
+ return;
120
+ const { checkWorkflowBody } = await import("@parcha/pi-durable-agent/workflow");
121
+ await checkWorkflowBody({ workflow: revision.workflow, tools: revision.tools ?? [] }).catch((error) => storeError(error, "definition.workflow"));
122
+ }
123
+ /** A new agent and its first revision, current. A definition id already here is `409 agent_exists`. `check` sees the
124
+ * revision before anything is written, and may refuse it. */
125
+ /** `fresh`: the place a new agent that names none is saved with, and the tools it gets when it names none (place.ts
126
+ * newAgentPlace); an agentic definition alone takes them, and only where it leaves them out. */
127
+ async create({ definition, skills = {}, note }, check, fresh) {
128
+ const given = typeof definition.id === "string" ? definition.id : undefined;
129
+ if (given !== undefined && (await this.request(() => this.store.readAgent(given))))
130
+ throw new ApiError("agent_exists", `an agent ${given} exists here`);
131
+ // Stamped on the revision now, never resolved at run time: an agent saved with no place keeps running on the runner.
132
+ const stamped = fresh && definition.place === undefined && !isObject(definition.workflow) ? { place: fresh.place, ...(definition.tools === undefined ? { tools: [...fresh.tools] } : {}) } : {};
133
+ const revision = this.revisionOf({ ...definition, ...stamped }, skills, note);
134
+ this.checkVersion(definition, 1);
135
+ await this.checked(revision);
136
+ await check?.(revision);
137
+ let agent;
138
+ try {
139
+ agent = await this.request(() => this.store.createAgent({ name: definition.name, ...(typeof definition.description === "string" ? { description: definition.description } : {}), ...(given !== undefined ? { id: given } : {}) }));
140
+ }
141
+ catch (error) {
142
+ if (error instanceof AgentHomeError && error.code === "exists")
143
+ throw new ApiError("agent_exists", `an agent ${given} exists here`);
144
+ storeError(error);
145
+ }
146
+ await this.request(() => this.store.commitRevision(agent.id, revision, { setCurrent: true })).catch((error) => storeError(error));
147
+ return (await this.get(agent.id));
148
+ }
149
+ /** An edit: a new revision of the agent, its parent the current one, made current. Without `skills` the current
150
+ * revision's skill files carry over. An edit that is the current revision writes nothing, so a PUT sent twice makes
151
+ * one revision. The store keeps an agent's id, name and description from its creation. `ifCurrent` (from If-Match)
152
+ * is the current revision the caller read, null for none: the store compares it in the commit's own transaction.
153
+ * `check` sees the revision, the current one's included, before anything is written, and may refuse it. */
154
+ /** `contract`: the contract's edit, whose version the caller has checked is past the current one. It always makes a new
155
+ * revision, the same definition included, numbered as this store numbers them (the next), whatever version it named. */
156
+ async commit(read, { definition, skills, note }, { ifCurrent, check, contract = false } = {}) {
157
+ const held = (now) => {
158
+ if (ifCurrent !== undefined && (now.revision?.id ?? null) !== ifCurrent)
159
+ storeError(new AgentHomeError("stale", "the agent's current revision is not the one the commit expects"));
160
+ return now;
161
+ };
162
+ let entry = held((await this.get(read.agent.id)) ?? read);
163
+ const { agent } = entry;
164
+ const kept = [
165
+ ...(definition.id !== undefined && definition.id !== agent.id ? [{ field: "definition.id", reason: "not_an_option", message: `definition.id is ${agent.id}, the agent's id` }] : []),
166
+ ...["name", "description"]
167
+ .filter((key) => definition[key] !== undefined && definition[key] !== agent[key])
168
+ .map((key) => ({ field: `definition.${key}`, reason: "not_allowed", message: `The agent store keeps an agent's ${key} from its creation; an edit does not change it.`, fix: `Remove definition.${key}.` })),
169
+ ];
170
+ if (kept.length)
171
+ throw invalid(kept);
172
+ // Each try builds the revision on the current one, checks it and commits it on that one: a current revision another
173
+ // writer moved since the build is sent back as stale, and the next try builds and checks again on the new one, so
174
+ // what an edit leaves out (skill files, harness, place, learning) is never carried over from a revision it does not
175
+ // follow.
176
+ for (let tries = 1;; tries++) {
177
+ if (tries > 1)
178
+ entry = held((await this.get(agent.id)) ?? entry);
179
+ let files = skills;
180
+ if (files === undefined) {
181
+ const held = Object.entries(entry.revision?.body.skills ?? {});
182
+ const texts = await this.request(() => this.texts(held.map(([, sha]) => sha)));
183
+ files = Object.fromEntries(held.map(([path, sha]) => [path, texts.get(sha) ?? ""]));
184
+ }
185
+ // An edit that names no harness, place, learning switch or default cap keeps the agent's, as it keeps its skill
186
+ // files: absent here is unchanged, not the default.
187
+ const harness = entry.revision?.body.harness;
188
+ const place = entry.revision?.body.place;
189
+ const learning = entry.revision?.kind === "agentic" && !isObject(definition.workflow) ? entry.revision.body.learning : undefined;
190
+ // And its default cap: leaving it out never removes a spend limit; only 0 clears it.
191
+ const cap = entry.revision?.kind === "agentic" && !isObject(definition.workflow) ? entry.revision.body.maxCostUsd : undefined;
192
+ const revision = this.revisionOf({ ...definition, ...(definition.harness === undefined && harness ? { harness } : {}), ...(definition.place === undefined && place ? { place } : {}), ...(definition.learning === undefined && learning !== undefined ? { learning } : {}), ...(definition.max_cost_usd === undefined && cap !== undefined ? { max_cost_usd: cap } : {}) }, files, note);
193
+ await this.checked(revision);
194
+ await check?.(revision);
195
+ const base = entry.revision?.id ?? null;
196
+ const attempt = async () => {
197
+ const now = held(this.entry(agent.id) ?? entry);
198
+ if ((now.revision?.id ?? null) !== base)
199
+ throw new AgentHomeError("stale", "the agent's current revision moved while the edit was checked");
200
+ if (!contract && now.revision && sameRevision(now.revision, revision)) {
201
+ this.checkVersion(definition, now.version);
202
+ return now;
203
+ }
204
+ if (!contract)
205
+ this.checkVersion(definition, now.revisions + 1);
206
+ await this.store.commitRevision(agent.id, revision, { setCurrent: true, ifCurrent: base });
207
+ return undefined;
208
+ };
209
+ try {
210
+ return (await this.request(attempt)) ?? (await this.get(agent.id));
211
+ }
212
+ catch (error) {
213
+ // Without If-Match an edit goes on the revision current when it commits: one moved under it is read again.
214
+ if (ifCurrent === undefined && tries < 5 && error instanceof AgentHomeError && error.code === "stale")
215
+ continue;
216
+ storeError(error);
217
+ }
218
+ }
219
+ }
220
+ /** Makes `revision`, one of the agent's own, its current one. */
221
+ async setCurrent(entry, revision) {
222
+ await this.request(() => this.store.setCurrent(entry.agent.id, revision)).catch((error) => storeError(error, "revision"));
223
+ return (await this.get(entry.agent.id));
224
+ }
225
+ /** Archives or unarchives an agent or a run. */
226
+ async setArchived(kind, id, archived) {
227
+ await this.request(() => this.store.setArchived(kind, id, archived)).catch((error) => storeError(error));
228
+ }
229
+ /** The agent's revisions, newest first, each with its number. */
230
+ revisions(id) {
231
+ return this.request(() => {
232
+ const rows = this.store.listRevisions(id);
233
+ return rows.map((row, index) => ({ ...row, version: rows.length - index }));
234
+ });
235
+ }
236
+ /** Revision `id` and its number, or null when it is not one of `agent`'s. */
237
+ async revision(agent, id) {
238
+ const row = (await this.revisions(agent)).find((r) => r.id === id);
239
+ return row ? { revision: await this.request(() => this.store.readRevision(id)), version: row.version } : null;
240
+ }
241
+ /** The agent `id`, or null. `runs` saves a read when the caller holds every run already. */
242
+ get(id) {
243
+ return this.request(() => this.entry(id));
244
+ }
245
+ entry(id, runs) {
246
+ const found = this.store.readAgent(id);
247
+ if (!found)
248
+ return null;
249
+ const at = found.revisions.findIndex((revision) => revision.current);
250
+ const revision = at < 0 ? null : (({ current: _, ...rest }) => rest)(found.revisions[at]);
251
+ const own = (runs ?? this.store.listRuns({ agent: id })).filter((run) => run.agent === id);
252
+ const sizes = new Map();
253
+ if (revision)
254
+ for (const [sha, text] of this.texts(Object.values(revision.body.skills)))
255
+ sizes.set(sha, Buffer.byteLength(text, "utf8"));
256
+ const live = own.filter((run) => run.state === "running").length;
257
+ return { agent: found.agent, revision, version: at < 0 ? 0 : found.revisions.length - at, revisions: found.revisions.length, runs: { count: own.length, live }, sizes };
258
+ }
259
+ /** Every agent here, newest first. */
260
+ list() {
261
+ return this.request(() => {
262
+ const runs = this.store.listRuns();
263
+ return this.store
264
+ .listAgents()
265
+ .map((row) => this.entry(row.id, runs))
266
+ .sort((a, b) => b.agent.createdAt.localeCompare(a.agent.createdAt) || a.agent.id.localeCompare(b.agent.id));
267
+ });
268
+ }
269
+ }
270
+ /** Whether `next` would be `current` again: the same kind and body, skills by their SHA-256. */
271
+ function sameRevision(current, next) {
272
+ const { kind, note: _, skills = {}, ...rest } = next;
273
+ const body = { ...rest, skills: Object.fromEntries(Object.entries(skills).map(([path, text]) => [path, createHash("sha256").update(text).digest("hex")])), tools: next.tools ?? [] };
274
+ return current.kind === kind && stable(current.body) === stable(body);
275
+ }
276
+ /** The agent's ETag: its current revision, which only an edit or `POST .../current` moves. */
277
+ export const etagOf = (entry) => `"${entry.revision?.id ?? "none"}"`;
278
+ /** A revision as a definition, as `POST /agents` takes one, numbered. */
279
+ export function definitionOf(agent, revision, version) {
280
+ const body = revision.kind === "agentic"
281
+ ? { instructions: revision.body.instructions, ...(revision.body.model ? { model: revision.body.model } : {}), ...(revision.body.thinking ? { thinking: revision.body.thinking } : {}), ...(revision.body.learning !== undefined ? { learning: revision.body.learning } : {}), ...(revision.body.maxCostUsd !== undefined ? { max_cost_usd: revision.body.maxCostUsd } : {}) }
282
+ : { workflow: revision.body.workflow };
283
+ return { id: agent.id, version, name: agent.name, ...(agent.description !== undefined ? { description: agent.description } : {}), ...body, harness: harnessOfBody(revision.body), ...(revision.body.place ? { place: revision.body.place } : {}), skills: skillNames(Object.keys(revision.body.skills)), tools: revision.body.tools, ...(revision.body.toolSettings ? { tool_settings: revision.body.toolSettings } : {}) };
284
+ }
285
+ /** `Agent` as the contract shows it, with its current revision and its saved sign-ins (sign-ins.ts view: never a ref). */
286
+ export function agentView(entry, signIns = []) {
287
+ const { agent, revision } = entry;
288
+ return {
289
+ agent_id: agent.id,
290
+ definition: revision ? definitionOf(agent, revision, entry.version) : null,
291
+ kind: revision?.kind ?? null,
292
+ revision: revision?.id ?? null,
293
+ revisions: entry.revisions,
294
+ source: null,
295
+ skills: Object.entries(revision?.body.skills ?? {}).map(([path, sha]) => ({ path, sha256: sha, size_bytes: entry.sizes.get(sha) ?? null })),
296
+ sign_ins: signIns,
297
+ runs: entry.runs,
298
+ region: "local",
299
+ home_etag: etagOf(entry),
300
+ archived_at: agent.archivedAt ?? null,
301
+ created_at: agent.createdAt,
302
+ updated_at: revision && revision.createdAt > agent.createdAt ? revision.createdAt : agent.createdAt,
303
+ };
304
+ }
305
+ /** One revision as `GET .../revisions` lists it. */
306
+ export function revisionView(agent, row, revision) {
307
+ return { revision: row.id, version: row.version, parent: row.parent, kind: row.kind, current: row.current, note: row.note ?? null, created_at: row.createdAt, definition: definitionOf(agent, revision, row.version) };
308
+ }
package/dist/app.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { AppContext, AppOptions } from "@parcha/pi-durable-disk";
2
+ import { promptOf } from "./skills.js";
3
+ /** The workflow adapters this host gives every run: model nodes, and calls `via: "tool"` to the table's tools. Typed
4
+ * questions (`runJudge`) run too where the host sets a decision provider's key (decisions.ts). */
5
+ export declare const WORKFLOW_ADAPTERS: readonly ["runNode", "runEffect"];
6
+ export { promptOf };
7
+ export default function app(where: AppContext): Promise<AppOptions>;