@parcha/agentrun-serve 0.1.0-beta.53 → 0.1.0-beta.55

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 (224) hide show
  1. package/CHANGELOG.md +138 -3
  2. package/README.md +346 -99
  3. package/dist/adapters.d.ts +10 -0
  4. package/dist/adapters.js +46 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +7 -14
  7. package/dist/agent-rows.d.ts +1 -1
  8. package/dist/agents-store.js +7 -6
  9. package/dist/api-only.d.ts +17 -6
  10. package/dist/api-only.js +22 -9
  11. package/dist/cli.js +11 -4
  12. package/dist/composio-made.d.ts +26 -1
  13. package/dist/composio-made.js +39 -2
  14. package/dist/composio-preset.d.ts +6 -4
  15. package/dist/composio-preset.js +50 -17
  16. package/dist/computer-held-routes.js +2 -3
  17. package/dist/computer-needs.d.ts +1 -1
  18. package/dist/computer-needs.js +1 -1
  19. package/dist/computer-setting.d.ts +8 -4
  20. package/dist/computer-setting.js +0 -2
  21. package/dist/computers-running.d.ts +8 -0
  22. package/dist/computers-running.js +27 -0
  23. package/dist/computers.d.ts +0 -2
  24. package/dist/computers.js +1 -1
  25. package/dist/console/assets/backend-D5EmB4N3.js +166 -0
  26. package/dist/console/assets/index-DUYLaqiR.js +746 -0
  27. package/dist/console/assets/index-DYhU4adm.css +1 -0
  28. package/dist/console/index.html +2 -2
  29. package/dist/docker-host-addresses.d.ts +23 -3
  30. package/dist/docker-host-addresses.js +90 -18
  31. package/dist/errors.d.ts +4 -0
  32. package/dist/errors.js +7 -0
  33. package/dist/exa-keyless.d.ts +2 -3
  34. package/dist/exa-keyless.js +43 -127
  35. package/dist/firecrawl-keyless.d.ts +41 -0
  36. package/dist/firecrawl-keyless.js +152 -0
  37. package/dist/github-connection.d.ts +50 -1
  38. package/dist/github-connection.js +96 -3
  39. package/dist/github-faux.d.ts +11 -2
  40. package/dist/github-faux.js +138 -7
  41. package/dist/github-pull-request.d.ts +37 -0
  42. package/dist/github-pull-request.js +110 -0
  43. package/dist/handed-secret.d.ts +3 -1
  44. package/dist/handed-secret.js +4 -2
  45. package/dist/harness-keys.d.ts +98 -0
  46. package/dist/harness-keys.js +247 -0
  47. package/dist/harness-recipe-entry.d.ts +14 -9
  48. package/dist/harness-recipe-entry.js +25 -14
  49. package/dist/harness-table.d.ts +16 -1
  50. package/dist/harness-table.js +19 -7
  51. package/dist/harness.d.ts +4 -0
  52. package/dist/harness.js +12 -1
  53. package/dist/host-check.d.ts +2 -0
  54. package/dist/host-check.js +6 -0
  55. package/dist/import-summary.d.ts +1 -1
  56. package/dist/import-summary.js +1 -1
  57. package/dist/import.d.ts +5 -5
  58. package/dist/import.js +54 -67
  59. package/dist/keyless-mcp.d.ts +36 -0
  60. package/dist/keyless-mcp.js +127 -0
  61. package/dist/learn/audit.d.ts +3 -3
  62. package/dist/learn/audit.js +3 -3
  63. package/dist/learn/commit.d.ts +8 -7
  64. package/dist/learn/commit.js +60 -20
  65. package/dist/learn/compile.d.ts +4 -3
  66. package/dist/learn/compile.js +7 -5
  67. package/dist/learn/folder.d.ts +16 -3
  68. package/dist/learn/folder.js +46 -13
  69. package/dist/learn/promote.d.ts +37 -13
  70. package/dist/learn/promote.js +112 -40
  71. package/dist/learn/secrets.js +10 -2
  72. package/dist/learning-routes.d.ts +22 -17
  73. package/dist/learning-routes.js +40 -39
  74. package/dist/learning.js +2 -2
  75. package/dist/live-reach.d.ts +34 -7
  76. package/dist/live-reach.js +76 -11
  77. package/dist/manifest.d.ts +10 -0
  78. package/dist/manifest.js +30 -0
  79. package/dist/mcp-pin-first.d.ts +4 -2
  80. package/dist/mcp-pin-first.js +5 -2
  81. package/dist/mcp-probe.js +2 -2
  82. package/dist/mcp-secret-writes.d.ts +16 -7
  83. package/dist/mcp-secret-writes.js +35 -27
  84. package/dist/mcp-servers-store.d.ts +30 -6
  85. package/dist/mcp-servers-store.js +112 -28
  86. package/dist/mcp-sources.d.ts +10 -2
  87. package/dist/mcp-sources.js +9 -2
  88. package/dist/mcp-store.d.ts +13 -7
  89. package/dist/mcp-store.js +12 -9
  90. package/dist/model-form.d.ts +3 -2
  91. package/dist/model-form.js +11 -7
  92. package/dist/model.d.ts +20 -4
  93. package/dist/model.js +68 -9
  94. package/dist/native/history.d.ts +1 -1
  95. package/dist/native/history.js +2 -2
  96. package/dist/ollama-provider.d.ts +92 -0
  97. package/dist/ollama-provider.js +495 -0
  98. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  99. package/dist/openapi.js +235 -41
  100. package/dist/page.d.ts +11 -3
  101. package/dist/page.js +22 -7
  102. package/dist/place-offers.d.ts +17 -1
  103. package/dist/place-offers.js +46 -5
  104. package/dist/print.js +1 -1
  105. package/dist/purged-workflow.d.ts +35 -7
  106. package/dist/purged-workflow.js +73 -26
  107. package/dist/run-computer.d.ts +2 -0
  108. package/dist/run-computer.js +2 -0
  109. package/dist/run-files.d.ts +4 -0
  110. package/dist/run-files.js +4 -0
  111. package/dist/run-keys.d.ts +2 -4
  112. package/dist/run-keys.js +6 -7
  113. package/dist/run-launch.d.ts +4 -0
  114. package/dist/run-launch.js +4 -0
  115. package/dist/run-reads-over-store.d.ts +3 -2
  116. package/dist/run-reads-over-store.js +66 -2
  117. package/dist/run-secrets.js +5 -2
  118. package/dist/runner/adapter-loop.d.ts +6 -3
  119. package/dist/runner/adapter-loop.js +34 -15
  120. package/dist/runner/adapter-run-spec.d.ts +3 -0
  121. package/dist/runner/adapter-run-spec.js +6 -4
  122. package/dist/runner/audit.js +8 -4
  123. package/dist/runner/beside.d.ts +2 -1
  124. package/dist/runner/beside.js +6 -2
  125. package/dist/runner/claim-secrets.d.ts +5 -8
  126. package/dist/runner/claim-secrets.js +6 -0
  127. package/dist/runner/cli-run-spec.d.ts +1 -1
  128. package/dist/runner/cli-run-spec.js +39 -7
  129. package/dist/runner/harness-loops.d.ts +22 -9
  130. package/dist/runner/harness-loops.js +21 -11
  131. package/dist/runner/held.d.ts +3 -0
  132. package/dist/runner/learning-end.d.ts +1 -1
  133. package/dist/runner/learning-end.js +8 -3
  134. package/dist/runner/loop-contract.d.ts +5 -4
  135. package/dist/runner/main.js +4 -2
  136. package/dist/runner/mcp-claim.d.ts +3 -0
  137. package/dist/runner/mcp-claim.js +26 -2
  138. package/dist/runner/mcp-run.d.ts +3 -0
  139. package/dist/runner/mcp-run.js +2 -1
  140. package/dist/runner/metrics.d.ts +10 -8
  141. package/dist/runner/metrics.js +20 -27
  142. package/dist/runner/model-route.d.ts +3 -0
  143. package/dist/runner/model-route.js +6 -2
  144. package/dist/runner/pr-checkout.d.ts +21 -4
  145. package/dist/runner/pr-checkout.js +103 -4
  146. package/dist/runner/promotion.d.ts +15 -9
  147. package/dist/runner/promotion.js +25 -15
  148. package/dist/runner/run-child-host.js +24 -11
  149. package/dist/runner/run-child.js +3 -1
  150. package/dist/runner/runner-check.d.ts +3 -0
  151. package/dist/runner/runner-check.js +23 -0
  152. package/dist/runner/sdk-loop.js +2 -0
  153. package/dist/runner/workflow-loop.d.ts +2 -2
  154. package/dist/runner/workflow-loop.js +1 -2
  155. package/dist/runner/workflow-spec.d.ts +1 -1
  156. package/dist/runner/workflow-spec.js +6 -6
  157. package/dist/sdk/check.d.ts +4 -1
  158. package/dist/sdk/check.js +2 -1
  159. package/dist/sdk/runs.d.ts +2 -2
  160. package/dist/sdk/runs.js +8 -6
  161. package/dist/secret-cut.js +2 -1
  162. package/dist/secret-writes.d.ts +3 -2
  163. package/dist/secret-writes.js +1 -1
  164. package/dist/server.d.ts +55 -8
  165. package/dist/server.js +363 -118
  166. package/dist/standard-webhooks.d.ts +11 -0
  167. package/dist/standard-webhooks.js +20 -2
  168. package/dist/store/agent-body.d.ts +2 -2
  169. package/dist/store/agent-body.js +2 -2
  170. package/dist/store/index.d.ts +1 -1
  171. package/dist/store/schema.js +5 -2
  172. package/dist/store/sqlite/store.js +90 -34
  173. package/dist/store/store.d.ts +54 -14
  174. package/dist/store-reads/journal.d.ts +7 -2
  175. package/dist/store-reads/journal.js +9 -6
  176. package/dist/store-reads/learning.d.ts +12 -9
  177. package/dist/store-reads/learning.js +18 -24
  178. package/dist/store-view.d.ts +0 -5
  179. package/dist/store-view.js +9 -8
  180. package/dist/suggestions.d.ts +282 -0
  181. package/dist/suggestions.js +919 -0
  182. package/dist/telemetry.d.ts +8 -1
  183. package/dist/telemetry.js +12 -4
  184. package/dist/template-eval.d.ts +49 -4
  185. package/dist/template-eval.js +168 -45
  186. package/dist/template-import.d.ts +17 -0
  187. package/dist/template-import.js +36 -2
  188. package/dist/templates.d.ts +83 -76
  189. package/dist/templates.js +29 -48
  190. package/dist/timeline/labels.d.ts +2 -2
  191. package/dist/timeline/labels.js +2 -2
  192. package/dist/timeline/timeline.d.ts +2 -2
  193. package/dist/timeline/timeline.js +1 -1
  194. package/dist/tool-plane.d.ts +17 -9
  195. package/dist/tool-plane.js +38 -17
  196. package/dist/tools.js +2 -2
  197. package/dist/trigger-launch-hook.d.ts +19 -9
  198. package/dist/trigger-launch-hook.js +35 -25
  199. package/dist/trigger-targets.d.ts +18 -8
  200. package/dist/trigger-targets.js +42 -19
  201. package/dist/triggers.d.ts +85 -23
  202. package/dist/triggers.js +303 -96
  203. package/dist/validate.d.ts +1 -1
  204. package/dist/validate.js +2 -2
  205. package/dist/web-fake.js +3 -3
  206. package/dist/web-fetch-direct.d.ts +4 -0
  207. package/dist/web-fetch-direct.js +8 -1
  208. package/dist/web-fetch.d.ts +12 -3
  209. package/dist/web-fetch.js +47 -14
  210. package/dist/web-search.d.ts +33 -4
  211. package/dist/web-search.js +100 -41
  212. package/dist/webhooks.js +4 -5
  213. package/dist/workspace/synced-folder.d.ts +1 -1
  214. package/dist/workspace/synced-folder.js +11 -14
  215. package/launcher/agentrun-serve +5 -1
  216. package/package.json +17 -13
  217. package/templates/README.md +5 -4
  218. package/templates/agent-scout/agent.md +46 -0
  219. package/templates/agent-scout/skills/scout/SKILL.md +88 -0
  220. package/templates/agent-scout/skills/scout/suggestions.schema.json +112 -0
  221. package/dist/console/assets/index-BFgyZzF_.js +0 -734
  222. package/dist/console/assets/index-DbilxljH.css +0 -1
  223. package/dist/import-sources.d.ts +0 -116
  224. package/dist/import-sources.js +0 -693
@@ -0,0 +1,495 @@
1
+ // Ollama as a model provider: the models the Ollama on this machine (or the one OLLAMA_HOST names) has pulled, listed live
2
+ // from its own API, run by pi alone, at $0, on Ollama's native chat API. No key: Ollama has none.
3
+ // Where: OLLAMA_HOST, Ollama's own variable, read as the ollama CLI reads it (ollamaBase), from the server's environment,
4
+ // never from a provider's auth context, so it is never a held secret. Unset, the server names the default address
5
+ // itself only on one owner's own machine (ollamaHostOf); unset anywhere else, no Ollama is asked. Plain http only to this machine (provider.ts
6
+ // gatewayBase, the one base rule); anything else needs https.
7
+ // Which models: GET /api/tags, then POST /api/show for each, whose `capabilities` say whether it chats (`completion`),
8
+ // takes tools (`tools`) and thinks (`thinking`), and whose model_info's `<family>.context_length` is the context it was
9
+ // trained on. Nothing is hardcoded. A model with no `tools` capability takes its tools as text (local-models.ts ToolsAs,
10
+ // on the runner's translated route).
11
+ // Wire: POST /api/chat, streamed as NDJSON. Its OpenAI-compatible API cannot set the context size, and Ollama's own
12
+ // default context is small, so every request names it: options.num_ctx, the model's trained context up to 64k
13
+ // (OLLAMA_NUM_CTX), and the model's window here is that same number.
14
+ // Listing never stalls a caller: one short deadline for the whole listing, no redirects, and a down, hung or refused Ollama
15
+ // lists no models and throws nothing. Each address's answer is kept (OLLAMA_TTL_MS) and refreshed behind the caller.
16
+ import { calculateCost, collapseSystemMessages, createAssistantMessageEventStream, getCurrentSystemPrompt, getCurrentTools } from "@earendil-works/pi-ai";
17
+ import { transformMessages } from "@earendil-works/pi-ai/api/transform-messages";
18
+ import { createProvider } from "@earendil-works/pi-ai/models";
19
+ import { gatewayBase } from "./provider.js";
20
+ /** The provider's id, the prefix of its models' refs (`ollama/<tag>`). */
21
+ export const OLLAMA_PROVIDER = "ollama";
22
+ /** The api its models name: Ollama's own chat API, neither Responses nor Messages, so the runner's route translates it. */
23
+ export const OLLAMA_API = "ollama-chat";
24
+ /** The most context a request asks Ollama for (options.num_ctx), and so the most window a model has here: 64k. */
25
+ export const OLLAMA_NUM_CTX = 65_536;
26
+ /** How long a listing may take, all of it: a stuck Ollama costs a caller this once per OLLAMA_TTL_MS at most. */
27
+ export const OLLAMA_LIST_TIMEOUT_MS = 2_000;
28
+ /** How long an address's listing is kept before it is asked again (behind the caller, which takes the kept one). */
29
+ export const OLLAMA_TTL_MS = 30_000;
30
+ /** Ollama's port, where OLLAMA_HOST names none and no scheme. */
31
+ const OLLAMA_PORT = "11434";
32
+ const ZERO = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
33
+ /**
34
+ * The base URL OLLAMA_HOST names, as the ollama CLI reads it (envconfig.Host): unset, this machine on 11434; with no
35
+ * scheme, http; with no port, 11434 with no scheme and the scheme's own with one (https: 443); a path kept. `0.0.0.0` and
36
+ * `::`, where `ollama serve` listens on every address, connect to this machine. Then the one base rule (provider.ts
37
+ * gatewayBase): plain http only to this machine, no user, query or fragment. Throws, naming OLLAMA_HOST, when refused.
38
+ */
39
+ export function ollamaBase(env) {
40
+ const given = (env.OLLAMA_HOST ?? "").trim();
41
+ const cut = given.indexOf("://");
42
+ const scheme = cut < 0 ? "http" : given.slice(0, cut).toLowerCase();
43
+ const rest = cut < 0 ? given : given.slice(cut + 3);
44
+ const slash = rest.indexOf("/");
45
+ const hostport = slash < 0 ? rest : rest.slice(0, slash);
46
+ const path = slash < 0 ? "" : rest.slice(slash);
47
+ // A user before the host: the base rule refuses it, in its words.
48
+ if (hostport.includes("@"))
49
+ return gatewayBase("OLLAMA_HOST", `${scheme}://${rest}`);
50
+ const defaultPort = cut < 0 ? OLLAMA_PORT : scheme === "https" ? "443" : scheme === "http" ? "80" : OLLAMA_PORT;
51
+ let [host, port] = splitHostPort(hostport);
52
+ if (!/^\d{1,5}$/.test(port ?? "") || Number(port) > 65_535)
53
+ port = defaultPort;
54
+ if (host === "" || host === "0.0.0.0")
55
+ host = "127.0.0.1";
56
+ if (host === "::")
57
+ host = "::1";
58
+ return gatewayBase("OLLAMA_HOST", `${scheme}://${host.includes(":") ? `[${host}]` : host}:${port}${path}`);
59
+ }
60
+ /** `host:port`, `[v6]:port`, `[v6]`, a bare IPv6 address or a host alone, as Go's net.SplitHostPort and the CLI's fallback
61
+ * read them: the host (brackets off) and the port, undefined where none is named. */
62
+ function splitHostPort(hostport) {
63
+ const bracketed = /^\[([^\]]*)\](?::(.*))?$/.exec(hostport);
64
+ if (bracketed)
65
+ return [bracketed[1], bracketed[2]];
66
+ const colons = hostport.split(":").length - 1;
67
+ if (colons === 1) {
68
+ const [host, port] = hostport.split(":");
69
+ return [host, port];
70
+ }
71
+ return [hostport, undefined];
72
+ }
73
+ /** Each address's last listing, by base URL, and the listing under way for it. */
74
+ const kept = new Map();
75
+ const asking = new Map();
76
+ /** The clock a listing is kept by: Date.now, or a test's (ollamaClock). */
77
+ let now = Date.now;
78
+ /** A test's clock for the kept listings, so it ages them without waiting; with none, Date.now again. */
79
+ export function ollamaClock(clock) {
80
+ now = clock ?? Date.now;
81
+ }
82
+ /** The listing under way for the Ollama `env` names (one a stale answer started behind its caller), or undefined: for a
83
+ * test to await what a refresh brings. */
84
+ export function ollamaAsking(env) {
85
+ const base = baseOf(env);
86
+ return base === undefined ? undefined : asking.get(base);
87
+ }
88
+ /** Whether an /api/tags or /api/show entry is a cloud model's. Its prompts leave this machine, so it is never listed: the
89
+ * models here are local, $0 and uncounted, and a cloud model is none of those. */
90
+ const remote = (entry) => entry?.remote_host !== undefined || entry?.remote_model !== undefined;
91
+ /** A test process's switch, read from its own environment (process.env), never from the `env` a caller passes: set, no
92
+ * Ollama is asked, whatever address that `env` names or leaves to the default. A test hook's name (model.ts FAUX_PREFIX),
93
+ * so a server never hands it on to its runs. The test suites set it (test/support.mjs); a test of Ollama clears it. */
94
+ export const OLLAMA_OFF_ENV = "AGENTRUN_SERVE_FAUX_NO_OLLAMA";
95
+ /** Ollama's own default address (ollamaBase of an unset OLLAMA_HOST). */
96
+ export const OLLAMA_DEFAULT_HOST = `127.0.0.1:${OLLAMA_PORT}`;
97
+ /**
98
+ * The OLLAMA_HOST a server asks, and hands the runner beside it: the one its environment sets, else Ollama's default
99
+ * address on one owner's own server on their own machine (`ownMachine`: server.ts whyNotOwnMachine, the rule
100
+ * --harness-sign-in starts under), else none. On a shared server, whatever answers on this machine's 11434 is no model of
101
+ * the people who start runs there, so it is asked only where its operator names it.
102
+ */
103
+ export function ollamaHostOf(env, ownMachine) {
104
+ const given = env.OLLAMA_HOST?.trim();
105
+ return given ? given : ownMachine ? OLLAMA_DEFAULT_HOST : undefined;
106
+ }
107
+ /** Why the OLLAMA_HOST `env` names is refused (ollamaBase's words, which never hold its value), or undefined. */
108
+ export function ollamaHostRefused(env) {
109
+ if (!env.OLLAMA_HOST?.trim())
110
+ return undefined;
111
+ try {
112
+ ollamaBase(env);
113
+ return undefined;
114
+ }
115
+ catch (error) {
116
+ return error instanceof Error ? error.message : String(error);
117
+ }
118
+ }
119
+ /** The base OLLAMA_HOST names, or undefined where it names none (a server names the default where it may: ollamaHostOf),
120
+ * is refused (ollamaBase) or the test switch is on (OLLAMA_OFF_ENV). */
121
+ const baseOf = (env) => {
122
+ if (process.env[OLLAMA_OFF_ENV] || !env.OLLAMA_HOST?.trim())
123
+ return undefined;
124
+ try {
125
+ return ollamaBase(env);
126
+ }
127
+ catch {
128
+ return undefined;
129
+ }
130
+ };
131
+ /** A request to the Ollama at `base`, under `signal`, following no redirect: its JSON answer, or a throw. */
132
+ const askerOf = (base, send, signal) => async (path, body) => {
133
+ const response = await send(`${base}${path}`, { method: body === undefined ? "GET" : "POST", redirect: "error", signal, ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) });
134
+ if (!response.ok)
135
+ throw new Error(`${path}: ${response.status}`);
136
+ return response.json();
137
+ };
138
+ /** Model `name` as /api/show reports it (`ask`): its capabilities and trained context. Undefined where it does not answer
139
+ * (a refusal, a wrong shape, the deadline) or names a cloud model. */
140
+ async function shownOf(ask, name) {
141
+ try {
142
+ const show = (await ask("/api/show", { model: name }));
143
+ if (remote(show))
144
+ return undefined;
145
+ // An Ollama from before /api/show said capabilities chats, with its tools as text.
146
+ const capabilities = Array.isArray(show?.capabilities) ? show.capabilities.filter((c) => typeof c === "string") : ["completion"];
147
+ const length = Object.entries(show?.model_info ?? {}).find(([key]) => key.endsWith(".context_length"))?.[1];
148
+ return { name, capabilities, trained: typeof length === "number" && Number.isSafeInteger(length) && length > 0 ? length : undefined };
149
+ }
150
+ catch {
151
+ return undefined;
152
+ }
153
+ }
154
+ /**
155
+ * The models the Ollama `env` names has, asked now: its tags (/api/tags), each one's capabilities and trained context
156
+ * (/api/show), in the order Ollama lists them. All of it within `timeoutMs`, with no redirect followed; a refused
157
+ * OLLAMA_HOST, a down or hung Ollama, or an answer of the wrong shape lists none, and nothing is thrown. A model /api/show
158
+ * does not answer for, before the deadline included, is left out and the others kept; so is a cloud model (remote_host or
159
+ * remote_model, in either answer). The answer is kept for its address (ollamaModels, ollamaKept). `fetch`: a test's.
160
+ */
161
+ export async function listOllama(env, { fetch: send = globalThis.fetch, timeoutMs = OLLAMA_LIST_TIMEOUT_MS } = {}) {
162
+ const base = baseOf(env);
163
+ if (base === undefined)
164
+ return [];
165
+ const ask = askerOf(base, send, AbortSignal.timeout(timeoutMs));
166
+ let models = [];
167
+ try {
168
+ const tags = (await ask("/api/tags"));
169
+ const names = (Array.isArray(tags?.models) ? tags.models : []).filter((tag) => !remote(tag)).map((tag) => tag?.name ?? tag?.model).filter((name) => typeof name === "string" && name.length > 0);
170
+ models = (await Promise.all(names.map((name) => shownOf(ask, name)))).filter((model) => model !== undefined);
171
+ }
172
+ catch {
173
+ models = [];
174
+ }
175
+ kept.set(base, { at: now(), models });
176
+ return models;
177
+ }
178
+ /** How long a run gives the /api/show of the one Ollama model it names (ollamaShown): longer than a listing's, since the
179
+ * run cannot start without it and Ollama may be loading another model. */
180
+ export const OLLAMA_SHOW_TIMEOUT_MS = 10_000;
181
+ /** Model `tag` of the Ollama `env` names, for a run that names it (`ollama/<tag>`): from its address's kept listing while
182
+ * that is fresh (OLLAMA_TTL_MS), else its own /api/show within `timeoutMs`, never /api/tags, so a run never waits on a
183
+ * whole listing and never runs on a model's context from before it was pulled again. Undefined where it is not there,
184
+ * does not answer, is a cloud model or OLLAMA_HOST is refused. Nothing kept: the listing is the kept one. */
185
+ export async function ollamaShown(env, tag, { fetch: send = globalThis.fetch, timeoutMs = OLLAMA_SHOW_TIMEOUT_MS } = {}) {
186
+ const base = baseOf(env);
187
+ if (base === undefined)
188
+ return undefined;
189
+ const known = kept.get(base);
190
+ const fresh = known && now() - known.at < OLLAMA_TTL_MS ? known.models.find((model) => model.name === tag) : undefined;
191
+ return fresh ?? shownOf(askerOf(base, send, AbortSignal.timeout(timeoutMs)), tag);
192
+ }
193
+ /** The models the Ollama `env` names has: its address's kept listing while fresh; a stale one at once, asked again behind
194
+ * the caller; none kept, asked now (listOllama). One listing per address at a time. */
195
+ export async function ollamaModels(env) {
196
+ const base = baseOf(env);
197
+ if (base === undefined)
198
+ return [];
199
+ const known = kept.get(base);
200
+ if (known && now() - known.at < OLLAMA_TTL_MS)
201
+ return known.models;
202
+ let listing = asking.get(base);
203
+ if (!listing) {
204
+ listing = listOllama(env).finally(() => asking.delete(base));
205
+ asking.set(base, listing);
206
+ }
207
+ return known ? known.models : listing;
208
+ }
209
+ /** The models the Ollama `env` names has, asked again now: its kept listing dropped first, so a tag removed since it was
210
+ * kept is gone from the answer (model.ts chooseModel, once the host's default no longer answers). A listing already
211
+ * under way for the address is awaited, never doubled. */
212
+ export async function ollamaRelisted(env) {
213
+ const base = baseOf(env);
214
+ if (base === undefined)
215
+ return [];
216
+ kept.delete(base);
217
+ return ollamaModels(env);
218
+ }
219
+ /** The models the Ollama `env` names had when last asked (ollamaModels): none where it was never asked. Synchronous, for
220
+ * the host's default model (model.ts hostModel), which a listing primes before it is read. */
221
+ export function ollamaKept(env) {
222
+ const base = baseOf(env);
223
+ return base === undefined ? [] : (kept.get(base)?.models ?? []);
224
+ }
225
+ /** `env`'s Ollama listing as last kept (ollamaKept), in one string: each model's tag, capabilities and trained context.
226
+ * A server compares it to see a model pulled, removed or an Ollama started since it made its offers (server.ts). */
227
+ export const ollamaListing = (env) => ollamaKept(env).map((model) => `${model.name}=${model.capabilities.join(",")}@${model.trained ?? ""}`).join(" ");
228
+ /** The context a request on `model` asks for, and its window here: its trained context up to OLLAMA_NUM_CTX (which a model
229
+ * /api/show names none for gets), and never above the OLLAMA_CONTEXT_LENGTH `env` sets. */
230
+ export const contextOf = (model, env) => Math.min(OLLAMA_NUM_CTX, model.trained ?? OLLAMA_NUM_CTX, contextLengthOf(env) ?? OLLAMA_NUM_CTX);
231
+ /** OLLAMA_CONTEXT_LENGTH, Ollama's own default context, where `env` sets it to a whole number above 0: a person who set it
232
+ * lower (for their memory) is never sent more. Any other value, none. */
233
+ const contextLengthOf = (env) => {
234
+ const given = env.OLLAMA_CONTEXT_LENGTH?.trim();
235
+ if (!given || !/^\d+$/.test(given))
236
+ return undefined;
237
+ const length = Number(given);
238
+ return Number.isSafeInteger(length) && length > 0 ? length : undefined;
239
+ };
240
+ /** Whether `model` chats (an embedding model does not). */
241
+ const chats = (model) => model.capabilities.includes("completion");
242
+ /** The models of `env`'s Ollama that chat and call tools, as refs (`ollama/<tag>`), from its kept listing (ollamaKept),
243
+ * in its order: the ones a run of pi has tools on. */
244
+ export function ollamaToolsModels(env) {
245
+ return ollamaKept(env).filter((each) => chats(each) && each.capabilities.includes("tools")).map((each) => `${OLLAMA_PROVIDER}/${each.name}`);
246
+ }
247
+ /** The first of ollamaToolsModels; undefined where none calls tools. */
248
+ export const ollamaToolsModel = (env) => ollamaToolsModels(env)[0];
249
+ /** The provider of `listed` (its chat models) at `base`: keyless, $0, each model's window its context (contextOf). */
250
+ export function ollamaProvider(base, listed, env) {
251
+ const models = listed.filter(chats).map((model) => {
252
+ const window = contextOf(model, env);
253
+ return {
254
+ id: model.name,
255
+ name: `${model.name} (Ollama)`,
256
+ api: OLLAMA_API,
257
+ provider: OLLAMA_PROVIDER,
258
+ baseUrl: base,
259
+ reasoning: model.capabilities.includes("thinking"),
260
+ input: model.capabilities.includes("vision") ? ["text", "image"] : ["text"],
261
+ cost: { ...ZERO },
262
+ contextWindow: window,
263
+ maxTokens: Math.min(16_384, Math.floor(window / 2)),
264
+ ...(model.capabilities.includes("tools") ? {} : { toolsAs: "text" }),
265
+ };
266
+ });
267
+ return createProvider({
268
+ id: OLLAMA_PROVIDER,
269
+ name: "Ollama",
270
+ baseUrl: base,
271
+ // No key: Ollama takes none, so its auth resolves to none, as the faux provider's does (model.ts runModels).
272
+ auth: { apiKey: { name: "Ollama", resolve: async () => ({ auth: {} }) } },
273
+ models,
274
+ api: { stream: streamChat, streamSimple: streamChat },
275
+ });
276
+ }
277
+ /** `context` as /api/chat's body for `model`: the current system prompt first, each message in Ollama's shape (a call's
278
+ * arguments an object, a result `tool` with the tool's name, images as base64), and the current tools in its `tools`. */
279
+ export function chatBody(model, context, options) {
280
+ const collapsed = collapseSystemMessages(context);
281
+ const system = getCurrentSystemPrompt(collapsed.messages);
282
+ const tools = getCurrentTools(collapsed.messages);
283
+ const messages = system ? [{ role: "system", content: system }] : [];
284
+ const textOf = (parts) => parts.filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n");
285
+ const imagesOf = (parts) => parts.flatMap((part) => (part.type === "image" && part.data ? [part.data] : []));
286
+ for (const message of transformMessages(collapsed.messages, model)) {
287
+ if (message.role === "system")
288
+ continue;
289
+ if (message.role === "user") {
290
+ const parts = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
291
+ const images = imagesOf(parts);
292
+ messages.push({ role: "user", content: textOf(parts), ...(images.length ? { images } : {}) });
293
+ }
294
+ else if (message.role === "assistant") {
295
+ const thinking = message.content.flatMap((part) => (part.type === "thinking" && !part.redacted ? [part.thinking] : [])).join("");
296
+ const calls = message.content.flatMap((part) => (part.type === "toolCall" ? [{ function: { name: part.name, arguments: part.arguments } }] : []));
297
+ messages.push({ role: "assistant", content: textOf(message.content), ...(thinking ? { thinking } : {}), ...(calls.length ? { tool_calls: calls } : {}) });
298
+ }
299
+ else {
300
+ const images = imagesOf(message.content);
301
+ messages.push({ role: "tool", tool_name: message.toolName, content: textOf(message.content), ...(images.length ? { images } : {}) });
302
+ }
303
+ }
304
+ const window = Math.min(model.contextWindow, OLLAMA_NUM_CTX);
305
+ return {
306
+ model: model.id,
307
+ messages,
308
+ ...(tools.length ? { tools: tools.map((tool) => ({ type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters } })) } : {}),
309
+ stream: true,
310
+ // A thinking model asked to reason thinks; asked nothing, Ollama's default.
311
+ ...(model.reasoning && options?.reasoning ? { think: true } : {}),
312
+ options: { num_ctx: window, ...(options?.maxTokens ? { num_predict: options.maxTokens } : {}), ...(options?.temperature === undefined ? {} : { temperature: options.temperature }) },
313
+ };
314
+ }
315
+ /** One request on /api/chat, its NDJSON read into pi-ai's events: text and thinking as they stream, each tool call whole,
316
+ * and the end with Ollama's counts as its usage (prompt_eval_count in, eval_count out), at the model's price ($0). An
317
+ * error line, a refused status or a broken stream ends in an error event; a stopped one in an aborted one. */
318
+ function streamChat(model, context, options) {
319
+ const stream = createAssistantMessageEventStream();
320
+ const output = { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...ZERO, total: 0 } }, stopReason: "stop", timestamp: Date.now() };
321
+ void (async () => {
322
+ const send = options?.fetch ?? globalThis.fetch;
323
+ const body = chatBody(model, context, options);
324
+ const response = await send(`${model.baseUrl}/api/chat`, { method: "POST", redirect: "error", headers: { "content-type": "application/json", ...headersOf(options) }, body: JSON.stringify(body), ...(options?.signal ? { signal: options.signal } : {}) });
325
+ await options?.onResponse?.({ status: response.status, headers: Object.fromEntries(response.headers) }, model);
326
+ if (!response.ok || !response.body) {
327
+ const text = await response.text().catch(() => "");
328
+ let said = text;
329
+ try {
330
+ said = JSON.parse(text).error ?? text;
331
+ }
332
+ catch { }
333
+ throw new Error(`${response.status} ${said}`.trim());
334
+ }
335
+ stream.push({ type: "start", partial: output });
336
+ // The block open now (text or thinking), by its index in the answer's content.
337
+ let open;
338
+ const close = () => {
339
+ if (!open)
340
+ return;
341
+ const block = output.content[open.index];
342
+ if (open.kind === "text")
343
+ stream.push({ type: "text_end", contentIndex: open.index, content: block.text, partial: output });
344
+ else
345
+ stream.push({ type: "thinking_end", contentIndex: open.index, content: block.thinking, partial: output });
346
+ open = undefined;
347
+ };
348
+ const add = (kind, delta) => {
349
+ if (!delta)
350
+ return;
351
+ if (open?.kind !== kind) {
352
+ close();
353
+ output.content.push(kind === "text" ? { type: "text", text: "" } : { type: "thinking", thinking: "" });
354
+ open = { kind, index: output.content.length - 1 };
355
+ stream.push({ type: kind === "text" ? "text_start" : "thinking_start", contentIndex: open.index, partial: output });
356
+ }
357
+ const block = output.content[open.index];
358
+ if (kind === "text")
359
+ block.text += delta;
360
+ else
361
+ block.thinking += delta;
362
+ stream.push({ type: kind === "text" ? "text_delta" : "thinking_delta", contentIndex: open.index, delta, partial: output });
363
+ };
364
+ let calls = 0;
365
+ let ended;
366
+ // A model without the thinking capability gets no split from Ollama: its content's opening <think> is split here.
367
+ const split = model.reasoning ? undefined : thinkSplit();
368
+ const content = (delta) => {
369
+ if (!split)
370
+ return add("text", delta);
371
+ for (const [kind, part] of split(delta))
372
+ add(kind, part);
373
+ };
374
+ const read = (line) => {
375
+ if (line.error)
376
+ throw new Error(line.error);
377
+ add("thinking", line.message?.thinking ?? "");
378
+ content(line.message?.content ?? "");
379
+ for (const call of line.message?.tool_calls ?? []) {
380
+ close();
381
+ const args = call.function?.arguments;
382
+ const parsed = typeof args === "string" ? safeJson(args) : args;
383
+ const toolCall = { type: "toolCall", id: call.id || `call_${calls}_${Math.random().toString(36).slice(2, 10)}`, name: call.function?.name ?? "", arguments: (parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}) };
384
+ calls += 1;
385
+ output.content.push(toolCall);
386
+ const index = output.content.length - 1;
387
+ stream.push({ type: "toolcall_start", contentIndex: index, partial: output });
388
+ stream.push({ type: "toolcall_delta", contentIndex: index, delta: JSON.stringify(toolCall.arguments), partial: output });
389
+ stream.push({ type: "toolcall_end", contentIndex: index, toolCall, partial: output });
390
+ }
391
+ if (line.done)
392
+ ended = line;
393
+ };
394
+ const decoder = new TextDecoder();
395
+ let rest = "";
396
+ for await (const chunk of response.body) {
397
+ rest += decoder.decode(chunk, { stream: true });
398
+ const lines = rest.split("\n");
399
+ rest = lines.pop() ?? "";
400
+ for (const line of lines)
401
+ if (line.trim())
402
+ read(JSON.parse(line));
403
+ }
404
+ if ((rest + decoder.decode()).trim())
405
+ read(JSON.parse(rest));
406
+ for (const [kind, part] of split?.(undefined) ?? [])
407
+ add(kind, part);
408
+ close();
409
+ if (!ended)
410
+ throw new Error("Ollama's answer ended before it was done");
411
+ const input = count(ended.prompt_eval_count);
412
+ const out = count(ended.eval_count);
413
+ output.usage = { input, output: out, cacheRead: 0, cacheWrite: 0, totalTokens: input + out, cost: { ...ZERO, total: 0 } };
414
+ output.usage.cost = calculateCost(model, output.usage);
415
+ output.stopReason = calls > 0 ? "toolUse" : ended.done_reason === "length" ? "length" : "stop";
416
+ if (ended.done_reason)
417
+ output.rawStopReason = ended.done_reason;
418
+ stream.push({ type: "done", reason: output.stopReason, message: output });
419
+ stream.end(output);
420
+ })().catch((error) => {
421
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
422
+ output.errorMessage = error instanceof Error ? error.message : String(error);
423
+ stream.push({ type: "error", reason: output.stopReason, error: output });
424
+ stream.end(output);
425
+ });
426
+ return stream;
427
+ }
428
+ const OPEN = "<think>";
429
+ const CLOSE = "</think>";
430
+ /**
431
+ * The content of a model Ollama splits no thinking out of, split as Ollama's own thinking parser splits a thinking
432
+ * model's: where the answer opens with `<think>` (after any whitespace), what follows is thinking up to `</think>`, then
433
+ * the rest is text, whitespace at the start of each left out. Any other answer is text as it came. Takes each delta in
434
+ * turn, and `undefined` at the end for what it held back (a tag still incomplete); answers the parts to add, in order.
435
+ */
436
+ function thinkSplit() {
437
+ let state = "opening";
438
+ let held = "";
439
+ return (delta) => {
440
+ const parts = [];
441
+ const end = delta === undefined;
442
+ let input = held + (delta ?? "");
443
+ held = "";
444
+ if (state === "opening") {
445
+ const start = input.trimStart();
446
+ if (start.startsWith(OPEN))
447
+ [state, input] = ["thinking", start.slice(OPEN.length).trimStart()];
448
+ else if (OPEN.startsWith(start) && !end)
449
+ return (held = input), parts;
450
+ else
451
+ state = "text";
452
+ }
453
+ if (state === "thinking") {
454
+ const at = input.indexOf(CLOSE);
455
+ if (at < 0) {
456
+ // A tail that may begin `</think>` waits for the next delta, unless this is the end.
457
+ let keep = 0;
458
+ if (!end)
459
+ for (let n = Math.min(CLOSE.length - 1, input.length); n > 0; n--)
460
+ if (CLOSE.startsWith(input.slice(-n))) {
461
+ keep = n;
462
+ break;
463
+ }
464
+ held = input.slice(input.length - keep);
465
+ if (input.length > keep)
466
+ parts.push(["thinking", input.slice(0, input.length - keep)]);
467
+ return parts;
468
+ }
469
+ if (at > 0)
470
+ parts.push(["thinking", input.slice(0, at)]);
471
+ [state, input] = ["after", input.slice(at + CLOSE.length)];
472
+ }
473
+ if (state === "after") {
474
+ input = input.trimStart();
475
+ if (!input)
476
+ return parts;
477
+ state = "text";
478
+ }
479
+ if (input)
480
+ parts.push(["text", input]);
481
+ return parts;
482
+ };
483
+ }
484
+ /** A count Ollama reports, or 0 where it reports none (a cached prompt reports no prompt_eval_count). */
485
+ const count = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0);
486
+ /** The request's own headers, a null one left out. */
487
+ const headersOf = (options) => Object.fromEntries(Object.entries(options?.headers ?? {}).filter((entry) => typeof entry[1] === "string"));
488
+ function safeJson(text) {
489
+ try {
490
+ return JSON.parse(text);
491
+ }
492
+ catch {
493
+ return undefined;
494
+ }
495
+ }
@@ -3523,7 +3523,7 @@
3523
3523
  },
3524
3524
  "TimelineKind": {
3525
3525
  "type": "string",
3526
- "description": "#572 `TimelineKind`: Grep's ten kinds, then `user_message`, `waiting` and `usage`.",
3526
+ "description": "#572 `TimelineKind`: the ten base kinds, then `user_message`, `waiting` and `usage`.",
3527
3527
  "enum": [
3528
3528
  "thinking",
3529
3529
  "text_block",
@@ -3542,7 +3542,7 @@
3542
3542
  },
3543
3543
  "TimelineRow": {
3544
3544
  "type": "object",
3545
- "description": "#572 `TimelineEvent`, field for field: Grep's 13 fields, then the open additions. `seq` is optional in the\ntype (Grep's rows have none) and required here: every /v2 row has it, and a page sorts by it.\nCaps are Grep's: summary and previews 500, text 2000. A row never carries a live-view URL, a browser\ncontext id or a cookie; every string but a person's own message keeps a URL's origin, path and query keys\nand drops the rest.\n",
3545
+ "description": "#572 `TimelineEvent`, field for field: the 13 base fields, then the open additions. `seq` is optional in the\ntype (a base row has none) and required here: every /v2 row has it, and a page sorts by it.\nThe base caps: summary and previews 500, text 2000. A row never carries a live-view URL, a browser\ncontext id or a cookie; every string but a person's own message keeps a URL's origin, path and query keys\nand drops the rest.\n",
3546
3546
  "additionalProperties": false,
3547
3547
  "required": [
3548
3548
  "id",