@nylorun/runtime 0.3.0-beta → 0.5.0-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.md +53 -20
- package/dist/adapters/media.d.ts +2 -18
- package/dist/adapters/media.js +2 -52
- package/dist/adapters/observe.js +1 -1
- package/dist/cli.js +11 -6
- package/dist/config.d.ts +17 -10
- package/dist/contracts.d.ts +3 -166
- package/dist/dev-entry.d.ts +1 -0
- package/dist/dev-entry.js +2 -0
- package/dist/dev.js +6 -1
- package/dist/environment.d.ts +2 -0
- package/dist/environment.js +64 -0
- package/dist/index.d.ts +8 -8
- package/dist/index.js +5 -5
- package/dist/launcher.d.ts +1 -0
- package/dist/launcher.js +33 -0
- package/dist/media.d.ts +29 -0
- package/dist/media.js +53 -0
- package/dist/model/auth-store.d.ts +2 -1
- package/dist/model/auth-store.js +9 -2
- package/dist/model/configure.js +60 -30
- package/dist/model/defaults.d.ts +17 -0
- package/dist/model/defaults.js +21 -0
- package/dist/model/http-model.d.ts +12 -0
- package/dist/model/http-model.js +299 -0
- package/dist/model/models.d.ts +2 -2
- package/dist/model/models.js +24 -3
- package/dist/model/pi-model.d.ts +2 -1
- package/dist/model/pi-model.js +53 -8
- package/dist/model/settings.js +35 -13
- package/dist/node/index.d.ts +5 -0
- package/dist/node/index.js +5 -0
- package/dist/node/local-sessions.d.ts +5 -0
- package/dist/node/local-sessions.js +157 -0
- package/dist/redact.d.ts +1 -0
- package/dist/redact.js +14 -0
- package/dist/server/ag-ui.d.ts +1 -1
- package/dist/server/delivery.d.ts +24 -0
- package/dist/server/delivery.js +107 -0
- package/dist/server/host.d.ts +11 -6
- package/dist/server/host.js +236 -305
- package/dist/sessions/host.d.ts +29 -0
- package/dist/sessions/host.js +291 -0
- package/dist/sessions/store.d.ts +40 -0
- package/dist/sessions/store.js +30 -0
- package/package.json +11 -4
- package/dist/adapters/journal.d.ts +0 -35
- package/dist/adapters/journal.js +0 -130
package/dist/model/models.js
CHANGED
|
@@ -1,8 +1,29 @@
|
|
|
1
|
-
import { createProvider, envApiKeyAuth, } from "@earendil-works/pi-ai";
|
|
1
|
+
import { createProvider, defaultProviderAuthContext, envApiKeyAuth, } from "@earendil-works/pi-ai";
|
|
2
2
|
import { stream, streamSimple, } from "@earendil-works/pi-ai/api/openai-completions";
|
|
3
3
|
import { builtinModels } from "@earendil-works/pi-ai/providers/all";
|
|
4
4
|
export function modelsFor(selection, credentials) {
|
|
5
|
-
const
|
|
5
|
+
const environmentFirst = {
|
|
6
|
+
async read(providerId, options) {
|
|
7
|
+
const explicit = process.env.MODEL_PROVIDER_API_KEY;
|
|
8
|
+
if (explicit &&
|
|
9
|
+
(!selection.provider || selection.provider === providerId))
|
|
10
|
+
return { type: "api_key", key: explicit };
|
|
11
|
+
const provider = models
|
|
12
|
+
.getProviders()
|
|
13
|
+
.find((item) => item.id === providerId);
|
|
14
|
+
const ambient = await provider?.auth.apiKey?.resolve({
|
|
15
|
+
ctx: defaultProviderAuthContext(),
|
|
16
|
+
signal: options?.signal ?? new AbortController().signal,
|
|
17
|
+
});
|
|
18
|
+
if (ambient)
|
|
19
|
+
return undefined;
|
|
20
|
+
return credentials.read(providerId, options);
|
|
21
|
+
},
|
|
22
|
+
list: (options) => credentials.list(options),
|
|
23
|
+
modify: (id, fn, options) => credentials.modify(id, fn, options),
|
|
24
|
+
delete: (id, options) => credentials.delete(id, options),
|
|
25
|
+
};
|
|
26
|
+
const models = builtinModels({ credentials: environmentFirst });
|
|
6
27
|
if (!selection.custom)
|
|
7
28
|
return models;
|
|
8
29
|
const model = {
|
|
@@ -22,7 +43,7 @@ export function modelsFor(selection, credentials) {
|
|
|
22
43
|
name: "Custom OpenAI-compatible",
|
|
23
44
|
baseUrl: selection.custom.baseUrl,
|
|
24
45
|
auth: {
|
|
25
|
-
apiKey: envApiKeyAuth("Custom API key", ["
|
|
46
|
+
apiKey: envApiKeyAuth("Custom API key", ["MODEL_PROVIDER_API_KEY"]),
|
|
26
47
|
},
|
|
27
48
|
models: [model],
|
|
28
49
|
api: { stream, streamSimple },
|
package/dist/model/pi-model.d.ts
CHANGED
|
@@ -3,8 +3,9 @@ import type { RuntimeMedia } from "../adapters/media.js";
|
|
|
3
3
|
import { type Selection } from "./models.js";
|
|
4
4
|
export interface PiModelOptions {
|
|
5
5
|
readonly root?: string;
|
|
6
|
+
readonly onPreview?: (preview: import("./defaults.js").ModelPreview) => void;
|
|
6
7
|
readonly selection?: Selection;
|
|
7
8
|
readonly media?: Pick<RuntimeMedia, "dataUrl">;
|
|
8
9
|
}
|
|
9
|
-
/**
|
|
10
|
+
/** Node model adapter. Local provider configuration is read only when invoked. */
|
|
10
11
|
export declare function piModel(options?: PiModelOptions): RuntimeModelAdapter;
|
package/dist/model/pi-model.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
-
import { scrub } from "../
|
|
2
|
+
import { scrub } from "../redact.js";
|
|
3
3
|
import { ProjectCredentialStore } from "./auth-store.js";
|
|
4
4
|
import { modelsFor } from "./models.js";
|
|
5
5
|
import { modelSelection, projectSecrets } from "./settings.js";
|
|
@@ -11,13 +11,20 @@ const emptyUsage = () => ({
|
|
|
11
11
|
cacheWrite: 0,
|
|
12
12
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
13
13
|
});
|
|
14
|
-
/**
|
|
14
|
+
/** Node model adapter. Local provider configuration is read only when invoked. */
|
|
15
15
|
export function piModel(options = {}) {
|
|
16
16
|
return async (call, context) => {
|
|
17
17
|
context.signal.throwIfAborted();
|
|
18
18
|
const root = options.root ?? process.cwd();
|
|
19
|
-
const
|
|
20
|
-
const
|
|
19
|
+
const configured = options.selection ?? modelSelection(root);
|
|
20
|
+
const requested = call.model?.id;
|
|
21
|
+
const selection = {
|
|
22
|
+
...configured,
|
|
23
|
+
model: requested?.startsWith(`${configured.provider}/`)
|
|
24
|
+
? requested.slice(configured.provider.length + 1)
|
|
25
|
+
: (requested ?? configured.model),
|
|
26
|
+
};
|
|
27
|
+
const registry = modelsFor(selection, new ProjectCredentialStore(join(root, ".nylorun", "auth.json"), join(root, ".env", "auth.json")));
|
|
21
28
|
const selected = registry.getModel(selection.provider, selection.model);
|
|
22
29
|
if (!selected)
|
|
23
30
|
throw new Error("Unknown model. Run nylorun configure.");
|
|
@@ -65,7 +72,9 @@ export function piModel(options = {}) {
|
|
|
65
72
|
typeof ref.agentId !== "string" ||
|
|
66
73
|
typeof ref.assetId !== "string")
|
|
67
74
|
throw new Error("Expected a local media reference.");
|
|
68
|
-
const asset = await options.media?.dataUrl({ agentId: ref.agentId, assetId: ref.assetId },
|
|
75
|
+
const asset = await options.media?.dataUrl({ agentId: ref.agentId, assetId: ref.assetId }, "sessionId" in ref && typeof ref.sessionId === "string"
|
|
76
|
+
? ref.sessionId
|
|
77
|
+
: call.executionId);
|
|
69
78
|
if (!asset)
|
|
70
79
|
throw new Error("Media is unavailable; pass the shared media adapter to piModel({ media }).");
|
|
71
80
|
const comma = asset.url.indexOf(",");
|
|
@@ -156,7 +165,14 @@ export function piModel(options = {}) {
|
|
|
156
165
|
parameters: { ...tool.inputSchema },
|
|
157
166
|
}));
|
|
158
167
|
const request = {
|
|
159
|
-
systemPrompt:
|
|
168
|
+
systemPrompt: [
|
|
169
|
+
...instructions,
|
|
170
|
+
...(call.outputSchema
|
|
171
|
+
? [
|
|
172
|
+
`Return the final answer as JSON matching this schema: ${JSON.stringify(call.outputSchema)}. Use tools when needed before returning the final JSON.`,
|
|
173
|
+
]
|
|
174
|
+
: []),
|
|
175
|
+
].join("\n"),
|
|
160
176
|
messages,
|
|
161
177
|
tools,
|
|
162
178
|
};
|
|
@@ -167,14 +183,34 @@ export function piModel(options = {}) {
|
|
|
167
183
|
call: scrub(call, secrets),
|
|
168
184
|
});
|
|
169
185
|
try {
|
|
170
|
-
const
|
|
186
|
+
const invocationOptions = {
|
|
171
187
|
signal: context.signal,
|
|
172
188
|
temperature: call.model?.controls?.temperature,
|
|
173
189
|
maxTokens: call.model?.controls?.maxOutputTokens,
|
|
174
190
|
...(call.model?.config
|
|
175
191
|
? { samplingParams: { ...call.model.config } }
|
|
176
192
|
: {}),
|
|
177
|
-
}
|
|
193
|
+
};
|
|
194
|
+
let response;
|
|
195
|
+
if (options.onPreview) {
|
|
196
|
+
const stream = registry.streamSimple(selected, request, invocationOptions);
|
|
197
|
+
for await (const event of stream) {
|
|
198
|
+
if (event.type === "text_delta") {
|
|
199
|
+
try {
|
|
200
|
+
void Promise.resolve(options.onPreview({
|
|
201
|
+
invocationId: context.invocationId,
|
|
202
|
+
text: event.delta,
|
|
203
|
+
})).catch(() => { });
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
/* Preview delivery is independent. */
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
response = await stream.result();
|
|
211
|
+
}
|
|
212
|
+
else
|
|
213
|
+
response = await registry.complete(selected, request, invocationOptions);
|
|
178
214
|
context.signal.throwIfAborted();
|
|
179
215
|
if (response.stopReason === "error" ||
|
|
180
216
|
response.stopReason === "aborted" ||
|
|
@@ -203,6 +239,15 @@ export function piModel(options = {}) {
|
|
|
203
239
|
...metadataFor(part.thoughtSignature),
|
|
204
240
|
});
|
|
205
241
|
}
|
|
242
|
+
if (call.outputSchema &&
|
|
243
|
+
!output.some((part) => part.type === "tool-call")) {
|
|
244
|
+
const text = output
|
|
245
|
+
.filter((part) => part.type === "text")
|
|
246
|
+
.map((part) => part.text)
|
|
247
|
+
.join("");
|
|
248
|
+
const value = JSON.parse(text);
|
|
249
|
+
output.splice(0, output.length, { type: "json", value });
|
|
250
|
+
}
|
|
206
251
|
return {
|
|
207
252
|
output,
|
|
208
253
|
finishReason: response.stopReason === "toolUse"
|
package/dist/model/settings.js
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
export function modelSelection(root = process.cwd()) {
|
|
4
|
+
const { MODEL_PROVIDER: provider, MODEL: model, MODEL_PROVIDER_BASE_URL: baseUrl, } = process.env;
|
|
5
|
+
if (provider !== undefined || model !== undefined || baseUrl !== undefined) {
|
|
6
|
+
if (!provider?.trim() || !model?.trim())
|
|
7
|
+
throw new Error("Set both MODEL_PROVIDER and MODEL, or run nylorun configure.");
|
|
8
|
+
if (provider === "custom" && !baseUrl?.trim())
|
|
9
|
+
throw new Error("Set MODEL_PROVIDER_BASE_URL for MODEL_PROVIDER=custom.");
|
|
10
|
+
if (baseUrl && provider !== "custom")
|
|
11
|
+
throw new Error("MODEL_PROVIDER_BASE_URL requires MODEL_PROVIDER=custom.");
|
|
12
|
+
if (baseUrl) {
|
|
13
|
+
let url;
|
|
14
|
+
try {
|
|
15
|
+
url = new URL(baseUrl);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw new Error("MODEL_PROVIDER_BASE_URL must be an HTTP(S) URL.");
|
|
19
|
+
}
|
|
20
|
+
if (!["http:", "https:"].includes(url.protocol))
|
|
21
|
+
throw new Error("MODEL_PROVIDER_BASE_URL must be an HTTP(S) URL.");
|
|
22
|
+
}
|
|
23
|
+
return { provider, model, ...(baseUrl ? { custom: { baseUrl } } : {}) };
|
|
24
|
+
}
|
|
4
25
|
try {
|
|
5
26
|
let contents;
|
|
6
27
|
try {
|
|
@@ -9,7 +30,7 @@ export function modelSelection(root = process.cwd()) {
|
|
|
9
30
|
catch (error) {
|
|
10
31
|
if (!(error instanceof Error) ||
|
|
11
32
|
!("code" in error) ||
|
|
12
|
-
error.code
|
|
33
|
+
!["ENOENT", "ENOTDIR"].includes(String(error.code)))
|
|
13
34
|
throw error;
|
|
14
35
|
contents = readFileSync(join(root, "config", "model.json"), "utf8");
|
|
15
36
|
}
|
|
@@ -30,17 +51,18 @@ export function projectSecrets(root = process.cwd()) {
|
|
|
30
51
|
const values = Object.entries(process.env)
|
|
31
52
|
.filter(([key]) => /key|token|secret|password|credential/i.test(key))
|
|
32
53
|
.flatMap(([, value]) => (value ? [value] : []));
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
54
|
+
for (const directory of [".nylorun", ".env"])
|
|
55
|
+
try {
|
|
56
|
+
const collect = (value) => {
|
|
57
|
+
if (typeof value === "string")
|
|
58
|
+
values.push(value);
|
|
59
|
+
else if (value && typeof value === "object")
|
|
60
|
+
Object.values(value).forEach(collect);
|
|
61
|
+
};
|
|
62
|
+
collect(JSON.parse(readFileSync(join(root, directory, "auth.json"), "utf8")));
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
/* The vault may not exist before setup. */
|
|
66
|
+
}
|
|
45
67
|
return values;
|
|
46
68
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { localSessions } from "./local-sessions.js";
|
|
2
|
+
export { localMedia, MediaStore } from "../adapters/media.js";
|
|
3
|
+
export { jsonlObserver } from "../adapters/observe.js";
|
|
4
|
+
export { piModel, type PiModelOptions } from "../model/pi-model.js";
|
|
5
|
+
export { projectAsset } from "../assets.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { localSessions } from "./local-sessions.js";
|
|
2
|
+
export { localMedia, MediaStore } from "../adapters/media.js";
|
|
3
|
+
export { jsonlObserver } from "../adapters/observe.js";
|
|
4
|
+
export { piModel } from "../model/pi-model.js";
|
|
5
|
+
export { projectAsset } from "../assets.js";
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { mkdir, open, readFile, readdir, rename, rm, realpath, } from "node:fs/promises";
|
|
2
|
+
import { resolve, join } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { sessionSummary, } from "../sessions/store.js";
|
|
5
|
+
/** Single-owner local disk store. No lease stealing, replay, or shared-filesystem guarantee. */
|
|
6
|
+
export function localSessions(options) {
|
|
7
|
+
let closed = false;
|
|
8
|
+
let directory;
|
|
9
|
+
const token = randomUUID();
|
|
10
|
+
const acquired = (async () => {
|
|
11
|
+
await mkdir(resolve(options.root), { recursive: true, mode: 0o700 });
|
|
12
|
+
directory = await realpath(resolve(options.root));
|
|
13
|
+
const path = join(directory, ".owner.lock");
|
|
14
|
+
let handle;
|
|
15
|
+
try {
|
|
16
|
+
handle = await open(path, "wx", 0o600);
|
|
17
|
+
}
|
|
18
|
+
catch (cause) {
|
|
19
|
+
throw new Error(`Session store ${directory} already has an owner. Stop the owner before opening it again. After a crash, confirm it has stopped and manually remove .owner.lock.`, { cause });
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
await handle.writeFile(JSON.stringify({ token, pid: process.pid }));
|
|
23
|
+
await handle.sync();
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
await handle.close();
|
|
27
|
+
}
|
|
28
|
+
})();
|
|
29
|
+
void acquired.catch(() => { });
|
|
30
|
+
let operations = Promise.resolve();
|
|
31
|
+
const check = async () => {
|
|
32
|
+
await acquired;
|
|
33
|
+
if (closed)
|
|
34
|
+
throw new Error("Session store is closed");
|
|
35
|
+
const owner = JSON.parse(await readFile(join(directory, ".owner.lock"), "utf8"));
|
|
36
|
+
if (owner.token !== token)
|
|
37
|
+
throw new Error("Session store ownership was lost; refusing further writes");
|
|
38
|
+
};
|
|
39
|
+
const pathFor = (agentId, sessionId) => join(directory, safe(agentId), `${safe(sessionId)}.json`);
|
|
40
|
+
const get = async (agentId, sessionId) => {
|
|
41
|
+
await check();
|
|
42
|
+
try {
|
|
43
|
+
const value = JSON.parse(await readFile(pathFor(agentId, sessionId), "utf8"));
|
|
44
|
+
if (value.version !== 1 ||
|
|
45
|
+
value.id !== sessionId ||
|
|
46
|
+
value.agentId !== agentId ||
|
|
47
|
+
!Array.isArray(value.events))
|
|
48
|
+
throw new Error("Invalid stored session document");
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (!isMissing(error))
|
|
53
|
+
throw error;
|
|
54
|
+
try {
|
|
55
|
+
const contents = await readFile(join(directory, safe(agentId), safe(sessionId), "events.jsonl"), "utf8");
|
|
56
|
+
const events = contents
|
|
57
|
+
.split("\n")
|
|
58
|
+
.filter(Boolean)
|
|
59
|
+
.map((line) => JSON.parse(line));
|
|
60
|
+
return {
|
|
61
|
+
version: 1,
|
|
62
|
+
id: sessionId,
|
|
63
|
+
agentId,
|
|
64
|
+
status: "archived",
|
|
65
|
+
startedAt: events[0] ? Date.parse(events[0].ts) : 0,
|
|
66
|
+
updatedAt: 0,
|
|
67
|
+
events,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
catch (legacyError) {
|
|
71
|
+
if (isMissing(legacyError))
|
|
72
|
+
return undefined;
|
|
73
|
+
throw legacyError;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
get,
|
|
79
|
+
put(agentId, sessionId, session) {
|
|
80
|
+
const contents = JSON.stringify(session);
|
|
81
|
+
const operation = operations.then(async () => {
|
|
82
|
+
await check();
|
|
83
|
+
if (session.id !== sessionId || session.agentId !== agentId)
|
|
84
|
+
throw new Error("Session identity mismatch");
|
|
85
|
+
const target = pathFor(agentId, sessionId);
|
|
86
|
+
await mkdir(join(directory, safe(agentId)), {
|
|
87
|
+
recursive: true,
|
|
88
|
+
mode: 0o700,
|
|
89
|
+
});
|
|
90
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
91
|
+
try {
|
|
92
|
+
const file = await open(temporary, "wx", 0o600);
|
|
93
|
+
try {
|
|
94
|
+
await file.writeFile(contents);
|
|
95
|
+
await file.sync();
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
await file.close();
|
|
99
|
+
}
|
|
100
|
+
await check();
|
|
101
|
+
await rename(temporary, target);
|
|
102
|
+
const parent = await open(join(directory, safe(agentId)), "r");
|
|
103
|
+
try {
|
|
104
|
+
await parent.sync();
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
await parent.close();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
await rm(temporary, { force: true });
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
operations = operation.catch(() => { });
|
|
115
|
+
return operation;
|
|
116
|
+
},
|
|
117
|
+
async list(agentId) {
|
|
118
|
+
await check();
|
|
119
|
+
let names;
|
|
120
|
+
try {
|
|
121
|
+
names = await readdir(join(directory, safe(agentId)), {
|
|
122
|
+
withFileTypes: true,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (isMissing(error))
|
|
127
|
+
return [];
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
const sessions = await Promise.all(names
|
|
131
|
+
.filter((item) => item.isDirectory() || item.name.endsWith(".json"))
|
|
132
|
+
.map((item) => get(agentId, item.isDirectory() ? item.name : item.name.slice(0, -5))));
|
|
133
|
+
return sessions
|
|
134
|
+
.flatMap((session) => (session ? [sessionSummary(session)] : []))
|
|
135
|
+
.sort((a, b) => b.startedAt - a.startedAt);
|
|
136
|
+
},
|
|
137
|
+
async close() {
|
|
138
|
+
await operations;
|
|
139
|
+
if (closed)
|
|
140
|
+
return;
|
|
141
|
+
await check();
|
|
142
|
+
closed = true;
|
|
143
|
+
await rm(join(directory, ".owner.lock"));
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function safe(value) {
|
|
148
|
+
if (value === "." || value === ".." || !/^[a-zA-Z0-9._-]+$/.test(value))
|
|
149
|
+
throw new Error("Invalid session path identifier");
|
|
150
|
+
return value;
|
|
151
|
+
}
|
|
152
|
+
function isMissing(error) {
|
|
153
|
+
return (!!error &&
|
|
154
|
+
typeof error === "object" &&
|
|
155
|
+
"code" in error &&
|
|
156
|
+
error.code === "ENOENT");
|
|
157
|
+
}
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function scrub(value: unknown, secrets: readonly string[]): unknown;
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function scrub(value, secrets) {
|
|
2
|
+
if (typeof value === "string")
|
|
3
|
+
return secrets.reduce((text, secret) => secret.length >= 8 ? text.split(secret).join("[redacted]") : text, value.replace(/data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/giu, "[inline image data redacted]"));
|
|
4
|
+
if (Array.isArray(value))
|
|
5
|
+
return value.map((item) => scrub(item, secrets));
|
|
6
|
+
if (value && typeof value === "object")
|
|
7
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
8
|
+
key,
|
|
9
|
+
/^(authorization|api[_-]?key|(?:access|refresh|id|auth)[_-]?token|token|secret|password|cookie|credentials?)$/iu.test(key)
|
|
10
|
+
? "[redacted]"
|
|
11
|
+
: scrub(item, secrets),
|
|
12
|
+
]));
|
|
13
|
+
return value;
|
|
14
|
+
}
|
package/dist/server/ag-ui.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CanonicalEvent } from "../
|
|
1
|
+
import type { CanonicalEvent } from "../sessions/store.js";
|
|
2
2
|
/** Minimal truthful AG-UI projection from the same canonical events Studio displays. */
|
|
3
3
|
export declare function agUiEvents(events: readonly CanonicalEvent[], threadId: string, runId: string): readonly Record<string, unknown>[];
|
|
4
4
|
/**
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Bounded per-request delivery. Generation never waits for a subscriber. */
|
|
2
|
+
export declare class EventDelivery {
|
|
3
|
+
private readonly abort;
|
|
4
|
+
private readonly limits;
|
|
5
|
+
readonly response: Response;
|
|
6
|
+
private controller;
|
|
7
|
+
private readonly queue;
|
|
8
|
+
private readonly suppressed;
|
|
9
|
+
private previewBytes;
|
|
10
|
+
private readonly previewTotals;
|
|
11
|
+
private eventBytes;
|
|
12
|
+
private eventCount;
|
|
13
|
+
private ended;
|
|
14
|
+
private closed;
|
|
15
|
+
constructor(abort: () => void, limits?: {
|
|
16
|
+
previewBytes?: number;
|
|
17
|
+
eventBytes?: number;
|
|
18
|
+
eventCount?: number;
|
|
19
|
+
}, inherited?: HeadersInit);
|
|
20
|
+
private waiting;
|
|
21
|
+
private flush;
|
|
22
|
+
push(event: Record<string, unknown>, preview?: string): void;
|
|
23
|
+
end(): void;
|
|
24
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/** Bounded per-request delivery. Generation never waits for a subscriber. */
|
|
2
|
+
export class EventDelivery {
|
|
3
|
+
abort;
|
|
4
|
+
limits;
|
|
5
|
+
response;
|
|
6
|
+
controller;
|
|
7
|
+
queue = [];
|
|
8
|
+
suppressed = new Set();
|
|
9
|
+
previewBytes = 0;
|
|
10
|
+
previewTotals = new Map();
|
|
11
|
+
eventBytes = 0;
|
|
12
|
+
eventCount = 0;
|
|
13
|
+
ended = false;
|
|
14
|
+
closed = false;
|
|
15
|
+
constructor(abort, limits = {}, inherited) {
|
|
16
|
+
this.abort = abort;
|
|
17
|
+
this.limits = limits;
|
|
18
|
+
for (const value of Object.values(limits))
|
|
19
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
20
|
+
throw new Error("Delivery limits must be positive integers");
|
|
21
|
+
const stream = new ReadableStream({
|
|
22
|
+
start: (controller) => {
|
|
23
|
+
this.controller = controller;
|
|
24
|
+
},
|
|
25
|
+
pull: () => this.flush(),
|
|
26
|
+
cancel: () => {
|
|
27
|
+
this.closed = true;
|
|
28
|
+
this.queue.length = 0;
|
|
29
|
+
abort();
|
|
30
|
+
},
|
|
31
|
+
}, { highWaterMark: 0 });
|
|
32
|
+
const headers = new Headers(inherited);
|
|
33
|
+
headers.set("content-type", "text/event-stream; charset=utf-8");
|
|
34
|
+
headers.set("cache-control", "no-cache");
|
|
35
|
+
this.response = new Response(stream, { headers });
|
|
36
|
+
}
|
|
37
|
+
waiting = false;
|
|
38
|
+
flush() {
|
|
39
|
+
if (this.closed)
|
|
40
|
+
return;
|
|
41
|
+
const item = this.queue.shift();
|
|
42
|
+
if (item) {
|
|
43
|
+
this.waiting = false;
|
|
44
|
+
if (item.preview)
|
|
45
|
+
this.previewBytes -= item.bytes.byteLength;
|
|
46
|
+
else {
|
|
47
|
+
this.eventBytes -= item.bytes.byteLength;
|
|
48
|
+
this.eventCount--;
|
|
49
|
+
}
|
|
50
|
+
this.controller.enqueue(item.bytes);
|
|
51
|
+
}
|
|
52
|
+
else if (this.ended) {
|
|
53
|
+
this.closed = true;
|
|
54
|
+
this.controller.close();
|
|
55
|
+
}
|
|
56
|
+
else
|
|
57
|
+
this.waiting = true;
|
|
58
|
+
}
|
|
59
|
+
push(event, preview) {
|
|
60
|
+
if (this.closed || this.ended || (preview && this.suppressed.has(preview)))
|
|
61
|
+
return;
|
|
62
|
+
const bytes = new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`);
|
|
63
|
+
if (preview &&
|
|
64
|
+
Math.max(this.previewBytes, this.previewTotals.get(preview) ?? 0) +
|
|
65
|
+
bytes.byteLength >
|
|
66
|
+
(this.limits.previewBytes ?? 64 * 1024)) {
|
|
67
|
+
this.suppressed.add(preview);
|
|
68
|
+
for (let i = this.queue.length - 1; i >= 0; i--)
|
|
69
|
+
if (this.queue[i].preview === preview) {
|
|
70
|
+
this.previewBytes -= this.queue[i].bytes.byteLength;
|
|
71
|
+
this.queue.splice(i, 1);
|
|
72
|
+
}
|
|
73
|
+
this.push({
|
|
74
|
+
type: "CUSTOM",
|
|
75
|
+
name: "nylorun.preview.incomplete",
|
|
76
|
+
value: { invocationId: preview },
|
|
77
|
+
});
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (!preview &&
|
|
81
|
+
(this.eventCount + 1 > (this.limits.eventCount ?? 256) ||
|
|
82
|
+
this.eventBytes + bytes.byteLength >
|
|
83
|
+
(this.limits.eventBytes ?? 1024 * 1024))) {
|
|
84
|
+
this.closed = true;
|
|
85
|
+
this.queue.length = 0;
|
|
86
|
+
this.controller.error(new Error("Subscriber exceeded execution-event delivery limits"));
|
|
87
|
+
this.abort();
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
this.queue.push({ bytes, ...(preview ? { preview } : {}) });
|
|
91
|
+
if (preview) {
|
|
92
|
+
this.previewBytes += bytes.byteLength;
|
|
93
|
+
this.previewTotals.set(preview, (this.previewTotals.get(preview) ?? 0) + bytes.byteLength);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
this.eventBytes += bytes.byteLength;
|
|
97
|
+
this.eventCount++;
|
|
98
|
+
}
|
|
99
|
+
if (this.waiting)
|
|
100
|
+
this.flush();
|
|
101
|
+
}
|
|
102
|
+
end() {
|
|
103
|
+
this.ended = true;
|
|
104
|
+
if (this.waiting)
|
|
105
|
+
this.flush();
|
|
106
|
+
}
|
|
107
|
+
}
|
package/dist/server/host.d.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { Hono, type Context } from "hono";
|
|
2
2
|
import type { JsonValue, RuntimeAgent } from "../contracts.js";
|
|
3
|
+
import { SessionHost } from "../sessions/host.js";
|
|
3
4
|
import type { RuntimeConfig } from "../config.js";
|
|
5
|
+
import type { ModelEnvironment } from "../model/http-model.js";
|
|
4
6
|
export type RuntimeActor = Readonly<{
|
|
5
7
|
id: string;
|
|
6
8
|
context?: Record<string, JsonValue>;
|
|
7
9
|
}>;
|
|
8
10
|
export type AgentRouterOptions = Readonly<{
|
|
9
|
-
/** Override the public URL prefix; defaults to the current Hono mount path. */
|
|
10
11
|
basePath?: string;
|
|
11
12
|
getActor?: (context: Context) => RuntimeActor | undefined | Promise<RuntimeActor | undefined>;
|
|
13
|
+
getInfo?: (context: Context) => unknown | Promise<unknown>;
|
|
14
|
+
getEnvironment?: (context: Context) => ModelEnvironment | Promise<ModelEnvironment>;
|
|
12
15
|
getRequestMetadata?: (context: Context) => Record<string, JsonValue> | undefined | Promise<Record<string, JsonValue> | undefined>;
|
|
13
16
|
}>;
|
|
14
17
|
export type ServeAgentsOptions = AgentRouterOptions & {
|
|
@@ -17,11 +20,13 @@ export type ServeAgentsOptions = AgentRouterOptions & {
|
|
|
17
20
|
};
|
|
18
21
|
declare const kServe: unique symbol;
|
|
19
22
|
export declare class Runtime {
|
|
20
|
-
|
|
21
|
-
|
|
23
|
+
private readonly config;
|
|
24
|
+
readonly host: SessionHost;
|
|
25
|
+
private served;
|
|
26
|
+
private closing?;
|
|
27
|
+
constructor(config?: RuntimeConfig);
|
|
22
28
|
close: () => Promise<void>;
|
|
23
|
-
[kServe](options: Omit<ServeAgentsOptions, "runtime">): Hono
|
|
29
|
+
[kServe](options: Omit<ServeAgentsOptions, "runtime">): Hono<any>;
|
|
24
30
|
}
|
|
25
|
-
|
|
26
|
-
export declare function serveAgents(options: ServeAgentsOptions): any;
|
|
31
|
+
export declare function serveAgents(options: ServeAgentsOptions): Hono<any>;
|
|
27
32
|
export {};
|