@trama-dev/runtime 0.7.0 → 0.8.0
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/dist/agent-backend.d.ts +49 -0
- package/dist/agent-hosts.d.ts +8 -0
- package/dist/agent-hosts.js +1 -0
- package/dist/agent.d.ts +3 -1
- package/dist/agent.js +1 -0
- package/dist/bridge-client.js +1 -0
- package/dist/budget.d.ts +6 -0
- package/dist/budget.js +1 -0
- package/dist/client.d.ts +3 -2
- package/dist/client.js +20 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +4 -1
- package/dist/ipc-server.js +6 -1
- package/dist/journal-view.d.ts +8 -0
- package/dist/journal-view.js +45 -3
- package/dist/journal.js +45 -1
- package/dist/model-relay.d.ts +19 -0
- package/dist/model-relay.js +56 -4
- package/dist/model-request.d.ts +9 -0
- package/dist/model-request.js +185 -0
- package/dist/pi-adapter.d.ts +12 -11
- package/dist/pi-adapter.js +51 -5
- package/dist/project.d.ts +8 -0
- package/dist/project.js +18 -1
- package/dist/runner-backend.js +31 -7
- package/dist/runner-types.d.ts +18 -0
- package/dist/runner.d.ts +2 -2
- package/dist/runner.js +92 -9
- package/dist/schema.d.ts +7 -0
- package/dist/schema.js +9 -0
- package/dist/tools.d.ts +8 -1
- package/dist/tools.js +5 -3
- package/dist/types.d.ts +128 -0
- package/dist/workspace.d.ts +8 -1
- package/dist/workspace.js +12 -1
- package/package.json +1 -1
package/dist/agent-backend.d.ts
CHANGED
|
@@ -182,6 +182,41 @@ export declare class CutOff extends Error {
|
|
|
182
182
|
readonly text: string;
|
|
183
183
|
constructor(text: string);
|
|
184
184
|
}
|
|
185
|
+
/**
|
|
186
|
+
* One request to a model: what it is to be sent — the conversation so far,
|
|
187
|
+
* and beside it what the model is told to be and the tools it may call, each
|
|
188
|
+
* declared — and how it is asked. Plain data, all of it, held to its shape by
|
|
189
|
+
* whoever made it (see model-request.ts): a backend sends it as it is.
|
|
190
|
+
*/
|
|
191
|
+
export interface ModelAsk {
|
|
192
|
+
context: {
|
|
193
|
+
systemPrompt?: string;
|
|
194
|
+
messages: Array<Record<string, unknown>>;
|
|
195
|
+
tools?: Array<{
|
|
196
|
+
name: string;
|
|
197
|
+
description: string;
|
|
198
|
+
parameters: Record<string, unknown>;
|
|
199
|
+
}>;
|
|
200
|
+
};
|
|
201
|
+
/** The model that is to answer, as the backend names its models — in place of the one it would ask. */
|
|
202
|
+
model?: string;
|
|
203
|
+
/** How much the model is to think, as the backend names its levels. */
|
|
204
|
+
thinking?: string;
|
|
205
|
+
/** The most the reply may come to, in tokens. */
|
|
206
|
+
maxTokens?: number;
|
|
207
|
+
temperature?: number;
|
|
208
|
+
/** Whether the model may call the tools it is told of ("auto", as it is without this) or is to answer without ("none"). */
|
|
209
|
+
toolChoice?: "auto" | "none";
|
|
210
|
+
/** How long the provider is waited for, in milliseconds. */
|
|
211
|
+
timeout?: number;
|
|
212
|
+
}
|
|
213
|
+
/** What goes with one request to a model, and is no part of it. */
|
|
214
|
+
export interface ModelCall {
|
|
215
|
+
/** Cancels the request. A cancelled request rejects. */
|
|
216
|
+
signal?: AbortSignal;
|
|
217
|
+
/** Told what the request used, at most once and before it settles — however it ended. (It does not throw.) */
|
|
218
|
+
used?: (usage: AgentUsage) => void;
|
|
219
|
+
}
|
|
185
220
|
export interface AgentBackend {
|
|
186
221
|
/**
|
|
187
222
|
* Run one prompt to completion and return the agent's final text. A final
|
|
@@ -192,4 +227,18 @@ export interface AgentBackend {
|
|
|
192
227
|
* honour something in `call` must reject, never silently ignore it.
|
|
193
228
|
*/
|
|
194
229
|
ask(prompt: string, call: AgentCall): Promise<string>;
|
|
230
|
+
/**
|
|
231
|
+
* Ask the backend's model once, and return its one reply: no agent, no
|
|
232
|
+
* tool run, nothing asked again — whoever asks is the harness. The reply
|
|
233
|
+
* is the model's as the backend has replies: plain data, to be sent back
|
|
234
|
+
* as it came where the conversation goes on. What is the model's doing is
|
|
235
|
+
* a reply, and is read in it: one that was cut off at its limit, and one
|
|
236
|
+
* the provider failed (its `stopReason` is "error", and `errorMessage`
|
|
237
|
+
* says how). What is not rejects: a model the backend has not got, or
|
|
238
|
+
* cannot ask; a level it does not think at; a request that was cancelled.
|
|
239
|
+
*
|
|
240
|
+
* As of `ask`: each stands alone, and what a backend cannot honour of a
|
|
241
|
+
* request it rejects.
|
|
242
|
+
*/
|
|
243
|
+
complete(request: ModelAsk, call: ModelCall): Promise<Record<string, unknown>>;
|
|
195
244
|
}
|
package/dist/agent-hosts.d.ts
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
import { type AgentCall } from "./agent-backend.js";
|
|
2
|
+
import { type ModelRelay } from "./model-relay.js";
|
|
2
3
|
import type { ModelConfig } from "./runner-types.js";
|
|
3
4
|
export interface AgentHosts {
|
|
4
5
|
/** Have a host serve one call, as the adapter would (see AgentBackend.ask). */
|
|
5
6
|
ask(config: ModelConfig, prompt: string, call: AgentCall): Promise<string>;
|
|
7
|
+
/**
|
|
8
|
+
* Who asks the models of the calls these hosts serve, where the hosts were
|
|
9
|
+
* started with variables: a process started with the same, that serves no
|
|
10
|
+
* call. To be asked by for what is no call of an agent's — one request to
|
|
11
|
+
* a model — and is to be asked with a run's variables all the same.
|
|
12
|
+
*/
|
|
13
|
+
readonly asks: ModelRelay;
|
|
6
14
|
/** End every host: what they were for is over. Resolves when none is left. (A call made after this starts one anew.) */
|
|
7
15
|
close(): Promise<void>;
|
|
8
16
|
}
|
package/dist/agent-hosts.js
CHANGED
package/dist/agent.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentOptions, Schema } from "./types.js";
|
|
2
|
-
import { type AgentBackend, type AgentCall, type OwnTool } from "./agent-backend.js";
|
|
2
|
+
import { type AgentBackend, type AgentCall, type ModelAsk, type OwnTool } from "./agent-backend.js";
|
|
3
3
|
/**
|
|
4
4
|
* The program in an LLM reply that was asked to contain nothing else: the last
|
|
5
5
|
* fenced block if there is one (models add explanations, or show a "before"
|
|
@@ -38,6 +38,8 @@ export interface RunnerAgent {
|
|
|
38
38
|
prompt: string;
|
|
39
39
|
schema: Schema;
|
|
40
40
|
}, used?: Used, ownTools?: OwnTool[]): Promise<T>;
|
|
41
|
+
/** One request to the model, held to its shape already (see model-request.ts), and its one reply. */
|
|
42
|
+
complete(request: ModelAsk, used?: Used): Promise<Record<string, unknown>>;
|
|
41
43
|
}
|
|
42
44
|
/**
|
|
43
45
|
* The `agent` a program talks to: its calls, served by `backend` working in
|
package/dist/agent.js
CHANGED
|
@@ -116,6 +116,7 @@ export function createAgent(backend, cwd, signal) {
|
|
|
116
116
|
const { system, model, thinking, tools, skills, templates, extensions, cutOff } = options ?? {};
|
|
117
117
|
return ask(prompt, { cwd, system, signal, ...asked({ model, thinking, tools, ownTools, skills, templates, extensions, used }) }, cutOff);
|
|
118
118
|
},
|
|
119
|
+
complete: (request, used) => backend.complete(request, { signal, ...(used && { used }) }),
|
|
119
120
|
async generate(input, used, ownTools) {
|
|
120
121
|
if (!isJsonObject(input.schema))
|
|
121
122
|
throw new Error("Schema validation failed: a schema is an object of the fields the answer is to have");
|
package/dist/bridge-client.js
CHANGED
|
@@ -125,5 +125,6 @@ export function remoteWorkspace(call, dir) {
|
|
|
125
125
|
write: (path, content) => call("/workspace/write", { dir, path, content }),
|
|
126
126
|
list: (pattern) => call("/workspace/list", { dir, pattern }),
|
|
127
127
|
observe: async (pattern, options) => call("/workspace/observe", withOptions({ dir, pattern }, options)),
|
|
128
|
+
shell: async (command, options) => call("/workspace/shell", withOptions({ dir, command }, options)),
|
|
128
129
|
};
|
|
129
130
|
}
|
package/dist/budget.d.ts
CHANGED
|
@@ -42,6 +42,12 @@ export interface Meter {
|
|
|
42
42
|
reached(): string | undefined;
|
|
43
43
|
/** Add to the count, here and above: calls taken on, and what calls used — more than was said of them before, or less. */
|
|
44
44
|
count(calls: number, cost: number, tokens: number): void;
|
|
45
|
+
/** What it has counted so far: the calls taken on, and what they have said they used. */
|
|
46
|
+
counted(): {
|
|
47
|
+
calls: number;
|
|
48
|
+
cost: number;
|
|
49
|
+
tokens: number;
|
|
50
|
+
};
|
|
45
51
|
}
|
|
46
52
|
/**
|
|
47
53
|
* The count of what a run uses, held to `limit`. What it counts is counted
|
package/dist/budget.js
CHANGED
package/dist/client.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import type { Ctx, Agent, AgentOptions, AgentTool, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace } from "./types.js";
|
|
2
|
-
export type { Ctx, Agent, AgentOptions, AgentTool, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace };
|
|
1
|
+
import type { Ctx, Agent, AgentOptions, AgentTool, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace, ModelRequest, ModelReply, ModelMessage, TextPart, ImagePart, ThinkingPart, ToolCallPart } from "./types.js";
|
|
2
|
+
export type { Ctx, Agent, AgentOptions, AgentTool, Thinking, Schema, SchemaField, ShellResult, Tools, ObserveResult, Workspace, ModelRequest, ModelReply, ModelMessage, TextPart, ImagePart, ThinkingPart, ToolCallPart };
|
|
3
3
|
export declare const ctx: Ctx;
|
|
4
4
|
export declare const agent: Agent;
|
|
5
5
|
export declare const tools: Tools;
|
|
6
6
|
/** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
|
|
7
7
|
export declare const workspace: Workspace;
|
|
8
|
+
export { heldTo } from "./schema.js";
|
package/dist/client.js
CHANGED
|
@@ -171,9 +171,28 @@ async function agentCall(endpoint, body) {
|
|
|
171
171
|
await waiting;
|
|
172
172
|
}
|
|
173
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* A request to a model as it is sent: of each tool, what it declares. Its
|
|
176
|
+
* function stays here, and waits for nobody: no agent is asked that would
|
|
177
|
+
* call it — the program reads the model's calls in the reply, and runs what
|
|
178
|
+
* it will.
|
|
179
|
+
*/
|
|
180
|
+
function asSent(request) {
|
|
181
|
+
const tools = isOwn(request) ? request.tools : undefined;
|
|
182
|
+
if (!Array.isArray(tools))
|
|
183
|
+
return request;
|
|
184
|
+
const declared = tools.map((tool) => {
|
|
185
|
+
if (!isOwn(tool))
|
|
186
|
+
return tool;
|
|
187
|
+
const { run: _run, ...rest } = tool;
|
|
188
|
+
return rest;
|
|
189
|
+
});
|
|
190
|
+
return { ...request, tools: declared };
|
|
191
|
+
}
|
|
174
192
|
export const agent = {
|
|
175
193
|
instruct: async (prompt, opts) => agentCall("/agent/instruct", withOptions({ prompt }, opts)),
|
|
176
194
|
generate: async (input) => agentCall("/agent/generate", input),
|
|
195
|
+
complete: async (request) => call("/agent/complete", asSent(request)),
|
|
177
196
|
};
|
|
178
197
|
export const tools = {
|
|
179
198
|
read: (path) => call("/tools/read", { path }),
|
|
@@ -188,3 +207,4 @@ export const workspace = remoteWorkspace((endpoint, body) => {
|
|
|
188
207
|
}
|
|
189
208
|
return call(endpoint, body);
|
|
190
209
|
});
|
|
210
|
+
export { heldTo } from "./schema.js";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export type { Budget, ProgramResult, RunOptions } from "./runner-types.js";
|
|
2
2
|
export { failureOf } from "./runner.js";
|
|
3
|
+
export { requestsWhole } from "./journal-view.js";
|
|
3
4
|
import type { ProgramResult, RunOptions } from "./runner-types.js";
|
|
4
5
|
export type { Workspace, ObserveResult } from "./types.js";
|
|
5
6
|
import type { Workspace } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -9,7 +9,7 @@ import { onAbort, throwIfAborted } from "./abort.js";
|
|
|
9
9
|
import { createMeter } from "./budget.js";
|
|
10
10
|
import { LATEST_LOG_PATH } from "./context.js";
|
|
11
11
|
import { readProjectMeta } from "./meta.js";
|
|
12
|
-
import { ensureProjectScaffold, loadConfig, loadProjectConfig, loadState } from "./project.js";
|
|
12
|
+
import { ensureProjectScaffold, loadConfig, loadProjectConfig, loadState, namesAPath, projectNamed } from "./project.js";
|
|
13
13
|
import { createBackend, saysOnce } from "./runner-backend.js";
|
|
14
14
|
import { validateProgram, installValidatedProgram, withTempDir, prepareProject, shownPaths, RUNTIME_TYPES, runProgram as runHere, whyNotReplaceable, tagged, } from "./runner.js";
|
|
15
15
|
import { createWorkspace as workspaceHere, ensureWorkspaceDir } from "./workspace.js";
|
|
@@ -18,6 +18,7 @@ import { guardPath, identityOf, sameProjectAs } from "./path-guard.js";
|
|
|
18
18
|
import { printJournals, spentIn } from "./journal-view.js";
|
|
19
19
|
import { messageOf } from "./errors.js";
|
|
20
20
|
export { failureOf } from "./runner.js";
|
|
21
|
+
export { requestsWhole } from "./journal-view.js";
|
|
21
22
|
// --- Running a project, making one, and reaching a workspace ---
|
|
22
23
|
//
|
|
23
24
|
// A program never runs another program, nor makes or changes a project: it
|
|
@@ -58,6 +59,8 @@ export async function runProgram(options) {
|
|
|
58
59
|
// The runner does not share this program's working directory.
|
|
59
60
|
projectDir: resolve(request.projectDir),
|
|
60
61
|
workspaceDir: request.workspaceDir && resolve(request.workspaceDir),
|
|
62
|
+
// (A path is this program's to say where it leads. A name is one of the user's projects, wherever it is said.)
|
|
63
|
+
repairWith: request.repairWith !== undefined && namesAPath(request.repairWith) ? projectNamed(request.repairWith) : request.repairWith,
|
|
61
64
|
}, signal);
|
|
62
65
|
}
|
|
63
66
|
/** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
|
package/dist/ipc-server.js
CHANGED
|
@@ -5,6 +5,7 @@ import { createServer } from "http";
|
|
|
5
5
|
import { timingSafeEqual } from "crypto";
|
|
6
6
|
import { OFF_THE_RECORD } from "./journal.js";
|
|
7
7
|
import { createToolAsks, imagesOf, toolsOf } from "./own-tools.js";
|
|
8
|
+
import { REQUEST_FIELDS, requestOf } from "./model-request.js";
|
|
8
9
|
import { describeJson, isJsonObject } from "./serializable.js";
|
|
9
10
|
import { checkedEnv, variableName } from "./child-process.js";
|
|
10
11
|
import { checkedBudget } from "./budget.js";
|
|
@@ -187,6 +188,9 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
|
|
|
187
188
|
return {
|
|
188
189
|
"/agent/instruct": route({ prompt: "string", ...HOW_SERVED, templates: "optional boolean or strings" }, ({ prompt, tools, toolsId, ...options }, _closed, call) => withTools(tools, toolsId, call, (names, own) => agent.instruct(prompt, { ...options, tools: names }, call.used, own))),
|
|
189
190
|
"/agent/generate": route({ prompt: "string", schema: "object", ...HOW_SERVED }, ({ tools, toolsId, ...input }, _closed, call) => withTools(tools, toolsId, call, (names, own) => agent.generate({ ...input, tools: names }, call.used, own))),
|
|
191
|
+
// One request to a model (see model-request.ts): what it holds is read there, all of it, before anything is
|
|
192
|
+
// asked or counted — a conversation is no list of fields, and what is wrong with one is said by where it is.
|
|
193
|
+
"/agent/complete": route(Object.fromEntries(REQUEST_FIELDS.map(field => [field, "optional any"])), (request, _closed, call) => agent.complete(asGiven(() => requestOf(request), ofAField), call.used)),
|
|
190
194
|
// How a program's own tools are asked (see own-tools.ts): its client waits here to be told that one is
|
|
191
195
|
// called, or is to stop — held until there is something to tell, or the agent call is over — and says
|
|
192
196
|
// here what one answered.
|
|
@@ -216,7 +220,7 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
|
|
|
216
220
|
projectDir: "string", args: "optional object",
|
|
217
221
|
timeout: "optional number", maxRepairAttempts: "optional number",
|
|
218
222
|
id: "optional string", label: "optional string", workspaceDir: "optional string", env: "optional object",
|
|
219
|
-
budget: "optional object",
|
|
223
|
+
budget: "optional object", repairWith: "optional string",
|
|
220
224
|
}, async ({ id, env, budget, timeout, maxRepairAttempts, ...asked }, connectionClosed, { seq }) => {
|
|
221
225
|
const request = { ...asked, timeout: timeoutOf(timeout), maxRepairAttempts: attemptsOf(maxRepairAttempts), env: envOf(env), budget: budgetOf(budget) };
|
|
222
226
|
return lasting(id, connectionClosed, stop => run(request, stop, seq));
|
|
@@ -241,6 +245,7 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
|
|
|
241
245
|
"/workspace/read": route({ path: "string", dir: "optional string" }, b => workspaceOf(b.dir).read(b.path)),
|
|
242
246
|
"/workspace/write": route({ path: "string", content: "string", dir: "optional string" }, b => workspaceOf(b.dir).write(b.path, b.content)),
|
|
243
247
|
"/workspace/list": route({ pattern: "string", dir: "optional string" }, b => workspaceOf(b.dir).list(b.pattern)),
|
|
248
|
+
"/workspace/shell": route({ command: "string", dir: "optional string", cwd: "optional string", timeout: "optional number", env: "optional object" }, b => workspaceOf(b.dir).shell(b.command, { cwd: b.cwd, timeout: b.timeout, env: envOf(b.env) })),
|
|
244
249
|
"/workspace/observe": route({ pattern: "string", dir: "optional string", expect: "optional number", timeout: "optional number" }, b => workspaceOf(b.dir).observe(b.pattern, { expect: b.expect, timeout: b.timeout })),
|
|
245
250
|
};
|
|
246
251
|
}
|
package/dist/journal-view.d.ts
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
/** The one field of a request that says most about it. */
|
|
2
|
+
/**
|
|
3
|
+
* The requests to a model on a record, each whole, by the position of its
|
|
4
|
+
* call: a journal has of each what it adds to the one before (see
|
|
5
|
+
* `besideTheLast` in journal.ts), and this puts them together again. (As far
|
|
6
|
+
* as the record has them: what was cut from a record for its size is cut.)
|
|
7
|
+
*/
|
|
8
|
+
export declare function requestsWhole(records: Array<Record<string, any>>): Map<number, Record<string, unknown>>;
|
|
1
9
|
/** What reports of usage — `usage` records, or what a backend said — add up to, in a few words: and nothing where there are none. */
|
|
2
10
|
export declare function spentIn(usage: object[]): string;
|
|
3
11
|
/**
|
package/dist/journal-view.js
CHANGED
|
@@ -34,6 +34,38 @@ const oneLine = (value, max) => {
|
|
|
34
34
|
return text.length > max ? text.slice(0, max - 1) + "…" : text;
|
|
35
35
|
};
|
|
36
36
|
/** The one field of a request that says most about it. */
|
|
37
|
+
/**
|
|
38
|
+
* The requests to a model on a record, each whole, by the position of its
|
|
39
|
+
* call: a journal has of each what it adds to the one before (see
|
|
40
|
+
* `besideTheLast` in journal.ts), and this puts them together again. (As far
|
|
41
|
+
* as the record has them: what was cut from a record for its size is cut.)
|
|
42
|
+
*/
|
|
43
|
+
export function requestsWhole(records) {
|
|
44
|
+
const whole = new Map();
|
|
45
|
+
let last;
|
|
46
|
+
for (const record of records) {
|
|
47
|
+
if (record.kind !== "call" || record.endpoint !== "/agent/complete" || !Array.isArray(record.request?.messages))
|
|
48
|
+
continue;
|
|
49
|
+
const { messagesBefore = 0, unchanged = [], messages, ...others } = record.request;
|
|
50
|
+
const request = { ...others };
|
|
51
|
+
for (const name of unchanged)
|
|
52
|
+
if (last?.[name] !== undefined)
|
|
53
|
+
request[name] = last[name];
|
|
54
|
+
request.messages = [...(last?.messages ?? []).slice(0, messagesBefore), ...messages];
|
|
55
|
+
whole.set(record.seq, request);
|
|
56
|
+
last = request;
|
|
57
|
+
}
|
|
58
|
+
return whole;
|
|
59
|
+
}
|
|
60
|
+
/** The words of a conversation's last message — or, where it has none, what it has instead. */
|
|
61
|
+
function lastSaid(messages) {
|
|
62
|
+
const content = messages.at(-1)?.content;
|
|
63
|
+
if (typeof content === "string")
|
|
64
|
+
return content;
|
|
65
|
+
const parts = Array.isArray(content) ? content : [];
|
|
66
|
+
const text = parts.find(part => typeof part?.text === "string");
|
|
67
|
+
return text ? String(text.text) : parts.length > 0 ? `(${String(parts[0]?.type)})` : "";
|
|
68
|
+
}
|
|
37
69
|
function gist(request) {
|
|
38
70
|
// A run that was asked for is best known by the name it was given.
|
|
39
71
|
if (typeof request?.label === "string")
|
|
@@ -41,6 +73,9 @@ function gist(request) {
|
|
|
41
73
|
// ...and a project that was asked for by its own.
|
|
42
74
|
if (typeof request?.name === "string")
|
|
43
75
|
return oneLine(`${request.name}: ${typeof request.prompt === "string" ? request.prompt : ""}`, 60);
|
|
76
|
+
// ...and a request to a model by the last that was said in the conversation it carries.
|
|
77
|
+
if (Array.isArray(request?.messages))
|
|
78
|
+
return oneLine(request.messages.length === 0 && request.messagesBefore ? "(asked again, as before)" : lastSaid(request.messages), 60);
|
|
44
79
|
for (const field of ["prompt", "command", "path", "pattern", "url", "message", "projectDir", "reason"]) {
|
|
45
80
|
if (request?.[field] !== undefined)
|
|
46
81
|
return oneLine(request[field], 60);
|
|
@@ -64,8 +99,11 @@ const usageIn = (records) => records.filter(record => record.kind === "usage");
|
|
|
64
99
|
* says so) unless the journal filled up: then it is what is on record, be
|
|
65
100
|
* that nothing, and is said to be.
|
|
66
101
|
*/
|
|
102
|
+
/** What a project asked for a fix used (see the `fix` record), as a report of usage is added up: its tokens are not told apart there. */
|
|
103
|
+
const asUsage = (used) => ({ input: used.tokens ?? 0, cost: used.cost ?? 0 });
|
|
67
104
|
function spentInAll(records, inAll = "") {
|
|
68
|
-
|
|
105
|
+
// (A fix is part of the run it is for, whoever made it: what a project used for one is counted with the rest.)
|
|
106
|
+
const counted = spentIn([...usageIn(records), ...records.filter(record => record.kind === "fix" && record.used).map(record => asUsage(record.used))]);
|
|
69
107
|
if (!records.some(record => record.kind === "full"))
|
|
70
108
|
return counted && counted + inAll;
|
|
71
109
|
return `${counted || "no usage"} on record — the journal was full`;
|
|
@@ -123,13 +161,17 @@ function printJournal(path, records) {
|
|
|
123
161
|
console.log(`${at} ${oneLine(record.spent, 100)}`);
|
|
124
162
|
break;
|
|
125
163
|
case "child":
|
|
126
|
-
|
|
164
|
+
// (A run a call of the program's started — or, for a fix, one the run itself started.)
|
|
165
|
+
console.log(record.purpose === "fix"
|
|
166
|
+
? `${at} the fix is asked of a project: run ${record.run}`
|
|
167
|
+
: `${at} #${String(record.seq).padEnd(3)} started ${record.purpose === "validate" ? "validation" : "run"} ${record.run}`);
|
|
127
168
|
break;
|
|
128
169
|
case "fix-request":
|
|
129
170
|
console.log(`${at} fix asked for: ${oneLine(record.error, 80)}`);
|
|
130
171
|
break;
|
|
131
172
|
case "fix":
|
|
132
|
-
|
|
173
|
+
// (What a project that was asked for it used is said with it: what pi's agent used is in the lines of `usage`.)
|
|
174
|
+
console.log(`${at} fix ${record.ok ? "returned" : `not returned: ${oneLine(record.error, 80)}`}${record.used ? ` ${spentIn([asUsage(record.used)])}` : ""}`);
|
|
133
175
|
break;
|
|
134
176
|
case "exit": {
|
|
135
177
|
const how = record.timedOut ? "timed out"
|
package/dist/journal.js
CHANGED
|
@@ -278,6 +278,42 @@ function recordable(endpoint, value) {
|
|
|
278
278
|
}
|
|
279
279
|
return value;
|
|
280
280
|
}
|
|
281
|
+
/** What a request to a model may have again that it had before, beside its conversation: left out of its record where it is the same (see `besideTheLast`). */
|
|
282
|
+
const SAID_ONCE = ["system", "tools"];
|
|
283
|
+
const markOf = (value) => createHash("sha1").update(JSON.stringify(value) ?? "").digest("base64");
|
|
284
|
+
/**
|
|
285
|
+
* A request to a model, as it is written down beside the one before it on
|
|
286
|
+
* the same record. A program that is its own harness sends the whole
|
|
287
|
+
* conversation with every request: written down whole each time, a record
|
|
288
|
+
* grows with the square of the turns. So of a conversation that begins as
|
|
289
|
+
* the last one did, what is written is what it adds: `messagesBefore` says
|
|
290
|
+
* how many of its messages are those the request before it began with, and
|
|
291
|
+
* `messages` has the rest. And `unchanged` names what else it has as that
|
|
292
|
+
* request had it (what the model is told to be, its tools), which is then
|
|
293
|
+
* left out. A request that shares nothing with the one before is written
|
|
294
|
+
* whole, as the first is. (Read back whole by `requestsWhole`.)
|
|
295
|
+
*/
|
|
296
|
+
function besideTheLast(request, last) {
|
|
297
|
+
if (!isJsonObject(request) || !Array.isArray(request.messages))
|
|
298
|
+
return { recorded: request };
|
|
299
|
+
const asked = {
|
|
300
|
+
messages: request.messages.map(markOf),
|
|
301
|
+
rest: Object.fromEntries(SAID_ONCE.filter(name => request[name] !== undefined).map(name => [name, markOf(request[name])])),
|
|
302
|
+
};
|
|
303
|
+
if (!last)
|
|
304
|
+
return { recorded: request, asked };
|
|
305
|
+
let same = 0;
|
|
306
|
+
while (same < asked.messages.length && same < last.messages.length && asked.messages[same] === last.messages[same])
|
|
307
|
+
same += 1;
|
|
308
|
+
const unchanged = SAID_ONCE.filter(name => asked.rest[name] !== undefined && asked.rest[name] === last.rest[name]);
|
|
309
|
+
if (same === 0 && unchanged.length === 0)
|
|
310
|
+
return { recorded: request, asked };
|
|
311
|
+
const { messages, ...others } = request;
|
|
312
|
+
for (const name of unchanged)
|
|
313
|
+
delete others[name];
|
|
314
|
+
// (The small fields first: a record's allowance is spent in order.)
|
|
315
|
+
return { recorded: { ...(same > 0 && { messagesBefore: same }), ...(unchanged.length > 0 && { unchanged }), ...others, messages: messages.slice(same) }, asked };
|
|
316
|
+
}
|
|
281
317
|
/** What is written down of a call that is not on record: nothing. */
|
|
282
318
|
const UNRECORDED = { end() { }, used() { }, tool: () => () => { } };
|
|
283
319
|
/** A call that is nobody's to look up: what carries other calls rather than being one (see ipc-server). */
|
|
@@ -436,6 +472,8 @@ export function openJournal(projectDir, keep, about) {
|
|
|
436
472
|
return !full;
|
|
437
473
|
};
|
|
438
474
|
let seq = 0;
|
|
475
|
+
// The last request to a model that was written down: the next is written beside it.
|
|
476
|
+
let lastAsked;
|
|
439
477
|
return {
|
|
440
478
|
run,
|
|
441
479
|
path,
|
|
@@ -448,7 +486,13 @@ export function openJournal(projectDir, keep, about) {
|
|
|
448
486
|
const arrived = performance.now();
|
|
449
487
|
// How many times the agent behind it has called a tool of the program's.
|
|
450
488
|
let uses = 0;
|
|
451
|
-
|
|
489
|
+
let recorded = recordable(endpoint, request);
|
|
490
|
+
if (endpoint === "/agent/complete") {
|
|
491
|
+
const beside = besideTheLast(request, lastAsked);
|
|
492
|
+
recorded = beside.recorded;
|
|
493
|
+
lastAsked = beside.asked ?? lastAsked;
|
|
494
|
+
}
|
|
495
|
+
write("call", () => ({ seq: position, endpoint, request: recorded }));
|
|
452
496
|
return {
|
|
453
497
|
seq: position,
|
|
454
498
|
end(outcome) {
|
package/dist/model-relay.d.ts
CHANGED
|
@@ -17,6 +17,15 @@ export interface RelayRequest {
|
|
|
17
17
|
by?: RelayWay;
|
|
18
18
|
/** The model, as the session that asks has it. */
|
|
19
19
|
model: RelayModel;
|
|
20
|
+
/**
|
|
21
|
+
* The model by name, "provider/model", where no session asks that has it:
|
|
22
|
+
* it is then the relay's own by that name — and where the relay has none
|
|
23
|
+
* such, has no key for it, or the model does not think as the request
|
|
24
|
+
* would have it, the reply says so, as one that was not asked for (see
|
|
25
|
+
* `unasked`). Such a request is never one for whoever sent it to ask
|
|
26
|
+
* itself: it has nothing to ask by.
|
|
27
|
+
*/
|
|
28
|
+
named?: string;
|
|
20
29
|
/** What the model is to be sent: as pi hands it to a provider. */
|
|
21
30
|
context: unknown;
|
|
22
31
|
/** The options of the request that are data (see `dataOf`). */
|
|
@@ -111,6 +120,16 @@ export declare function usageAtEnd(event: RelayEvent): ReplyUsage | undefined;
|
|
|
111
120
|
* the conversation up — and a request that is not to be made is neither.)
|
|
112
121
|
*/
|
|
113
122
|
export declare function notAsked(model: RelayModel, why: string, as?: "aborted" | "error"): RelayEvent;
|
|
123
|
+
/** Why a model that was asked for by name was not asked: which of the things a request by name is refused for. */
|
|
124
|
+
export type Unasked = "model" | "key" | "thinking";
|
|
125
|
+
/**
|
|
126
|
+
* A model by the name a call gives it, "provider/model", among those `models`
|
|
127
|
+
* has: the provider's name ends at a stroke, and either name may have more of
|
|
128
|
+
* them — so each stroke is tried, the first first.
|
|
129
|
+
*/
|
|
130
|
+
export declare function modelNamed<M>(models: {
|
|
131
|
+
getModel(provider: string, id: string): M | undefined;
|
|
132
|
+
}, name: string): M | undefined;
|
|
114
133
|
/**
|
|
115
134
|
* Makes of a reply's events the events as they are sent: without the reply
|
|
116
135
|
* so far. (One for each reply: it keeps how much of each tool call has been
|
package/dist/model-relay.js
CHANGED
|
@@ -176,6 +176,33 @@ export function notAsked(model, why, as = "aborted") {
|
|
|
176
176
|
},
|
|
177
177
|
};
|
|
178
178
|
}
|
|
179
|
+
/** The reply of a request by name that was not made (see RelayRequest.named): one event, that says why — and of which kind the reason is. */
|
|
180
|
+
async function* unasked(model, kind, why) {
|
|
181
|
+
yield { ...notAsked(model, why, "error"), unasked: kind };
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* A model by the name a call gives it, "provider/model", among those `models`
|
|
185
|
+
* has: the provider's name ends at a stroke, and either name may have more of
|
|
186
|
+
* them — so each stroke is tried, the first first.
|
|
187
|
+
*/
|
|
188
|
+
export function modelNamed(models, name) {
|
|
189
|
+
for (const { index } of name.matchAll(/\//g)) {
|
|
190
|
+
const model = models.getModel(name.slice(0, index), name.slice(index + 1));
|
|
191
|
+
if (model)
|
|
192
|
+
return model;
|
|
193
|
+
}
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
/** The levels a model thinks at, as pi-ai has them of it. (pi-ai's own, had by its file: pi hands it to nobody.) */
|
|
197
|
+
async function levelsOf(model) {
|
|
198
|
+
try {
|
|
199
|
+
const { getSupportedThinkingLevels } = await import(pathToFileURL(inPisAi("./models")).href);
|
|
200
|
+
return getSupportedThinkingLevels?.(model);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
179
206
|
// --- An event without the reply so far, and with it again ---
|
|
180
207
|
// Every event of a reply but the last carries `partial`: the whole reply so
|
|
181
208
|
// far. Sent as they are, a reply's events grow with the square of its length.
|
|
@@ -303,14 +330,39 @@ export function createModelRelay() {
|
|
|
303
330
|
const way = WAYS.get(by);
|
|
304
331
|
if (!way)
|
|
305
332
|
return undefined;
|
|
306
|
-
const own = way.of === "chat" ? found.getModel(provider, id) : found.getModelOfType(way.of, provider, id);
|
|
307
|
-
// The same model, to the letter, with a key to ask it by — and a provider nobody has had a hand in.
|
|
308
|
-
if (!own || JSON.stringify(own) !== JSON.stringify(request.model) || !found.hasConfiguredAuth(provider))
|
|
309
|
-
return undefined;
|
|
310
333
|
// (What goes with a request is held to here as where it was sent from: whoever sent it may not be who should have.)
|
|
311
334
|
const options = dataOf(request.options);
|
|
312
335
|
if (!options)
|
|
313
336
|
return undefined;
|
|
337
|
+
let own;
|
|
338
|
+
if (request.named !== undefined) {
|
|
339
|
+
// By name: this relay's own model of that name, or none — and what stands against asking it is said.
|
|
340
|
+
const name = request.named;
|
|
341
|
+
const mine = way.of === "chat" ? modelNamed(found, name) : undefined;
|
|
342
|
+
if (!mine)
|
|
343
|
+
return unasked(request.model, "model", `Unknown model "${name}". A model is named "provider/model", as pi's model catalog has it.`);
|
|
344
|
+
if (!found.hasConfiguredAuth(mine.provider))
|
|
345
|
+
return unasked(request.model, "key", `The model ${name} cannot be asked: pi has no key for the provider "${mine.provider}".`);
|
|
346
|
+
if (options.reasoning !== undefined) {
|
|
347
|
+
// (pi gives the level it has that is nearest, without a word: a request is to have what it asked for, or fail.)
|
|
348
|
+
const levels = await levelsOf(mine);
|
|
349
|
+
if (!levels)
|
|
350
|
+
return unasked(request.model, "thinking", `Whether the model ${name} thinks at level "${String(options.reasoning)}" cannot be told: pi's list of a model's levels was not found.`);
|
|
351
|
+
if (!levels.includes(String(options.reasoning))) {
|
|
352
|
+
return unasked(request.model, "thinking", `The model ${name} does not think at level "${String(options.reasoning)}". Its levels: ${levels.join(", ")}.`);
|
|
353
|
+
}
|
|
354
|
+
// (Not at all is how a model is asked without a word of it.)
|
|
355
|
+
if (options.reasoning === "off")
|
|
356
|
+
delete options.reasoning;
|
|
357
|
+
}
|
|
358
|
+
own = mine;
|
|
359
|
+
}
|
|
360
|
+
else {
|
|
361
|
+
own = way.of === "chat" ? found.getModel(provider, id) : found.getModelOfType(way.of, provider, id);
|
|
362
|
+
// The same model, to the letter, with a key to ask it by — and a provider nobody has had a hand in.
|
|
363
|
+
if (!own || JSON.stringify(own) !== JSON.stringify(request.model) || !found.hasConfiguredAuth(provider))
|
|
364
|
+
return undefined;
|
|
365
|
+
}
|
|
314
366
|
if (typeof options.sessionId === "string")
|
|
315
367
|
sessions.add(options.sessionId);
|
|
316
368
|
// (pi's models, asked by the name of the way: each takes the model, what it is to be sent, and the options.)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type ModelAsk } from "./agent-backend.js";
|
|
2
|
+
/** What a request may hold, as a program names it. */
|
|
3
|
+
export declare const REQUEST_FIELDS: readonly ["messages", "system", "tools", "model", "thinking", "maxTokens", "temperature", "toolChoice", "timeout"];
|
|
4
|
+
/**
|
|
5
|
+
* A request as a program gave it, held to what one is: returns it as a
|
|
6
|
+
* backend is handed it. Throws with what is wrong, in words for whoever
|
|
7
|
+
* wrote it. (What is given as null is not given: it is how JSON says so.)
|
|
8
|
+
*/
|
|
9
|
+
export declare function requestOf(given: unknown): ModelAsk;
|