@nylorun/harness 0.24.0-beta → 0.25.1-beta
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 +31 -0
- package/HOST_CONTRACT.md +2 -2
- package/README.md +6 -1
- package/dist/index.d.ts +0 -1
- package/dist/run/durable.js +1 -1
- package/package.json +2 -6
- package/dist/loop/model/adapters.d.ts +0 -162
- package/dist/loop/model/adapters.js +0 -557
- package/dist/loop/model/prepared.d.ts +0 -16
- package/dist/loop/model/prepared.js +0 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.25.1-beta
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Pin core to the tested release.
|
|
8
|
+
- Updated dependencies [212364b]
|
|
9
|
+
- @nylorun/core@0.19.0-beta
|
|
10
|
+
|
|
11
|
+
## 0.25.0-beta
|
|
12
|
+
|
|
13
|
+
### Major Changes
|
|
14
|
+
|
|
15
|
+
- 417f336: **The harness has no provider adapters.** The harness makes no model call: it builds the provider-neutral `ModelCall` and reads back a `ModelCandidate`, and the Runtime's Model Gate makes the provider call. MIGRATION.md ("The harness has no provider adapters") has the details.
|
|
16
|
+
|
|
17
|
+
- **Breaking (`@nylorun/harness`): the `./model/adapters` subpath is removed**, with the OpenAI Chat Completions, OpenAI Responses and Anthropic Messages translators in it (`toChatCompletions`, `fromChatCompletions`, `chatCompletionsAdapter`, `toResponses`, `fromResponses`, `responsesAdapter`, `toMessages`, `fromMessages`, `anthropicAdapter`, their request and message types, `AnthropicAdapterOptions`, `AdapterSend`) and `preparedModel`. The package root no longer exports `PreparedModelOptions`. A host that runs the engine in process passes its own `onModelCall` (the Runtime's `piModel`, or its own provider mapping) and reports the provider request with `context.reportPreparedCall({ adapter, call })`, as `preparedModel()` did. Nothing changes on the wire, in manifests or in checkpoints.
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- 6fecd4c: **Docs: who journals effects.** `HOST_CONTRACT.md` no longer says Restate journals effect boundaries. The Runtime journals each effect in the Session Store under the advance's lease, and Durable Session Execution (Restate) only runs one advance per session at a time and delivers wakes and timers.
|
|
22
|
+
- 070674d: **One source of truth for the manifest and Harness API schemas.**
|
|
23
|
+
|
|
24
|
+
- `@nylorun/core`: `Agent.from` (`agentFrom`) checks a manifest with `AgentManifestSchema`, the Runtime's own check, instead of a validator of its own, and refuses with `agent.build-failed` and the schema's messages (each prefixed with its path, such as `capabilities.0.tools.0.name: …`). It now refuses what the Runtime refuses at registration and it let through, such as unknown fields (it dropped them) or a tool or MCP server name that not every model provider accepts. The schema names a top-level `model` or `schemaVersion` and a capability's `model` as before, and the skill whose `files` are wrong (`Skill 'triage' files must include SKILL.md`). The rebuilt manifest is a frozen copy; the object passed in is no longer frozen. `AgentManifestSchema` and `WorkflowManifestSchema` are no longer force-cast to their types: the build checks that each accepts exactly `AgentManifest` and `WorkflowManifest`. `@nylorun/core/contracts` exports `McpServerManifestSchema`, `HEADER_NAME_PATTERN` and `LOOPBACK_HOSTS`. The Harness API's types (`@nylorun/core/harness-api`) are inferred from the schemas that validate its frames, so they match them: `TurnStart.manifest`, `TurnStart.checkpoint` and `RunRouting.rootManifest` are `object`, `WorkspaceCall.tool` is a sandbox tool name, `ABORT_REASONS` is a tuple, and properties are no longer `readonly` (arrays that were stay so).
|
|
25
|
+
- `@nylorun/harness`: `runDurable` checks the manifest once, when it rebuilds the agent, instead of twice. The unpublished, stale `schemas/manifest.schema.json` (manifest `schemaVersion` 2) is gone; `z.toJSONSchema(AgentManifestSchema)` is the manifest's JSON Schema.
|
|
26
|
+
- `@nylorun/agents`: a plugin's MCP servers are checked with core's `McpServerManifestSchema`, header-name pattern and loopback hosts. A server whose key is not a name every model provider accepts is skipped with a `plugin.mcp-server-skipped` warning, since the Runtime would refuse the manifest declaring it.
|
|
27
|
+
- `@nylorun/runtime`: the stack configuration reads its four listeners (`NYLORUN_LISTEN_*`, `NYLORUN_GATES_LISTEN_*`, `NYLORUN_HARNESS_LISTEN_*`, `NYLORUN_EGRESS_LISTEN_*`) with one parser; the variables and their errors are unchanged.
|
|
28
|
+
|
|
29
|
+
- Pin core to the tested release.
|
|
30
|
+
- Updated dependencies [7780b2f]
|
|
31
|
+
- Updated dependencies [070674d]
|
|
32
|
+
- @nylorun/core@0.18.0-beta
|
|
33
|
+
|
|
3
34
|
## 0.24.0-beta
|
|
4
35
|
|
|
5
36
|
### Minor Changes
|
package/HOST_CONTRACT.md
CHANGED
|
@@ -44,7 +44,7 @@ Persist checkpoint BEFORE scheduling, effect intent BEFORE provider invocation o
|
|
|
44
44
|
|
|
45
45
|
A terminal/paused result includes `result.state`. Save it. A new message uses a new turnId with prior completed state. Approval/response resumes paused state via a new checkpoint, same turnId, `segment + 1`, with `{kind:'approve',interactionId,approved}` or `{kind:'respond',interactionId,value}`. An action result simply reruns the SAME suspended checkpoint/segment after recording the outcome. `runDurable({yieldAfter: {steps, ms}})` lets a long turn end a segment at a step boundary with status `yielded` (Model Calls §10): the result state is mid-turn (status `active`, `turn` kept); save it, write a new checkpoint for the same turnId at `segment + 1` with input `{kind:'continue'}`, and schedule it. A yielded segment emits no `turn.*` event, and its effects are never read again. Paused plan records pending interactions/deferred calls; waiting on remote action is distinct from a human wait. Cancellation is host-owned and must fence both running and pending work. Runtime supplies canonical events; execution observations are not wire events and reconstruction must not republish duplicate history.
|
|
46
46
|
|
|
47
|
-
Host resolveEffect must bind the effect ID to the original request and reject drift. Intent/outcome, checkpoint settlement and canonical event/outbox writes must use runtime transactions.
|
|
47
|
+
Host resolveEffect must bind the effect ID to the original request and reject drift. Intent/outcome, checkpoint settlement and canonical event/outbox writes must use runtime transactions. The Runtime journals individual effect boundaries, not the loop, in the Session Store under the advance's lease; Durable Session Execution (Restate) only runs one advance per session at a time and delivers wakes and timers, and journals no effects. Scheduling, storage, publication, delivery policy and reconciliation remain runtime-owned.
|
|
48
48
|
|
|
49
49
|
Agents used as tools: a manifest tool with an `agent` body (the child manifest inlined; name equals the child id, description equals the child description, input is the standard `{task}` schema, no outputSchema, no nested agent tools, identical sandbox specs across the tree — in a session opened with a sandbox the Runtime adds the same `nylorun.sandbox` capability to the root and each inlined child) is run by the engine inside the parent's `runDurable`. Its model and tool effects carry `agent: {id, path, delegationId}` (`delegationId` is the parent tool call's invocationId), keep the root `agentId` and `manifestHash`, and use identity `<delegationId>/<inner identity>`; tool context `idempotencyKey` is prefixed the same way. Hosts resolve child effects against the child manifest (`delegateManifest`) for pinned tool schemas, sandbox and MCP routing, and include `agent` in `tool.completed` payloads. A `delegation` effect (identity `<delegationId>:started` or `<delegationId>:settled`, input `{task}` or `{status, outcome}`) must be recorded completed immediately with value null and publish `delegation.started` / `delegation.completed` exactly once; the journal makes replays silent. `DurableSessionTool.agentId` attaches discovered MCP tools to a child; MCP snapshot records and diagnostics carry `agentId`. Children share the session sandbox. `GET /v1/sessions/:id/items?agent=` filters history by `payload.agent.delegationId` or `payload.agent.path`. Existing checkpoints are unaffected; engine version stays `hosted-2`. A tool whose `agent` body is a flow agent (workflow manifest v3) is not run in-process: the engine issues one `agent` effect (identity `<delegationId>:flow`, input `{agentId, input: task, path}`, context `{role: "delegate", delegationId}`, `agent` ref set) between the `delegation` start and settle points. The host starts a linked flow session from the pinned parent manifest's inlined flow (session id `derive(parentSessionId, path, "delegate", delegationId)`), sends the task as its message, and completes the effect with the flow's output, or `{kind: "failed", code, message}`, when its turn ends. Cancelling the parent cascades to linked sessions.
|
|
50
50
|
|
|
@@ -62,7 +62,7 @@ Frames: `{t:"req",id,m,p}`, `{t:"res",id,ok,r|e:{code,message}}`, `{t:"msg",m,p}
|
|
|
62
62
|
|
|
63
63
|
- **Work.** `hello` → `{api, sandbox:{backend}, renewEveryMs}`. A harness keeps one `lease` waiting; an advance that took a session's lease offers its segment, and the answer is `{run: {runId, sessionId, turnId, epoch, token?, tokenExpiresAt?}, input: TurnStart}`. A run is bound to the connection that leased it. `lease.renew` every `renewEveryMs` renews the session's ownership lease (`{ok:false}`: lost, abort with `ownership.lost`); `lease.release{reason}` gives the run back (`shutdown`, `ownership.lost`; a lost connection counts as `connection.lost`).
|
|
64
64
|
- **Input.** `TurnStart` (`type` `turn.start`, or `approval.answer` for approve/respond): `engine` (`agent` | `flow`), the turn's `manifest`, the segment's `checkpoint` with an empty transcript, `sessionTools`, the segment's completed `outcomes` (`{effectId, requestHash, outcome}`), `transcript.cursor`, `options` (`yieldAfter`, `flowLimits`, `fixtureModel`) and `routing` (root manifest, plugin roots, MCP snapshot, sandbox owner). Core aborts a run with `cancel{runId, reason, message}`, `reason` one of `cancel`, `shutdown`, `deadline`, `ownership.lost`.
|
|
65
|
-
- **Record.** `requestHash = sha256(canonical(requestIdentity(effect)))` (canonical JSON: keys by code unit, `undefined` dropped; a delegation's identity leaves out `context`). An effect in `outcomes` with the same hash resolves in the harness; another hash is drift. Any other effect is an `effect.intent{effect, requestHash}`: a model intent carries no `input`, so a prompt never crosses twice. Core journals the row with `requestHash` (a model row without `input`) and answers `completed`, `pending`, `uncertain`, or `execute` (`rejoin` for a call its gate recovers, P1.2/F4.1). The harness
|
|
65
|
+
- **Record.** `requestHash = sha256(canonical(requestIdentity(effect)))` (canonical JSON: keys by code unit, `undefined` dropped; a delegation's identity leaves out `context`). An effect in `outcomes` with the same hash resolves in the harness; another hash is drift. Any other effect is an `effect.intent{effect, requestHash}`: a model intent carries no `input`, so a prompt never crosses twice. Core journals the row with `requestHash` (a model row without `input`) and answers `completed`, `pending`, `uncertain`, or `execute` (`rejoin` for a call its gate recovers, P1.2/F4.1). The harness runs model, MCP, HTTP and sandbox calls through the executors it is given (a model call reaches its provider through the Runtime's Model Gate, never from the harness) and reports `effect.outcome{value}` or `{error}` (uncertain); after a `shutdown` a recoverable call reports nothing and stays `invoking`. Core runs flow work, linked sessions, delegation journaling and its built-in tools, and fails a tool that would run the developer's code (`tool.unavailable`). Rows written before carry their full request and are hashed on read.
|
|
66
66
|
- **Transcript.** The cursor is the record seq of the last `transcript.updated`, `turn.cancelled` or `turn.failed`. A harness resumes from its cached transcript at that cursor, else reads it once (`transcript.read`). Outputs carry the agent's state without its transcript plus the `TranscriptUpdate[]` from the transcript the segment started with; core records them and answers with the new cursor.
|
|
67
67
|
- **Output.** `turn.completed`, `turn.paused`, `turn.waiting{status, effectIds}`, `turn.failed{status, error}` or `{thrown}`, and `checkpoint` for a yielded segment; answered `{cursor?}` once core settled it, idempotent per run and type. Core settles them exactly as the engine's own results, classifying aborts from its own signal.
|
|
68
68
|
|
package/README.md
CHANGED
|
@@ -5,10 +5,15 @@ contracts live in `@nylorun/core`; applications use `@nylorun/agents`.
|
|
|
5
5
|
OSS publishes harness for local Runtime; Cloud installs published packages from
|
|
6
6
|
npm independently.
|
|
7
7
|
|
|
8
|
-
Use `/run` for explicit execution, `/
|
|
8
|
+
Use `/run` for explicit execution, `/api` for a harness over the Harness API,
|
|
9
9
|
and `/compatibility` for checkpoint compatibility. Definitions and protocol
|
|
10
10
|
schemas are no longer harness exports.
|
|
11
11
|
|
|
12
|
+
The harness makes no model call. Each step projects a provider-neutral `ModelCall`
|
|
13
|
+
(`@nylorun/core/define`) and hands it to its host: to `onModelCall` with `run`, or
|
|
14
|
+
as a model effect with `runDurable` and `/api`. The Runtime's Model Gate makes the
|
|
15
|
+
provider call.
|
|
16
|
+
|
|
12
17
|
> **DX v5.6:** definition ⊥ engine. `model` is not on `Agent({})` — Runtime injects `onModelCall`. Host data stays `info` (not `user`); session memory is `state`.
|
|
13
18
|
|
|
14
19
|
## Compose an agent
|
package/dist/index.d.ts
CHANGED
package/dist/run/durable.js
CHANGED
|
@@ -28,8 +28,8 @@ export function createDurableCheckpoint(input) {
|
|
|
28
28
|
* Returning waiting releases all execution stacks; no process-local continuation survives.
|
|
29
29
|
*/
|
|
30
30
|
export async function runDurable(options) {
|
|
31
|
+
// `hostedDefinition` checks the manifest against AgentManifestSchema (`agentFrom`).
|
|
31
32
|
const { manifest, checkpoint, host } = options;
|
|
32
|
-
AgentManifestSchema.parse(manifest);
|
|
33
33
|
if (checkpoint.version !== CHECKPOINT_VERSION ||
|
|
34
34
|
checkpoint.engineVersion !== ENGINE_VERSION ||
|
|
35
35
|
checkpoint.manifestHash !== hashManifest(manifest))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nylorun/harness",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.1-beta",
|
|
4
4
|
"description": "Nylorun's TypeScript agent execution engine. See github.com/nylorun/agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -36,10 +36,6 @@
|
|
|
36
36
|
"types": "./dist/api/index.d.ts",
|
|
37
37
|
"import": "./dist/api/index.js"
|
|
38
38
|
},
|
|
39
|
-
"./model/adapters": {
|
|
40
|
-
"types": "./dist/loop/model/adapters.d.ts",
|
|
41
|
-
"import": "./dist/loop/model/adapters.js"
|
|
42
|
-
},
|
|
43
39
|
"./compatibility": {
|
|
44
40
|
"types": "./dist/compatibility.d.ts",
|
|
45
41
|
"import": "./dist/compatibility.js"
|
|
@@ -81,7 +77,7 @@
|
|
|
81
77
|
"zod": "^4.6.5"
|
|
82
78
|
},
|
|
83
79
|
"dependencies": {
|
|
84
|
-
"@nylorun/core": "0.
|
|
80
|
+
"@nylorun/core": "0.19.0-beta"
|
|
85
81
|
},
|
|
86
82
|
"peerDependencies": {
|
|
87
83
|
"zod": "^4.6.5"
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
import type { ModelAdapter, ModelAdapterContext, ModelCall, ModelCandidate } from "@nylorun/core/define";
|
|
2
|
-
import type { JsonObject } from "@nylorun/core/define";
|
|
3
|
-
import { preparedModel } from "./prepared.js";
|
|
4
|
-
export { preparedModel };
|
|
5
|
-
export type ChatCompletionsMessage = {
|
|
6
|
-
readonly role: "system";
|
|
7
|
-
readonly content: string;
|
|
8
|
-
} | {
|
|
9
|
-
readonly role: "user";
|
|
10
|
-
readonly content: string | readonly ChatCompletionsContentPart[];
|
|
11
|
-
} | {
|
|
12
|
-
readonly role: "assistant";
|
|
13
|
-
readonly content: string | null;
|
|
14
|
-
readonly tool_calls?: readonly ChatCompletionsToolCall[];
|
|
15
|
-
} | {
|
|
16
|
-
readonly role: "tool";
|
|
17
|
-
readonly tool_call_id: string;
|
|
18
|
-
readonly content: string;
|
|
19
|
-
};
|
|
20
|
-
export type ChatCompletionsContentPart = {
|
|
21
|
-
readonly type: "text";
|
|
22
|
-
readonly text: string;
|
|
23
|
-
} | {
|
|
24
|
-
readonly type: "image_url";
|
|
25
|
-
readonly image_url: Readonly<{
|
|
26
|
-
url: string;
|
|
27
|
-
}>;
|
|
28
|
-
};
|
|
29
|
-
export interface ChatCompletionsToolCall {
|
|
30
|
-
readonly id: string;
|
|
31
|
-
readonly type: "function";
|
|
32
|
-
readonly function: Readonly<{
|
|
33
|
-
name: string;
|
|
34
|
-
arguments: string;
|
|
35
|
-
}>;
|
|
36
|
-
}
|
|
37
|
-
export interface ChatCompletionsRequest {
|
|
38
|
-
readonly messages: readonly ChatCompletionsMessage[];
|
|
39
|
-
readonly tools?: readonly Readonly<{
|
|
40
|
-
type: "function";
|
|
41
|
-
function: Readonly<{
|
|
42
|
-
name: string;
|
|
43
|
-
description?: string;
|
|
44
|
-
parameters: JsonObject;
|
|
45
|
-
}>;
|
|
46
|
-
}>[];
|
|
47
|
-
readonly temperature?: number;
|
|
48
|
-
readonly max_completion_tokens?: number;
|
|
49
|
-
readonly response_format?: Readonly<{
|
|
50
|
-
type: "json_schema";
|
|
51
|
-
json_schema: Readonly<{
|
|
52
|
-
name: string;
|
|
53
|
-
schema: JsonObject;
|
|
54
|
-
}>;
|
|
55
|
-
}>;
|
|
56
|
-
}
|
|
57
|
-
export interface ResponsesRequest {
|
|
58
|
-
readonly instructions?: string;
|
|
59
|
-
readonly input: readonly ResponsesInputItem[];
|
|
60
|
-
readonly tools?: readonly Readonly<{
|
|
61
|
-
type: "function";
|
|
62
|
-
name: string;
|
|
63
|
-
description?: string;
|
|
64
|
-
parameters: JsonObject;
|
|
65
|
-
}>[];
|
|
66
|
-
readonly temperature?: number;
|
|
67
|
-
readonly max_output_tokens?: number;
|
|
68
|
-
readonly text?: Readonly<{
|
|
69
|
-
format: Readonly<{
|
|
70
|
-
type: "json_schema";
|
|
71
|
-
name: string;
|
|
72
|
-
schema: JsonObject;
|
|
73
|
-
}>;
|
|
74
|
-
}>;
|
|
75
|
-
}
|
|
76
|
-
export type ResponsesInputItem = {
|
|
77
|
-
readonly type: "message";
|
|
78
|
-
readonly role: "user" | "assistant";
|
|
79
|
-
readonly content: string | readonly ResponsesContentPart[];
|
|
80
|
-
} | {
|
|
81
|
-
readonly type: "function_call";
|
|
82
|
-
readonly call_id: string;
|
|
83
|
-
readonly name: string;
|
|
84
|
-
readonly arguments: string;
|
|
85
|
-
} | {
|
|
86
|
-
readonly type: "function_call_output";
|
|
87
|
-
readonly call_id: string;
|
|
88
|
-
readonly output: string;
|
|
89
|
-
};
|
|
90
|
-
export type ResponsesContentPart = {
|
|
91
|
-
readonly type: "input_text";
|
|
92
|
-
readonly text: string;
|
|
93
|
-
} | {
|
|
94
|
-
readonly type: "input_image";
|
|
95
|
-
readonly image_url: string;
|
|
96
|
-
};
|
|
97
|
-
export interface MessagesRequest {
|
|
98
|
-
readonly system?: string;
|
|
99
|
-
readonly messages: readonly MessagesMessage[];
|
|
100
|
-
readonly tools?: readonly Readonly<{
|
|
101
|
-
name: string;
|
|
102
|
-
description?: string;
|
|
103
|
-
input_schema: JsonObject;
|
|
104
|
-
}>[];
|
|
105
|
-
readonly temperature?: number;
|
|
106
|
-
readonly max_tokens: number;
|
|
107
|
-
}
|
|
108
|
-
export type MessagesMessage = {
|
|
109
|
-
readonly role: "user";
|
|
110
|
-
readonly content: string | readonly (MessagesToolResult | MessagesUserContentPart)[];
|
|
111
|
-
} | {
|
|
112
|
-
readonly role: "assistant";
|
|
113
|
-
readonly content: readonly MessagesAssistantPart[];
|
|
114
|
-
};
|
|
115
|
-
export type MessagesAssistantPart = {
|
|
116
|
-
readonly type: "text";
|
|
117
|
-
readonly text: string;
|
|
118
|
-
} | {
|
|
119
|
-
readonly type: "tool_use";
|
|
120
|
-
readonly id: string;
|
|
121
|
-
readonly name: string;
|
|
122
|
-
readonly input: JsonObject;
|
|
123
|
-
};
|
|
124
|
-
export interface MessagesToolResult {
|
|
125
|
-
readonly type: "tool_result";
|
|
126
|
-
readonly tool_use_id: string;
|
|
127
|
-
readonly content: string;
|
|
128
|
-
readonly is_error?: boolean;
|
|
129
|
-
}
|
|
130
|
-
export type MessagesUserContentPart = {
|
|
131
|
-
readonly type: "text";
|
|
132
|
-
readonly text: string;
|
|
133
|
-
} | {
|
|
134
|
-
readonly type: "image";
|
|
135
|
-
readonly source: Readonly<{
|
|
136
|
-
type: "url";
|
|
137
|
-
url: string;
|
|
138
|
-
}>;
|
|
139
|
-
};
|
|
140
|
-
export type AdapterSend<Request> = (request: Request, call: ModelCall, context: ModelAdapterContext) => Promise<unknown>;
|
|
141
|
-
export interface AnthropicAdapterOptions {
|
|
142
|
-
readonly defaultMaxOutputTokens: number;
|
|
143
|
-
readonly send: AdapterSend<MessagesRequest>;
|
|
144
|
-
}
|
|
145
|
-
/** Translate a Harness call to the OpenAI Chat Completions request shape. */
|
|
146
|
-
export declare function toChatCompletions(call: ModelCall): ChatCompletionsRequest;
|
|
147
|
-
/** Translate a Chat Completions response into a Harness candidate. */
|
|
148
|
-
export declare function fromChatCompletions(value: unknown, call?: Pick<ModelCall, "outputSchema">): ModelCandidate;
|
|
149
|
-
/** Return a Harness adapter backed by an application-owned Chat Completions send function. */
|
|
150
|
-
export declare function chatCompletionsAdapter(send: AdapterSend<ChatCompletionsRequest>): ModelAdapter;
|
|
151
|
-
/** Translate a Harness call to the OpenAI Responses request shape. */
|
|
152
|
-
export declare function toResponses(call: ModelCall): ResponsesRequest;
|
|
153
|
-
/** Translate an OpenAI Responses response into a Harness candidate. */
|
|
154
|
-
export declare function fromResponses(value: unknown, call?: Pick<ModelCall, "outputSchema">): ModelCandidate;
|
|
155
|
-
/** Return a Harness adapter backed by an application-owned Responses send function. */
|
|
156
|
-
export declare function responsesAdapter(send: AdapterSend<ResponsesRequest>): ModelAdapter;
|
|
157
|
-
/** Translate a Harness call to the Anthropic Messages request shape. */
|
|
158
|
-
export declare function toMessages(call: ModelCall, defaultMaxOutputTokens: number): MessagesRequest;
|
|
159
|
-
/** Translate an Anthropic Messages response into a Harness candidate. */
|
|
160
|
-
export declare function fromMessages(value: unknown): ModelCandidate;
|
|
161
|
-
/** Return a Harness adapter backed by an application-owned Anthropic Messages send function. */
|
|
162
|
-
export declare function anthropicAdapter(options: AnthropicAdapterOptions): ModelAdapter;
|
|
@@ -1,557 +0,0 @@
|
|
|
1
|
-
import { HarnessError } from "@nylorun/core/define";
|
|
2
|
-
import { copyJsonObject } from "@nylorun/core/define";
|
|
3
|
-
import { preparedModel } from "./prepared.js";
|
|
4
|
-
export { preparedModel };
|
|
5
|
-
/** Translate a Harness call to the OpenAI Chat Completions request shape. */
|
|
6
|
-
export function toChatCompletions(call) {
|
|
7
|
-
const messages = withoutProviderReasoning(call.prompt).map((item) => {
|
|
8
|
-
if (item.kind === "instructions")
|
|
9
|
-
return { role: "system", content: textOf(item) };
|
|
10
|
-
if (item.kind === "tool-result")
|
|
11
|
-
return { role: "tool", tool_call_id: item.toolCallId, content: textOf(item) };
|
|
12
|
-
if (item.kind === "message" && item.role === "assistant") {
|
|
13
|
-
const toolCalls = toolCallsOf(item.content).map((part) => ({
|
|
14
|
-
id: part.id,
|
|
15
|
-
type: "function",
|
|
16
|
-
function: { name: part.name, arguments: JSON.stringify(part.args) },
|
|
17
|
-
}));
|
|
18
|
-
const text = textOf(item);
|
|
19
|
-
return {
|
|
20
|
-
role: "assistant",
|
|
21
|
-
content: text === "" ? null : text,
|
|
22
|
-
...(toolCalls.length === 0 ? {} : { tool_calls: toolCalls }),
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
return { role: "user", content: chatContent(item.content) };
|
|
26
|
-
});
|
|
27
|
-
return {
|
|
28
|
-
messages,
|
|
29
|
-
...(call.tools.length === 0
|
|
30
|
-
? {}
|
|
31
|
-
: {
|
|
32
|
-
tools: call.tools.map((tool) => ({
|
|
33
|
-
type: "function",
|
|
34
|
-
function: {
|
|
35
|
-
name: tool.name,
|
|
36
|
-
...(tool.description === undefined ? {} : { description: tool.description }),
|
|
37
|
-
parameters: tool.inputSchema,
|
|
38
|
-
},
|
|
39
|
-
})),
|
|
40
|
-
}),
|
|
41
|
-
...chatControls(call),
|
|
42
|
-
...(call.outputSchema === undefined
|
|
43
|
-
? {}
|
|
44
|
-
: {
|
|
45
|
-
response_format: {
|
|
46
|
-
type: "json_schema",
|
|
47
|
-
json_schema: { name: "harness_output", schema: call.outputSchema },
|
|
48
|
-
},
|
|
49
|
-
}),
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
/** Translate a Chat Completions response into a Harness candidate. */
|
|
53
|
-
export function fromChatCompletions(value, call) {
|
|
54
|
-
const response = record(value, "response");
|
|
55
|
-
const choices = array(response.choices, "response.choices");
|
|
56
|
-
if (choices.length === 0)
|
|
57
|
-
throw invalidResponse("response.choices must contain a choice", "response.choices");
|
|
58
|
-
const choice = record(choices[0], "response.choices[0]");
|
|
59
|
-
const message = record(choice.message, "response.choices[0].message");
|
|
60
|
-
const output = [];
|
|
61
|
-
if (typeof message.content === "string" && message.content !== "")
|
|
62
|
-
output.push(outputText(message.content, call?.outputSchema !== undefined));
|
|
63
|
-
if (typeof message.reasoning_content === "string" && message.reasoning_content !== "")
|
|
64
|
-
output.push({ type: "reasoning", text: message.reasoning_content });
|
|
65
|
-
for (const [index, raw] of optionalArray(message.tool_calls, "response.choices[0].message.tool_calls").entries()) {
|
|
66
|
-
const call = record(raw, `response.choices[0].message.tool_calls[${index}]`);
|
|
67
|
-
const fn = record(call.function, `response.choices[0].message.tool_calls[${index}].function`);
|
|
68
|
-
output.push({
|
|
69
|
-
type: "tool-call",
|
|
70
|
-
id: string(call.id, `response.choices[0].message.tool_calls[${index}].id`),
|
|
71
|
-
name: string(fn.name, `response.choices[0].message.tool_calls[${index}].function.name`),
|
|
72
|
-
...argumentsOf(fn.arguments, `response.choices[0].message.tool_calls[${index}].function.arguments`),
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
return candidate({
|
|
76
|
-
output,
|
|
77
|
-
finishReason: chatFinishReason(choice.finish_reason, output),
|
|
78
|
-
usage: chatUsage(response.usage),
|
|
79
|
-
evidence: evidence(response),
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
/** Return a Harness adapter backed by an application-owned Chat Completions send function. */
|
|
83
|
-
export function chatCompletionsAdapter(send) {
|
|
84
|
-
return preparedModel({
|
|
85
|
-
adapter: "openai.chat-completions",
|
|
86
|
-
async prepare(call) {
|
|
87
|
-
const request = toChatCompletions(call);
|
|
88
|
-
return { request, observed: request };
|
|
89
|
-
},
|
|
90
|
-
send,
|
|
91
|
-
decode: fromChatCompletions,
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
/** Translate a Harness call to the OpenAI Responses request shape. */
|
|
95
|
-
export function toResponses(call) {
|
|
96
|
-
const instructions = call.prompt.filter((item) => item.kind === "instructions").map(textOf);
|
|
97
|
-
const input = withoutProviderReasoning(call.prompt).flatMap((item) => {
|
|
98
|
-
if (item.kind === "instructions")
|
|
99
|
-
return [];
|
|
100
|
-
if (item.kind === "tool-result")
|
|
101
|
-
return [{ type: "function_call_output", call_id: item.toolCallId, output: textOf(item) }];
|
|
102
|
-
if (item.kind === "message" && item.role === "assistant") {
|
|
103
|
-
const text = textOf(item);
|
|
104
|
-
return [
|
|
105
|
-
...(text === ""
|
|
106
|
-
? []
|
|
107
|
-
: [{ type: "message", role: "assistant", content: text }]),
|
|
108
|
-
...toolCallsOf(item.content).map((part) => ({
|
|
109
|
-
type: "function_call",
|
|
110
|
-
call_id: part.id,
|
|
111
|
-
name: part.name,
|
|
112
|
-
arguments: JSON.stringify(part.args),
|
|
113
|
-
})),
|
|
114
|
-
];
|
|
115
|
-
}
|
|
116
|
-
return [{ type: "message", role: "user", content: responsesContent(item.content) }];
|
|
117
|
-
});
|
|
118
|
-
return {
|
|
119
|
-
...(instructions.length === 0 ? {} : { instructions: instructions.join("\n\n") }),
|
|
120
|
-
input,
|
|
121
|
-
...(call.tools.length === 0
|
|
122
|
-
? {}
|
|
123
|
-
: {
|
|
124
|
-
tools: call.tools.map((tool) => ({
|
|
125
|
-
type: "function",
|
|
126
|
-
name: tool.name,
|
|
127
|
-
...(tool.description === undefined ? {} : { description: tool.description }),
|
|
128
|
-
parameters: tool.inputSchema,
|
|
129
|
-
})),
|
|
130
|
-
}),
|
|
131
|
-
...responsesControls(call),
|
|
132
|
-
...(call.outputSchema === undefined
|
|
133
|
-
? {}
|
|
134
|
-
: {
|
|
135
|
-
text: {
|
|
136
|
-
format: {
|
|
137
|
-
type: "json_schema",
|
|
138
|
-
name: "harness_output",
|
|
139
|
-
schema: call.outputSchema,
|
|
140
|
-
},
|
|
141
|
-
},
|
|
142
|
-
}),
|
|
143
|
-
};
|
|
144
|
-
}
|
|
145
|
-
/** Translate an OpenAI Responses response into a Harness candidate. */
|
|
146
|
-
export function fromResponses(value, call) {
|
|
147
|
-
const response = record(value, "response");
|
|
148
|
-
if (response.error !== undefined && response.error !== null)
|
|
149
|
-
throw invalidResponse("response.error is present", "response.error");
|
|
150
|
-
const output = [];
|
|
151
|
-
for (const [index, raw] of array(response.output, "response.output").entries()) {
|
|
152
|
-
const item = record(raw, `response.output[${index}]`);
|
|
153
|
-
if (item.type === "function_call") {
|
|
154
|
-
output.push({
|
|
155
|
-
type: "tool-call",
|
|
156
|
-
id: string(item.call_id, `response.output[${index}].call_id`),
|
|
157
|
-
name: string(item.name, `response.output[${index}].name`),
|
|
158
|
-
...argumentsOf(item.arguments, `response.output[${index}].arguments`),
|
|
159
|
-
});
|
|
160
|
-
continue;
|
|
161
|
-
}
|
|
162
|
-
if (item.type === "message") {
|
|
163
|
-
for (const [partIndex, rawPart] of optionalArray(item.content, `response.output[${index}].content`).entries()) {
|
|
164
|
-
const part = record(rawPart, `response.output[${index}].content[${partIndex}]`);
|
|
165
|
-
if (part.type === "output_text" && typeof part.text === "string")
|
|
166
|
-
output.push(outputText(part.text, call?.outputSchema !== undefined));
|
|
167
|
-
}
|
|
168
|
-
continue;
|
|
169
|
-
}
|
|
170
|
-
if (item.type === "reasoning") {
|
|
171
|
-
const summary = optionalArray(item.summary, `response.output[${index}].summary`)
|
|
172
|
-
.map((rawPart, partIndex) => record(rawPart, `response.output[${index}].summary[${partIndex}]`))
|
|
173
|
-
.filter((part) => part.type === "summary_text" && typeof part.text === "string")
|
|
174
|
-
.map((part) => part.text)
|
|
175
|
-
.join("\n");
|
|
176
|
-
if (summary !== "")
|
|
177
|
-
output.push({ type: "reasoning", text: summary });
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
return candidate({
|
|
181
|
-
output,
|
|
182
|
-
finishReason: responsesFinishReason(response, output),
|
|
183
|
-
usage: responsesUsage(response.usage),
|
|
184
|
-
evidence: evidence(response),
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
/** Return a Harness adapter backed by an application-owned Responses send function. */
|
|
188
|
-
export function responsesAdapter(send) {
|
|
189
|
-
return preparedModel({
|
|
190
|
-
adapter: "openai.responses",
|
|
191
|
-
async prepare(call) {
|
|
192
|
-
const request = toResponses(call);
|
|
193
|
-
return { request, observed: request };
|
|
194
|
-
},
|
|
195
|
-
send,
|
|
196
|
-
decode: fromResponses,
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
/** Translate a Harness call to the Anthropic Messages request shape. */
|
|
200
|
-
export function toMessages(call, defaultMaxOutputTokens) {
|
|
201
|
-
checkedMaxOutputTokens(defaultMaxOutputTokens);
|
|
202
|
-
if (call.outputSchema !== undefined)
|
|
203
|
-
throw new HarnessError("model.unsupported-output-schema", "Anthropic Messages output schemas require a custom prepared adapter");
|
|
204
|
-
const instructions = call.prompt.filter((item) => item.kind === "instructions").map(textOf);
|
|
205
|
-
const messages = withoutProviderReasoning(call.prompt).flatMap((item) => {
|
|
206
|
-
if (item.kind === "instructions")
|
|
207
|
-
return [];
|
|
208
|
-
if (item.kind === "tool-result")
|
|
209
|
-
return [
|
|
210
|
-
{
|
|
211
|
-
role: "user",
|
|
212
|
-
content: [
|
|
213
|
-
{
|
|
214
|
-
type: "tool_result",
|
|
215
|
-
tool_use_id: item.toolCallId,
|
|
216
|
-
content: textOf(item),
|
|
217
|
-
...(item.status === "completed" ? {} : { is_error: true }),
|
|
218
|
-
},
|
|
219
|
-
],
|
|
220
|
-
},
|
|
221
|
-
];
|
|
222
|
-
if (item.kind === "message" && item.role === "assistant")
|
|
223
|
-
return [
|
|
224
|
-
{
|
|
225
|
-
role: "assistant",
|
|
226
|
-
content: item.content.map((part) => {
|
|
227
|
-
if (part.type === "text")
|
|
228
|
-
return { type: "text", text: part.text };
|
|
229
|
-
if (part.type === "tool-call")
|
|
230
|
-
return { type: "tool_use", id: part.id, name: part.name, input: part.args };
|
|
231
|
-
throw unsupportedContent(part);
|
|
232
|
-
}),
|
|
233
|
-
},
|
|
234
|
-
];
|
|
235
|
-
return [{ role: "user", content: messagesContent(item.content) }];
|
|
236
|
-
});
|
|
237
|
-
return {
|
|
238
|
-
...(instructions.length === 0 ? {} : { system: instructions.join("\n\n") }),
|
|
239
|
-
messages,
|
|
240
|
-
...(call.tools.length === 0
|
|
241
|
-
? {}
|
|
242
|
-
: {
|
|
243
|
-
tools: call.tools.map((tool) => ({
|
|
244
|
-
name: tool.name,
|
|
245
|
-
...(tool.description === undefined ? {} : { description: tool.description }),
|
|
246
|
-
input_schema: tool.inputSchema,
|
|
247
|
-
})),
|
|
248
|
-
}),
|
|
249
|
-
...(call.model?.controls?.temperature === undefined
|
|
250
|
-
? {}
|
|
251
|
-
: { temperature: call.model.controls.temperature }),
|
|
252
|
-
max_tokens: call.model?.controls?.maxOutputTokens ?? defaultMaxOutputTokens,
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
function outputText(text, structured) {
|
|
256
|
-
if (!structured)
|
|
257
|
-
return { type: "text", text };
|
|
258
|
-
try {
|
|
259
|
-
return { type: "json", value: JSON.parse(text) };
|
|
260
|
-
}
|
|
261
|
-
catch {
|
|
262
|
-
return { type: "text", text };
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
/** Translate an Anthropic Messages response into a Harness candidate. */
|
|
266
|
-
export function fromMessages(value) {
|
|
267
|
-
const response = record(value, "response");
|
|
268
|
-
const output = [];
|
|
269
|
-
for (const [index, raw] of array(response.content, "response.content").entries()) {
|
|
270
|
-
const part = record(raw, `response.content[${index}]`);
|
|
271
|
-
if (part.type === "text" && typeof part.text === "string") {
|
|
272
|
-
output.push({ type: "text", text: part.text });
|
|
273
|
-
continue;
|
|
274
|
-
}
|
|
275
|
-
if (part.type === "thinking" && typeof part.thinking === "string") {
|
|
276
|
-
output.push({ type: "reasoning", text: part.thinking });
|
|
277
|
-
continue;
|
|
278
|
-
}
|
|
279
|
-
if (part.type === "tool_use") {
|
|
280
|
-
output.push({
|
|
281
|
-
type: "tool-call",
|
|
282
|
-
id: string(part.id, `response.content[${index}].id`),
|
|
283
|
-
name: string(part.name, `response.content[${index}].name`),
|
|
284
|
-
args: jsonObject(part.input, `response.content[${index}].input`),
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
return candidate({
|
|
289
|
-
output,
|
|
290
|
-
finishReason: messagesFinishReason(response.stop_reason, output),
|
|
291
|
-
usage: messagesUsage(response.usage),
|
|
292
|
-
evidence: evidence(response),
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
/** Return a Harness adapter backed by an application-owned Anthropic Messages send function. */
|
|
296
|
-
export function anthropicAdapter(options) {
|
|
297
|
-
checkedMaxOutputTokens(options.defaultMaxOutputTokens);
|
|
298
|
-
return preparedModel({
|
|
299
|
-
adapter: "anthropic.messages",
|
|
300
|
-
async prepare(call) {
|
|
301
|
-
const request = toMessages(call, options.defaultMaxOutputTokens);
|
|
302
|
-
return { request, observed: request };
|
|
303
|
-
},
|
|
304
|
-
send: options.send,
|
|
305
|
-
decode: fromMessages,
|
|
306
|
-
});
|
|
307
|
-
}
|
|
308
|
-
function chatContent(parts) {
|
|
309
|
-
if (!parts.some((part) => part.type === "media"))
|
|
310
|
-
return textOfParts(parts);
|
|
311
|
-
return parts.map((part) => {
|
|
312
|
-
if (part.type === "text")
|
|
313
|
-
return { type: "text", text: part.text };
|
|
314
|
-
if (part.type === "media")
|
|
315
|
-
return { type: "image_url", image_url: { url: imageUrl(part) } };
|
|
316
|
-
throw unsupportedContent(part);
|
|
317
|
-
});
|
|
318
|
-
}
|
|
319
|
-
function responsesContent(parts) {
|
|
320
|
-
if (!parts.some((part) => part.type === "media"))
|
|
321
|
-
return textOfParts(parts);
|
|
322
|
-
return parts.map((part) => {
|
|
323
|
-
if (part.type === "text")
|
|
324
|
-
return { type: "input_text", text: part.text };
|
|
325
|
-
if (part.type === "media")
|
|
326
|
-
return { type: "input_image", image_url: imageUrl(part) };
|
|
327
|
-
throw unsupportedContent(part);
|
|
328
|
-
});
|
|
329
|
-
}
|
|
330
|
-
function messagesContent(parts) {
|
|
331
|
-
if (!parts.some((part) => part.type === "media"))
|
|
332
|
-
return textOfParts(parts);
|
|
333
|
-
return parts.map((part) => {
|
|
334
|
-
if (part.type === "text")
|
|
335
|
-
return { type: "text", text: part.text };
|
|
336
|
-
if (part.type === "media")
|
|
337
|
-
return { type: "image", source: { type: "url", url: imageUrl(part) } };
|
|
338
|
-
throw unsupportedContent(part);
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
function imageUrl(part) {
|
|
342
|
-
if (!part.mediaType.startsWith("image/"))
|
|
343
|
-
throw unsupportedContent(part);
|
|
344
|
-
const reference = part.reference;
|
|
345
|
-
if (!reference || typeof reference !== "object" || Array.isArray(reference))
|
|
346
|
-
throw unsupportedContent(part);
|
|
347
|
-
const url = reference.url;
|
|
348
|
-
if (typeof url !== "string" || url === "")
|
|
349
|
-
throw unsupportedContent(part);
|
|
350
|
-
return url;
|
|
351
|
-
}
|
|
352
|
-
function unsupportedContent(part) {
|
|
353
|
-
const label = part.type === "media" ? part.mediaType : part.type;
|
|
354
|
-
return new HarnessError("model.unsupported-content", `Adapter does not support ${label} content without a custom prepared adapter`);
|
|
355
|
-
}
|
|
356
|
-
function textOf(item) {
|
|
357
|
-
const unsupported = item.content.find((part) => part.type === "media");
|
|
358
|
-
if (unsupported)
|
|
359
|
-
throw unsupportedContent(unsupported);
|
|
360
|
-
return textOfParts(item.content);
|
|
361
|
-
}
|
|
362
|
-
function textOfParts(parts) {
|
|
363
|
-
return parts
|
|
364
|
-
.filter((part) => part.type === "text")
|
|
365
|
-
.map((part) => part.text)
|
|
366
|
-
.join("");
|
|
367
|
-
}
|
|
368
|
-
function toolCallsOf(parts) {
|
|
369
|
-
return parts.filter((part) => part.type === "tool-call");
|
|
370
|
-
}
|
|
371
|
-
function chatControls(call) {
|
|
372
|
-
return {
|
|
373
|
-
...(call.model?.controls?.temperature === undefined
|
|
374
|
-
? {}
|
|
375
|
-
: { temperature: call.model.controls.temperature }),
|
|
376
|
-
...(call.model?.controls?.maxOutputTokens === undefined
|
|
377
|
-
? {}
|
|
378
|
-
: { max_completion_tokens: call.model.controls.maxOutputTokens }),
|
|
379
|
-
};
|
|
380
|
-
}
|
|
381
|
-
function responsesControls(call) {
|
|
382
|
-
return {
|
|
383
|
-
...(call.model?.controls?.temperature === undefined
|
|
384
|
-
? {}
|
|
385
|
-
: { temperature: call.model.controls.temperature }),
|
|
386
|
-
...(call.model?.controls?.maxOutputTokens === undefined
|
|
387
|
-
? {}
|
|
388
|
-
: { max_output_tokens: call.model.controls.maxOutputTokens }),
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
function argumentsOf(value, path) {
|
|
392
|
-
const raw = string(value, path);
|
|
393
|
-
try {
|
|
394
|
-
return { args: jsonObject(JSON.parse(raw), path), raw };
|
|
395
|
-
}
|
|
396
|
-
catch (error) {
|
|
397
|
-
throw invalidResponse(`${path} must be a JSON object`, path, error);
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
function jsonObject(value, path) {
|
|
401
|
-
try {
|
|
402
|
-
return copyJsonObject(value, path);
|
|
403
|
-
}
|
|
404
|
-
catch (error) {
|
|
405
|
-
throw invalidResponse(`${path} must be a JSON object`, path, error);
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
function candidate(value) {
|
|
409
|
-
return {
|
|
410
|
-
output: value.output,
|
|
411
|
-
...(value.finishReason === undefined ? {} : { finishReason: value.finishReason }),
|
|
412
|
-
...(value.usage === undefined ? {} : { usage: value.usage }),
|
|
413
|
-
...(value.evidence === undefined ? {} : { evidence: value.evidence }),
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
function chatFinishReason(value, output) {
|
|
417
|
-
if (value === "tool_calls" || value === "function_call")
|
|
418
|
-
return "tool-calls";
|
|
419
|
-
if (value === "length")
|
|
420
|
-
return "length";
|
|
421
|
-
if (value === "content_filter")
|
|
422
|
-
return "content-filter";
|
|
423
|
-
if (value === "stop" || value === null || value === undefined)
|
|
424
|
-
return hasToolCall(output) ? "tool-calls" : "stop";
|
|
425
|
-
return "other";
|
|
426
|
-
}
|
|
427
|
-
function responsesFinishReason(response, output) {
|
|
428
|
-
if (response.status === "incomplete") {
|
|
429
|
-
const details = response.incomplete_details === undefined
|
|
430
|
-
? undefined
|
|
431
|
-
: record(response.incomplete_details, "response.incomplete_details");
|
|
432
|
-
return details?.reason === "max_output_tokens" ? "length" : "other";
|
|
433
|
-
}
|
|
434
|
-
if (response.status === "failed" || response.status === "cancelled")
|
|
435
|
-
throw invalidResponse(`response.status is ${String(response.status)}`, "response.status");
|
|
436
|
-
return hasToolCall(output) ? "tool-calls" : "stop";
|
|
437
|
-
}
|
|
438
|
-
function messagesFinishReason(value, output) {
|
|
439
|
-
if (value === "tool_use")
|
|
440
|
-
return "tool-calls";
|
|
441
|
-
if (value === "max_tokens")
|
|
442
|
-
return "length";
|
|
443
|
-
if (value === "end_turn" || value === "stop_sequence" || value === undefined || value === null)
|
|
444
|
-
return hasToolCall(output) ? "tool-calls" : "stop";
|
|
445
|
-
return "other";
|
|
446
|
-
}
|
|
447
|
-
function chatUsage(value) {
|
|
448
|
-
const usage = optionalRecord(value, "response.usage");
|
|
449
|
-
if (usage === undefined)
|
|
450
|
-
return undefined;
|
|
451
|
-
return usageOf({
|
|
452
|
-
inputTokens: usage.prompt_tokens,
|
|
453
|
-
outputTokens: usage.completion_tokens,
|
|
454
|
-
totalTokens: usage.total_tokens,
|
|
455
|
-
cachedTokens: optionalRecord(usage.prompt_tokens_details, "response.usage.prompt_tokens_details")?.cached_tokens,
|
|
456
|
-
reasoningTokens: optionalRecord(usage.completion_tokens_details, "response.usage.completion_tokens_details")?.reasoning_tokens,
|
|
457
|
-
}, "response.usage");
|
|
458
|
-
}
|
|
459
|
-
function responsesUsage(value) {
|
|
460
|
-
const usage = optionalRecord(value, "response.usage");
|
|
461
|
-
if (usage === undefined)
|
|
462
|
-
return undefined;
|
|
463
|
-
return usageOf({
|
|
464
|
-
inputTokens: usage.input_tokens,
|
|
465
|
-
outputTokens: usage.output_tokens,
|
|
466
|
-
totalTokens: usage.total_tokens,
|
|
467
|
-
cachedTokens: optionalRecord(usage.input_tokens_details, "response.usage.input_tokens_details")?.cached_tokens,
|
|
468
|
-
reasoningTokens: optionalRecord(usage.output_tokens_details, "response.usage.output_tokens_details")?.reasoning_tokens,
|
|
469
|
-
}, "response.usage");
|
|
470
|
-
}
|
|
471
|
-
function messagesUsage(value) {
|
|
472
|
-
const usage = optionalRecord(value, "response.usage");
|
|
473
|
-
if (usage === undefined)
|
|
474
|
-
return undefined;
|
|
475
|
-
return usageOf({
|
|
476
|
-
inputTokens: usage.input_tokens,
|
|
477
|
-
outputTokens: usage.output_tokens,
|
|
478
|
-
cachedTokens: usage.cache_read_input_tokens,
|
|
479
|
-
}, "response.usage");
|
|
480
|
-
}
|
|
481
|
-
function usageOf(value, path) {
|
|
482
|
-
const fields = Object.entries(value).flatMap(([key, raw]) => {
|
|
483
|
-
if (raw === undefined)
|
|
484
|
-
return [];
|
|
485
|
-
if (!isNonNegativeInteger(raw))
|
|
486
|
-
throw invalidResponse(`${path}.${key} must be a non-negative integer`, `${path}.${key}`);
|
|
487
|
-
return [[key, raw]];
|
|
488
|
-
});
|
|
489
|
-
return Object.fromEntries(fields);
|
|
490
|
-
}
|
|
491
|
-
function evidence(response) {
|
|
492
|
-
const requestId = optionalString(response.id, "response.id");
|
|
493
|
-
const resolvedModel = optionalString(response.model, "response.model");
|
|
494
|
-
return requestId === undefined && resolvedModel === undefined
|
|
495
|
-
? undefined
|
|
496
|
-
: {
|
|
497
|
-
...(requestId === undefined ? {} : { requestId }),
|
|
498
|
-
...(resolvedModel === undefined ? {} : { resolvedModel }),
|
|
499
|
-
};
|
|
500
|
-
}
|
|
501
|
-
function record(value, path) {
|
|
502
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
503
|
-
throw invalidResponse(`${path} must be an object`, path);
|
|
504
|
-
return value;
|
|
505
|
-
}
|
|
506
|
-
function optionalRecord(value, path) {
|
|
507
|
-
return value === undefined || value === null ? undefined : record(value, path);
|
|
508
|
-
}
|
|
509
|
-
function array(value, path) {
|
|
510
|
-
if (!Array.isArray(value))
|
|
511
|
-
throw invalidResponse(`${path} must be an array`, path);
|
|
512
|
-
return value;
|
|
513
|
-
}
|
|
514
|
-
function optionalArray(value, path) {
|
|
515
|
-
if (value === undefined || value === null)
|
|
516
|
-
return [];
|
|
517
|
-
if (!Array.isArray(value))
|
|
518
|
-
throw invalidResponse(`${path} must be an array`, path);
|
|
519
|
-
return value;
|
|
520
|
-
}
|
|
521
|
-
function string(value, path) {
|
|
522
|
-
if (typeof value !== "string")
|
|
523
|
-
throw invalidResponse(`${path} must be a string`, path);
|
|
524
|
-
return value;
|
|
525
|
-
}
|
|
526
|
-
function optionalString(value, path) {
|
|
527
|
-
if (value === undefined || value === null)
|
|
528
|
-
return undefined;
|
|
529
|
-
return string(value, path);
|
|
530
|
-
}
|
|
531
|
-
function checkedMaxOutputTokens(value) {
|
|
532
|
-
if (!isNonNegativeInteger(value))
|
|
533
|
-
throw new HarnessError("model.adapter-invalid-options", "Anthropic defaultMaxOutputTokens must be a non-negative integer", { details: { path: "defaultMaxOutputTokens" } });
|
|
534
|
-
}
|
|
535
|
-
function isNonNegativeInteger(value) {
|
|
536
|
-
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
537
|
-
}
|
|
538
|
-
function hasToolCall(output) {
|
|
539
|
-
return output.some((part) => part.type === "tool-call");
|
|
540
|
-
}
|
|
541
|
-
function invalidResponse(message, path, cause) {
|
|
542
|
-
return new HarnessError("model.adapter-invalid-response", message, {
|
|
543
|
-
...(cause === undefined ? {} : { cause }),
|
|
544
|
-
details: { path },
|
|
545
|
-
});
|
|
546
|
-
}
|
|
547
|
-
// These portable translators do not interpret another adapter's signed reasoning.
|
|
548
|
-
function withoutProviderReasoning(prompt) {
|
|
549
|
-
return prompt.flatMap((item) => {
|
|
550
|
-
if (item.kind !== "message" ||
|
|
551
|
-
item.role !== "assistant" ||
|
|
552
|
-
!item.content.some((part) => part.type === "reasoning"))
|
|
553
|
-
return [item];
|
|
554
|
-
const content = item.content.filter((part) => part.type !== "reasoning");
|
|
555
|
-
return content.length === 0 ? [] : [{ ...item, content }];
|
|
556
|
-
});
|
|
557
|
-
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { ModelAdapter, ModelAdapterContext, ModelCandidate, ModelCall } from "@nylorun/core/define";
|
|
2
|
-
import type { JsonValue } from "@nylorun/core/define";
|
|
3
|
-
export interface PreparedModelOptions<Wire> {
|
|
4
|
-
readonly adapter: string;
|
|
5
|
-
prepare(call: ModelCall, context: ModelAdapterContext): Promise<{
|
|
6
|
-
readonly request: Wire;
|
|
7
|
-
readonly observed: JsonValue;
|
|
8
|
-
}>;
|
|
9
|
-
send(request: Wire, call: ModelCall, context: ModelAdapterContext): Promise<unknown>;
|
|
10
|
-
decode(response: unknown, call: ModelCall): ModelCandidate | string;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Builds a ModelAdapter that reports the provider request derived from Harness's canonical call.
|
|
14
|
-
* The observed value is deliberately JSON-only; opaque wire data remains adapter-local.
|
|
15
|
-
*/
|
|
16
|
-
export declare function preparedModel<Wire>(options: PreparedModelOptions<Wire>): ModelAdapter;
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Builds a ModelAdapter that reports the provider request derived from Harness's canonical call.
|
|
3
|
-
* The observed value is deliberately JSON-only; opaque wire data remains adapter-local.
|
|
4
|
-
*/
|
|
5
|
-
export function preparedModel(options) {
|
|
6
|
-
return async (call, context) => {
|
|
7
|
-
const prepared = await options.prepare(call, context);
|
|
8
|
-
context.reportPreparedCall({ adapter: options.adapter, call: prepared.observed });
|
|
9
|
-
return options.decode(await options.send(prepared.request, call, context), call);
|
|
10
|
-
};
|
|
11
|
-
}
|