orchajs 0.21.0 → 0.23.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/amarsia/analytics.d.ts +21 -0
- package/dist/amarsia/analytics.js +517 -0
- package/dist/amarsia/endpoint.d.ts +1 -0
- package/dist/amarsia/endpoint.js +8 -0
- package/dist/amarsia/sync.js +1 -4
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +102 -0
- package/dist/runtime/agent.js +30 -5
- package/dist/runtime/create-orcha.d.ts +4 -0
- package/dist/runtime/create-orcha.js +20 -2
- package/dist/types.d.ts +78 -0
- package/dist-cjs/amarsia/analytics.js +493 -0
- package/dist-cjs/amarsia/endpoint.js +32 -0
- package/dist-cjs/amarsia/sync.js +2 -5
- package/dist-cjs/errors.js +92 -2
- package/dist-cjs/runtime/agent.js +29 -8
- package/dist-cjs/runtime/create-orcha.js +16 -2
- package/package.json +1 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { AmarsiaTelemetryRunV1, CompiledAgentManifest, SessionStore } from "../types.js";
|
|
2
|
+
export type AmarsiaRunFact = AmarsiaTelemetryRunV1;
|
|
3
|
+
export declare class AmarsiaTelemetryClient {
|
|
4
|
+
#private;
|
|
5
|
+
constructor(options: {
|
|
6
|
+
key: string;
|
|
7
|
+
endpoint?: string;
|
|
8
|
+
});
|
|
9
|
+
enqueue(fact: AmarsiaRunFact): void;
|
|
10
|
+
drain(options?: {
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
}): Promise<void>;
|
|
13
|
+
close(options?: {
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
}): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export declare function withAmarsiaTelemetry(options: {
|
|
18
|
+
store: SessionStore;
|
|
19
|
+
manifest: CompiledAgentManifest;
|
|
20
|
+
client: AmarsiaTelemetryClient;
|
|
21
|
+
}): SessionStore;
|
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
import { resolveAmarsiaEndpoint } from "./endpoint.js";
|
|
2
|
+
const RELEVANT_EVENTS = new Set([
|
|
3
|
+
"run.started",
|
|
4
|
+
"run.completed",
|
|
5
|
+
"run.failed",
|
|
6
|
+
"run.paused",
|
|
7
|
+
"evaluation.completed",
|
|
8
|
+
"evaluation.failed",
|
|
9
|
+
]);
|
|
10
|
+
const MAX_BATCH_RUNS = 100;
|
|
11
|
+
const MAX_KEEPALIVE_BYTES = 48 * 1024;
|
|
12
|
+
const HEARTBEAT_INTERVAL_MS = 30_000;
|
|
13
|
+
export class AmarsiaTelemetryClient {
|
|
14
|
+
#key;
|
|
15
|
+
#baseUrl;
|
|
16
|
+
#queue = new Map();
|
|
17
|
+
#activeRuns = new Map();
|
|
18
|
+
#timer;
|
|
19
|
+
#heartbeatTimer;
|
|
20
|
+
#attempt = 0;
|
|
21
|
+
#flushPromise;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.#key = options.key;
|
|
24
|
+
this.#baseUrl = resolveAmarsiaEndpoint(options.endpoint);
|
|
25
|
+
}
|
|
26
|
+
enqueue(fact) {
|
|
27
|
+
this.#queue.set(fact.event_id, fact);
|
|
28
|
+
if (fact.status === "running") {
|
|
29
|
+
this.#activeRuns.set(fact.event_id, fact);
|
|
30
|
+
this.#scheduleHeartbeat();
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
this.#activeRuns.delete(fact.event_id);
|
|
34
|
+
if (this.#activeRuns.size === 0 && this.#heartbeatTimer) {
|
|
35
|
+
clearTimeout(this.#heartbeatTimer);
|
|
36
|
+
this.#heartbeatTimer = undefined;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (fact.status !== "running") {
|
|
40
|
+
this.#scheduleTerminal();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (this.#queue.size >= 20) {
|
|
44
|
+
void this.#flush();
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
this.#schedule(250);
|
|
48
|
+
}
|
|
49
|
+
#schedule(delay) {
|
|
50
|
+
if (this.#timer)
|
|
51
|
+
return;
|
|
52
|
+
this.#timer = setTimeout(() => {
|
|
53
|
+
this.#timer = undefined;
|
|
54
|
+
void this.#flush();
|
|
55
|
+
}, delay);
|
|
56
|
+
const timer = this.#timer;
|
|
57
|
+
timer.unref?.();
|
|
58
|
+
}
|
|
59
|
+
#scheduleTerminal() {
|
|
60
|
+
if (this.#timer)
|
|
61
|
+
clearTimeout(this.#timer);
|
|
62
|
+
this.#timer = setTimeout(() => {
|
|
63
|
+
this.#timer = undefined;
|
|
64
|
+
void this.#flush();
|
|
65
|
+
}, 0);
|
|
66
|
+
}
|
|
67
|
+
#scheduleHeartbeat() {
|
|
68
|
+
if (this.#heartbeatTimer || this.#activeRuns.size === 0)
|
|
69
|
+
return;
|
|
70
|
+
this.#heartbeatTimer = setTimeout(() => {
|
|
71
|
+
this.#heartbeatTimer = undefined;
|
|
72
|
+
for (const fact of this.#activeRuns.values()) {
|
|
73
|
+
this.#queue.set(fact.event_id, fact);
|
|
74
|
+
}
|
|
75
|
+
void this.#flush();
|
|
76
|
+
this.#scheduleHeartbeat();
|
|
77
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
78
|
+
const timer = this.#heartbeatTimer;
|
|
79
|
+
timer.unref?.();
|
|
80
|
+
}
|
|
81
|
+
async drain(options = {}) {
|
|
82
|
+
const timeoutMs = Math.max(0, options.timeoutMs ?? 2_000);
|
|
83
|
+
const deadline = Date.now() + timeoutMs;
|
|
84
|
+
if (this.#timer) {
|
|
85
|
+
clearTimeout(this.#timer);
|
|
86
|
+
this.#timer = undefined;
|
|
87
|
+
}
|
|
88
|
+
while (this.#queue.size > 0 || this.#flushPromise) {
|
|
89
|
+
const remaining = deadline - Date.now();
|
|
90
|
+
if (remaining <= 0)
|
|
91
|
+
return;
|
|
92
|
+
await Promise.race([
|
|
93
|
+
this.#flush(),
|
|
94
|
+
new Promise((resolve) => setTimeout(resolve, remaining)),
|
|
95
|
+
]);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async close(options = {}) {
|
|
99
|
+
if (this.#heartbeatTimer) {
|
|
100
|
+
clearTimeout(this.#heartbeatTimer);
|
|
101
|
+
this.#heartbeatTimer = undefined;
|
|
102
|
+
}
|
|
103
|
+
this.#activeRuns.clear();
|
|
104
|
+
await this.drain(options);
|
|
105
|
+
}
|
|
106
|
+
async #flush() {
|
|
107
|
+
if (this.#flushPromise)
|
|
108
|
+
return this.#flushPromise;
|
|
109
|
+
if (this.#queue.size === 0)
|
|
110
|
+
return;
|
|
111
|
+
this.#flushPromise = this.#performFlush();
|
|
112
|
+
try {
|
|
113
|
+
await this.#flushPromise;
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
this.#flushPromise = undefined;
|
|
117
|
+
if (this.#queue.size > 0 && !this.#timer) {
|
|
118
|
+
const hasTerminalFact = [...this.#queue.values()].some((fact) => fact.status !== "running");
|
|
119
|
+
if (hasTerminalFact) {
|
|
120
|
+
void this.#flush();
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
this.#schedule(250);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async #performFlush() {
|
|
129
|
+
const batch = takeBatch(this.#queue);
|
|
130
|
+
if (batch.length === 0)
|
|
131
|
+
return;
|
|
132
|
+
const body = JSON.stringify({
|
|
133
|
+
schema_version: 1,
|
|
134
|
+
runs: batch,
|
|
135
|
+
});
|
|
136
|
+
for (const fact of batch)
|
|
137
|
+
this.#queue.delete(fact.event_id);
|
|
138
|
+
try {
|
|
139
|
+
const response = await fetch(`${this.#baseUrl}/v3/project-analytics/runs/batch`, {
|
|
140
|
+
method: "POST",
|
|
141
|
+
headers: {
|
|
142
|
+
"content-type": "application/json",
|
|
143
|
+
"x-amarsia-project-key": this.#key,
|
|
144
|
+
},
|
|
145
|
+
keepalive: utf8ByteLength(body) <= MAX_KEEPALIVE_BYTES,
|
|
146
|
+
body,
|
|
147
|
+
});
|
|
148
|
+
if (!response.ok) {
|
|
149
|
+
throw new Error(`HTTP ${response.status}`);
|
|
150
|
+
}
|
|
151
|
+
this.#attempt = 0;
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
this.#attempt += 1;
|
|
155
|
+
if (this.#attempt <= 6) {
|
|
156
|
+
for (const fact of batch) {
|
|
157
|
+
if (!this.#queue.has(fact.event_id)) {
|
|
158
|
+
this.#queue.set(fact.event_id, fact);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
this.#schedule(Math.min(30_000, 500 * 2 ** this.#attempt));
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
this.#attempt = 0;
|
|
165
|
+
console.warn(`Amarsia telemetry delivery failed after 6 retries; dropping ${batch.length} run update(s).`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
export function withAmarsiaTelemetry(options) {
|
|
171
|
+
const { store, manifest, client } = options;
|
|
172
|
+
const projections = new Map();
|
|
173
|
+
const pending = new Map();
|
|
174
|
+
return {
|
|
175
|
+
read: (sessionId) => store.read(sessionId),
|
|
176
|
+
listSessionIds: () => store.listSessionIds(),
|
|
177
|
+
describeLocation: store.describeLocation?.bind(store),
|
|
178
|
+
subscribe: store.subscribe?.bind(store),
|
|
179
|
+
subscribeAll: store.subscribeAll?.bind(store),
|
|
180
|
+
async append(sessionId, events) {
|
|
181
|
+
await store.append(sessionId, events);
|
|
182
|
+
const runs = relevantRuns(events);
|
|
183
|
+
if (runs.size === 0 &&
|
|
184
|
+
!projections.has(sessionId) &&
|
|
185
|
+
!pending.has(sessionId)) {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const previous = pending.get(sessionId) ?? Promise.resolve();
|
|
189
|
+
const processing = previous
|
|
190
|
+
.then(async () => {
|
|
191
|
+
let projection = projections.get(sessionId);
|
|
192
|
+
if (!projection) {
|
|
193
|
+
projection = createProjection(await store.read(sessionId));
|
|
194
|
+
projections.set(sessionId, projection);
|
|
195
|
+
}
|
|
196
|
+
else {
|
|
197
|
+
appendToProjection(projection, events);
|
|
198
|
+
}
|
|
199
|
+
if (projection.isTest)
|
|
200
|
+
return;
|
|
201
|
+
for (const run of runs) {
|
|
202
|
+
const fact = projectRunFact(manifest, sessionId, run, projection);
|
|
203
|
+
if (fact)
|
|
204
|
+
client.enqueue(fact);
|
|
205
|
+
}
|
|
206
|
+
})
|
|
207
|
+
.catch(() => undefined);
|
|
208
|
+
pending.set(sessionId, processing);
|
|
209
|
+
void processing.finally(() => {
|
|
210
|
+
if (pending.get(sessionId) === processing) {
|
|
211
|
+
pending.delete(sessionId);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
function createProjection(events) {
|
|
218
|
+
const projection = {
|
|
219
|
+
seenSequences: new Set(),
|
|
220
|
+
runs: new Map(),
|
|
221
|
+
isTest: false,
|
|
222
|
+
};
|
|
223
|
+
appendToProjection(projection, events);
|
|
224
|
+
return projection;
|
|
225
|
+
}
|
|
226
|
+
function appendToProjection(projection, events) {
|
|
227
|
+
for (const event of events) {
|
|
228
|
+
if (projection.seenSequences.has(event.sequence))
|
|
229
|
+
continue;
|
|
230
|
+
projection.seenSequences.add(event.sequence);
|
|
231
|
+
if (event.type === "session.created") {
|
|
232
|
+
projection.sessionCreated = event;
|
|
233
|
+
const metadata = asRecord(event.data.metadata);
|
|
234
|
+
projection.isTest = metadata?.orchaTest === true;
|
|
235
|
+
}
|
|
236
|
+
if (typeof event.run !== "number")
|
|
237
|
+
continue;
|
|
238
|
+
const runEvents = projection.runs.get(event.run);
|
|
239
|
+
if (runEvents) {
|
|
240
|
+
runEvents.push(event);
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
projection.runs.set(event.run, [event]);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
function relevantRuns(events) {
|
|
248
|
+
const runs = new Set();
|
|
249
|
+
for (const event of events) {
|
|
250
|
+
if (typeof event.run === "number" && RELEVANT_EVENTS.has(event.type)) {
|
|
251
|
+
runs.add(event.run);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return runs;
|
|
255
|
+
}
|
|
256
|
+
function projectRunFact(manifest, sessionId, run, projection) {
|
|
257
|
+
const runEvents = projection.runs.get(run);
|
|
258
|
+
if (!runEvents)
|
|
259
|
+
return undefined;
|
|
260
|
+
const started = runEvents.find((event) => event.type === "run.started");
|
|
261
|
+
if (!started)
|
|
262
|
+
return undefined;
|
|
263
|
+
const terminal = [...runEvents]
|
|
264
|
+
.reverse()
|
|
265
|
+
.find((event) => ["run.completed", "run.failed", "run.paused"].includes(event.type));
|
|
266
|
+
const lineage = asRecord(projection.sessionCreated?.data.lineage);
|
|
267
|
+
const assistants = runEvents.filter((event) => event.type === "message.created" && event.data.role === "assistant");
|
|
268
|
+
const usage = normalizeUsage(terminal?.data.usage, assistants);
|
|
269
|
+
const completedActions = runEvents.filter((event) => event.type === "action.completed");
|
|
270
|
+
const failedActions = runEvents.filter((event) => event.type === "action.failed");
|
|
271
|
+
const evaluations = runEvents.filter((event) => event.type === "evaluation.completed" ||
|
|
272
|
+
event.type === "evaluation.failed");
|
|
273
|
+
const evaluationMetrics = evaluations.flatMap((event) => Array.isArray(event.data.metrics) ? event.data.metrics : []);
|
|
274
|
+
const error = asRecord(terminal?.data.error);
|
|
275
|
+
const lastAssistant = assistants.at(-1);
|
|
276
|
+
const status = terminal?.type === "run.completed"
|
|
277
|
+
? "completed"
|
|
278
|
+
: terminal?.type === "run.failed"
|
|
279
|
+
? "failed"
|
|
280
|
+
: terminal?.type === "run.paused"
|
|
281
|
+
? "paused"
|
|
282
|
+
: "running";
|
|
283
|
+
return {
|
|
284
|
+
event_id: `${manifest.key}:${sessionId}:${run}`,
|
|
285
|
+
agent_external_id: manifest.key,
|
|
286
|
+
session_id: sessionId,
|
|
287
|
+
run_number: run,
|
|
288
|
+
...(typeof lineage?.parentAgent === "string"
|
|
289
|
+
? { parent_agent_external_id: lineage.parentAgent }
|
|
290
|
+
: {}),
|
|
291
|
+
...(typeof lineage?.parentSessionId === "string"
|
|
292
|
+
? { parent_session_id: lineage.parentSessionId }
|
|
293
|
+
: {}),
|
|
294
|
+
status,
|
|
295
|
+
provider: typeof started.data.provider === "string"
|
|
296
|
+
? started.data.provider
|
|
297
|
+
: manifest.provider,
|
|
298
|
+
model: typeof started.data.model === "string"
|
|
299
|
+
? started.data.model
|
|
300
|
+
: manifest.model,
|
|
301
|
+
...(typeof started.data.region === "string"
|
|
302
|
+
? { region: started.data.region }
|
|
303
|
+
: {}),
|
|
304
|
+
...(typeof started.data.outputType === "string"
|
|
305
|
+
? { output_type: started.data.outputType }
|
|
306
|
+
: {}),
|
|
307
|
+
...(typeof lastAssistant?.data.stopReason === "string"
|
|
308
|
+
? { stop_reason: lastAssistant.data.stopReason }
|
|
309
|
+
: {}),
|
|
310
|
+
started_at: started.timestamp,
|
|
311
|
+
...(terminal ? { ended_at: terminal.timestamp } : {}),
|
|
312
|
+
...(typeof terminal?.data.durationMs === "number"
|
|
313
|
+
? { duration_ms: terminal.data.durationMs }
|
|
314
|
+
: {}),
|
|
315
|
+
model_duration_ms: sumNumber(assistants, "durationMs"),
|
|
316
|
+
action_duration_ms: sumNumber([...completedActions, ...failedActions], "durationMs"),
|
|
317
|
+
...usage,
|
|
318
|
+
user_message_count: runEvents.filter((event) => event.type === "message.created" && event.data.role === "user").length,
|
|
319
|
+
assistant_message_count: assistants.length,
|
|
320
|
+
action_count: runEvents.filter((event) => event.type === "action.requested").length,
|
|
321
|
+
action_success_count: completedActions.length,
|
|
322
|
+
action_failure_count: failedActions.length,
|
|
323
|
+
subagent_count: runEvents.filter((event) => event.type === "subagent.initiated").length,
|
|
324
|
+
actions: projectActionLogs(runEvents),
|
|
325
|
+
evaluation_count: evaluations.length,
|
|
326
|
+
evaluation_pass_count: evaluations.filter((event) => event.type === "evaluation.completed" &&
|
|
327
|
+
event.data.status === "passed").length,
|
|
328
|
+
evaluation_failure_count: evaluations.filter((event) => event.type === "evaluation.completed" &&
|
|
329
|
+
event.data.status === "failed").length,
|
|
330
|
+
evaluation_error_count: evaluations.filter((event) => event.type === "evaluation.failed").length,
|
|
331
|
+
evaluation_metric_count: evaluationMetrics.length,
|
|
332
|
+
evaluation_metric_pass_count: evaluationMetrics.filter((metric) => asRecord(metric)?.passed === true).length,
|
|
333
|
+
evaluations: projectEvaluationLogs(evaluations),
|
|
334
|
+
...(typeof error?.code === "string" ? { error_code: error.code } : {}),
|
|
335
|
+
...(typeof error?.message === "string"
|
|
336
|
+
? { error_message: sanitizeErrorMessage(error.message) }
|
|
337
|
+
: {}),
|
|
338
|
+
...(typeof error?.retryable === "boolean"
|
|
339
|
+
? { error_retryable: error.retryable }
|
|
340
|
+
: {}),
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
function normalizeUsage(terminalUsage, assistants) {
|
|
344
|
+
const direct = asRecord(terminalUsage);
|
|
345
|
+
if (direct) {
|
|
346
|
+
return usageFields(direct);
|
|
347
|
+
}
|
|
348
|
+
const total = {
|
|
349
|
+
inputTokens: 0,
|
|
350
|
+
outputTokens: 0,
|
|
351
|
+
reasoningTokens: 0,
|
|
352
|
+
cacheReadTokens: 0,
|
|
353
|
+
cacheWriteTokens: 0,
|
|
354
|
+
};
|
|
355
|
+
for (const event of assistants) {
|
|
356
|
+
const usage = asRecord(event.data.usage);
|
|
357
|
+
if (!usage)
|
|
358
|
+
continue;
|
|
359
|
+
total.inputTokens += numberValue(usage.inputTokens);
|
|
360
|
+
total.outputTokens += numberValue(usage.outputTokens);
|
|
361
|
+
total.reasoningTokens =
|
|
362
|
+
(total.reasoningTokens ?? 0) + numberValue(usage.reasoningTokens);
|
|
363
|
+
total.cacheReadTokens += numberValue(usage.cacheReadTokens);
|
|
364
|
+
total.cacheWriteTokens += numberValue(usage.cacheWriteTokens);
|
|
365
|
+
}
|
|
366
|
+
return usageFields(total);
|
|
367
|
+
}
|
|
368
|
+
function usageFields(usage) {
|
|
369
|
+
const reasoning = numberValue(usage.reasoningTokens);
|
|
370
|
+
return {
|
|
371
|
+
input_tokens: numberValue(usage.inputTokens),
|
|
372
|
+
output_tokens: numberValue(usage.outputTokens),
|
|
373
|
+
...(reasoning > 0 ? { reasoning_tokens: reasoning } : {}),
|
|
374
|
+
cache_read_tokens: numberValue(usage.cacheReadTokens),
|
|
375
|
+
cache_write_tokens: numberValue(usage.cacheWriteTokens),
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function sumNumber(events, key) {
|
|
379
|
+
return events.reduce((sum, event) => sum + numberValue(event.data[key]), 0);
|
|
380
|
+
}
|
|
381
|
+
function projectActionLogs(events) {
|
|
382
|
+
const requestedByCallId = new Map();
|
|
383
|
+
for (const event of events) {
|
|
384
|
+
if (event.type === "action.requested" &&
|
|
385
|
+
typeof event.data.callId === "string") {
|
|
386
|
+
requestedByCallId.set(event.data.callId, event);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return events
|
|
390
|
+
.filter((event) => event.type === "action.completed" || event.type === "action.failed")
|
|
391
|
+
.slice(0, 100)
|
|
392
|
+
.map((event) => {
|
|
393
|
+
const error = asRecord(event.data.error);
|
|
394
|
+
const requested = typeof event.data.callId === "string"
|
|
395
|
+
? requestedByCallId.get(event.data.callId)
|
|
396
|
+
: undefined;
|
|
397
|
+
return {
|
|
398
|
+
call_id: typeof event.data.callId === "string"
|
|
399
|
+
? event.data.callId
|
|
400
|
+
: `action-${event.sequence}`,
|
|
401
|
+
name: typeof event.data.name === "string" ? event.data.name : "unknown",
|
|
402
|
+
status: event.type === "action.completed"
|
|
403
|
+
? "completed"
|
|
404
|
+
: "failed",
|
|
405
|
+
started_at: requested?.timestamp ?? event.timestamp,
|
|
406
|
+
ended_at: event.timestamp,
|
|
407
|
+
duration_ms: numberValue(event.data.durationMs),
|
|
408
|
+
...(typeof error?.code === "string" ? { error_code: error.code } : {}),
|
|
409
|
+
...(typeof error?.message === "string"
|
|
410
|
+
? { error_message: sanitizeErrorMessage(error.message) }
|
|
411
|
+
: {}),
|
|
412
|
+
};
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
function projectEvaluationLogs(events) {
|
|
416
|
+
return events.slice(0, 50).map((event) => {
|
|
417
|
+
const usage = asRecord(event.data.usage);
|
|
418
|
+
const error = asRecord(event.data.error);
|
|
419
|
+
const metrics = Array.isArray(event.data.metrics)
|
|
420
|
+
? event.data.metrics
|
|
421
|
+
.map(asRecord)
|
|
422
|
+
.filter((metric) => metric !== undefined)
|
|
423
|
+
.slice(0, 50)
|
|
424
|
+
.map((metric) => ({
|
|
425
|
+
name: typeof metric.name === "string" ? metric.name : "unknown_metric",
|
|
426
|
+
score: numberValue(metric.score),
|
|
427
|
+
threshold: numberValue(metric.threshold),
|
|
428
|
+
passed: metric.passed === true,
|
|
429
|
+
reasoning: typeof metric.reasoning === "string"
|
|
430
|
+
? sanitizeErrorMessage(metric.reasoning)
|
|
431
|
+
: "",
|
|
432
|
+
evidence: Array.isArray(metric.evidence)
|
|
433
|
+
? metric.evidence
|
|
434
|
+
.filter((item) => typeof item === "string")
|
|
435
|
+
.slice(0, 20)
|
|
436
|
+
.map(sanitizeErrorMessage)
|
|
437
|
+
: [],
|
|
438
|
+
}))
|
|
439
|
+
: [];
|
|
440
|
+
return {
|
|
441
|
+
name: typeof event.data.name === "string"
|
|
442
|
+
? event.data.name
|
|
443
|
+
: "unknown_evaluation",
|
|
444
|
+
status: event.type === "evaluation.failed"
|
|
445
|
+
? "error"
|
|
446
|
+
: event.data.status === "passed"
|
|
447
|
+
? "passed"
|
|
448
|
+
: "failed",
|
|
449
|
+
...(typeof event.data.provider === "string"
|
|
450
|
+
? { provider: event.data.provider }
|
|
451
|
+
: {}),
|
|
452
|
+
...(typeof event.data.model === "string"
|
|
453
|
+
? { model: event.data.model }
|
|
454
|
+
: {}),
|
|
455
|
+
duration_ms: numberValue(event.data.durationMs),
|
|
456
|
+
input_tokens: numberValue(usage?.inputTokens),
|
|
457
|
+
output_tokens: numberValue(usage?.outputTokens),
|
|
458
|
+
reasoning_tokens: numberValue(usage?.reasoningTokens),
|
|
459
|
+
cache_read_tokens: numberValue(usage?.cacheReadTokens),
|
|
460
|
+
cache_write_tokens: numberValue(usage?.cacheWriteTokens),
|
|
461
|
+
metrics,
|
|
462
|
+
...(typeof error?.message === "string"
|
|
463
|
+
? { error_message: sanitizeErrorMessage(error.message) }
|
|
464
|
+
: {}),
|
|
465
|
+
};
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
function takeBatch(queue) {
|
|
469
|
+
const batch = [];
|
|
470
|
+
let bytes = utf8ByteLength('{"schema_version":1,"runs":[]}');
|
|
471
|
+
for (const fact of queue.values()) {
|
|
472
|
+
const factBytes = utf8ByteLength(JSON.stringify(fact)) + 1;
|
|
473
|
+
if (batch.length > 0 &&
|
|
474
|
+
(batch.length >= MAX_BATCH_RUNS ||
|
|
475
|
+
bytes + factBytes > MAX_KEEPALIVE_BYTES)) {
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
batch.push(fact);
|
|
479
|
+
bytes += factBytes;
|
|
480
|
+
}
|
|
481
|
+
return batch;
|
|
482
|
+
}
|
|
483
|
+
function utf8ByteLength(value) {
|
|
484
|
+
if (typeof TextEncoder !== "undefined") {
|
|
485
|
+
return new TextEncoder().encode(value).byteLength;
|
|
486
|
+
}
|
|
487
|
+
let bytes = 0;
|
|
488
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
489
|
+
const code = value.charCodeAt(index);
|
|
490
|
+
if (code < 0x80)
|
|
491
|
+
bytes += 1;
|
|
492
|
+
else if (code < 0x800)
|
|
493
|
+
bytes += 2;
|
|
494
|
+
else if (code >= 0xd800 && code <= 0xdbff) {
|
|
495
|
+
bytes += 4;
|
|
496
|
+
index += 1;
|
|
497
|
+
}
|
|
498
|
+
else
|
|
499
|
+
bytes += 3;
|
|
500
|
+
}
|
|
501
|
+
return bytes;
|
|
502
|
+
}
|
|
503
|
+
function numberValue(value) {
|
|
504
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
505
|
+
}
|
|
506
|
+
function asRecord(value) {
|
|
507
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
508
|
+
? value
|
|
509
|
+
: undefined;
|
|
510
|
+
}
|
|
511
|
+
function sanitizeErrorMessage(value) {
|
|
512
|
+
return value
|
|
513
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, "Bearer [redacted]")
|
|
514
|
+
.replace(/\b(authorization|api[-_ ]?key|token|secret|password)\b\s*[:=]\s*[^\s,;]+/gi, "$1=[redacted]")
|
|
515
|
+
.replace(/\b(?:sk|pk|amarsia)_[A-Za-z0-9_-]{12,}\b/gi, "[redacted]")
|
|
516
|
+
.slice(0, 8000);
|
|
517
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function resolveAmarsiaEndpoint(endpoint: string | undefined): string;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
const DEFAULT_AMARSIA_API_URL = "https://api.amarsia.com";
|
|
2
|
+
export function resolveAmarsiaEndpoint(endpoint) {
|
|
3
|
+
return (endpoint?.trim() ||
|
|
4
|
+
(typeof process !== "undefined"
|
|
5
|
+
? process.env?.AMARSIA_API_URL
|
|
6
|
+
: undefined) ||
|
|
7
|
+
DEFAULT_AMARSIA_API_URL).replace(/\/$/, "");
|
|
8
|
+
}
|
package/dist/amarsia/sync.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createAmarsiaProjectMetadata, } from "./metadata.js";
|
|
2
|
-
|
|
2
|
+
import { resolveAmarsiaEndpoint } from "./endpoint.js";
|
|
3
3
|
const syncedHashes = new Map();
|
|
4
4
|
export function syncAmarsiaProject(options) {
|
|
5
5
|
const metadata = createAmarsiaProjectMetadata(options.bundle, options.projectRoot);
|
|
@@ -19,9 +19,6 @@ export function syncAmarsiaProject(options) {
|
|
|
19
19
|
console.warn(`[orcha] Amarsia project sync failed: ${message}`);
|
|
20
20
|
});
|
|
21
21
|
}
|
|
22
|
-
function resolveAmarsiaEndpoint(endpoint) {
|
|
23
|
-
return (endpoint?.trim() || process.env.AMARSIA_API_URL || DEFAULT_AMARSIA_API_URL).replace(/\/$/, "");
|
|
24
|
-
}
|
|
25
22
|
async function postProjectMetadata(options) {
|
|
26
23
|
const response = await fetch(`${options.baseUrl}/v3/project-sync`, {
|
|
27
24
|
method: "PUT",
|
package/dist/errors.d.ts
CHANGED
|
@@ -9,3 +9,8 @@ export declare class OrchaError extends Error {
|
|
|
9
9
|
cause?: unknown;
|
|
10
10
|
});
|
|
11
11
|
}
|
|
12
|
+
export declare function describeProviderError(error: unknown): {
|
|
13
|
+
message: string;
|
|
14
|
+
details?: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
export declare function isRetryableProviderConnectionError(error: unknown): boolean;
|
package/dist/errors.js
CHANGED
|
@@ -10,3 +10,105 @@ export class OrchaError extends Error {
|
|
|
10
10
|
this.details = options.details;
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
+
export function describeProviderError(error) {
|
|
14
|
+
const rootMessage = errorMessage(error);
|
|
15
|
+
const cause = deepestUsefulCause(error);
|
|
16
|
+
if (!cause) {
|
|
17
|
+
return { message: rootMessage };
|
|
18
|
+
}
|
|
19
|
+
const causeMessage = errorMessage(cause);
|
|
20
|
+
const causeCode = stringOrNumberField(cause, "code");
|
|
21
|
+
const syscall = stringField(cause, "syscall");
|
|
22
|
+
const hostname = stringField(cause, "hostname");
|
|
23
|
+
const explanation = causeMessage !== rootMessage
|
|
24
|
+
? causeMessage
|
|
25
|
+
: causeCode
|
|
26
|
+
? String(causeCode)
|
|
27
|
+
: undefined;
|
|
28
|
+
const details = {
|
|
29
|
+
...(causeCode !== undefined ? { causeCode } : {}),
|
|
30
|
+
...(syscall ? { syscall } : {}),
|
|
31
|
+
...(hostname ? { hostname } : {}),
|
|
32
|
+
...(explanation ? { causeMessage: explanation } : {}),
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
message: explanation ? `${rootMessage}: ${explanation}` : rootMessage,
|
|
36
|
+
...(Object.keys(details).length > 0 ? { details } : {}),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export function isRetryableProviderConnectionError(error) {
|
|
40
|
+
const retryableCodes = new Set([
|
|
41
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
42
|
+
"EAI_AGAIN",
|
|
43
|
+
"ENETUNREACH",
|
|
44
|
+
"EHOSTUNREACH",
|
|
45
|
+
"ECONNREFUSED",
|
|
46
|
+
]);
|
|
47
|
+
const pending = [error];
|
|
48
|
+
const visited = new Set();
|
|
49
|
+
while (pending.length > 0 && visited.size < 8) {
|
|
50
|
+
const current = pending.shift();
|
|
51
|
+
if (typeof current !== "object" ||
|
|
52
|
+
current === null ||
|
|
53
|
+
visited.has(current)) {
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
visited.add(current);
|
|
57
|
+
const record = current;
|
|
58
|
+
if (typeof record.code === "string" &&
|
|
59
|
+
retryableCodes.has(record.code)) {
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
if (record.cause !== undefined)
|
|
63
|
+
pending.push(record.cause);
|
|
64
|
+
if (Array.isArray(record.errors))
|
|
65
|
+
pending.push(...record.errors);
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
function deepestUsefulCause(error) {
|
|
70
|
+
let current = error;
|
|
71
|
+
let useful;
|
|
72
|
+
const visited = new Set();
|
|
73
|
+
for (let depth = 0; depth < 5; depth += 1) {
|
|
74
|
+
if ((typeof current !== "object" || current === null) ||
|
|
75
|
+
visited.has(current)) {
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
visited.add(current);
|
|
79
|
+
const record = current;
|
|
80
|
+
const next = record.cause ??
|
|
81
|
+
(Array.isArray(record.errors) ? record.errors[0] : undefined);
|
|
82
|
+
if (next === undefined)
|
|
83
|
+
break;
|
|
84
|
+
useful = next;
|
|
85
|
+
current = next;
|
|
86
|
+
}
|
|
87
|
+
return useful;
|
|
88
|
+
}
|
|
89
|
+
function errorMessage(error) {
|
|
90
|
+
if (error instanceof Error && error.message.trim()) {
|
|
91
|
+
return error.message.trim();
|
|
92
|
+
}
|
|
93
|
+
if (typeof error === "object" && error !== null) {
|
|
94
|
+
const message = error.message;
|
|
95
|
+
if (typeof message === "string" && message.trim()) {
|
|
96
|
+
return message.trim();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return String(error);
|
|
100
|
+
}
|
|
101
|
+
function stringField(value, key) {
|
|
102
|
+
if (typeof value !== "object" || value === null)
|
|
103
|
+
return undefined;
|
|
104
|
+
const field = value[key];
|
|
105
|
+
return typeof field === "string" && field.trim() ? field : undefined;
|
|
106
|
+
}
|
|
107
|
+
function stringOrNumberField(value, key) {
|
|
108
|
+
if (typeof value !== "object" || value === null)
|
|
109
|
+
return undefined;
|
|
110
|
+
const field = value[key];
|
|
111
|
+
return typeof field === "string" || typeof field === "number"
|
|
112
|
+
? field
|
|
113
|
+
: undefined;
|
|
114
|
+
}
|