@tangle-network/agent-runtime 0.128.0 → 0.131.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -20
- package/dist/{activation-DhWJ3p8N.js → activation-BCzMOTaV.js} +3 -3
- package/dist/{activation-DhWJ3p8N.js.map → activation-BCzMOTaV.js.map} +1 -1
- package/dist/agent.d.ts +2 -3
- package/dist/agent.js +4 -5
- package/dist/agent.js.map +1 -1
- package/dist/{analyst-loop-DvSciOfB.js → analyst-loop-BE8cDs5Q.js} +2 -2
- package/dist/{analyst-loop-DvSciOfB.js.map → analyst-loop-BE8cDs5Q.js.map} +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/analyst-loop.js +1 -1
- package/dist/authoring-Dv3t6SXe.js +163 -0
- package/dist/authoring-Dv3t6SXe.js.map +1 -0
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-BFpq-Xi6.js → candidate-execution-BNxKr-Bu.js} +5 -5
- package/dist/{candidate-execution-BFpq-Xi6.js.map → candidate-execution-BNxKr-Bu.js.map} +1 -1
- package/dist/{conversation-BpLQZGPH.js → conversation-DNtxaJ1Z.js} +113 -31
- package/dist/conversation-DNtxaJ1Z.js.map +1 -0
- package/dist/conversation.d.ts +2 -2
- package/dist/conversation.js +2 -2
- package/dist/environment-provider-CxvSd1W6.d.ts +86 -0
- package/dist/{environment-provider-DqFS6FSZ.js → environment-provider-Dyg8DtLK.js} +8 -4
- package/dist/environment-provider-Dyg8DtLK.js.map +1 -0
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/graph-xWdv53Le.js +471 -0
- package/dist/graph-xWdv53Le.js.map +1 -0
- package/dist/{improvement-cycle-IJgCbKWQ.js → improvement-cycle-Csp38cWg.js} +133 -224
- package/dist/improvement-cycle-Csp38cWg.js.map +1 -0
- package/dist/{index-BhZhQw77.d.ts → index-CoO7atyo.d.ts} +556 -1278
- package/dist/{index-BhuzfG2r.d.ts → index-DwGtu9nc.d.ts} +7 -9
- package/dist/{index-Efjb3nrQ.d.ts → index-qYHpsmG2.d.ts} +36 -18
- package/dist/index.d.ts +353 -11
- package/dist/index.js +111 -354
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +6 -6
- package/dist/intelligence.js +9 -8
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +7 -5
- package/dist/kernel.js +13 -9
- package/dist/{knowledge-DF63xPr4.js → knowledge-DPEu4f-0.js} +19 -17
- package/dist/knowledge-DPEu4f-0.js.map +1 -0
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-Ckp_9tmD.d.ts → loop-runner-bin-BwgZ8m_7.d.ts} +6 -3
- package/dist/{loop-runner-bin-CWqOpCEw.js → loop-runner-bin-dg6li2-b.js} +5 -27
- package/dist/loop-runner-bin-dg6li2-b.js.map +1 -0
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/materialization-COJ1UYQ-.js +272 -0
- package/dist/materialization-COJ1UYQ-.js.map +1 -0
- package/dist/mcp/bin.js +39 -47
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +24 -26
- package/dist/mcp/index.js +67 -84
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/{memory-server-DL6cE2Ag.js → memory-server-eD2baiRO.js} +3 -3
- package/dist/{memory-server-DL6cE2Ag.js.map → memory-server-eD2baiRO.js.map} +1 -1
- package/dist/model-policy-CqziaqS1.js +232 -0
- package/dist/model-policy-CqziaqS1.js.map +1 -0
- package/dist/{openai-tools-B68JaOCx.d.ts → openai-tools-D3oMyVGl.d.ts} +2 -2
- package/dist/{openai-tools-D3XfrrQ6.js → openai-tools-zRphjXS4.js} +2 -2
- package/dist/openai-tools-zRphjXS4.js.map +1 -0
- package/dist/{prepare--8EvLqCr.js → prepare-DYWjVcPx.js} +169 -153
- package/dist/prepare-DYWjVcPx.js.map +1 -0
- package/dist/primeintellect/index.d.ts +7 -6
- package/dist/primeintellect/index.js +9 -11
- package/dist/primeintellect/index.js.map +1 -1
- package/dist/profiles.d.ts +21 -174
- package/dist/profiles.js +67 -276
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-CXVfOUu_.js → protected-model-port-48ALLGxT.js} +2 -2
- package/dist/{protected-model-port-CXVfOUu_.js.map → protected-model-port-48ALLGxT.js.map} +1 -1
- package/dist/{redact-PQzmE1Jn.d.ts → redact-9_Gf-8m3.d.ts} +58 -69
- package/dist/{researcher-CoVqNhfI.js → researcher-Skz5-Uc8.js} +50 -26
- package/dist/researcher-Skz5-Uc8.js.map +1 -0
- package/dist/{run-layout-C2FGmZ3v.js → run-layout-CeJsEAom.js} +2 -2
- package/dist/{run-layout-C2FGmZ3v.js.map → run-layout-CeJsEAom.js.map} +1 -1
- package/dist/runtime-D-QfLbSd.d.ts +893 -0
- package/dist/{runtime-5uDVVfER.js → runtime-cOzDOOHr.js} +315 -1191
- package/dist/runtime-cOzDOOHr.js.map +1 -0
- package/dist/{sandbox-events-Yhd1GYWl.js → sandbox-events-CRDwc5WN.js} +42 -5
- package/dist/sandbox-events-CRDwc5WN.js.map +1 -0
- package/dist/snapshot-CXiiuHhL.js +21 -0
- package/dist/snapshot-CXiiuHhL.js.map +1 -0
- package/dist/{spawn-journal-DsZKDqeh.js → spawn-journal-saHQzqYi.js} +15 -21
- package/dist/spawn-journal-saHQzqYi.js.map +1 -0
- package/dist/stream-agent-turn-C852AgMT.d.ts +128 -0
- package/dist/stream-agent-turn-rYgaOLO0.js +910 -0
- package/dist/stream-agent-turn-rYgaOLO0.js.map +1 -0
- package/dist/{structural-rollout-zY0oqQzO.js → structural-rollout-3uxVGcg2.js} +459 -235
- package/dist/structural-rollout-3uxVGcg2.js.map +1 -0
- package/dist/{supervise-CsTKbH9R.js → supervise-DHYX8gO2.js} +867 -4788
- package/dist/supervise-DHYX8gO2.js.map +1 -0
- package/dist/{supervisor-DpjO0Gmy.js → supervisor-CV6Jh28D.js} +7439 -2897
- package/dist/supervisor-CV6Jh28D.js.map +1 -0
- package/dist/testing.d.ts +3 -1
- package/dist/testing.js +271 -221
- package/dist/testing.js.map +1 -1
- package/dist/{tool-server-RcWgLIsL.js → tool-server-Gs3VvfSK.js} +22 -9
- package/dist/tool-server-Gs3VvfSK.js.map +1 -0
- package/dist/{top-app-5unxqovu.js → top-app-G4M18b6i.js} +3 -3
- package/dist/{top-app-5unxqovu.js.map → top-app-G4M18b6i.js.map} +1 -1
- package/dist/tui/bin.js +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{environment-provider-CUFsyymu.d.ts → types-C6Q-J0Dt.d.ts} +51 -114
- package/dist/{types-DnNGJ5Gz.d.ts → types-ebIY0dMG.d.ts} +556 -30
- package/dist/{util-MVgdwuIS.js → util-Bw6srryQ.js} +3 -2
- package/dist/{util-MVgdwuIS.js.map → util-Bw6srryQ.js.map} +1 -1
- package/dist/{workspace-archive-BQxvkypI.js → workspace-archive-aOfJ47ms.js} +3 -3
- package/dist/{workspace-archive-BQxvkypI.js.map → workspace-archive-aOfJ47ms.js.map} +1 -1
- package/package.json +13 -15
- package/skills/agent-graphs/IMPROVE.md +3 -3
- package/skills/agent-graphs/SKILL.md +4 -5
- package/skills/agent-graphs/cases/review-pipeline.json +1 -2
- package/skills/agent-graphs/cases/unmeasured-harness.json +2 -4
- package/dist/backends-CiOCyRHb.js +0 -743
- package/dist/backends-CiOCyRHb.js.map +0 -1
- package/dist/conversation-BpLQZGPH.js.map +0 -1
- package/dist/environment-provider-DqFS6FSZ.js.map +0 -1
- package/dist/improvement-cycle-IJgCbKWQ.js.map +0 -1
- package/dist/index-DLM0W1h1.d.ts +0 -545
- package/dist/knowledge-DF63xPr4.js.map +0 -1
- package/dist/local-harness-BIajef4A.d.ts +0 -465
- package/dist/loop-runner-bin-CWqOpCEw.js.map +0 -1
- package/dist/model-resolution-Btd9iIKV.js +0 -98
- package/dist/model-resolution-Btd9iIKV.js.map +0 -1
- package/dist/openai-tools-D3XfrrQ6.js.map +0 -1
- package/dist/prepare--8EvLqCr.js.map +0 -1
- package/dist/researcher-CoVqNhfI.js.map +0 -1
- package/dist/runtime-5uDVVfER.js.map +0 -1
- package/dist/sandbox-events-Yhd1GYWl.js.map +0 -1
- package/dist/spawn-journal-DsZKDqeh.js.map +0 -1
- package/dist/structural-rollout-zY0oqQzO.js.map +0 -1
- package/dist/supervise-CsTKbH9R.js.map +0 -1
- package/dist/supervisor-DpjO0Gmy.js.map +0 -1
- package/dist/tool-server-RcWgLIsL.js.map +0 -1
- package/dist/types-C9j4qg6l.d.ts +0 -500
- package/skills/agent-graphs/cases/floor-trap-pi.json +0 -11
|
@@ -1,465 +0,0 @@
|
|
|
1
|
-
import { AgentProfile, HarnessType, ReasoningEffort } from "@tangle-network/agent-interface";
|
|
2
|
-
import { ChildProcess } from "node:child_process";
|
|
3
|
-
//#region src/runtime/tool-loop.d.ts
|
|
4
|
-
/** Provider-neutral conversation record accepted by a tool-loop brain. */
|
|
5
|
-
type ToolLoopMessageRecord = Record<string, unknown>;
|
|
6
|
-
/** One inference turn over the running conversation + the tool specs → the model's text, any
|
|
7
|
-
* tool calls, and token usage. The seam every brain satisfies. */
|
|
8
|
-
type ToolLoopChat = (messages: ReadonlyArray<ToolLoopMessageRecord>, tools: ReadonlyArray<ToolSpec>) => Promise<{
|
|
9
|
-
content?: string | null;
|
|
10
|
-
toolCalls: RouterToolCall[];
|
|
11
|
-
usage?: {
|
|
12
|
-
input: number;
|
|
13
|
-
output: number;
|
|
14
|
-
};
|
|
15
|
-
/** The turn's inference cost (usd) when the provider priced it — for callers that meter usd
|
|
16
|
-
* into a conserved pool (the supervisor brain). `runBrainLoop` itself ignores it. */
|
|
17
|
-
costUsd?: number;
|
|
18
|
-
/** The turn ran but its usage was not reported when the transport EXPECTED one (the streamed
|
|
19
|
-
* router transport asks for usage and this says it never arrived). A metering caller records an
|
|
20
|
-
* unknown turn on it; `runBrainLoop` itself ignores it. */
|
|
21
|
-
usageUnknown?: true;
|
|
22
|
-
}>;
|
|
23
|
-
/** Self-compaction — bound the loop's OWN context window the way a fresh-respawn (dumb-Ralph) loop
|
|
24
|
-
* does, but in place. A stateless chat API re-sends the WHOLE running conversation every turn, so an
|
|
25
|
-
* agent that accumulates dozens of turns of tool results re-bills its entire transcript on every
|
|
26
|
-
* inference — the context-overflow-one-level-up that the conserved budget pool cannot fix. With
|
|
27
|
-
* compaction set, once the conversation exceeds `thresholdTokens` the accumulated middle (every prior
|
|
28
|
-
* assistant turn + tool result) is distilled into ONE compact progress note and the conversation is
|
|
29
|
-
* reset to `[...head, digest]`: the preserved head (system + the original task) survives, the stale
|
|
30
|
-
* turn-by-turn history does not. The model keeps deciding; it stops re-billing the whole transcript.
|
|
31
|
-
* Fires at a CLEAN turn boundary (after a turn's tool results are folded in, before the next
|
|
32
|
-
* inference) so it never orphans an assistant `tool_calls` from its `tool` replies. */
|
|
33
|
-
interface ToolLoopCompaction {
|
|
34
|
-
/** Compact once the estimated token count of the conversation exceeds this. */
|
|
35
|
-
readonly thresholdTokens: number;
|
|
36
|
-
/** Distill the conversation into a compact progress note that REPLACES the middle. Receives the
|
|
37
|
-
* full conversation (so it can summarize everything done so far); returns the digest string. */
|
|
38
|
-
readonly distill: (messages: ReadonlyArray<ToolLoopMessageRecord>) => Promise<string> | string;
|
|
39
|
-
/** Leading messages preserved verbatim (system + the original task). Default 2. */
|
|
40
|
-
readonly preserveHead?: number;
|
|
41
|
-
/** Token estimator over the conversation. Default ≈ chars/4 (incl. tool-call arguments). */
|
|
42
|
-
readonly estimateTokens?: (messages: ReadonlyArray<ToolLoopMessageRecord>) => number;
|
|
43
|
-
/** Notified each time a compaction fires — for observability/metering. */
|
|
44
|
-
readonly onCompact?: (info: {
|
|
45
|
-
turn: number;
|
|
46
|
-
beforeTokens: number;
|
|
47
|
-
afterTokens: number;
|
|
48
|
-
}) => void;
|
|
49
|
-
}
|
|
50
|
-
/** Public supervisor-facing compaction config: same knobs as the primitive, but `distill` is optional
|
|
51
|
-
* because the supervisor has a default digest that combines a brain note with live worker state. */
|
|
52
|
-
type ToolLoopCompactionOptions = Omit<ToolLoopCompaction, 'distill'> & {
|
|
53
|
-
readonly distill?: ToolLoopCompaction['distill'];
|
|
54
|
-
};
|
|
55
|
-
//#endregion
|
|
56
|
-
//#region src/runtime/router-client.d.ts
|
|
57
|
-
interface RouterConfig {
|
|
58
|
-
routerBaseUrl: string;
|
|
59
|
-
routerKey: string;
|
|
60
|
-
model: string;
|
|
61
|
-
/**
|
|
62
|
-
* Optional completion transport. When set, `routerChatWithUsage` / `routerChatWithTools` call it
|
|
63
|
-
* with the OpenAI-shape request body and use the parsed `/chat/completions` JSON it returns,
|
|
64
|
-
* INSTEAD of `fetch(routerBaseUrl + '/chat/completions')`. When absent the fetch path runs
|
|
65
|
-
* unchanged — the live router stays the default. The injection seam an offline benchmark uses to
|
|
66
|
-
* drive the worker with no network: a deterministic in-process responder satisfies it, no server.
|
|
67
|
-
*/
|
|
68
|
-
complete?: (body: Record<string, unknown>) => Promise<unknown>;
|
|
69
|
-
/**
|
|
70
|
-
* Ceiling for one completion, forwarded as `max_tokens`. Defaults to 8192.
|
|
71
|
-
*
|
|
72
|
-
* A REASONING model spends this budget on hidden thinking BEFORE it emits a visible token, so
|
|
73
|
-
* the default can truncate one mid-thought and return no content at all — observed live with a
|
|
74
|
-
* model that spent 8,188 of the 8,192 on reasoning and answered with nothing. Raise it for a
|
|
75
|
-
* thinking model; the ceiling belongs to the router and model a caller chose, which is why it
|
|
76
|
-
* lives here rather than on one call site.
|
|
77
|
-
*/
|
|
78
|
-
maxTokens?: number;
|
|
79
|
-
/**
|
|
80
|
-
* Take the tool-calling completion over SSE instead of one buffered POST. Off by default —
|
|
81
|
-
* `routerChatWithTools` never streams, and every existing caller keeps the buffered transport
|
|
82
|
-
* byte for byte.
|
|
83
|
-
*
|
|
84
|
-
* Why it exists: a buffered POST holds one connection idle for the WHOLE completion, and a
|
|
85
|
-
* supervisor turn is the longest completion in the system. An intermediary gateway with an
|
|
86
|
-
* idle-read timeout kills that connection mid-completion (the 524/503 family). A streamed
|
|
87
|
-
* response puts bytes on the wire from the first generated token on, so the connection is only
|
|
88
|
-
* idle through prefill. It does NOT shorten prefill, so a gateway whose deadline is
|
|
89
|
-
* time-to-FIRST-byte is unaffected; only an idle-timeout gateway is.
|
|
90
|
-
*
|
|
91
|
-
* Mutually exclusive with `complete`: the injected transport returns one parsed JSON body and has
|
|
92
|
-
* no stream to read, so setting both throws rather than silently taking the buffered path.
|
|
93
|
-
*
|
|
94
|
-
* WHICH PATHS CAN OPT IN. This flag is read in exactly one place (the private `chatWithTools` transport switch), so
|
|
95
|
-
* every entry point that takes a caller-supplied `RouterConfig` honors it: `routerBrain`,
|
|
96
|
-
* `routerToolLoop`, and `supervisorAgent` (which spreads `deps.router` into the brain's config —
|
|
97
|
-
* the supervisor turn this exists for). Two production call sites build a `RouterConfig` literal
|
|
98
|
-
* from their own options and therefore CANNOT express it today: the bench strategy's
|
|
99
|
-
* `routerToolLoop` config in `strategy.ts` and the local sandbox client's `routerBrain` config in
|
|
100
|
-
* `local-sandbox-client.ts`. Neither drives a supervisor-length turn; setting `stream` on a
|
|
101
|
-
* config handed to either has no path to reach them, and they stay buffered.
|
|
102
|
-
*/
|
|
103
|
-
stream?: boolean;
|
|
104
|
-
}
|
|
105
|
-
interface RouterChatResult {
|
|
106
|
-
/** The final answer, with any inline `<think>...</think>` block stripped into `reasoning`. */
|
|
107
|
-
content: string;
|
|
108
|
-
/**
|
|
109
|
-
* Thinking-model reasoning, when the provider surfaced it — either as a separate
|
|
110
|
-
* `reasoning`/`reasoning_content` message field (OpenRouter style) or inlined into
|
|
111
|
-
* `content` as a `<think>` block (Groq style). Undefined for non-thinking models.
|
|
112
|
-
* Downstream parsers that match single-token answers must read `content`, which is
|
|
113
|
-
* clean either way; before this split, Groq-style inlining made the same model look
|
|
114
|
-
* broken on one provider and fine on another.
|
|
115
|
-
*/
|
|
116
|
-
reasoning?: string;
|
|
117
|
-
/** REAL usage, or undefined when the provider reported none. */
|
|
118
|
-
usage?: {
|
|
119
|
-
input: number;
|
|
120
|
-
output: number;
|
|
121
|
-
};
|
|
122
|
-
/** Derived from usage via `estimateCost` when the model is priced; else undefined. */
|
|
123
|
-
costUsd?: number;
|
|
124
|
-
}
|
|
125
|
-
/** One OpenAI-compatible chat completion through the Tangle router, returning text + REAL token usage (`undefined` when the provider omits it — never a fabricated 0). */
|
|
126
|
-
declare function routerChatWithUsage(cfg: RouterConfig, messages: Array<{
|
|
127
|
-
role: string;
|
|
128
|
-
content: string;
|
|
129
|
-
}>, opts?: {
|
|
130
|
-
temperature?: number;
|
|
131
|
-
signal?: AbortSignal;
|
|
132
|
-
maxTokens?: number;
|
|
133
|
-
/**
|
|
134
|
-
* Reasoning control for thinking models, forwarded as `reasoning_effort`.
|
|
135
|
-
* 'none' is the load-bearing value: binary/single-token decisions (routing,
|
|
136
|
-
* gating) on a thinking model otherwise burn the whole token budget inside
|
|
137
|
-
* the think block — on slow backends (CPU-local) that turns into a client
|
|
138
|
-
* timeout, not just waste. Providers that ignore the field are handled by
|
|
139
|
-
* the reasoning/content split in `parseChatResult`.
|
|
140
|
-
*/
|
|
141
|
-
reasoningEffort?: 'none' | 'low' | 'medium' | 'high';
|
|
142
|
-
}): Promise<RouterChatResult>;
|
|
143
|
-
/** A tool-call the model emitted (provider-neutral; mirrors the runtime's ToolCallRequest). */
|
|
144
|
-
interface RouterToolCall {
|
|
145
|
-
id: string;
|
|
146
|
-
name: string;
|
|
147
|
-
/** Raw JSON arguments string as emitted by the model. */
|
|
148
|
-
arguments: string;
|
|
149
|
-
}
|
|
150
|
-
interface RouterChatToolsResult {
|
|
151
|
-
content: string | null;
|
|
152
|
-
toolCalls: RouterToolCall[];
|
|
153
|
-
usage?: {
|
|
154
|
-
input: number;
|
|
155
|
-
output: number;
|
|
156
|
-
};
|
|
157
|
-
costUsd?: number;
|
|
158
|
-
/**
|
|
159
|
-
* Thinking-model reasoning, normalized the way `RouterChatResult.reasoning` is (a separate
|
|
160
|
-
* `reasoning_content`/`reasoning` field, or an inline `<think>` block split out of `content`).
|
|
161
|
-
* Populated by the STREAMED path only — `routerChatWithTools` discards reasoning today and its
|
|
162
|
-
* behavior is preserved unchanged, so a buffered turn still leaves this undefined.
|
|
163
|
-
*/
|
|
164
|
-
reasoning?: string;
|
|
165
|
-
/**
|
|
166
|
-
* The provider's `finish_reason` for the turn (`'stop'`, `'tool_calls'`, `'length'`, …).
|
|
167
|
-
* Populated by the STREAMED path only. `'length'` is the truncation signal the buffered path
|
|
168
|
-
* cannot surface: it says the turn hit `max_tokens`, not that the model chose to stop.
|
|
169
|
-
*/
|
|
170
|
-
finishReason?: string;
|
|
171
|
-
/**
|
|
172
|
-
* The turn happened and its token usage is UNKNOWN — not zero, not free. Set by the STREAMED
|
|
173
|
-
* transport when the stream ran to completion without a single usage-bearing chunk, which means
|
|
174
|
-
* the `stream_options.include_usage` contract was not honored upstream.
|
|
175
|
-
*
|
|
176
|
-
* It exists so a bare `usage: undefined` cannot read as a free turn: a metering caller branches
|
|
177
|
-
* on this marker and records an UNKNOWN turn (see the coordination driver's `meteredBrain`),
|
|
178
|
-
* rather than skipping the turn and letting a conserved budget pool believe it cost nothing.
|
|
179
|
-
*/
|
|
180
|
-
usageUnknown?: true;
|
|
181
|
-
}
|
|
182
|
-
/**
|
|
183
|
-
* A router completion WITH tool-calling — the operator driver's LLM seam. Passes OpenAI-shape
|
|
184
|
-
* `messages` (system/user/assistant-with-tool_calls/tool roles) + function `tools`, and returns the
|
|
185
|
-
* assistant text plus the tool calls the model wants run. Same fail-loud + real-usage discipline as
|
|
186
|
-
* `routerChatWithUsage`. `tool_choice: 'auto'` lets the model decide; the driver loops on the result.
|
|
187
|
-
*/
|
|
188
|
-
declare function routerChatWithTools(cfg: RouterConfig, messages: ReadonlyArray<Record<string, unknown>>, tools: ReadonlyArray<{
|
|
189
|
-
type: 'function';
|
|
190
|
-
function: {
|
|
191
|
-
name: string;
|
|
192
|
-
description?: string;
|
|
193
|
-
parameters: unknown;
|
|
194
|
-
};
|
|
195
|
-
}>, opts?: {
|
|
196
|
-
temperature?: number;
|
|
197
|
-
signal?: AbortSignal;
|
|
198
|
-
toolChoice?: 'auto' | 'required' | 'none';
|
|
199
|
-
maxTokens?: number;
|
|
200
|
-
}): Promise<RouterChatToolsResult>;
|
|
201
|
-
/**
|
|
202
|
-
* The SAME completion as `routerChatWithTools`, taken over SSE (`stream: true`) and reassembled
|
|
203
|
-
* into the identical `RouterChatToolsResult`. Opt in with `RouterConfig.stream` — the buffered
|
|
204
|
-
* function is untouched and stays the default for every existing caller.
|
|
205
|
-
*
|
|
206
|
-
* What it buys: a buffered POST holds one connection idle for the whole completion, and that idle
|
|
207
|
-
* window is what an intermediary gateway kills (524/503). Streaming puts bytes on the wire from the
|
|
208
|
-
* first generated token, so the connection is only idle through prefill.
|
|
209
|
-
*
|
|
210
|
-
* Usage accounting is preserved exactly: `stream_options.include_usage` asks the provider for a
|
|
211
|
-
* terminal usage chunk, and those tokens run through the same `meterTurn` the buffered path uses.
|
|
212
|
-
*
|
|
213
|
-
* When NO chunk reported usage, `usage`/`costUsd` stay undefined (never a fabricated 0) AND
|
|
214
|
-
* `usageUnknown: true` is set. A stream that finishes with no usage chunk means the
|
|
215
|
-
* `include_usage` request was not honored upstream, and returning a quiet `undefined` for it is
|
|
216
|
-
* indistinguishable from a free turn — the marker is what lets a metering caller record an UNKNOWN
|
|
217
|
-
* turn instead. Streaming raises the odds of this (one dropped terminal frame is enough), which is
|
|
218
|
-
* why the streamed transport says so explicitly and the buffered one has no equivalent claim to make.
|
|
219
|
-
*/
|
|
220
|
-
declare function streamRouterChatWithTools(cfg: RouterConfig, messages: ReadonlyArray<Record<string, unknown>>, tools: ReadonlyArray<ToolSpec>, opts?: {
|
|
221
|
-
temperature?: number;
|
|
222
|
-
signal?: AbortSignal;
|
|
223
|
-
toolChoice?: 'auto' | 'required' | 'none';
|
|
224
|
-
maxTokens?: number;
|
|
225
|
-
}): Promise<RouterChatToolsResult>;
|
|
226
|
-
interface ToolSpec {
|
|
227
|
-
type: 'function';
|
|
228
|
-
function: {
|
|
229
|
-
name: string;
|
|
230
|
-
description?: string;
|
|
231
|
-
parameters: unknown;
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
interface RouterToolLoopResult {
|
|
235
|
-
/** The model's final assistant text (the turn where it stopped calling tools, or the budget turn). */
|
|
236
|
-
final: string;
|
|
237
|
-
/** Inference turns spent (≤ maxTurns) — the equal-budget unit vs random@k. */
|
|
238
|
-
turns: number;
|
|
239
|
-
toolCalls: number;
|
|
240
|
-
/** The behavior trace: each tool call + its result, in order. What a trace-analyst
|
|
241
|
-
* steerer reads (behavior, never the verdict) to diagnose + redirect the next shot. */
|
|
242
|
-
toolTrace: Array<{
|
|
243
|
-
name: string;
|
|
244
|
-
args: string;
|
|
245
|
-
result: string;
|
|
246
|
-
}>;
|
|
247
|
-
usage: {
|
|
248
|
-
input: number;
|
|
249
|
-
output: number;
|
|
250
|
-
};
|
|
251
|
-
/** The full conversation after the loop (seed + every assistant/tool turn). Lets a caller
|
|
252
|
-
* CARRY the messages into the next shot (depth continuation) and read the trajectory. */
|
|
253
|
-
messages: Array<Record<string, unknown>>;
|
|
254
|
-
}
|
|
255
|
-
/**
|
|
256
|
-
* The tool-using router backend: a real agentic loop OVER the Tangle router (which
|
|
257
|
-
* supports tool-calling), off-box — no sandbox. Each turn is one router completion
|
|
258
|
-
* with `tools`; if the model emits tool_calls, `execute` runs them on the host and
|
|
259
|
-
* their results are folded back as `tool` messages; the loop repeats until the
|
|
260
|
-
* model answers without a tool call or the turn budget is hit. One turn = one
|
|
261
|
-
* inference call, so `maxTurns` is the equal-compute unit against random@k.
|
|
262
|
-
*
|
|
263
|
-
* This is the depth substrate for agentic gates (the worker ACTS, observes the real
|
|
264
|
-
* result, and continues) that the chat-only `routerChatWithUsage` cannot express.
|
|
265
|
-
*/
|
|
266
|
-
declare function routerToolLoop(cfg: RouterConfig, system: string, user: string, tools: ReadonlyArray<ToolSpec>, execute: (name: string, args: Record<string, unknown>) => Promise<string>, opts?: {
|
|
267
|
-
maxTurns?: number;
|
|
268
|
-
temperature?: number;
|
|
269
|
-
signal?: AbortSignal;
|
|
270
|
-
maxTokens?: number;
|
|
271
|
-
/** Seed the loop with an existing conversation (depth continuation) instead of
|
|
272
|
-
* `[system, user]`. When set, `system`/`user` are ignored. The array is copied. */
|
|
273
|
-
initialMessages?: ReadonlyArray<Record<string, unknown>>;
|
|
274
|
-
}): Promise<RouterToolLoopResult>;
|
|
275
|
-
/**
|
|
276
|
-
* The router as a supervisor BRAIN: the canonical `ToolLoopChat` seam backed by the router's
|
|
277
|
-
* tool-calling. The driver's spawn/observe/steer/await/stop turns become real router tool-calls.
|
|
278
|
-
* The turnkey production brain — tests script a mock `ToolLoopChat`; production passes
|
|
279
|
-
* `routerBrain(cfg)`. No message translation: the loop already speaks the router's OpenAI shape.
|
|
280
|
-
*
|
|
281
|
-
* Transport follows `cfg.stream`: buffered by default, SSE when the caller opts in. A supervisor
|
|
282
|
-
* turn is the longest completion in the system, so it is the call site streaming exists for.
|
|
283
|
-
*/
|
|
284
|
-
declare function routerBrain(cfg: RouterConfig, opts?: {
|
|
285
|
-
temperature?: number;
|
|
286
|
-
}): ToolLoopChat;
|
|
287
|
-
//#endregion
|
|
288
|
-
//#region src/mcp/local-harness.d.ts
|
|
289
|
-
/**
|
|
290
|
-
* Local coding harness available inside the sandbox — a narrowing of the shared `HarnessType`
|
|
291
|
-
* vocabulary, NOT a private spelling of it. The harness id is `claude-code`; `claude` is the
|
|
292
|
-
* EXECUTABLE name and lives only in the `command` field below. Keeping one vocabulary is what
|
|
293
|
-
* lets a `LocalHarness` be handed straight to the profile materializer and the capability table
|
|
294
|
-
* with no translation step.
|
|
295
|
-
*/
|
|
296
|
-
type LocalHarness = Extract<HarnessType, 'claude-code' | 'codex' | 'opencode'>;
|
|
297
|
-
/** Every local harness, in table order — the one list `AGENT_RUNTIME_LOCAL_HARNESSES` and any
|
|
298
|
-
* other harness enumeration reads, so adding a row above is the only edit a new harness needs. */
|
|
299
|
-
declare const LOCAL_HARNESSES: ReadonlyArray<LocalHarness>;
|
|
300
|
-
/** The harness a caller gets when it expresses no preference. A composition-root default, not a
|
|
301
|
-
* capability claim: one constant so the several entry points cannot drift apart. */
|
|
302
|
-
declare const DEFAULT_LOCAL_HARNESS: LocalHarness;
|
|
303
|
-
/** The CLI binary a harness id runs. The two are NOT the same string (`claude-code` runs `claude`),
|
|
304
|
-
* so anything spawning a harness — a version probe, a login check — reads it from here rather than
|
|
305
|
-
* passing the harness id as a command. */
|
|
306
|
-
declare function localHarnessExecutable(harness: LocalHarness): string;
|
|
307
|
-
/**
|
|
308
|
-
* Whether the harness's native control can express this reasoning effort. Admission checks read
|
|
309
|
-
* this so a profile the invocation would later refuse is rejected BEFORE any workspace state is
|
|
310
|
-
* created, against the same table that emits the argv.
|
|
311
|
-
*/
|
|
312
|
-
declare function harnessSupportsReasoningEffort(harness: LocalHarness, reasoningEffort: ReasoningEffort): boolean;
|
|
313
|
-
/** @experimental */
|
|
314
|
-
interface RunLocalHarnessOptions {
|
|
315
|
-
harness: LocalHarness;
|
|
316
|
-
/** Working directory for the subprocess (typically a worktree path). */
|
|
317
|
-
cwd: string;
|
|
318
|
-
/** Prompt forwarded as the harness CLI's task argument. */
|
|
319
|
-
taskPrompt: string;
|
|
320
|
-
/**
|
|
321
|
-
* Pre-built command + args (e.g. from `harnessInvocation` so the full authored
|
|
322
|
-
* `AgentProfile` — systemPrompt + model — reaches the harness). When set it OVERRIDES the
|
|
323
|
-
* default prompt-only `buildArgs(taskPrompt)` path; `command` defaults to the harness's
|
|
324
|
-
* default binary when only `args` is supplied. When absent the legacy prompt-only shape
|
|
325
|
-
* is used unchanged.
|
|
326
|
-
*/
|
|
327
|
-
invocation?: {
|
|
328
|
-
command?: string;
|
|
329
|
-
args: ReadonlyArray<string>;
|
|
330
|
-
};
|
|
331
|
-
/** Allow autonomous edits without an interactive approval gate, using whichever bypass argv the
|
|
332
|
-
* harness declares. Use only when `cwd` is an isolated candidate worktree. */
|
|
333
|
-
dangerouslySkipPermissions?: boolean;
|
|
334
|
-
/** Isolate Codex from ambient configuration/instructions and require JSONL token usage.
|
|
335
|
-
* The invocation should come from `harnessInvocation(..., { codexReproducible: true })`. */
|
|
336
|
-
codexReproducible?: boolean;
|
|
337
|
-
/** Absolute host paths that reproducible Codex must not read. The normalized set is compiled
|
|
338
|
-
* into the controlled permission profile and its digest is returned in execution evidence. */
|
|
339
|
-
codexReadDeniedPaths?: ReadonlyArray<string>;
|
|
340
|
-
/** Wall-clock kill deadline (ms). Default 5 min. Subprocess SIGTERMed on expiry. */
|
|
341
|
-
timeoutMs?: number;
|
|
342
|
-
/** Newest stdout/stderr bytes retained per stream. Default 64 MiB. */
|
|
343
|
-
maxOutputBytes?: number;
|
|
344
|
-
/** Caller cancellation. SIGTERM is sent on abort. */
|
|
345
|
-
signal?: AbortSignal;
|
|
346
|
-
/** Override env (defaults to inheriting from the parent). */
|
|
347
|
-
env?: NodeJS.ProcessEnv;
|
|
348
|
-
/**
|
|
349
|
-
* Test seam — inject a custom spawner so unit tests can mock the
|
|
350
|
-
* subprocess without touching the OS. Defaults to node's `child_process.spawn`.
|
|
351
|
-
*/
|
|
352
|
-
spawn?: (command: string, args: ReadonlyArray<string>, opts: {
|
|
353
|
-
cwd: string;
|
|
354
|
-
env: NodeJS.ProcessEnv;
|
|
355
|
-
stdio: 'pipe';
|
|
356
|
-
detached: boolean;
|
|
357
|
-
}) => ChildProcess;
|
|
358
|
-
/** Test seam for locating the native Codex executable before it is staged in the worktree. */
|
|
359
|
-
resolveCodexExecutable?: (command: string, env: NodeJS.ProcessEnv) => Promise<string>;
|
|
360
|
-
}
|
|
361
|
-
/** Exact aggregate usage emitted by Codex's terminal `turn.completed` JSONL event. */
|
|
362
|
-
interface CodexTokenUsage {
|
|
363
|
-
inputTokens: number;
|
|
364
|
-
cachedInputTokens: number;
|
|
365
|
-
outputTokens: number;
|
|
366
|
-
reasoningOutputTokens: number;
|
|
367
|
-
}
|
|
368
|
-
/** Isolation settings asserted before a reproducible Codex run is allowed to start. */
|
|
369
|
-
interface CodexExecutionPolicy {
|
|
370
|
-
sessionPersistence: 'ephemeral';
|
|
371
|
-
userConfig: false;
|
|
372
|
-
rules: false;
|
|
373
|
-
projectInstructions: false;
|
|
374
|
-
skillInstructions: false;
|
|
375
|
-
appInstructions: false;
|
|
376
|
-
toolSuggestions: false;
|
|
377
|
-
multiAgentInstructions: false;
|
|
378
|
-
sandbox: 'workspace-write';
|
|
379
|
-
permissionProfile: 'agent_runtime_reproducible';
|
|
380
|
-
approvalPolicy: 'never';
|
|
381
|
-
shellNetwork: false;
|
|
382
|
-
webSearch: false;
|
|
383
|
-
serviceTier: 'default';
|
|
384
|
-
shellEnvironment: 'core-filtered';
|
|
385
|
-
loginShell: false;
|
|
386
|
-
credentialsReadable: false;
|
|
387
|
-
hostHomeReadable: false;
|
|
388
|
-
procEnvironment: 'private-sanitized';
|
|
389
|
-
sensitiveEnvironmentNamesVisible: false;
|
|
390
|
-
parentRepoRead: false;
|
|
391
|
-
gitMetadata: false;
|
|
392
|
-
temporaryDirectory: 'workspace-private';
|
|
393
|
-
stagedExecutable: 'static-elf-read-only';
|
|
394
|
-
callerReadDeniedPaths: 'enforced';
|
|
395
|
-
containerSockets: false;
|
|
396
|
-
}
|
|
397
|
-
/** Zero-model-call evidence for the exact Codex process about to run. */
|
|
398
|
-
interface CodexExecutionEvidence {
|
|
399
|
-
cliVersion: string;
|
|
400
|
-
executableSha256: string;
|
|
401
|
-
/** SHA-256 of the exact composed prompt argument proved present in the rendered prompt. */
|
|
402
|
-
requestedPromptSha256: string;
|
|
403
|
-
effectivePromptSha256: string;
|
|
404
|
-
nonPromptArgsSha256: string;
|
|
405
|
-
controlledConfigSha256: string;
|
|
406
|
-
/** Sorted normalized paths compiled into the permission profile. */
|
|
407
|
-
readDeniedPaths: string[];
|
|
408
|
-
readDeniedPathsSha256: string;
|
|
409
|
-
readDeniedPathCount: number;
|
|
410
|
-
policy: CodexExecutionPolicy;
|
|
411
|
-
}
|
|
412
|
-
/** @experimental */
|
|
413
|
-
interface LocalHarnessResult {
|
|
414
|
-
/** OS exit code. `null` when killed before exit. */
|
|
415
|
-
exitCode: number | null;
|
|
416
|
-
/** Concatenated stdout. */
|
|
417
|
-
stdout: string;
|
|
418
|
-
/** Concatenated stderr. */
|
|
419
|
-
stderr: string;
|
|
420
|
-
/** Set when the process exited via signal (timeout / abort). */
|
|
421
|
-
killedBySignal: NodeJS.Signals | null;
|
|
422
|
-
/** Wall-clock duration ms (spawn → exit). */
|
|
423
|
-
durationMs: number;
|
|
424
|
-
/** Set when timeoutMs elapsed before exit. */
|
|
425
|
-
timedOut: boolean;
|
|
426
|
-
/**
|
|
427
|
-
* Set when the caller's AbortSignal fired before this result settled.
|
|
428
|
-
* Optional so injected runners and stored results from older releases remain valid.
|
|
429
|
-
*/
|
|
430
|
-
aborted?: boolean;
|
|
431
|
-
/** Present for a reproducible Codex run; parsed from the real terminal JSONL event. */
|
|
432
|
-
usage?: CodexTokenUsage;
|
|
433
|
-
/** Present for reproducible Codex runs; generated and checked before model execution. */
|
|
434
|
-
evidence?: CodexExecutionEvidence;
|
|
435
|
-
}
|
|
436
|
-
/**
|
|
437
|
-
* Spawn a local coding harness CLI as a subprocess + collect its output.
|
|
438
|
-
*
|
|
439
|
-
* NOT responsible for parsing the harness's output or extracting a diff —
|
|
440
|
-
* the in-process executor's `streamPrompt` orchestrates `git diff` against
|
|
441
|
-
* the worktree after this resolves. This function is intentionally narrow:
|
|
442
|
-
* spawn, wait, capture, return.
|
|
443
|
-
*
|
|
444
|
-
* Fails loud — throws when:
|
|
445
|
-
* - `cwd` doesn't exist (subprocess emits ENOENT; surfaced as Error)
|
|
446
|
-
* - the harness binary is not on PATH (ENOENT)
|
|
447
|
-
* - the caller signal was already aborted before process launch
|
|
448
|
-
*
|
|
449
|
-
* Does NOT throw when:
|
|
450
|
-
* - the subprocess exits non-zero (`result.exitCode` carries the code)
|
|
451
|
-
* - a non-reproducible subprocess is aborted / timed out (`result.aborted` /
|
|
452
|
-
* `result.timedOut` carries the reason even when a TERM-aware child exits zero)
|
|
453
|
-
*
|
|
454
|
-
* Reproducible Codex additionally requires a terminal usage event. If cancellation
|
|
455
|
-
* prevents that event, this rejects with `CodexExecutionDiagnosticError` instead of
|
|
456
|
-
* returning an incomplete reproducibility receipt.
|
|
457
|
-
*
|
|
458
|
-
* @experimental
|
|
459
|
-
*/
|
|
460
|
-
declare function runLocalHarness(options: RunLocalHarnessOptions): Promise<LocalHarnessResult>;
|
|
461
|
-
/** Parse and validate the one terminal usage event emitted by `codex exec --json`. */
|
|
462
|
-
declare function parseCodexTokenUsage(stdout: string): CodexTokenUsage;
|
|
463
|
-
//#endregion
|
|
464
|
-
export { streamRouterChatWithTools as C, ToolLoopMessageRecord as D, ToolLoopCompactionOptions as E, routerToolLoop as S, ToolLoopCompaction as T, RouterToolLoopResult as _, LOCAL_HARNESSES as a, routerChatWithTools as b, RunLocalHarnessOptions as c, parseCodexTokenUsage as d, runLocalHarness as f, RouterToolCall as g, RouterConfig as h, DEFAULT_LOCAL_HARNESS as i, harnessSupportsReasoningEffort as l, RouterChatToolsResult as m, CodexExecutionPolicy as n, LocalHarness as o, RouterChatResult as p, CodexTokenUsage as r, LocalHarnessResult as s, CodexExecutionEvidence as t, localHarnessExecutable as u, ToolSpec as v, ToolLoopChat as w, routerChatWithUsage as x, routerBrain as y };
|
|
465
|
-
//# sourceMappingURL=local-harness-BIajef4A.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"loop-runner-bin-CWqOpCEw.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,u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/** Default Tangle Router base URL used when no env override is set. */
|
|
3
|
-
const DEFAULT_ROUTER_BASE_URL = "https://router.tangle.tools";
|
|
4
|
-
/** Resolve the router base URL from env, normalised — no trailing `/v1` or `/`. */
|
|
5
|
-
function resolveRouterBaseUrl(env = {}) {
|
|
6
|
-
return (env.TANGLE_ROUTER_URL ?? env.TANGLE_ROUTER_BASE_URL ?? "https://router.tangle.tools").replace(/\/v1\/?$/, "").replace(/\/$/, "");
|
|
7
|
-
}
|
|
8
|
-
/**
|
|
9
|
-
* Fetch the model catalog from the router's `/v1/models`. Throws on a non-2xx
|
|
10
|
-
* response — callers decide whether to fail open (empty catalog) or closed.
|
|
11
|
-
*/
|
|
12
|
-
async function getModels(routerBaseUrl = DEFAULT_ROUTER_BASE_URL) {
|
|
13
|
-
const res = await fetch(`${routerBaseUrl}/v1/models`, { headers: { Accept: "application/json" } });
|
|
14
|
-
if (!res.ok) throw new Error(`router /v1/models ${res.status}`);
|
|
15
|
-
const body = await res.json();
|
|
16
|
-
return Array.isArray(body.data) ? body.data : [];
|
|
17
|
-
}
|
|
18
|
-
/** Trim a candidate model id; `undefined` for non-strings and blanks. */
|
|
19
|
-
function cleanModelId(value) {
|
|
20
|
-
if (typeof value !== "string") return void 0;
|
|
21
|
-
const trimmed = value.trim();
|
|
22
|
-
return trimmed.length > 0 ? trimmed : void 0;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Resolve a chat model by precedence: the first candidate carrying a
|
|
26
|
-
* non-blank model wins, else `fallback`. The caller owns the precedence
|
|
27
|
-
* order, so each product keeps its own policy (request → workspace → env,
|
|
28
|
-
* etc.) while the first-non-blank logic and the telemetry shape stay shared.
|
|
29
|
-
*/
|
|
30
|
-
function resolveChatModel(candidates, fallback) {
|
|
31
|
-
for (const candidate of candidates) {
|
|
32
|
-
const model = cleanModelId(candidate.model);
|
|
33
|
-
if (model) return {
|
|
34
|
-
source: candidate.source,
|
|
35
|
-
model
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
return fallback;
|
|
39
|
-
}
|
|
40
|
-
const WELL_FORMED_MODEL_ID = /^[A-Za-z0-9._/@:-]+$/;
|
|
41
|
-
function isWellFormedModelId(modelId) {
|
|
42
|
-
return modelId.length <= 200 && WELL_FORMED_MODEL_ID.test(modelId);
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Every id a catalog entry can be addressed by — its bare id, plus a
|
|
46
|
-
* `provider/id` form when the router exposes a separate provider slug.
|
|
47
|
-
*/
|
|
48
|
-
function catalogIdsForModel(model) {
|
|
49
|
-
const ids = /* @__PURE__ */ new Set();
|
|
50
|
-
const id = cleanModelId(model.id);
|
|
51
|
-
if (id) ids.add(id);
|
|
52
|
-
const provider = cleanModelId(model._provider) ?? cleanModelId(model.provider);
|
|
53
|
-
if (provider && id && !id.includes("/")) ids.add(`${provider}/${id}`);
|
|
54
|
-
return [...ids];
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Validate a caller-supplied chat-model id. Rejects non-strings, malformed
|
|
58
|
-
* ids, and ids absent from both the caller's `allowlist` and the live router
|
|
59
|
-
* catalog. Fails closed: when the catalog cannot be fetched, an unverifiable
|
|
60
|
-
* id is rejected rather than admitted — a bad model never reaches the agent.
|
|
61
|
-
*/
|
|
62
|
-
async function validateChatModelId(modelId, options = {}) {
|
|
63
|
-
const { allowlist = [], routerBaseUrl = DEFAULT_ROUTER_BASE_URL, loadModels = getModels } = options;
|
|
64
|
-
const cleaned = cleanModelId(modelId);
|
|
65
|
-
if (!cleaned) return {
|
|
66
|
-
succeeded: false,
|
|
67
|
-
error: "Model id must be a non-empty string."
|
|
68
|
-
};
|
|
69
|
-
if (!isWellFormedModelId(cleaned)) return {
|
|
70
|
-
succeeded: false,
|
|
71
|
-
error: `Model id is malformed: ${cleaned}`
|
|
72
|
-
};
|
|
73
|
-
if (allowlist.some((id) => cleanModelId(id) === cleaned)) return {
|
|
74
|
-
succeeded: true,
|
|
75
|
-
value: cleaned
|
|
76
|
-
};
|
|
77
|
-
let catalog;
|
|
78
|
-
try {
|
|
79
|
-
catalog = await loadModels(routerBaseUrl);
|
|
80
|
-
} catch (err) {
|
|
81
|
-
return {
|
|
82
|
-
succeeded: false,
|
|
83
|
-
error: `Could not validate model catalog: ${err instanceof Error ? err.message : String(err)}`
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
if (!new Set(catalog.flatMap(catalogIdsForModel)).has(cleaned)) return {
|
|
87
|
-
succeeded: false,
|
|
88
|
-
error: `Model is not available: ${cleaned}`
|
|
89
|
-
};
|
|
90
|
-
return {
|
|
91
|
-
succeeded: true,
|
|
92
|
-
value: cleaned
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
//#endregion
|
|
96
|
-
export { resolveRouterBaseUrl as a, resolveChatModel as i, cleanModelId as n, validateChatModelId as o, getModels as r, DEFAULT_ROUTER_BASE_URL as t };
|
|
97
|
-
|
|
98
|
-
//# sourceMappingURL=model-resolution-Btd9iIKV.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"model-resolution-Btd9iIKV.js","names":[],"sources":["../src/model-resolution.ts"],"sourcesContent":["/**\n *\n * Chat-model resolution + catalog validation — the shared primitive every\n * product chat handler needs and was, until now, hand-rolling. Lifts the\n * router `/v1/models` fetch, the fail-closed id validation, and the\n * precedence resolver out of four near-identical per-repo copies.\n *\n * Policy-free by design: callers pass their own precedence order\n * (`resolveChatModel`) and their own known-good `allowlist`\n * (`validateChatModelId`), so each product keeps its resolution policy while\n * sharing the catalog fetch, the malformed-id guard, and the fail-closed\n * admission rule. No React, no `process.env` assumption — `env` is an\n * explicit narrow record so this runs unchanged in Node and in Workers.\n *\n * @stable\n */\n\n/**\n * A model entry as returned by the Tangle Router `/v1/models` endpoint.\n * Intentionally minimal — only the fields resolution + validation read.\n */\nexport interface ModelInfo {\n id: string\n name?: string\n description?: string\n /** Provider slug, when the router exposes it (`provider` or `_provider`). */\n provider?: string\n _provider?: string\n architecture?: {\n modality?: string\n input_modalities?: string[]\n output_modalities?: string[]\n }\n}\n\n/** Env keys the router base URL is resolved from. */\nexport interface RouterEnv {\n TANGLE_ROUTER_URL?: string\n TANGLE_ROUTER_BASE_URL?: string\n}\n\n/** Default Tangle Router base URL used when no env override is set. */\nexport const DEFAULT_ROUTER_BASE_URL = 'https://router.tangle.tools'\n\n/** Resolve the router base URL from env, normalised — no trailing `/v1` or `/`. */\nexport function resolveRouterBaseUrl(env: RouterEnv = {}): string {\n return (env.TANGLE_ROUTER_URL ?? env.TANGLE_ROUTER_BASE_URL ?? DEFAULT_ROUTER_BASE_URL)\n .replace(/\\/v1\\/?$/, '')\n .replace(/\\/$/, '')\n}\n\n/**\n * Fetch the model catalog from the router's `/v1/models`. Throws on a non-2xx\n * response — callers decide whether to fail open (empty catalog) or closed.\n */\nexport async function getModels(\n routerBaseUrl: string = DEFAULT_ROUTER_BASE_URL,\n): Promise<ModelInfo[]> {\n const res = await fetch(`${routerBaseUrl}/v1/models`, {\n headers: { Accept: 'application/json' },\n })\n if (!res.ok) throw new Error(`router /v1/models ${res.status}`)\n const body = (await res.json()) as { data?: ModelInfo[] }\n return Array.isArray(body.data) ? body.data : []\n}\n\n/** Trim a candidate model id; `undefined` for non-strings and blanks. */\nexport function cleanModelId(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nexport interface ChatModelCandidate {\n /** Stable label for telemetry — e.g. `request`, `workspace`, `env`. */\n source: string\n model: string | undefined\n}\n\nexport interface ResolvedChatModel {\n source: string\n model: string\n}\n\n/**\n * Resolve a chat model by precedence: the first candidate carrying a\n * non-blank model wins, else `fallback`. The caller owns the precedence\n * order, so each product keeps its own policy (request → workspace → env,\n * etc.) while the first-non-blank logic and the telemetry shape stay shared.\n */\nexport function resolveChatModel(\n candidates: ChatModelCandidate[],\n fallback: ResolvedChatModel,\n): ResolvedChatModel {\n for (const candidate of candidates) {\n const model = cleanModelId(candidate.model)\n if (model) return { source: candidate.source, model }\n }\n return fallback\n}\n\nexport type ChatModelValidation =\n | { succeeded: true; value: string }\n | { succeeded: false; error: string }\n\nconst WELL_FORMED_MODEL_ID = /^[A-Za-z0-9._/@:-]+$/\n\nfunction isWellFormedModelId(modelId: string): boolean {\n return modelId.length <= 200 && WELL_FORMED_MODEL_ID.test(modelId)\n}\n\n/**\n * Every id a catalog entry can be addressed by — its bare id, plus a\n * `provider/id` form when the router exposes a separate provider slug.\n */\nfunction catalogIdsForModel(model: ModelInfo): string[] {\n const ids = new Set<string>()\n const id = cleanModelId(model.id)\n if (id) ids.add(id)\n const provider = cleanModelId(model._provider) ?? cleanModelId(model.provider)\n if (provider && id && !id.includes('/')) ids.add(`${provider}/${id}`)\n return [...ids]\n}\n\n/**\n * Validate a caller-supplied chat-model id. Rejects non-strings, malformed\n * ids, and ids absent from both the caller's `allowlist` and the live router\n * catalog. Fails closed: when the catalog cannot be fetched, an unverifiable\n * id is rejected rather than admitted — a bad model never reaches the agent.\n */\nexport async function validateChatModelId(\n modelId: unknown,\n options: {\n /**\n * Known-good ids that skip the catalog round trip — e.g. the product's\n * default model plus any env-configured ids.\n */\n allowlist?: string[]\n routerBaseUrl?: string\n /** Injectable catalog loader — overridden in tests. */\n loadModels?: (routerBaseUrl: string) => Promise<ModelInfo[]>\n } = {},\n): Promise<ChatModelValidation> {\n const {\n allowlist = [],\n routerBaseUrl = DEFAULT_ROUTER_BASE_URL,\n loadModels = getModels,\n } = options\n\n const cleaned = cleanModelId(modelId)\n if (!cleaned) return { succeeded: false, error: 'Model id must be a non-empty string.' }\n if (!isWellFormedModelId(cleaned)) {\n return { succeeded: false, error: `Model id is malformed: ${cleaned}` }\n }\n if (allowlist.some((id) => cleanModelId(id) === cleaned)) {\n return { succeeded: true, value: cleaned }\n }\n\n let catalog: ModelInfo[]\n try {\n catalog = await loadModels(routerBaseUrl)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return { succeeded: false, error: `Could not validate model catalog: ${message}` }\n }\n\n const ids = new Set(catalog.flatMap(catalogIdsForModel))\n if (!ids.has(cleaned)) return { succeeded: false, error: `Model is not available: ${cleaned}` }\n return { succeeded: true, value: cleaned }\n}\n"],"mappings":";;AA0CA,MAAa,0BAA0B;;AAGvC,SAAgB,qBAAqB,MAAiB,CAAC,GAAW;CAChE,QAAQ,IAAI,qBAAqB,IAAI,0BAAA,8BAAA,CAClC,QAAQ,YAAY,EAAE,CAAC,CACvB,QAAQ,OAAO,EAAE;AACtB;;;;;AAMA,eAAsB,UACpB,gBAAwB,yBACF;CACtB,MAAM,MAAM,MAAM,MAAM,GAAG,cAAc,aAAa,EACpD,SAAS,EAAE,QAAQ,mBAAmB,EACxC,CAAC;CACD,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,qBAAqB,IAAI,QAAQ;CAC9D,MAAM,OAAQ,MAAM,IAAI,KAAK;CAC7B,OAAO,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC;AACjD;;AAGA,SAAgB,aAAa,OAAoC;CAC/D,IAAI,OAAO,UAAU,UAAU,OAAO,KAAA;CACtC,MAAM,UAAU,MAAM,KAAK;CAC3B,OAAO,QAAQ,SAAS,IAAI,UAAU,KAAA;AACxC;;;;;;;AAmBA,SAAgB,iBACd,YACA,UACmB;CACnB,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,QAAQ,aAAa,UAAU,KAAK;EAC1C,IAAI,OAAO,OAAO;GAAE,QAAQ,UAAU;GAAQ;EAAM;CACtD;CACA,OAAO;AACT;AAMA,MAAM,uBAAuB;AAE7B,SAAS,oBAAoB,SAA0B;CACrD,OAAO,QAAQ,UAAU,OAAO,qBAAqB,KAAK,OAAO;AACnE;;;;;AAMA,SAAS,mBAAmB,OAA4B;CACtD,MAAM,sBAAM,IAAI,IAAY;CAC5B,MAAM,KAAK,aAAa,MAAM,EAAE;CAChC,IAAI,IAAI,IAAI,IAAI,EAAE;CAClB,MAAM,WAAW,aAAa,MAAM,SAAS,KAAK,aAAa,MAAM,QAAQ;CAC7E,IAAI,YAAY,MAAM,CAAC,GAAG,SAAS,GAAG,GAAG,IAAI,IAAI,GAAG,SAAS,GAAG,IAAI;CACpE,OAAO,CAAC,GAAG,GAAG;AAChB;;;;;;;AAQA,eAAsB,oBACpB,SACA,UASI,CAAC,GACyB;CAC9B,MAAM,EACJ,YAAY,CAAC,GACb,gBAAgB,yBAChB,aAAa,cACX;CAEJ,MAAM,UAAU,aAAa,OAAO;CACpC,IAAI,CAAC,SAAS,OAAO;EAAE,WAAW;EAAO,OAAO;CAAuC;CACvF,IAAI,CAAC,oBAAoB,OAAO,GAC9B,OAAO;EAAE,WAAW;EAAO,OAAO,0BAA0B;CAAU;CAExE,IAAI,UAAU,MAAM,OAAO,aAAa,EAAE,MAAM,OAAO,GACrD,OAAO;EAAE,WAAW;EAAM,OAAO;CAAQ;CAG3C,IAAI;CACJ,IAAI;EACF,UAAU,MAAM,WAAW,aAAa;CAC1C,SAAS,KAAK;EAEZ,OAAO;GAAE,WAAW;GAAO,OAAO,qCADlB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EACkB;CACnF;CAGA,IAAI,CAAC,IADW,IAAI,QAAQ,QAAQ,kBAAkB,CAC/C,CAAC,CAAC,IAAI,OAAO,GAAG,OAAO;EAAE,WAAW;EAAO,OAAO,2BAA2B;CAAU;CAC9F,OAAO;EAAE,WAAW;EAAM,OAAO;CAAQ;AAC3C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"openai-tools-D3XfrrQ6.js","names":[],"sources":["../src/mcp/openai-tools.ts"],"sourcesContent":["/**\n *\n * OpenAI Chat Completions `tools[]` projection of the queue-bound agent-runtime\n * MCP delegation tools.\n *\n * Use when configuring `createOpenAICompatibleBackend({ tools: ... })` so the\n * model can call `delegate_feedback`, `delegation_status`, and\n * `delegation_history` through the OpenAI-compat transport (tcloud, OpenRouter,\n * OpenAI direct, cli-bridge). The runtime surfaces tool calls as `tool_call`\n * stream events — execution is the caller's responsibility (typically the\n * parent sandbox runtime's MCP mount).\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n *\n * @experimental\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compat backend JSON-serializes the body so a shallow copy\n // into a plain object is sufficient — and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n *\n * Returns the queue-bound delegation tools projected into OpenAI Chat\n * Completions `tools[]` shape. The order is stable: `delegate_feedback`,\n * `delegation_status`, `delegation_history`.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n"],"mappings":";;AAwCA,SAAS,UACP,MACA,aACA,YACgB;CAKhB,OAAO;EACL,MAAM;EACN,UAAU;GAAE;GAAM;GAAa,YAAY,EAAE,GAAG,WAAW;EAAE;CAC/D;AACF;;;;;;;;;AAUA,SAAgB,wBAA0C;CACxD,OAAO;EACL,UACE,6BACA,+BACA,8BACF;EACA,UACE,6BACA,+BACA,8BACF;EACA,UACE,8BACA,gCACA,+BACF;CACF;AACF;;;;;;;;;;AAWA,SAAgB,4BAA4B,OAAgD;CAC1F,MAAM,UAAU,IAAI,IAAI,KAAK;CAC7B,OAAO,sBAAsB,CAAC,CAAC,QAAQ,SAAS,QAAQ,IAAI,KAAK,SAAS,IAAI,CAAC;AACjF"}
|