@parcha/agentrun-serve 0.1.0-beta.59 → 0.1.0-beta.61

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 (250) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +230 -120
  3. package/dist/acp-package.d.ts +4 -0
  4. package/dist/agent-delete.d.ts +6 -9
  5. package/dist/agent-delete.js +5 -3
  6. package/dist/agent-package.js +11 -1
  7. package/dist/api-only.d.ts +21 -3
  8. package/dist/api-only.js +41 -6
  9. package/dist/archil-routes.d.ts +4 -1
  10. package/dist/archil-routes.js +15 -12
  11. package/dist/archil-settings.d.ts +18 -8
  12. package/dist/archil-settings.js +35 -17
  13. package/dist/browser-person.d.ts +1 -1
  14. package/dist/browser-person.js +1 -1
  15. package/dist/calendar/tools.js +1 -1
  16. package/dist/chatgpt-plan.d.ts +4 -2
  17. package/dist/chatgpt-plan.js +13 -3
  18. package/dist/claude-login-token.d.ts +5 -0
  19. package/dist/claude-login-token.js +8 -0
  20. package/dist/claude-login.d.ts +49 -3
  21. package/dist/claude-login.js +140 -10
  22. package/dist/cli-learning/connections.js +1 -1
  23. package/dist/cli.js +42 -10
  24. package/dist/console/assets/{backend-BztxEAvb.js → backend-C9ffXUR5.js} +1 -1
  25. package/dist/console/assets/index-BnZV3lvW.js +639 -0
  26. package/dist/console/assets/{share-L84tlUDW.js → share-B1o5mJ56.js} +2 -2
  27. package/dist/console/assets/{styles-CaRKlHke.js → styles-D_znYrHR.js} +31 -31
  28. package/dist/console/assets/styles-fjQBFfMv.css +1 -0
  29. package/dist/console/index.html +3 -3
  30. package/dist/console/share.html +3 -3
  31. package/dist/decisions.d.ts +1 -1
  32. package/dist/decisions.js +2 -2
  33. package/dist/errors.d.ts +1 -0
  34. package/dist/errors.js +2 -0
  35. package/dist/factory-activity.d.ts +68 -0
  36. package/dist/factory-activity.js +153 -0
  37. package/dist/factory-runs.d.ts +11 -0
  38. package/dist/factory-runs.js +52 -0
  39. package/dist/filed-tool.d.ts +32 -0
  40. package/dist/filed-tool.js +122 -0
  41. package/dist/harness-check.js +2 -1
  42. package/dist/harness-keys.d.ts +1 -2
  43. package/dist/harness-keys.js +1 -2
  44. package/dist/harness-recipe.d.ts +13 -2
  45. package/dist/harness-recipe.js +30 -7
  46. package/dist/harness-sign-in.js +2 -1
  47. package/dist/harness-table.d.ts +9 -3
  48. package/dist/harness-table.js +11 -5
  49. package/dist/harness.js +6 -2
  50. package/dist/import-worker.js +2 -2
  51. package/dist/import.d.ts +9 -0
  52. package/dist/import.js +11 -1
  53. package/dist/key-refusal.d.ts +5 -0
  54. package/dist/key-refusal.js +30 -18
  55. package/dist/learn/audit.d.ts +20 -22
  56. package/dist/learn/audit.js +72 -55
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +35 -43
  59. package/dist/learn/commit.js +62 -270
  60. package/dist/learn/compile.d.ts +4 -4
  61. package/dist/learn/compile.js +6 -7
  62. package/dist/learn/corrections.js +1 -1
  63. package/dist/learn/delete.d.ts +5 -12
  64. package/dist/learn/delete.js +17 -30
  65. package/dist/learn/forget-run.d.ts +16 -0
  66. package/dist/learn/forget-run.js +53 -0
  67. package/dist/learn/index.js +1 -1
  68. package/dist/learn/learning-of.d.ts +0 -4
  69. package/dist/learn/learning-of.js +0 -5
  70. package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
  71. package/dist/learn/{folder.js → legacy/folder.js} +4 -7
  72. package/dist/learn/legacy/place.d.ts +16 -0
  73. package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
  74. package/dist/learn/legacy/scrub.d.ts +28 -0
  75. package/dist/learn/legacy/scrub.js +258 -0
  76. package/dist/learn/promote.d.ts +40 -66
  77. package/dist/learn/promote.js +69 -207
  78. package/dist/learn/reset-ledger.d.ts +18 -0
  79. package/dist/learn/reset-ledger.js +14 -0
  80. package/dist/learn/rows.d.ts +186 -0
  81. package/dist/learn/rows.js +376 -0
  82. package/dist/learn/secrets.d.ts +2 -1
  83. package/dist/learn/secrets.js +2 -2
  84. package/dist/learn/workflow-draft.d.ts +4 -1
  85. package/dist/learn/workflow-draft.js +12 -2
  86. package/dist/learned-nodes.d.ts +36 -0
  87. package/dist/learned-nodes.js +23 -0
  88. package/dist/learning-reset.d.ts +1 -1
  89. package/dist/learning-reset.js +9 -11
  90. package/dist/learning-routes.d.ts +60 -81
  91. package/dist/learning-routes.js +187 -360
  92. package/dist/learning-words.d.ts +2 -0
  93. package/dist/learning-words.js +2 -0
  94. package/dist/learning.d.ts +18 -24
  95. package/dist/learning.js +35 -66
  96. package/dist/local-model.d.ts +144 -0
  97. package/dist/local-model.js +214 -0
  98. package/dist/mcp-gateway.d.ts +6 -0
  99. package/dist/mcp-gateway.js +44 -8
  100. package/dist/mcp-probe.d.ts +7 -0
  101. package/dist/mcp-probe.js +7 -0
  102. package/dist/mcp-resources.d.ts +1 -1
  103. package/dist/native/discovery.d.ts +6 -0
  104. package/dist/native/discovery.js +14 -1
  105. package/dist/native/remote.d.ts +5 -0
  106. package/dist/native/remote.js +16 -0
  107. package/dist/native/runtime.js +3 -2
  108. package/dist/observation/observer.d.ts +6 -6
  109. package/dist/ollama-provider.d.ts +35 -0
  110. package/dist/ollama-provider.js +108 -2
  111. package/dist/openapi.js +147 -35
  112. package/dist/place-offers.d.ts +3 -0
  113. package/dist/place-offers.js +3 -0
  114. package/dist/place.d.ts +35 -12
  115. package/dist/place.js +67 -29
  116. package/dist/print.js +1 -1
  117. package/dist/purged-workflow.d.ts +0 -33
  118. package/dist/purged-workflow.js +3 -71
  119. package/dist/redact/match.d.ts +36 -8
  120. package/dist/redact/match.js +179 -44
  121. package/dist/run-export.js +4 -2
  122. package/dist/run-launch.d.ts +3 -3
  123. package/dist/run-learning-served.d.ts +3 -3
  124. package/dist/run-learning-served.js +1 -1
  125. package/dist/run-listing.d.ts +1 -1
  126. package/dist/run-timeline-served.d.ts +1 -1
  127. package/dist/run-timeline-served.js +6 -5
  128. package/dist/run-usage.js +3 -2
  129. package/dist/runnable.js +25 -8
  130. package/dist/runner/adapter-loop.d.ts +8 -1
  131. package/dist/runner/adapter-loop.js +100 -20
  132. package/dist/runner/adapter-run-spec.d.ts +3 -5
  133. package/dist/runner/adapter-run-spec.js +35 -61
  134. package/dist/runner/adapters/pi.d.ts +3 -2
  135. package/dist/runner/adapters/pi.js +3 -1
  136. package/dist/runner/audit.d.ts +3 -5
  137. package/dist/runner/audit.js +28 -51
  138. package/dist/runner/cli-run-spec.js +19 -22
  139. package/dist/runner/compare-end.d.ts +1 -3
  140. package/dist/runner/compare-end.js +6 -2
  141. package/dist/runner/disk-free.d.ts +15 -4
  142. package/dist/runner/disk-free.js +25 -7
  143. package/dist/runner/dispatch.js +2 -2
  144. package/dist/runner/feedback-round.d.ts +1 -1
  145. package/dist/runner/feedback-round.js +2 -2
  146. package/dist/runner/harness-loops.d.ts +9 -0
  147. package/dist/runner/harness-loops.js +49 -7
  148. package/dist/runner/held.d.ts +4 -11
  149. package/dist/runner/held.js +0 -25
  150. package/dist/runner/journal-kinds.d.ts +4 -1
  151. package/dist/runner/journal-kinds.js +1 -1
  152. package/dist/runner/learned-first.d.ts +0 -2
  153. package/dist/runner/learned-first.js +3 -3
  154. package/dist/runner/learning-end.d.ts +12 -16
  155. package/dist/runner/learning-end.js +41 -75
  156. package/dist/runner/learning-seed.d.ts +13 -16
  157. package/dist/runner/learning-seed.js +13 -23
  158. package/dist/runner/live-ticker.js +3 -4
  159. package/dist/runner/main.js +1 -1
  160. package/dist/runner/mcp-claim.js +3 -2
  161. package/dist/runner/mcp-run.d.ts +23 -4
  162. package/dist/runner/mcp-run.js +31 -2
  163. package/dist/runner/metrics.d.ts +4 -0
  164. package/dist/runner/metrics.js +9 -3
  165. package/dist/runner/monid-run.js +3 -1
  166. package/dist/runner/native-loop.js +3 -4
  167. package/dist/runner/promotion.d.ts +19 -28
  168. package/dist/runner/promotion.js +50 -69
  169. package/dist/runner/redact.d.ts +3 -0
  170. package/dist/runner/redact.js +7 -0
  171. package/dist/runner/reflect-hook.d.ts +2 -2
  172. package/dist/runner/reflect-hook.js +4 -1
  173. package/dist/runner/run-child-host.d.ts +1 -9
  174. package/dist/runner/run-child-host.js +12 -68
  175. package/dist/runner/runner.d.ts +1 -1
  176. package/dist/runner/sdk-loop.js +7 -7
  177. package/dist/runner/workflow-calls.d.ts +4 -1
  178. package/dist/runner/workflow-calls.js +35 -18
  179. package/dist/runner/workflow-loop.d.ts +1 -1
  180. package/dist/runner/workflow-loop.js +3 -1
  181. package/dist/runner/workflow-spec.d.ts +4 -0
  182. package/dist/runner/workflow-spec.js +18 -13
  183. package/dist/runs-over-store.d.ts +2 -2
  184. package/dist/runs-over-store.js +1 -1
  185. package/dist/sdk/check.d.ts +1 -4
  186. package/dist/sdk/check.js +2 -3
  187. package/dist/sdk/runs.d.ts +20 -7
  188. package/dist/sdk/runs.js +105 -68
  189. package/dist/secret-cut.js +7 -4
  190. package/dist/secret-rules.js +97 -83
  191. package/dist/secrets.d.ts +4 -0
  192. package/dist/secrets.js +44 -10
  193. package/dist/server-fs.d.ts +1 -1
  194. package/dist/server-fs.js +1 -1
  195. package/dist/server-keys.d.ts +6 -0
  196. package/dist/server-keys.js +12 -0
  197. package/dist/server.d.ts +22 -15
  198. package/dist/server.js +311 -198
  199. package/dist/slack.js +2 -1
  200. package/dist/source-sync/auxiliary.js +2 -2
  201. package/dist/store/index.d.ts +1 -1
  202. package/dist/store/index.js +1 -1
  203. package/dist/store/postgres/migrate.js +3 -1
  204. package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
  205. package/dist/store/schema.d.ts +28 -2
  206. package/dist/store/schema.js +81 -5
  207. package/dist/store/sqlite/learning-rows.d.ts +23 -0
  208. package/dist/store/sqlite/learning-rows.js +559 -0
  209. package/dist/store/sqlite/store.d.ts +7 -1
  210. package/dist/store/sqlite/store.js +84 -18
  211. package/dist/store/store.d.ts +219 -6
  212. package/dist/store/store.js +13 -0
  213. package/dist/store-reads/journal.d.ts +33 -3
  214. package/dist/store-reads/journal.js +99 -4
  215. package/dist/store-reads/learning.d.ts +23 -26
  216. package/dist/store-reads/learning.js +42 -30
  217. package/dist/store-reads/loop.js +1 -1
  218. package/dist/store-view.d.ts +24 -2
  219. package/dist/store-view.js +40 -11
  220. package/dist/templates.d.ts +10 -2
  221. package/dist/templates.js +31 -4
  222. package/dist/tool-plane.d.ts +27 -3
  223. package/dist/tool-plane.js +79 -4
  224. package/dist/tools.d.ts +12 -2
  225. package/dist/tools.js +42 -7
  226. package/dist/trigger-launch-hook.d.ts +2 -2
  227. package/dist/trigger-launch-hook.js +1 -1
  228. package/dist/triggers.d.ts +7 -4
  229. package/dist/triggers.js +4 -4
  230. package/dist/web-holds.d.ts +2 -0
  231. package/dist/web-holds.js +5 -2
  232. package/dist/web-run.js +2 -1
  233. package/dist/workspace/archil-exec.js +1 -1
  234. package/dist/workspace/archil.d.ts +1 -1
  235. package/dist/workspace/archil.js +1 -1
  236. package/dist/workspace/computer-deps.js +5 -3
  237. package/dist/workspace/computer-providers.d.ts +11 -1
  238. package/dist/workspace/computer-providers.js +29 -2
  239. package/dist/workspace/index.d.ts +1 -2
  240. package/dist/workspace/index.js +1 -2
  241. package/dist/workspace/paths.d.ts +0 -4
  242. package/dist/workspace/paths.js +0 -6
  243. package/dist/workspace/workspace.d.ts +1 -1
  244. package/dist/workspace/workspace.js +1 -1
  245. package/package.json +13 -13
  246. package/templates/TOOLS.md +46 -0
  247. package/dist/console/assets/index-LwNL4L9q.js +0 -619
  248. package/dist/console/assets/styles-DQo8rzY-.css +0 -1
  249. package/dist/workspace/learning-workspace.d.ts +0 -24
  250. /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
@@ -57,6 +57,8 @@ export declare const said: {
57
57
  stopped: (cause: string) => string;
58
58
  /** A run whose learning seed predates a reset of its agent's learning (runner/learning-end.ts, reason `reset`). */
59
59
  reset: string;
60
+ /** A run whose learning seed predates a run's purge (learn/commit.ts `purged`, reason `purged_since_seed`). */
61
+ purgedSinceSeed: string;
60
62
  };
61
63
  /** A run's learning in words as a read says them, whole: what it learned and what waits for the owner's OK, said again
62
64
  * from its parts (`workflows`, `corrections`, `problems`), each name cut by `cut` first (the host's secrets as they are
@@ -113,6 +113,8 @@ export const said = {
113
113
  stopped: (cause) => `Not kept: learning stopped (${cause}).`,
114
114
  /** A run whose learning seed predates a reset of its agent's learning (runner/learning-end.ts, reason `reset`). */
115
115
  reset: "Dropped: its learning seed predates a reset of the agent's learning.",
116
+ /** A run whose learning seed predates a run's purge (learn/commit.ts `purged`, reason `purged_since_seed`). */
117
+ purgedSinceSeed: "Dropped: another run's learning was purged after this run started, so nothing it learned is kept.",
116
118
  };
117
119
  /** A run's learning in words as a read says them, whole: what it learned and what waits for the owner's OK, said again
118
120
  * from its parts (`workflows`, `corrections`, `problems`), each name cut by `cut` first (the host's secrets as they are
@@ -1,7 +1,5 @@
1
1
  import { type Problem } from "./learn/index.js";
2
- import { type LearningFolder } from "./learn/folder.js";
3
- import type { Store } from "./store/index.js";
4
- import type { Workspace } from "./workspace/index.js";
2
+ import { type AgentLearning } from "./learn/rows.js";
5
3
  export { learnsOf } from "./learning-setting.js";
6
4
  /** The server's learning switch (`--learning`, AGENTRUN_SERVE_LEARNING; capabilities.features.learning). `on`, the
7
5
  * default: a run learns when its agent's definition says `learning: true`. `off`: no run this server starts does. */
@@ -15,7 +13,7 @@ export declare function learningOf(env: NodeJS.ProcessEnv, given?: string): Lear
15
13
  * is on main, or `dropped` with a reason from the closed list. A learning fault never refuses a run: it starts with
16
14
  * nothing learned, `seed_failed`. */
17
15
  export declare const LEARNING_STATES: readonly ["seeded", "reflecting", "merged", "dropped"];
18
- export declare const LEARNING_REASONS: readonly ["seed_failed", "no_budget", "unknown_cost", "cancelled", "crashed", "reflect_failed", "empty", "checker", "use", "reset"];
16
+ export declare const LEARNING_REASONS: readonly ["seed_failed", "no_budget", "unknown_cost", "cancelled", "crashed", "reflect_failed", "empty", "checker", "use", "reset", "purged_since_seed"];
19
17
  /** A run's own `learning` on its start (POST /agents/{agent_id}/runs): it starts from what its agent learned, as a run that
20
18
  * learns does, and keeps nothing (no compile, no correction, at any end), so runs of one agent read one learned state
21
19
  * however many run at once. Its learning ends `dropped`, reason `use`. */
@@ -112,7 +110,7 @@ export declare const detailShown: (learning: Learning, shown: Shown, max?: numbe
112
110
  export declare const learningView: (learning: Learning, shown: Shown) => {
113
111
  workflows?: LearnedFile[];
114
112
  state: "dropped" | "merged" | "seeded" | "reflecting";
115
- reason: "cancelled" | "reset" | "use" | "empty" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "checker" | null;
113
+ reason: "cancelled" | "reset" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "empty" | "checker" | "use" | "purged_since_seed" | null;
116
114
  detail: string | null;
117
115
  at: string;
118
116
  };
@@ -127,7 +125,7 @@ export declare function shortOf<T extends {
127
125
  at: string;
128
126
  }>({ state, reason, detail, at: _, ...rest }: T): {
129
127
  state: "dropped" | "merged" | "seeded" | "reflecting";
130
- reason: "cancelled" | "reset" | "use" | "empty" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "checker" | null;
128
+ reason: "cancelled" | "reset" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "empty" | "checker" | "use" | "purged_since_seed" | null;
131
129
  detail: string | null;
132
130
  } & Omit<T, "at" | "reason" | "detail" | "state">;
133
131
  /** The label of the end-of-run turn's timeline rows, and the kind and label of a run's learning row. */
@@ -163,24 +161,20 @@ export declare const LEARNED_WORKFLOWS_BUDGET: number;
163
161
  export declare const workflowLine: ({ name, description, workflow }: Pick<LearnedWorkflow, "name" | "description"> & {
164
162
  workflow?: string;
165
163
  }) => string;
166
- /** The agent's learning folder: `learning/` in its folder on the disk, which only the host writes. The folder is files.ts
167
- * agentFolderOf (server-fs.ts agentDiskDir), so two ids that differ only in case never share one. */
168
- export declare const learningRepo: (data: string, agentId: string) => string;
169
- /** Runs `work` once every call queued before it on the agent's folder has finished: one at a time per agent, in this
170
- * process. Everything that touches an agent's folder goes through it, so two runs made at once never both make it. */
171
- export declare const withAgentRepo: <T>(data: string, agentId: string, work: () => Promise<T>) => Promise<T>;
172
- /** Agent `agentId`'s learning folder (learn/folder.ts learningWorkspace), in this server's place: Mode 1's local folder
173
- * under `data`. The one point that names the place; its `end()` is called in a finally after every use. */
174
- export declare const learningFolderOf: (data: string, agentId: string) => LearningFolder;
175
- /** The seed of a run of agent `agentId` about to be made: main's commit, the folder made first when it is absent (the
176
- * learning script's init), what main holds for a run (seedIn), and when it was read (`at`). In the agent's queue, as a
177
- * reset is (learning-reset.ts). No git in this process: the folder's own script and file API. */
178
- export declare function seedOf(data: string, agentId: string): Promise<Seed>;
179
- /** What commit `commit` of the folder holds for a run, as seedOf reads main (one read-only exec of the script), but a
180
- * learned workflow a purged run wrote, by `store`'s runs (purged-workflow.ts): no claim lays, checks, replays or serves
181
- * it. `store` null: a run's own process, which reads no other run; its runner reads the seed again with its store
182
- * (runner/learning-seed.ts). No commit (null) is the empty seed; a commit the folder no longer holds throws. */
183
- export declare function seedAt(ws: Workspace, commit: string | null, store: Pick<Store, "runs"> | null): Promise<Seed>;
164
+ /** Runs `work` once every call queued before it on agent `agentId`'s learning has finished: one at a time per agent, in
165
+ * this process. A run's seed read and a reset of the agent's learning (learning-reset.ts) go through it, so a seed is
166
+ * read wholly before a reset or wholly after. Keyed by the agent's folder (files.ts agentFolderOf): two ids that
167
+ * differ only in case share one queue. */
168
+ export declare const inLearningQueue: <T>(data: string, agentId: string, work: () => Promise<T>) => Promise<T>;
169
+ /** The seed of a run of agent `agentId` about to be made: its learning's newest save (its first, empty, made when it has
170
+ * none, so every seed names one), what it holds for a run (seedIn), and when it was read (`at`). In the agent's queue, as
171
+ * a reset is (learning-reset.ts). */
172
+ export declare function seedOf(data: string, store: {
173
+ readonly learning: Pick<AgentLearning["rows"], "seed">;
174
+ }, agentId: string): Promise<Seed>;
175
+ /** What save `save` of the agent's learning holds for a run, as seedOf reads the newest, read now: a purged run's
176
+ * workflow is gone from it. No save (null) is the empty seed; a save the agent's learning no longer holds throws. */
177
+ export declare function seedAt(learning: AgentLearning, save: string | null): Promise<Seed>;
184
178
  /** Whether `text` holds a host secret (`shown`): as written, or, read as JSON, in any string it decodes to (its escapes
185
179
  * decoded), or nested past the bound. The one check a learned workflow's text passes at a run's start (chooseWorkflows)
186
180
  * and every text its compile turn is told (runner/learning-end.ts compileAskOf); a text that is not JSON is read as
package/dist/learning.js CHANGED
@@ -1,24 +1,16 @@
1
- // Learning: an agent whose definition says `learning: true` keeps a folder of what it learned, and each of its runs
2
- // starts from it. The folder is `learning/` in the agent's folder on the disk (files.ts agentFolderOf): plain git with
3
- // main checked out, reached through its Workspace (learningWorkspace). It holds two things:
1
+ // Learning: an agent whose definition says `learning: true` keeps what it learned, and each of its runs starts from it.
2
+ // It is kept as versioned rows in the store (Store.learning; learn/rows.ts reads and writes them as files):
4
3
  // - corrections.md, its owner's standing corrections (learn/corrections.ts): every run of the agent is served it whole
5
4
  // under `# Learned` (laidLearned), cut of the host's secrets;
6
5
  // - workflows/<name>/, the workflows its runs compiled (learn/compile.ts): a run whose input one fits is answered by it
7
6
  // (runner/workflow-first.ts).
8
- // Every write to main is one exec of the learning script (learn/folder.ts), which also writes `.agentrun/snapshot.json`,
9
- // what the routes and a run's seed read: no git runs in this process. When a run of such an agent is made, the server
10
- // makes the folder if it is absent (the script's init: one empty host commit on main) and reads main's snapshot; the
11
- // run's launch keeps the commit it started from and its # Learned text, so its runner reads no folder.
12
- //
13
- // The host never follows a symbolic link into the folder (learn/folder.ts learningWorkspace, and the script): a link
14
- // there is refused, and the run starts with nothing learned.
15
- import { join } from "node:path";
7
+ // When a run of such an agent is made, the server reads its newest save (its first, empty, made when there is none);
8
+ // the run's launch keeps the save it started from and its # Learned text.
16
9
  import { CORRECTIONS_FILE, decodedStrings, frontMatter, learnedSecretShapes, redactLearned, valueMatcher } from "./learn/index.js";
17
- import { folderAt, learningInit, learningWorkspace, readLearning } from "./learn/folder.js";
10
+ import { readAt, readOf } from "./learn/rows.js";
18
11
  import { agentFolderOf, serialBy } from "./files.js";
19
12
  import { withoutLoopbackAddresses } from "./key-refusal.js";
20
13
  import { DETAIL_MAX, LIST_DETAIL, said, short, wordsOf } from "./learning-words.js";
21
- import { purgeGate } from "./purged-workflow.js";
22
14
  export { learnsOf } from "./learning-setting.js";
23
15
  /** The server's learning switch (`--learning`, AGENTRUN_SERVE_LEARNING; capabilities.features.learning). `on`, the
24
16
  * default: a run learns when its agent's definition says `learning: true`. `off`: no run this server starts does. */
@@ -36,7 +28,7 @@ export function learningOf(env, given) {
36
28
  * is on main, or `dropped` with a reason from the closed list. A learning fault never refuses a run: it starts with
37
29
  * nothing learned, `seed_failed`. */
38
30
  export const LEARNING_STATES = ["seeded", "reflecting", "merged", "dropped"];
39
- export const LEARNING_REASONS = ["seed_failed", "no_budget", "unknown_cost", "cancelled", "crashed", "reflect_failed", "empty", "checker", "use", "reset"];
31
+ export const LEARNING_REASONS = ["seed_failed", "no_budget", "unknown_cost", "cancelled", "crashed", "reflect_failed", "empty", "checker", "use", "reset", "purged_since_seed"];
40
32
  /** A run's own `learning` on its start (POST /agents/{agent_id}/runs): it starts from what its agent learned, as a run that
41
33
  * learns does, and keeps nothing (no compile, no correction, at any end), so runs of one agent read one learned state
42
34
  * however many run at once. Its learning ends `dropped`, reason `use`. */
@@ -160,69 +152,46 @@ function compactSchema(schema, schemas, depth = 0, defs = {}) {
160
152
  return s.enum.map((value) => JSON.stringify(value)).join("|");
161
153
  return typeof s.type === "string" ? s.type : Array.isArray(s.type) ? s.type.join("|") : "any";
162
154
  }
163
- /** The agent's learning folder: `learning/` in its folder on the disk, which only the host writes. The folder is files.ts
164
- * agentFolderOf (server-fs.ts agentDiskDir), so two ids that differ only in case never share one. */
165
- export const learningRepo = (data, agentId) => join(agentFolderOf(data, agentId), "learning");
166
155
  const queues = new Map();
167
- /** Runs `work` once every call queued before it on the agent's folder has finished: one at a time per agent, in this
168
- * process. Everything that touches an agent's folder goes through it, so two runs made at once never both make it. */
169
- export const withAgentRepo = (data, agentId, work) => serialBy(queues, learningRepo(data, agentId), work);
170
- /** Agent `agentId`'s learning folder (learn/folder.ts learningWorkspace), in this server's place: Mode 1's local folder
171
- * under `data`. The one point that names the place; its `end()` is called in a finally after every use. */
172
- export const learningFolderOf = (data, agentId) => learningWorkspace({ mode: "local", agentId, data });
173
- /** The seed of `snapshot` (undefined: no main yet), each body read by `text`: corrections.md, and each active draft's
174
- * README.md and workflow.json. A draft whose README's front matter does not read one way is never read as active. */
175
- async function seedIn(sha, snapshot, text) {
176
- const corrections = snapshot?.corrections ? await text(CORRECTIONS_FILE, snapshot.corrections.oid) : "";
156
+ /** Runs `work` once every call queued before it on agent `agentId`'s learning has finished: one at a time per agent, in
157
+ * this process. A run's seed read and a reset of the agent's learning (learning-reset.ts) go through it, so a seed is
158
+ * read wholly before a reset or wholly after. Keyed by the agent's folder (files.ts agentFolderOf): two ids that
159
+ * differ only in case share one queue. */
160
+ export const inLearningQueue = (data, agentId, work) => serialBy(queues, agentFolderOf(data, agentId), work);
161
+ /** The seed of a read (its view undefined: no save yet): corrections.md, and each active draft's README.md and
162
+ * workflow.json. A draft whose README's front matter does not read one way is never read as active. */
163
+ function seedIn(read) {
164
+ const corrections = read.text(CORRECTIONS_FILE) ?? "";
177
165
  const workflows = [];
178
- for (const item of snapshot?.workflows ?? []) {
166
+ for (const item of read.view?.workflows ?? []) {
179
167
  if (item.status !== "active")
180
168
  continue;
181
- const readme = item.files.find((file) => file.path.endsWith("/README.md"));
182
- const json = item.files.find((file) => file.path.endsWith("/workflow.json"));
183
- if (!readme || !json)
169
+ const readme = read.text(item.file);
170
+ const json = read.text(item.files.find((file) => file.path.endsWith("/workflow.json"))?.path ?? "");
171
+ if (readme === undefined || json === undefined)
184
172
  continue;
185
- const front = frontMatter(await text(readme.path, readme.oid));
173
+ const front = frontMatter(readme);
186
174
  if (!front)
187
175
  continue;
188
- workflows.push({ name: item.name, description: front.get("description") ?? "", workflow: await text(json.path, json.oid) });
176
+ workflows.push({ name: item.name, description: front.get("description") ?? "", workflow: json });
189
177
  }
190
- return { sha, corrections, workflows };
178
+ return { sha: read.view?.main ?? null, corrections, workflows };
191
179
  }
192
- /** The seed of a run of agent `agentId` about to be made: main's commit, the folder made first when it is absent (the
193
- * learning script's init), what main holds for a run (seedIn), and when it was read (`at`). In the agent's queue, as a
194
- * reset is (learning-reset.ts). No git in this process: the folder's own script and file API. */
195
- export function seedOf(data, agentId) {
196
- return withAgentRepo(data, agentId, async () => {
197
- const { workspace, end } = learningFolderOf(data, agentId);
198
- try {
199
- await learningInit(workspace);
200
- const seed = await readLearning(workspace, async ({ snapshot, body }) => seedIn(snapshot?.main ?? null, snapshot, body));
201
- return { ...seed, at: Date.now() };
202
- }
203
- finally {
204
- await end();
205
- }
206
- });
180
+ /** The seed of a run of agent `agentId` about to be made: its learning's newest save (its first, empty, made when it has
181
+ * none, so every seed names one), what it holds for a run (seedIn), and when it was read (`at`). In the agent's queue, as
182
+ * a reset is (learning-reset.ts). */
183
+ export function seedOf(data, store, agentId) {
184
+ return inLearningQueue(data, agentId, async () => ({ ...seedIn(readOf(await store.learning.seed(agentId))), at: Date.now() }));
207
185
  }
208
- /** What commit `commit` of the folder holds for a run, as seedOf reads main (one read-only exec of the script), but a
209
- * learned workflow a purged run wrote, by `store`'s runs (purged-workflow.ts): no claim lays, checks, replays or serves
210
- * it. `store` null: a run's own process, which reads no other run; its runner reads the seed again with its store
211
- * (runner/learning-seed.ts). No commit (null) is the empty seed; a commit the folder no longer holds throws. */
212
- export async function seedAt(ws, commit, store) {
213
- if (commit === null)
186
+ /** What save `save` of the agent's learning holds for a run, as seedOf reads the newest, read now: a purged run's
187
+ * workflow is gone from it. No save (null) is the empty seed; a save the agent's learning no longer holds throws. */
188
+ export async function seedAt(learning, save) {
189
+ if (save === null)
214
190
  return { sha: null, corrections: "", workflows: [] };
215
- const at = await folderAt(ws, commit);
216
- if (!at)
217
- throw new Error(`the learning folder's read at ${commit} is gone`);
218
- const purged = store ? (await purgeGate(at.snapshot, store)).workflows : new Map();
219
- const seed = await seedIn(commit, at.snapshot, async (_path, oid) => {
220
- const bytes = at.blobs.get(oid);
221
- if (!bytes)
222
- throw new Error(`the learning folder's read at ${commit} holds no blob ${oid}`);
223
- return bytes.toString("utf8");
224
- });
225
- return { ...seed, workflows: seed.workflows.filter(({ name }) => !purged.has(name)) };
191
+ const read = await readAt(learning, save);
192
+ if (!read)
193
+ throw new Error(`the agent's learning holds no save ${save}`);
194
+ return seedIn(read);
226
195
  }
227
196
  /** Whether `text` holds a host secret (`shown`): as written, or, read as JSON, in any string it decodes to (its escapes
228
197
  * decoded), or nested past the bound. The one check a learned workflow's text passes at a run's start (chooseWorkflows)
@@ -0,0 +1,144 @@
1
+ import { type OllamaPullLine } from "./ollama-provider.js";
2
+ /** The GPU where it is cheap to read: Apple silicon's unified memory (darwin on arm64), an NVIDIA card as nvidia-smi names
3
+ * it, else unknown. */
4
+ export type Gpu = {
5
+ readonly kind: "apple";
6
+ readonly unified: true;
7
+ } | {
8
+ readonly kind: "nvidia";
9
+ readonly name: string;
10
+ readonly memory_bytes: number;
11
+ } | {
12
+ readonly kind: "unknown";
13
+ };
14
+ /** What this machine is. */
15
+ export type Machine = {
16
+ readonly platform: string;
17
+ readonly arch: string;
18
+ readonly ram_bytes: number;
19
+ readonly gpu: Gpu;
20
+ };
21
+ /** The Ollama here: whether this server asks one at all (never under the faux model or a model gateway, model.ts
22
+ * asksOllama), whether it answered, and the version it says. */
23
+ export type OllamaFacts = {
24
+ readonly asked: false;
25
+ readonly reachable: false;
26
+ readonly version: null;
27
+ } | {
28
+ readonly asked: true;
29
+ readonly reachable: false;
30
+ readonly version: null;
31
+ } | {
32
+ readonly asked: true;
33
+ readonly reachable: true;
34
+ readonly version: string;
35
+ };
36
+ /** Everything the recommendation reads: the machine, its Ollama, and the tags that Ollama has pulled. */
37
+ export type LocalFacts = {
38
+ readonly machine: Machine;
39
+ readonly ollama: OllamaFacts;
40
+ readonly pulled: readonly string[];
41
+ };
42
+ /** The model recommended here, and why in words; `tag` null where none fits, and the words say what to do instead. */
43
+ export type Recommendation = {
44
+ readonly tag: string;
45
+ readonly why: string;
46
+ readonly pulled: boolean;
47
+ } | {
48
+ readonly tag: null;
49
+ readonly why: string;
50
+ readonly pulled: false;
51
+ };
52
+ /** The non-Apple pick, and Apple's where Inkling does not run: one line. A measurement (qwen3:8b against qwen3:30b-a3b,
53
+ * through this server's own runs) sets it. */
54
+ export declare const QWEN3_DEFAULT = "qwen3:8b";
55
+ /** Apple silicon's pick, where its Ollama runs it (MLX, on Apple silicon alone). */
56
+ export declare const INKLING = "inkling-2-mini";
57
+ /** The first Ollama that runs INKLING. */
58
+ export declare const INKLING_OLLAMA = "0.40.17";
59
+ /** Where Ollama is installed from. */
60
+ export declare const OLLAMA_DOWNLOAD = "https://ollama.com/download";
61
+ /** The least memory (total RAM; Apple silicon's unified memory) each tag is offered on, in GiB: its weights at Ollama's
62
+ * default quantization, the KV cache of the context this server asks (ollama-provider.ts contextOf), and room for the
63
+ * system. A machine sold as 16 GB reads about 15.5 GiB, so each floor sits under the size it is meant for. */
64
+ export declare const RAM_FLOOR_GIB: Readonly<Record<string, number>>;
65
+ /** Every tag the recommendation can name, and so the only tags a pull here takes. */
66
+ export declare const LOCAL_MODEL_TAGS: readonly string[];
67
+ /** A tag as Ollama lists it: with no `:`, `:latest`. */
68
+ export declare const fullTag: (tag: string) => string;
69
+ /** `version` at or past `floor`, both dotted numbers (a suffix such as `-rc1` ignored); an unreadable version is not. */
70
+ export declare function versionAtLeast(version: string, floor: string): boolean;
71
+ /**
72
+ * The model this server recommends for `facts`, and why. No Ollama: none, and where to install it. Apple silicon with an
73
+ * Ollama at INKLING_OLLAMA or later and the memory for it: INKLING. Everyone else: QWEN3_DEFAULT, or the next smaller qwen3
74
+ * that fits in memory, or none, saying what each needs; Apple silicon on an older Ollama is told to update for INKLING. A
75
+ * tag already pulled says so: no pull needed.
76
+ */
77
+ export declare function recommendLocalModel(facts: LocalFacts): Recommendation;
78
+ /** How long nvidia-smi is waited for. */
79
+ export declare const NVIDIA_SMI_TIMEOUT_MS = 2000;
80
+ /** nvidia-smi's first line, `<name>, <MiB>`, as a GPU; unknown for anything else. */
81
+ export declare function nvidiaOf(out: string | undefined): Gpu;
82
+ /** This machine, read once: what a server serves for its life. A test hands its own (ServeOptions.machine). */
83
+ export declare function readMachine(): Promise<Machine>;
84
+ /** The pull here, as the read surface shows it. */
85
+ export type PullView = {
86
+ tag: string;
87
+ state: "pulling" | "done" | "failed";
88
+ status: string;
89
+ completed_bytes: number;
90
+ total_bytes: number;
91
+ error?: string;
92
+ };
93
+ /** One pull at a time, through `pull`; `finished` once it succeeds (the listing dropped and read again), before it reads
94
+ * done. A log line at its start, its end and its failure: the tag, the bytes and the milliseconds, nothing else. */
95
+ export declare function localPulls({ pull, finished, log, signal }: {
96
+ pull: (tag: string, onLine: (line: OllamaPullLine) => void, signal: AbortSignal) => Promise<void>;
97
+ finished: (tag: string) => Promise<void>;
98
+ log?: (line: string) => void;
99
+ signal: AbortSignal;
100
+ }): {
101
+ view: () => PullView | null;
102
+ pulling: () => boolean;
103
+ /** Starts pulling `tag` (checked by the caller), behind the answer. */
104
+ start(tag: string): PullView;
105
+ };
106
+ export type LocalPulls = ReturnType<typeof localPulls>;
107
+ /** Whether the Ollama `env` names is on another machine: OLLAMA_HOST names an address that is not this machine's own
108
+ * (a loopback name). This server reads only its own memory and GPU, so it recommends and pulls nothing for that one. An
109
+ * address the base rule refuses is no Ollama asked at all, and not said to be elsewhere. */
110
+ export declare function ollamaElsewhere(env: NodeJS.ProcessEnv): boolean;
111
+ /** The words for an Ollama on another machine (ollamaElsewhere), which never name its address. */
112
+ export declare const OLLAMA_ELSEWHERE = "The Ollama OLLAMA_HOST names is on another machine, and this server reads only its own memory and GPU, so it recommends and pulls no model for that one. Pull one where that Ollama runs: ollama pull <tag>.";
113
+ /** Why no pull is made through the Ollama `env` names, in words, or undefined where one may: the faux model or a model
114
+ * gateway takes every model here (asksOllama); a server that is not one owner's own on their own machine (`notOwn`,
115
+ * server.ts whyNotOwnMachine's reasons) pulls nothing into an Ollama that is not theirs. */
116
+ export declare function pullRefusal(env: NodeJS.ProcessEnv, notOwn: readonly string[]): string | undefined;
117
+ /** What GET /settings/local-model and POST /settings/local-model/pull read. */
118
+ export type LocalModelDeps = {
119
+ env: NodeJS.ProcessEnv;
120
+ notOwn: readonly string[];
121
+ machine: () => Promise<Machine>;
122
+ pulls: LocalPulls;
123
+ };
124
+ /** The read surface: the machine, its Ollama, the recommendation, the pull here, and whether a pull may be made. */
125
+ export declare function localModelView({ env, notOwn, machine, pulls }: LocalModelDeps): Promise<{
126
+ machine: Machine;
127
+ ollama: OllamaFacts;
128
+ recommended: Recommendation;
129
+ pull: PullView | null;
130
+ can_pull: boolean;
131
+ refused: string | null;
132
+ }>;
133
+ /** POST /settings/local-model/pull: `{ tag }`, one of LOCAL_MODEL_TAGS (422 otherwise), where a pull may be made (403 in
134
+ * words otherwise), none under way (409 local_model_pulling). Answers the read surface with the pull started. */
135
+ export declare function pullLocalModel(deps: LocalModelDeps, body: unknown): Promise<{
136
+ machine: Machine;
137
+ ollama: OllamaFacts;
138
+ recommended: Recommendation;
139
+ pull: PullView | null;
140
+ can_pull: boolean;
141
+ refused: string | null;
142
+ }>;
143
+ /** The real pull: through the Ollama `env` names (ollama-provider.ts ollamaPull). */
144
+ export declare const pullThrough: (env: () => NodeJS.ProcessEnv, stallMs?: number) => (tag: string, onLine: (line: OllamaPullLine) => void, signal: AbortSignal) => Promise<void>;
@@ -0,0 +1,214 @@
1
+ // A free local model on the owner's own machine: what the machine is (platform, arch, memory, GPU) and its Ollama, the
2
+ // model this server recommends for it (recommendLocalModel, a pure function of those facts), and one pull of it at a time
3
+ // through that Ollama, its progress on the read surface (GET /settings/local-model). A pull is only ever of a tag the
4
+ // recommendation can name (LOCAL_MODEL_TAGS), and only where the Ollama here is the owner's own: one owner's own server on
5
+ // their own machine (server.ts whyNotOwnMachine, the rule ollama-provider.ts ollamaHostOf names the default address by),
6
+ // never under the faux model or a model gateway (model.ts asksOllama). Once a pull ends, the kept listing is dropped
7
+ // (ollamaForget), so the model is in the picker at once.
8
+ import { execFile } from "node:child_process";
9
+ import { arch, platform, totalmem } from "node:os";
10
+ import { ApiError } from "./errors.js";
11
+ import { isLoopbackName } from "./host-check.js";
12
+ import { asksOllama, FAUX_ENV } from "./model.js";
13
+ import { ollamaBase, ollamaModels, ollamaPull, ollamaVersion } from "./ollama-provider.js";
14
+ import { logLine } from "./print.js";
15
+ import { registerSecretPage, registerSecretWrite } from "./secret-writes.js";
16
+ import { isObject, unknownFields } from "./validate.js";
17
+ // Owner-only: the machine's facts are the owner's, and a pull spends their disk and bandwidth.
18
+ for (const operation of ["getLocalModel", "pullLocalModel"])
19
+ registerSecretWrite(operation, () => true);
20
+ registerSecretPage(["getLocalModel", "pullLocalModel"], "/#/");
21
+ /** The non-Apple pick, and Apple's where Inkling does not run: one line. A measurement (qwen3:8b against qwen3:30b-a3b,
22
+ * through this server's own runs) sets it. */
23
+ export const QWEN3_DEFAULT = "qwen3:8b";
24
+ /** Apple silicon's pick, where its Ollama runs it (MLX, on Apple silicon alone). */
25
+ export const INKLING = "inkling-2-mini";
26
+ /** The first Ollama that runs INKLING. */
27
+ export const INKLING_OLLAMA = "0.40.17";
28
+ /** Where Ollama is installed from. */
29
+ export const OLLAMA_DOWNLOAD = "https://ollama.com/download";
30
+ const GIB = 1024 ** 3;
31
+ /** The least memory (total RAM; Apple silicon's unified memory) each tag is offered on, in GiB: its weights at Ollama's
32
+ * default quantization, the KV cache of the context this server asks (ollama-provider.ts contextOf), and room for the
33
+ * system. A machine sold as 16 GB reads about 15.5 GiB, so each floor sits under the size it is meant for. */
34
+ export const RAM_FLOOR_GIB = {
35
+ [INKLING]: 15,
36
+ "qwen3:30b-a3b": 30,
37
+ "qwen3:8b": 15,
38
+ "qwen3:4b": 11,
39
+ };
40
+ /** The qwen3 tags, largest first: the pick is QWEN3_DEFAULT, else the next smaller that fits. */
41
+ const QWEN3_LADDER = ["qwen3:30b-a3b", "qwen3:8b", "qwen3:4b"];
42
+ const QWEN3_FITS = QWEN3_LADDER.slice(Math.max(0, QWEN3_LADDER.indexOf(QWEN3_DEFAULT)));
43
+ /** Every tag the recommendation can name, and so the only tags a pull here takes. */
44
+ export const LOCAL_MODEL_TAGS = Object.freeze([INKLING, ...QWEN3_FITS]);
45
+ /** A tag as Ollama lists it: with no `:`, `:latest`. */
46
+ export const fullTag = (tag) => (tag.includes(":") ? tag : `${tag}:latest`);
47
+ const gib = (bytes) => `${(bytes / GIB).toFixed(1)} GiB`;
48
+ const fits = (machine, tag) => machine.ram_bytes >= (RAM_FLOOR_GIB[tag] ?? Infinity) * GIB;
49
+ const needs = (tag) => `${tag} needs ${RAM_FLOOR_GIB[tag]} GiB of memory`;
50
+ /** `version` at or past `floor`, both dotted numbers (a suffix such as `-rc1` ignored); an unreadable version is not. */
51
+ export function versionAtLeast(version, floor) {
52
+ const parts = (text) => /^v?(\d+)\.(\d+)\.(\d+)/.exec(text.trim())?.slice(1).map(Number);
53
+ const [have, want] = [parts(version), parts(floor)];
54
+ if (!have || !want)
55
+ return false;
56
+ for (let i = 0; i < 3; i++)
57
+ if (have[i] !== want[i])
58
+ return have[i] > want[i];
59
+ return true;
60
+ }
61
+ /** Whether this machine is Apple silicon. */
62
+ const appleSilicon = (machine) => machine.gpu.kind === "apple";
63
+ /**
64
+ * The model this server recommends for `facts`, and why. No Ollama: none, and where to install it. Apple silicon with an
65
+ * Ollama at INKLING_OLLAMA or later and the memory for it: INKLING. Everyone else: QWEN3_DEFAULT, or the next smaller qwen3
66
+ * that fits in memory, or none, saying what each needs; Apple silicon on an older Ollama is told to update for INKLING. A
67
+ * tag already pulled says so: no pull needed.
68
+ */
69
+ export function recommendLocalModel(facts) {
70
+ const { machine, ollama } = facts;
71
+ if (!ollama.asked)
72
+ return { tag: null, why: "This server asks no Ollama.", pulled: false };
73
+ if (!ollama.reachable)
74
+ return { tag: null, why: `Ollama isn't running on this machine. Install it from ${OLLAMA_DOWNLOAD}, start it, then come back here.`, pulled: false };
75
+ const has = new Set(facts.pulled.map(fullTag));
76
+ const done = (tag, why) => (has.has(fullTag(tag)) ? { tag, why: `${why} Already pulled: no pull needed.`, pulled: true } : { tag, why, pulled: false });
77
+ const apple = appleSilicon(machine);
78
+ const inklingRuns = apple && versionAtLeast(ollama.version, INKLING_OLLAMA);
79
+ if (inklingRuns && fits(machine, INKLING))
80
+ return done(INKLING, `Apple silicon with Ollama ${ollama.version} runs ${INKLING}; ${needs(INKLING)}, and this Mac has ${gib(machine.ram_bytes)}.`);
81
+ const notes = [
82
+ ...(apple && !inklingRuns ? [`Update Ollama to ${INKLING_OLLAMA} for ${INKLING}.`] : []),
83
+ ...(inklingRuns ? [`${needs(INKLING)}, and this Mac has ${gib(machine.ram_bytes)}.`] : []),
84
+ ];
85
+ const tag = QWEN3_FITS.find((candidate) => fits(machine, candidate));
86
+ if (!tag) {
87
+ const least = QWEN3_FITS[QWEN3_FITS.length - 1];
88
+ return { tag: null, why: [`This machine has ${gib(machine.ram_bytes)} of memory, and the smallest local model offered here, ${needs(least)}. Add a model key instead.`, ...notes].join(" "), pulled: false };
89
+ }
90
+ const smaller = tag === QWEN3_DEFAULT ? "" : ` ${needs(QWEN3_DEFAULT)}, so the smaller ${tag}.`;
91
+ return done(tag, [`${tag} fits this machine's ${gib(machine.ram_bytes)} of memory (it needs ${RAM_FLOOR_GIB[tag]} GiB).${smaller}`, ...notes].join(" "));
92
+ }
93
+ // ---- the machine ------------------------------------------------------------------------------------------------------
94
+ /** How long nvidia-smi is waited for. */
95
+ export const NVIDIA_SMI_TIMEOUT_MS = 2_000;
96
+ /** The first GPU nvidia-smi names (`name, memory.total` in MiB), or unknown where it is not there, fails or is slow. */
97
+ async function nvidiaGpu() {
98
+ const out = await new Promise((resolve) => {
99
+ execFile("nvidia-smi", ["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"], { timeout: NVIDIA_SMI_TIMEOUT_MS, windowsHide: true }, (error, stdout) => resolve(error ? undefined : stdout));
100
+ });
101
+ return nvidiaOf(out);
102
+ }
103
+ /** nvidia-smi's first line, `<name>, <MiB>`, as a GPU; unknown for anything else. */
104
+ export function nvidiaOf(out) {
105
+ const line = out?.split("\n").map((text) => text.trim()).find(Boolean);
106
+ const match = line ? /^(.+?),\s*(\d+)(?:\s*MiB)?$/.exec(line) : null;
107
+ return match ? { kind: "nvidia", name: match[1].trim().slice(0, 200), memory_bytes: Number(match[2]) * 1024 ** 2 } : { kind: "unknown" };
108
+ }
109
+ /** This machine, read once: what a server serves for its life. A test hands its own (ServeOptions.machine). */
110
+ export async function readMachine() {
111
+ const [os, cpu] = [platform(), arch()];
112
+ const gpu = os === "darwin" && cpu === "arm64" ? { kind: "apple", unified: true } : await nvidiaGpu();
113
+ return { platform: os, arch: cpu, ram_bytes: totalmem(), gpu };
114
+ }
115
+ /** One pull at a time, through `pull`; `finished` once it succeeds (the listing dropped and read again), before it reads
116
+ * done. A log line at its start, its end and its failure: the tag, the bytes and the milliseconds, nothing else. */
117
+ export function localPulls({ pull, finished, log, signal }) {
118
+ let current;
119
+ return {
120
+ view: () => (current ? { ...current } : null),
121
+ pulling: () => current?.state === "pulling",
122
+ /** Starts pulling `tag` (checked by the caller), behind the answer. */
123
+ start(tag) {
124
+ const layers = new Map();
125
+ const mine = { tag, state: "pulling", status: "starting", completed_bytes: 0, total_bytes: 0 };
126
+ current = mine;
127
+ const started = performance.now();
128
+ log?.(logLine("local_model_pull_start", { tag }));
129
+ const onLine = (line) => {
130
+ mine.status = line.status.slice(0, 200);
131
+ if (line.digest && line.total !== undefined) {
132
+ layers.set(line.digest, { total: line.total, completed: Math.min(line.completed ?? 0, line.total) });
133
+ mine.total_bytes = [...layers.values()].reduce((sum, layer) => sum + layer.total, 0);
134
+ mine.completed_bytes = [...layers.values()].reduce((sum, layer) => sum + layer.completed, 0);
135
+ }
136
+ };
137
+ void pull(tag, onLine, signal)
138
+ .then(() => finished(tag))
139
+ .then(() => {
140
+ Object.assign(mine, { state: "done", status: "success", completed_bytes: mine.total_bytes });
141
+ log?.(logLine("local_model_pull_end", { tag, bytes: mine.total_bytes, ms: Math.round(performance.now() - started) }));
142
+ })
143
+ .catch((error) => {
144
+ Object.assign(mine, { state: "failed", error: (error instanceof Error ? error.message : String(error)).slice(0, 500) });
145
+ log?.(logLine("local_model_pull_failed", { tag, bytes: mine.completed_bytes, ms: Math.round(performance.now() - started) }));
146
+ });
147
+ return { ...mine };
148
+ },
149
+ };
150
+ }
151
+ // ---- the route --------------------------------------------------------------------------------------------------------
152
+ /** Whether the Ollama `env` names is on another machine: OLLAMA_HOST names an address that is not this machine's own
153
+ * (a loopback name). This server reads only its own memory and GPU, so it recommends and pulls nothing for that one. An
154
+ * address the base rule refuses is no Ollama asked at all, and not said to be elsewhere. */
155
+ export function ollamaElsewhere(env) {
156
+ if (!env.OLLAMA_HOST?.trim())
157
+ return false;
158
+ try {
159
+ return !isLoopbackName(new URL(ollamaBase(env)).hostname);
160
+ }
161
+ catch {
162
+ return false;
163
+ }
164
+ }
165
+ /** The words for an Ollama on another machine (ollamaElsewhere), which never name its address. */
166
+ export const OLLAMA_ELSEWHERE = "The Ollama OLLAMA_HOST names is on another machine, and this server reads only its own memory and GPU, so it recommends and pulls no model for that one. Pull one where that Ollama runs: ollama pull <tag>.";
167
+ /** Why no pull is made through the Ollama `env` names, in words, or undefined where one may: the faux model or a model
168
+ * gateway takes every model here (asksOllama); a server that is not one owner's own on their own machine (`notOwn`,
169
+ * server.ts whyNotOwnMachine's reasons) pulls nothing into an Ollama that is not theirs. */
170
+ export function pullRefusal(env, notOwn) {
171
+ if (env[FAUX_ENV])
172
+ return "This server runs the faux model, so no local model is pulled here.";
173
+ if (!asksOllama(env))
174
+ return "This server sends every model to its model gateway (AGENT_MODEL_BASE_URL), so a local model would not run here.";
175
+ if (notOwn.length)
176
+ return `A local model is pulled from here only on one owner's own server on their own machine, and this server ${notOwn.join("; ")}. Pull it where Ollama runs: ollama pull <tag>.`;
177
+ if (!env.OLLAMA_HOST?.trim())
178
+ return "No Ollama is asked here.";
179
+ if (ollamaElsewhere(env))
180
+ return OLLAMA_ELSEWHERE;
181
+ return undefined;
182
+ }
183
+ /** The read surface: the machine, its Ollama, the recommendation, the pull here, and whether a pull may be made. */
184
+ export async function localModelView({ env, notOwn, machine, pulls }) {
185
+ const refused = pullRefusal(env, notOwn);
186
+ const asked = asksOllama(env);
187
+ const [facts, version, listed] = await Promise.all([machine(), asked ? ollamaVersion(env) : undefined, asked ? ollamaModels(env) : []]);
188
+ const ollama = !asked ? { asked: false, reachable: false, version: null } : version === undefined ? { asked: true, reachable: false, version: null } : { asked: true, reachable: true, version };
189
+ // An Ollama on another machine is not this machine's: no recommendation from this machine's memory and GPU for it.
190
+ const recommended = asked && ollamaElsewhere(env) ? { tag: null, why: OLLAMA_ELSEWHERE, pulled: false }
191
+ : recommendLocalModel({ machine: facts, ollama, pulled: listed.map((model) => model.name) });
192
+ // Not asked, the refusal is the only word on it: never that Ollama isn't running.
193
+ return { machine: facts, ollama, recommended: asked || !refused ? recommended : { ...recommended, why: refused }, pull: pulls.view(), can_pull: refused === undefined, refused: refused ?? null };
194
+ }
195
+ /** POST /settings/local-model/pull: `{ tag }`, one of LOCAL_MODEL_TAGS (422 otherwise), where a pull may be made (403 in
196
+ * words otherwise), none under way (409 local_model_pulling). Answers the read surface with the pull started. */
197
+ export async function pullLocalModel(deps, body) {
198
+ if (!isObject(body) || typeof body.tag !== "string")
199
+ throw new ApiError("input_invalid", "Name the tag to pull: { \"tag\": \"<tag>\" }.", { fields: [{ field: "tag", reason: "missing", message: "required, a string" }] });
200
+ const extra = unknownFields(body, ["tag"]);
201
+ if (extra.length)
202
+ throw new ApiError("input_invalid", extra.map((issue) => issue.message).join(" "), { fields: extra });
203
+ if (!LOCAL_MODEL_TAGS.includes(body.tag))
204
+ throw new ApiError("input_invalid", `Only the tags this server recommends are pulled from here: ${LOCAL_MODEL_TAGS.join(", ")}.`, { fields: [{ field: "tag", reason: "not_an_option", message: `one of ${LOCAL_MODEL_TAGS.join(", ")}` }] });
205
+ const refused = pullRefusal(deps.env, deps.notOwn);
206
+ if (refused)
207
+ throw new ApiError("forbidden", refused);
208
+ if (deps.pulls.pulling())
209
+ throw new ApiError("local_model_pulling", `A pull of ${deps.pulls.view()?.tag} is under way here: one at a time. Its progress is on GET /settings/local-model.`);
210
+ deps.pulls.start(body.tag);
211
+ return localModelView(deps);
212
+ }
213
+ /** The real pull: through the Ollama `env` names (ollama-provider.ts ollamaPull). */
214
+ export const pullThrough = (env, stallMs) => (tag, onLine, signal) => ollamaPull(env(), tag, onLine, { signal, ...(stallMs !== undefined ? { stallMs } : {}) });
@@ -1,5 +1,6 @@
1
1
  import type { McpCallResult, McpTool } from "@parcha/agentrun-kernel";
2
2
  import { type FalMeterName, type MediaReader } from "./fal-price.js";
3
+ import { type FileSetting, UNREADABLE } from "./filed-tool.js";
3
4
  import { type Workspace } from "./workspace/index.js";
4
5
  /** The longest answer the model reads whole; past it, the rest is filed in the run's work/ as lines read pages through
5
6
  * (filed-answer.ts). Within the host's result bound (HOST_RESULT_MAX_CHARS), so every harness passes it whole. */
@@ -128,6 +129,11 @@ export interface McpGatewayOptions {
128
129
  now?: () => number;
129
130
  /** The run's id: what a meter scopes a server's keys to (McpMeter.keys). None: no key is scoped. */
130
131
  run?: string;
132
+ /** The file setting of a server's tool, read from the agent's own tool settings (filed-tool.ts filedBy): each answer
133
+ * of it, an error answer too, is filed whole in its folder of the run's files, and the tool's result is only a
134
+ * summary. UNREADABLE for a tool: a stored setting that does not read, and every call of the tool is refused unsent.
135
+ * None, or undefined for a tool: its answers are the model's, as always. */
136
+ filed?: (server: string, tool: string) => FileSetting | typeof UNREADABLE | undefined;
131
137
  }
132
138
  /** A run's journal commit. */
133
139
  export type McpCommit = <T>(change: (tx: unknown) => Promise<T>) => Promise<T>;