@parcha/agentrun-serve 0.1.0-beta.60 → 0.1.0-beta.62

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 (179) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/README.md +139 -22
  3. package/dist/acp-package.d.ts +4 -0
  4. package/dist/api-only.d.ts +23 -1
  5. package/dist/api-only.js +43 -4
  6. package/dist/archil-settings.d.ts +9 -0
  7. package/dist/archil-settings.js +8 -1
  8. package/dist/bash-read-only.d.ts +3 -0
  9. package/dist/bash-read-only.js +6 -3
  10. package/dist/browser-person.d.ts +1 -1
  11. package/dist/browser-person.js +1 -1
  12. package/dist/calendar/tools.js +1 -1
  13. package/dist/chatgpt-plan.d.ts +26 -8
  14. package/dist/chatgpt-plan.js +89 -21
  15. package/dist/claude-login.d.ts +12 -5
  16. package/dist/claude-login.js +28 -3
  17. package/dist/cli.js +61 -18
  18. package/dist/composio-triggers.d.ts +9 -3
  19. package/dist/computers.d.ts +3 -0
  20. package/dist/computers.js +2 -1
  21. package/dist/console/assets/{backend-QnwGVBeU.js → backend-DEgVn5lC.js} +1 -1
  22. package/dist/console/assets/index-CG5tELph.js +639 -0
  23. package/dist/console/assets/share-CIeFK2Oe.js +6 -0
  24. package/dist/console/assets/{styles-CcceGcu2.js → styles-BGZxYkky.js} +2 -2
  25. package/dist/console/assets/{styles-fjQBFfMv.css → styles-D0SufbzK.css} +1 -1
  26. package/dist/console/index.html +3 -3
  27. package/dist/console/share.html +3 -3
  28. package/dist/cut-pool.d.ts +14 -0
  29. package/dist/cut-pool.js +98 -0
  30. package/dist/cut-worker.d.ts +14 -0
  31. package/dist/cut-worker.js +16 -0
  32. package/dist/decisions.d.ts +4 -0
  33. package/dist/decisions.js +9 -1
  34. package/dist/env-switch.d.ts +3 -0
  35. package/dist/env-switch.js +3 -0
  36. package/dist/errors.d.ts +1 -0
  37. package/dist/errors.js +2 -0
  38. package/dist/harness-check.js +2 -1
  39. package/dist/harness-recipe.d.ts +13 -2
  40. package/dist/harness-recipe.js +30 -7
  41. package/dist/harness-sign-in.js +2 -1
  42. package/dist/harness-table.d.ts +12 -3
  43. package/dist/harness-table.js +13 -8
  44. package/dist/import.d.ts +8 -1
  45. package/dist/import.js +36 -5
  46. package/dist/key-check.js +22 -8
  47. package/dist/key-refusal.js +6 -4
  48. package/dist/learn/secrets.d.ts +2 -1
  49. package/dist/learn/secrets.js +2 -2
  50. package/dist/learned-nodes.d.ts +37 -0
  51. package/dist/learned-nodes.js +24 -0
  52. package/dist/local-model.d.ts +144 -0
  53. package/dist/local-model.js +214 -0
  54. package/dist/mcp-gateway.d.ts +24 -0
  55. package/dist/mcp-gateway.js +97 -8
  56. package/dist/mcp-probe.d.ts +7 -0
  57. package/dist/mcp-probe.js +7 -0
  58. package/dist/mcp-servers-store.d.ts +7 -10
  59. package/dist/mcp-servers-store.js +15 -9
  60. package/dist/native/cli.js +5 -1
  61. package/dist/ollama-provider.d.ts +42 -0
  62. package/dist/ollama-provider.js +118 -2
  63. package/dist/openapi.js +85 -16
  64. package/dist/otel/tracer.d.ts +6 -3
  65. package/dist/otel/tracer.js +24 -6
  66. package/dist/page.d.ts +7 -0
  67. package/dist/page.js +17 -4
  68. package/dist/place.d.ts +28 -11
  69. package/dist/place.js +43 -14
  70. package/dist/print.d.ts +3 -2
  71. package/dist/print.js +8 -6
  72. package/dist/redact/match.d.ts +17 -4
  73. package/dist/redact/match.js +57 -15
  74. package/dist/run-export.js +4 -2
  75. package/dist/run-launch.js +16 -3
  76. package/dist/run-model-key.d.ts +2 -1
  77. package/dist/run-model-key.js +2 -1
  78. package/dist/run-reads-over-store.d.ts +7 -0
  79. package/dist/run-reads-over-store.js +32 -4
  80. package/dist/run-usage.js +3 -2
  81. package/dist/runnable.d.ts +6 -3
  82. package/dist/runnable.js +16 -6
  83. package/dist/runner/adapter-loop.d.ts +8 -1
  84. package/dist/runner/adapter-loop.js +148 -29
  85. package/dist/runner/adapter-run-spec.d.ts +9 -6
  86. package/dist/runner/adapter-run-spec.js +38 -52
  87. package/dist/runner/adapters/index.d.ts +4 -0
  88. package/dist/runner/adapters/index.js +2 -1
  89. package/dist/runner/adapters/pi.d.ts +3 -2
  90. package/dist/runner/adapters/pi.js +3 -1
  91. package/dist/runner/audit.d.ts +1 -1
  92. package/dist/runner/claim-secrets.d.ts +3 -1
  93. package/dist/runner/claim-secrets.js +18 -7
  94. package/dist/runner/cli-run-spec.js +24 -17
  95. package/dist/runner/compare-end.d.ts +1 -1
  96. package/dist/runner/dispatch.js +4 -2
  97. package/dist/runner/harness-loops.d.ts +14 -0
  98. package/dist/runner/harness-loops.js +51 -5
  99. package/dist/runner/held.d.ts +4 -1
  100. package/dist/runner/live-ticker.js +5 -4
  101. package/dist/runner/loop-contract.d.ts +4 -1
  102. package/dist/runner/mcp-claim.js +3 -2
  103. package/dist/runner/mcp-run.d.ts +24 -4
  104. package/dist/runner/mcp-run.js +47 -2
  105. package/dist/runner/meta-tools.js +4 -4
  106. package/dist/runner/metrics.d.ts +6 -0
  107. package/dist/runner/metrics.js +12 -4
  108. package/dist/runner/monid-run.js +3 -1
  109. package/dist/runner/native-loop.js +3 -3
  110. package/dist/runner/redact.d.ts +3 -0
  111. package/dist/runner/redact.js +7 -0
  112. package/dist/runner/run-child-host.d.ts +10 -6
  113. package/dist/runner/run-child-host.js +44 -29
  114. package/dist/runner/run-child.js +1 -0
  115. package/dist/runner/runner.js +2 -0
  116. package/dist/runner/sdk-loop.js +5 -3
  117. package/dist/runner/workflow-calls.d.ts +5 -1
  118. package/dist/runner/workflow-calls.js +65 -19
  119. package/dist/runner/workflow-loop.d.ts +1 -1
  120. package/dist/runner/workflow-loop.js +3 -1
  121. package/dist/runner/workflow-spec.d.ts +4 -0
  122. package/dist/runner/workflow-spec.js +18 -13
  123. package/dist/runs-over-store.d.ts +2 -2
  124. package/dist/runs-over-store.js +1 -1
  125. package/dist/secret-cut.js +7 -4
  126. package/dist/secret-rules.d.ts +0 -1
  127. package/dist/secret-rules.js +122 -88
  128. package/dist/server.d.ts +17 -1
  129. package/dist/server.js +208 -69
  130. package/dist/share-host.d.ts +111 -0
  131. package/dist/share-host.js +666 -0
  132. package/dist/slack.js +2 -1
  133. package/dist/store/postgres/migrate.js +3 -1
  134. package/dist/store-reads/analytics.d.ts +15 -0
  135. package/dist/store-reads/analytics.js +17 -0
  136. package/dist/store-reads/learning.d.ts +5 -4
  137. package/dist/store-reads/learning.js +7 -4
  138. package/dist/suggestions.js +32 -3
  139. package/dist/templates.d.ts +3 -1
  140. package/dist/templates.js +7 -3
  141. package/dist/tool-gate.d.ts +25 -9
  142. package/dist/tool-gate.js +58 -19
  143. package/dist/tool-plane.d.ts +24 -1
  144. package/dist/tool-plane.js +75 -3
  145. package/dist/tools.d.ts +12 -2
  146. package/dist/tools.js +42 -7
  147. package/dist/trigger-composio.js +1 -1
  148. package/dist/trigger-launch-hook.d.ts +2 -2
  149. package/dist/trigger-launch-hook.js +1 -1
  150. package/dist/triggers.d.ts +7 -4
  151. package/dist/triggers.js +4 -4
  152. package/dist/webhooks.d.ts +3 -0
  153. package/dist/webhooks.js +5 -0
  154. package/dist/workspace/archil-claim.d.ts +7 -3
  155. package/dist/workspace/archil-claim.js +13 -5
  156. package/dist/workspace/archil-mount-credential.d.ts +6 -0
  157. package/dist/workspace/archil-mount-credential.js +11 -0
  158. package/dist/workspace/computer-deps.d.ts +5 -3
  159. package/dist/workspace/computer-deps.js +11 -9
  160. package/dist/workspace/computer-for-claim.d.ts +6 -2
  161. package/dist/workspace/computer-for-claim.js +43 -12
  162. package/dist/workspace/computer-janitor.d.ts +7 -4
  163. package/dist/workspace/computer-janitor.js +7 -4
  164. package/dist/workspace/computer-kept.d.ts +7 -1
  165. package/dist/workspace/computer-kept.js +7 -1
  166. package/dist/workspace/kind-skills/desktop/SKILL.md +12 -3
  167. package/dist/workspace/mount-revoke-left.d.ts +16 -4
  168. package/dist/workspace/mount-revoke-left.js +42 -22
  169. package/dist/workspace/resolve-computer.d.ts +11 -5
  170. package/dist/workspace/resolve-computer.js +22 -13
  171. package/dist/workspace/run-end-computers.js +1 -1
  172. package/dist/workspace/run-tools.d.ts +10 -3
  173. package/dist/workspace/run-tools.js +5 -4
  174. package/dist/wrapped.d.ts +29 -2
  175. package/dist/wrapped.js +20 -3
  176. package/launcher/agentrun-serve +1 -1
  177. package/package.json +12 -12
  178. package/dist/console/assets/index-DZi-muIj.js +0 -629
  179. package/dist/console/assets/share-pz61zIn9.js +0 -6
@@ -1,5 +1,6 @@
1
1
  import { type InputIssue } from "./errors.js";
2
2
  import { type Listed, type McpPrices, type McpTool } from "./mcp-probe.js";
3
+ import type { ComposioCredentialOf } from "./composio-triggers.js";
3
4
  import { type SecretMeta } from "./secret-writes.js";
4
5
  import { type ClientKind, type OAuthNetwork } from "./mcp-oauth.js";
5
6
  import { type Cleanup, COMPOSIO_KEY_ENV, type ComposioMade } from "./composio-made.js";
@@ -439,17 +440,13 @@ export declare class McpServersOverStore {
439
440
  /** The saved OAuth token set of `row` (the row read and checked, as opened), for a sign-in again that reuses the kept
440
441
  * client. */
441
442
  private openedSet;
442
- /** A saved Composio preset server's key (its sealed x-api-key), the Composio user its address names (`user_id`, the
443
- * preset's default when none), its toolkit and the auth config its save recorded (composio-made.ts; none for a server
444
- * saved before that was recorded): what its Composio triggers are made with (composio-triggers.ts). Refused
445
- * when `name` is no such server: on the trigger's `source.server` at its create (`field`), as a 404 on the server's own
443
+ /** A saved Composio preset server's key (its sealed x-api-key), its toolkit and the auth config its save recorded
444
+ * (composio-made.ts; none for a server saved before that was recorded), and for a trigger's own steps (`field`) the
445
+ * Composio user its address names (`user_id`, the preset's default when none): what its Composio triggers are made with
446
+ * (composio-triggers.ts). The server's own routes (`route`) are answered no user: none of them sends one. Refused when
447
+ * `name` is no such server: on the trigger's `source.server` at its create (`field`), as a 404 on the server's own
446
448
  * routes (`route`). The key goes only to Composio. */
447
- composioOf(name: string, refusal: "field" | "route"): Promise<{
448
- key: string;
449
- user: string;
450
- toolkit: string;
451
- auth_config?: string;
452
- }>;
449
+ composioOf<R extends "field" | "route">(name: string, refusal: R): Promise<ComposioCredentialOf<R>>;
453
450
  /** What the saved server `row` is, for a template's apply to match (mcp-sources.ts sourceOf): github on the GitHub App's
454
451
  * tokens, else its record, else url with none. */
455
452
  sourceOf(row: RecordedRow & {
@@ -829,10 +829,11 @@ export class McpServersOverStore {
829
829
  const open = openMcpRow(this.sealKey, row);
830
830
  return "credential" in open && open.credential.type === "oauth" ? open.credential.set : undefined;
831
831
  }
832
- /** A saved Composio preset server's key (its sealed x-api-key), the Composio user its address names (`user_id`, the
833
- * preset's default when none), its toolkit and the auth config its save recorded (composio-made.ts; none for a server
834
- * saved before that was recorded): what its Composio triggers are made with (composio-triggers.ts). Refused
835
- * when `name` is no such server: on the trigger's `source.server` at its create (`field`), as a 404 on the server's own
832
+ /** A saved Composio preset server's key (its sealed x-api-key), its toolkit and the auth config its save recorded
833
+ * (composio-made.ts; none for a server saved before that was recorded), and for a trigger's own steps (`field`) the
834
+ * Composio user its address names (`user_id`, the preset's default when none): what its Composio triggers are made with
835
+ * (composio-triggers.ts). The server's own routes (`route`) are answered no user: none of them sends one. Refused when
836
+ * `name` is no such server: on the trigger's `source.server` at its create (`field`), as a 404 on the server's own
836
837
  * routes (`route`). The key goes only to Composio. */
837
838
  async composioOf(name, refusal) {
838
839
  const refuse = (message) => (refusal === "route" ? new ApiError("not_found", message) : invalid([{ field: "source.server", reason: "not_an_option", message }]));
@@ -853,15 +854,20 @@ export class McpServersOverStore {
853
854
  if (!key)
854
855
  throw refuse(`${name}'s saved credential holds no Composio key: save it again with its key.`);
855
856
  const config = recordedMade(recorded, row.createdAt)?.auth_config?.id;
857
+ const made = { key, toolkit, ...(config ? { auth_config: config } : {}) };
858
+ // A route sends Composio no user: its events, its triggers and the project's subscription are read by the key, and a
859
+ // delete or a save takes the project's turn by it, so it is answered none, and a server with a blank user keeps its
860
+ // routes and that turn.
861
+ if (refusal === "route")
862
+ return made;
856
863
  // Only an address with no user_id at all is the default user's: an empty one is a blank user, refused below.
857
864
  const user = new URL(row.url).searchParams.get("user_id") ?? COMPOSIO_USER;
858
865
  // A user that is no Composio user id (a blank one Composio may read as every user) is refused for a trigger's own steps
859
- // (`field`) before Composio is asked anything: a create sends the user (its account read, its connect link, its
860
- // instance's upsert). A route sends none: its events, its triggers and the project's subscription are read by the key,
861
- // and a delete or a save takes the project's turn by it, so a server with a blank user keeps its routes and that turn.
862
- if (refusal === "field" && !COMPOSIO_USER_ID.test(user))
866
+ // before Composio is asked anything: a create sends the user (its account read, its connect link, its instance's
867
+ // upsert).
868
+ if (!COMPOSIO_USER_ID.test(user))
863
869
  throw refuse(`${name}'s saved Composio user ${JSON.stringify(user)} is no Composio user id: save the server again with its user.`);
864
- return { key, user, toolkit, ...(config ? { auth_config: config } : {}) };
870
+ return { ...made, user };
865
871
  }
866
872
  /** What the saved server `row` is, for a template's apply to match (mcp-sources.ts sourceOf): github on the GitHub App's
867
873
  * tokens, else its record, else url with none. */
@@ -1,4 +1,5 @@
1
1
  import { parseArgs } from 'node:util';
2
+ import { keyBase } from '@parcha/agentrun-computer';
2
3
  import { readFile } from 'node:fs/promises';
3
4
  import { join } from 'node:path';
4
5
  import { defaultData } from '../server-fs.js';
@@ -33,7 +34,10 @@ export async function nativeMain(argv, usage) {
33
34
  recorded = record.base_url;
34
35
  }
35
36
  catch { /* explicit/default URL below */ }
36
- const url = new URL(values.url ?? process.env.AGENTRUN_BASE_URL ?? process.env.AGENTRUN_URL ?? recorded ?? 'http://127.0.0.1:7340');
37
+ const named = [['--url', values.url], ['AGENTRUN_BASE_URL', process.env.AGENTRUN_BASE_URL], ['AGENTRUN_URL', process.env.AGENTRUN_URL], ["the server's recorded base_url", recorded]];
38
+ const [setting, given] = named.find((entry) => entry[1] !== undefined) ?? ['the default URL', 'http://127.0.0.1:7340'];
39
+ // The token goes to it, and fetch's errors print the whole URL: the rule of a URL a key goes to (keyBase), over loopback's http or https.
40
+ const url = new URL(keyBase(given, setting, ['http:', 'https:']));
37
41
  if (!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
38
42
  throw new Error('Run AgentRun on this source machine and connect to its loopback URL; hosted native pairing is not available yet.');
39
43
  const token = secret('AGENTRUN_API_KEY') || secret('AGENTRUN_TOKEN') || (await readFile(join(data, '.token'), 'utf8')).trim();
@@ -88,6 +88,48 @@ export declare function ollamaRelisted(env: NodeJS.ProcessEnv): Promise<readonly
88
88
  * one none): none where it was never asked. Synchronous, for the host's default model (model.ts hostModel), which a
89
89
  * listing primes before it is read. */
90
90
  export declare function ollamaKept(env: NodeJS.ProcessEnv): readonly OllamaListed[];
91
+ /** Forgets the listing kept for the Ollama `env` names, and the one under way for it, so the next ollamaModels asks it
92
+ * again at once: after a pull here (local-model.ts), the model is in the picker with no wait for OLLAMA_TTL_MS. A
93
+ * listing under way when it is forgotten still answers its caller, but is never kept: it may be from before the pull. */
94
+ export declare function ollamaForget(env: NodeJS.ProcessEnv): void;
95
+ /** How long the version of the Ollama here is waited for (ollamaVersion): a listing's deadline. */
96
+ export declare const OLLAMA_VERSION_TIMEOUT_MS = 2000;
97
+ /** The version the Ollama `env` names says it is (GET /api/version), or undefined where it names none, is refused, down,
98
+ * hung past `timeoutMs` or answers another shape. Nothing thrown. */
99
+ export declare function ollamaVersion(env: NodeJS.ProcessEnv, { fetch: send, timeoutMs }?: {
100
+ fetch?: typeof fetch;
101
+ timeoutMs?: number;
102
+ }): Promise<string | undefined>;
103
+ /** One line of a pull's progress as Ollama streams it (POST /api/pull): its status, and a layer's digest with its bytes. */
104
+ export type OllamaPullLine = {
105
+ readonly status: string;
106
+ readonly digest?: string;
107
+ readonly total?: number;
108
+ readonly completed?: number;
109
+ };
110
+ /** How long a pull may go with no byte from Ollama before it stops (ollamaPull): a registry that stalls, or an Ollama
111
+ * that wedges, frees the one pull here instead of holding it at `pulling` until the server restarts. */
112
+ export declare const PULL_STALL_MS = 120000;
113
+ /** How long a pull may go with no byte from Ollama once it says `verifying sha256 digest`: it then hashes every blob of the
114
+ * model with no further line, and on a slow disk a model of gigabytes takes minutes. An Ollama that wedges there still
115
+ * frees the pull. */
116
+ export declare const PULL_VERIFY_STALL_MS: number;
117
+ /** The longest progress line a pull takes, in characters: Ollama's are a few hundred, so a stream that sends no newline
118
+ * ends. */
119
+ export declare const PULL_LINE_MAX: number;
120
+ /**
121
+ * Pulls `tag` through the Ollama `env` names (POST /api/pull, streamed as NDJSON), each line of progress to `onLine` as it
122
+ * comes. Resolves once Ollama says `success`; throws, in Ollama's words, on an `error` line, a refusal, a stream that ends
123
+ * before `success`, or `signal`; in its own, on `stallMs` with no byte from Ollama (the answer's head or a chunk of the
124
+ * stream), `verifyStallMs` once Ollama says it is verifying the digest, or a line past PULL_LINE_MAX. No deadline on the
125
+ * whole: a model is gigabytes, and a pull that moves is let run.
126
+ */
127
+ export declare function ollamaPull(env: NodeJS.ProcessEnv, tag: string, onLine: (line: OllamaPullLine) => void, { fetch: send, signal, stallMs, verifyStallMs }?: {
128
+ fetch?: typeof fetch;
129
+ signal?: AbortSignal;
130
+ stallMs?: number;
131
+ verifyStallMs?: number;
132
+ }): Promise<void>;
91
133
  /** `env`'s Ollama listing as last kept (ollamaKept), in one string: each model's tag, capabilities and trained context.
92
134
  * A server compares it to see a model pulled, removed or an Ollama started since it made its offers (server.ts). */
93
135
  export declare const ollamaListing: (env: NodeJS.ProcessEnv) => string;
@@ -80,6 +80,9 @@ function splitHostPort(hostport) {
80
80
  * for it. */
81
81
  const kept = new Map();
82
82
  const asking = new Map();
83
+ /** Bumped by ollamaForget, per address: a listing asked before a forget answers its caller but is never kept, since it
84
+ * may be from before the pull that made the forget. */
85
+ const forgets = new Map();
83
86
  /** The clock a listing is kept by: Date.now, or a test's (ollamaClock). */
84
87
  let now = Date.now;
85
88
  /** A test's clock for the kept listings, so it ages them without waiting; with none, Date.now again. */
@@ -181,6 +184,7 @@ export async function listOllama(env, { fetch: send = globalThis.fetch, timeoutM
181
184
  return [];
182
185
  const deadline = AbortSignal.timeout(timeoutMs);
183
186
  const ask = askerOf(base, send, deadline);
187
+ const asked = forgets.get(base) ?? 0;
184
188
  let models = [];
185
189
  let whole = false;
186
190
  let down = false;
@@ -197,7 +201,9 @@ export async function listOllama(env, { fetch: send = globalThis.fetch, timeoutM
197
201
  }
198
202
  const before = kept.get(base)?.models;
199
203
  const listing = whole ? { at: now(), models } : { at: -Infinity, models: !down && before?.length ? before : models };
200
- kept.set(base, listing);
204
+ // A forget since this listing was asked: it answers its caller, and is never kept.
205
+ if ((forgets.get(base) ?? 0) === asked)
206
+ kept.set(base, listing);
201
207
  return listing.models;
202
208
  }
203
209
  /** Whether `error` is a refused connection (ECONNREFUSED anywhere in its causes): nothing listens at the address. */
@@ -239,7 +245,9 @@ export async function ollamaModels(env) {
239
245
  return known.models;
240
246
  let listing = asking.get(base);
241
247
  if (!listing) {
242
- listing = listOllama(env).finally(() => asking.delete(base));
248
+ const mine = listOllama(env).finally(() => { if (asking.get(base) === mine)
249
+ asking.delete(base); });
250
+ listing = mine;
243
251
  asking.set(base, listing);
244
252
  }
245
253
  return known ? known.models : listing;
@@ -261,6 +269,114 @@ export function ollamaKept(env) {
261
269
  const base = baseOf(env);
262
270
  return base === undefined ? [] : (kept.get(base)?.models ?? []);
263
271
  }
272
+ /** Forgets the listing kept for the Ollama `env` names, and the one under way for it, so the next ollamaModels asks it
273
+ * again at once: after a pull here (local-model.ts), the model is in the picker with no wait for OLLAMA_TTL_MS. A
274
+ * listing under way when it is forgotten still answers its caller, but is never kept: it may be from before the pull. */
275
+ export function ollamaForget(env) {
276
+ const base = baseOf(env);
277
+ if (base === undefined)
278
+ return;
279
+ forgets.set(base, (forgets.get(base) ?? 0) + 1);
280
+ kept.delete(base);
281
+ asking.delete(base);
282
+ }
283
+ /** How long the version of the Ollama here is waited for (ollamaVersion): a listing's deadline. */
284
+ export const OLLAMA_VERSION_TIMEOUT_MS = OLLAMA_LIST_TIMEOUT_MS;
285
+ /** The version the Ollama `env` names says it is (GET /api/version), or undefined where it names none, is refused, down,
286
+ * hung past `timeoutMs` or answers another shape. Nothing thrown. */
287
+ export async function ollamaVersion(env, { fetch: send = globalThis.fetch, timeoutMs = OLLAMA_VERSION_TIMEOUT_MS } = {}) {
288
+ const base = baseOf(env);
289
+ if (base === undefined)
290
+ return undefined;
291
+ try {
292
+ const answer = (await askerOf(base, send, AbortSignal.timeout(timeoutMs))("/api/version"));
293
+ return typeof answer?.version === "string" && answer.version.length > 0 && answer.version.length <= 64 ? answer.version : undefined;
294
+ }
295
+ catch {
296
+ return undefined;
297
+ }
298
+ }
299
+ /** How long a pull may go with no byte from Ollama before it stops (ollamaPull): a registry that stalls, or an Ollama
300
+ * that wedges, frees the one pull here instead of holding it at `pulling` until the server restarts. */
301
+ export const PULL_STALL_MS = 120_000;
302
+ /** How long a pull may go with no byte from Ollama once it says `verifying sha256 digest`: it then hashes every blob of the
303
+ * model with no further line, and on a slow disk a model of gigabytes takes minutes. An Ollama that wedges there still
304
+ * frees the pull. */
305
+ export const PULL_VERIFY_STALL_MS = 15 * 60_000;
306
+ /** The longest progress line a pull takes, in characters: Ollama's are a few hundred, so a stream that sends no newline
307
+ * ends. */
308
+ export const PULL_LINE_MAX = 64 * 1024;
309
+ /**
310
+ * Pulls `tag` through the Ollama `env` names (POST /api/pull, streamed as NDJSON), each line of progress to `onLine` as it
311
+ * comes. Resolves once Ollama says `success`; throws, in Ollama's words, on an `error` line, a refusal, a stream that ends
312
+ * before `success`, or `signal`; in its own, on `stallMs` with no byte from Ollama (the answer's head or a chunk of the
313
+ * stream), `verifyStallMs` once Ollama says it is verifying the digest, or a line past PULL_LINE_MAX. No deadline on the
314
+ * whole: a model is gigabytes, and a pull that moves is let run.
315
+ */
316
+ export async function ollamaPull(env, tag, onLine, { fetch: send = globalThis.fetch, signal, stallMs = PULL_STALL_MS, verifyStallMs = PULL_VERIFY_STALL_MS } = {}) {
317
+ const base = baseOf(env);
318
+ if (base === undefined)
319
+ throw new Error("no Ollama is asked here");
320
+ const stall = new AbortController();
321
+ let timer;
322
+ // The silence let pass now: the stall deadline, until Ollama says it is verifying the digest.
323
+ let quietMs = stallMs;
324
+ const moved = () => {
325
+ clearTimeout(timer);
326
+ timer = setTimeout(() => stall.abort(), quietMs);
327
+ };
328
+ const stopped = signal ? AbortSignal.any([signal, stall.signal]) : stall.signal;
329
+ moved();
330
+ try {
331
+ const response = await send(`${base}/api/pull`, { method: "POST", redirect: "error", signal: stopped, headers: { "content-type": "application/json" }, body: JSON.stringify({ model: tag, stream: true }) });
332
+ if (!response.ok || !response.body) {
333
+ const said = safeJson(await response.text().catch(() => ""));
334
+ throw new Error(typeof said?.error === "string" ? said.error : `/api/pull: ${response.status}`);
335
+ }
336
+ const decoder = new TextDecoder();
337
+ let rest = "";
338
+ let succeeded = false;
339
+ const take = (text) => {
340
+ const line = safeJson(text);
341
+ if (!line || typeof line !== "object")
342
+ return;
343
+ if (typeof line.error === "string")
344
+ throw new Error(line.error);
345
+ if (typeof line.status !== "string")
346
+ return;
347
+ if (line.status === "success")
348
+ succeeded = true;
349
+ quietMs = line.status.startsWith("verifying") ? Math.max(stallMs, verifyStallMs) : stallMs;
350
+ onLine({ status: line.status, ...(typeof line.digest === "string" ? { digest: line.digest } : {}), ...(line.total !== undefined ? { total: count(line.total) } : {}), ...(line.completed !== undefined ? { completed: count(line.completed) } : {}) });
351
+ };
352
+ for await (const chunk of response.body) {
353
+ rest += decoder.decode(chunk, { stream: true });
354
+ let cut;
355
+ while ((cut = rest.indexOf("\n")) >= 0) {
356
+ const text = rest.slice(0, cut).trim();
357
+ rest = rest.slice(cut + 1);
358
+ if (text)
359
+ take(text);
360
+ }
361
+ // Armed after the chunk's lines are read, so a `verifying` line sets the silence that follows it.
362
+ moved();
363
+ if (rest.length > PULL_LINE_MAX)
364
+ throw new Error(`Ollama sent a progress line longer than ${PULL_LINE_MAX} characters, so the pull stopped. Press Pull again.`);
365
+ }
366
+ if (rest.trim())
367
+ take(rest.trim());
368
+ if (!succeeded)
369
+ throw new Error("the pull ended before Ollama said success");
370
+ }
371
+ catch (error) {
372
+ if (stall.signal.aborted && !signal?.aborted)
373
+ throw new Error(`Ollama sent nothing for ${Math.round(quietMs / 1000)} s, so the pull stopped. Press Pull again.`);
374
+ throw error;
375
+ }
376
+ finally {
377
+ clearTimeout(timer);
378
+ }
379
+ }
264
380
  /** `env`'s Ollama listing as last kept (ollamaKept), in one string: each model's tag, capabilities and trained context.
265
381
  * A server compares it to see a model pulled, removed or an Ollama started since it made its offers (server.ts). */
266
382
  export const ollamaListing = (env) => ollamaKept(env).map((model) => `${model.name}=${model.capabilities.join(",")}@${model.trained ?? ""}`).join(" ");