agent-neckbeard 1.1.29 → 1.1.30
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 +7 -0
- package/README.md +25 -27
- package/dist/archil.d.ts +73 -0
- package/dist/archil.js +673 -0
- package/dist/build.cjs +129 -5315
- package/dist/build.d.cts +9 -5
- package/dist/build.d.ts +9 -5
- package/dist/build.js +4 -6
- package/dist/{chunk-BPXEIXPM.js → chunk-FHNQ5DNA.js} +3264 -564
- package/dist/{chunk-FSBTLBB5.js → chunk-I5GIWADK.js} +29 -7
- package/dist/chunk-I5NULOJP.js +129 -0
- package/dist/chunk-PKUGXECR.js +13 -0
- package/dist/chunk-QA4L7ZI2.js +72 -0
- package/dist/{chunk-KG6SJM74.js → chunk-VHBDBB3N.js} +8 -5
- package/dist/cli.cjs +124 -5309
- package/dist/cli.js +7 -8
- package/dist/define-gdmBe9RA.d.ts +227 -0
- package/dist/durable.d.ts +53 -0
- package/dist/durable.js +92 -0
- package/dist/index.cjs +720 -988
- package/dist/index.d.cts +139 -87
- package/dist/index.d.ts +139 -87
- package/dist/index.js +12 -11
- package/dist/inside.d.ts +15 -0
- package/dist/inside.js +530 -0
- package/dist/{invoke-client-P2CPBYTF.js → invoke-client-QB2NTZ3L.js} +1 -2
- package/dist/pi-watch-legacy.d.ts +4503 -0
- package/dist/serve.cjs +9 -439
- package/dist/serve.d.cts +14 -1
- package/dist/serve.d.ts +14 -1
- package/dist/serve.js +3 -5
- package/docs/AGENT.md +81 -77
- package/docs/DAYTONA.md +2 -0
- package/docs/DOCKER.md +0 -1
- package/docs/E2B.md +1 -1
- package/docs/LEGACY.md +1 -8
- package/docs/MODAL.md +1 -1
- package/package.json +57 -23
- package/types/pi-watch.d.cts +68 -0
- package/dist/chunk-33IXN6MM.js +0 -21
- package/dist/chunk-6P5I7ZCH.js +0 -2552
- package/dist/chunk-YFG4EKZM.js +0 -508
- package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +0 -77
- package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +0 -77
- package/dist/serve-Du2NCz9_.d.cts +0 -111
- package/dist/serve-Du2NCz9_.d.ts +0 -111
- package/dist/supervisor.cjs +0 -5731
- package/dist/supervisor.d.cts +0 -482
- package/dist/supervisor.d.ts +0 -482
- package/dist/supervisor.js +0 -3187
- package/docs/SUPERVISOR.md +0 -258
package/dist/inside.js
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
import {
|
|
2
|
+
closeDurableResources,
|
|
3
|
+
durableWatchWindow,
|
|
4
|
+
openDurableHarness,
|
|
5
|
+
prepareSubmissionStop
|
|
6
|
+
} from "./chunk-I5NULOJP.js";
|
|
7
|
+
import {
|
|
8
|
+
withTimeout
|
|
9
|
+
} from "./chunk-QA4L7ZI2.js";
|
|
10
|
+
|
|
11
|
+
// src/inside-conversation.ts
|
|
12
|
+
import { mkdir } from "fs/promises";
|
|
13
|
+
import os from "os";
|
|
14
|
+
import path from "path";
|
|
15
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
16
|
+
import {
|
|
17
|
+
InboxDoc,
|
|
18
|
+
LiveDoc,
|
|
19
|
+
MemoryStorage
|
|
20
|
+
} from "@earendil-works/pi-durable";
|
|
21
|
+
import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
|
|
22
|
+
import { openNodeSqliteDatabase } from "@earendil-works/pi-durable/storage/sqlite/node";
|
|
23
|
+
import { SqliteStorage } from "@earendil-works/pi-durable/storage/sqlite";
|
|
24
|
+
import { builtinModels } from "@earendil-works/pi-ai/providers/all";
|
|
25
|
+
|
|
26
|
+
// src/braintrust.ts
|
|
27
|
+
var API_KEY = "BRAINTRUST_API_KEY";
|
|
28
|
+
var PROJECT_NAME = "BRAINTRUST_PROJECT_NAME";
|
|
29
|
+
var FLUSH_TIMEOUT_MS = 1e4;
|
|
30
|
+
var BRAINTRUST_PACKAGE = "braintrust";
|
|
31
|
+
var BRAINTRUST_VERSIONS = ">=3.44.0 <4.0.0";
|
|
32
|
+
var warn = (message) => console.warn(`neckbeard: ${message}`);
|
|
33
|
+
var errorText = (error) => error instanceof Error ? error.message : String(error);
|
|
34
|
+
function readBraintrustSettings(env, where) {
|
|
35
|
+
const apiKey = env[API_KEY]?.trim();
|
|
36
|
+
const projectName = env[PROJECT_NAME]?.trim();
|
|
37
|
+
if (apiKey && projectName) return { apiKey, projectName };
|
|
38
|
+
if (apiKey) warn(`Braintrust logging isn't configured ${where}: ${PROJECT_NAME} is not set.`);
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
async function startBraintrust({ apiKey, projectName }) {
|
|
42
|
+
const notTracing = "Braintrust tracing is off in the sandbox";
|
|
43
|
+
let sdk;
|
|
44
|
+
try {
|
|
45
|
+
sdk = await import(
|
|
46
|
+
/* webpackIgnore: true */
|
|
47
|
+
BRAINTRUST_PACKAGE
|
|
48
|
+
);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (errorText(error).includes(`Cannot find package '${BRAINTRUST_PACKAGE}'`)) {
|
|
51
|
+
warn(`${notTracing}: add ${BRAINTRUST_PACKAGE} ${BRAINTRUST_VERSIONS} to the agent's package's dependencies so the image has it.`);
|
|
52
|
+
} else {
|
|
53
|
+
warn(`${notTracing}: ${BRAINTRUST_PACKAGE} failed to load: ${errorText(error)}`);
|
|
54
|
+
}
|
|
55
|
+
return void 0;
|
|
56
|
+
}
|
|
57
|
+
if (typeof sdk.traced !== "function") {
|
|
58
|
+
warn(`${notTracing}: its ${BRAINTRUST_PACKAGE} can't trace Pi; use ${BRAINTRUST_VERSIONS}.`);
|
|
59
|
+
return void 0;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
sdk.initLogger({ projectName, apiKey });
|
|
63
|
+
} catch (error) {
|
|
64
|
+
warn(`${notTracing}: ${errorText(error)}`);
|
|
65
|
+
return void 0;
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
turn: (fn) => sdk.traced(fn, { name: "Pi Durable turn" }),
|
|
69
|
+
async flush() {
|
|
70
|
+
try {
|
|
71
|
+
await withTimeout(sdk.flush(), FLUSH_TIMEOUT_MS, `not sent within ${FLUSH_TIMEOUT_MS / 1e3} seconds; it may arrive later`);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
warn(`could not send the turn's Braintrust trace: ${errorText(error)}`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/inside-conversation.ts
|
|
80
|
+
async function openInsideConversation(pi, models = builtinModels(), maxDuration) {
|
|
81
|
+
const home = os.homedir();
|
|
82
|
+
const cwd = path.resolve(home, pi.cwd ?? "workspace");
|
|
83
|
+
await mkdir(cwd, { recursive: true });
|
|
84
|
+
const executionEnv = new NodeExecutionEnv({ cwd, shellEnv: { NECKBEARD_CWD: cwd } });
|
|
85
|
+
const storage = pi.persist ? await sqlite(home) : new MemoryStorage();
|
|
86
|
+
const ctx = BACKGROUND_CONTEXT;
|
|
87
|
+
const recovered = [];
|
|
88
|
+
let opened;
|
|
89
|
+
let tracing;
|
|
90
|
+
try {
|
|
91
|
+
opened = await openDurableHarness({ definition: { pi }, storage, executionEnv, models }, ctx);
|
|
92
|
+
const { root: root2, harness: harness2 } = opened;
|
|
93
|
+
const settings = readBraintrustSettings(process.env, "in the sandbox");
|
|
94
|
+
tracing = settings && await startBraintrust(settings);
|
|
95
|
+
if (pi.persist && (maxDuration || tracing)) {
|
|
96
|
+
const live = await harness2.snapshot(LiveDoc, root2.id, ctx);
|
|
97
|
+
const inbox = await harness2.snapshot(InboxDoc, root2.id, ctx);
|
|
98
|
+
const queued = inbox?.items.filter((item) => item.mode !== "write").map((item) => item.id) ?? [];
|
|
99
|
+
for (const id of [...live?.run?.inputs ?? [], ...queued]) {
|
|
100
|
+
const submission = await harness2.submission(id, ctx);
|
|
101
|
+
if (submission) recovered.push(submission);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
} catch (error) {
|
|
105
|
+
await closeDurableResources(opened?.harness, storage, executionEnv, ctx);
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const { root, harness } = opened;
|
|
109
|
+
const deadlines = /* @__PURE__ */ new Map();
|
|
110
|
+
let closed = false;
|
|
111
|
+
const settling = /* @__PURE__ */ new Map();
|
|
112
|
+
async function stopSubmission(id, context) {
|
|
113
|
+
const submission = await harness.submission(id, context);
|
|
114
|
+
if (!submission || (await submission.status(context)).conversationId !== root.id) return;
|
|
115
|
+
if (await submission.abort(context) !== "already_placed") return;
|
|
116
|
+
for (; ; ) {
|
|
117
|
+
const task = await root.commit((tx) => prepareSubmissionStop(tx, root.id, id), context);
|
|
118
|
+
if (task === void 0) return;
|
|
119
|
+
await harness.abortTask(task, context);
|
|
120
|
+
await harness.waitForTask(task, context);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function track(submission) {
|
|
124
|
+
if (settling.has(submission.id)) return;
|
|
125
|
+
if (maxDuration && !deadlines.has(submission.id)) {
|
|
126
|
+
deadlines.set(
|
|
127
|
+
submission.id,
|
|
128
|
+
setTimeout(() => {
|
|
129
|
+
void stopSubmission(submission.id, ctx).catch(() => {
|
|
130
|
+
});
|
|
131
|
+
}, maxDuration)
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
const settle = async () => {
|
|
135
|
+
await submission.wait(ctx);
|
|
136
|
+
await root.waitForIdle(ctx);
|
|
137
|
+
};
|
|
138
|
+
const finished = (tracing ? tracing.turn(settle) : settle()).catch(() => {
|
|
139
|
+
}).finally(async () => {
|
|
140
|
+
clearTimeout(deadlines.get(submission.id));
|
|
141
|
+
deadlines.delete(submission.id);
|
|
142
|
+
if (!closed) await tracing?.flush();
|
|
143
|
+
});
|
|
144
|
+
settling.set(submission.id, finished);
|
|
145
|
+
void finished.finally(() => settling.delete(submission.id));
|
|
146
|
+
}
|
|
147
|
+
function trackRecovered() {
|
|
148
|
+
for (const submission of recovered.splice(0)) track(submission);
|
|
149
|
+
}
|
|
150
|
+
async function submit(draft, context) {
|
|
151
|
+
const prior = await storage.submissionByRequest(root.id, draft.requestId, context);
|
|
152
|
+
if (prior?.status === "done" || prior?.status === "unanswered") return prior.id;
|
|
153
|
+
trackRecovered();
|
|
154
|
+
const submission = await root.submit(draft, context);
|
|
155
|
+
track(submission);
|
|
156
|
+
return submission.id;
|
|
157
|
+
}
|
|
158
|
+
async function settledCleanups(context) {
|
|
159
|
+
const cleanups = [];
|
|
160
|
+
for (const [id, finished] of [...settling]) {
|
|
161
|
+
const record = await storage.submission(id, context);
|
|
162
|
+
if (record?.status === "done" || record?.status === "unanswered") cleanups.push(finished);
|
|
163
|
+
}
|
|
164
|
+
return cleanups;
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
submit,
|
|
168
|
+
stopSubmission,
|
|
169
|
+
watch: (context, window) => root.watch(context, window),
|
|
170
|
+
abort: (context, options) => root.abort(context, options),
|
|
171
|
+
async waitForIdle(context) {
|
|
172
|
+
trackRecovered();
|
|
173
|
+
await root.waitForIdle(context);
|
|
174
|
+
await Promise.all(await settledCleanups(context));
|
|
175
|
+
},
|
|
176
|
+
async busy(context) {
|
|
177
|
+
return !!(await harness.snapshot(LiveDoc, root.id, context))?.run || (await settledCleanups(context)).length > 0;
|
|
178
|
+
},
|
|
179
|
+
async entry(id, context) {
|
|
180
|
+
return (await storage.entry(root.id, id, context))?.entry;
|
|
181
|
+
},
|
|
182
|
+
async submissionByRequest(key, context) {
|
|
183
|
+
return (await storage.submissionByRequest(root.id, key, context))?.id;
|
|
184
|
+
},
|
|
185
|
+
async submission(id, context) {
|
|
186
|
+
const record = await storage.submission(id, context);
|
|
187
|
+
if (record?.conversationId !== root.id || record.type !== "input") return;
|
|
188
|
+
const handle = await harness.submission(id, context);
|
|
189
|
+
if (!handle || !recovered.length) return handle;
|
|
190
|
+
return {
|
|
191
|
+
id,
|
|
192
|
+
status: (ctx2) => handle.status(ctx2),
|
|
193
|
+
abort: (ctx2) => handle.abort(ctx2),
|
|
194
|
+
async wait(ctx2) {
|
|
195
|
+
const status = await handle.status(ctx2);
|
|
196
|
+
if (status.status === "done" || status.status === "unanswered") return status;
|
|
197
|
+
trackRecovered();
|
|
198
|
+
return handle.wait(ctx2);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
},
|
|
202
|
+
async close() {
|
|
203
|
+
closed = true;
|
|
204
|
+
for (const timer of deadlines.values()) clearTimeout(timer);
|
|
205
|
+
await closeDurableResources(harness, storage, executionEnv, ctx);
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
async function sqlite(home) {
|
|
210
|
+
const id = process.env.NECKBEARD_SESSION_ID;
|
|
211
|
+
if (!id || !/^[a-zA-Z0-9_-]+$/.test(id)) throw new Error("A persisted Pi session needs a valid sessionId.");
|
|
212
|
+
const db = await openNodeSqliteDatabase(path.join(home, "agent/.pi/sessions", id + ".sqlite"));
|
|
213
|
+
try {
|
|
214
|
+
await db.exec("PRAGMA journal_mode = DELETE");
|
|
215
|
+
} catch (error) {
|
|
216
|
+
await db.close();
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
return SqliteStorage.open(db);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// src/turn-protocol.ts
|
|
223
|
+
var TURN_PROTOCOL_VERSION = 6;
|
|
224
|
+
var STARTUP_ENV_KEYS = "NECKBEARD_STARTUP_ENV_KEYS";
|
|
225
|
+
var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
|
|
226
|
+
function isRecord(value) {
|
|
227
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/serialized-error.ts
|
|
231
|
+
function serializeError(error) {
|
|
232
|
+
if (error instanceof Error) {
|
|
233
|
+
return {
|
|
234
|
+
name: error.name,
|
|
235
|
+
message: error.message,
|
|
236
|
+
...error.stack === void 0 ? {} : { stack: error.stack }
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
return { message: String(error) };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// src/sensitive-value-redactor.ts
|
|
243
|
+
var DEFAULT_MINIMUM_CAPTURE_LENGTH = 8;
|
|
244
|
+
var DEFAULT_CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;
|
|
245
|
+
function defaultEnvironmentValueIsSensitive(name, value) {
|
|
246
|
+
return value.length >= DEFAULT_MINIMUM_CAPTURE_LENGTH && DEFAULT_CREDENTIAL_ENV_NAME_PATTERN.test(name);
|
|
247
|
+
}
|
|
248
|
+
var SensitiveValueRedactor = class {
|
|
249
|
+
secrets = /* @__PURE__ */ new Set();
|
|
250
|
+
minimumCaptureLength;
|
|
251
|
+
environment;
|
|
252
|
+
isEnvironmentValueSensitive;
|
|
253
|
+
constructor(values = [], options = {}) {
|
|
254
|
+
this.minimumCaptureLength = options.minimumCaptureLength ?? DEFAULT_MINIMUM_CAPTURE_LENGTH;
|
|
255
|
+
const environment = options.environment;
|
|
256
|
+
this.environment = typeof environment === "function" ? environment : () => environment ?? process.env;
|
|
257
|
+
this.isEnvironmentValueSensitive = options.isEnvironmentValueSensitive ?? defaultEnvironmentValueIsSensitive;
|
|
258
|
+
this.captureAll(values);
|
|
259
|
+
}
|
|
260
|
+
capture(value) {
|
|
261
|
+
if (value) this.secrets.add(value);
|
|
262
|
+
}
|
|
263
|
+
captureAll(values) {
|
|
264
|
+
for (const value of values) {
|
|
265
|
+
if (value.length >= this.minimumCaptureLength) this.capture(value);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
redact(value, replacement = "[REDACTED]") {
|
|
269
|
+
const environmentSecrets = Object.entries(this.environment()).filter(
|
|
270
|
+
(entry) => Boolean(entry[1]) && this.isEnvironmentValueSensitive(entry[0], entry[1])
|
|
271
|
+
).map(([, secret]) => secret);
|
|
272
|
+
const orderedSecrets = [.../* @__PURE__ */ new Set([...this.secrets, ...environmentSecrets])].sort(
|
|
273
|
+
(left, right) => {
|
|
274
|
+
const lengthDifference = right.length - left.length;
|
|
275
|
+
if (lengthDifference !== 0) return lengthDifference;
|
|
276
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
277
|
+
}
|
|
278
|
+
);
|
|
279
|
+
let redacted = value;
|
|
280
|
+
for (const secret of orderedSecrets) {
|
|
281
|
+
redacted = redacted.split(secret).join(replacement);
|
|
282
|
+
}
|
|
283
|
+
return redacted;
|
|
284
|
+
}
|
|
285
|
+
serialize(error) {
|
|
286
|
+
const serialized = serializeError(error);
|
|
287
|
+
return {
|
|
288
|
+
...serialized.name === void 0 ? {} : { name: this.redact(serialized.name) },
|
|
289
|
+
message: this.redact(serialized.message),
|
|
290
|
+
...serialized.stack === void 0 ? {} : { stack: this.redact(serialized.stack) }
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
function conversationDiagnosticRedactor() {
|
|
295
|
+
let keys;
|
|
296
|
+
try {
|
|
297
|
+
keys = JSON.parse(process.env[STARTUP_ENV_KEYS] ?? "[]");
|
|
298
|
+
} catch {
|
|
299
|
+
throw new Error("Invalid sandbox startup environment key list.");
|
|
300
|
+
}
|
|
301
|
+
if (!Array.isArray(keys) || !keys.every((key) => typeof key === "string")) {
|
|
302
|
+
throw new Error("Invalid sandbox startup environment key list.");
|
|
303
|
+
}
|
|
304
|
+
const provided = new Set(keys);
|
|
305
|
+
const redactor = new SensitiveValueRedactor([], {
|
|
306
|
+
isEnvironmentValueSensitive: (name) => provided.has(name) || /secret|token|cookie|password|api_key|credential|private_key/i.test(name)
|
|
307
|
+
});
|
|
308
|
+
return (text) => redactor.redact(text, "[redacted]");
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// src/conversation-server.ts
|
|
312
|
+
import { once } from "events";
|
|
313
|
+
import { randomUUID } from "crypto";
|
|
314
|
+
import { createServer } from "http";
|
|
315
|
+
import { BACKGROUND_CONTEXT as BACKGROUND_CONTEXT2, withAbortSignal } from "@earendil-works/chord/context";
|
|
316
|
+
import { ConversationBusy, ConversationIdle } from "@earendil-works/pi-durable";
|
|
317
|
+
|
|
318
|
+
// src/sse-framing.ts
|
|
319
|
+
function encodeSseFrame(payload) {
|
|
320
|
+
return `data: ${JSON.stringify(payload)}
|
|
321
|
+
|
|
322
|
+
`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// src/conversation-server.ts
|
|
326
|
+
var InvalidRequest = class extends Error {
|
|
327
|
+
};
|
|
328
|
+
async function body(req) {
|
|
329
|
+
let size = 0;
|
|
330
|
+
const chunks = [];
|
|
331
|
+
for await (const chunk of req) {
|
|
332
|
+
size += chunk.length;
|
|
333
|
+
if (size > MAX_TURN_REQUEST_BYTES) throw new InvalidRequest("Request too large.");
|
|
334
|
+
chunks.push(chunk);
|
|
335
|
+
}
|
|
336
|
+
let data;
|
|
337
|
+
try {
|
|
338
|
+
data = JSON.parse(Buffer.concat(chunks).toString());
|
|
339
|
+
} catch {
|
|
340
|
+
throw new InvalidRequest("Expected JSON object.");
|
|
341
|
+
}
|
|
342
|
+
if (!isRecord(data)) throw new InvalidRequest("Expected JSON object.");
|
|
343
|
+
return data;
|
|
344
|
+
}
|
|
345
|
+
function numericId(value) {
|
|
346
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new InvalidRequest("Invalid ID.");
|
|
347
|
+
return value;
|
|
348
|
+
}
|
|
349
|
+
function writeJson(res, status, value) {
|
|
350
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
351
|
+
res.end(JSON.stringify(value ?? null));
|
|
352
|
+
}
|
|
353
|
+
async function serveConversation(open, options = {}) {
|
|
354
|
+
const redact = conversationDiagnosticRedactor();
|
|
355
|
+
let session;
|
|
356
|
+
let closing = false;
|
|
357
|
+
const watches = /* @__PURE__ */ new Map();
|
|
358
|
+
async function handle(req, res) {
|
|
359
|
+
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
360
|
+
if (closing) return writeJson(res, 503, { error: "Runtime closed." });
|
|
361
|
+
const controller = new AbortController();
|
|
362
|
+
res.on("close", () => controller.abort());
|
|
363
|
+
const ctx = withAbortSignal(controller.signal, BACKGROUND_CONTEXT2);
|
|
364
|
+
if (req.method === "GET" && pathname === "/health") {
|
|
365
|
+
const s2 = await session;
|
|
366
|
+
const busy = s2 ? await s2.busy(ctx) : false;
|
|
367
|
+
return writeJson(res, 200, { ok: true, protocolVersion: TURN_PROTOCOL_VERSION, busy, turnId: null });
|
|
368
|
+
}
|
|
369
|
+
if (req.method !== "POST" || !pathname.startsWith("/conversation/"))
|
|
370
|
+
return writeJson(res, 404, { error: "Unknown route." });
|
|
371
|
+
const data = await body(req);
|
|
372
|
+
session ??= open().catch((error) => {
|
|
373
|
+
session = void 0;
|
|
374
|
+
throw error;
|
|
375
|
+
});
|
|
376
|
+
const s = await session;
|
|
377
|
+
const op = pathname.slice("/conversation/".length);
|
|
378
|
+
if (op === "watch") {
|
|
379
|
+
let safeDiagnostic2 = function(value) {
|
|
380
|
+
if (typeof value === "string") return redact(value);
|
|
381
|
+
if (Array.isArray(value)) return value.map(safeDiagnostic2);
|
|
382
|
+
if (isRecord(value))
|
|
383
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [redact(key), safeDiagnostic2(item)]));
|
|
384
|
+
return value;
|
|
385
|
+
}, sendWatch2 = function(key, message) {
|
|
386
|
+
if (message.error instanceof Error) {
|
|
387
|
+
return send(
|
|
388
|
+
{ [key]: { kind: message.kind } },
|
|
389
|
+
{ name: redact(message.error.name), message: redact(message.error.message) }
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
return send({ [key]: "error" in message ? { ...message, error: safeDiagnostic2(message.error) } : message });
|
|
393
|
+
};
|
|
394
|
+
var safeDiagnostic = safeDiagnostic2, sendWatch = sendWatch2;
|
|
395
|
+
const window = {};
|
|
396
|
+
if (data.window !== void 0) {
|
|
397
|
+
if (!isRecord(data.window)) throw new InvalidRequest("Invalid watch window.");
|
|
398
|
+
for (const key of ["min", "max", "from"]) {
|
|
399
|
+
if (data.window[key] !== void 0) Object.assign(window, { [key]: numericId(data.window[key]) });
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const watch = await s.watch(ctx, data.window === void 0 ? durableWatchWindow : window);
|
|
403
|
+
const id = randomUUID();
|
|
404
|
+
let pendingWrite;
|
|
405
|
+
watches.set(id, async () => {
|
|
406
|
+
while (pendingWrite) {
|
|
407
|
+
await pendingWrite;
|
|
408
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
409
|
+
}
|
|
410
|
+
return watch.stop();
|
|
411
|
+
});
|
|
412
|
+
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store" });
|
|
413
|
+
let seq = 0;
|
|
414
|
+
const send = (frame, exception) => res.write(encodeSseFrame({ seq: seq++, frame, exception }));
|
|
415
|
+
send({ opened: id, value: watch.value });
|
|
416
|
+
watch.start(async (call) => {
|
|
417
|
+
if (!sendWatch2("call", call)) {
|
|
418
|
+
pendingWrite = once(res, "drain", { signal: controller.signal });
|
|
419
|
+
try {
|
|
420
|
+
await pendingWrite;
|
|
421
|
+
} finally {
|
|
422
|
+
pendingWrite = void 0;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
const heartbeat = setInterval(() => {
|
|
427
|
+
if (!res.destroyed && !res.writableNeedDrain) res.write(": heartbeat\n\n");
|
|
428
|
+
}, 15e3);
|
|
429
|
+
const end = await watch.closed;
|
|
430
|
+
clearInterval(heartbeat);
|
|
431
|
+
watches.delete(id);
|
|
432
|
+
if (!res.destroyed) {
|
|
433
|
+
sendWatch2("end", end);
|
|
434
|
+
res.end();
|
|
435
|
+
}
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (op === "stop-watch") {
|
|
439
|
+
const watch = typeof data.id === "string" && watches.get(data.id);
|
|
440
|
+
if (!watch) return writeJson(res, 404, { error: "Watch attachment lost." });
|
|
441
|
+
await watch();
|
|
442
|
+
return writeJson(res, 200, null);
|
|
443
|
+
}
|
|
444
|
+
if (op === "submit") {
|
|
445
|
+
const d = data.draft;
|
|
446
|
+
if (!isRecord(d) || d.type !== "input" || typeof d.content !== "string" || !d.requestId || typeof d.requestId !== "string" || d.whenBusy !== void 0 && d.whenBusy !== "reject" && d.whenBusy !== "steer" && d.whenBusy !== "followUp" || d.whenIdle !== void 0 && d.whenIdle !== "reject" || d.onAbort !== void 0 && d.onAbort !== "withdraw" && d.onAbort !== "keep")
|
|
447
|
+
throw new InvalidRequest("Expected a text input with a requestId.");
|
|
448
|
+
if (Object.keys(d).some((k) => !["type", "content", "requestId", "whenBusy", "whenIdle", "onAbort"].includes(k)))
|
|
449
|
+
throw new InvalidRequest("Unsupported remote input field.");
|
|
450
|
+
if (Object.keys(data).some((key) => key !== "draft")) throw new InvalidRequest("Submit accepts only a draft.");
|
|
451
|
+
const id = await s.submit(
|
|
452
|
+
{
|
|
453
|
+
type: "input",
|
|
454
|
+
content: d.content,
|
|
455
|
+
requestId: d.requestId,
|
|
456
|
+
whenBusy: d.whenBusy,
|
|
457
|
+
whenIdle: d.whenIdle,
|
|
458
|
+
onAbort: d.onAbort
|
|
459
|
+
},
|
|
460
|
+
ctx
|
|
461
|
+
);
|
|
462
|
+
return writeJson(res, 200, id);
|
|
463
|
+
}
|
|
464
|
+
if (op === "lookup" && typeof data.requestId === "string")
|
|
465
|
+
return writeJson(res, 200, await s.submissionByRequest(data.requestId, ctx));
|
|
466
|
+
if (op === "entry") return writeJson(res, 200, await s.entry(numericId(data.id), ctx));
|
|
467
|
+
async function poll(operation) {
|
|
468
|
+
const elapsed = AbortSignal.timeout(1e4);
|
|
469
|
+
const polling = withAbortSignal(AbortSignal.any([elapsed, controller.signal]), ctx);
|
|
470
|
+
try {
|
|
471
|
+
return writeJson(res, 200, await operation(polling));
|
|
472
|
+
} catch (error) {
|
|
473
|
+
if (!elapsed.aborted || controller.signal.aborted) throw error;
|
|
474
|
+
return writeJson(res, 202, { pending: true });
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (op === "idle") return poll((context) => s.waitForIdle(context));
|
|
478
|
+
if (op === "abort") {
|
|
479
|
+
if (data.background !== void 0 && typeof data.background !== "boolean")
|
|
480
|
+
throw new InvalidRequest("Invalid background option.");
|
|
481
|
+
return writeJson(res, 200, await s.abort(ctx, { background: data.background }));
|
|
482
|
+
}
|
|
483
|
+
if (op === "stop") return writeJson(res, 200, await s.stopSubmission(numericId(data.id), ctx));
|
|
484
|
+
if (op === "status" || op === "wait" || op === "withdraw") {
|
|
485
|
+
const submission = await s.submission(numericId(data.id), ctx);
|
|
486
|
+
if (!submission) return writeJson(res, 404, { code: "submission_missing", error: "Unknown submission." });
|
|
487
|
+
if (op === "wait") return poll((context) => submission.wait(context));
|
|
488
|
+
return writeJson(res, 200, await (op === "withdraw" ? submission.abort(ctx) : submission.status(ctx)));
|
|
489
|
+
}
|
|
490
|
+
return writeJson(res, 404, { error: "Unknown operation." });
|
|
491
|
+
}
|
|
492
|
+
const server = createServer((req, res) => {
|
|
493
|
+
void handle(req, res).catch((error) => {
|
|
494
|
+
if (res.destroyed) return;
|
|
495
|
+
if (res.headersSent) {
|
|
496
|
+
res.destroy();
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
const name = error instanceof Error ? error.name : "Error";
|
|
500
|
+
const policyRejection = error instanceof ConversationBusy || error instanceof ConversationIdle;
|
|
501
|
+
writeJson(res, error instanceof InvalidRequest ? 400 : policyRejection ? 409 : 500, {
|
|
502
|
+
name: redact(name),
|
|
503
|
+
code: error instanceof InvalidRequest || policyRejection ? "request_rejected" : void 0,
|
|
504
|
+
error: error instanceof Error ? redact(error.message) : "Conversation request failed."
|
|
505
|
+
});
|
|
506
|
+
});
|
|
507
|
+
});
|
|
508
|
+
await new Promise((resolve, reject) => {
|
|
509
|
+
server.once("error", reject);
|
|
510
|
+
server.listen(options.port ?? Number(process.env.NECKBEARD_PORT || 8080), options.host ?? "0.0.0.0", resolve);
|
|
511
|
+
});
|
|
512
|
+
return {
|
|
513
|
+
port: server.address().port,
|
|
514
|
+
async close() {
|
|
515
|
+
closing = true;
|
|
516
|
+
try {
|
|
517
|
+
await new Promise((resolve, reject) => {
|
|
518
|
+
server.close((err) => err ? reject(err) : resolve());
|
|
519
|
+
server.closeAllConnections();
|
|
520
|
+
});
|
|
521
|
+
} finally {
|
|
522
|
+
await (await session)?.close();
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
export {
|
|
528
|
+
openInsideConversation,
|
|
529
|
+
serveConversation
|
|
530
|
+
};
|