@parcha/agentrun-serve 0.1.0-beta.58 → 0.1.0-beta.59
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.
- package/CHANGELOG.md +325 -1
- package/README.md +332 -88
- package/dist/acp-package.d.ts +5 -1
- package/dist/acp-package.js +19 -2
- package/dist/adapters.d.ts +23 -2
- package/dist/adapters.js +106 -33
- package/dist/agents-store.js +1 -1
- package/dist/answer-text.d.ts +3 -0
- package/dist/answer-text.js +22 -0
- package/dist/attach-conformance.js +5 -4
- package/dist/box-paths.d.ts +3 -2
- package/dist/box-paths.js +5 -4
- package/dist/browser-computer.d.ts +3 -8
- package/dist/browser-computer.js +12 -35
- package/dist/browser-cost.js +94 -20
- package/dist/capacity.d.ts +1 -1
- package/dist/capacity.js +3 -3
- package/dist/chatgpt-plan.d.ts +5 -0
- package/dist/chatgpt-plan.js +25 -11
- package/dist/claude-login-token.d.ts +15 -11
- package/dist/claude-login-token.js +167 -107
- package/dist/claude-login.d.ts +76 -31
- package/dist/claude-login.js +426 -79
- package/dist/claude-sign-in.d.ts +3 -0
- package/dist/claude-sign-in.js +10 -1
- package/dist/cli.js +323 -292
- package/dist/composio-made.d.ts +1 -6
- package/dist/composio-made.js +1 -6
- package/dist/composio-owners.d.ts +26 -0
- package/dist/composio-owners.js +36 -0
- package/dist/composio-preset.d.ts +56 -23
- package/dist/composio-preset.js +173 -77
- package/dist/composio-triggers.d.ts +4 -4
- package/dist/composio-triggers.js +6 -7
- package/dist/compute-cost.js +11 -2
- package/dist/computer-attach.d.ts +6 -3
- package/dist/computer-attach.js +41 -29
- package/dist/computer-held-routes.d.ts +1 -1
- package/dist/computer-held-routes.js +9 -4
- package/dist/computer-keys.d.ts +11 -1
- package/dist/computer-keys.js +26 -1
- package/dist/computer-record.js +3 -1
- package/dist/computer-view.d.ts +5 -3
- package/dist/computer-view.js +10 -6
- package/dist/computer-viewer.js +36 -7
- package/dist/computers.d.ts +2 -1
- package/dist/computers.js +6 -3
- package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
- package/dist/console/assets/backend-BztxEAvb.js +166 -0
- package/dist/console/assets/index-LwNL4L9q.js +619 -0
- package/dist/console/assets/share-L84tlUDW.js +6 -0
- package/dist/console/assets/styles-CaRKlHke.js +291 -0
- package/dist/console/assets/styles-DQo8rzY-.css +1 -0
- package/dist/console/index.html +4 -3
- package/dist/console/share.html +17 -0
- package/dist/decisions.d.ts +17 -7
- package/dist/decisions.js +41 -15
- package/dist/dial-relay.js +10 -4
- package/dist/docker-daemon.js +4 -5
- package/dist/docker-host-addresses.js +29 -11
- package/dist/email/account.d.ts +6 -0
- package/dist/email/account.js +6 -0
- package/dist/email/authentication.d.ts +21 -0
- package/dist/email/authentication.js +106 -0
- package/dist/email/email-faux.d.ts +11 -2
- package/dist/email/email-faux.js +21 -5
- package/dist/email/mail.d.ts +25 -0
- package/dist/email/mail.js +58 -2
- package/dist/email/names.js +2 -2
- package/dist/email/tools.d.ts +9 -4
- package/dist/email/tools.js +95 -13
- package/dist/env-switch.d.ts +12 -2
- package/dist/env-switch.js +23 -3
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +2 -0
- package/dist/fal-price.d.ts +11 -1
- package/dist/fal-price.js +33 -0
- package/dist/faux-computers.js +1 -1
- package/dist/filed-answer.d.ts +2 -2
- package/dist/filed-answer.js +2 -2
- package/dist/graph-served.d.ts +10 -5
- package/dist/graph-served.js +40 -10
- package/dist/handed-values.js +1 -2
- package/dist/harness-check.d.ts +2 -1
- package/dist/harness-check.js +45 -12
- package/dist/harness-keys.js +9 -6
- package/dist/harness-opencode/facts.js +2 -0
- package/dist/harness-recipe-entry.d.ts +9 -3
- package/dist/harness-recipe-entry.js +18 -9
- package/dist/harness-recipe.d.ts +21 -0
- package/dist/harness-recipe.js +25 -3
- package/dist/harness-table.d.ts +8 -0
- package/dist/harness-table.js +17 -6
- package/dist/helper-env.d.ts +4 -1
- package/dist/helper-env.js +4 -1
- package/dist/host-check.d.ts +2 -3
- package/dist/host-check.js +13 -7
- package/dist/hosted-search.js +1 -1
- package/dist/import.d.ts +11 -8
- package/dist/import.js +437 -186
- package/dist/key-refusal.d.ts +9 -2
- package/dist/key-refusal.js +86 -32
- package/dist/learn/audit.d.ts +8 -5
- package/dist/learn/audit.js +15 -7
- package/dist/learn/compile.d.ts +5 -2
- package/dist/learn/compile.js +45 -21
- package/dist/learn/field-check.d.ts +111 -0
- package/dist/learn/field-check.js +174 -0
- package/dist/learn/ledger.d.ts +32 -29
- package/dist/learn/ledger.js +26 -19
- package/dist/learn/promote.d.ts +79 -36
- package/dist/learn/promote.js +60 -65
- package/dist/learn/secrets.d.ts +4 -0
- package/dist/learn/secrets.js +12 -0
- package/dist/learned-nodes.d.ts +8 -5
- package/dist/learned-nodes.js +8 -5
- package/dist/learned-workflow.d.ts +2 -1
- package/dist/learned-workflow.js +13 -10
- package/dist/learning-cost.d.ts +25 -8
- package/dist/learning-cost.js +23 -8
- package/dist/learning-setting.d.ts +6 -0
- package/dist/learning-setting.js +11 -1
- package/dist/listen-first.d.ts +5 -4
- package/dist/listen-first.js +4 -5
- package/dist/live-reach.d.ts +7 -0
- package/dist/live-reach.js +7 -0
- package/dist/mcp-api-only-origins.d.ts +15 -0
- package/dist/mcp-api-only-origins.js +40 -0
- package/dist/mcp-gateway.d.ts +16 -2
- package/dist/mcp-gateway.js +41 -3
- package/dist/mcp-oauth.d.ts +1 -1
- package/dist/mcp-oauth.js +3 -2
- package/dist/mcp-probe.d.ts +3 -0
- package/dist/mcp-probe.js +3 -0
- package/dist/mcp-secret-writes.d.ts +24 -2
- package/dist/mcp-secret-writes.js +30 -2
- package/dist/mcp-servers-store.d.ts +52 -14
- package/dist/mcp-servers-store.js +165 -61
- package/dist/mcp-sources.d.ts +1 -2
- package/dist/mcp-sources.js +1 -2
- package/dist/mcp-store.d.ts +5 -5
- package/dist/mcp-store.js +3 -3
- package/dist/mcp.js +1 -1
- package/dist/model-gateway.d.ts +1 -1
- package/dist/model-gateway.js +20 -36
- package/dist/ollama-provider.d.ts +23 -9
- package/dist/ollama-provider.js +49 -20
- package/dist/openapi.js +202 -51
- package/dist/otel/genai.d.ts +83 -7
- package/dist/otel/genai.js +69 -9
- package/dist/otel/tracer.d.ts +42 -13
- package/dist/otel/tracer.js +241 -56
- package/dist/page.d.ts +7 -1
- package/dist/page.js +76 -22
- package/dist/paid-calls.d.ts +6 -4
- package/dist/paid-calls.js +15 -7
- package/dist/place-offers.d.ts +55 -34
- package/dist/place-offers.js +93 -54
- package/dist/place.d.ts +13 -14
- package/dist/place.js +56 -41
- package/dist/print.js +1 -1
- package/dist/provider.d.ts +3 -2
- package/dist/provider.js +17 -8
- package/dist/redact/match.d.ts +27 -9
- package/dist/redact/match.js +266 -57
- package/dist/run-census.d.ts +1 -1
- package/dist/run-census.js +4 -5
- package/dist/run-cut.js +4 -5
- package/dist/run-export-store.d.ts +15 -0
- package/dist/run-export-store.js +30 -0
- package/dist/run-export.d.ts +139 -0
- package/dist/run-export.js +379 -0
- package/dist/run-file-cut.d.ts +5 -0
- package/dist/run-file-cut.js +13 -0
- package/dist/run-launch.js +16 -3
- package/dist/run-model-key.d.ts +15 -6
- package/dist/run-model-key.js +30 -31
- package/dist/run-reads-over-store.js +4 -4
- package/dist/run-secrets.js +3 -5
- package/dist/run-timeline-served.js +3 -1
- package/dist/runnable.js +2 -2
- package/dist/runner/adapter-loop.d.ts +35 -18
- package/dist/runner/adapter-loop.js +94 -47
- package/dist/runner/adapter-run-spec.d.ts +14 -1
- package/dist/runner/adapter-run-spec.js +64 -28
- package/dist/runner/adapters/pi.js +4 -2
- package/dist/runner/audit.d.ts +8 -5
- package/dist/runner/audit.js +37 -17
- package/dist/runner/beside.js +5 -6
- package/dist/runner/claim-secrets.d.ts +10 -3
- package/dist/runner/claim-secrets.js +29 -13
- package/dist/runner/cli-run-spec.d.ts +18 -0
- package/dist/runner/cli-run-spec.js +81 -46
- package/dist/runner/compare-end.d.ts +2 -1
- package/dist/runner/compare-end.js +25 -10
- package/dist/runner/conformance/harness.js +2 -3
- package/dist/runner/conformance/subject.d.ts +4 -1
- package/dist/runner/harness-loops.js +3 -3
- package/dist/runner/held.d.ts +5 -2
- package/dist/runner/journal-kinds.d.ts +4 -1
- package/dist/runner/journal-kinds.js +22 -4
- package/dist/runner/learned-first.js +20 -4
- package/dist/runner/learning-end.d.ts +2 -8
- package/dist/runner/learning-end.js +11 -19
- package/dist/runner/live-ticker.js +7 -5
- package/dist/runner/loop-contract.d.ts +0 -2
- package/dist/runner/loop.d.ts +7 -0
- package/dist/runner/loop.js +1 -0
- package/dist/runner/main.js +12 -11
- package/dist/runner/mcp-claim.js +21 -5
- package/dist/runner/meta-tools.js +3 -2
- package/dist/runner/metrics.d.ts +7 -0
- package/dist/runner/metrics.js +19 -0
- package/dist/runner/model-route.d.ts +10 -7
- package/dist/runner/model-route.js +79 -15
- package/dist/runner/native-loop.js +10 -8
- package/dist/runner/presence.d.ts +1 -4
- package/dist/runner/presence.js +6 -8
- package/dist/runner/promotion.d.ts +25 -13
- package/dist/runner/promotion.js +125 -50
- package/dist/runner/redact.d.ts +3 -1
- package/dist/runner/redact.js +5 -3
- package/dist/runner/responses-fetch.d.ts +36 -0
- package/dist/runner/responses-fetch.js +511 -0
- package/dist/runner/run-child-host.d.ts +20 -5
- package/dist/runner/run-child-host.js +179 -77
- package/dist/runner/run-child.js +11 -4
- package/dist/runner/runner-check.js +5 -1
- package/dist/runner/runner.d.ts +2 -3
- package/dist/runner/runner.js +13 -9
- package/dist/runner/sdk-loop.js +8 -8
- package/dist/runner/spec-holds.d.ts +8 -1
- package/dist/runner/spec-holds.js +9 -4
- package/dist/runner/workflow-calls.d.ts +9 -0
- package/dist/runner/workflow-calls.js +150 -0
- package/dist/runner/workflow-first.d.ts +120 -32
- package/dist/runner/workflow-first.js +218 -94
- package/dist/runner/workflow-spec.js +1 -1
- package/dist/runs-over-store.js +8 -7
- package/dist/save-once.d.ts +14 -0
- package/dist/save-once.js +31 -0
- package/dist/scrub-command.d.ts +34 -31
- package/dist/scrub-command.js +116 -147
- package/dist/sdk/runs.d.ts +6 -0
- package/dist/sdk/runs.js +89 -10
- package/dist/seal-key.js +4 -4
- package/dist/secret-cut.d.ts +3 -0
- package/dist/secret-cut.js +7 -1
- package/dist/secret-rules.d.ts +8 -1
- package/dist/secret-rules.js +482 -53
- package/dist/secrets.d.ts +51 -9
- package/dist/secrets.js +311 -21
- package/dist/server-keys.d.ts +4 -3
- package/dist/server-keys.js +4 -3
- package/dist/server-secrets-store.js +2 -4
- package/dist/server.d.ts +15 -3
- package/dist/server.js +312 -80
- package/dist/share-context.d.ts +22 -0
- package/dist/share-context.js +76 -0
- package/dist/shell-lex.d.ts +105 -0
- package/dist/shell-lex.js +646 -0
- package/dist/sign-ins-store.d.ts +5 -7
- package/dist/sign-ins-store.js +12 -16
- package/dist/sign-ins.d.ts +7 -11
- package/dist/sign-ins.js +40 -41
- package/dist/skills/agentrun-serve/SKILL.md +5 -2
- package/dist/start-switches.d.ts +6 -5
- package/dist/start-switches.js +8 -4
- package/dist/stats.d.ts +5 -1
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.js +2 -2
- package/dist/store/dialect.d.ts +4 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/mcp-record-keys.d.ts +10 -0
- package/dist/store/mcp-record-keys.js +13 -0
- package/dist/store/postgres/dialect.js +2 -0
- package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
- package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
- package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
- package/dist/store/postgres/store.js +4 -0
- package/dist/store/schema.d.ts +33 -10
- package/dist/store/schema.js +70 -16
- package/dist/store/seal.d.ts +4 -1
- package/dist/store/sqlite/run-launch.d.ts +3 -10
- package/dist/store/sqlite/run-launch.js +12 -23
- package/dist/store/sqlite/run-patch.d.ts +17 -10
- package/dist/store/sqlite/run-patch.js +50 -13
- package/dist/store/sqlite/store.d.ts +3 -0
- package/dist/store/sqlite/store.js +116 -34
- package/dist/store/store-schema.js +3 -4
- package/dist/store/store.d.ts +67 -32
- package/dist/store/store.js +14 -11
- package/dist/store-reads/analytics.d.ts +2 -1
- package/dist/store-reads/analytics.js +7 -5
- package/dist/store-reads/learning.d.ts +35 -26
- package/dist/store-reads/learning.js +120 -92
- package/dist/store-reads/stats.d.ts +2 -2
- package/dist/store-reads/stats.js +13 -7
- package/dist/store-view.js +10 -7
- package/dist/suggestions.d.ts +1 -1
- package/dist/suggestions.js +29 -13
- package/dist/template-eval.d.ts +72 -9
- package/dist/template-eval.js +358 -64
- package/dist/timeline/labels.d.ts +1 -1
- package/dist/timeline/labels.js +4 -3
- package/dist/timeline/timeline.d.ts +23 -11
- package/dist/timeline/timeline.js +115 -31
- package/dist/timeline/web-calls.d.ts +8 -6
- package/dist/timeline/web-calls.js +10 -6
- package/dist/tool-gate.d.ts +13 -1
- package/dist/tool-gate.js +43 -3
- package/dist/tool-keys-store.js +2 -4
- package/dist/tool-keys.d.ts +11 -0
- package/dist/tool-keys.js +16 -0
- package/dist/tool-plane.d.ts +50 -11
- package/dist/tool-plane.js +94 -30
- package/dist/tools.d.ts +5 -1
- package/dist/tools.js +7 -7
- package/dist/trigger-email.js +12 -6
- package/dist/triggers.d.ts +15 -34
- package/dist/triggers.js +119 -126
- package/dist/validate.d.ts +8 -1
- package/dist/validate.js +163 -23
- package/dist/web-fake.d.ts +2 -1
- package/dist/web-fake.js +8 -6
- package/dist/web-fetch.d.ts +8 -6
- package/dist/web-fetch.js +13 -11
- package/dist/web-holds.d.ts +32 -0
- package/dist/web-holds.js +86 -0
- package/dist/web-run.d.ts +32 -5
- package/dist/web-run.js +75 -28
- package/dist/web-save.js +23 -12
- package/dist/web-search.js +14 -25
- package/dist/wires.d.ts +4 -3
- package/dist/wires.js +5 -4
- package/dist/workspace/archil-claim.d.ts +12 -5
- package/dist/workspace/archil-claim.js +45 -5
- package/dist/workspace/attach.js +52 -19
- package/dist/workspace/attached-computers.d.ts +6 -2
- package/dist/workspace/attached-computers.js +5 -4
- package/dist/workspace/computer-deps.d.ts +23 -6
- package/dist/workspace/computer-deps.js +35 -17
- package/dist/workspace/computer-for-claim.d.ts +21 -4
- package/dist/workspace/computer-for-claim.js +160 -54
- package/dist/workspace/computer-intervals.d.ts +2 -0
- package/dist/workspace/computer-intervals.js +1 -1
- package/dist/workspace/computer-janitor.d.ts +48 -14
- package/dist/workspace/computer-janitor.js +153 -44
- package/dist/workspace/computer-kept.d.ts +158 -32
- package/dist/workspace/computer-kept.js +288 -63
- package/dist/workspace/computer-providers.d.ts +8 -3
- package/dist/workspace/computer-providers.js +12 -5
- package/dist/workspace/index.d.ts +1 -1
- package/dist/workspace/index.js +1 -1
- package/dist/workspace/local.js +41 -1
- package/dist/workspace/mount-revoke-left.d.ts +31 -0
- package/dist/workspace/mount-revoke-left.js +72 -0
- package/dist/workspace/paired-route.js +4 -5
- package/dist/workspace/resolve-computer.d.ts +5 -2
- package/dist/workspace/resolve-computer.js +9 -3
- package/dist/workspace/run-end-computers.d.ts +11 -5
- package/dist/workspace/run-end-computers.js +153 -28
- package/dist/workspace/run-tools.d.ts +22 -3
- package/dist/workspace/run-tools.js +17 -5
- package/dist/workspace/run-workspace.d.ts +14 -1
- package/dist/workspace/run-workspace.js +34 -1
- package/dist/workspace/workspace.d.ts +6 -0
- package/package.json +12 -13
- package/skills/agentrun-serve/SKILL.md +5 -2
- package/templates/README.md +22 -6
- package/dist/console/assets/backend-CSAWUqtZ.js +0 -166
- package/dist/console/assets/index-Bwn1oTem.css +0 -1
- package/dist/console/assets/index-DPh29cyz.js +0 -747
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
// OpenAI's Responses API over the route's own Messages translation (model-route.ts messagesFetch), for a model that
|
|
2
|
+
// speaks neither wire (an Ollama model: TRANSLATED), so a harness on the openai-responses wire (codex, opencode, any
|
|
3
|
+
// other) runs it as pi and claude-agent do, on the one translation: the same pi-ai model (num_ctx, tools as text), the
|
|
4
|
+
// same redaction of errors and reasoning, the same text-tools re-asks and the same booking of a failed answer.
|
|
5
|
+
// Request: a stateless Responses body becomes one Messages body. `instructions` and the system or developer messages
|
|
6
|
+
// before the first turn are the system prompt; one later is a user turn's text. A `function_call` is a tool_use
|
|
7
|
+
// under its own call_id and its `function_call_output` the tool_result of that id; reasoning items are dropped (the
|
|
8
|
+
// Messages translation drops replayed thinking too). Function tools alone: a `custom` (freeform) tool, an
|
|
9
|
+
// `item_reference`, a file or an image by URL is refused with a 400 naming it, never dropped in silence. So is a
|
|
10
|
+
// `tool_choice` that forces a call ("required", or one naming a function): Ollama cannot be made to call a tool, and
|
|
11
|
+
// a forced call run as "auto" would be a promise the route breaks. "auto" is taken, and "none" sends no tool.
|
|
12
|
+
// `text.format` json_schema is Ollama's `format` (the answer held to the schema), json_object an object schema;
|
|
13
|
+
// beside tools sent it is refused, since the model could call none. temperature and top_p reach Ollama's options;
|
|
14
|
+
// `reasoning.effort` is a thinking model's level (Ollama's think), and "none" asks it not to think. An effort or a
|
|
15
|
+
// format this route does not know is refused. parallel_tool_calls false keeps an answer's first call alone, since
|
|
16
|
+
// Ollama's chat has no switch for one call per answer, and warns the names of those it drops. What this asks Ollama
|
|
17
|
+
// past the Messages body rides the in-process call (EdgeAsks), never the body: the Messages wire stays as it is.
|
|
18
|
+
// Answer: the Messages stream becomes a Responses stream: response.created, an output item for each block (message,
|
|
19
|
+
// reasoning, function_call) with its deltas and its done events, then response.completed, or response.incomplete
|
|
20
|
+
// with `incomplete_details.reason: "max_output_tokens"` where the model stopped at its output limit, both carrying
|
|
21
|
+
// the usage (OpenAI's shape: cached tokens inside input_tokens). A failure is response.failed, with the usage the
|
|
22
|
+
// translation reported before it, so the proxy books the tokens a failed answer used. A part of the Messages stream
|
|
23
|
+
// that does not read, or a stream that breaks, is a failure in words of its own (UNREAD), never that part's text.
|
|
24
|
+
// State: none is kept. A request is its whole conversation: one that asks `store: true` or names `previous_response_id`
|
|
25
|
+
// is refused, since nothing is stored here to continue from. `include` is read for nothing: this writes no encrypted
|
|
26
|
+
// reasoning, and a replayed reasoning item (OpenAI's encrypted one included) is dropped, never refused.
|
|
27
|
+
// A request streams only with `stream: true`, as OpenAI's API does; one with `stream: false` or none gets the final
|
|
28
|
+
// response as one JSON body.
|
|
29
|
+
// The answer runs through messagesFetch whole (a Responses body made a Messages one, its Messages stream made a Responses
|
|
30
|
+
// one), so the Messages translation stays as it is. Split into a parser per wire, one driver and an encoder per wire if a
|
|
31
|
+
// third wire arrives.
|
|
32
|
+
import { randomBytes } from "node:crypto";
|
|
33
|
+
/** A request this translation does not take: answered 400 with `message`, in OpenAI's error shape. */
|
|
34
|
+
export class ResponsesRefusal extends Error {
|
|
35
|
+
}
|
|
36
|
+
const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
37
|
+
const idOf = (prefix) => `${prefix}_${randomBytes(12).toString("hex")}`;
|
|
38
|
+
/** pi's thinking levels a Responses `reasoning.effort` may name and the Messages translation asks by name. */
|
|
39
|
+
const EFFORTS = new Set(["minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
40
|
+
/** A Responses message's content as Messages blocks: text, and an image only as base64 (a data URL). */
|
|
41
|
+
function partsOf(content, role) {
|
|
42
|
+
if (typeof content === "string")
|
|
43
|
+
return content ? [{ type: "text", text: content }] : [];
|
|
44
|
+
if (!Array.isArray(content))
|
|
45
|
+
return [];
|
|
46
|
+
return content.flatMap((part) => {
|
|
47
|
+
if (!isPlain(part))
|
|
48
|
+
return [];
|
|
49
|
+
if (part.type === "input_text" || part.type === "output_text")
|
|
50
|
+
return [{ type: "text", text: String(part.text ?? "") }];
|
|
51
|
+
if (part.type === "refusal")
|
|
52
|
+
return [{ type: "text", text: String(part.refusal ?? "") }];
|
|
53
|
+
if (part.type === "input_image") {
|
|
54
|
+
const url = typeof part.image_url === "string" ? part.image_url : "";
|
|
55
|
+
const data = /^data:([^;,]+);base64,(.*)$/s.exec(url);
|
|
56
|
+
if (!data)
|
|
57
|
+
throw new ResponsesRefusal(`an image by URL or file id in a ${role} message is not taken on this model's route: send it as a data URL`);
|
|
58
|
+
return [{ type: "image", source: { type: "base64", media_type: data[1], data: data[2] } }];
|
|
59
|
+
}
|
|
60
|
+
throw new ResponsesRefusal(`a ${String(part.type)} part in a ${role} message is not taken on this model's route`);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** A function_call_output's output as a tool_result's content: its text, or its text and image parts. */
|
|
64
|
+
function outputOf(output) {
|
|
65
|
+
if (typeof output === "string")
|
|
66
|
+
return output;
|
|
67
|
+
if (Array.isArray(output))
|
|
68
|
+
return partsOf(output, "tool output");
|
|
69
|
+
return output === undefined || output === null ? "" : JSON.stringify(output);
|
|
70
|
+
}
|
|
71
|
+
/** The tool call's arguments as the object a tool_use carries: its JSON, or none where it is not an object's. */
|
|
72
|
+
function argumentsOf(text) {
|
|
73
|
+
if (isPlain(text))
|
|
74
|
+
return text;
|
|
75
|
+
try {
|
|
76
|
+
const parsed = JSON.parse(String(text ?? "{}"));
|
|
77
|
+
return isPlain(parsed) ? parsed : {};
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return {};
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** Throws a ResponsesRefusal for a `tool_choice` other than "auto" or "none" (or none at all): the model behind the route
|
|
84
|
+
* (Ollama's chat) takes no tool choice, so a call forced by "required" or by a function's name, or tools narrowed by
|
|
85
|
+
* "allowed_tools", cannot be kept. */
|
|
86
|
+
function refuseForcedChoice(choice) {
|
|
87
|
+
if (choice === undefined || choice === null || choice === "auto" || choice === "none")
|
|
88
|
+
return;
|
|
89
|
+
const unkept = "is not taken on this model's route: the model here cannot be made to call a tool, so send \"auto\"";
|
|
90
|
+
if (choice === "required")
|
|
91
|
+
throw new ResponsesRefusal(`tool_choice "required" ${unkept}`);
|
|
92
|
+
if (isPlain(choice) && choice.type === "function")
|
|
93
|
+
throw new ResponsesRefusal(`tool_choice naming the function ${String(choice.name ?? "(none)")} ${unkept}`);
|
|
94
|
+
throw new ResponsesRefusal(`tool_choice ${JSON.stringify(isPlain(choice) ? (choice.type ?? "(no type)") : choice)} is not taken on this model's route: "auto" and "none" only`);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* A Responses request as one Messages request (see the head of this file). `reasons`: whether the model reasons, so a
|
|
98
|
+
* `reasoning.effort` reaches it as the Messages translation's named level; a model that does not is asked none.
|
|
99
|
+
* Returns the Messages body and what it asks Ollama past it (EdgeAsks). Throws a ResponsesRefusal for what it does not take.
|
|
100
|
+
*/
|
|
101
|
+
export function messagesOfResponses(body, reasons) {
|
|
102
|
+
if (body.store === true)
|
|
103
|
+
throw new ResponsesRefusal("store: true is not taken on this model's route: nothing is stored here, so send store: false and the whole conversation");
|
|
104
|
+
if (body.previous_response_id !== undefined && body.previous_response_id !== null)
|
|
105
|
+
throw new ResponsesRefusal("previous_response_id is not taken on this model's route: no response is stored here, so send the whole conversation");
|
|
106
|
+
refuseForcedChoice(body.tool_choice);
|
|
107
|
+
const system = [];
|
|
108
|
+
if (typeof body.instructions === "string" && body.instructions)
|
|
109
|
+
system.push(body.instructions);
|
|
110
|
+
const messages = [];
|
|
111
|
+
const push = (role, blocks) => {
|
|
112
|
+
if (!blocks.length)
|
|
113
|
+
return;
|
|
114
|
+
const last = messages.at(-1);
|
|
115
|
+
// One Messages turn per run of items of one role: an answer's text and its calls are one assistant turn, and the
|
|
116
|
+
// outputs of its calls one user turn, as a Messages client sends them.
|
|
117
|
+
if (last?.role === role)
|
|
118
|
+
last.content.push(...blocks);
|
|
119
|
+
else
|
|
120
|
+
messages.push({ role, content: blocks });
|
|
121
|
+
};
|
|
122
|
+
const input = typeof body.input === "string" ? [{ type: "message", role: "user", content: body.input }] : Array.isArray(body.input) ? body.input : [];
|
|
123
|
+
for (const item of input) {
|
|
124
|
+
if (!isPlain(item))
|
|
125
|
+
throw new ResponsesRefusal("an input item that is not an object is not taken on this model's route");
|
|
126
|
+
const type = item.type ?? (item.role !== undefined ? "message" : undefined);
|
|
127
|
+
if (type === "message") {
|
|
128
|
+
const role = String(item.role ?? "");
|
|
129
|
+
if (role === "system" || role === "developer") {
|
|
130
|
+
const text = partsOf(item.content, role).filter((part) => part.type === "text").map((part) => String(part.text)).join("\n");
|
|
131
|
+
// Before the first turn, the system prompt; after it, the turn's own text, so the prompt the model has already
|
|
132
|
+
// read stays the same from request to request.
|
|
133
|
+
if (!messages.length) {
|
|
134
|
+
if (text)
|
|
135
|
+
system.push(text);
|
|
136
|
+
}
|
|
137
|
+
else if (text)
|
|
138
|
+
push("user", [{ type: "text", text }]);
|
|
139
|
+
}
|
|
140
|
+
else if (role === "user")
|
|
141
|
+
push("user", partsOf(item.content, role));
|
|
142
|
+
else if (role === "assistant")
|
|
143
|
+
push("assistant", partsOf(item.content, role));
|
|
144
|
+
else
|
|
145
|
+
throw new ResponsesRefusal(`a message of role ${role || "(none)"} is not taken on this model's route`);
|
|
146
|
+
}
|
|
147
|
+
else if (type === "function_call") {
|
|
148
|
+
push("assistant", [{ type: "tool_use", id: String(item.call_id ?? ""), name: String(item.name ?? ""), input: argumentsOf(item.arguments) }]);
|
|
149
|
+
}
|
|
150
|
+
else if (type === "function_call_output") {
|
|
151
|
+
push("user", [{ type: "tool_result", tool_use_id: String(item.call_id ?? ""), content: outputOf(item.output) }]);
|
|
152
|
+
}
|
|
153
|
+
else if (type === "reasoning") {
|
|
154
|
+
// Replayed reasoning is not sent back to the model, as the Messages translation drops a replayed thinking block:
|
|
155
|
+
// OpenAI's encrypted reasoning (encrypted_content) is no text a local model could read, and this route's own carries
|
|
156
|
+
// only a summary of what the model already acted on. Dropped, never refused, so a replayed turn goes on.
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
throw new ResponsesRefusal(`a ${String(type)} input item is not taken on this model's route${type === "item_reference" ? ": send the whole conversation (store is off)" : ""}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const tools = Array.isArray(body.tools) ? body.tools : [];
|
|
163
|
+
const functions = tools.map((tool) => {
|
|
164
|
+
if (!isPlain(tool) || tool.type !== "function")
|
|
165
|
+
throw new ResponsesRefusal(`a ${isPlain(tool) ? String(tool.type) : "malformed"} tool is not taken on this model's route: function tools only${isPlain(tool) && tool.type === "custom" ? " (a custom, freeform tool has no function schema to give the model)" : ""}`);
|
|
166
|
+
return { name: String(tool.name ?? ""), description: typeof tool.description === "string" ? tool.description : "", input_schema: isPlain(tool.parameters) ? tool.parameters : { type: "object", properties: {} } };
|
|
167
|
+
});
|
|
168
|
+
const sendsTools = functions.length > 0 && body.tool_choice !== "none";
|
|
169
|
+
const schema = schemaOf(body.text, sendsTools);
|
|
170
|
+
// Ollama holds the answer to the schema (its `format`); the schema is in the prompt too, as Ollama advises, so the
|
|
171
|
+
// model writes what the schema means and not only its shape.
|
|
172
|
+
if (schema)
|
|
173
|
+
system.push(`Answer with one JSON value only, no other text, matching this JSON schema:\n${JSON.stringify(schema)}`);
|
|
174
|
+
const effort = isPlain(body.reasoning) ? body.reasoning.effort : undefined;
|
|
175
|
+
if (effort !== undefined && effort !== null && !(typeof effort === "string" && (EFFORTS.has(effort) || effort === "none")))
|
|
176
|
+
throw new ResponsesRefusal(`reasoning.effort ${JSON.stringify(effort)} is not taken on this model's route: "none", ${[...EFFORTS].map((each) => `"${each}"`).join(", ")} only`);
|
|
177
|
+
const level = reasons && typeof effort === "string" && EFFORTS.has(effort) ? effort : undefined;
|
|
178
|
+
// "none" on a model that reasons: Ollama is asked not to think (think: false), where its own default would have the
|
|
179
|
+
// model think.
|
|
180
|
+
const off = reasons && effort === "none";
|
|
181
|
+
const request = {
|
|
182
|
+
model: typeof body.model === "string" ? body.model : "route",
|
|
183
|
+
stream: true,
|
|
184
|
+
...(typeof body.max_output_tokens === "number" ? { max_tokens: body.max_output_tokens } : {}),
|
|
185
|
+
...(system.length ? { system: system.join("\n\n") } : {}),
|
|
186
|
+
messages,
|
|
187
|
+
...(sendsTools ? { tools: functions } : {}),
|
|
188
|
+
...(level ? { thinking: { type: "adaptive" }, output_config: { effort: level } } : {}),
|
|
189
|
+
};
|
|
190
|
+
const asks = { ...(schema ? { format: schema } : {}), ...numberOf(body, "temperature"), ...numberOf(body, "top_p"), ...(off ? { think: false } : {}) };
|
|
191
|
+
return { request, asks };
|
|
192
|
+
}
|
|
193
|
+
/** `field` of `body` (temperature, top_p) as this edge asks it of Ollama (EdgeAsks): a number as it is, null or absent as
|
|
194
|
+
* none (the model's own default). Anything else is refused, never dropped. */
|
|
195
|
+
function numberOf(body, field) {
|
|
196
|
+
const value = body[field];
|
|
197
|
+
if (value === undefined || value === null)
|
|
198
|
+
return {};
|
|
199
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
200
|
+
throw new ResponsesRefusal(`${field} ${JSON.stringify(value)} is not taken on this model's route: a number, or null for the model's default`);
|
|
201
|
+
return field === "temperature" ? { temperature: value } : { top_p: value };
|
|
202
|
+
}
|
|
203
|
+
/** The JSON schema `text.format` holds the answer to: json_schema's own, json_object's any object; none for a text format
|
|
204
|
+
* or none. Ollama holds the whole answer to it (constrained decoding), which leaves the model no way to call a tool, so a
|
|
205
|
+
* format beside tools sent is refused, as is one of another type: never asked in words alone. */
|
|
206
|
+
function schemaOf(text, sendsTools) {
|
|
207
|
+
const format = isPlain(text) ? text.format : undefined;
|
|
208
|
+
if (format === undefined || format === null || (isPlain(format) && format.type === "text"))
|
|
209
|
+
return undefined;
|
|
210
|
+
const type = isPlain(format) ? format.type : undefined;
|
|
211
|
+
if (type !== "json_schema" && type !== "json_object")
|
|
212
|
+
throw new ResponsesRefusal(`text.format ${JSON.stringify(type ?? format)} is not taken on this model's route: "text", "json_schema" and "json_object" only`);
|
|
213
|
+
const schema = type === "json_object" ? { type: "object" } : format.schema;
|
|
214
|
+
if (!isPlain(schema))
|
|
215
|
+
throw new ResponsesRefusal("text.format json_schema with no schema object is not taken on this model's route");
|
|
216
|
+
if (sendsTools)
|
|
217
|
+
throw new ResponsesRefusal(`text.format ${type} beside tools is not taken on this model's route: Ollama holds the whole answer to the format, which leaves the model no way to call a tool, so drop the output schema, or use a model route that takes tools with a format (or send tool_choice "none")`);
|
|
218
|
+
return schema;
|
|
219
|
+
}
|
|
220
|
+
/** What a failed response says of a Messages stream a part of which does not read: never that part's own text. */
|
|
221
|
+
const UNREAD = "The model's answer could not be read: a part of it is not JSON, or its stream broke.";
|
|
222
|
+
/** The events of a Messages SSE body, as they come. */
|
|
223
|
+
async function* messagesEvents(body) {
|
|
224
|
+
const decoder = new TextDecoder();
|
|
225
|
+
let held = "";
|
|
226
|
+
const eventOf = (block) => {
|
|
227
|
+
let name;
|
|
228
|
+
const data = [];
|
|
229
|
+
for (const line of block.split("\n")) {
|
|
230
|
+
if (line.startsWith("event:"))
|
|
231
|
+
name = line.slice(6).trim();
|
|
232
|
+
else if (line.startsWith("data:"))
|
|
233
|
+
data.push(line.slice(line.startsWith("data: ") ? 6 : 5));
|
|
234
|
+
}
|
|
235
|
+
if (!data.length)
|
|
236
|
+
return undefined;
|
|
237
|
+
const text = data.join("\n");
|
|
238
|
+
try {
|
|
239
|
+
const json = JSON.parse(text);
|
|
240
|
+
if (isPlain(json))
|
|
241
|
+
return { json, ...(name ? { name } : {}) };
|
|
242
|
+
}
|
|
243
|
+
catch { }
|
|
244
|
+
// An error event's words alone (messagesFetch sendWords); anything else that does not read is said as UNREAD.
|
|
245
|
+
return name === "error" ? { words: text, name } : { unread: true };
|
|
246
|
+
};
|
|
247
|
+
for await (const chunk of body) {
|
|
248
|
+
held += decoder.decode(chunk, { stream: true }).replace(/\r\n/g, "\n");
|
|
249
|
+
let end;
|
|
250
|
+
while ((end = held.indexOf("\n\n")) >= 0) {
|
|
251
|
+
const event = eventOf(held.slice(0, end));
|
|
252
|
+
held = held.slice(end + 2);
|
|
253
|
+
if (event)
|
|
254
|
+
yield event;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
held += decoder.decode();
|
|
258
|
+
const last = held.trim() ? eventOf(held) : undefined;
|
|
259
|
+
if (last)
|
|
260
|
+
yield last;
|
|
261
|
+
}
|
|
262
|
+
/** A Messages usage object as Responses states it: the cached and cache-write tokens inside input_tokens. */
|
|
263
|
+
function usageOf(usage) {
|
|
264
|
+
const count = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0);
|
|
265
|
+
const input = count(usage?.input_tokens);
|
|
266
|
+
const cacheRead = count(usage?.cache_read_input_tokens);
|
|
267
|
+
const cacheWrite = count(usage?.cache_creation_input_tokens);
|
|
268
|
+
const output = count(usage?.output_tokens);
|
|
269
|
+
const details = isPlain(usage?.output_tokens_details) ? usage.output_tokens_details : {};
|
|
270
|
+
const cost = usage?.cost;
|
|
271
|
+
return {
|
|
272
|
+
input_tokens: input + cacheRead + cacheWrite,
|
|
273
|
+
input_tokens_details: { cached_tokens: cacheRead, ...(cacheWrite ? { cache_write_tokens: cacheWrite } : {}) },
|
|
274
|
+
output_tokens: output,
|
|
275
|
+
output_tokens_details: { reasoning_tokens: count(details.thinking_tokens) },
|
|
276
|
+
total_tokens: input + cacheRead + cacheWrite + output,
|
|
277
|
+
...(typeof cost === "number" ? { cost } : {}),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* A fetch that answers OpenAI Responses requests through `messages` (a Messages fetch: the route's own translation,
|
|
282
|
+
* model-route.ts messagesFetch). `reasons`: whether the model reasons (messagesOfResponses). A request it does not take
|
|
283
|
+
* is answered 400 and never reaches `messages`. `warn`: where a line on what the edge did to an answer goes (the calls
|
|
284
|
+
* parallel_tool_calls false kept from the client, by count and tool name, never their arguments); stderr by default,
|
|
285
|
+
* which the run's own log keeps.
|
|
286
|
+
*/
|
|
287
|
+
export function responsesFetch(messages, { reasons = false, warn = (line) => console.warn(line) } = {}) {
|
|
288
|
+
return (async (url, init = {}) => {
|
|
289
|
+
let body;
|
|
290
|
+
let request;
|
|
291
|
+
let asks;
|
|
292
|
+
try {
|
|
293
|
+
const parsed = JSON.parse(String(init.body ?? "{}"));
|
|
294
|
+
if (!isPlain(parsed))
|
|
295
|
+
throw new ResponsesRefusal("the request body is not a JSON object");
|
|
296
|
+
body = parsed;
|
|
297
|
+
({ request, asks } = messagesOfResponses(body, reasons));
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
const message = error instanceof ResponsesRefusal ? error.message : "the request body is not JSON";
|
|
301
|
+
return new Response(JSON.stringify({ error: { message, type: "invalid_request_error", param: null, code: null } }), { status: 400, headers: { "content-type": "application/json" } });
|
|
302
|
+
}
|
|
303
|
+
const target = String(url).replace(/\/v1\/responses(?=$|\?)/, "/v1/messages");
|
|
304
|
+
const answer = await messages(target, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(request), edgeAsks: asks, ...(init.signal ? { signal: init.signal } : {}) });
|
|
305
|
+
if (!answer.ok || !answer.body) {
|
|
306
|
+
const text = await answer.text().catch(() => "");
|
|
307
|
+
return new Response(JSON.stringify({ error: { message: text || `the model's request failed (${answer.status})`, type: "server_error", param: null, code: null } }), { status: answer.status >= 400 ? answer.status : 500, headers: { "content-type": "application/json" } });
|
|
308
|
+
}
|
|
309
|
+
const response = {
|
|
310
|
+
id: idOf("resp"),
|
|
311
|
+
object: "response",
|
|
312
|
+
created_at: Math.floor(Date.now() / 1000),
|
|
313
|
+
status: "in_progress",
|
|
314
|
+
background: false,
|
|
315
|
+
error: null,
|
|
316
|
+
incomplete_details: null,
|
|
317
|
+
instructions: null,
|
|
318
|
+
model: typeof body.model === "string" ? body.model : "route",
|
|
319
|
+
output: [],
|
|
320
|
+
parallel_tool_calls: body.parallel_tool_calls !== false,
|
|
321
|
+
tool_choice: body.tool_choice ?? "auto",
|
|
322
|
+
tools: [],
|
|
323
|
+
store: false,
|
|
324
|
+
text: { format: { type: "text" } },
|
|
325
|
+
usage: null,
|
|
326
|
+
metadata: {},
|
|
327
|
+
};
|
|
328
|
+
const events = messagesEvents(answer.body);
|
|
329
|
+
// parallel_tool_calls false: the answer's first call alone; the names of those it loses, said once it ends.
|
|
330
|
+
const dropped = body.parallel_tool_calls === false ? [] : undefined;
|
|
331
|
+
const said = () => {
|
|
332
|
+
if (dropped?.length)
|
|
333
|
+
warn(`responses edge: parallel_tool_calls false kept the answer's first tool call and dropped ${dropped.length} more: ${dropped.join(", ")}`);
|
|
334
|
+
};
|
|
335
|
+
// OpenAI's own default: a body streams only when it asks to; one that names no stream is answered whole.
|
|
336
|
+
if (body.stream !== true) {
|
|
337
|
+
// The whole answer, then its final response as one body.
|
|
338
|
+
await translate(events, response, () => { }, dropped);
|
|
339
|
+
said();
|
|
340
|
+
if (response.status === "failed") {
|
|
341
|
+
// 500 for a failed answer, as the Messages side answers one asked whole (model-route.ts wholeOf: Anthropic's
|
|
342
|
+
// api_error is a 500, OpenAI's server_error too); a rate limit 429.
|
|
343
|
+
const error = response.error;
|
|
344
|
+
return new Response(JSON.stringify({ error: { message: error.message, type: error.code === "rate_limit_exceeded" ? "rate_limit_error" : "server_error", param: null, code: error.code } }), { status: error.code === "rate_limit_exceeded" ? 429 : 500, headers: { "content-type": "application/json" } });
|
|
345
|
+
}
|
|
346
|
+
return new Response(JSON.stringify(response), { status: 200, headers: { "content-type": "application/json" } });
|
|
347
|
+
}
|
|
348
|
+
const encoder = new TextEncoder();
|
|
349
|
+
let sequence = 0;
|
|
350
|
+
const stream = new ReadableStream({
|
|
351
|
+
async start(controller) {
|
|
352
|
+
const send = (event) => controller.enqueue(encoder.encode(`event: ${String(event.type)}\ndata: ${JSON.stringify({ ...event, sequence_number: sequence++ })}\n\n`));
|
|
353
|
+
try {
|
|
354
|
+
// translate never throws on the Messages stream (a part that does not read is its own failed end); what throws
|
|
355
|
+
// here is the client gone, whose stream takes nothing more.
|
|
356
|
+
await translate(events, response, send, dropped);
|
|
357
|
+
said();
|
|
358
|
+
controller.close();
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
// Its loop has already let go of the Messages stream (for await returns it), which ends the route's request.
|
|
362
|
+
}
|
|
363
|
+
},
|
|
364
|
+
});
|
|
365
|
+
return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } });
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
/** The response as an event carries it: its fields so far, the output items as they stand. */
|
|
369
|
+
const snapshot = (response) => ({ ...response, output: [...response.output] });
|
|
370
|
+
/**
|
|
371
|
+
* The Messages events as Responses events, each given to `send`, the response filled as they come: its output items,
|
|
372
|
+
* then its end (completed, incomplete at the output limit, or failed, each with the usage the Messages stream stated).
|
|
373
|
+
* `dropped` (given for the request's parallel_tool_calls false): the answer's first function_call alone, the name of each
|
|
374
|
+
* later one pushed onto it.
|
|
375
|
+
*/
|
|
376
|
+
async function translate(events, response, send, dropped) {
|
|
377
|
+
const output = response.output;
|
|
378
|
+
const open = new Map();
|
|
379
|
+
let usage;
|
|
380
|
+
let stop;
|
|
381
|
+
let ended = false;
|
|
382
|
+
const end = (status) => {
|
|
383
|
+
if (ended)
|
|
384
|
+
return;
|
|
385
|
+
ended = true;
|
|
386
|
+
response.status = status;
|
|
387
|
+
if (status === "incomplete")
|
|
388
|
+
response.incomplete_details = { reason: "max_output_tokens" };
|
|
389
|
+
response.usage = usageOf(usage);
|
|
390
|
+
send({ type: `response.${status}`, response: snapshot(response) });
|
|
391
|
+
};
|
|
392
|
+
const fail = (message, rateLimit) => {
|
|
393
|
+
if (ended)
|
|
394
|
+
return;
|
|
395
|
+
ended = true;
|
|
396
|
+
response.status = "failed";
|
|
397
|
+
response.error = { code: rateLimit ? "rate_limit_exceeded" : "server_error", message };
|
|
398
|
+
// The tokens the model used before it failed, as the Messages stream stated them: the proxy books them.
|
|
399
|
+
if (usage)
|
|
400
|
+
response.usage = usageOf(usage);
|
|
401
|
+
send({ type: "response.failed", response: snapshot(response) });
|
|
402
|
+
};
|
|
403
|
+
send({ type: "response.created", response: snapshot(response) });
|
|
404
|
+
send({ type: "response.in_progress", response: snapshot(response) });
|
|
405
|
+
try {
|
|
406
|
+
for await (const event of events) {
|
|
407
|
+
const json = event.json;
|
|
408
|
+
if (!json || event.words !== undefined) {
|
|
409
|
+
fail(event.unread ? UNREAD : (event.words ?? "the model's request failed"), false);
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
const type = json.type;
|
|
413
|
+
if (type === "content_block_start" && typeof json.index === "number" && isPlain(json.content_block)) {
|
|
414
|
+
const block = json.content_block;
|
|
415
|
+
const index = output.length;
|
|
416
|
+
if (block.type === "text") {
|
|
417
|
+
const item = { id: idOf("msg"), type: "message", status: "in_progress", role: "assistant", content: [] };
|
|
418
|
+
open.set(json.index, { index, item, text: "", kind: "message" });
|
|
419
|
+
output.push(item);
|
|
420
|
+
send({ type: "response.output_item.added", output_index: index, item: { ...item, content: [] } });
|
|
421
|
+
send({ type: "response.content_part.added", item_id: item.id, output_index: index, content_index: 0, part: { type: "output_text", text: "", annotations: [] } });
|
|
422
|
+
}
|
|
423
|
+
else if (block.type === "thinking") {
|
|
424
|
+
const item = { id: idOf("rs"), type: "reasoning", summary: [] };
|
|
425
|
+
open.set(json.index, { index, item, text: "", kind: "reasoning" });
|
|
426
|
+
output.push(item);
|
|
427
|
+
send({ type: "response.output_item.added", output_index: index, item: { ...item, summary: [] } });
|
|
428
|
+
send({ type: "response.reasoning_summary_part.added", item_id: item.id, output_index: index, summary_index: 0, part: { type: "summary_text", text: "" } });
|
|
429
|
+
}
|
|
430
|
+
else if (block.type === "tool_use" && dropped && output.some((item) => item.type === "function_call")) {
|
|
431
|
+
// parallel_tool_calls false: the answer's first call alone (a later one is never opened, so its deltas and its
|
|
432
|
+
// stop find nothing), since Ollama's chat has no switch for one call per answer. Its name is said, never dropped
|
|
433
|
+
// in silence.
|
|
434
|
+
dropped.push(String(block.name ?? "(no name)"));
|
|
435
|
+
}
|
|
436
|
+
else if (block.type === "tool_use") {
|
|
437
|
+
const item = { id: idOf("fc"), type: "function_call", status: "in_progress", call_id: String(block.id ?? ""), name: String(block.name ?? ""), arguments: "" };
|
|
438
|
+
open.set(json.index, { index, item, text: "", kind: "function_call" });
|
|
439
|
+
output.push(item);
|
|
440
|
+
send({ type: "response.output_item.added", output_index: index, item: { ...item } });
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
else if (type === "content_block_delta" && typeof json.index === "number" && isPlain(json.delta)) {
|
|
444
|
+
const at = open.get(json.index);
|
|
445
|
+
if (!at)
|
|
446
|
+
continue;
|
|
447
|
+
const delta = json.delta;
|
|
448
|
+
if (delta.type === "text_delta" && at.kind === "message") {
|
|
449
|
+
const text = String(delta.text ?? "");
|
|
450
|
+
at.text += text;
|
|
451
|
+
send({ type: "response.output_text.delta", item_id: at.item.id, output_index: at.index, content_index: 0, delta: text, logprobs: [] });
|
|
452
|
+
}
|
|
453
|
+
else if (delta.type === "thinking_delta" && at.kind === "reasoning") {
|
|
454
|
+
const text = String(delta.thinking ?? "");
|
|
455
|
+
at.text += text;
|
|
456
|
+
send({ type: "response.reasoning_summary_text.delta", item_id: at.item.id, output_index: at.index, summary_index: 0, delta: text });
|
|
457
|
+
}
|
|
458
|
+
else if (delta.type === "input_json_delta" && at.kind === "function_call") {
|
|
459
|
+
const text = String(delta.partial_json ?? "");
|
|
460
|
+
at.text += text;
|
|
461
|
+
send({ type: "response.function_call_arguments.delta", item_id: at.item.id, output_index: at.index, delta: text });
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
else if (type === "content_block_stop" && typeof json.index === "number") {
|
|
465
|
+
const at = open.get(json.index);
|
|
466
|
+
if (!at)
|
|
467
|
+
continue;
|
|
468
|
+
open.delete(json.index);
|
|
469
|
+
if (at.kind === "message") {
|
|
470
|
+
const part = { type: "output_text", text: at.text, annotations: [] };
|
|
471
|
+
Object.assign(at.item, { status: "completed", content: [part] });
|
|
472
|
+
send({ type: "response.output_text.done", item_id: at.item.id, output_index: at.index, content_index: 0, text: at.text, logprobs: [] });
|
|
473
|
+
send({ type: "response.content_part.done", item_id: at.item.id, output_index: at.index, content_index: 0, part });
|
|
474
|
+
}
|
|
475
|
+
else if (at.kind === "reasoning") {
|
|
476
|
+
const part = { type: "summary_text", text: at.text };
|
|
477
|
+
at.item.summary = [part];
|
|
478
|
+
send({ type: "response.reasoning_summary_text.done", item_id: at.item.id, output_index: at.index, summary_index: 0, text: at.text });
|
|
479
|
+
send({ type: "response.reasoning_summary_part.done", item_id: at.item.id, output_index: at.index, summary_index: 0, part });
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
const args = at.text || "{}";
|
|
483
|
+
Object.assign(at.item, { status: "completed", arguments: args });
|
|
484
|
+
send({ type: "response.function_call_arguments.done", item_id: at.item.id, output_index: at.index, arguments: args });
|
|
485
|
+
}
|
|
486
|
+
send({ type: "response.output_item.done", output_index: at.index, item: { ...at.item } });
|
|
487
|
+
}
|
|
488
|
+
else if (type === "message_delta") {
|
|
489
|
+
if (isPlain(json.usage))
|
|
490
|
+
usage = json.usage;
|
|
491
|
+
if (isPlain(json.delta) && typeof json.delta.stop_reason === "string")
|
|
492
|
+
stop = json.delta.stop_reason;
|
|
493
|
+
}
|
|
494
|
+
else if (type === "message_stop") {
|
|
495
|
+
end(stop === "max_tokens" ? "incomplete" : "completed");
|
|
496
|
+
}
|
|
497
|
+
else if (type === "error") {
|
|
498
|
+
const error = isPlain(json.error) ? json.error : {};
|
|
499
|
+
fail(String(json.message ?? error.message ?? "the model's request failed"), error.type === "rate_limit_error");
|
|
500
|
+
break;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
catch {
|
|
505
|
+
// The stream broke while it was read: said as a part that does not read is, never the error's own text.
|
|
506
|
+
fail(UNREAD, false);
|
|
507
|
+
}
|
|
508
|
+
// A Messages stream that closed with no stop: the answer was cut short, never a whole one.
|
|
509
|
+
if (!ended)
|
|
510
|
+
fail("the model's answer ended before it was complete", false);
|
|
511
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { Duplex } from "node:stream";
|
|
2
|
+
import { type GenAiTracing } from "../otel/tracer.js";
|
|
2
3
|
import { type HeldRedact, type Redact } from "./redact.js";
|
|
3
4
|
import type { Workspace } from "../workspace/workspace.js";
|
|
4
5
|
import { type AdapterSpecDeps } from "./adapter-run-spec.js";
|
|
6
|
+
import type { ClaudeAgentLogin } from "@parcha/agentrun-harness-claude";
|
|
5
7
|
import type { Held } from "./held.js";
|
|
6
8
|
import { type Claim, type LoopFactory } from "./loop-contract.js";
|
|
7
9
|
import { Channel } from "./run-channel.js";
|
|
@@ -120,6 +122,10 @@ interface ClaimReads {
|
|
|
120
122
|
readonly signal?: AbortSignal;
|
|
121
123
|
/** The runner's presence incarnation (LoopDeps.incarnation): with the claim's runner, who keeps a computer a park pins. */
|
|
122
124
|
readonly incarnation?: string;
|
|
125
|
+
/** The Claude login the claim read for this run (staysInRunner), handed down as it was read: none, and a turn-on after
|
|
126
|
+
* its claim never moves it onto a login its claim did not check; one, and the runner reads the setting again at the
|
|
127
|
+
* run's start (claudeLogin), handing it only when both reads name the same folder. */
|
|
128
|
+
readonly login: ClaudeAgentLogin | undefined;
|
|
123
129
|
}
|
|
124
130
|
/** The runner's redactor as the host side of a run's process holds it (LoopDeps.redact): its cut, and the carry of a
|
|
125
131
|
* value into what it cuts from the run's journal, which a token the runner hands the run needs (claudeLogin). */
|
|
@@ -151,6 +157,9 @@ export interface ChildLoopsOptions {
|
|
|
151
157
|
readonly log: (line: string) => void;
|
|
152
158
|
/** The program a run's process starts with (default this Node and dist/runner/run-child.js under dist/secrets.js). */
|
|
153
159
|
readonly argv?: readonly string[];
|
|
160
|
+
/** The runs' GenAI tracing: this runner's (otel/tracer.ts), from its OTEL_* env, by default. A run's process posts its
|
|
161
|
+
* trace's calls here (tracePosts) and exports nothing itself. A test gives its own, over an in-memory exporter. */
|
|
162
|
+
readonly tracing?: Promise<GenAiTracing | undefined>;
|
|
154
163
|
}
|
|
155
164
|
/** The node and module a run's process starts with. */
|
|
156
165
|
export declare const childArgv: () => string[];
|
|
@@ -181,14 +190,20 @@ export { RECIPE_SIGN_IN_PERSON_ONLY } from "./harness-loops.js";
|
|
|
181
190
|
* never the folder; it is refused at its claim (ClaimRefused, in words) on this machine's own login (machineFolder), and
|
|
182
191
|
* while a `process` runner on the same data folder is live (its CLI renews the folder's login itself). A run its caller
|
|
183
192
|
* handed a model key (model_key) runs on that key and never on the login (cli-run-spec.ts), so it is a process of its
|
|
184
|
-
* own like any other.
|
|
185
|
-
|
|
193
|
+
* own like any other. A run that is a process of its own is handed the login this claim read (`login`, ClaimReads): a
|
|
194
|
+
* claim that read it off is never put on it, so a turn-on landing after it never puts the run on a login whose refusals
|
|
195
|
+
* here it was never checked against; a claim that read it on has its runner read the setting again at the start
|
|
196
|
+
* (heldFor claudeLogin), and is refused there, in fixed words, when that read names none or another folder. */
|
|
197
|
+
export type ClaimPlace = {
|
|
198
|
+
readonly stays: true;
|
|
199
|
+
} | {
|
|
200
|
+
readonly stays: false;
|
|
201
|
+
readonly login: ClaudeAgentLogin | undefined;
|
|
202
|
+
};
|
|
203
|
+
export declare function staysInRunner(deps: Pick<AdapterSpecDeps, "store" | "data" | "env" | "sealKey">, harness: string, launch: RunLaunch, runId: string, isolation: RunIsolation): Promise<ClaimPlace>;
|
|
186
204
|
/** The runner's loop factory where each run is a process of its own: a ChildLoop per claim, but for a run that stays in
|
|
187
205
|
* the runner (staysInRunner). */
|
|
188
206
|
export declare function childLoops(options: ChildLoopsOptions): LoopFactory;
|
|
189
|
-
/** The pair a run's process is handed this runner's OpenTelemetry settings in (secrets.ts OTEL_PAIR): none when it has
|
|
190
|
-
* none. */
|
|
191
|
-
export declare const otelPair: (env?: NodeJS.ProcessEnv) => (readonly [string, string])[];
|
|
192
207
|
/** The runner's side of a run's channel over `socket`. Each call of the run's process runs inside the ledger of the tool
|
|
193
208
|
* call it was made in (paid-calls.ts). web_save's slots are `gate`, this runner's one (save-slots.ts); the channel's end
|
|
194
209
|
* (the run's end, or its process gone) gives back every slot the run held or waited for, and lets go of every pieced write
|