@nylorun/harness 0.23.1-beta → 0.25.0-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 +58 -0
- package/HOST_CONTRACT.md +2 -2
- package/README.md +6 -1
- package/dist/index.d.ts +0 -1
- package/dist/loop/model/project.js +12 -1
- package/dist/loop/state.js +8 -1
- package/dist/loop/tool-result.js +16 -2
- package/dist/loop/transcript.js +26 -3
- package/dist/run/durable.d.ts +8 -1
- package/dist/run/durable.js +64 -4
- 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,63 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.25.0-beta
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
- **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.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 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.
|
|
14
|
+
- 070674d: **One source of truth for the manifest and Harness API schemas.**
|
|
15
|
+
|
|
16
|
+
- `@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).
|
|
17
|
+
- `@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.
|
|
18
|
+
- `@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.
|
|
19
|
+
- `@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.
|
|
20
|
+
|
|
21
|
+
- Pin core to the tested release.
|
|
22
|
+
- Updated dependencies [7780b2f]
|
|
23
|
+
- Updated dependencies [070674d]
|
|
24
|
+
- @nylorun/core@0.18.0-beta
|
|
25
|
+
|
|
26
|
+
## 0.24.0-beta
|
|
27
|
+
|
|
28
|
+
### Minor Changes
|
|
29
|
+
|
|
30
|
+
- 18f9a2f: **Model-safe MCP tool names, coded MCP tool errors and credential scrubbing** (R2b C6, C7, C8). MIGRATION.md (protocol 10, "Tool and MCP server names" and "Tool errors the model sees") has the details.
|
|
31
|
+
|
|
32
|
+
- `@nylorun/core`: a declared tool's name and an MCP server's name must match `^[A-Za-z0-9_-]{1,64}$` (`AgentManifestSchema`, so `PUT /v1/agents/{id}` refuses others). `mcp.discovered`'s server outcomes gain `renamed: [{ serverToolName, name }]`; `tool.completed` gains `redacted` and its `error` gains `retryable`. A failed `ToolOutcome` and `ToolResult` may carry `retryable`.
|
|
33
|
+
- `@nylorun/harness`: a failed tool result keeps the outcome's `retryable`, and the model sees it beside `code` and `message`.
|
|
34
|
+
- `@nylorun/runtime`: the model knows an MCP tool by `server__tool` with characters outside `[A-Za-z0-9_-]` replaced by `_`, shortened to 64 with an 8-hex SHA-256 suffix (also given to a renamed tool that collides); the server is still called by its own name. A failed MCP tool call is a failed tool result the model sees, with code `mcp.unreachable` (never sent; retryable), `credential_rejected` (`401`), `mcp.forbidden` (`403`), `mcp.error` (a JSON-RPC error) or `mcp.status` (another HTTP status); a call whose answer was lost after it was sent is `mcp.lost` for a `readOnlyHint` or `idempotentHint` tool and stays `uncertain` otherwise, as does a call lost with a gateway restart. A pooled connection whose server ended its session (`404` to its `Mcp-Session-Id`) or whose credential's `via` moved is dropped, opened again, and the call sent once more, since the tool never saw it. The credential values sent on a call (at least 8 characters, and a `Bearer` value's token) are replaced with `[redacted]` in MCP and HTTP tool results and errors before the gate records or returns them; no other field is touched.
|
|
35
|
+
|
|
36
|
+
- 90a817d: **MCP and HTTP tool results that fit** (R2b C11). MIGRATION.md (protocol 10, "Tool results that fit") has the details.
|
|
37
|
+
|
|
38
|
+
- `@nylorun/core`: a completed `ToolOutcome` may carry `files` (`ToolResultFile`: a media type and the host's reference) and `truncated`; a completed `ToolResult` carries the `files`. `artifactsCapabilityManifest({ save, read })` adds the built-in `read_artifact` (`READ_ARTIFACT_TOOL`, `READ_ARTIFACT_MAX_BYTES`), and `codeToolsOf` leaves it alone. `SessionView` gains `definitionHash`, the definition the session was opened from. Transcript edits are split at 48 KiB, down from 256 KiB, so each `transcript.updated` event stays under 64 KiB when no entry is larger.
|
|
39
|
+
- `@nylorun/harness`: a tool result's files go to the model after its output, as media parts; an outcome marked `truncated` is not checked against the tool's output schema.
|
|
40
|
+
- `@nylorun/runtime`: an agent's remote MCP or HTTP tool result past 32 KiB is stored as a file artifact of the session, and the model gets `{ truncated: true, artifactId, size, preview }` (the first 4 KiB and the last 1 KiB). Image, audio and blob resource parts become artifacts too, an image also shown to a model that reads images (a note for one that does not); each part of a mixed result is shaped alone, and a `resource_link` stays a link. One step's results share a 256 KiB budget, so many parallel results never make an event near S2's 1 MiB record: past it, a result is a stub naming its artifact. When an artifact cannot be stored, the preview stays and `dropped` says why. An MCP answer past 8 MiB is `mcp.too-large`. `read_artifact { artifactId, offset?, length? }` reads 32 KiB of the session's own artifact a call, with or without a sandbox: a session gets it for each agent with an MCP server or an HTTP tool. The session view names its `definitionHash`.
|
|
41
|
+
- `@nylorun/studio`: a session is shown as running an older manifest only when the definition it was opened from is not the registered one, not because the Runtime pinned its own tools (a sandbox's, `save_artifact`, `read_artifact`) beside it.
|
|
42
|
+
|
|
43
|
+
- b8d10cb: **Per-tool MCP settings (manifest v6) and deferred tools** (R2b C9, C10). MIGRATION.md (protocol 10, "Per-tool settings and manifest v6" and "Deferred tools") has the details.
|
|
44
|
+
|
|
45
|
+
- `@nylorun/core`: an MCP server takes `tools` (`McpToolSettings` by the server's own tool name, `"*"` for the rest: `enabled`, `approval`, `deferred`) and `deferred`, in manifest v6. `mcp()` and `Agent.mcp()` accept them, and the builder writes v6 only for a manifest that uses them, so other manifests keep their hashes; `AgentManifestSchema` accepts v5 unchanged and refuses the fields in v5. `mcpToolSettings` resolves a tool's settings, `manifestVersionFor` says which version a definition needs. `isVariantOf` lets a turn variant disable an MCP tool or require its approval, and nothing else. `TOOLS_CAPABILITY_ID`, `TOOL_SEARCH_TOOL`, `TOOL_CALL_TOOL`, `deferredToolsTools` and `deferredToolsInstructions` describe `tool_search` and `tool_call`. A session tool may carry instructions, read with its capability's. `mcp.discovered` gains `deferred`, `disabled` and `unknownTools` per server.
|
|
46
|
+
- `@nylorun/harness`: a session tool marked `deferred` stays out of the model's tool list; `tool_call` runs it as its own call, after checking the arguments against its `inputSchema`, and asks for approval when it needs it.
|
|
47
|
+
- `@nylorun/runtime`: discovery leaves out the tools a server's settings disable and names keys that match no tool. A session of an agent with a remote MCP server pins an empty `nylorun.tools` capability; when the agent's MCP tools pass a tenth of the model's context window (or settings say so), they are deferred for the session's life, and the model gets `tool_search` (BM25 over the deferred tools' names and descriptions, served by core) and `tool_call`, with a note naming each server and its instructions. Approval resolves per tool, and a turn variant's tightening applies to its turn. The gate's `mcp/connect` answers the server's instructions.
|
|
48
|
+
|
|
49
|
+
### Patch Changes
|
|
50
|
+
|
|
51
|
+
- Pin core to the tested release.
|
|
52
|
+
- Updated dependencies [50e2f7e]
|
|
53
|
+
- Updated dependencies [e0e39ff]
|
|
54
|
+
- Updated dependencies [fed5e58]
|
|
55
|
+
- Updated dependencies [18f9a2f]
|
|
56
|
+
- Updated dependencies [da93711]
|
|
57
|
+
- Updated dependencies [90a817d]
|
|
58
|
+
- Updated dependencies [b8d10cb]
|
|
59
|
+
- @nylorun/core@0.17.0-beta
|
|
60
|
+
|
|
3
61
|
## 0.23.1-beta
|
|
4
62
|
|
|
5
63
|
### Patch 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
|
@@ -114,7 +114,17 @@ function projectToolResult(result) {
|
|
|
114
114
|
toolCallId: result.callId,
|
|
115
115
|
toolName: result.toolName,
|
|
116
116
|
status: result.kind,
|
|
117
|
-
content: [
|
|
117
|
+
content: [
|
|
118
|
+
textPart(JSON.stringify(toolResultPayload(result))),
|
|
119
|
+
// Images the tool returned, stored by the host (R2b C11): the model call resolves them.
|
|
120
|
+
...(result.kind === "completed" && result.files
|
|
121
|
+
? result.files.map((file) => Object.freeze({
|
|
122
|
+
type: "media",
|
|
123
|
+
mediaType: file.mediaType,
|
|
124
|
+
reference: copyJson(file.reference),
|
|
125
|
+
}))
|
|
126
|
+
: []),
|
|
127
|
+
],
|
|
118
128
|
});
|
|
119
129
|
}
|
|
120
130
|
function toolResultPayload(result) {
|
|
@@ -126,6 +136,7 @@ function toolResultPayload(result) {
|
|
|
126
136
|
kind: result.kind,
|
|
127
137
|
code: result.code,
|
|
128
138
|
message: result.message,
|
|
139
|
+
...(result.retryable === undefined ? {} : { retryable: result.retryable }),
|
|
129
140
|
...(result.details === undefined ? {} : { details: result.details }),
|
|
130
141
|
};
|
|
131
142
|
}
|
package/dist/loop/state.js
CHANGED
|
@@ -25,7 +25,14 @@ const interaction = z
|
|
|
25
25
|
const outcome = z.discriminatedUnion("kind", [
|
|
26
26
|
z.object({ kind: z.literal("completed"), output: json }).strict(),
|
|
27
27
|
z.object({ kind: z.literal("denied"), reason: z.string() }).strict(),
|
|
28
|
-
z
|
|
28
|
+
z
|
|
29
|
+
.object({
|
|
30
|
+
kind: z.literal("failed"),
|
|
31
|
+
code: id,
|
|
32
|
+
message: z.string(),
|
|
33
|
+
retryable: z.boolean().optional(),
|
|
34
|
+
})
|
|
35
|
+
.strict(),
|
|
29
36
|
]);
|
|
30
37
|
const reference = z
|
|
31
38
|
.object({
|
package/dist/loop/tool-result.js
CHANGED
|
@@ -3,7 +3,8 @@ import { copyJson } from "@nylorun/core/define";
|
|
|
3
3
|
export function toolResult(call, definition, outcome) {
|
|
4
4
|
const identity = { callId: call.callId, toolName: call.toolName };
|
|
5
5
|
if (outcome.kind === "completed") {
|
|
6
|
-
|
|
6
|
+
// A preview the Runtime made of a result too large to show is not the tool's output (R2b C11).
|
|
7
|
+
const checked = outcome.truncated === true ? undefined : definition.outputSchema?.validate(outcome.output);
|
|
7
8
|
if (checked && !checked.ok)
|
|
8
9
|
return {
|
|
9
10
|
...identity,
|
|
@@ -16,15 +17,28 @@ export function toolResult(call, definition, outcome) {
|
|
|
16
17
|
...identity,
|
|
17
18
|
kind: "completed",
|
|
18
19
|
output: checked?.ok ? checked.value : outcome.output,
|
|
20
|
+
...(outcome.files?.length ? { files: outcome.files.map(fileOf) } : {}),
|
|
19
21
|
});
|
|
20
22
|
}
|
|
21
23
|
if (outcome.kind === "failed" &&
|
|
22
24
|
typeof outcome.code === "string" &&
|
|
23
25
|
typeof outcome.message === "string")
|
|
24
|
-
return copyJson({
|
|
26
|
+
return copyJson({
|
|
27
|
+
...identity,
|
|
28
|
+
kind: "failed",
|
|
29
|
+
code: outcome.code,
|
|
30
|
+
message: outcome.message,
|
|
31
|
+
...(typeof outcome.retryable === "boolean" ? { retryable: outcome.retryable } : {}),
|
|
32
|
+
});
|
|
25
33
|
if (outcome.kind === "denied" && typeof outcome.reason !== "string")
|
|
26
34
|
throw new HarnessError("tool.invalid-tool-result", "Tool denial reason must be a string");
|
|
27
35
|
if (outcome.kind === "denied" && typeof outcome.reason === "string")
|
|
28
36
|
return copyJson({ ...identity, kind: "denied", reason: outcome.reason });
|
|
29
37
|
throw new HarnessError("tool.invalid-tool-result", "Expected a completed, failed, or denied tool result");
|
|
30
38
|
}
|
|
39
|
+
/** A file the model sees beside a tool's output (R2b C11): a media type and the host's reference. */
|
|
40
|
+
function fileOf(file) {
|
|
41
|
+
if (typeof file?.mediaType !== "string" || file.mediaType === "" || file.reference === undefined)
|
|
42
|
+
throw new HarnessError("tool.invalid-tool-result", "A tool result file needs a mediaType and a reference");
|
|
43
|
+
return { mediaType: file.mediaType, reference: file.reference };
|
|
44
|
+
}
|
package/dist/loop/transcript.js
CHANGED
|
@@ -180,23 +180,31 @@ function toolResult(value, index) {
|
|
|
180
180
|
const base = { callId: result.callId, toolName: result.toolName };
|
|
181
181
|
switch (result.kind) {
|
|
182
182
|
case "completed":
|
|
183
|
-
exactKeys(result, ["callId", "toolName", "kind", "output"], `Tool result ${index}`);
|
|
183
|
+
exactKeys(result, ["callId", "toolName", "kind", "output", "files"], `Tool result ${index}`);
|
|
184
184
|
assertJson(result.output, `tool result ${index} output`);
|
|
185
|
-
return Object.freeze({
|
|
185
|
+
return Object.freeze({
|
|
186
|
+
...base,
|
|
187
|
+
kind: "completed",
|
|
188
|
+
output: copyJson(result.output),
|
|
189
|
+
...(result.files === undefined ? {} : { files: resultFiles(result.files, index) }),
|
|
190
|
+
});
|
|
186
191
|
case "denied":
|
|
187
192
|
exactKeys(result, ["callId", "toolName", "kind", "reason"], `Tool result ${index}`);
|
|
188
193
|
if (typeof result.reason !== "string")
|
|
189
194
|
fail(`Tool result ${index} reason must be a string`);
|
|
190
195
|
return Object.freeze({ ...base, kind: "denied", reason: result.reason });
|
|
191
196
|
case "failed":
|
|
192
|
-
exactKeys(result, ["callId", "toolName", "kind", "code", "message", "details"], `Tool result ${index}`);
|
|
197
|
+
exactKeys(result, ["callId", "toolName", "kind", "code", "message", "details", "retryable"], `Tool result ${index}`);
|
|
193
198
|
if (typeof result.code !== "string" || typeof result.message !== "string")
|
|
194
199
|
fail(`Tool result ${index} code and message must be strings`);
|
|
200
|
+
if (result.retryable !== undefined && typeof result.retryable !== "boolean")
|
|
201
|
+
fail(`Tool result ${index} retryable must be a boolean`);
|
|
195
202
|
return Object.freeze({
|
|
196
203
|
...base,
|
|
197
204
|
kind: "failed",
|
|
198
205
|
code: result.code,
|
|
199
206
|
message: result.message,
|
|
207
|
+
...(result.retryable === undefined ? {} : { retryable: result.retryable }),
|
|
200
208
|
...(result.details === undefined
|
|
201
209
|
? {}
|
|
202
210
|
: { details: validationDetails(result.details, index) }),
|
|
@@ -205,6 +213,21 @@ function toolResult(value, index) {
|
|
|
205
213
|
fail(`Tool result ${index} has unknown kind '${String(result.kind)}'`);
|
|
206
214
|
}
|
|
207
215
|
}
|
|
216
|
+
/** A completed result's files (R2b C11): a media type and the host's reference each. */
|
|
217
|
+
function resultFiles(value, index) {
|
|
218
|
+
if (!Array.isArray(value))
|
|
219
|
+
fail(`Tool result ${index} files must be an array`);
|
|
220
|
+
return Object.freeze(value.map((file, fileIndex) => {
|
|
221
|
+
if (!file || typeof file !== "object" || Array.isArray(file))
|
|
222
|
+
fail(`Tool result ${index} file ${fileIndex} must be an object`);
|
|
223
|
+
const item = file;
|
|
224
|
+
exactKeys(item, ["mediaType", "reference"], `Tool result ${index} file ${fileIndex}`);
|
|
225
|
+
if (typeof item.mediaType !== "string" || item.mediaType === "")
|
|
226
|
+
fail(`Tool result ${index} file ${fileIndex} must contain mediaType`);
|
|
227
|
+
assertJson(item.reference, `tool result ${index} file ${fileIndex} reference`);
|
|
228
|
+
return Object.freeze({ mediaType: item.mediaType, reference: copyJson(item.reference) });
|
|
229
|
+
}));
|
|
230
|
+
}
|
|
208
231
|
function validationDetails(value, index) {
|
|
209
232
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
210
233
|
fail(`Tool result ${index} details must be an object`);
|
package/dist/run/durable.d.ts
CHANGED
|
@@ -72,8 +72,15 @@ export interface DurableSessionTool {
|
|
|
72
72
|
readonly description?: string;
|
|
73
73
|
readonly inputSchema: JsonObject;
|
|
74
74
|
readonly outputSchema?: JsonObject;
|
|
75
|
-
/** `always`: each call waits for approval (a remote MCP server's `approval`). */
|
|
75
|
+
/** `always`: each call waits for approval (a remote MCP server's, or its tool's, `approval`). */
|
|
76
76
|
readonly approval?: ApprovalMode;
|
|
77
|
+
/**
|
|
78
|
+
* Not in the model's tool list (R2b C10): the model finds it with `tool_search` and runs it
|
|
79
|
+
* with `tool_call`, which makes the call as this tool's own.
|
|
80
|
+
*/
|
|
81
|
+
readonly deferred?: boolean;
|
|
82
|
+
/** Text the model reads with the capability's instructions while this tool is advertised. */
|
|
83
|
+
readonly instructions?: readonly string[];
|
|
77
84
|
}
|
|
78
85
|
export declare function createDurableCheckpoint(input: {
|
|
79
86
|
manifest: AgentManifest;
|
package/dist/run/durable.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { HarnessError } from "@nylorun/core/define";
|
|
2
2
|
import { AgentManifestSchema } from "@nylorun/core/contracts";
|
|
3
|
-
import { agentFrom, withHttpTarget } from "@nylorun/core/define";
|
|
3
|
+
import { TOOL_CALL_TOOL, TOOLS_CAPABILITY_ID, agentFrom, withHttpTarget, } from "@nylorun/core/define";
|
|
4
4
|
import { definitionFor } from "../definition/agent-definition.js";
|
|
5
5
|
import { schemaFromJSON } from "@nylorun/core/define";
|
|
6
6
|
import { hashManifest } from "@nylorun/core/define";
|
|
@@ -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))
|
|
@@ -126,7 +126,10 @@ export async function runDurable(options) {
|
|
|
126
126
|
/** Rebuild one agent from its manifest with every tool routed through host effects. */
|
|
127
127
|
const hostedDefinition = (agent, ref) => {
|
|
128
128
|
const hostedTool = hostedTools(ref);
|
|
129
|
-
const
|
|
129
|
+
const mine = sessionTools.filter((tool) => (tool.agentId ?? manifest.id) === agent.id);
|
|
130
|
+
// Deferred tools stay out of the model's list; `tool_call` runs them (R2b C10).
|
|
131
|
+
const owned = mine.filter((tool) => !tool.deferred);
|
|
132
|
+
const deferred = new Map(mine.filter((tool) => tool.deferred).map((tool) => [tool.name, tool]));
|
|
130
133
|
const implementations = {};
|
|
131
134
|
for (const capability of agent.capabilities) {
|
|
132
135
|
const tools = {};
|
|
@@ -142,7 +145,10 @@ export async function runDurable(options) {
|
|
|
142
145
|
tools[tool.name] = hostedTool(capability.id, tool);
|
|
143
146
|
for (const tool of owned)
|
|
144
147
|
if (tool.capabilityId === capability.id)
|
|
145
|
-
tools[tool.name] =
|
|
148
|
+
tools[tool.name] =
|
|
149
|
+
capability.id === TOOLS_CAPABILITY_ID && tool.name === TOOL_CALL_TOOL
|
|
150
|
+
? deferredToolCall(tool, deferred, hostedTool)
|
|
151
|
+
: hostedTool(capability.id, tool);
|
|
146
152
|
implementations[capability.id] = { tools };
|
|
147
153
|
}
|
|
148
154
|
return definitionFor(agentFrom(agent, implementations, owned.length === 0
|
|
@@ -151,6 +157,7 @@ export async function runDurable(options) {
|
|
|
151
157
|
sessionTools: owned.map((tool) => ({
|
|
152
158
|
capabilityId: tool.capabilityId,
|
|
153
159
|
name: tool.name,
|
|
160
|
+
...(tool.instructions?.length ? { instructions: tool.instructions } : {}),
|
|
154
161
|
})),
|
|
155
162
|
}));
|
|
156
163
|
};
|
|
@@ -208,3 +215,56 @@ export async function runDurable(options) {
|
|
|
208
215
|
function scoped(ref, identity) {
|
|
209
216
|
return ref ? `${ref.delegationId}/${identity}` : identity;
|
|
210
217
|
}
|
|
218
|
+
/**
|
|
219
|
+
* `tool_call` (R2b C10): runs a deferred tool by name, as that tool's own call. It checks the
|
|
220
|
+
* arguments against the tool's `inputSchema` first, so a mistake comes back to the model as a
|
|
221
|
+
* failed result it can fix. The effect then names the tool, so the host routes it, shapes its
|
|
222
|
+
* result and records `tool.completed` as for a direct call; a tool with approval waits for it
|
|
223
|
+
* here, with the prompt a direct call would have.
|
|
224
|
+
*/
|
|
225
|
+
function deferredToolCall(tool, deferred, hostedTool) {
|
|
226
|
+
const hosted = new Map();
|
|
227
|
+
const targetOf = (args) => {
|
|
228
|
+
const name = args?.name;
|
|
229
|
+
return typeof name === "string" ? deferred.get(name) : undefined;
|
|
230
|
+
};
|
|
231
|
+
const gated = [...deferred.values()].some((item) => item.approval === "always");
|
|
232
|
+
return {
|
|
233
|
+
name: tool.name,
|
|
234
|
+
...(tool.description === undefined ? {} : { description: tool.description }),
|
|
235
|
+
inputSchema: schemaFromJSON(tool.inputSchema),
|
|
236
|
+
...(gated
|
|
237
|
+
? {
|
|
238
|
+
approval: (args) => {
|
|
239
|
+
const target = targetOf(args);
|
|
240
|
+
return target?.approval === "always" ? `Approve ${target.name}?` : undefined;
|
|
241
|
+
},
|
|
242
|
+
}
|
|
243
|
+
: {}),
|
|
244
|
+
async execute(args, ctx) {
|
|
245
|
+
const call = args;
|
|
246
|
+
const target = targetOf(call);
|
|
247
|
+
if (!target)
|
|
248
|
+
return {
|
|
249
|
+
kind: "failed",
|
|
250
|
+
code: "tool.unknown",
|
|
251
|
+
message: `No deferred tool is named '${call.name}'. Find one with tool_search, and pass its name as it returned it.`,
|
|
252
|
+
};
|
|
253
|
+
const checked = schemaFromJSON(target.inputSchema).validate(call.arguments ?? {});
|
|
254
|
+
if (!checked.ok)
|
|
255
|
+
return {
|
|
256
|
+
kind: "failed",
|
|
257
|
+
code: "tool.invalid-arguments",
|
|
258
|
+
message: `The arguments do not match the inputSchema of '${target.name}': ${checked.issues
|
|
259
|
+
.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)
|
|
260
|
+
.join("; ")}`,
|
|
261
|
+
};
|
|
262
|
+
let run = hosted.get(target.name);
|
|
263
|
+
if (!run) {
|
|
264
|
+
run = hostedTool(target.capabilityId, target);
|
|
265
|
+
hosted.set(target.name, run);
|
|
266
|
+
}
|
|
267
|
+
return run.execute(checked.value, ctx);
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nylorun/harness",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0-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.18.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
|
-
}
|