@trama-dev/runtime 0.5.0 → 0.6.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.
@@ -3,14 +3,23 @@
3
3
  // bridge-client.ts for the other end, and client.ts for what is made of it).
4
4
  import { createServer } from "http";
5
5
  import { timingSafeEqual } from "crypto";
6
- import { isJsonObject } from "./serializable.js";
6
+ import { describeJson, isJsonObject } from "./serializable.js";
7
+ import { checkedEnv, variableName } from "./child-process.js";
8
+ import { checkedBudget } from "./budget.js";
9
+ import { messageOf } from "./errors.js";
7
10
  const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
8
11
  const MAX_STOPPED_AHEAD = 1024;
9
12
  /** A request the program got wrong — answered with 400 rather than 500. */
10
13
  class BadRequest extends Error {
11
14
  }
12
- const isOfKind = (value, kind) => kind === "any" ? value !== undefined : kind === "object" ? isJsonObject(value) : typeof value === kind;
13
- /** Read a call's declared fields out of a request body — refusing a body that does not hold them as declared. */
15
+ const isStrings = (value) => Array.isArray(value) && value.every(item => typeof item === "string");
16
+ const isOfKind = (value, kind) => kind === "any" ? value !== undefined
17
+ : kind === "object" ? isJsonObject(value)
18
+ : kind === "strings" ? isStrings(value)
19
+ : kind === "boolean or strings" ? typeof value === "boolean" || isStrings(value)
20
+ : kind === "boolean or string" ? typeof value === "boolean" || typeof value === "string"
21
+ : typeof value === kind;
22
+ /** Read a call's declared fields out of a request body — refusing a body that does not hold them as declared, or holds any other. */
14
23
  function read(body, fields) {
15
24
  if (!isJsonObject(body))
16
25
  throw new BadRequest("The request body must be a JSON object");
@@ -29,28 +38,97 @@ function read(body, fields) {
29
38
  }
30
39
  args[name] = value;
31
40
  }
41
+ // What a call does not declare it cannot do anything with: to pass it over would be to let its sender think it had.
42
+ const unknown = Object.keys(body).find(name => !Object.hasOwn(fields, name));
43
+ if (unknown !== undefined)
44
+ throw new BadRequest(`Unknown field: ${unknown} (this call takes: ${Object.keys(fields).join(", ")})`);
32
45
  return args;
33
46
  }
34
47
  /**
35
48
  * A call: every field it takes, and what is done with them. The declaration
36
- * is the whole of what a handler sees of a request — a field that is not
37
- * declared does not reach it, and one that is arrives as the kind it says.
49
+ * is the whole of what a request may hold — a field that is not declared
50
+ * is refused, and one that is arrives as the kind it says.
38
51
  * (What is inside an object is the business of whoever it is handed to.)
39
52
  */
40
53
  function route(fields, handle) {
41
- return { handle: (body, connectionClosed, seq) => handle(read(body, fields), connectionClosed, seq) };
54
+ return { handle: (body, connectionClosed, call) => handle(read(body, fields), connectionClosed, call) };
42
55
  }
56
+ /** The variables a call gives, held to what variables are (see checkedEnv): what is none is the request's fault. */
57
+ function envOf(env) {
58
+ if (env === undefined)
59
+ return undefined;
60
+ try {
61
+ return checkedEnv(env);
62
+ }
63
+ catch (err) {
64
+ throw new BadRequest(`Invalid field: ${messageOf(err)}`);
65
+ }
66
+ }
67
+ /** The budget a call gives a run, held to what a budget is (see checkedBudget). */
68
+ function budgetOf(budget) {
69
+ if (budget === undefined)
70
+ return undefined;
71
+ try {
72
+ return checkedBudget(budget);
73
+ }
74
+ catch (err) {
75
+ throw new BadRequest(`Invalid field: ${messageOf(err)}`);
76
+ }
77
+ }
78
+ /**
79
+ * A request as it is written down: all of it, but for what it gives as
80
+ * variables — a journal is no place for a key. Of variables the names are
81
+ * kept; of what is given in their place and is none, what kind of thing it is.
82
+ */
83
+ const asRecorded = (body) => !isJsonObject(body) || body.env == null ? body
84
+ : { ...body, env: isJsonObject(body.env) ? Object.keys(body.env).map(variableName) : `(${describeJson(body.env)})` };
85
+ /**
86
+ * What an agent call may say about how it is served (see AgentOptions). (A
87
+ * prompt of `instruct` may be read as a template besides: a typed answer's is
88
+ * not, for what says how to answer follows it.)
89
+ */
90
+ const HOW_SERVED = {
91
+ system: "optional string", model: "optional string", thinking: "optional string", tools: "optional strings",
92
+ skills: "optional boolean or strings", extensions: "optional boolean or string", cutOff: "optional string",
93
+ };
43
94
  /** Whether a request carries `Authorization: Bearer <token>`, compared in constant time. */
44
95
  function isAuthorized(header, token) {
45
96
  const expected = Buffer.from(`Bearer ${token}`);
46
97
  const actual = Buffer.from(header ?? "");
47
98
  return actual.length === expected.length && timingSafeEqual(actual, expected);
48
99
  }
49
- function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run }) {
50
- /** Runs the program has asked for and that have not ended, by the id it gave each. */
100
+ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, make }) {
101
+ /** What the program has asked for that lasts — a run, a project made — and has not ended, by the id it gave each. */
51
102
  const runsAskedFor = new Map();
52
- /** Ids the program asked to stop before their run was seen here: such a run starts stopped. */
103
+ /** Ids the program asked to stop before what bears them was seen here: such a thing starts stopped. */
53
104
  const stoppedAhead = new Set();
105
+ /**
106
+ * Carry out what a call asks for and that lasts as long as the call does,
107
+ * until it ends or is to stop: the program says so by the id it gave it,
108
+ * or is gone — its process died, or it gave up — and no longer wants it.
109
+ */
110
+ const lasting = async (id, connectionClosed, work) => {
111
+ if (id !== undefined) {
112
+ if (id === "")
113
+ throw new BadRequest("Invalid field: id (expected a non-empty string)");
114
+ if (runsAskedFor.has(id))
115
+ throw new BadRequest(`Duplicate run id: ${id}`);
116
+ }
117
+ const stop = new AbortController();
118
+ void connectionClosed.then(() => stop.abort());
119
+ if (id !== undefined) {
120
+ if (stoppedAhead.delete(id))
121
+ stop.abort();
122
+ runsAskedFor.set(id, stop);
123
+ }
124
+ try {
125
+ return await work(stop.signal);
126
+ }
127
+ finally {
128
+ if (id !== undefined)
129
+ runsAskedFor.delete(id);
130
+ }
131
+ };
54
132
  /** The workspace a call is about: the directory it names, or else the one this run was started with. */
55
133
  const workspaceOf = (dir) => {
56
134
  if (dir !== undefined) {
@@ -63,11 +141,11 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run }) {
63
141
  return workspace;
64
142
  };
65
143
  return {
66
- "/agent/instruct": route({ prompt: "string", system: "optional string" }, b => agent.instruct(b.prompt, { system: b.system })),
67
- "/agent/generate": route({ prompt: "string", schema: "object", system: "optional string" }, b => agent.generate({ prompt: b.prompt, schema: b.schema, system: b.system })),
144
+ "/agent/instruct": route({ prompt: "string", ...HOW_SERVED, templates: "optional boolean or strings" }, ({ prompt, ...options }, _closed, call) => agent.instruct(prompt, options, call.used)),
145
+ "/agent/generate": route({ prompt: "string", schema: "object", ...HOW_SERVED }, (input, _closed, call) => agent.generate(input, call.used)),
68
146
  "/tools/read": route({ path: "string" }, b => tools.read(b.path)),
69
147
  "/tools/write": route({ path: "string", content: "string" }, b => tools.write(b.path, b.content)),
70
- "/tools/shell": route({ command: "string", cwd: "optional string", timeout: "optional number" }, b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout })),
148
+ "/tools/shell": route({ command: "string", cwd: "optional string", timeout: "optional number", env: "optional object" }, b => tools.shell(b.command, { cwd: b.cwd, timeout: b.timeout, env: envOf(b.env) })),
71
149
  "/tools/fetch": route({ url: "string", method: "optional string", headers: "optional object", body: "optional string" }, b => tools.fetch(b.url, { method: b.method, headers: b.headers, body: b.body })),
72
150
  "/ctx/log": route({ message: "string", data: "optional any" }, b => ctx.log(b.message, b.data)),
73
151
  "/ctx/ready": route({ data: "optional object" }, b => ctx.ready(b.data)),
@@ -81,33 +159,18 @@ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run }) {
81
159
  "/run/program": route({
82
160
  projectDir: "string", args: "optional object",
83
161
  timeout: "optional number", maxRepairAttempts: "optional number",
84
- id: "optional string", label: "optional string", workspaceDir: "optional string",
85
- }, async ({ id, ...request }, connectionClosed, seq) => {
86
- if (id !== undefined) {
87
- if (id === "")
88
- throw new BadRequest("Invalid field: id (expected a non-empty string)");
89
- if (runsAskedFor.has(id))
90
- throw new BadRequest(`Duplicate run id: ${id}`);
91
- }
92
- const stop = new AbortController();
93
- // A caller that is gone — its process died, or it gave up — no longer wants the run.
94
- void connectionClosed.then(() => stop.abort());
95
- // `id` is the name the program gave the run, to stop it by.
96
- if (id !== undefined) {
97
- if (stoppedAhead.delete(id))
98
- stop.abort();
99
- runsAskedFor.set(id, stop);
100
- }
101
- try {
102
- return await run(request, stop.signal, seq);
103
- }
104
- finally {
105
- if (id !== undefined)
106
- runsAskedFor.delete(id);
107
- }
162
+ id: "optional string", label: "optional string", workspaceDir: "optional string", env: "optional object",
163
+ budget: "optional object",
164
+ }, async ({ id, env, budget, ...asked }, connectionClosed, { seq }) => {
165
+ const request = { ...asked, env: envOf(env), budget: budgetOf(budget) };
166
+ return lasting(id, connectionClosed, stop => run(request, stop, seq));
108
167
  }),
109
- // Stop a run asked for above. The call that asked for it still gets its
110
- // answer — a failed run — once the run is over.
168
+ // Nor does a program make a project, or change one: its runner does, as it runs one — under the
169
+ // run's budget, on its record, and stopped with it.
170
+ "/project/create": route({ name: "string", prompt: "string", model: "optional string", args: "optional object", id: "optional string" }, ({ id, ...asked }, connectionClosed, { seq }) => lasting(id, connectionClosed, stop => make({ kind: "create", ...asked }, stop, seq))),
171
+ "/project/update": route({ name: "string", prompt: "string", id: "optional string" }, ({ id, ...asked }, connectionClosed, { seq }) => lasting(id, connectionClosed, stop => make({ kind: "update", ...asked }, stop, seq))),
172
+ // Stop a run asked for above, or a project being made. The call that asked
173
+ // for it still gets its answer — a failed run, an error — once it is over.
111
174
  "/run/stop": route({ id: "string" }, b => {
112
175
  if (b.id === "")
113
176
  throw new BadRequest("Invalid field: id (expected a non-empty string)");
@@ -132,7 +195,7 @@ export function createIPCServer(backends) {
132
195
  return createServer((req, res) => {
133
196
  const connectionClosed = new Promise(resolve => res.once("close", resolve));
134
197
  // An answer can be given once, and only while there is someone to give it to.
135
- const answerable = () => !res.writableEnded && !res.destroyed;
198
+ const answerable = () => !backends.programOver() && !res.writableEnded && !res.destroyed;
136
199
  const reply = (status, body, json = false) => {
137
200
  if (!answerable())
138
201
  return;
@@ -180,8 +243,8 @@ export function createIPCServer(backends) {
180
243
  const route = req.url && Object.hasOwn(routes, req.url) ? routes[req.url] : undefined;
181
244
  if (!route)
182
245
  return reply(404, "Not found");
183
- call = backends.journal.call(req.url, body);
184
- const result = (await route.handle(body, connectionClosed, call.seq)) ?? null;
246
+ call = backends.journal.call(req.url, asRecorded(body));
247
+ const result = (await route.handle(body, connectionClosed, call)) ?? null;
185
248
  const payload = JSON.stringify({ result });
186
249
  if (answerable())
187
250
  call.end({ ok: true, result });
@@ -1,3 +1,5 @@
1
+ /** 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
+ export declare function spentIn(usage: object[]): string;
1
3
  /**
2
4
  * Print what a run of the project in `projectDir` did: the latest run, or the
3
5
  * one named. With `list`, print which runs have a journal instead. `name` is
@@ -38,12 +38,35 @@ function gist(request) {
38
38
  // A run that was asked for is best known by the name it was given.
39
39
  if (typeof request?.label === "string")
40
40
  return oneLine(`${request.label} (${request.projectDir})`, 60);
41
+ // ...and a project that was asked for by its own.
42
+ if (typeof request?.name === "string")
43
+ return oneLine(`${request.name}: ${typeof request.prompt === "string" ? request.prompt : ""}`, 60);
41
44
  for (const field of ["prompt", "command", "path", "pattern", "url", "message", "projectDir", "reason"]) {
42
45
  if (request?.[field] !== undefined)
43
46
  return oneLine(request[field], 60);
44
47
  }
45
48
  return "";
46
49
  }
50
+ /** What reports of usage — `usage` records, or what a backend said — add up to, in a few words: and nothing where there are none. */
51
+ export function spentIn(usage) {
52
+ if (usage.length === 0)
53
+ return "";
54
+ const sum = (field) => usage.reduce((total, record) => total + (Number(record[field]) || 0), 0);
55
+ return `${sum("input") + sum("output") + sum("cacheRead") + sum("cacheWrite")} tokens $${sum("cost").toFixed(4)}`;
56
+ }
57
+ const spent = spentIn;
58
+ const usageIn = (records) => records.filter(record => record.kind === "usage");
59
+ /**
60
+ * What a run used, as far as its journal says. That is all of it (`inAll`
61
+ * says so) unless the journal filled up: then it is what is on record, be
62
+ * that nothing, and is said to be.
63
+ */
64
+ function spentInAll(records, inAll = "") {
65
+ const counted = spent(usageIn(records));
66
+ if (!records.some(record => record.kind === "full"))
67
+ return counted && counted + inAll;
68
+ return `${counted || "no usage"} on record — the journal was full`;
69
+ }
47
70
  /** How a run ended, in a word or two — or that it has not, or never will. */
48
71
  function ending(path, records) {
49
72
  const end = records.find(record => record.kind === "end");
@@ -62,6 +85,8 @@ function printJournal(path, records) {
62
85
  for (const record of records)
63
86
  if (record.kind === "result")
64
87
  results.set(record.seq, record);
88
+ const usage = usageIn(records);
89
+ const total = spentInAll(records, " in all");
65
90
  for (const record of records) {
66
91
  const at = `${(record.at / 1000).toFixed(3).padStart(9)}s`;
67
92
  switch (record.kind) {
@@ -73,11 +98,22 @@ function printJournal(path, records) {
73
98
  const how = !result ? "never answered"
74
99
  : result.ok ? `ok ${result.ms}ms`
75
100
  : `failed ${result.ms}ms ${oneLine(result.error, 60)}`;
76
- console.log(`${at} #${String(record.seq).padEnd(3)} ${record.endpoint.slice(1).padEnd(18)} ${gist(record.request).padEnd(60)} ${how}`);
101
+ const used = spent(usage.filter(item => item.seq === record.seq));
102
+ console.log(`${at} #${String(record.seq).padEnd(3)} ${record.endpoint.slice(1).padEnd(18)} ${gist(record.request).padEnd(60)} ${how}${used && ` ${used}`}`);
77
103
  break;
78
104
  }
105
+ case "usage":
106
+ // (What a call used is shown with the call.)
107
+ if (record.for === "fix")
108
+ console.log(`${at} asking for the fix used ${spent([record])}`);
109
+ if (record.for === "generate")
110
+ console.log(`${at} writing the program used ${spent([record])}`);
111
+ break;
112
+ case "budget":
113
+ console.log(`${at} ${oneLine(record.spent, 100)}`);
114
+ break;
79
115
  case "child":
80
- console.log(`${at} #${String(record.seq).padEnd(3)} started run ${record.run}`);
116
+ console.log(`${at} #${String(record.seq).padEnd(3)} started ${record.purpose === "validate" ? "validation" : "run"} ${record.run}`);
81
117
  break;
82
118
  case "fix-request":
83
119
  console.log(`${at} fix asked for: ${oneLine(record.error, 80)}`);
@@ -104,7 +140,7 @@ function printJournal(path, records) {
104
140
  console.log(`${at} the journal is full: calls from here on were not recorded`);
105
141
  break;
106
142
  case "end":
107
- console.log(`${at} end: ${howEnded}`);
143
+ console.log(`${at} end: ${howEnded}${total && ` (${total})`}`);
108
144
  break;
109
145
  }
110
146
  }
@@ -126,7 +162,8 @@ export function printJournals(projectDir, name, options) {
126
162
  const path = journalIn(dir, run);
127
163
  const records = readJournal(path);
128
164
  const calls = records.filter(record => record.kind === "call").length;
129
- console.log(`${run} ${String(records[0]?.purpose ?? "").padEnd(8)} ${String(calls).padStart(4)} calls ${ending(path, records)}`);
165
+ const used = spentInAll(records);
166
+ console.log(`${run} ${String(records[0]?.purpose ?? "").padEnd(8)} ${String(calls).padStart(4)} calls ${ending(path, records)}${used && ` ${used}`}`);
130
167
  }
131
168
  return;
132
169
  }
package/dist/journal.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type AgentUsage } from "./agent-backend.js";
1
2
  /** The format of the records. Bump it when a reader of older journals would be misled. */
2
3
  export declare const JOURNAL_VERSION = 1;
3
4
  /** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
@@ -26,6 +27,14 @@ export type CallOutcome = {
26
27
  ok: false;
27
28
  error: string;
28
29
  };
30
+ /** A bridge call on record: its position among the run's calls, and what is written down of it later. */
31
+ export interface RecordedCall {
32
+ seq: number;
33
+ /** How it was answered. */
34
+ end(outcome: CallOutcome): void;
35
+ /** What the agent behind it used — each time it was asked, and whether or not the call is answered. */
36
+ used(usage: AgentUsage): void;
37
+ }
29
38
  export interface Journal {
30
39
  /** The run's id — the name of its journal file, without the extension. Empty if nothing is being recorded. */
31
40
  readonly run: string;
@@ -36,14 +45,13 @@ export interface Journal {
36
45
  * allowance is spent in order, and what comes last is what gets cut.
37
46
  */
38
47
  note(kind: string, fields?: Record<string, unknown>): void;
48
+ /** Record what the agent used on the runner's own account — asking for a fix, say (`what`: "fix"). */
49
+ used(what: string, usage: AgentUsage): void;
39
50
  /**
40
51
  * Record a bridge call as it arrives. Returns its position among the run's
41
52
  * calls, and what records how it was answered.
42
53
  */
43
- call(endpoint: string, request: unknown): {
44
- seq: number;
45
- end(outcome: CallOutcome): void;
46
- };
54
+ call(endpoint: string, request: unknown): RecordedCall;
47
55
  /** Stop recording. Anything noted after this is dropped. */
48
56
  close(): void;
49
57
  }
package/dist/journal.js CHANGED
@@ -19,6 +19,7 @@ import { guardPath, identityIn, identityOf, makeDirsIn, realRootOf } from "./pat
19
19
  import { stagedNameFor } from "./replace-file.js";
20
20
  import { isJsonObject } from "./serializable.js";
21
21
  import { messageOf } from "./errors.js";
22
+ import { declaredUsage } from "./agent-backend.js";
22
23
  /** The format of the records. Bump it when a reader of older journals would be misled. */
23
24
  export const JOURNAL_VERSION = 1;
24
25
  /** Where a project keeps its journals, relative to the project — under logs/, which trama keeps out of version control. */
@@ -277,7 +278,7 @@ function recordable(endpoint, value) {
277
278
  /** A journal that records nothing. Calls are still numbered, so the rest of the runner need not care. */
278
279
  function noJournal() {
279
280
  let seq = 0;
280
- return { run: "", path: "", note() { }, call: () => ({ seq: ++seq, end() { } }), close() { } };
281
+ return { run: "", path: "", note() { }, used() { }, call: () => ({ seq: ++seq, end() { }, used() { } }), close() { } };
281
282
  }
282
283
  /**
283
284
  * Journals this process is writing, each by what it is (see identityOf): a
@@ -432,10 +433,11 @@ export function openJournal(projectDir, keep, about) {
432
433
  run,
433
434
  path,
434
435
  note: (kind, fields = {}) => write(kind, () => fields),
436
+ used: (what, usage) => write("usage", () => ({ for: what, ...declaredUsage(usage) })),
435
437
  call(endpoint, request) {
436
438
  const position = ++seq;
437
439
  if (!roomForCalls())
438
- return { seq: position, end() { } };
440
+ return { seq: position, end() { }, used() { } };
439
441
  const arrived = performance.now();
440
442
  write("call", () => ({ seq: position, endpoint, request: recordable(endpoint, request) }));
441
443
  return {
@@ -447,6 +449,9 @@ export function openJournal(projectDir, keep, about) {
447
449
  ...(outcome.ok ? { ok: true, result: recordable(endpoint, outcome.result) } : outcome),
448
450
  }));
449
451
  },
452
+ used(usage) {
453
+ write("usage", () => ({ seq: position, ...declaredUsage(usage) }));
454
+ },
450
455
  };
451
456
  },
452
457
  close,
@@ -0,0 +1,188 @@
1
+ /** A model as pi has it in its catalog: plain data. */
2
+ export type RelayModel = {
3
+ provider: string;
4
+ id: string;
5
+ api?: string;
6
+ } & Record<string, unknown>;
7
+ /**
8
+ * The ways pi has of asking a model, that a relay asks by: for a reply, as
9
+ * pi's agent asks (by options that are any provider's) or by the options of
10
+ * the model's own provider; for images; for what a classifier makes of a
11
+ * state. Each is a method of pi's models by that name.
12
+ */
13
+ export type RelayWay = "streamSimple" | "stream" | "generateImages" | "classify";
14
+ /** A request of a model: plain data, all of it. */
15
+ export interface RelayRequest {
16
+ /** The way the model is asked: as pi's agent asks, where it is not said. */
17
+ by?: RelayWay;
18
+ /** The model, as the session that asks has it. */
19
+ model: RelayModel;
20
+ /** What the model is to be sent: as pi hands it to a provider. */
21
+ context: unknown;
22
+ /** The options of the request that are data (see `dataOf`). */
23
+ options: Record<string, unknown>;
24
+ /** Whether it is asked beside a call that is over — one that has its answer, or has failed (see AgentCall.sofar). */
25
+ answered?: true;
26
+ }
27
+ /**
28
+ * An event of a reply, as pi's stream of it has them. The last is of type
29
+ * "done" or "error", and has the reply whole. What comes all at once —
30
+ * images, a classifier's answers — comes as a reply of one event, "done",
31
+ * with it as its `message`: so that it is counted, and waited for, as any
32
+ * reply is (see `wholeOf`).
33
+ */
34
+ export type RelayEvent = {
35
+ type: string;
36
+ } & Record<string, unknown>;
37
+ export interface ModelRelay {
38
+ /**
39
+ * Ask the model. Resolves to the events of the reply, to the last — or to
40
+ * undefined where the model is not one this relay can ask as the session
41
+ * that asks would: that session then asks it itself. It does not reject.
42
+ */
43
+ ask(request: RelayRequest, signal?: AbortSignal): Promise<AsyncIterable<RelayEvent> | undefined>;
44
+ }
45
+ /**
46
+ * Whether a value is data: what it is on the other side of a channel is what
47
+ * it is here. Text, numbers that are numbers, yes and no, nothing; and lists
48
+ * and plain records of those. Not a function, nor anything that is of a kind
49
+ * of its own (a date, a signal, bytes; a list or a record that is more than
50
+ * one), nor what holds itself, nor what says of itself something other than
51
+ * it shows. (What a record has by a symbol, or has and does not show, is no
52
+ * part of it on any channel, and a provider is sent none of it either: pi's
53
+ * schemas have such.)
54
+ */
55
+ export declare function isData(value: unknown, within?: Set<object>): boolean;
56
+ /**
57
+ * The options a session asks with, as those that go with a relayed request —
58
+ * or undefined where one is there that cannot go, and would be missed.
59
+ *
60
+ * What goes is whatever is data, by whatever name: a provider's own options
61
+ * are its own, and are not known here by name. What cannot go: a key of the
62
+ * asker's own, a way of its own to reach the provider, a span to report to,
63
+ * a reply that is to be fetched later (it is fetched where it was asked
64
+ * for) — and anything else that is not data: a provider may read whatever
65
+ * it is given, and what goes with a request is its asker's to mean something
66
+ * by. (What whoever hands a request over knows to be nothing a provider is
67
+ * handed, they leave out first: see `account`, pi-adapter.ts.) The word to
68
+ * stop by is no option here: it goes beside the request.
69
+ */
70
+ export declare function dataOf(options?: Record<string, unknown>): Record<string, unknown> | undefined;
71
+ /**
72
+ * Data as it goes on a channel, where a record in it has nothing under a
73
+ * name. A channel carries no such name — and to have nothing under a name is
74
+ * not to be without it, where records are laid one over another, name by
75
+ * name and in the order of their names (as pi lays a request's headers, and
76
+ * what a model is sampled by, over the model's own). So a word is put under
77
+ * each such name, that is nothing else: said beside the data (`mark`), and
78
+ * taken out again where the data is had (`unmarked`). The name then stands
79
+ * where it stood, with nothing under it.
80
+ */
81
+ export declare function marked<T>(data: T): {
82
+ data: T;
83
+ mark?: string;
84
+ };
85
+ /** Data that came by a channel (see `marked`), with nothing under the names of its records that the mark is under. (In a list the mark is a word like any: nothing is ever marked there.) */
86
+ export declare function unmarked<T>(data: T, mark: unknown): T;
87
+ /**
88
+ * What came of asking a model, of a reply that is gone through to its end:
89
+ * the reply whole — or, of a request that failed before it was one, its
90
+ * failure thrown (as pi's own `generateImages` and `classify` have what a
91
+ * provider throws, and make of it what they give back).
92
+ */
93
+ export declare function wholeOf(reply: AsyncIterable<RelayEvent>): Promise<unknown>;
94
+ /** What a reply used, as pi has it on the reply. */
95
+ export interface ReplyUsage {
96
+ input: number;
97
+ output: number;
98
+ cacheRead: number;
99
+ cacheWrite: number;
100
+ cost: {
101
+ total: number;
102
+ };
103
+ }
104
+ /** What the reply an event is the last of used — undefined of any other event. */
105
+ export declare function usageAtEnd(event: RelayEvent): ReplyUsage | undefined;
106
+ /**
107
+ * The event that ends a reply the model was not asked for: as pi makes the
108
+ * reply of a request that was cancelled before it was sent. (Said as one that
109
+ * was cancelled, whyever it was: pi reads the words of a reply that failed —
110
+ * for a number that looks like a server's, to try again; for a limit, to sum
111
+ * the conversation up — and a request that is not to be made is neither.)
112
+ */
113
+ export declare function notAsked(model: RelayModel, why: string, as?: "aborted" | "error"): RelayEvent;
114
+ /**
115
+ * Makes of a reply's events the events as they are sent: without the reply
116
+ * so far. (One for each reply: it keeps how much of each tool call has been
117
+ * sent.) What an event adds is sent with it — but a tool call's arguments,
118
+ * which pi puts together from their pieces in its own way for each kind of
119
+ * provider, can only be sent whole: so they are, with every piece while they
120
+ * are short, and after that each time they have grown by half — and whole at
121
+ * their end. Whoever is shown a long tool call as it comes is shown its
122
+ * arguments as they were a little while before.
123
+ */
124
+ export declare function leaner(): (event: RelayEvent) => RelayEvent;
125
+ /** The reply so far, kept where events that were sent without it are given it again. */
126
+ export interface SoFar {
127
+ partial?: {
128
+ content: Record<string, unknown>[];
129
+ } & Record<string, unknown>;
130
+ }
131
+ /** An event that was sent without the reply so far (see `leaner`), with it. */
132
+ export declare function whole(event: RelayEvent, state: SoFar): RelayEvent;
133
+ /**
134
+ * A relay that asks with this process's own pi: the models it finds, and the
135
+ * keys it has for their providers. Its events are sent ones (see `leaner`).
136
+ * `close` when whoever it asks for is done: what is still being asked is
137
+ * asked no further, and what was kept for it is let go of.
138
+ */
139
+ export declare function createModelRelay(): ModelRelay & {
140
+ close(): Promise<void>;
141
+ };
142
+ /** What the end that asks sends: a request, or that one it sent is cancelled. */
143
+ export type RelayAsked = {
144
+ relay: {
145
+ id: number;
146
+ request: RelayRequest;
147
+ mark?: string;
148
+ };
149
+ } | {
150
+ relayAbort: number;
151
+ };
152
+ /** What the end that answers sends: an event of the reply to a request, or that the request is not one it can serve. */
153
+ export type RelayAnswered = {
154
+ relayed: {
155
+ id: number;
156
+ event: RelayEvent;
157
+ } | {
158
+ id: number;
159
+ not: true;
160
+ };
161
+ };
162
+ /**
163
+ * The asking end: a relay that is reached by messages. `heard` is to be told
164
+ * what the other end answers; `close` when the other end is gone — whatever
165
+ * is still waited for then ends as a request that failed, saying so (nobody
166
+ * cancelled it), and nothing more is asked by it.
167
+ */
168
+ export declare function relayClient(send: (message: RelayAsked) => void): {
169
+ relay: ModelRelay;
170
+ heard(answer: RelayAnswered["relayed"]): void;
171
+ close(): void;
172
+ };
173
+ /**
174
+ * The answering end: serves, by `relay`, the requests that `heard` is told
175
+ * of. `refuse`: whether a request is not to be made at all (it then ends as
176
+ * one that was cancelled) — asked before each, and waited for; `replied`:
177
+ * told what each reply used, as its last event passes. `close`: what is
178
+ * still being asked is asked no further.
179
+ */
180
+ export declare function relayServer(relay: ModelRelay, send: (message: RelayAnswered) => void, on?: {
181
+ refuse?: (request: RelayRequest) => boolean | Promise<boolean>;
182
+ replied?: (usage: ReplyUsage) => void;
183
+ }): {
184
+ heard(message: RelayAsked): void;
185
+ close(): void;
186
+ };
187
+ /** A relay whose events are sent ones, as one whose events are pi's own: each with the reply so far. */
188
+ export declare function withRepliesWhole(relay: ModelRelay): ModelRelay;