@visual-z/xeno 0.8.4 → 0.9.1
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 +19 -0
- package/README.md +31 -746
- package/bin/xeno.exe +26 -0
- package/install.cjs +88 -0
- package/package.json +18 -48
- package/docs/app-server.md +0 -115
- package/docs/foundations.md +0 -88
- package/docs/install.md +0 -244
- package/docs/providers.md +0 -172
- package/docs/research/foundation-clients-2026-10-09.md +0 -27
- package/docs/research/foundation-editing-2026-10-09.md +0 -56
- package/docs/research/foundation-network-2026-10-09.md +0 -37
- package/docs/research/foundation-workflow-2026-10-09.md +0 -37
- package/src/apps/acp-server.ts +0 -41
- package/src/apps/agent-profiles.ts +0 -19
- package/src/apps/app-server.ts +0 -30
- package/src/apps/approve.ts +0 -49
- package/src/apps/cli.ts +0 -99
- package/src/apps/commands.ts +0 -319
- package/src/apps/completions.ts +0 -87
- package/src/apps/control-transport.ts +0 -90
- package/src/apps/export-cli.ts +0 -24
- package/src/apps/goal-flow.ts +0 -70
- package/src/apps/image-draft.ts +0 -46
- package/src/apps/input.ts +0 -312
- package/src/apps/model-catalog.ts +0 -69
- package/src/apps/preferences.ts +0 -20
- package/src/apps/project-trust.ts +0 -9
- package/src/apps/provider-connect.ts +0 -346
- package/src/apps/question-ui.ts +0 -27
- package/src/apps/render.ts +0 -181
- package/src/apps/resources.ts +0 -66
- package/src/apps/review.ts +0 -109
- package/src/apps/session-hub.ts +0 -96
- package/src/apps/session-lifecycle.ts +0 -64
- package/src/apps/shell.ts +0 -2071
- package/src/apps/startup-input.ts +0 -135
- package/src/apps/startup.ts +0 -1677
- package/src/apps/ui/app.ts +0 -1818
- package/src/apps/ui/control-model.ts +0 -43
- package/src/apps/ui/extension-host.ts +0 -194
- package/src/apps/ui/image-cache.ts +0 -121
- package/src/apps/ui/palette.ts +0 -88
- package/src/apps/ui/project.ts +0 -127
- package/src/apps/ui/standalone.ts +0 -148
- package/src/apps/ui/status-model.ts +0 -68
- package/src/apps/ui/surface.ts +0 -91
- package/src/apps/ui/theme.ts +0 -86
- package/src/apps/update-check.ts +0 -112
- package/src/apps/workflow.ts +0 -58
- package/src/core/acceptance.ts +0 -139
- package/src/core/action-defaults.ts +0 -58
- package/src/core/activity-status.ts +0 -52
- package/src/core/agent-profile.ts +0 -130
- package/src/core/attachment-input.ts +0 -17
- package/src/core/blind-checks.ts +0 -72
- package/src/core/boundary.ts +0 -174
- package/src/core/branch-receipt.ts +0 -26
- package/src/core/catalog-merge.ts +0 -19
- package/src/core/checkpoints.ts +0 -85
- package/src/core/churn.ts +0 -61
- package/src/core/command-artifacts.ts +0 -94
- package/src/core/command-contract.ts +0 -151
- package/src/core/completion-action.ts +0 -20
- package/src/core/completion-review.ts +0 -98
- package/src/core/context-detail.ts +0 -37
- package/src/core/context-policy.ts +0 -133
- package/src/core/context-window.ts +0 -54
- package/src/core/continuation.ts +0 -130
- package/src/core/control-protocol.ts +0 -69
- package/src/core/control-view.ts +0 -39
- package/src/core/cycle.ts +0 -17
- package/src/core/data-query.ts +0 -201
- package/src/core/deadline.ts +0 -40
- package/src/core/derive.ts +0 -516
- package/src/core/draft-images.ts +0 -56
- package/src/core/edit-plan.ts +0 -200
- package/src/core/environment.ts +0 -181
- package/src/core/event-validation.ts +0 -220
- package/src/core/events.ts +0 -670
- package/src/core/evidence-ladder.ts +0 -62
- package/src/core/evidence-links.ts +0 -68
- package/src/core/evidence.ts +0 -240
- package/src/core/execution.ts +0 -18
- package/src/core/exhaustive.ts +0 -18
- package/src/core/export.ts +0 -179
- package/src/core/extension-flags.ts +0 -14
- package/src/core/external-effects.ts +0 -488
- package/src/core/failure-recovery.ts +0 -173
- package/src/core/file-precondition.ts +0 -78
- package/src/core/file-references.ts +0 -35
- package/src/core/frontmatter.ts +0 -213
- package/src/core/git-status.ts +0 -29
- package/src/core/goal-view.ts +0 -64
- package/src/core/goal.ts +0 -200
- package/src/core/handoff.ts +0 -479
- package/src/core/history-query.ts +0 -139
- package/src/core/history.ts +0 -237
- package/src/core/image-limits.ts +0 -72
- package/src/core/images.ts +0 -46
- package/src/core/integration-health.ts +0 -34
- package/src/core/json-event.ts +0 -131
- package/src/core/json-pointer.ts +0 -46
- package/src/core/keymap.ts +0 -153
- package/src/core/lsp-framing.ts +0 -34
- package/src/core/mcp-config.ts +0 -68
- package/src/core/model-picker.ts +0 -64
- package/src/core/model-preferences.ts +0 -28
- package/src/core/model-replay.ts +0 -22
- package/src/core/model-scope.ts +0 -53
- package/src/core/note-guidance.ts +0 -34
- package/src/core/oauth-fields.ts +0 -44
- package/src/core/observation-view.ts +0 -152
- package/src/core/outcome.ts +0 -44
- package/src/core/overflow.ts +0 -59
- package/src/core/packages.ts +0 -47
- package/src/core/patch.ts +0 -130
- package/src/core/path-suggestions.ts +0 -59
- package/src/core/permissions.ts +0 -410
- package/src/core/process-receipt.ts +0 -105
- package/src/core/process-state.ts +0 -37
- package/src/core/program-status.ts +0 -40
- package/src/core/progress.ts +0 -150
- package/src/core/project.ts +0 -431
- package/src/core/prompt-policy.ts +0 -46
- package/src/core/prompts.ts +0 -111
- package/src/core/question.ts +0 -94
- package/src/core/queue.ts +0 -78
- package/src/core/read-bounds.ts +0 -24
- package/src/core/read-observation.ts +0 -106
- package/src/core/recovery-sources.ts +0 -74
- package/src/core/regex-dialect.ts +0 -25
- package/src/core/request-budget.ts +0 -23
- package/src/core/request-progress.ts +0 -87
- package/src/core/request-state.ts +0 -273
- package/src/core/resource-selection.ts +0 -36
- package/src/core/response-recovery.ts +0 -59
- package/src/core/resume.ts +0 -59
- package/src/core/review.ts +0 -68
- package/src/core/ripgrep-release.ts +0 -64
- package/src/core/runtime-target.ts +0 -94
- package/src/core/scheduling.ts +0 -8
- package/src/core/search-observation.ts +0 -97
- package/src/core/secrets.ts +0 -188
- package/src/core/session-archive.ts +0 -4
- package/src/core/session-browser.ts +0 -82
- package/src/core/session-entry.ts +0 -61
- package/src/core/session-exit.ts +0 -42
- package/src/core/session-format.ts +0 -169
- package/src/core/session-position.ts +0 -26
- package/src/core/session-tree.ts +0 -147
- package/src/core/settings.ts +0 -192
- package/src/core/skills.ts +0 -165
- package/src/core/sql-query.ts +0 -211
- package/src/core/stall.ts +0 -128
- package/src/core/stop-report.ts +0 -68
- package/src/core/text-normalize.ts +0 -81
- package/src/core/theme.ts +0 -166
- package/src/core/thinking.ts +0 -26
- package/src/core/tokens.ts +0 -151
- package/src/core/tool-contract.ts +0 -153
- package/src/core/tool-discovery.ts +0 -87
- package/src/core/tool-failure.ts +0 -81
- package/src/core/tool-input.ts +0 -44
- package/src/core/transcript.ts +0 -108
- package/src/core/tui-mode.ts +0 -29
- package/src/core/update-check.ts +0 -157
- package/src/core/version.ts +0 -55
- package/src/core/web-content.ts +0 -80
- package/src/core/work-state.ts +0 -154
- package/src/core/workflow-mode.ts +0 -34
- package/src/core/working-set.ts +0 -119
- package/src/core/yaml.ts +0 -282
- package/src/runtime/acp-agent.ts +0 -289
- package/src/runtime/agent-profiles.ts +0 -21
- package/src/runtime/auth.ts +0 -367
- package/src/runtime/blind-check.ts +0 -36
- package/src/runtime/branch-jobs.ts +0 -36
- package/src/runtime/catalog.ts +0 -285
- package/src/runtime/clipboard.ts +0 -125
- package/src/runtime/command-artifacts.ts +0 -64
- package/src/runtime/connection-reuse.ts +0 -40
- package/src/runtime/control-client.ts +0 -149
- package/src/runtime/control-connection.ts +0 -139
- package/src/runtime/counter-check.ts +0 -74
- package/src/runtime/environment-tools.ts +0 -60
- package/src/runtime/evidence-notes.ts +0 -35
- package/src/runtime/exec-sessions.ts +0 -456
- package/src/runtime/execution-control.ts +0 -40
- package/src/runtime/extension-loader.ts +0 -37
- package/src/runtime/extension-ui.ts +0 -47
- package/src/runtime/extensions.ts +0 -370
- package/src/runtime/formatter-tool.ts +0 -38
- package/src/runtime/formatter.ts +0 -50
- package/src/runtime/foundation.ts +0 -116
- package/src/runtime/history-cache.ts +0 -57
- package/src/runtime/history-tools.ts +0 -168
- package/src/runtime/images.ts +0 -80
- package/src/runtime/integrations.ts +0 -216
- package/src/runtime/loop.ts +0 -3108
- package/src/runtime/lsp-client.ts +0 -201
- package/src/runtime/mcp-client.ts +0 -264
- package/src/runtime/mcp-oauth.ts +0 -168
- package/src/runtime/mcp-schema.ts +0 -51
- package/src/runtime/model-config.ts +0 -232
- package/src/runtime/model-data.LICENSE +0 -27
- package/src/runtime/model-data.ts +0 -21
- package/src/runtime/model-discovery.ts +0 -208
- package/src/runtime/model-replay.ts +0 -10
- package/src/runtime/model-scope.ts +0 -20
- package/src/runtime/model-sources.ts +0 -151
- package/src/runtime/model.ts +0 -686
- package/src/runtime/models-fetch.ts +0 -57
- package/src/runtime/oauth-device.ts +0 -86
- package/src/runtime/oauth.ts +0 -853
- package/src/runtime/open-image.ts +0 -42
- package/src/runtime/openai-responses.ts +0 -304
- package/src/runtime/openai.ts +0 -697
- package/src/runtime/output-schema.ts +0 -26
- package/src/runtime/package-manager.ts +0 -125
- package/src/runtime/patch-tool.ts +0 -38
- package/src/runtime/permission-resources.ts +0 -18
- package/src/runtime/pi-provider.ts +0 -423
- package/src/runtime/program-status.ts +0 -38
- package/src/runtime/progress.ts +0 -26
- package/src/runtime/provider-access.ts +0 -21
- package/src/runtime/provider-connect.ts +0 -109
- package/src/runtime/provider-presets.ts +0 -98
- package/src/runtime/provider-protocols.ts +0 -29
- package/src/runtime/provider-request.ts +0 -87
- package/src/runtime/provider-tool-policy.ts +0 -33
- package/src/runtime/provider.ts +0 -580
- package/src/runtime/question-tool.ts +0 -62
- package/src/runtime/retry.ts +0 -447
- package/src/runtime/review-tool.ts +0 -48
- package/src/runtime/rich-text.ts +0 -36
- package/src/runtime/runtime-target.ts +0 -149
- package/src/runtime/secrets.ts +0 -79
- package/src/runtime/self-update.ts +0 -74
- package/src/runtime/session-control.ts +0 -265
- package/src/runtime/session-hub.ts +0 -85
- package/src/runtime/stream-idle.ts +0 -80
- package/src/runtime/tool-broker.ts +0 -137
- package/src/runtime/tool-discovery.ts +0 -58
- package/src/runtime/tool-queue.ts +0 -77
- package/src/runtime/tools.ts +0 -1820
- package/src/runtime/turn-effects.ts +0 -31
- package/src/runtime/update-check.ts +0 -48
- package/src/runtime/usage.ts +0 -253
- package/src/runtime/version.ts +0 -12
- package/src/runtime/web-http.ts +0 -56
- package/src/runtime/web-tools.ts +0 -88
- package/src/runtime/working-notes.ts +0 -60
- package/src/runtime/workspace-lifecycle.ts +0 -141
- package/src/store/acceptance.ts +0 -15
- package/src/store/agent-profile-files.ts +0 -13
- package/src/store/atomic.ts +0 -31
- package/src/store/auth-store.ts +0 -50
- package/src/store/blind-checks.ts +0 -32
- package/src/store/blobs.ts +0 -143
- package/src/store/checkpoint-history.ts +0 -32
- package/src/store/command-artifacts.ts +0 -96
- package/src/store/command.ts +0 -111
- package/src/store/config.ts +0 -69
- package/src/store/context-files.ts +0 -436
- package/src/store/file-checkpoints.ts +0 -108
- package/src/store/file-index.ts +0 -174
- package/src/store/foundation-config.ts +0 -24
- package/src/store/git-checkpoints.ts +0 -67
- package/src/store/git-status.ts +0 -15
- package/src/store/history-search.ts +0 -19
- package/src/store/log.ts +0 -725
- package/src/store/lsp-document.ts +0 -30
- package/src/store/mcp-credentials.ts +0 -85
- package/src/store/models.ts +0 -60
- package/src/store/observations.ts +0 -224
- package/src/store/packages.ts +0 -98
- package/src/store/patch.ts +0 -92
- package/src/store/permission-paths.ts +0 -34
- package/src/store/process-receipts.ts +0 -34
- package/src/store/query-source.ts +0 -49
- package/src/store/recovery.ts +0 -44
- package/src/store/replay.ts +0 -76
- package/src/store/resource-index.ts +0 -170
- package/src/store/resources.ts +0 -285
- package/src/store/restore.ts +0 -110
- package/src/store/review.ts +0 -109
- package/src/store/runtime-target.ts +0 -64
- package/src/store/search.ts +0 -728
- package/src/store/secrets.ts +0 -44
- package/src/store/serial.ts +0 -13
- package/src/store/session-archive.ts +0 -165
- package/src/store/session-browser.ts +0 -68
- package/src/store/session-position.ts +0 -27
- package/src/store/sessions.ts +0 -525
- package/src/store/source-cancellation.ts +0 -6
- package/src/store/tool-binaries.ts +0 -90
- package/src/store/trust.ts +0 -82
- package/src/store/update-cache.ts +0 -36
- package/src/store/user-settings.ts +0 -30
- package/src/store/workspace-clone.ts +0 -42
- package/src/store/workspace-observation.ts +0 -113
- package/src/store/workspace.ts +0 -115
- package/src/store/worktree.ts +0 -278
- package/src/tui/ansi-spans.ts +0 -126
- package/src/tui/diff.ts +0 -160
- package/src/tui/exhaustive.ts +0 -14
- package/src/tui/fuzzy.ts +0 -75
- package/src/tui/style.ts +0 -208
- package/src/tui/ui/atomic-draft.ts +0 -121
- package/src/tui/ui/branch-panel.ts +0 -47
- package/src/tui/ui/canvas.ts +0 -96
- package/src/tui/ui/colors.ts +0 -70
- package/src/tui/ui/composer.ts +0 -199
- package/src/tui/ui/control-panel.ts +0 -25
- package/src/tui/ui/control-sidebar.ts +0 -49
- package/src/tui/ui/dialog.ts +0 -398
- package/src/tui/ui/draft.ts +0 -23
- package/src/tui/ui/duration.ts +0 -16
- package/src/tui/ui/edge.ts +0 -186
- package/src/tui/ui/image-size.ts +0 -44
- package/src/tui/ui/ink.ts +0 -210
- package/src/tui/ui/items.ts +0 -42
- package/src/tui/ui/keys.ts +0 -40
- package/src/tui/ui/layout.ts +0 -74
- package/src/tui/ui/list-model.ts +0 -86
- package/src/tui/ui/list-view.ts +0 -172
- package/src/tui/ui/mascot.ts +0 -67
- package/src/tui/ui/messages.ts +0 -518
- package/src/tui/ui/motion.ts +0 -28
- package/src/tui/ui/paths.ts +0 -10
- package/src/tui/ui/pictures.ts +0 -108
- package/src/tui/ui/prompt-history.ts +0 -60
- package/src/tui/ui/screen.ts +0 -579
- package/src/tui/ui/status.ts +0 -403
- package/src/tui/ui/styled.ts +0 -85
- package/src/tui/ui/tool-card.ts +0 -150
- package/src/tui/width.ts +0 -567
- package/src/vendor/pi-rich/LICENSE.upstream +0 -21
- package/src/vendor/pi-rich/UPSTREAM.json +0 -17
- package/src/vendor/pi-rich/clipboard-command.ts +0 -44
- package/src/vendor/pi-rich/exif-orientation.ts +0 -182
- package/src/vendor/pi-rich/html.ts +0 -51
- package/src/vendor/pi-rich/image-convert.ts +0 -49
- package/src/vendor/pi-rich/image-resize-core.ts +0 -164
- package/src/vendor/pi-rich/image-resize-worker.ts +0 -42
- package/src/vendor/pi-rich/image-resize.ts +0 -123
- package/src/vendor/pi-rich/mime.ts +0 -116
- package/src/vendor/pi-rich/photon.ts +0 -139
- package/src/vendor/pi-rich/syntax-highlight.ts +0 -214
package/src/runtime/openai.ts
DELETED
|
@@ -1,697 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The OpenAI Chat Completions adapter.
|
|
3
|
-
*
|
|
4
|
-
* "OpenAI-compatible" names a family of dialects rather than a protocol. The
|
|
5
|
-
* differences are small, undocumented in aggregate, and each one is a 400 or a
|
|
6
|
-
* silently wrong number: which field caps the output, whether the system
|
|
7
|
-
* prompt may use the `developer` role, where reasoning lives on the way out
|
|
8
|
-
* and on the way back, which usage field carries a cache hit. So the accent is
|
|
9
|
-
* carried as data on the model (`Compat`) and this file only reads it. The
|
|
10
|
-
* alternative -- branching on the provider's name -- ends as a chain of `||`
|
|
11
|
-
* that nobody can safely extend, which is where every adapter that started
|
|
12
|
-
* that way has arrived.
|
|
13
|
-
*
|
|
14
|
-
* Two of the three functions here are pure. `buildRequest` turns the core's
|
|
15
|
-
* provider-neutral messages into a request body and `parseResponse` turns a
|
|
16
|
-
* response body back into a turn; only `OpenAICompletionsProvider.send` is
|
|
17
|
-
* allowed to touch the network. That split is what lets the expensive mistakes
|
|
18
|
-
* -- a missing field that costs a 400, a cache hit counted as fresh input --
|
|
19
|
-
* be caught offline, without a key.
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import type { Message, ContentBlock, FrozenPrefix } from "../core/project.ts";
|
|
23
|
-
import { imageData } from "./images.ts";
|
|
24
|
-
import type { AssistantBlock } from "../core/events.ts";
|
|
25
|
-
import { assertNever } from "../core/exhaustive.ts";
|
|
26
|
-
import { coherentTurn, type Provider, type ProviderConfig, type Turn, type ToolSchema, type OnDelta } from "./provider.ts";
|
|
27
|
-
import { DEFAULT_COMPAT, type Compat, type Effort, type ModelSpec } from "./model.ts";
|
|
28
|
-
import { withRetry, retryLabel, DEFAULT_RETRY, type RetryPolicy } from "./retry.ts";
|
|
29
|
-
import { ConnectionReuse } from "./connection-reuse.ts";
|
|
30
|
-
import { watchIdle, type IdleWatch } from "./stream-idle.ts";
|
|
31
|
-
|
|
32
|
-
import type { ProviderSendOptions } from "./provider-tool-policy.ts";
|
|
33
|
-
|
|
34
|
-
/** One message as Chat Completions wants it. */
|
|
35
|
-
export interface WireMessage {
|
|
36
|
-
role: "system" | "developer" | "user" | "assistant" | "tool";
|
|
37
|
-
content?: string | null | ({ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } })[];
|
|
38
|
-
reasoning_content?: string;
|
|
39
|
-
/** OpenRouter's structured reasoning, replayed as received. */
|
|
40
|
-
reasoning_details?: unknown;
|
|
41
|
-
tool_calls?: ({
|
|
42
|
-
id: string;
|
|
43
|
-
type: "function";
|
|
44
|
-
function: { name: string; arguments: string };
|
|
45
|
-
} & Record<string, unknown>)[];
|
|
46
|
-
tool_call_id?: string;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export interface WireRequest {
|
|
50
|
-
model: string;
|
|
51
|
-
messages: WireMessage[];
|
|
52
|
-
max_tokens?: number;
|
|
53
|
-
max_completion_tokens?: number;
|
|
54
|
-
tools?: unknown[];
|
|
55
|
-
tool_choice?: "none";
|
|
56
|
-
thinking?: { type: "enabled" | "disabled" };
|
|
57
|
-
reasoning_effort?: string;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* The shape this adapter puts in a thinking block's opaque `raw`.
|
|
62
|
-
*
|
|
63
|
-
* `raw` is the core's escape hatch for "whatever this provider needs to see
|
|
64
|
-
* again, unchanged" -- the Anthropic adapter parks a signed block there. Here
|
|
65
|
-
* it is the reasoning text, because that is what has to go back on the wire.
|
|
66
|
-
* Each adapter recognises only its own, which is exactly why the field is
|
|
67
|
-
* typed `unknown` in the core.
|
|
68
|
-
*/
|
|
69
|
-
interface ReasoningRaw {
|
|
70
|
-
reasoning_content: string;
|
|
71
|
-
/** OpenRouter: structured, sometimes encrypted, reasoning it wants back verbatim. */
|
|
72
|
-
reasoning_details?: unknown;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function reasoningDetailsOf(raw: unknown): unknown {
|
|
76
|
-
if (typeof raw !== "object" || raw === null) return undefined;
|
|
77
|
-
return (raw as Partial<ReasoningRaw>).reasoning_details;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* A tool call's fields beyond the ones this adapter reads.
|
|
82
|
-
*
|
|
83
|
-
* Gemini's OpenAI-compatible endpoint puts a thought signature under
|
|
84
|
-
* `extra_content` and rejects the next request if it is not echoed back.
|
|
85
|
-
* Rather than learn each provider's extension, keep whatever else arrived and
|
|
86
|
-
* send it back unchanged -- the same contract as a thinking block's raw.
|
|
87
|
-
*/
|
|
88
|
-
function extraFields(call: Record<string, unknown>): Record<string, unknown> | undefined {
|
|
89
|
-
const extra: Record<string, unknown> = {};
|
|
90
|
-
for (const [key, value] of Object.entries(call)) {
|
|
91
|
-
if (key !== "id" && key !== "type" && key !== "function" && key !== "index") extra[key] = value;
|
|
92
|
-
}
|
|
93
|
-
return Object.keys(extra).length > 0 ? extra : undefined;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function reasoningOf(raw: unknown): string | null {
|
|
97
|
-
if (typeof raw !== "object" || raw === null) return null;
|
|
98
|
-
const value = (raw as Partial<ReasoningRaw>).reasoning_content;
|
|
99
|
-
return typeof value === "string" ? value : null;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* Chat Completions takes the whole tool list flat under `function`, where the
|
|
104
|
-
* Anthropic shape nests the schema under `input_schema`. `strict` is omitted
|
|
105
|
-
* rather than set false: providers in this family reject unknown fields, and
|
|
106
|
-
* the ones that support strict mode are not the ones we talk to.
|
|
107
|
-
*/
|
|
108
|
-
function toWireTools(tools: readonly unknown[]): unknown[] {
|
|
109
|
-
return tools.map((t) => {
|
|
110
|
-
const tool = t as ToolSchema;
|
|
111
|
-
return {
|
|
112
|
-
type: "function",
|
|
113
|
-
function: {
|
|
114
|
-
name: tool.name,
|
|
115
|
-
description: tool.description,
|
|
116
|
-
parameters: tool.input_schema,
|
|
117
|
-
},
|
|
118
|
-
};
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Flattens one assistant turn's blocks into the single string + tool_calls
|
|
124
|
-
* pair this API expects.
|
|
125
|
-
*
|
|
126
|
-
* The content must be a plain string and not an array of `{type:"text"}`
|
|
127
|
-
* blocks. The array form is legal OpenAI but some models in this family mirror
|
|
128
|
-
* the structure literally into their own output, producing nested
|
|
129
|
-
* `[{'type':'text','text':'[{...}]'}]` that then poisons every later turn.
|
|
130
|
-
*/
|
|
131
|
-
function assistantMessage(content: readonly ContentBlock[], compat: Compat, reasoning: boolean): WireMessage {
|
|
132
|
-
const text: string[] = [];
|
|
133
|
-
const thinking: string[] = [];
|
|
134
|
-
const details: unknown[] = [];
|
|
135
|
-
const toolCalls: NonNullable<WireMessage["tool_calls"]> = [];
|
|
136
|
-
|
|
137
|
-
for (const b of content) {
|
|
138
|
-
switch (b.type) {
|
|
139
|
-
case "text":
|
|
140
|
-
text.push(b.text);
|
|
141
|
-
break;
|
|
142
|
-
case "thinking": {
|
|
143
|
-
const r = reasoningOf(b.raw);
|
|
144
|
-
if (r !== null && r.length > 0) thinking.push(r);
|
|
145
|
-
const d = reasoningDetailsOf(b.raw);
|
|
146
|
-
if (Array.isArray(d)) details.push(...d);
|
|
147
|
-
else if (d !== undefined) details.push(d);
|
|
148
|
-
break;
|
|
149
|
-
}
|
|
150
|
-
case "tool_use":
|
|
151
|
-
toolCalls.push({
|
|
152
|
-
...(typeof b.wire === "object" && b.wire !== null ? b.wire as Record<string, unknown> : {}),
|
|
153
|
-
id: b.id,
|
|
154
|
-
type: "function",
|
|
155
|
-
function: { name: b.name, arguments: JSON.stringify(b.input) },
|
|
156
|
-
});
|
|
157
|
-
break;
|
|
158
|
-
case "tool_result":
|
|
159
|
-
case "image":
|
|
160
|
-
// A tool_result inside an assistant turn is not a shape the projection
|
|
161
|
-
// produces. Ignored rather than thrown: the request stays valid, and
|
|
162
|
-
// the pairing checks that would catch it live in the core.
|
|
163
|
-
break;
|
|
164
|
-
default:
|
|
165
|
-
return assertNever(b, "assistantMessage");
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
const message: WireMessage = { role: "assistant" };
|
|
170
|
-
if (text.length > 0) message.content = text.join("");
|
|
171
|
-
if (toolCalls.length > 0) message.tool_calls = toolCalls;
|
|
172
|
-
|
|
173
|
-
// The documented rule, and the reason this adapter exists in this shape:
|
|
174
|
-
// once `tools` is in the request, DeepSeek requires reasoning_content on
|
|
175
|
-
// EVERY assistant message in the history -- including turns that did no
|
|
176
|
-
// thinking and made no tool call -- and returns 400 without it. An empty
|
|
177
|
-
// string is the documented stand-in, not a guess.
|
|
178
|
-
if (compat.requiresReasoningContentOnAssistantMessages && reasoning) {
|
|
179
|
-
message.reasoning_content = thinking.join("\n");
|
|
180
|
-
} else if (thinking.length > 0) {
|
|
181
|
-
message.reasoning_content = thinking.join("\n");
|
|
182
|
-
}
|
|
183
|
-
if (details.length > 0) message.reasoning_details = details;
|
|
184
|
-
|
|
185
|
-
return message;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
* Turns one projected user message into wire messages.
|
|
190
|
-
*
|
|
191
|
-
* The projection deliberately batches every tool result for a turn into a
|
|
192
|
-
* single user message, because splitting them teaches the model to stop
|
|
193
|
-
* issuing parallel calls. This API wants the opposite: one `tool` message per
|
|
194
|
-
* result, keyed by call id. So the split happens here, at the wire boundary,
|
|
195
|
-
* and the projection's property is left intact.
|
|
196
|
-
*/
|
|
197
|
-
function userMessages(content: readonly ContentBlock[]): WireMessage[] {
|
|
198
|
-
const out: WireMessage[] = [];
|
|
199
|
-
const text: string[] = [];
|
|
200
|
-
const parts: NonNullable<Exclude<WireMessage["content"], string>> = [];
|
|
201
|
-
|
|
202
|
-
for (const b of content) {
|
|
203
|
-
switch (b.type) {
|
|
204
|
-
case "image": parts.push({ type: "image_url", image_url: { url: `data:${b.image.mimeType};base64,${imageData(b)}` } }); break;
|
|
205
|
-
case "tool_result":
|
|
206
|
-
out.push({
|
|
207
|
-
role: "tool",
|
|
208
|
-
tool_call_id: b.tool_use_id,
|
|
209
|
-
content: b.content,
|
|
210
|
-
});
|
|
211
|
-
break;
|
|
212
|
-
case "text":
|
|
213
|
-
text.push(b.text);
|
|
214
|
-
break;
|
|
215
|
-
case "thinking":
|
|
216
|
-
case "tool_use":
|
|
217
|
-
// Neither appears in a user turn in any projection this harness
|
|
218
|
-
// produces; dropping them keeps the request valid.
|
|
219
|
-
break;
|
|
220
|
-
default:
|
|
221
|
-
return assertNever(b, "userMessages");
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
if (parts.length) out.push({ role: "user", content: [...(text.length ? [{ type: "text" as const, text: text.join("\n") }] : []), ...parts] });
|
|
226
|
-
else if (text.length > 0) out.push({ role: "user", content: text.join("\n") });
|
|
227
|
-
return out;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
/** Maps our effort onto what this model accepts; `null` in the map means "send nothing". */
|
|
231
|
-
function wireEffort(spec: ModelSpec, effort: Effort): string | null {
|
|
232
|
-
const mapped = spec.thinkingLevelMap?.[effort];
|
|
233
|
-
if (mapped === null) return null;
|
|
234
|
-
return mapped ?? effort;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
export function buildRequest(
|
|
238
|
-
config: ProviderConfig,
|
|
239
|
-
frozen: FrozenPrefix,
|
|
240
|
-
messages: readonly Message[],
|
|
241
|
-
): WireRequest {
|
|
242
|
-
const spec = config.spec;
|
|
243
|
-
const compat = spec.compat ?? DEFAULT_COMPAT;
|
|
244
|
-
|
|
245
|
-
const wire: WireMessage[] = [
|
|
246
|
-
// The system prompt leads, which is all the prefix management this
|
|
247
|
-
// provider needs: its cache is automatic and keyed on the literal prefix,
|
|
248
|
-
// so the core's append-only property is what produces the hits. There is
|
|
249
|
-
// no breakpoint to place and none to get wrong.
|
|
250
|
-
{
|
|
251
|
-
role: compat.supportsDeveloperRole && spec.reasoning ? "developer" : "system",
|
|
252
|
-
content: frozen.system,
|
|
253
|
-
},
|
|
254
|
-
];
|
|
255
|
-
|
|
256
|
-
for (const m of messages) {
|
|
257
|
-
if (m.role === "assistant") {
|
|
258
|
-
const built = assistantMessage(m.content, compat, spec.reasoning);
|
|
259
|
-
// Some providers reject an assistant message with neither content nor
|
|
260
|
-
// tool calls, which is what an aborted turn leaves behind.
|
|
261
|
-
if (built.content !== undefined || built.tool_calls !== undefined) wire.push(built);
|
|
262
|
-
} else {
|
|
263
|
-
wire.push(...userMessages(m.content));
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
const request: WireRequest = { model: spec.id, messages: wire };
|
|
268
|
-
|
|
269
|
-
if (compat.maxTokensField === "max_tokens") request.max_tokens = config.maxTokens;
|
|
270
|
-
else request.max_completion_tokens = config.maxTokens;
|
|
271
|
-
|
|
272
|
-
if (frozen.tools.length > 0) request.tools = toWireTools(frozen.tools);
|
|
273
|
-
|
|
274
|
-
if (spec.reasoning) {
|
|
275
|
-
if (compat.thinkingFormat === "deepseek") request.thinking = { type: config.effort === "off" ? "disabled" : "enabled" };
|
|
276
|
-
if (compat.supportsReasoningEffort && config.effort !== "off") {
|
|
277
|
-
const effort = wireEffort(spec, config.effort);
|
|
278
|
-
if (effort !== null) request.reasoning_effort = effort;
|
|
279
|
-
} else if (config.effort === "off" && compat.thinkingFormat !== "deepseek" && typeof spec.thinkingLevelMap?.off === "string") {
|
|
280
|
-
request.reasoning_effort = spec.thinkingLevelMap.off;
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
return request;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
/** Only the fields we read, so a provider adding more cannot break parsing. */
|
|
288
|
-
interface WireResponse {
|
|
289
|
-
choices?: {
|
|
290
|
-
message?: {
|
|
291
|
-
content?: string | null;
|
|
292
|
-
reasoning_content?: string | null;
|
|
293
|
-
/** OpenRouter's name for the reasoning text. */
|
|
294
|
-
reasoning?: string | null;
|
|
295
|
-
reasoning_details?: unknown;
|
|
296
|
-
tool_calls?: ({
|
|
297
|
-
id?: string;
|
|
298
|
-
function?: { name?: string; arguments?: string };
|
|
299
|
-
} & Record<string, unknown>)[];
|
|
300
|
-
};
|
|
301
|
-
finish_reason?: string | null;
|
|
302
|
-
}[];
|
|
303
|
-
usage?: {
|
|
304
|
-
prompt_tokens?: number;
|
|
305
|
-
completion_tokens?: number;
|
|
306
|
-
prompt_cache_hit_tokens?: number;
|
|
307
|
-
prompt_tokens_details?: { cached_tokens?: number };
|
|
308
|
-
};
|
|
309
|
-
error?: { message?: string };
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/**
|
|
313
|
-
* Decodes tool arguments, which arrive as a JSON string.
|
|
314
|
-
*
|
|
315
|
-
* A model can emit malformed JSON there. The raw string is kept rather than
|
|
316
|
-
* dropped so the tool layer reports a bad argument, instead of the call
|
|
317
|
-
* vanishing and the turn ending with an unanswered tool_use.
|
|
318
|
-
*/
|
|
319
|
-
function decodeArguments(raw: string | undefined): unknown {
|
|
320
|
-
if (raw === undefined || raw.length === 0) return {};
|
|
321
|
-
try {
|
|
322
|
-
return JSON.parse(raw);
|
|
323
|
-
} catch {
|
|
324
|
-
return { __unparsed_arguments: raw };
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
export function parseResponse(body: unknown, node: number, ms: number): Turn {
|
|
329
|
-
const response = body as WireResponse;
|
|
330
|
-
const message = response.choices?.[0]?.message;
|
|
331
|
-
const blocks: AssistantBlock[] = [];
|
|
332
|
-
|
|
333
|
-
// Reasoning first, matching the order the model produced it and the order
|
|
334
|
-
// the Anthropic adapter yields. `raw` is what goes back on the wire; `text`
|
|
335
|
-
// is only for display.
|
|
336
|
-
const reasoning = message?.reasoning_content ?? message?.reasoning;
|
|
337
|
-
const details = message?.reasoning_details;
|
|
338
|
-
if ((typeof reasoning === "string" && reasoning.length > 0) || details !== undefined) {
|
|
339
|
-
const text = typeof reasoning === "string" ? reasoning : "";
|
|
340
|
-
blocks.push({ type: "thinking", text,
|
|
341
|
-
raw: { reasoning_content: text, ...(details === undefined ? {} : { reasoning_details: details }) } });
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
const text = message?.content;
|
|
345
|
-
if (typeof text === "string" && text.length > 0) {
|
|
346
|
-
blocks.push({ type: "text", text });
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
(message?.tool_calls ?? []).forEach((call, index) => {
|
|
350
|
-
const wire = extraFields(call);
|
|
351
|
-
blocks.push({
|
|
352
|
-
type: "tool_use",
|
|
353
|
-
// A missing id would make every call in the batch pair with the same
|
|
354
|
-
// result. The position is deterministic, so a replay derives the same one.
|
|
355
|
-
call_id: typeof call.id === "string" && call.id.length > 0 ? call.id : `call_${index}`,
|
|
356
|
-
name: call.function?.name ?? "",
|
|
357
|
-
input: decodeArguments(call.function?.arguments),
|
|
358
|
-
...(wire === undefined ? {} : { wire }),
|
|
359
|
-
});
|
|
360
|
-
});
|
|
361
|
-
|
|
362
|
-
const usage = response.usage;
|
|
363
|
-
const prompt = usage?.prompt_tokens ?? 0;
|
|
364
|
-
// DeepSeek reports hits in prompt_cache_hit_tokens; the rest of the family
|
|
365
|
-
// uses prompt_tokens_details.cached_tokens. Both mean the same thing, and
|
|
366
|
-
// both are already included in prompt_tokens -- so the uncached remainder
|
|
367
|
-
// is the difference, not the whole.
|
|
368
|
-
const cacheRead = usage?.prompt_cache_hit_tokens ?? usage?.prompt_tokens_details?.cached_tokens ?? 0;
|
|
369
|
-
|
|
370
|
-
return {
|
|
371
|
-
blocks,
|
|
372
|
-
stopReason: response.choices?.[0]?.finish_reason ?? null,
|
|
373
|
-
usage: {
|
|
374
|
-
input_tokens: Math.max(0, prompt - cacheRead),
|
|
375
|
-
output_tokens: usage?.completion_tokens ?? 0,
|
|
376
|
-
// This family bills nothing for a cache write and reports no count for
|
|
377
|
-
// one. Zero is the actual value, not a missing measurement.
|
|
378
|
-
cache_creation_input_tokens: 0,
|
|
379
|
-
cache_read_input_tokens: cacheRead,
|
|
380
|
-
node,
|
|
381
|
-
ms,
|
|
382
|
-
},
|
|
383
|
-
};
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
/** An API error that carries its status, so the retry layer can read it. */
|
|
387
|
-
/**
|
|
388
|
-
* A failure the server reported after answering 200, as an error object in
|
|
389
|
-
* the stream. It has no HTTP status, so retry.ts decides from `code` (the
|
|
390
|
-
* provider's error type) and the message whether it is worth another attempt.
|
|
391
|
-
*/
|
|
392
|
-
export class StreamError extends Error {
|
|
393
|
-
readonly code: string | undefined;
|
|
394
|
-
constructor(message: string, code?: string) {
|
|
395
|
-
super(message);
|
|
396
|
-
this.name = "StreamError";
|
|
397
|
-
this.code = code;
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
export class HttpError extends Error {
|
|
402
|
-
readonly status: number;
|
|
403
|
-
readonly headers: Headers;
|
|
404
|
-
|
|
405
|
-
constructor(status: number, headers: Headers, message: string) {
|
|
406
|
-
super(message);
|
|
407
|
-
this.name = "HttpError";
|
|
408
|
-
this.status = status;
|
|
409
|
-
this.headers = headers;
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
export class OpenAICompletionsProvider implements Provider {
|
|
414
|
-
readonly config: ProviderConfig;
|
|
415
|
-
private readonly apiKey: string;
|
|
416
|
-
private readonly fetchImpl: typeof fetch;
|
|
417
|
-
private readonly connections = new ConnectionReuse();
|
|
418
|
-
private readonly retry: RetryPolicy;
|
|
419
|
-
private readonly onRetry: ((attempt: number, delayMs: number, error: unknown) => void) | undefined;
|
|
420
|
-
private readonly streamIdleMs: number | undefined;
|
|
421
|
-
|
|
422
|
-
constructor(
|
|
423
|
-
config: ProviderConfig,
|
|
424
|
-
apiKey: string,
|
|
425
|
-
options: {
|
|
426
|
-
fetchImpl?: typeof fetch;
|
|
427
|
-
retry?: RetryPolicy;
|
|
428
|
-
onRetry?: (attempt: number, delayMs: number, error: unknown) => void;
|
|
429
|
-
/** Silence after which one attempt is abandoned; tests shorten it (stream-idle.ts). */
|
|
430
|
-
streamIdleMs?: number;
|
|
431
|
-
} = {},
|
|
432
|
-
) {
|
|
433
|
-
this.config = config;
|
|
434
|
-
this.apiKey = apiKey;
|
|
435
|
-
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
436
|
-
this.retry = options.retry ?? DEFAULT_RETRY;
|
|
437
|
-
this.onRetry = options.onRetry;
|
|
438
|
-
this.streamIdleMs = options.streamIdleMs;
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
send(
|
|
442
|
-
frozen: FrozenPrefix,
|
|
443
|
-
messages: readonly Message[],
|
|
444
|
-
node: number,
|
|
445
|
-
signal?: AbortSignal,
|
|
446
|
-
onDelta?: OnDelta,
|
|
447
|
-
options?: ProviderSendOptions,
|
|
448
|
-
): Promise<Turn> {
|
|
449
|
-
// The clock starts inside the retried request, so a reported duration is
|
|
450
|
-
// one attempt rather than the sum of the ones that failed.
|
|
451
|
-
return withRetry(
|
|
452
|
-
() => watchIdle(signal, this.streamIdleMs, idle => this.attempt(frozen, messages, node, idle, onDelta, options)).catch((error: unknown) => { this.connections.note(error); throw error; }),
|
|
453
|
-
this.retry,
|
|
454
|
-
undefined,
|
|
455
|
-
(attempt, delayMs, error) => {
|
|
456
|
-
onDelta?.({ kind: "discard" });
|
|
457
|
-
onDelta?.({ kind: "retry", attempt, delayMs, max: this.retry.maxRetries, reason: retryLabel(error) });
|
|
458
|
-
this.onRetry?.(attempt, delayMs, error);
|
|
459
|
-
},
|
|
460
|
-
signal,
|
|
461
|
-
);
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
private async attempt(
|
|
465
|
-
frozen: FrozenPrefix,
|
|
466
|
-
messages: readonly Message[],
|
|
467
|
-
node: number,
|
|
468
|
-
idle: IdleWatch,
|
|
469
|
-
onDelta?: OnDelta,
|
|
470
|
-
options?: ProviderSendOptions,
|
|
471
|
-
): Promise<Turn> {
|
|
472
|
-
const started = Date.now();
|
|
473
|
-
const baseUrl = this.config.spec.baseUrl;
|
|
474
|
-
if (baseUrl === undefined) {
|
|
475
|
-
throw new Error(`model ${this.config.spec.id} has no baseUrl to send to`);
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
const compat = this.config.spec.compat ?? DEFAULT_COMPAT;
|
|
479
|
-
const payload: WireRequest & {
|
|
480
|
-
stream: true;
|
|
481
|
-
stream_options?: { include_usage: true };
|
|
482
|
-
} = { ...buildRequest(this.config, frozen, messages), stream: true };
|
|
483
|
-
if (options?.toolUse === "disabled") payload.tool_choice = "none";
|
|
484
|
-
// Without include_usage an OpenAI-dialect stream never reports usage, and
|
|
485
|
-
// the loop would treat the resulting zeros as a real prompt size. Servers
|
|
486
|
-
// that 400 on the field opt out via Compat.supportsUsageInStreaming.
|
|
487
|
-
if (compat.supportsUsageInStreaming) {
|
|
488
|
-
payload.stream_options = { include_usage: true };
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
const init: RequestInit = {
|
|
492
|
-
method: "POST",
|
|
493
|
-
headers: {
|
|
494
|
-
"content-type": "application/json",
|
|
495
|
-
authorization: `Bearer ${this.apiKey}`,
|
|
496
|
-
},
|
|
497
|
-
body: JSON.stringify(payload),
|
|
498
|
-
signal: idle.signal,
|
|
499
|
-
};
|
|
500
|
-
|
|
501
|
-
const response = await this.fetchImpl(`${baseUrl.replace(/\/$/, "")}/chat/completions`, this.connections.init(init));
|
|
502
|
-
|
|
503
|
-
if (!response.ok) {
|
|
504
|
-
const text = await response.text();
|
|
505
|
-
throw new HttpError(response.status, response.headers, errorMessage(response.status, text));
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
if (response.body === null) {
|
|
509
|
-
throw new Error(`${baseUrl} returned a streaming 200 with no body`);
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
const assembled = await readCompletionsSse(idle.body(response.body), onDelta);
|
|
513
|
-
return coherentTurn(parseResponse(assembled, node, Date.now() - started), assembled.usage !== undefined);
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
function errorMessage(status: number, text: string): string {
|
|
518
|
-
try {
|
|
519
|
-
const parsed = JSON.parse(text) as { error?: { message?: string } };
|
|
520
|
-
const detail = parsed.error?.message;
|
|
521
|
-
if (typeof detail === "string" && detail.length > 0) return `HTTP ${status}: ${detail}`;
|
|
522
|
-
} catch {
|
|
523
|
-
// Fall through to the raw body.
|
|
524
|
-
}
|
|
525
|
-
return `HTTP ${status}: ${text.slice(0, 200)}`;
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
/**
|
|
529
|
-
* Incremental SSE decoder. A TCP chunk is not a frame: the last line of one
|
|
530
|
-
* read is often the first half of the next, and parsing each read as JSON
|
|
531
|
-
* is how a valid stream becomes "non-JSON 200".
|
|
532
|
-
*
|
|
533
|
-
* Ported from pi (earendil-works/pi, MIT) — packages/ai/src/api/anthropic-messages.ts
|
|
534
|
-
* (line-split / half-frame handling). The `data:` / `[DONE]` dialect is ours.
|
|
535
|
-
*/
|
|
536
|
-
export function pushSse(buffer: string, chunk: string): { buffer: string; payloads: string[] } {
|
|
537
|
-
buffer += chunk;
|
|
538
|
-
const payloads: string[] = [];
|
|
539
|
-
for (;;) {
|
|
540
|
-
const nl = buffer.search(/\r\n|\n|\r/);
|
|
541
|
-
if (nl < 0) break;
|
|
542
|
-
const crlf = buffer.startsWith("\r\n", nl) ? 2 : 1;
|
|
543
|
-
const line = buffer.slice(0, nl);
|
|
544
|
-
buffer = buffer.slice(nl + crlf);
|
|
545
|
-
if (line.length === 0 || line.startsWith(":")) continue;
|
|
546
|
-
if (line.startsWith("data:")) {
|
|
547
|
-
payloads.push(line.startsWith("data: ") ? line.slice(6) : line.slice(5));
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
return { buffer, payloads };
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
interface StreamAcc {
|
|
554
|
-
text: string;
|
|
555
|
-
thinking: string;
|
|
556
|
-
details: unknown[];
|
|
557
|
-
finishReason: string | null;
|
|
558
|
-
usage: WireResponse["usage"];
|
|
559
|
-
tools: Map<number, { id: string; name: string; arguments: string; extra: Record<string, unknown> }>;
|
|
560
|
-
/** Index of the call a chunk without `index` continues. */
|
|
561
|
-
lastIndex: number;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
function applyCompletionChunk(chunk: WireStreamChunk, acc: StreamAcc, onDelta?: OnDelta): void {
|
|
565
|
-
// A server that fails mid-stream sends an error object instead of a choice.
|
|
566
|
-
// Ignoring it left finish_reason null and the cause invisible -- including
|
|
567
|
-
// an overflow the loop could otherwise recover from.
|
|
568
|
-
if (chunk.error !== undefined) {
|
|
569
|
-
const message = typeof chunk.error.message === "string" ? chunk.error.message : JSON.stringify(chunk.error);
|
|
570
|
-
const code = typeof chunk.error.type === "string" ? chunk.error.type : typeof chunk.error.code === "string" ? chunk.error.code : undefined;
|
|
571
|
-
throw new StreamError(`stream error: ${message}`, code);
|
|
572
|
-
}
|
|
573
|
-
if (chunk.usage !== undefined) acc.usage = chunk.usage;
|
|
574
|
-
const choice = chunk.choices?.[0];
|
|
575
|
-
if (choice === undefined) return;
|
|
576
|
-
if (choice.finish_reason) acc.finishReason = choice.finish_reason;
|
|
577
|
-
const delta = choice.delta;
|
|
578
|
-
if (delta === undefined) return;
|
|
579
|
-
|
|
580
|
-
const reasoning = delta.reasoning_content ?? delta.reasoning;
|
|
581
|
-
if (typeof reasoning === "string" && reasoning.length > 0) {
|
|
582
|
-
acc.thinking += reasoning;
|
|
583
|
-
onDelta?.({ kind: "thinking", text: reasoning });
|
|
584
|
-
}
|
|
585
|
-
if (Array.isArray(delta.reasoning_details)) acc.details.push(...delta.reasoning_details);
|
|
586
|
-
if (typeof delta.content === "string" && delta.content.length > 0) {
|
|
587
|
-
acc.text += delta.content;
|
|
588
|
-
onDelta?.({ kind: "text", text: delta.content });
|
|
589
|
-
}
|
|
590
|
-
for (const call of delta.tool_calls ?? []) {
|
|
591
|
-
// Without an index, a chunk carrying an id the current call does not
|
|
592
|
-
// have starts a new call; one without an id continues the current one.
|
|
593
|
-
// Defaulting every index-less chunk to 0 merged parallel calls into one.
|
|
594
|
-
let index = call.index;
|
|
595
|
-
if (index === undefined) {
|
|
596
|
-
const current = acc.tools.get(acc.lastIndex);
|
|
597
|
-
index = current === undefined ? 0 : call.id && current.id && call.id !== current.id ? acc.lastIndex + 1 : acc.lastIndex;
|
|
598
|
-
}
|
|
599
|
-
acc.lastIndex = index;
|
|
600
|
-
let tool = acc.tools.get(index);
|
|
601
|
-
if (tool === undefined) {
|
|
602
|
-
tool = { id: call.id ?? "", name: call.function?.name ?? "", arguments: "", extra: {} };
|
|
603
|
-
acc.tools.set(index, tool);
|
|
604
|
-
}
|
|
605
|
-
if (call.id) tool.id = call.id;
|
|
606
|
-
if (call.function?.name) tool.name = call.function.name;
|
|
607
|
-
if (call.function?.arguments) tool.arguments += call.function.arguments;
|
|
608
|
-
onDelta?.({ kind: "tool", id: tool.id || String(index), name: tool.name, arguments: tool.arguments });
|
|
609
|
-
Object.assign(tool.extra, extraFields(call as Record<string, unknown>) ?? {});
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
interface WireStreamChunk {
|
|
614
|
-
choices?: {
|
|
615
|
-
delta?: {
|
|
616
|
-
content?: string | null;
|
|
617
|
-
reasoning_content?: string | null;
|
|
618
|
-
reasoning?: string | null;
|
|
619
|
-
reasoning_details?: unknown[];
|
|
620
|
-
tool_calls?: {
|
|
621
|
-
index?: number;
|
|
622
|
-
id?: string;
|
|
623
|
-
function?: { name?: string; arguments?: string };
|
|
624
|
-
}[];
|
|
625
|
-
};
|
|
626
|
-
finish_reason?: string | null;
|
|
627
|
-
}[];
|
|
628
|
-
usage?: WireResponse["usage"];
|
|
629
|
-
error?: { message?: unknown; type?: unknown; code?: unknown };
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
async function readCompletionsSse(
|
|
633
|
-
body: ReadableStream<Uint8Array>,
|
|
634
|
-
onDelta: OnDelta | undefined,
|
|
635
|
-
): Promise<WireResponse> {
|
|
636
|
-
const acc: StreamAcc = {
|
|
637
|
-
text: "",
|
|
638
|
-
thinking: "",
|
|
639
|
-
details: [],
|
|
640
|
-
finishReason: null,
|
|
641
|
-
usage: undefined,
|
|
642
|
-
tools: new Map(),
|
|
643
|
-
lastIndex: 0,
|
|
644
|
-
};
|
|
645
|
-
const reader = body.getReader();
|
|
646
|
-
const decoder = new TextDecoder();
|
|
647
|
-
let buffer = "";
|
|
648
|
-
try {
|
|
649
|
-
while (true) {
|
|
650
|
-
const { value, done } = await reader.read();
|
|
651
|
-
const piece = decoder.decode(value ?? new Uint8Array(), { stream: !done });
|
|
652
|
-
const pushed = pushSse(buffer, piece);
|
|
653
|
-
buffer = pushed.buffer;
|
|
654
|
-
for (const payload of pushed.payloads) {
|
|
655
|
-
if (payload === "[DONE]") return toWireResponse(acc);
|
|
656
|
-
if (payload.length === 0) continue;
|
|
657
|
-
applyCompletionChunk(JSON.parse(payload) as WireStreamChunk, acc, onDelta);
|
|
658
|
-
}
|
|
659
|
-
if (done) break;
|
|
660
|
-
}
|
|
661
|
-
for (const payload of pushSse(buffer, "\n").payloads) {
|
|
662
|
-
if (payload === "[DONE]") break;
|
|
663
|
-
if (payload.length === 0) continue;
|
|
664
|
-
applyCompletionChunk(JSON.parse(payload) as WireStreamChunk, acc, onDelta);
|
|
665
|
-
}
|
|
666
|
-
} finally {
|
|
667
|
-
reader.releaseLock();
|
|
668
|
-
}
|
|
669
|
-
return toWireResponse(acc);
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
function toWireResponse(acc: StreamAcc): WireResponse {
|
|
673
|
-
const tools = [...acc.tools.entries()].sort(([a], [b]) => a - b).map(([, tool]) => tool);
|
|
674
|
-
const response: WireResponse = {
|
|
675
|
-
choices: [
|
|
676
|
-
{
|
|
677
|
-
message: {
|
|
678
|
-
content: acc.text.length > 0 ? acc.text : null,
|
|
679
|
-
...(acc.thinking.length > 0 ? { reasoning_content: acc.thinking } : {}),
|
|
680
|
-
...(acc.details.length > 0 ? { reasoning_details: acc.details } : {}),
|
|
681
|
-
...(tools.length > 0
|
|
682
|
-
? {
|
|
683
|
-
tool_calls: tools.map((t) => ({
|
|
684
|
-
...t.extra,
|
|
685
|
-
id: t.id,
|
|
686
|
-
function: { name: t.name, arguments: t.arguments },
|
|
687
|
-
})),
|
|
688
|
-
}
|
|
689
|
-
: {}),
|
|
690
|
-
},
|
|
691
|
-
finish_reason: acc.finishReason,
|
|
692
|
-
},
|
|
693
|
-
],
|
|
694
|
-
};
|
|
695
|
-
if (acc.usage !== undefined) response.usage = acc.usage;
|
|
696
|
-
return response;
|
|
697
|
-
}
|