@abelxiaoxing/cadence 2.0.44 → 2.0.45
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/docs/conversation-mode.md +12 -3
- package/package.json +2 -1
- package/src/model-preview.mjs +3180 -0
- package/src/native-build.ts +1 -1
- package/src/service/contracts/models.ts +23 -12
- package/src/service-cli.mjs +15 -4
- package/src/service-host.mjs +493 -220
- package/web/dist/assets/cadence.js +18 -18
- package/web/dist/manifest.json +5 -5
|
@@ -0,0 +1,3180 @@
|
|
|
1
|
+
// Generated by scripts/build-service.mjs; edit the entry and source modules.
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
4
|
+
|
|
5
|
+
// src/service/model-config.ts
|
|
6
|
+
import { lstatSync as lstatSync3, realpathSync as realpathSync2 } from "node:fs";
|
|
7
|
+
import { dirname as dirname3, isAbsolute as isAbsolute3, join as join3, resolve as resolve3 } from "node:path";
|
|
8
|
+
|
|
9
|
+
// src/worker-public.mjs
|
|
10
|
+
var WORKER_PROTOCOL = 2;
|
|
11
|
+
var LIMITS = Object.freeze({
|
|
12
|
+
controlBytes: 1024 * 1024,
|
|
13
|
+
admissionCount: 16,
|
|
14
|
+
admissionBytes: 32 * 1024 * 1024,
|
|
15
|
+
cancelBytes: 64 * 1024,
|
|
16
|
+
headerBytes: 8 * 1024,
|
|
17
|
+
wsClientFrameBytes: 16 * 1024,
|
|
18
|
+
startWaitMs: 1e4,
|
|
19
|
+
stopWaitMs: 60000,
|
|
20
|
+
authWaitMs: 30000,
|
|
21
|
+
authValidityMarginMs: 120000,
|
|
22
|
+
browserLifetimeMs: 12 * 60 * 60 * 1000,
|
|
23
|
+
terminateGraceMs: 1000,
|
|
24
|
+
unconfirmedStopMs: 3000,
|
|
25
|
+
graphBytes: 512 * 1024,
|
|
26
|
+
grantMs: 120000,
|
|
27
|
+
assignments: 16,
|
|
28
|
+
instructionsBytes: 16 * 1024,
|
|
29
|
+
expectedOutputBytes: 2048,
|
|
30
|
+
workerRequestBytes: 128 * 1024,
|
|
31
|
+
publicRequestBytes: 96 * 1024,
|
|
32
|
+
predecessorBytes: 16 * 1024,
|
|
33
|
+
handoffBytes: 32 * 1024,
|
|
34
|
+
frameBytes: 64 * 1024,
|
|
35
|
+
chunkBytes: 8 * 1024,
|
|
36
|
+
detailBytes: 32 * 1024 * 1024,
|
|
37
|
+
childProtocolBytes: 128 * 1024 * 1024,
|
|
38
|
+
dataFrames: 1e5,
|
|
39
|
+
controlFrames: 256,
|
|
40
|
+
sdkEvents: 1e6,
|
|
41
|
+
workerQueueBytes: 4 * 1024 * 1024,
|
|
42
|
+
workerQueueFrames: 1024,
|
|
43
|
+
ownerQueueBytes: 8 * 1024 * 1024,
|
|
44
|
+
ownerQueueFrames: 2048,
|
|
45
|
+
ownerControlBytes: 1024 * 1024,
|
|
46
|
+
ownerControlFrames: 256,
|
|
47
|
+
recordingStallMs: 5000,
|
|
48
|
+
episodes: 8,
|
|
49
|
+
queuedAssignments: 128,
|
|
50
|
+
childReservations: 2,
|
|
51
|
+
episodeMs: 6 * 60 * 60 * 1000,
|
|
52
|
+
readyWaitMs: 10 * 60 * 1000,
|
|
53
|
+
workerMs: 1200000,
|
|
54
|
+
artifactPartBytes: 256 * 1024,
|
|
55
|
+
progressBatchMs: 100,
|
|
56
|
+
progressBatchBytes: 256 * 1024,
|
|
57
|
+
segmentBytes: 8 * 1024 * 1024,
|
|
58
|
+
segmentRecords: 4096,
|
|
59
|
+
checkoutQuotaBytes: 10 * 1024 * 1024 * 1024,
|
|
60
|
+
episodeReservationBytes: 512 * 1024 * 1024,
|
|
61
|
+
freeSpaceFloorBytes: 256 * 1024 * 1024,
|
|
62
|
+
episodeControlBytes: 1024 * 1024,
|
|
63
|
+
searchReaders: 2,
|
|
64
|
+
exportReaders: 2,
|
|
65
|
+
downloadIdleMs: 120000,
|
|
66
|
+
pageEntries: 50,
|
|
67
|
+
maxPageEntries: 200,
|
|
68
|
+
pageBytes: 512 * 1024,
|
|
69
|
+
detailPageBytes: 256 * 1024,
|
|
70
|
+
previewBytes: 4096,
|
|
71
|
+
searchBytes: 8 * 1024 * 1024,
|
|
72
|
+
searchMs: 100,
|
|
73
|
+
queryBytes: 1024,
|
|
74
|
+
navigationBytes: 8192,
|
|
75
|
+
ringEvents: 1024,
|
|
76
|
+
ringBytes: 2 * 1024 * 1024,
|
|
77
|
+
viewers: 16,
|
|
78
|
+
viewerMessages: 256,
|
|
79
|
+
viewerBytes: 1024 * 1024,
|
|
80
|
+
heartbeatMs: 5000,
|
|
81
|
+
staleMs: 15000,
|
|
82
|
+
reconcileMs: 30000
|
|
83
|
+
});
|
|
84
|
+
var ERROR_CODES = [
|
|
85
|
+
"invalid",
|
|
86
|
+
"oversize",
|
|
87
|
+
"unauthenticated",
|
|
88
|
+
"forbidden",
|
|
89
|
+
"stale",
|
|
90
|
+
"conflict",
|
|
91
|
+
"corrupt-selected",
|
|
92
|
+
"expired-grant",
|
|
93
|
+
"consumed-grant",
|
|
94
|
+
"unsupported-context",
|
|
95
|
+
"retired-conversation",
|
|
96
|
+
"quarantine",
|
|
97
|
+
"capacity",
|
|
98
|
+
"unavailable",
|
|
99
|
+
"registry-locked",
|
|
100
|
+
"auth-unavailable",
|
|
101
|
+
"recording-exhausted",
|
|
102
|
+
"receipt-inconclusive"
|
|
103
|
+
];
|
|
104
|
+
|
|
105
|
+
class ContractError extends Error {
|
|
106
|
+
code;
|
|
107
|
+
constructor(code = "invalid") {
|
|
108
|
+
super(code);
|
|
109
|
+
this.code = code;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function publicError(code, effect = "none") {
|
|
113
|
+
return {
|
|
114
|
+
code,
|
|
115
|
+
effect,
|
|
116
|
+
recovery: effect !== "none" || code === "receipt-inconclusive" ? "observe" : ["stale", "expired-grant", "consumed-grant"].includes(code) ? "fresh-confirmation" : "operator"
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function invalid() {
|
|
120
|
+
throw new ContractError;
|
|
121
|
+
}
|
|
122
|
+
function text(v, max, nonempty = false) {
|
|
123
|
+
if (typeof v !== "string" || v.includes("\x00") || /[\uD800-\uDFFF]/u.test(v) || nonempty && !v.trim())
|
|
124
|
+
invalid();
|
|
125
|
+
if (utf8Bytes(v) > max)
|
|
126
|
+
throw new ContractError("oversize");
|
|
127
|
+
return v;
|
|
128
|
+
}
|
|
129
|
+
function utf8Bytes(v) {
|
|
130
|
+
return new TextEncoder().encode(v).length;
|
|
131
|
+
}
|
|
132
|
+
function integer(v, min = 0, max = Number.MAX_SAFE_INTEGER) {
|
|
133
|
+
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < min || v > max)
|
|
134
|
+
invalid();
|
|
135
|
+
return v;
|
|
136
|
+
}
|
|
137
|
+
function bool(v) {
|
|
138
|
+
if (typeof v !== "boolean")
|
|
139
|
+
invalid();
|
|
140
|
+
return v;
|
|
141
|
+
}
|
|
142
|
+
function oneOf(v, values) {
|
|
143
|
+
if (typeof v !== "string" || !values.includes(v))
|
|
144
|
+
invalid();
|
|
145
|
+
return v;
|
|
146
|
+
}
|
|
147
|
+
function literal(v, expected) {
|
|
148
|
+
if (v !== expected)
|
|
149
|
+
invalid();
|
|
150
|
+
return expected;
|
|
151
|
+
}
|
|
152
|
+
function nullable(v, read) {
|
|
153
|
+
return v === null ? null : read(v);
|
|
154
|
+
}
|
|
155
|
+
function closed(v, keys) {
|
|
156
|
+
if (v === null || typeof v !== "object" || Array.isArray(v) || ![null, Object.prototype].includes(Object.getPrototypeOf(v)))
|
|
157
|
+
invalid();
|
|
158
|
+
const names = Reflect.ownKeys(v);
|
|
159
|
+
if (names.length !== keys.length || names.some((k) => typeof k !== "string" || !keys.includes(k)))
|
|
160
|
+
invalid();
|
|
161
|
+
const out = Object.create(null);
|
|
162
|
+
for (const k of keys) {
|
|
163
|
+
const d = Object.getOwnPropertyDescriptor(v, k);
|
|
164
|
+
if (!d || !("value" in d) || !d.enumerable)
|
|
165
|
+
invalid();
|
|
166
|
+
out[k] = d.value;
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
function list(v, max, read) {
|
|
171
|
+
if (!Array.isArray(v) || v.length > max || Reflect.ownKeys(v).length !== v.length + 1)
|
|
172
|
+
invalid();
|
|
173
|
+
const out = [];
|
|
174
|
+
for (let i = 0;i < v.length; i++) {
|
|
175
|
+
const d = Object.getOwnPropertyDescriptor(v, String(i));
|
|
176
|
+
if (!d || !("value" in d))
|
|
177
|
+
invalid();
|
|
178
|
+
out.push(read(d.value));
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
function decodeId(v) {
|
|
183
|
+
const s = text(v, 36);
|
|
184
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s))
|
|
185
|
+
invalid();
|
|
186
|
+
return s;
|
|
187
|
+
}
|
|
188
|
+
function decodeHash(v) {
|
|
189
|
+
const s = text(v, 64);
|
|
190
|
+
if (!/^[0-9a-f]{64}$/.test(s))
|
|
191
|
+
invalid();
|
|
192
|
+
return s;
|
|
193
|
+
}
|
|
194
|
+
function decodeSequence(v) {
|
|
195
|
+
const s = text(v, LIMITS.controlBytes);
|
|
196
|
+
if (!/^(0|[1-9][0-9]*)$/.test(s))
|
|
197
|
+
invalid();
|
|
198
|
+
return s;
|
|
199
|
+
}
|
|
200
|
+
function compareSequence(a, b) {
|
|
201
|
+
decodeSequence(a);
|
|
202
|
+
decodeSequence(b);
|
|
203
|
+
return a.length === b.length ? a === b ? 0 : a < b ? -1 : 1 : a.length < b.length ? -1 : 1;
|
|
204
|
+
}
|
|
205
|
+
function assignmentId(v) {
|
|
206
|
+
const s = text(v, 48);
|
|
207
|
+
if (!/^[a-z][a-z0-9-]{0,47}$/.test(s))
|
|
208
|
+
invalid();
|
|
209
|
+
return s;
|
|
210
|
+
}
|
|
211
|
+
function canonicalJson(value, maximum = LIMITS.controlBytes) {
|
|
212
|
+
let remaining = maximum;
|
|
213
|
+
const charge = (s) => {
|
|
214
|
+
remaining -= utf8Bytes(s);
|
|
215
|
+
if (remaining < 0)
|
|
216
|
+
throw new ContractError("oversize");
|
|
217
|
+
return s;
|
|
218
|
+
};
|
|
219
|
+
function visit(v, depth) {
|
|
220
|
+
if (depth > 64)
|
|
221
|
+
invalid();
|
|
222
|
+
if (v === null || typeof v === "boolean")
|
|
223
|
+
return charge(String(v));
|
|
224
|
+
if (typeof v === "string") {
|
|
225
|
+
text(v, maximum);
|
|
226
|
+
return charge(JSON.stringify(v));
|
|
227
|
+
}
|
|
228
|
+
if (typeof v === "number") {
|
|
229
|
+
if (!Number.isFinite(v))
|
|
230
|
+
invalid();
|
|
231
|
+
return charge(JSON.stringify(v));
|
|
232
|
+
}
|
|
233
|
+
if (Array.isArray(v)) {
|
|
234
|
+
const items = list(v, maximum, (x) => x);
|
|
235
|
+
charge(`[]${",".repeat(Math.max(0, items.length - 1))}`);
|
|
236
|
+
return `[${items.map((x) => visit(x, depth + 1)).join(",")}]`;
|
|
237
|
+
}
|
|
238
|
+
if (v && typeof v === "object") {
|
|
239
|
+
const keys = Reflect.ownKeys(v);
|
|
240
|
+
if (keys.some((k) => typeof k !== "string"))
|
|
241
|
+
invalid();
|
|
242
|
+
const names = keys.sort();
|
|
243
|
+
const o = closed(v, names);
|
|
244
|
+
charge(`{}${",".repeat(Math.max(0, names.length - 1))}`);
|
|
245
|
+
return `{${names.map((k) => `${charge(`${JSON.stringify(k)}:`)}${visit(o[k], depth + 1)}`).join(",")}}`;
|
|
246
|
+
}
|
|
247
|
+
return invalid();
|
|
248
|
+
}
|
|
249
|
+
return visit(value, 0);
|
|
250
|
+
}
|
|
251
|
+
function parseWireJson(source, maximum = LIMITS.controlBytes) {
|
|
252
|
+
text(source, maximum);
|
|
253
|
+
let at = 0;
|
|
254
|
+
const ws = () => {
|
|
255
|
+
while (/[\x20\t\r\n]/.test(source[at] ?? "!"))
|
|
256
|
+
at++;
|
|
257
|
+
};
|
|
258
|
+
function string() {
|
|
259
|
+
const start = at++;
|
|
260
|
+
let escaped = false;
|
|
261
|
+
while (at < source.length) {
|
|
262
|
+
const c = source[at++];
|
|
263
|
+
if (!escaped && c === '"') {
|
|
264
|
+
try {
|
|
265
|
+
const s = JSON.parse(source.slice(start, at));
|
|
266
|
+
return text(s, maximum);
|
|
267
|
+
} catch {
|
|
268
|
+
return invalid();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (!escaped && c === "\\")
|
|
272
|
+
escaped = true;
|
|
273
|
+
else
|
|
274
|
+
escaped = false;
|
|
275
|
+
}
|
|
276
|
+
return invalid();
|
|
277
|
+
}
|
|
278
|
+
function value(depth) {
|
|
279
|
+
if (depth > 64)
|
|
280
|
+
invalid();
|
|
281
|
+
ws();
|
|
282
|
+
if (source[at] === '"')
|
|
283
|
+
return string();
|
|
284
|
+
if (source[at] === "{" || source[at] === "[") {
|
|
285
|
+
const object = source[at++] === "{";
|
|
286
|
+
const end = object ? "}" : "]";
|
|
287
|
+
const out = Object.create(null);
|
|
288
|
+
const arr = [];
|
|
289
|
+
const keys = new Set;
|
|
290
|
+
ws();
|
|
291
|
+
if (source[at] === end) {
|
|
292
|
+
at++;
|
|
293
|
+
return object ? out : arr;
|
|
294
|
+
}
|
|
295
|
+
for (;; ) {
|
|
296
|
+
ws();
|
|
297
|
+
let key = "";
|
|
298
|
+
if (object) {
|
|
299
|
+
if (source[at] !== '"')
|
|
300
|
+
invalid();
|
|
301
|
+
key = string();
|
|
302
|
+
if (keys.has(key))
|
|
303
|
+
invalid();
|
|
304
|
+
keys.add(key);
|
|
305
|
+
ws();
|
|
306
|
+
if (source[at++] !== ":")
|
|
307
|
+
invalid();
|
|
308
|
+
}
|
|
309
|
+
const item = value(depth + 1);
|
|
310
|
+
if (object)
|
|
311
|
+
out[key] = item;
|
|
312
|
+
else
|
|
313
|
+
arr.push(item);
|
|
314
|
+
ws();
|
|
315
|
+
const c = source[at++];
|
|
316
|
+
if (c === end)
|
|
317
|
+
break;
|
|
318
|
+
if (c !== ",")
|
|
319
|
+
invalid();
|
|
320
|
+
}
|
|
321
|
+
return object ? out : arr;
|
|
322
|
+
}
|
|
323
|
+
const token = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(source.slice(at))?.[0];
|
|
324
|
+
if (!token)
|
|
325
|
+
invalid();
|
|
326
|
+
at += token.length;
|
|
327
|
+
const result2 = JSON.parse(token);
|
|
328
|
+
if (typeof result2 === "number" && !Number.isFinite(result2))
|
|
329
|
+
invalid();
|
|
330
|
+
return result2;
|
|
331
|
+
}
|
|
332
|
+
const result = value(0);
|
|
333
|
+
ws();
|
|
334
|
+
if (at !== source.length)
|
|
335
|
+
invalid();
|
|
336
|
+
return result;
|
|
337
|
+
}
|
|
338
|
+
function decodePublicError(v) {
|
|
339
|
+
const o = closed(v, ["code", "effect", "recovery"]);
|
|
340
|
+
return {
|
|
341
|
+
code: oneOf(o.code, ERROR_CODES),
|
|
342
|
+
effect: oneOf(o.effect, ["none", "accepted", "uncertain"]),
|
|
343
|
+
recovery: oneOf(o.recovery, ["observe", "fresh-confirmation", "operator"])
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
var fields = [
|
|
347
|
+
"plan",
|
|
348
|
+
"context",
|
|
349
|
+
"message",
|
|
350
|
+
"final-text",
|
|
351
|
+
"tool-args",
|
|
352
|
+
"tool-update",
|
|
353
|
+
"tool-result",
|
|
354
|
+
"check",
|
|
355
|
+
"changes",
|
|
356
|
+
"review"
|
|
357
|
+
];
|
|
358
|
+
var outcomes = [
|
|
359
|
+
"completed",
|
|
360
|
+
"failed",
|
|
361
|
+
"canceled",
|
|
362
|
+
"timeout",
|
|
363
|
+
"unknown",
|
|
364
|
+
"blocked"
|
|
365
|
+
];
|
|
366
|
+
var closures = ["not-launched", "direct-child-closed", "unconfirmed"];
|
|
367
|
+
var modelApis = [
|
|
368
|
+
"openai-completions",
|
|
369
|
+
"openai-responses",
|
|
370
|
+
"openai-codex-responses",
|
|
371
|
+
"anthropic-messages",
|
|
372
|
+
"google-generative-ai",
|
|
373
|
+
"mistral-conversations",
|
|
374
|
+
"azure-openai-responses"
|
|
375
|
+
];
|
|
376
|
+
var thinkingLevels = [
|
|
377
|
+
"off",
|
|
378
|
+
"minimal",
|
|
379
|
+
"low",
|
|
380
|
+
"medium",
|
|
381
|
+
"high",
|
|
382
|
+
"xhigh",
|
|
383
|
+
"max"
|
|
384
|
+
];
|
|
385
|
+
function decodeModelSelector(v) {
|
|
386
|
+
const o = closed(v, ["provider", "model", "api", "thinking"]);
|
|
387
|
+
return {
|
|
388
|
+
provider: text(o.provider, 128, true),
|
|
389
|
+
model: text(o.model, 256, true),
|
|
390
|
+
api: oneOf(o.api, modelApis),
|
|
391
|
+
thinking: oneOf(o.thinking, thinkingLevels)
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
function decodeModelSelection(v) {
|
|
395
|
+
const o = closed(v, [
|
|
396
|
+
"sourceSelectionId",
|
|
397
|
+
"provider",
|
|
398
|
+
"model",
|
|
399
|
+
"api",
|
|
400
|
+
"thinking"
|
|
401
|
+
]);
|
|
402
|
+
const { sourceSelectionId, ...selector } = o;
|
|
403
|
+
return {
|
|
404
|
+
sourceSelectionId: decodeId(sourceSelectionId),
|
|
405
|
+
...decodeModelSelector(selector)
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
function decodeContentRef(v) {
|
|
409
|
+
const o = closed(v, ["recordId", "version", "field", "bytes", "sha256"]);
|
|
410
|
+
return {
|
|
411
|
+
recordId: decodeId(o.recordId),
|
|
412
|
+
version: integer(o.version, 1),
|
|
413
|
+
field: oneOf(o.field, fields),
|
|
414
|
+
bytes: integer(o.bytes, 0, LIMITS.detailBytes),
|
|
415
|
+
sha256: decodeHash(o.sha256)
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
function range(v) {
|
|
419
|
+
const o = closed(v, ["start", "end"]);
|
|
420
|
+
const start = integer(o.start);
|
|
421
|
+
return { start, end: integer(o.end, start + 1, LIMITS.detailBytes) };
|
|
422
|
+
}
|
|
423
|
+
function tag(v, key = "kind") {
|
|
424
|
+
if (v === null || typeof v !== "object")
|
|
425
|
+
invalid();
|
|
426
|
+
const d = Object.getOwnPropertyDescriptor(v, key);
|
|
427
|
+
if (!d || !("value" in d))
|
|
428
|
+
invalid();
|
|
429
|
+
return text(d.value, 64, true);
|
|
430
|
+
}
|
|
431
|
+
function taskVersion(v) {
|
|
432
|
+
const o = closed(v, [
|
|
433
|
+
"id",
|
|
434
|
+
"kind",
|
|
435
|
+
"revision",
|
|
436
|
+
"identity",
|
|
437
|
+
"graphRevision",
|
|
438
|
+
"graphIdentity"
|
|
439
|
+
]);
|
|
440
|
+
const graphRevision = nullable(o.graphRevision, (v2) => integer(v2, 1));
|
|
441
|
+
const graphIdentity = nullable(o.graphIdentity, decodeHash);
|
|
442
|
+
if (graphRevision === null !== (graphIdentity === null))
|
|
443
|
+
invalid();
|
|
444
|
+
return {
|
|
445
|
+
id: decodeId(o.id),
|
|
446
|
+
kind: oneOf(o.kind, ["code", "research", "diagnosis"]),
|
|
447
|
+
revision: integer(o.revision, 1),
|
|
448
|
+
identity: decodeHash(o.identity),
|
|
449
|
+
graphRevision,
|
|
450
|
+
graphIdentity
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
function decodeContext(v) {
|
|
454
|
+
const o = closed(v, [
|
|
455
|
+
"epoch",
|
|
456
|
+
"accessGeneration",
|
|
457
|
+
"configRev",
|
|
458
|
+
"controlRev",
|
|
459
|
+
"workspaceId",
|
|
460
|
+
"cwdId",
|
|
461
|
+
"model",
|
|
462
|
+
"checkEnvGeneration",
|
|
463
|
+
"checkoutGeneration",
|
|
464
|
+
"observation",
|
|
465
|
+
"task"
|
|
466
|
+
]);
|
|
467
|
+
const obs = closed(o.observation, ["identity", "complete"]);
|
|
468
|
+
return {
|
|
469
|
+
epoch: decodeId(o.epoch),
|
|
470
|
+
accessGeneration: integer(o.accessGeneration, 1),
|
|
471
|
+
configRev: integer(o.configRev, 1),
|
|
472
|
+
controlRev: integer(o.controlRev, 1),
|
|
473
|
+
workspaceId: decodeId(o.workspaceId),
|
|
474
|
+
cwdId: decodeId(o.cwdId),
|
|
475
|
+
model: decodeModelSelection(o.model),
|
|
476
|
+
checkEnvGeneration: integer(o.checkEnvGeneration, 1),
|
|
477
|
+
checkoutGeneration: integer(o.checkoutGeneration),
|
|
478
|
+
observation: {
|
|
479
|
+
identity: decodeHash(obs.identity),
|
|
480
|
+
complete: bool(obs.complete)
|
|
481
|
+
},
|
|
482
|
+
task: nullable(o.task, taskVersion)
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
function checkSelection(v) {
|
|
486
|
+
const o = closed(v, ["kind", "name", "command", "timeoutMs"]);
|
|
487
|
+
const result = {
|
|
488
|
+
kind: oneOf(o.kind, ["configured", "manual"]),
|
|
489
|
+
name: text(o.name, 128, true),
|
|
490
|
+
command: text(o.command, 4096, true),
|
|
491
|
+
timeoutMs: integer(o.timeoutMs, 100, LIMITS.workerMs)
|
|
492
|
+
};
|
|
493
|
+
const controls = /[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/u;
|
|
494
|
+
if (controls.test(result.name) || controls.test(result.command) || /[\n\t]/.test(result.name) || result.name === "Manual command")
|
|
495
|
+
invalid();
|
|
496
|
+
if (result.kind === "manual" && (result.name !== "Manual" || result.timeoutMs !== 120000))
|
|
497
|
+
invalid();
|
|
498
|
+
return result;
|
|
499
|
+
}
|
|
500
|
+
function decodeCoverage(v) {
|
|
501
|
+
const o = closed(v, ["observed", "source", "redacted", "omissions"]);
|
|
502
|
+
const result = {
|
|
503
|
+
observed: oneOf(o.observed, ["complete", "incomplete"]),
|
|
504
|
+
source: oneOf(o.source, ["complete", "limited", "unavailable"]),
|
|
505
|
+
redacted: bool(o.redacted),
|
|
506
|
+
omissions: list(o.omissions, 6, (v2) => oneOf(v2, [
|
|
507
|
+
"binary",
|
|
508
|
+
"hidden-thinking",
|
|
509
|
+
"source-limit",
|
|
510
|
+
"capture-limit",
|
|
511
|
+
"gap",
|
|
512
|
+
"unsupported"
|
|
513
|
+
]))
|
|
514
|
+
};
|
|
515
|
+
if (new Set(result.omissions).size !== result.omissions.length || result.observed === "complete" && result.omissions.some((x) => x === "capture-limit" || x === "gap"))
|
|
516
|
+
invalid();
|
|
517
|
+
return result;
|
|
518
|
+
}
|
|
519
|
+
function decodeHandoff(v) {
|
|
520
|
+
const o = closed(v, ["graphRevision", "inputs"]);
|
|
521
|
+
let total = 0;
|
|
522
|
+
const seen = new Set;
|
|
523
|
+
return {
|
|
524
|
+
graphRevision: integer(o.graphRevision, 1),
|
|
525
|
+
inputs: list(o.inputs, LIMITS.assignments, (v2) => {
|
|
526
|
+
const i = closed(v2, [
|
|
527
|
+
"assignmentId",
|
|
528
|
+
"dependencyIndex",
|
|
529
|
+
"runId",
|
|
530
|
+
"childRunId",
|
|
531
|
+
"result",
|
|
532
|
+
"range",
|
|
533
|
+
"text",
|
|
534
|
+
"coverage"
|
|
535
|
+
]);
|
|
536
|
+
const result = decodeContentRef(i.result);
|
|
537
|
+
literal(result.field, "final-text");
|
|
538
|
+
const selected = nullable(i.range, range);
|
|
539
|
+
if (selected && selected.end > result.bytes)
|
|
540
|
+
invalid();
|
|
541
|
+
const supplied = text(i.text, LIMITS.predecessorBytes);
|
|
542
|
+
total += utf8Bytes(supplied);
|
|
543
|
+
if (total > LIMITS.handoffBytes)
|
|
544
|
+
throw new ContractError("oversize");
|
|
545
|
+
const dependencyIndex = integer(i.dependencyIndex, 0, LIMITS.assignments - 1);
|
|
546
|
+
if (seen.has(dependencyIndex))
|
|
547
|
+
invalid();
|
|
548
|
+
seen.add(dependencyIndex);
|
|
549
|
+
if (utf8Bytes(supplied) !== (selected ? selected.end - selected.start : result.bytes))
|
|
550
|
+
invalid();
|
|
551
|
+
return {
|
|
552
|
+
assignmentId: assignmentId(i.assignmentId),
|
|
553
|
+
dependencyIndex,
|
|
554
|
+
runId: decodeId(i.runId),
|
|
555
|
+
childRunId: decodeId(i.childRunId),
|
|
556
|
+
result,
|
|
557
|
+
range: selected,
|
|
558
|
+
text: supplied,
|
|
559
|
+
coverage: decodeCoverage(i.coverage)
|
|
560
|
+
};
|
|
561
|
+
})
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
function decodeNativeSettlement(v) {
|
|
565
|
+
const o = closed(v, [
|
|
566
|
+
"outcome",
|
|
567
|
+
"closure",
|
|
568
|
+
"exitCode",
|
|
569
|
+
"signal",
|
|
570
|
+
"durationMs",
|
|
571
|
+
"stdin",
|
|
572
|
+
"final",
|
|
573
|
+
"cleanup",
|
|
574
|
+
"capture"
|
|
575
|
+
]);
|
|
576
|
+
const r = {
|
|
577
|
+
outcome: oneOf(o.outcome, [
|
|
578
|
+
"completed",
|
|
579
|
+
"failed",
|
|
580
|
+
"canceled",
|
|
581
|
+
"timeout",
|
|
582
|
+
"unknown"
|
|
583
|
+
]),
|
|
584
|
+
closure: oneOf(o.closure, closures),
|
|
585
|
+
exitCode: nullable(o.exitCode, (v2) => integer(v2, -2147483648, 4294967295)),
|
|
586
|
+
signal: nullable(o.signal, (v2) => text(v2, 32, true)),
|
|
587
|
+
durationMs: integer(o.durationMs),
|
|
588
|
+
stdin: oneOf(o.stdin, ["delivered", "failed", "not-required"]),
|
|
589
|
+
final: oneOf(o.final, ["valid", "missing", "invalid"]),
|
|
590
|
+
cleanup: oneOf(o.cleanup, ["settled", "failed", "unconfirmed"]),
|
|
591
|
+
capture: decodeCoverage(o.capture)
|
|
592
|
+
};
|
|
593
|
+
if (r.closure === "not-launched" && (r.exitCode !== null || r.signal !== null))
|
|
594
|
+
invalid();
|
|
595
|
+
if (r.outcome === "completed" && (r.closure !== "direct-child-closed" || r.exitCode !== 0 || r.signal !== null || r.stdin !== "delivered" || r.final !== "valid" || r.cleanup !== "settled" || r.capture.observed !== "complete"))
|
|
596
|
+
invalid();
|
|
597
|
+
return r;
|
|
598
|
+
}
|
|
599
|
+
function decodeSourceIdentity(v) {
|
|
600
|
+
const o = closed(v, ["disposition", "value"]);
|
|
601
|
+
const disposition = oneOf(o.disposition, [
|
|
602
|
+
"observed",
|
|
603
|
+
"unavailable",
|
|
604
|
+
"redacted"
|
|
605
|
+
]);
|
|
606
|
+
const value = sourceId(o.value);
|
|
607
|
+
if (disposition === "observed" !== (value !== null))
|
|
608
|
+
invalid();
|
|
609
|
+
return { disposition, value };
|
|
610
|
+
}
|
|
611
|
+
function callLink(v) {
|
|
612
|
+
const o = closed(v, ["messageId", "blockId"]);
|
|
613
|
+
return { messageId: decodeId(o.messageId), blockId: decodeId(o.blockId) };
|
|
614
|
+
}
|
|
615
|
+
function decodeContentOwner(v) {
|
|
616
|
+
const kind = tag(v);
|
|
617
|
+
if (kind === "message-final") {
|
|
618
|
+
const o2 = closed(v, ["kind", "messageId"]);
|
|
619
|
+
return { kind, messageId: decodeId(o2.messageId) };
|
|
620
|
+
}
|
|
621
|
+
if (kind === "context") {
|
|
622
|
+
const o2 = closed(v, ["kind", "component"]);
|
|
623
|
+
return {
|
|
624
|
+
kind,
|
|
625
|
+
component: oneOf(o2.component, [
|
|
626
|
+
"request-context",
|
|
627
|
+
"request-prompt",
|
|
628
|
+
"request-instructions",
|
|
629
|
+
"role",
|
|
630
|
+
"effective-system"
|
|
631
|
+
])
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
if (kind === "handoff") {
|
|
635
|
+
const o2 = closed(v, ["kind", "dependencyIndex", "source"]);
|
|
636
|
+
const source = decodeContentRef(o2.source);
|
|
637
|
+
literal(source.field, "final-text");
|
|
638
|
+
return {
|
|
639
|
+
kind,
|
|
640
|
+
dependencyIndex: integer(o2.dependencyIndex, 0, LIMITS.assignments - 1),
|
|
641
|
+
source
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
if (kind === "message") {
|
|
645
|
+
const o2 = closed(v, ["kind", "messageId", "blockId", "index", "stage"]);
|
|
646
|
+
return {
|
|
647
|
+
kind,
|
|
648
|
+
messageId: decodeId(o2.messageId),
|
|
649
|
+
blockId: decodeId(o2.blockId),
|
|
650
|
+
index: integer(o2.index, 0, LIMITS.dataFrames),
|
|
651
|
+
stage: oneOf(o2.stage, ["stream", "final"])
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
const o = closed(v, ["kind", "callId", "blockId", "index", "stage"]);
|
|
655
|
+
literal(kind, "tool");
|
|
656
|
+
return {
|
|
657
|
+
kind: "tool",
|
|
658
|
+
callId: decodeId(o.callId),
|
|
659
|
+
blockId: decodeId(o.blockId),
|
|
660
|
+
index: integer(o.index, 0, LIMITS.dataFrames),
|
|
661
|
+
stage: oneOf(o.stage, [
|
|
662
|
+
"arguments-partial",
|
|
663
|
+
"arguments-final",
|
|
664
|
+
"execution-arguments",
|
|
665
|
+
"update-snapshot",
|
|
666
|
+
"result"
|
|
667
|
+
])
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
function decodeDetailDescriptor(v) {
|
|
671
|
+
const o = closed(v, ["owner", "field", "encoding"]);
|
|
672
|
+
const owner = decodeContentOwner(o.owner);
|
|
673
|
+
const field = oneOf(o.field, [
|
|
674
|
+
"context",
|
|
675
|
+
"message",
|
|
676
|
+
"final-text",
|
|
677
|
+
"tool-args",
|
|
678
|
+
"tool-update",
|
|
679
|
+
"tool-result"
|
|
680
|
+
]);
|
|
681
|
+
const encoding = oneOf(o.encoding, ["utf8", "canonical-json"]);
|
|
682
|
+
const expected = owner.kind === "context" || owner.kind === "handoff" ? "context" : owner.kind === "message-final" ? "final-text" : owner.kind === "message" ? "message" : owner.stage === "result" ? "tool-result" : owner.stage === "update-snapshot" ? "tool-update" : "tool-args";
|
|
683
|
+
if (field !== expected || owner.kind !== "tool" && encoding !== "utf8" || field === "tool-args" && encoding !== "canonical-json" && !(owner.kind === "tool" && owner.stage === "arguments-partial"))
|
|
684
|
+
invalid();
|
|
685
|
+
return { owner, field, encoding };
|
|
686
|
+
}
|
|
687
|
+
function decodeOmittedBlock(v) {
|
|
688
|
+
const o = closed(v, ["owner", "sourceType", "mimeType", "reason"]);
|
|
689
|
+
const sourceType = oneOf(o.sourceType, [
|
|
690
|
+
"image",
|
|
691
|
+
"audio",
|
|
692
|
+
"binary",
|
|
693
|
+
"hidden-thinking",
|
|
694
|
+
"unsupported"
|
|
695
|
+
]);
|
|
696
|
+
const reason = oneOf(o.reason, ["binary", "hidden-thinking", "unsupported"]);
|
|
697
|
+
const mimeType = nullable(o.mimeType, (v2) => text(v2, 128, true));
|
|
698
|
+
if (reason !== (sourceType === "hidden-thinking" ? "hidden-thinking" : sourceType === "unsupported" ? "unsupported" : "binary") || mimeType !== null && (sourceType === "hidden-thinking" || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(mimeType)))
|
|
699
|
+
invalid();
|
|
700
|
+
return { owner: decodeContentOwner(o.owner), sourceType, mimeType, reason };
|
|
701
|
+
}
|
|
702
|
+
function sourceId(v) {
|
|
703
|
+
if (v === null)
|
|
704
|
+
return null;
|
|
705
|
+
const s = text(v, 128, true);
|
|
706
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(s))
|
|
707
|
+
invalid();
|
|
708
|
+
return s;
|
|
709
|
+
}
|
|
710
|
+
function decodeCaptureEvent(v) {
|
|
711
|
+
const kind = tag(v);
|
|
712
|
+
switch (kind) {
|
|
713
|
+
case "ready": {
|
|
714
|
+
const o = closed(v, [
|
|
715
|
+
"kind",
|
|
716
|
+
"requestProtocol",
|
|
717
|
+
...Object.hasOwn(v ?? {}, "runtime") ? ["runtime"] : []
|
|
718
|
+
]);
|
|
719
|
+
return {
|
|
720
|
+
kind,
|
|
721
|
+
requestProtocol: literal(o.requestProtocol, WORKER_PROTOCOL),
|
|
722
|
+
...o.runtime === undefined ? {} : {
|
|
723
|
+
runtime: (() => {
|
|
724
|
+
const r = closed(o.runtime, ["sdkVersion", "workerHash"]);
|
|
725
|
+
return {
|
|
726
|
+
sdkVersion: text(r.sdkVersion, 128, true),
|
|
727
|
+
workerHash: decodeHash(r.workerHash)
|
|
728
|
+
};
|
|
729
|
+
})()
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
case "message-start": {
|
|
734
|
+
const o = closed(v, [
|
|
735
|
+
"kind",
|
|
736
|
+
"messageId",
|
|
737
|
+
"role",
|
|
738
|
+
"source",
|
|
739
|
+
"resultCallId"
|
|
740
|
+
]);
|
|
741
|
+
const role = oneOf(o.role, ["user", "assistant", "tool-result"]);
|
|
742
|
+
const resultCallId = nullable(o.resultCallId, decodeId);
|
|
743
|
+
if (role !== "tool-result" && resultCallId !== null)
|
|
744
|
+
invalid();
|
|
745
|
+
return {
|
|
746
|
+
kind,
|
|
747
|
+
messageId: decodeId(o.messageId),
|
|
748
|
+
role,
|
|
749
|
+
source: decodeSourceIdentity(o.source),
|
|
750
|
+
resultCallId
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
case "message-text": {
|
|
754
|
+
const o = closed(v, ["kind", "messageId", "blockId", "detailId"]);
|
|
755
|
+
return {
|
|
756
|
+
kind,
|
|
757
|
+
...callLink({ messageId: o.messageId, blockId: o.blockId }),
|
|
758
|
+
detailId: decodeId(o.detailId)
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
case "message-end": {
|
|
762
|
+
const o = closed(v, [
|
|
763
|
+
"kind",
|
|
764
|
+
"messageId",
|
|
765
|
+
"finalDetailId",
|
|
766
|
+
"finalBlockCount",
|
|
767
|
+
"stopReason"
|
|
768
|
+
]);
|
|
769
|
+
return {
|
|
770
|
+
kind,
|
|
771
|
+
messageId: decodeId(o.messageId),
|
|
772
|
+
finalDetailId: nullable(o.finalDetailId, decodeId),
|
|
773
|
+
finalBlockCount: integer(o.finalBlockCount, 0, LIMITS.dataFrames),
|
|
774
|
+
stopReason: oneOf(o.stopReason, [
|
|
775
|
+
"stop",
|
|
776
|
+
"length",
|
|
777
|
+
"toolUse",
|
|
778
|
+
"error",
|
|
779
|
+
"aborted",
|
|
780
|
+
"unknown"
|
|
781
|
+
])
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
case "call-declaration": {
|
|
785
|
+
const o = closed(v, [
|
|
786
|
+
"kind",
|
|
787
|
+
"callId",
|
|
788
|
+
"declaration",
|
|
789
|
+
"index",
|
|
790
|
+
"source",
|
|
791
|
+
"name",
|
|
792
|
+
"argsDetailId",
|
|
793
|
+
"stage"
|
|
794
|
+
]);
|
|
795
|
+
return {
|
|
796
|
+
kind,
|
|
797
|
+
callId: decodeId(o.callId),
|
|
798
|
+
declaration: callLink(o.declaration),
|
|
799
|
+
index: integer(o.index, 0, LIMITS.dataFrames),
|
|
800
|
+
source: decodeSourceIdentity(o.source),
|
|
801
|
+
name: text(o.name, 128, true),
|
|
802
|
+
argsDetailId: nullable(o.argsDetailId, decodeId),
|
|
803
|
+
stage: oneOf(o.stage, ["partial", "final"])
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
case "tool-start": {
|
|
807
|
+
const o = closed(v, [
|
|
808
|
+
"kind",
|
|
809
|
+
"callId",
|
|
810
|
+
"declaration",
|
|
811
|
+
"source",
|
|
812
|
+
"name",
|
|
813
|
+
"argsDetailId"
|
|
814
|
+
]);
|
|
815
|
+
return {
|
|
816
|
+
kind,
|
|
817
|
+
callId: decodeId(o.callId),
|
|
818
|
+
declaration: nullable(o.declaration, callLink),
|
|
819
|
+
source: decodeSourceIdentity(o.source),
|
|
820
|
+
name: text(o.name, 128, true),
|
|
821
|
+
argsDetailId: nullable(o.argsDetailId, decodeId)
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
case "tool-update": {
|
|
825
|
+
const o = closed(v, ["kind", "callId", "detailId", "semantics"]);
|
|
826
|
+
return {
|
|
827
|
+
kind,
|
|
828
|
+
callId: decodeId(o.callId),
|
|
829
|
+
detailId: decodeId(o.detailId),
|
|
830
|
+
semantics: literal(o.semantics, "snapshot")
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
case "tool-end": {
|
|
834
|
+
const o = closed(v, [
|
|
835
|
+
"kind",
|
|
836
|
+
"callId",
|
|
837
|
+
"declaration",
|
|
838
|
+
"source",
|
|
839
|
+
"name",
|
|
840
|
+
"resultDetailId",
|
|
841
|
+
"isError",
|
|
842
|
+
"association",
|
|
843
|
+
"startObserved"
|
|
844
|
+
]);
|
|
845
|
+
const association = oneOf(o.association, [
|
|
846
|
+
"declared",
|
|
847
|
+
"execution-only",
|
|
848
|
+
"orphan",
|
|
849
|
+
"ambiguous"
|
|
850
|
+
]);
|
|
851
|
+
const declaration = nullable(o.declaration, callLink);
|
|
852
|
+
const startObserved = bool(o.startObserved);
|
|
853
|
+
if (association === "declared" !== (declaration !== null) || association === "execution-only" && !startObserved || (association === "orphan" || association === "ambiguous") && startObserved)
|
|
854
|
+
invalid();
|
|
855
|
+
return {
|
|
856
|
+
kind,
|
|
857
|
+
callId: decodeId(o.callId),
|
|
858
|
+
declaration,
|
|
859
|
+
source: decodeSourceIdentity(o.source),
|
|
860
|
+
name: text(o.name, 128, true),
|
|
861
|
+
resultDetailId: decodeId(o.resultDetailId),
|
|
862
|
+
isError: bool(o.isError),
|
|
863
|
+
association,
|
|
864
|
+
startObserved
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
case "omitted-block": {
|
|
868
|
+
const o = closed(v, ["kind", "block"]);
|
|
869
|
+
return { kind, block: decodeOmittedBlock(o.block) };
|
|
870
|
+
}
|
|
871
|
+
case "detail-begin": {
|
|
872
|
+
const o = closed(v, ["kind", "detailId", "descriptor"]);
|
|
873
|
+
return {
|
|
874
|
+
kind,
|
|
875
|
+
detailId: decodeId(o.detailId),
|
|
876
|
+
descriptor: decodeDetailDescriptor(o.descriptor)
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
case "detail-chunk": {
|
|
880
|
+
const o = closed(v, ["kind", "detailId", "offset", "text"]);
|
|
881
|
+
const chunk = text(o.text, LIMITS.chunkBytes);
|
|
882
|
+
const offset = integer(o.offset, 0, LIMITS.detailBytes);
|
|
883
|
+
if (offset + utf8Bytes(chunk) > LIMITS.detailBytes)
|
|
884
|
+
invalid();
|
|
885
|
+
return { kind, detailId: decodeId(o.detailId), offset, text: chunk };
|
|
886
|
+
}
|
|
887
|
+
case "detail-end": {
|
|
888
|
+
const o = closed(v, ["kind", "detailId", "bytes", "sha256", "coverage"]);
|
|
889
|
+
return {
|
|
890
|
+
kind,
|
|
891
|
+
detailId: decodeId(o.detailId),
|
|
892
|
+
bytes: integer(o.bytes, 0, LIMITS.detailBytes),
|
|
893
|
+
sha256: decodeHash(o.sha256),
|
|
894
|
+
coverage: decodeCoverage(o.coverage)
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
case "capture-status": {
|
|
898
|
+
const o = closed(v, ["kind", "coverage"]);
|
|
899
|
+
return { kind, coverage: decodeCoverage(o.coverage) };
|
|
900
|
+
}
|
|
901
|
+
case "worker-failure": {
|
|
902
|
+
const o = closed(v, ["kind", "code"]);
|
|
903
|
+
return {
|
|
904
|
+
kind,
|
|
905
|
+
code: oneOf(o.code, [
|
|
906
|
+
"protocol",
|
|
907
|
+
"capture",
|
|
908
|
+
"model",
|
|
909
|
+
"auth",
|
|
910
|
+
"network",
|
|
911
|
+
"cleanup",
|
|
912
|
+
"prompt"
|
|
913
|
+
])
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
case "final": {
|
|
917
|
+
const o = closed(v, ["kind", "messageId", "detailId", "stopReason"]);
|
|
918
|
+
return {
|
|
919
|
+
kind,
|
|
920
|
+
messageId: decodeId(o.messageId),
|
|
921
|
+
detailId: decodeId(o.detailId),
|
|
922
|
+
stopReason: literal(o.stopReason, "stop")
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
default:
|
|
926
|
+
return invalid();
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
function decodeCheckNativeSettlement(v) {
|
|
930
|
+
const o = closed(v, [
|
|
931
|
+
"outcome",
|
|
932
|
+
"closure",
|
|
933
|
+
"exitCode",
|
|
934
|
+
"signal",
|
|
935
|
+
"durationMs",
|
|
936
|
+
"stdin"
|
|
937
|
+
]);
|
|
938
|
+
const r = {
|
|
939
|
+
outcome: oneOf(o.outcome, [
|
|
940
|
+
"completed",
|
|
941
|
+
"failed",
|
|
942
|
+
"canceled",
|
|
943
|
+
"timeout",
|
|
944
|
+
"unknown"
|
|
945
|
+
]),
|
|
946
|
+
closure: oneOf(o.closure, closures),
|
|
947
|
+
exitCode: nullable(o.exitCode, (v2) => integer(v2, -2147483648, 4294967295)),
|
|
948
|
+
signal: nullable(o.signal, (v2) => text(v2, 32, true)),
|
|
949
|
+
durationMs: integer(o.durationMs),
|
|
950
|
+
stdin: literal(o.stdin, "not-required")
|
|
951
|
+
};
|
|
952
|
+
if (r.closure === "not-launched" && (r.exitCode !== null || r.signal !== null) || r.outcome === "completed" && (r.closure !== "direct-child-closed" || r.exitCode !== 0 || r.signal !== null))
|
|
953
|
+
invalid();
|
|
954
|
+
return r;
|
|
955
|
+
}
|
|
956
|
+
function decodeFinalSelection(v) {
|
|
957
|
+
const o = closed(v, ["messageId", "detailId"]);
|
|
958
|
+
return { messageId: decodeId(o.messageId), detailId: decodeId(o.detailId) };
|
|
959
|
+
}
|
|
960
|
+
function decodeDetailCommit(v) {
|
|
961
|
+
const o = closed(v, ["childRunId", "detailId", "content", "committedSeq"]);
|
|
962
|
+
const committedSeq = decodeSequence(o.committedSeq);
|
|
963
|
+
if (committedSeq === "0")
|
|
964
|
+
invalid();
|
|
965
|
+
return {
|
|
966
|
+
childRunId: decodeId(o.childRunId),
|
|
967
|
+
detailId: decodeId(o.detailId),
|
|
968
|
+
content: decodeContentRef(o.content),
|
|
969
|
+
committedSeq
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
function decodeFinalRecording(v) {
|
|
973
|
+
const status = tag(v, "status");
|
|
974
|
+
if (status === "committed") {
|
|
975
|
+
const o2 = closed(v, ["status", "selected", "detail"]);
|
|
976
|
+
const selected = decodeFinalSelection(o2.selected), detail = decodeDetailCommit(o2.detail);
|
|
977
|
+
if (selected.detailId !== detail.detailId || detail.content.field !== "final-text")
|
|
978
|
+
invalid();
|
|
979
|
+
return { status, selected, detail };
|
|
980
|
+
}
|
|
981
|
+
if (status === "refused") {
|
|
982
|
+
const o2 = closed(v, ["status", "selected", "error"]);
|
|
983
|
+
return {
|
|
984
|
+
status,
|
|
985
|
+
selected: nullable(o2.selected, decodeFinalSelection),
|
|
986
|
+
error: decodePublicError(o2.error)
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
const o = closed(v, ["status", "selected"]);
|
|
990
|
+
return {
|
|
991
|
+
status: oneOf(status, ["pending", "uncertain"]),
|
|
992
|
+
selected: nullable(o.selected, decodeFinalSelection)
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
function decodeSettlementSeq(v, recording) {
|
|
996
|
+
const seq = nullable(v, decodeSequence);
|
|
997
|
+
if (seq === "0" || seq !== null && recording.status === "committed" && compareSequence(seq, recording.detail.committedSeq) < 0)
|
|
998
|
+
invalid();
|
|
999
|
+
return seq;
|
|
1000
|
+
}
|
|
1001
|
+
function childSatisfied(child) {
|
|
1002
|
+
return child.native?.outcome === "completed" && child.recording.status === "committed" && child.settlementSeq !== null;
|
|
1003
|
+
}
|
|
1004
|
+
function decodeRunSettlement(v) {
|
|
1005
|
+
const kind = tag(v);
|
|
1006
|
+
if (kind === "sdk") {
|
|
1007
|
+
const o2 = closed(v, ["kind", "native", "recording", "settlementSeq"]);
|
|
1008
|
+
const recording = decodeFinalRecording(o2.recording), settlementSeq = decodeSettlementSeq(o2.settlementSeq, recording);
|
|
1009
|
+
return {
|
|
1010
|
+
kind,
|
|
1011
|
+
native: decodeNativeSettlement(o2.native),
|
|
1012
|
+
recording,
|
|
1013
|
+
settlementSeq
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
if (kind === "check") {
|
|
1017
|
+
const o2 = closed(v, ["kind", "native", "capture", "settlementSeq"]);
|
|
1018
|
+
const settlementSeq = nullable(o2.settlementSeq, decodeSequence);
|
|
1019
|
+
if (settlementSeq === "0")
|
|
1020
|
+
invalid();
|
|
1021
|
+
return {
|
|
1022
|
+
kind,
|
|
1023
|
+
native: decodeCheckNativeSettlement(o2.native),
|
|
1024
|
+
capture: decodeCoverage(o2.capture),
|
|
1025
|
+
settlementSeq
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
const o = closed(v, ["kind", "outcome", "required"]);
|
|
1029
|
+
literal(kind, "parent");
|
|
1030
|
+
const required = list(o.required, LIMITS.assignments, (v2) => {
|
|
1031
|
+
const c = closed(v2, [
|
|
1032
|
+
"assignmentId",
|
|
1033
|
+
"childRunId",
|
|
1034
|
+
"native",
|
|
1035
|
+
"recording",
|
|
1036
|
+
"settlementSeq"
|
|
1037
|
+
]);
|
|
1038
|
+
const childRunId = decodeId(c.childRunId), recording = decodeFinalRecording(c.recording);
|
|
1039
|
+
if (recording.status === "committed" && recording.detail.childRunId !== childRunId)
|
|
1040
|
+
invalid();
|
|
1041
|
+
return {
|
|
1042
|
+
assignmentId: assignmentId(c.assignmentId),
|
|
1043
|
+
childRunId,
|
|
1044
|
+
native: nullable(c.native, decodeNativeSettlement),
|
|
1045
|
+
recording,
|
|
1046
|
+
settlementSeq: decodeSettlementSeq(c.settlementSeq, recording)
|
|
1047
|
+
};
|
|
1048
|
+
});
|
|
1049
|
+
const outcome = oneOf(o.outcome, outcomes);
|
|
1050
|
+
if (!required.length || new Set(required.map((c) => c.assignmentId)).size !== required.length || new Set(required.map((c) => c.childRunId)).size !== required.length || outcome === "completed" && !required.every(childSatisfied))
|
|
1051
|
+
invalid();
|
|
1052
|
+
return { kind: "parent", outcome, required };
|
|
1053
|
+
}
|
|
1054
|
+
function decodeSourceRange(v) {
|
|
1055
|
+
const o = closed(v, ["first", "last", "firstObservedMs", "lastObservedMs"]);
|
|
1056
|
+
const first = integer(o.first, 1, LIMITS.dataFrames + LIMITS.controlFrames);
|
|
1057
|
+
const last = integer(o.last, first, LIMITS.dataFrames + LIMITS.controlFrames);
|
|
1058
|
+
const firstObservedMs = integer(o.firstObservedMs);
|
|
1059
|
+
const lastObservedMs = integer(o.lastObservedMs, firstObservedMs);
|
|
1060
|
+
if (first === last && firstObservedMs !== lastObservedMs)
|
|
1061
|
+
invalid();
|
|
1062
|
+
return { first, last, firstObservedMs, lastObservedMs };
|
|
1063
|
+
}
|
|
1064
|
+
function decodeRecordingEvent(v) {
|
|
1065
|
+
const o = closed(v, ["source", "event"]);
|
|
1066
|
+
const source = decodeSourceRange(o.source);
|
|
1067
|
+
const kind = tag(o.event);
|
|
1068
|
+
if (kind === "stored-chunk") {
|
|
1069
|
+
const e = closed(o.event, ["kind", "detailId", "text"]);
|
|
1070
|
+
return {
|
|
1071
|
+
source,
|
|
1072
|
+
event: {
|
|
1073
|
+
kind,
|
|
1074
|
+
detailId: decodeId(e.detailId),
|
|
1075
|
+
text: text(e.text, LIMITS.chunkBytes)
|
|
1076
|
+
}
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
if (kind === "stored-end") {
|
|
1080
|
+
const e = closed(o.event, ["kind", "detailId", "coverage"]);
|
|
1081
|
+
return {
|
|
1082
|
+
source,
|
|
1083
|
+
event: {
|
|
1084
|
+
kind,
|
|
1085
|
+
detailId: decodeId(e.detailId),
|
|
1086
|
+
coverage: decodeCoverage(e.coverage)
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
const event = decodeCaptureEvent(o.event);
|
|
1091
|
+
if (event.kind === "detail-chunk" || event.kind === "detail-end")
|
|
1092
|
+
invalid();
|
|
1093
|
+
return { source, event };
|
|
1094
|
+
}
|
|
1095
|
+
function decodeRecordingLink(v) {
|
|
1096
|
+
const o = closed(v, ["epoch", "taskId", "runId", "childRunId"]);
|
|
1097
|
+
return {
|
|
1098
|
+
epoch: decodeId(o.epoch),
|
|
1099
|
+
taskId: decodeId(o.taskId),
|
|
1100
|
+
runId: decodeId(o.runId),
|
|
1101
|
+
childRunId: decodeId(o.childRunId)
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
function decodeRecordingInput(v) {
|
|
1105
|
+
canonicalJson(v, LIMITS.ownerQueueBytes);
|
|
1106
|
+
const o = closed(v, ["link", "source", "events"]);
|
|
1107
|
+
const source = decodeSourceRange(o.source), events = list(o.events, LIMITS.ownerQueueFrames, decodeRecordingEvent);
|
|
1108
|
+
if (events.some((e) => e.source.first < source.first || e.source.last > source.last || e.source.firstObservedMs < source.firstObservedMs || e.source.lastObservedMs > source.lastObservedMs))
|
|
1109
|
+
invalid();
|
|
1110
|
+
return { link: decodeRecordingLink(o.link), source, events };
|
|
1111
|
+
}
|
|
1112
|
+
function decodeCaptureBudget(v) {
|
|
1113
|
+
const o = closed(v, [
|
|
1114
|
+
"sourceFrames",
|
|
1115
|
+
"retainedBytes",
|
|
1116
|
+
"outputBytes",
|
|
1117
|
+
"outputChunks",
|
|
1118
|
+
"lane"
|
|
1119
|
+
]);
|
|
1120
|
+
const r = {
|
|
1121
|
+
sourceFrames: integer(o.sourceFrames, 0, LIMITS.ownerQueueFrames),
|
|
1122
|
+
retainedBytes: integer(o.retainedBytes, 0, LIMITS.ownerQueueBytes),
|
|
1123
|
+
outputBytes: integer(o.outputBytes, 0, LIMITS.ownerQueueBytes),
|
|
1124
|
+
outputChunks: integer(o.outputChunks, 0, LIMITS.ownerQueueFrames),
|
|
1125
|
+
lane: oneOf(o.lane, ["data", "control"])
|
|
1126
|
+
};
|
|
1127
|
+
if (r.retainedBytes + r.outputBytes > LIMITS.ownerQueueBytes || !r.sourceFrames && !r.retainedBytes && !r.outputBytes && !r.outputChunks)
|
|
1128
|
+
invalid();
|
|
1129
|
+
return r;
|
|
1130
|
+
}
|
|
1131
|
+
// src/service/contracts/history.ts
|
|
1132
|
+
function decodeRunIdentity(v) {
|
|
1133
|
+
const o = closed(v, [
|
|
1134
|
+
"operationId",
|
|
1135
|
+
"commandId",
|
|
1136
|
+
"kind",
|
|
1137
|
+
"context",
|
|
1138
|
+
"assignments",
|
|
1139
|
+
"graph"
|
|
1140
|
+
]);
|
|
1141
|
+
const context = decodeContext(o.context);
|
|
1142
|
+
const graph = nullable(o.graph, (v2) => {
|
|
1143
|
+
const g = closed(v2, ["recordId", "revision", "sha256"]);
|
|
1144
|
+
return {
|
|
1145
|
+
recordId: decodeId(g.recordId),
|
|
1146
|
+
revision: integer(g.revision, 1),
|
|
1147
|
+
sha256: decodeHash(g.sha256)
|
|
1148
|
+
};
|
|
1149
|
+
});
|
|
1150
|
+
const kind = oneOf(o.kind, ["start", "generate-plan", "check"]);
|
|
1151
|
+
const assignments = list(o.assignments, LIMITS.assignments, (v2) => {
|
|
1152
|
+
const a = closed(v2, ["assignmentId", "childRunId"]);
|
|
1153
|
+
return {
|
|
1154
|
+
assignmentId: assignmentId(a.assignmentId),
|
|
1155
|
+
childRunId: decodeId(a.childRunId)
|
|
1156
|
+
};
|
|
1157
|
+
});
|
|
1158
|
+
if (kind === "check" !== (assignments.length === 0) || new Set(assignments.map((a) => a.assignmentId)).size !== assignments.length || new Set(assignments.map((a) => a.childRunId)).size !== assignments.length)
|
|
1159
|
+
invalid();
|
|
1160
|
+
if (!context.task || kind === "start" && (!graph || graph.revision !== context.task.graphRevision || graph.sha256 !== context.task.graphIdentity) || kind !== "start" && graph !== null)
|
|
1161
|
+
invalid();
|
|
1162
|
+
return {
|
|
1163
|
+
operationId: decodeId(o.operationId),
|
|
1164
|
+
commandId: decodeId(o.commandId),
|
|
1165
|
+
kind,
|
|
1166
|
+
context,
|
|
1167
|
+
assignments,
|
|
1168
|
+
graph
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
function decodeRecordOwner(v) {
|
|
1172
|
+
const o = closed(v, ["taskId", "runId", "childRunId", "entity"]), e = closed(o.entity, ["kind", "id", "version"]);
|
|
1173
|
+
const r = {
|
|
1174
|
+
taskId: decodeId(o.taskId),
|
|
1175
|
+
runId: nullable(o.runId, decodeId),
|
|
1176
|
+
childRunId: nullable(o.childRunId, decodeId),
|
|
1177
|
+
entity: {
|
|
1178
|
+
kind: oneOf(e.kind, [
|
|
1179
|
+
"task",
|
|
1180
|
+
"run",
|
|
1181
|
+
"child",
|
|
1182
|
+
"message",
|
|
1183
|
+
"tool",
|
|
1184
|
+
"check",
|
|
1185
|
+
"changes",
|
|
1186
|
+
"review"
|
|
1187
|
+
]),
|
|
1188
|
+
id: decodeId(e.id),
|
|
1189
|
+
version: integer(e.version, 1)
|
|
1190
|
+
}
|
|
1191
|
+
};
|
|
1192
|
+
if (r.childRunId !== null && r.runId === null || r.entity.kind === "task" && (r.entity.id !== r.taskId || r.runId !== null) || r.entity.kind === "run" && (r.entity.id !== r.runId || r.childRunId !== null) || r.entity.kind === "child" && r.entity.id !== r.childRunId || ["message", "tool"].includes(r.entity.kind) && r.childRunId === null || ["check", "changes", "review"].includes(r.entity.kind) && r.childRunId !== null)
|
|
1193
|
+
invalid();
|
|
1194
|
+
return r;
|
|
1195
|
+
}
|
|
1196
|
+
function observationFact(v) {
|
|
1197
|
+
const o = closed(v, ["identity", "complete", "checkoutGeneration"]);
|
|
1198
|
+
return {
|
|
1199
|
+
identity: decodeHash(o.identity),
|
|
1200
|
+
complete: bool(o.complete),
|
|
1201
|
+
checkoutGeneration: integer(o.checkoutGeneration)
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
function decodeOwnerFact(v) {
|
|
1205
|
+
canonicalJson(v, LIMITS.controlBytes);
|
|
1206
|
+
const kind = tag(v);
|
|
1207
|
+
switch (kind) {
|
|
1208
|
+
case "assignment-state": {
|
|
1209
|
+
const o = closed(v, ["kind", "childRunId", "state", "reason"]);
|
|
1210
|
+
const state = oneOf(o.state, [
|
|
1211
|
+
"waiting",
|
|
1212
|
+
"ready",
|
|
1213
|
+
"preparing",
|
|
1214
|
+
"closing",
|
|
1215
|
+
"unstarted"
|
|
1216
|
+
]);
|
|
1217
|
+
const reason = nullable(o.reason, (v2) => oneOf(v2, [
|
|
1218
|
+
"capacity",
|
|
1219
|
+
"dependency",
|
|
1220
|
+
"writer",
|
|
1221
|
+
"parent-stopped",
|
|
1222
|
+
"wait-expired",
|
|
1223
|
+
"handoff-overflow",
|
|
1224
|
+
"stale-dependency",
|
|
1225
|
+
"quarantine"
|
|
1226
|
+
]));
|
|
1227
|
+
if ((state === "waiting" || state === "unstarted") && reason === null)
|
|
1228
|
+
invalid();
|
|
1229
|
+
if ((state === "ready" || state === "preparing") && reason !== null)
|
|
1230
|
+
invalid();
|
|
1231
|
+
return { kind, childRunId: decodeId(o.childRunId), state, reason };
|
|
1232
|
+
}
|
|
1233
|
+
case "admission-closed": {
|
|
1234
|
+
const o = closed(v, ["kind", "reason"]);
|
|
1235
|
+
return {
|
|
1236
|
+
kind,
|
|
1237
|
+
reason: oneOf(o.reason, [
|
|
1238
|
+
"failed",
|
|
1239
|
+
"canceled",
|
|
1240
|
+
"timeout",
|
|
1241
|
+
"wait-expired",
|
|
1242
|
+
"handoff-overflow",
|
|
1243
|
+
"stale-dependency",
|
|
1244
|
+
"quarantine"
|
|
1245
|
+
])
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
case "parent-admitted": {
|
|
1249
|
+
const o = closed(v, ["kind", "runId", "identity"]);
|
|
1250
|
+
return {
|
|
1251
|
+
kind,
|
|
1252
|
+
runId: decodeId(o.runId),
|
|
1253
|
+
identity: decodeRunIdentity(o.identity)
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
case "parent-settled": {
|
|
1257
|
+
const o = closed(v, ["kind", "runId", "settlement"]), settlement = decodeRunSettlement(o.settlement);
|
|
1258
|
+
if (settlement.kind !== "parent")
|
|
1259
|
+
invalid();
|
|
1260
|
+
return { kind, runId: decodeId(o.runId), settlement };
|
|
1261
|
+
}
|
|
1262
|
+
case "gate": {
|
|
1263
|
+
const hasReservation = typeof v === "object" && v !== null && Object.hasOwn(v, "reservationId");
|
|
1264
|
+
const o = closed(v, [
|
|
1265
|
+
"kind",
|
|
1266
|
+
"lane",
|
|
1267
|
+
"state",
|
|
1268
|
+
"checkoutGeneration",
|
|
1269
|
+
...hasReservation ? ["reservationId"] : []
|
|
1270
|
+
]);
|
|
1271
|
+
return {
|
|
1272
|
+
kind,
|
|
1273
|
+
...hasReservation ? { reservationId: decodeId(o.reservationId) } : {},
|
|
1274
|
+
lane: oneOf(o.lane, ["reader", "writer", "check"]),
|
|
1275
|
+
state: oneOf(o.state, ["waiting", "held", "released", "unknown"]),
|
|
1276
|
+
checkoutGeneration: integer(o.checkoutGeneration)
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
case "handoff": {
|
|
1280
|
+
const o = closed(v, ["kind", "childRunId", "handoff", "observation"]);
|
|
1281
|
+
return {
|
|
1282
|
+
kind,
|
|
1283
|
+
childRunId: decodeId(o.childRunId),
|
|
1284
|
+
handoff: decodeHandoff(o.handoff),
|
|
1285
|
+
observation: observationFact(o.observation)
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
case "changes": {
|
|
1289
|
+
const o = closed(v, [
|
|
1290
|
+
"kind",
|
|
1291
|
+
"observationId",
|
|
1292
|
+
"stage",
|
|
1293
|
+
"observation",
|
|
1294
|
+
"content"
|
|
1295
|
+
]), content = decodeContentRef(o.content);
|
|
1296
|
+
literal(content.field, "changes");
|
|
1297
|
+
return {
|
|
1298
|
+
kind,
|
|
1299
|
+
observationId: decodeId(o.observationId),
|
|
1300
|
+
stage: oneOf(o.stage, ["before", "after", "review"]),
|
|
1301
|
+
observation: observationFact(o.observation),
|
|
1302
|
+
content
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
case "check-start": {
|
|
1306
|
+
const o = closed(v, [
|
|
1307
|
+
"kind",
|
|
1308
|
+
"checkId",
|
|
1309
|
+
"selection",
|
|
1310
|
+
"cwdId",
|
|
1311
|
+
"cwdLabel",
|
|
1312
|
+
"checkEnvGeneration",
|
|
1313
|
+
"before"
|
|
1314
|
+
]);
|
|
1315
|
+
return {
|
|
1316
|
+
kind,
|
|
1317
|
+
checkId: decodeId(o.checkId),
|
|
1318
|
+
selection: checkSelection(o.selection),
|
|
1319
|
+
cwdId: decodeId(o.cwdId),
|
|
1320
|
+
cwdLabel: text(o.cwdLabel, 4096, true),
|
|
1321
|
+
checkEnvGeneration: integer(o.checkEnvGeneration, 1),
|
|
1322
|
+
before: observationFact(o.before)
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
case "check-settled": {
|
|
1326
|
+
const hasAdvance = typeof v === "object" && v !== null && Object.hasOwn(v, "ownAdvance");
|
|
1327
|
+
const o = closed(v, [
|
|
1328
|
+
"kind",
|
|
1329
|
+
"checkId",
|
|
1330
|
+
"native",
|
|
1331
|
+
"status",
|
|
1332
|
+
"before",
|
|
1333
|
+
"after",
|
|
1334
|
+
"output",
|
|
1335
|
+
"coverage",
|
|
1336
|
+
...hasAdvance ? ["ownAdvance"] : []
|
|
1337
|
+
]);
|
|
1338
|
+
let ownAdvance;
|
|
1339
|
+
if (hasAdvance) {
|
|
1340
|
+
const a = closed(o.ownAdvance, [
|
|
1341
|
+
"operationId",
|
|
1342
|
+
"reservationId",
|
|
1343
|
+
"from",
|
|
1344
|
+
"to"
|
|
1345
|
+
]);
|
|
1346
|
+
ownAdvance = {
|
|
1347
|
+
operationId: decodeId(a.operationId),
|
|
1348
|
+
reservationId: decodeId(a.reservationId),
|
|
1349
|
+
from: integer(a.from),
|
|
1350
|
+
to: integer(a.to)
|
|
1351
|
+
};
|
|
1352
|
+
if (ownAdvance.to !== ownAdvance.from + 1 || ownAdvance.reservationId !== o.checkId)
|
|
1353
|
+
invalid();
|
|
1354
|
+
}
|
|
1355
|
+
const native = decodeCheckNativeSettlement(o.native), status = oneOf(o.status, ["passed", "failed", "canceled", "stale"]), before = observationFact(o.before), after = observationFact(o.after), output = nullable(o.output, decodeContentRef), coverage = decodeCoverage(o.coverage);
|
|
1356
|
+
if (output && output.field !== "check")
|
|
1357
|
+
invalid();
|
|
1358
|
+
if (status === "passed" && (native.outcome !== "completed" || canonicalJson({
|
|
1359
|
+
...before,
|
|
1360
|
+
checkoutGeneration: after.checkoutGeneration
|
|
1361
|
+
}) !== canonicalJson(after) || (ownAdvance ? before.checkoutGeneration !== ownAdvance.from || after.checkoutGeneration !== ownAdvance.to || output === null : before.checkoutGeneration !== after.checkoutGeneration) || coverage.observed !== "complete"))
|
|
1362
|
+
invalid();
|
|
1363
|
+
if (status === "canceled" && !["canceled", "timeout"].includes(native.outcome))
|
|
1364
|
+
invalid();
|
|
1365
|
+
return {
|
|
1366
|
+
kind,
|
|
1367
|
+
...ownAdvance ? { ownAdvance } : {},
|
|
1368
|
+
checkId: decodeId(o.checkId),
|
|
1369
|
+
native,
|
|
1370
|
+
status,
|
|
1371
|
+
before,
|
|
1372
|
+
after,
|
|
1373
|
+
output,
|
|
1374
|
+
coverage
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
case "review": {
|
|
1378
|
+
const o = closed(v, [
|
|
1379
|
+
"kind",
|
|
1380
|
+
"reviewId",
|
|
1381
|
+
"runId",
|
|
1382
|
+
"checksRevision",
|
|
1383
|
+
"changesIdentity",
|
|
1384
|
+
"acceptIssues",
|
|
1385
|
+
"outcome",
|
|
1386
|
+
"content"
|
|
1387
|
+
]);
|
|
1388
|
+
const acceptIssues = bool(o.acceptIssues), outcome = oneOf(o.outcome, ["reviewed", "reviewed-with-issues"]), content = decodeContentRef(o.content);
|
|
1389
|
+
literal(content.field, "review");
|
|
1390
|
+
if (outcome === "reviewed-with-issues" && !acceptIssues)
|
|
1391
|
+
invalid();
|
|
1392
|
+
return {
|
|
1393
|
+
kind,
|
|
1394
|
+
reviewId: decodeId(o.reviewId),
|
|
1395
|
+
runId: decodeId(o.runId),
|
|
1396
|
+
checksRevision: integer(o.checksRevision),
|
|
1397
|
+
changesIdentity: decodeHash(o.changesIdentity),
|
|
1398
|
+
acceptIssues,
|
|
1399
|
+
outcome,
|
|
1400
|
+
content
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
case "publication-intent": {
|
|
1404
|
+
const o = closed(v, [
|
|
1405
|
+
"kind",
|
|
1406
|
+
"publicationId",
|
|
1407
|
+
"expectedRevision",
|
|
1408
|
+
"expectedIdentity",
|
|
1409
|
+
"nextRevision",
|
|
1410
|
+
"nextIdentity"
|
|
1411
|
+
]);
|
|
1412
|
+
const expectedRevision = integer(o.expectedRevision), expectedIdentity = nullable(o.expectedIdentity, decodeHash), nextRevision = integer(o.nextRevision, 1);
|
|
1413
|
+
if (expectedRevision === 0 !== (expectedIdentity === null) || nextRevision !== expectedRevision + 1)
|
|
1414
|
+
invalid();
|
|
1415
|
+
return {
|
|
1416
|
+
kind,
|
|
1417
|
+
publicationId: decodeId(o.publicationId),
|
|
1418
|
+
expectedRevision,
|
|
1419
|
+
expectedIdentity,
|
|
1420
|
+
nextRevision,
|
|
1421
|
+
nextIdentity: decodeHash(o.nextIdentity)
|
|
1422
|
+
};
|
|
1423
|
+
}
|
|
1424
|
+
case "publication-settled": {
|
|
1425
|
+
const o = closed(v, ["kind", "publicationId", "status", "observed"]);
|
|
1426
|
+
const status = oneOf(o.status, ["published", "conflict", "uncertain"]), observed = nullable(o.observed, (v2) => {
|
|
1427
|
+
const x = closed(v2, ["revision", "identity"]);
|
|
1428
|
+
return {
|
|
1429
|
+
revision: integer(x.revision, 1),
|
|
1430
|
+
identity: decodeHash(x.identity)
|
|
1431
|
+
};
|
|
1432
|
+
});
|
|
1433
|
+
if (status === "published" && observed === null)
|
|
1434
|
+
invalid();
|
|
1435
|
+
return {
|
|
1436
|
+
kind,
|
|
1437
|
+
publicationId: decodeId(o.publicationId),
|
|
1438
|
+
status,
|
|
1439
|
+
observed
|
|
1440
|
+
};
|
|
1441
|
+
}
|
|
1442
|
+
default:
|
|
1443
|
+
return invalid();
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
function decodeOwnerLink(v) {
|
|
1447
|
+
const o = closed(v, ["epoch", "operationId", "taskId", "runId"]);
|
|
1448
|
+
return {
|
|
1449
|
+
epoch: decodeId(o.epoch),
|
|
1450
|
+
operationId: decodeId(o.operationId),
|
|
1451
|
+
taskId: decodeId(o.taskId),
|
|
1452
|
+
runId: nullable(o.runId, decodeId)
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
function decodeOwnerRecordingInput(v) {
|
|
1456
|
+
canonicalJson(v, LIMITS.ownerQueueBytes);
|
|
1457
|
+
const o = closed(v, ["observedMs", "link", "events"]), link = decodeOwnerLink(o.link);
|
|
1458
|
+
const events = list(o.events, LIMITS.ownerQueueFrames, (v2) => {
|
|
1459
|
+
const kind = tag(v2);
|
|
1460
|
+
if (kind === "fact") {
|
|
1461
|
+
const e2 = closed(v2, ["kind", "fact"]), fact = decodeOwnerFact(e2.fact);
|
|
1462
|
+
if ("runId" in fact && fact.runId !== link.runId || fact.kind === "parent-admitted" && (fact.identity.context.task?.id !== link.taskId || fact.identity.operationId !== link.operationId) || [
|
|
1463
|
+
"gate",
|
|
1464
|
+
"assignment-state",
|
|
1465
|
+
"admission-closed",
|
|
1466
|
+
"handoff",
|
|
1467
|
+
"check-start",
|
|
1468
|
+
"check-settled"
|
|
1469
|
+
].includes(fact.kind) && link.runId === null)
|
|
1470
|
+
invalid();
|
|
1471
|
+
return { kind, fact };
|
|
1472
|
+
}
|
|
1473
|
+
if (kind === "content-begin") {
|
|
1474
|
+
const e2 = closed(v2, ["kind", "detailId", "owner", "field", "encoding"]), owner = decodeRecordOwner(e2.owner);
|
|
1475
|
+
const field = oneOf(e2.field, ["plan", "check", "changes", "review"]);
|
|
1476
|
+
if (owner.taskId !== link.taskId || owner.runId !== link.runId || owner.childRunId !== null || owner.entity.kind !== (field === "plan" ? "task" : field))
|
|
1477
|
+
invalid();
|
|
1478
|
+
return {
|
|
1479
|
+
kind,
|
|
1480
|
+
detailId: decodeId(e2.detailId),
|
|
1481
|
+
owner,
|
|
1482
|
+
field,
|
|
1483
|
+
encoding: literal(e2.encoding, "utf8")
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
if (kind === "content-chunk") {
|
|
1487
|
+
const e2 = closed(v2, ["kind", "detailId", "text"]);
|
|
1488
|
+
return {
|
|
1489
|
+
kind,
|
|
1490
|
+
detailId: decodeId(e2.detailId),
|
|
1491
|
+
text: text(e2.text, LIMITS.chunkBytes)
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
const e = closed(v2, ["kind", "detailId", "coverage"]);
|
|
1495
|
+
literal(kind, "content-end");
|
|
1496
|
+
return {
|
|
1497
|
+
kind: "content-end",
|
|
1498
|
+
detailId: decodeId(e.detailId),
|
|
1499
|
+
coverage: decodeCoverage(e.coverage)
|
|
1500
|
+
};
|
|
1501
|
+
});
|
|
1502
|
+
return { observedMs: integer(o.observedMs), link, events };
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
// src/service/contracts/budget.ts
|
|
1506
|
+
class CaptureBudgetPool {
|
|
1507
|
+
leases = new Set;
|
|
1508
|
+
reserve(input) {
|
|
1509
|
+
const budget = decodeCaptureBudget(input);
|
|
1510
|
+
const lease = new CaptureBudgetLease((next) => this.check(lease, next), () => {
|
|
1511
|
+
this.leases.delete(lease);
|
|
1512
|
+
}, budget);
|
|
1513
|
+
this.check(lease, budget);
|
|
1514
|
+
this.leases.add(lease);
|
|
1515
|
+
return lease;
|
|
1516
|
+
}
|
|
1517
|
+
get accounting() {
|
|
1518
|
+
const values = [...this.leases].map((l) => l.budget);
|
|
1519
|
+
return {
|
|
1520
|
+
leases: values.length,
|
|
1521
|
+
bytes: values.reduce((n, b) => n + b.retainedBytes + b.outputBytes, 0),
|
|
1522
|
+
sourceFrames: values.reduce((n, b) => n + b.sourceFrames, 0),
|
|
1523
|
+
outputChunks: values.reduce((n, b) => n + b.outputChunks, 0)
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
1526
|
+
check(lease, budget) {
|
|
1527
|
+
const values = [...this.leases].filter((l) => l !== lease).map((l) => l.budget).concat(budget);
|
|
1528
|
+
const fits = (items, bytes, frames) => items.reduce((n, b) => n + b.retainedBytes + b.outputBytes, 0) <= bytes && items.reduce((n, b) => n + Math.max(1, b.sourceFrames + b.outputChunks), 0) <= frames;
|
|
1529
|
+
if (!fits(values, LIMITS.ownerQueueBytes, LIMITS.ownerQueueFrames) || !fits(values.filter((b) => b.lane === "data"), LIMITS.ownerQueueBytes - LIMITS.ownerControlBytes, LIMITS.ownerQueueFrames - LIMITS.ownerControlFrames))
|
|
1530
|
+
throw new ContractError("capacity");
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
class CaptureBudgetLease {
|
|
1535
|
+
resize;
|
|
1536
|
+
forget;
|
|
1537
|
+
value;
|
|
1538
|
+
state = "reserved";
|
|
1539
|
+
constructor(resize, forget, value) {
|
|
1540
|
+
this.resize = resize;
|
|
1541
|
+
this.forget = forget;
|
|
1542
|
+
this.value = value;
|
|
1543
|
+
}
|
|
1544
|
+
get budget() {
|
|
1545
|
+
return { ...this.value };
|
|
1546
|
+
}
|
|
1547
|
+
grow(input) {
|
|
1548
|
+
if (this.state !== "reserved")
|
|
1549
|
+
throw new ContractError("conflict");
|
|
1550
|
+
const extra = decodeCaptureBudget(input);
|
|
1551
|
+
if (extra.lane !== this.value.lane)
|
|
1552
|
+
throw new ContractError("invalid");
|
|
1553
|
+
const next = decodeCaptureBudget({
|
|
1554
|
+
lane: extra.lane,
|
|
1555
|
+
sourceFrames: extra.sourceFrames + this.value.sourceFrames,
|
|
1556
|
+
retainedBytes: extra.retainedBytes + this.value.retainedBytes,
|
|
1557
|
+
outputBytes: extra.outputBytes + this.value.outputBytes,
|
|
1558
|
+
outputChunks: extra.outputChunks + this.value.outputChunks
|
|
1559
|
+
});
|
|
1560
|
+
this.resize(next);
|
|
1561
|
+
this.value = next;
|
|
1562
|
+
}
|
|
1563
|
+
beginWorker(input) {
|
|
1564
|
+
if (this.state !== "reserved")
|
|
1565
|
+
throw new ContractError("conflict");
|
|
1566
|
+
this.size(input);
|
|
1567
|
+
const value = decodeRecordingInput(input);
|
|
1568
|
+
this.chunks(value.events.length);
|
|
1569
|
+
if (this.value.lane === "control" && value.events.some((e) => !["ready", "capture-status", "worker-failure", "final"].includes(e.event.kind)))
|
|
1570
|
+
throw new ContractError("invalid");
|
|
1571
|
+
this.state = "in-flight";
|
|
1572
|
+
return value;
|
|
1573
|
+
}
|
|
1574
|
+
beginOwner(input) {
|
|
1575
|
+
if (this.state !== "reserved")
|
|
1576
|
+
throw new ContractError("conflict");
|
|
1577
|
+
this.size(input);
|
|
1578
|
+
const value = decodeOwnerRecordingInput(input);
|
|
1579
|
+
this.chunks(value.events.length);
|
|
1580
|
+
if (this.value.sourceFrames !== 0 || this.value.lane === "control" && value.events.some((e) => e.kind !== "fact"))
|
|
1581
|
+
throw new ContractError("invalid");
|
|
1582
|
+
this.state = "in-flight";
|
|
1583
|
+
return value;
|
|
1584
|
+
}
|
|
1585
|
+
size(input) {
|
|
1586
|
+
if (utf8Bytes(canonicalJson(input, this.value.outputBytes)) > this.value.outputBytes)
|
|
1587
|
+
throw new ContractError("capacity");
|
|
1588
|
+
}
|
|
1589
|
+
chunks(count) {
|
|
1590
|
+
if (count > this.value.outputChunks)
|
|
1591
|
+
throw new ContractError("capacity");
|
|
1592
|
+
}
|
|
1593
|
+
release() {
|
|
1594
|
+
if (this.state !== "reserved")
|
|
1595
|
+
throw new ContractError("conflict");
|
|
1596
|
+
this.state = "released";
|
|
1597
|
+
this.forget();
|
|
1598
|
+
}
|
|
1599
|
+
settled() {
|
|
1600
|
+
if (this.state !== "in-flight")
|
|
1601
|
+
throw new ContractError("conflict");
|
|
1602
|
+
this.state = "released";
|
|
1603
|
+
this.forget();
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
// src/service/contracts/models.ts
|
|
1607
|
+
function decodeModelCandidate(value) {
|
|
1608
|
+
const o = closed(value, [
|
|
1609
|
+
"provider",
|
|
1610
|
+
"model",
|
|
1611
|
+
"api",
|
|
1612
|
+
"thinking",
|
|
1613
|
+
"eligibility",
|
|
1614
|
+
...Object.hasOwn(value ?? {}, "images") ? ["images"] : []
|
|
1615
|
+
]);
|
|
1616
|
+
const candidate = {
|
|
1617
|
+
...o.images === undefined ? {} : { images: bool(o.images) },
|
|
1618
|
+
provider: text(o.provider, 128, true),
|
|
1619
|
+
model: text(o.model, 256, true),
|
|
1620
|
+
api: nullable(o.api, (v) => oneOf(v, modelApis)),
|
|
1621
|
+
thinking: list(o.thinking, 7, (v) => {
|
|
1622
|
+
const t = closed(v, ["level", "selectable"]);
|
|
1623
|
+
return {
|
|
1624
|
+
level: oneOf(t.level, thinkingLevels),
|
|
1625
|
+
selectable: bool(t.selectable)
|
|
1626
|
+
};
|
|
1627
|
+
}),
|
|
1628
|
+
eligibility: oneOf(o.eligibility, [
|
|
1629
|
+
"candidate",
|
|
1630
|
+
"unsupported",
|
|
1631
|
+
"auth-unavailable"
|
|
1632
|
+
])
|
|
1633
|
+
};
|
|
1634
|
+
if (new Set(candidate.thinking.map((t) => t.level)).size !== candidate.thinking.length || candidate.thinking.some((t) => t.selectable && (candidate.api === null || candidate.eligibility !== "candidate")) || candidate.eligibility === "candidate" && !candidate.thinking.some((t) => t.selectable))
|
|
1635
|
+
invalid();
|
|
1636
|
+
return candidate;
|
|
1637
|
+
}
|
|
1638
|
+
function catalogOffers(entries, selector) {
|
|
1639
|
+
return entries.some((e) => e.provider === selector.provider && e.model === selector.model && e.api === selector.api && e.thinking.some((t) => t.selectable && t.level === selector.thinking));
|
|
1640
|
+
}
|
|
1641
|
+
function decodeModelPreview(value) {
|
|
1642
|
+
canonicalJson({ kind: "ok", value }, LIMITS.pageBytes);
|
|
1643
|
+
const o = closed(value, ["status", "entries", "withheld", "remembered"]);
|
|
1644
|
+
const entries = list(o.entries, LIMITS.maxPageEntries, decodeModelCandidate);
|
|
1645
|
+
const remembered = nullable(o.remembered, decodeModelSelector);
|
|
1646
|
+
const status = oneOf(o.status, ["complete", "capacity"]);
|
|
1647
|
+
const withheld = integer(o.withheld, 0, LIMITS.maxPageEntries);
|
|
1648
|
+
if (status === "capacity" && (entries.length || withheld) || entries.length + withheld > LIMITS.maxPageEntries || new Set(entries.map((e) => canonicalJson([e.provider, e.model]))).size !== entries.length || remembered && !catalogOffers(entries, remembered))
|
|
1649
|
+
invalid();
|
|
1650
|
+
return {
|
|
1651
|
+
status,
|
|
1652
|
+
entries,
|
|
1653
|
+
withheld,
|
|
1654
|
+
remembered
|
|
1655
|
+
};
|
|
1656
|
+
}
|
|
1657
|
+
// src/service/private-files.ts
|
|
1658
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
1659
|
+
import {
|
|
1660
|
+
closeSync as closeSync2,
|
|
1661
|
+
constants as constants2,
|
|
1662
|
+
fstatSync as fstatSync2,
|
|
1663
|
+
fsyncSync,
|
|
1664
|
+
lstatSync as lstatSync2,
|
|
1665
|
+
mkdirSync as mkdirSync2,
|
|
1666
|
+
openSync as openSync2,
|
|
1667
|
+
readSync as readSync2,
|
|
1668
|
+
renameSync,
|
|
1669
|
+
unlinkSync,
|
|
1670
|
+
writeFileSync
|
|
1671
|
+
} from "node:fs";
|
|
1672
|
+
import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
|
|
1673
|
+
// src/workspace.ts
|
|
1674
|
+
import {
|
|
1675
|
+
closeSync,
|
|
1676
|
+
constants,
|
|
1677
|
+
fstatSync,
|
|
1678
|
+
lstatSync,
|
|
1679
|
+
mkdirSync,
|
|
1680
|
+
openSync,
|
|
1681
|
+
readSync,
|
|
1682
|
+
realpathSync
|
|
1683
|
+
} from "node:fs";
|
|
1684
|
+
import {
|
|
1685
|
+
dirname,
|
|
1686
|
+
isAbsolute,
|
|
1687
|
+
join,
|
|
1688
|
+
parse,
|
|
1689
|
+
relative,
|
|
1690
|
+
resolve,
|
|
1691
|
+
sep
|
|
1692
|
+
} from "node:path";
|
|
1693
|
+
|
|
1694
|
+
// src/data-shapes.ts
|
|
1695
|
+
function object(value) {
|
|
1696
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
// src/workspace.ts
|
|
1700
|
+
function absent(error) {
|
|
1701
|
+
return object(error) && error.code === "ENOENT";
|
|
1702
|
+
}
|
|
1703
|
+
function safeDirectory(path, create = false, inspectExisting) {
|
|
1704
|
+
const full = resolve(path);
|
|
1705
|
+
const root = parse(full).root;
|
|
1706
|
+
if (inspectExisting) {
|
|
1707
|
+
const st = lstatSync(root);
|
|
1708
|
+
if (!st.isDirectory() || st.isSymbolicLink())
|
|
1709
|
+
throw new Error("Unsafe directory");
|
|
1710
|
+
inspectExisting(root, st);
|
|
1711
|
+
}
|
|
1712
|
+
let at = root;
|
|
1713
|
+
for (const part of full.slice(root.length).split(sep).filter(Boolean)) {
|
|
1714
|
+
at = join(at, part);
|
|
1715
|
+
let existing;
|
|
1716
|
+
try {
|
|
1717
|
+
const checked = lstatSync(at);
|
|
1718
|
+
if (!checked.isDirectory() || checked.isSymbolicLink())
|
|
1719
|
+
throw new Error("Unsafe directory");
|
|
1720
|
+
existing = checked;
|
|
1721
|
+
} catch (error) {
|
|
1722
|
+
if (!absent(error))
|
|
1723
|
+
throw error;
|
|
1724
|
+
if (!create)
|
|
1725
|
+
return false;
|
|
1726
|
+
try {
|
|
1727
|
+
mkdirSync(at, { mode: 448 });
|
|
1728
|
+
} catch (mkdirError) {
|
|
1729
|
+
if (!object(mkdirError) || mkdirError.code !== "EEXIST")
|
|
1730
|
+
throw mkdirError;
|
|
1731
|
+
}
|
|
1732
|
+
const created = lstatSync(at);
|
|
1733
|
+
if (!created.isDirectory() || created.isSymbolicLink())
|
|
1734
|
+
throw new Error("Unsafe directory");
|
|
1735
|
+
}
|
|
1736
|
+
if (existing)
|
|
1737
|
+
inspectExisting?.(at, existing);
|
|
1738
|
+
}
|
|
1739
|
+
return true;
|
|
1740
|
+
}
|
|
1741
|
+
var transientWindows = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
1742
|
+
function retryWindowsFileOperation(operation, recheck) {
|
|
1743
|
+
if (process.platform !== "win32")
|
|
1744
|
+
return operation();
|
|
1745
|
+
const deadline = performance.now() + 2000;
|
|
1746
|
+
for (let delay = 2;; delay = Math.min(delay * 2, 50)) {
|
|
1747
|
+
try {
|
|
1748
|
+
return operation();
|
|
1749
|
+
} catch (error) {
|
|
1750
|
+
if (!object(error) || !transientWindows.has(String(error.code)) || performance.now() >= deadline)
|
|
1751
|
+
throw error;
|
|
1752
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay);
|
|
1753
|
+
recheck?.();
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
// src/service/private-files.ts
|
|
1759
|
+
var METADATA_BYTES = 16 * 1024;
|
|
1760
|
+
var REGISTRY_BYTES = 1024 * 1024;
|
|
1761
|
+
function refused() {
|
|
1762
|
+
throw new ContractError("corrupt-selected");
|
|
1763
|
+
}
|
|
1764
|
+
function hash(bytes) {
|
|
1765
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
1766
|
+
}
|
|
1767
|
+
function privateMode(st, ownerOnly = true) {
|
|
1768
|
+
if (process.platform !== "win32" && (ownerOnly && (st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
|
|
1769
|
+
refused();
|
|
1770
|
+
}
|
|
1771
|
+
function same(a, b) {
|
|
1772
|
+
return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.ctimeMs === b.ctimeMs && a.mtimeMs === b.mtimeMs && a.mode === b.mode && a.uid === b.uid && a.nlink === b.nlink;
|
|
1773
|
+
}
|
|
1774
|
+
function missing(error) {
|
|
1775
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
1776
|
+
}
|
|
1777
|
+
var job = 0;
|
|
1778
|
+
var advancing = false;
|
|
1779
|
+
function currentJob() {
|
|
1780
|
+
if (!advancing) {
|
|
1781
|
+
advancing = true;
|
|
1782
|
+
queueMicrotask(() => {
|
|
1783
|
+
job++;
|
|
1784
|
+
advancing = false;
|
|
1785
|
+
});
|
|
1786
|
+
}
|
|
1787
|
+
return job;
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
class DirectoryWalks {
|
|
1791
|
+
job = currentJob();
|
|
1792
|
+
walked = new Map;
|
|
1793
|
+
open() {
|
|
1794
|
+
if (this.job === job)
|
|
1795
|
+
return true;
|
|
1796
|
+
this.walked.clear();
|
|
1797
|
+
return false;
|
|
1798
|
+
}
|
|
1799
|
+
remember(path, st) {
|
|
1800
|
+
if (this.open())
|
|
1801
|
+
this.walked.set(path, { dev: st.dev, ino: st.ino });
|
|
1802
|
+
}
|
|
1803
|
+
reuse(path, ownerOnly = true) {
|
|
1804
|
+
const walked = this.open() ? this.walked.get(path) : undefined;
|
|
1805
|
+
if (!walked)
|
|
1806
|
+
return false;
|
|
1807
|
+
let st;
|
|
1808
|
+
try {
|
|
1809
|
+
st = lstatSync2(path);
|
|
1810
|
+
} catch (error) {
|
|
1811
|
+
if (!missing(error))
|
|
1812
|
+
throw error;
|
|
1813
|
+
this.walked.delete(path);
|
|
1814
|
+
return false;
|
|
1815
|
+
}
|
|
1816
|
+
if (!st.isDirectory() || st.isSymbolicLink() || st.dev !== walked.dev || st.ino !== walked.ino) {
|
|
1817
|
+
this.walked.delete(path);
|
|
1818
|
+
return false;
|
|
1819
|
+
}
|
|
1820
|
+
privateMode(st, ownerOnly);
|
|
1821
|
+
return true;
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
class PrivateFiles {
|
|
1826
|
+
namespace;
|
|
1827
|
+
ownerOnly;
|
|
1828
|
+
constructor(namespace, ownerOnly = true) {
|
|
1829
|
+
this.namespace = namespace;
|
|
1830
|
+
this.ownerOnly = ownerOnly;
|
|
1831
|
+
}
|
|
1832
|
+
directory(path, create = false, walks) {
|
|
1833
|
+
const tail = relative2(this.namespace, path);
|
|
1834
|
+
if (isAbsolute2(tail) || tail === ".." || tail.startsWith(`..${sep2}`))
|
|
1835
|
+
refused();
|
|
1836
|
+
if (!create) {
|
|
1837
|
+
const full = resolve2(path);
|
|
1838
|
+
if (walks?.reuse(full, this.ownerOnly))
|
|
1839
|
+
return true;
|
|
1840
|
+
const namespace = resolve2(this.namespace);
|
|
1841
|
+
let inside = false, last;
|
|
1842
|
+
const found = safeDirectory(path, false, (at2, st) => {
|
|
1843
|
+
if (at2 === namespace)
|
|
1844
|
+
inside = true;
|
|
1845
|
+
if (inside)
|
|
1846
|
+
privateMode(st, this.ownerOnly);
|
|
1847
|
+
last = st;
|
|
1848
|
+
});
|
|
1849
|
+
if (found && last)
|
|
1850
|
+
walks?.remember(full, last);
|
|
1851
|
+
return found;
|
|
1852
|
+
}
|
|
1853
|
+
if (!safeDirectory(this.namespace, true))
|
|
1854
|
+
return false;
|
|
1855
|
+
privateMode(lstatSync2(this.namespace), this.ownerOnly);
|
|
1856
|
+
let at = this.namespace;
|
|
1857
|
+
for (const part of tail.split(sep2).filter(Boolean)) {
|
|
1858
|
+
at = join2(at, part);
|
|
1859
|
+
let st;
|
|
1860
|
+
try {
|
|
1861
|
+
st = lstatSync2(at);
|
|
1862
|
+
} catch (error) {
|
|
1863
|
+
if (!missing(error))
|
|
1864
|
+
throw error;
|
|
1865
|
+
try {
|
|
1866
|
+
mkdirSync2(at, { mode: 448 });
|
|
1867
|
+
} catch (mkdirError) {
|
|
1868
|
+
if (!(mkdirError instanceof Error && ("code" in mkdirError) && mkdirError.code === "EEXIST"))
|
|
1869
|
+
throw mkdirError;
|
|
1870
|
+
}
|
|
1871
|
+
st = lstatSync2(at);
|
|
1872
|
+
}
|
|
1873
|
+
if (!st.isDirectory() || st.isSymbolicLink())
|
|
1874
|
+
throw new Error("Unsafe directory");
|
|
1875
|
+
privateMode(st, this.ownerOnly);
|
|
1876
|
+
}
|
|
1877
|
+
return true;
|
|
1878
|
+
}
|
|
1879
|
+
read(path, maximum = METADATA_BYTES, walks) {
|
|
1880
|
+
if (!this.directory(dirname2(path), false, walks))
|
|
1881
|
+
return;
|
|
1882
|
+
let before;
|
|
1883
|
+
try {
|
|
1884
|
+
before = lstatSync2(path);
|
|
1885
|
+
} catch (error) {
|
|
1886
|
+
if (missing(error))
|
|
1887
|
+
return;
|
|
1888
|
+
return refused();
|
|
1889
|
+
}
|
|
1890
|
+
if (!before.isFile() || before.nlink !== 1 || before.size > maximum)
|
|
1891
|
+
refused();
|
|
1892
|
+
privateMode(before, this.ownerOnly);
|
|
1893
|
+
const fd = openSync2(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
|
|
1894
|
+
try {
|
|
1895
|
+
const opened = fstatSync2(fd);
|
|
1896
|
+
if (!same(before, opened))
|
|
1897
|
+
refused();
|
|
1898
|
+
const buffer = Buffer.alloc(opened.size + 1);
|
|
1899
|
+
let size = 0;
|
|
1900
|
+
while (size < buffer.length) {
|
|
1901
|
+
const n = readSync2(fd, buffer, size, buffer.length - size, null);
|
|
1902
|
+
if (!n)
|
|
1903
|
+
break;
|
|
1904
|
+
size += n;
|
|
1905
|
+
}
|
|
1906
|
+
const bytes = buffer.subarray(0, size);
|
|
1907
|
+
if (size !== opened.size || !same(opened, fstatSync2(fd)) || !same(opened, lstatSync2(path)))
|
|
1908
|
+
refused();
|
|
1909
|
+
return { bytes, identity: hash(bytes), stamp: stamp(opened) };
|
|
1910
|
+
} finally {
|
|
1911
|
+
closeSync2(fd);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
assert(path, expected, maximum = METADATA_BYTES, walks) {
|
|
1915
|
+
const current = this.read(path, maximum, walks);
|
|
1916
|
+
if (current?.identity !== expected?.identity || current?.stamp !== expected?.stamp)
|
|
1917
|
+
throw new ContractError("conflict");
|
|
1918
|
+
}
|
|
1919
|
+
create(path, bytes, maximum = METADATA_BYTES) {
|
|
1920
|
+
if (Buffer.byteLength(bytes) > maximum)
|
|
1921
|
+
throw new ContractError("oversize");
|
|
1922
|
+
this.directory(dirname2(path), true);
|
|
1923
|
+
const fd = retryWindowsFileOperation(() => openSync2(path, "wx", 384));
|
|
1924
|
+
try {
|
|
1925
|
+
writeFileSync(fd, bytes);
|
|
1926
|
+
fsyncSync(fd);
|
|
1927
|
+
} finally {
|
|
1928
|
+
closeSync2(fd);
|
|
1929
|
+
}
|
|
1930
|
+
this.syncDirectory(dirname2(path));
|
|
1931
|
+
const result = this.read(path, maximum);
|
|
1932
|
+
if (!result || result.identity !== hash(bytes))
|
|
1933
|
+
refused();
|
|
1934
|
+
return result;
|
|
1935
|
+
}
|
|
1936
|
+
replace(path, expected, bytes, maximum = METADATA_BYTES) {
|
|
1937
|
+
this.assert(path, expected, maximum);
|
|
1938
|
+
const temporary = join2(dirname2(path), `pending-${randomUUID()}.json`);
|
|
1939
|
+
this.create(temporary, bytes, maximum);
|
|
1940
|
+
this.assert(path, expected, maximum);
|
|
1941
|
+
retryWindowsFileOperation(() => renameSync(temporary, path), () => this.assert(path, expected, maximum));
|
|
1942
|
+
this.syncDirectory(dirname2(path));
|
|
1943
|
+
const result = this.read(path, maximum);
|
|
1944
|
+
if (!result || result.identity !== hash(bytes))
|
|
1945
|
+
refused();
|
|
1946
|
+
return result;
|
|
1947
|
+
}
|
|
1948
|
+
remove(path, expected, maximum = METADATA_BYTES) {
|
|
1949
|
+
this.assert(path, expected, maximum);
|
|
1950
|
+
retryWindowsFileOperation(() => unlinkSync(path), () => this.assert(path, expected, maximum));
|
|
1951
|
+
this.syncDirectory(dirname2(path));
|
|
1952
|
+
}
|
|
1953
|
+
syncDirectory(path) {
|
|
1954
|
+
if (process.platform === "win32")
|
|
1955
|
+
return;
|
|
1956
|
+
const fd = openSync2(path, constants2.O_RDONLY | constants2.O_DIRECTORY);
|
|
1957
|
+
try {
|
|
1958
|
+
fsyncSync(fd);
|
|
1959
|
+
} finally {
|
|
1960
|
+
closeSync2(fd);
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
function stamp(st) {
|
|
1965
|
+
return [
|
|
1966
|
+
st.dev,
|
|
1967
|
+
st.ino,
|
|
1968
|
+
st.size,
|
|
1969
|
+
st.mode,
|
|
1970
|
+
st.uid,
|
|
1971
|
+
st.nlink,
|
|
1972
|
+
st.ctimeMs,
|
|
1973
|
+
st.mtimeMs
|
|
1974
|
+
].join(":");
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
// src/service/model-config.ts
|
|
1978
|
+
var CONFIG_BYTES = 1024 * 1024;
|
|
1979
|
+
var ENTRY_LIMIT = 256;
|
|
1980
|
+
function refuse() {
|
|
1981
|
+
throw new ContractError("corrupt-selected");
|
|
1982
|
+
}
|
|
1983
|
+
function data(value) {
|
|
1984
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1985
|
+
refuse();
|
|
1986
|
+
if (![null, Object.prototype].includes(Object.getPrototypeOf(value)))
|
|
1987
|
+
refuse();
|
|
1988
|
+
const out = Object.create(null);
|
|
1989
|
+
const keys = Reflect.ownKeys(value);
|
|
1990
|
+
if (keys.length > ENTRY_LIMIT)
|
|
1991
|
+
refuse();
|
|
1992
|
+
for (const key of keys) {
|
|
1993
|
+
const d = Object.getOwnPropertyDescriptor(value, key);
|
|
1994
|
+
if (typeof key !== "string" || !d || !("value" in d) || !d.enumerable)
|
|
1995
|
+
refuse();
|
|
1996
|
+
if (["__proto__", "constructor", "prototype"].includes(key))
|
|
1997
|
+
refuse();
|
|
1998
|
+
out[key] = d.value;
|
|
1999
|
+
}
|
|
2000
|
+
return out;
|
|
2001
|
+
}
|
|
2002
|
+
function string(value) {
|
|
2003
|
+
if (typeof value !== "string" || !value || value.includes("\x00"))
|
|
2004
|
+
refuse();
|
|
2005
|
+
return value;
|
|
2006
|
+
}
|
|
2007
|
+
function environment(value) {
|
|
2008
|
+
const out = Object.create(null);
|
|
2009
|
+
for (const [name, entry] of Object.entries(data(value))) {
|
|
2010
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
|
|
2011
|
+
refuse();
|
|
2012
|
+
if (/(?:_FILE|_PATH|_CREDENTIALS)$/.test(name))
|
|
2013
|
+
throw new ContractError("unsupported-context");
|
|
2014
|
+
if (typeof entry !== "string" || entry.includes("\x00"))
|
|
2015
|
+
refuse();
|
|
2016
|
+
out[name] = entry;
|
|
2017
|
+
}
|
|
2018
|
+
return out;
|
|
2019
|
+
}
|
|
2020
|
+
function captureEnvironment(value) {
|
|
2021
|
+
const out = Object.create(null);
|
|
2022
|
+
const names = Reflect.ownKeys(value);
|
|
2023
|
+
if (names.length > 4096)
|
|
2024
|
+
throw new ContractError("oversize");
|
|
2025
|
+
let bytes = 0;
|
|
2026
|
+
for (const name of names) {
|
|
2027
|
+
const d = Object.getOwnPropertyDescriptor(value, name);
|
|
2028
|
+
if (typeof name !== "string" || !d || !("value" in d) || d.value !== undefined && typeof d.value !== "string")
|
|
2029
|
+
refuse();
|
|
2030
|
+
bytes += Buffer.byteLength(name) + Buffer.byteLength(d.value ?? "");
|
|
2031
|
+
if (bytes > CONFIG_BYTES)
|
|
2032
|
+
throw new ContractError("oversize");
|
|
2033
|
+
out[name] = d.value;
|
|
2034
|
+
}
|
|
2035
|
+
return Object.freeze(out);
|
|
2036
|
+
}
|
|
2037
|
+
function piSource(agentDir, home, cwd, env) {
|
|
2038
|
+
if (!isAbsolute3(home) || !isAbsolute3(cwd))
|
|
2039
|
+
refuse();
|
|
2040
|
+
let selected = agentDir ?? env.PI_CODING_AGENT_DIR ?? join3(home, ".pi", "agent");
|
|
2041
|
+
if (!selected || selected.includes("\x00"))
|
|
2042
|
+
refuse();
|
|
2043
|
+
if (selected === "~" || selected.startsWith("~/"))
|
|
2044
|
+
selected = home + selected.slice(1);
|
|
2045
|
+
selected = resolve3(cwd, selected);
|
|
2046
|
+
try {
|
|
2047
|
+
const directory = join3(realpathSync2(dirname3(selected)), selected.slice(dirname3(selected).length + 1));
|
|
2048
|
+
const st = lstatSync3(directory);
|
|
2049
|
+
if (!st.isDirectory() || st.isSymbolicLink())
|
|
2050
|
+
refuse();
|
|
2051
|
+
const files = new PrivateFiles(directory, false);
|
|
2052
|
+
if (!files.directory(directory))
|
|
2053
|
+
refuse();
|
|
2054
|
+
return {
|
|
2055
|
+
directory,
|
|
2056
|
+
files,
|
|
2057
|
+
authPath: join3(directory, "auth.json"),
|
|
2058
|
+
modelsPath: join3(directory, "models.json")
|
|
2059
|
+
};
|
|
2060
|
+
} catch (error) {
|
|
2061
|
+
throw new PiSourceRefusal({
|
|
2062
|
+
file: "agent-directory",
|
|
2063
|
+
check: "file",
|
|
2064
|
+
field: null,
|
|
2065
|
+
reason: fileReason(selected, true)
|
|
2066
|
+
}, error instanceof ContractError ? error.code : "unavailable");
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
function templateNames(value) {
|
|
2070
|
+
const text2 = string(value);
|
|
2071
|
+
if (text2.startsWith("!"))
|
|
2072
|
+
throw new ContractError("unsupported-context");
|
|
2073
|
+
const names = new Set;
|
|
2074
|
+
for (let i = 0;i < text2.length; ) {
|
|
2075
|
+
const dollar = text2.indexOf("$", i);
|
|
2076
|
+
if (dollar < 0)
|
|
2077
|
+
break;
|
|
2078
|
+
const next = text2[dollar + 1];
|
|
2079
|
+
if (next === "$" || next === "!") {
|
|
2080
|
+
i = dollar + 2;
|
|
2081
|
+
} else if (next === "{") {
|
|
2082
|
+
const end = text2.indexOf("}", dollar + 2);
|
|
2083
|
+
if (end < 0) {
|
|
2084
|
+
i = dollar + 1;
|
|
2085
|
+
continue;
|
|
2086
|
+
}
|
|
2087
|
+
const name = text2.slice(dollar + 2, end);
|
|
2088
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
|
|
2089
|
+
names.add(name);
|
|
2090
|
+
i = end + 1;
|
|
2091
|
+
} else {
|
|
2092
|
+
const name = text2.slice(dollar + 1).match(/^[A-Za-z_][A-Za-z0-9_]*/)?.[0];
|
|
2093
|
+
if (name)
|
|
2094
|
+
names.add(name);
|
|
2095
|
+
i = dollar + 1 + (name?.length ?? 0);
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
return [...names];
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
class PiSourceRefusal extends ContractError {
|
|
2102
|
+
problem;
|
|
2103
|
+
constructor(problem, code = "corrupt-selected") {
|
|
2104
|
+
super(code);
|
|
2105
|
+
this.problem = problem;
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
class FieldRefusal extends ContractError {
|
|
2110
|
+
field;
|
|
2111
|
+
reason;
|
|
2112
|
+
constructor(field, reason, code = "corrupt-selected") {
|
|
2113
|
+
super(code);
|
|
2114
|
+
this.field = field;
|
|
2115
|
+
this.reason = reason;
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
function fail(field, reason, code) {
|
|
2119
|
+
throw new FieldRefusal(field, reason, code);
|
|
2120
|
+
}
|
|
2121
|
+
function child(at, key) {
|
|
2122
|
+
if (typeof key === "number")
|
|
2123
|
+
return `${at}[${key}]`;
|
|
2124
|
+
if (/^[A-Za-z_$][\w$]{0,63}$/.test(key))
|
|
2125
|
+
return at ? `${at}.${key}` : key;
|
|
2126
|
+
return /^[\x21-\x7e]{1,64}$/.test(key) && !/["\\]/.test(key) ? `${at}["${key}"]` : `${at}[…]`;
|
|
2127
|
+
}
|
|
2128
|
+
var UNSUPPORTED = "is not a field Cadence's pinned Pi SDK supports";
|
|
2129
|
+
function object2(value, at) {
|
|
2130
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2131
|
+
fail(at, "must be an object");
|
|
2132
|
+
if (Reflect.ownKeys(value).length > ENTRY_LIMIT)
|
|
2133
|
+
fail(at, `has more than ${ENTRY_LIMIT} entries`);
|
|
2134
|
+
try {
|
|
2135
|
+
return data(value);
|
|
2136
|
+
} catch {
|
|
2137
|
+
return fail(at, "must be a plain object without reserved keys");
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
function shape(fields2, required = [], retired = {}) {
|
|
2141
|
+
const check = (value, at) => {
|
|
2142
|
+
const o = object2(value, at);
|
|
2143
|
+
for (const key of Object.keys(o))
|
|
2144
|
+
if (!Object.hasOwn(fields2, key))
|
|
2145
|
+
fail(child(at, key), Object.hasOwn(retired, key) ? retired[key] : UNSUPPORTED);
|
|
2146
|
+
for (const key of required)
|
|
2147
|
+
if (o[key] === undefined)
|
|
2148
|
+
fail(child(at, key), "is required");
|
|
2149
|
+
for (const [key, field] of Object.entries(fields2))
|
|
2150
|
+
if (o[key] !== undefined)
|
|
2151
|
+
field(o[key], child(at, key));
|
|
2152
|
+
};
|
|
2153
|
+
check.fields = fields2;
|
|
2154
|
+
return check;
|
|
2155
|
+
}
|
|
2156
|
+
function record(entries) {
|
|
2157
|
+
const check = (value, at) => {
|
|
2158
|
+
for (const [key, entry] of Object.entries(object2(value, at)))
|
|
2159
|
+
entries(entry, child(at, key));
|
|
2160
|
+
};
|
|
2161
|
+
check.entries = entries;
|
|
2162
|
+
return check;
|
|
2163
|
+
}
|
|
2164
|
+
function list2(items, maximum = ENTRY_LIMIT) {
|
|
2165
|
+
const check = (value, at) => {
|
|
2166
|
+
if (!Array.isArray(value))
|
|
2167
|
+
fail(at, "must be a list");
|
|
2168
|
+
if (value.length > maximum)
|
|
2169
|
+
fail(at, `has more than ${maximum} entries`);
|
|
2170
|
+
for (const [i, item] of value.entries())
|
|
2171
|
+
items(item, child(at, i));
|
|
2172
|
+
};
|
|
2173
|
+
check.items = items;
|
|
2174
|
+
return check;
|
|
2175
|
+
}
|
|
2176
|
+
function scalarOr(scalar, objectShape, reason) {
|
|
2177
|
+
const check = (value, at) => {
|
|
2178
|
+
if (scalar(value))
|
|
2179
|
+
return;
|
|
2180
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2181
|
+
fail(at, reason);
|
|
2182
|
+
objectShape(value, at);
|
|
2183
|
+
};
|
|
2184
|
+
check.fields = objectShape.fields;
|
|
2185
|
+
return check;
|
|
2186
|
+
}
|
|
2187
|
+
var scalar = (test, reason) => (value, at) => {
|
|
2188
|
+
if (!test(value))
|
|
2189
|
+
fail(at, reason);
|
|
2190
|
+
};
|
|
2191
|
+
var isNumber = (v) => typeof v === "number" && Number.isFinite(v);
|
|
2192
|
+
var isString = (v) => typeof v === "string";
|
|
2193
|
+
var boolean = scalar((v) => typeof v === "boolean", "must be true or false");
|
|
2194
|
+
var number = scalar(isNumber, "must be a number");
|
|
2195
|
+
var positive = scalar((v) => isNumber(v) && v > 0, "must be a number greater than 0");
|
|
2196
|
+
var whole = (maximum = Number.MAX_SAFE_INTEGER) => scalar((v) => Number.isSafeInteger(v) && v >= 1 && v <= maximum, maximum === Number.MAX_SAFE_INTEGER ? "must be a whole number of at least 1" : `must be a whole number from 1 to ${maximum}`);
|
|
2197
|
+
var nonEmpty = scalar((v) => typeof v === "string" && v !== "" && !v.includes("\x00"), "must be a non-empty string");
|
|
2198
|
+
var anyString = scalar(isString, "must be a string");
|
|
2199
|
+
var stringOrNull = scalar((v) => v === null || isString(v), "must be a string or null");
|
|
2200
|
+
var numberOrString = scalar((v) => isNumber(v) || isString(v), "must be a number or a string");
|
|
2201
|
+
var oneOf2 = (...values) => scalar((v) => values.includes(v), `must be ${values.length === 1 ? "" : "one of "}${values.map((v) => JSON.stringify(v)).join(", ")}`);
|
|
2202
|
+
var freeform = scalar((v) => !!v && typeof v === "object" && !Array.isArray(v), "must be an object");
|
|
2203
|
+
var template = (value, at) => {
|
|
2204
|
+
nonEmpty(value, at);
|
|
2205
|
+
if (value.startsWith("!"))
|
|
2206
|
+
fail(at, 'runs a command ("!…"), which Cadence never runs; use a literal value or $VARIABLE', "unsupported-context");
|
|
2207
|
+
};
|
|
2208
|
+
var headerValue = (value, at) => {
|
|
2209
|
+
if (typeof value !== "string" || /[\r\n\0]/.test(value))
|
|
2210
|
+
fail(at, "must be a single-line string");
|
|
2211
|
+
if (value)
|
|
2212
|
+
template(value, at);
|
|
2213
|
+
};
|
|
2214
|
+
var headers = (value, at) => {
|
|
2215
|
+
for (const [name, entry] of Object.entries(object2(value, at))) {
|
|
2216
|
+
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name))
|
|
2217
|
+
fail(child(at, name), "is not a valid HTTP header name");
|
|
2218
|
+
headerValue(entry, child(at, name));
|
|
2219
|
+
}
|
|
2220
|
+
};
|
|
2221
|
+
headers.entries = headerValue;
|
|
2222
|
+
var variableValue = (value, at) => {
|
|
2223
|
+
if (typeof value !== "string" || value.includes("\x00"))
|
|
2224
|
+
fail(at, "must be a string");
|
|
2225
|
+
};
|
|
2226
|
+
var variables = (value, at) => {
|
|
2227
|
+
for (const [name, entry] of Object.entries(object2(value, at))) {
|
|
2228
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
|
|
2229
|
+
fail(child(at, name), "is not a valid environment variable name");
|
|
2230
|
+
if (/(?:_FILE|_PATH|_CREDENTIALS)$/.test(name))
|
|
2231
|
+
fail(child(at, name), "names a file (*_FILE, *_PATH or *_CREDENTIALS), which Cadence does not pass on", "unsupported-context");
|
|
2232
|
+
variableValue(entry, child(at, name));
|
|
2233
|
+
}
|
|
2234
|
+
};
|
|
2235
|
+
variables.entries = variableValue;
|
|
2236
|
+
var LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
2237
|
+
var levels = (each) => shape(Object.fromEntries(LEVELS.map((level) => [level, each])));
|
|
2238
|
+
var RATES = ["input", "output", "cacheRead", "cacheWrite"];
|
|
2239
|
+
var rates = Object.fromEntries(RATES.map((rate) => [rate, number]));
|
|
2240
|
+
var costTiers = list2(shape({ inputTokensAbove: number, ...rates }, ["inputTokensAbove", ...RATES]));
|
|
2241
|
+
var cost = shape({ ...rates, tiers: costTiers }, RATES);
|
|
2242
|
+
var strings = list2(anyString);
|
|
2243
|
+
var percentiles = shape(Object.fromEntries(["p50", "p75", "p90", "p99"].map((p) => [p, number])));
|
|
2244
|
+
var chatTemplate = record(scalarOr((v) => v === null || ["string", "number", "boolean"].includes(typeof v), shape({
|
|
2245
|
+
$var: oneOf2("thinking.enabled", "thinking.effort", "thinking.budget"),
|
|
2246
|
+
omitWhenOff: boolean
|
|
2247
|
+
}, ["$var"]), 'must be a string, number, true/false, null or a {"$var": …} object'));
|
|
2248
|
+
var compat = shape({
|
|
2249
|
+
...Object.fromEntries([
|
|
2250
|
+
"supportsStore",
|
|
2251
|
+
"supportsDeveloperRole",
|
|
2252
|
+
"supportsReasoningEffort",
|
|
2253
|
+
"supportsUsageInStreaming",
|
|
2254
|
+
"supportsFinishReason",
|
|
2255
|
+
"requiresToolResultName",
|
|
2256
|
+
"requiresAssistantAfterToolResult",
|
|
2257
|
+
"requiresThinkingAsText",
|
|
2258
|
+
"requiresReasoningContentOnAssistantMessages",
|
|
2259
|
+
"zaiToolStream",
|
|
2260
|
+
"supportsThinkingTokenBudget",
|
|
2261
|
+
"supportsOpenAIGrammarTools",
|
|
2262
|
+
"supportsMidConvoSystemMessages",
|
|
2263
|
+
"supportsMidConvoToolAdditions",
|
|
2264
|
+
"supportsStrictMode",
|
|
2265
|
+
"sendSessionAffinityHeaders",
|
|
2266
|
+
"supportsLongCacheRetention",
|
|
2267
|
+
"supportsAdditionalTools",
|
|
2268
|
+
"supportsToolSearch",
|
|
2269
|
+
"supportsExplicitPromptCacheMode",
|
|
2270
|
+
"supportsMidConvoEffort",
|
|
2271
|
+
"supportsMaxOutputTokens",
|
|
2272
|
+
"supportsEagerToolInputStreaming",
|
|
2273
|
+
"supportsCacheControlOnTools",
|
|
2274
|
+
"supportsTemperature",
|
|
2275
|
+
"forceAdaptiveThinking",
|
|
2276
|
+
"allowEmptySignature",
|
|
2277
|
+
"supportsStrictTools",
|
|
2278
|
+
"supportsMidConvoToolChanges",
|
|
2279
|
+
"sendImageOptInHeader"
|
|
2280
|
+
].map((key) => [key, boolean])),
|
|
2281
|
+
maxTokensField: oneOf2("max_completion_tokens", "max_tokens"),
|
|
2282
|
+
thinkingFormat: oneOf2("openai", "openrouter", "deepseek", "together", "baseten", "zai", "qwen", "chat-template", "qwen-chat-template", "string-thinking", "ant-ling"),
|
|
2283
|
+
thinkingTokenBudgetField: oneOf2("thinking_token_budget", "thinking_budget", "thinking_budget_tokens"),
|
|
2284
|
+
cacheControlFormat: oneOf2("anthropic"),
|
|
2285
|
+
sessionAffinityFormat: oneOf2("openai", "openai-nosession", "openrouter"),
|
|
2286
|
+
imageInput: oneOf2("assets", "images", "state-image-urls"),
|
|
2287
|
+
vllmPriority: number,
|
|
2288
|
+
chatTemplateKwargs: chatTemplate,
|
|
2289
|
+
chatTemplateArgs: chatTemplate,
|
|
2290
|
+
openRouterRouting: shape({
|
|
2291
|
+
allow_fallbacks: boolean,
|
|
2292
|
+
require_parameters: boolean,
|
|
2293
|
+
data_collection: oneOf2("deny", "allow"),
|
|
2294
|
+
zdr: boolean,
|
|
2295
|
+
enforce_distillable_text: boolean,
|
|
2296
|
+
order: strings,
|
|
2297
|
+
only: strings,
|
|
2298
|
+
ignore: strings,
|
|
2299
|
+
quantizations: strings,
|
|
2300
|
+
sort: scalarOr(isString, shape({ by: anyString, partition: stringOrNull }), "must be a string or an object"),
|
|
2301
|
+
max_price: shape(Object.fromEntries(["prompt", "completion", "image", "audio", "request"].map((k) => [
|
|
2302
|
+
k,
|
|
2303
|
+
numberOrString
|
|
2304
|
+
]))),
|
|
2305
|
+
preferred_min_throughput: scalarOr(isNumber, percentiles, "must be a number or an object"),
|
|
2306
|
+
preferred_max_latency: scalarOr(isNumber, percentiles, "must be a number or an object")
|
|
2307
|
+
}),
|
|
2308
|
+
vercelGatewayRouting: shape({ only: strings, order: strings }),
|
|
2309
|
+
allowedFallbackModels: list2(shape({ provider: nonEmpty, model: nonEmpty, cost }, [
|
|
2310
|
+
"provider",
|
|
2311
|
+
"model",
|
|
2312
|
+
"cost"
|
|
2313
|
+
]), 3)
|
|
2314
|
+
}, [], {
|
|
2315
|
+
reasoningEffortMap: "was replaced in Pi 0.72 by each model's own thinkingLevelMap; move these mappings there (null hides a level the model does not support)"
|
|
2316
|
+
});
|
|
2317
|
+
var modelFields = {
|
|
2318
|
+
id: nonEmpty,
|
|
2319
|
+
name: nonEmpty,
|
|
2320
|
+
api: nonEmpty,
|
|
2321
|
+
baseUrl: nonEmpty,
|
|
2322
|
+
reasoning: boolean,
|
|
2323
|
+
thinkingLevelMap: levels(stringOrNull),
|
|
2324
|
+
input: list2(oneOf2("text", "image")),
|
|
2325
|
+
inputLimits: shape({
|
|
2326
|
+
maxRequestBytes: whole(),
|
|
2327
|
+
images: shape({
|
|
2328
|
+
resize: shape({
|
|
2329
|
+
maxWidth: whole(),
|
|
2330
|
+
maxHeight: whole(),
|
|
2331
|
+
maxBytes: whole(),
|
|
2332
|
+
jpegQuality: whole(100)
|
|
2333
|
+
}),
|
|
2334
|
+
maxPerMessage: whole(),
|
|
2335
|
+
maxPerRequest: whole()
|
|
2336
|
+
})
|
|
2337
|
+
}),
|
|
2338
|
+
cost,
|
|
2339
|
+
promptCache: shape({ short: positive, long: positive }),
|
|
2340
|
+
contextWindow: positive,
|
|
2341
|
+
maxTokens: positive,
|
|
2342
|
+
samplingParams: freeform,
|
|
2343
|
+
samplingParamsByThinkingLevel: levels(freeform),
|
|
2344
|
+
headers,
|
|
2345
|
+
compat
|
|
2346
|
+
};
|
|
2347
|
+
var {
|
|
2348
|
+
id: _id,
|
|
2349
|
+
api: _api,
|
|
2350
|
+
baseUrl: _baseUrl,
|
|
2351
|
+
...overrideFields
|
|
2352
|
+
} = modelFields;
|
|
2353
|
+
var model = shape(modelFields, ["id"]);
|
|
2354
|
+
var models = list2(model);
|
|
2355
|
+
var uniqueModels = (value, at) => {
|
|
2356
|
+
models(value, at);
|
|
2357
|
+
const ids = new Set;
|
|
2358
|
+
value.forEach((entry, i) => {
|
|
2359
|
+
if (ids.has(entry.id))
|
|
2360
|
+
fail(child(child(at, i), "id"), "repeats the id of an earlier model of this provider");
|
|
2361
|
+
ids.add(entry.id);
|
|
2362
|
+
});
|
|
2363
|
+
};
|
|
2364
|
+
uniqueModels.items = model;
|
|
2365
|
+
var MODELS_JSON = shape({
|
|
2366
|
+
$schema: anyString,
|
|
2367
|
+
providers: record(shape({
|
|
2368
|
+
name: nonEmpty,
|
|
2369
|
+
baseUrl: nonEmpty,
|
|
2370
|
+
apiKey: template,
|
|
2371
|
+
api: nonEmpty,
|
|
2372
|
+
oauth: oneOf2("radius"),
|
|
2373
|
+
headers,
|
|
2374
|
+
compat,
|
|
2375
|
+
authHeader: boolean,
|
|
2376
|
+
models: uniqueModels,
|
|
2377
|
+
modelOverrides: record(shape({
|
|
2378
|
+
...overrideFields,
|
|
2379
|
+
cost: shape({ ...rates, tiers: costTiers })
|
|
2380
|
+
}))
|
|
2381
|
+
}))
|
|
2382
|
+
}, ["providers"]);
|
|
2383
|
+
var credential = (value, at) => {
|
|
2384
|
+
const o = object2(value, at);
|
|
2385
|
+
if (o.type === "api_key") {
|
|
2386
|
+
for (const key of Object.keys(o))
|
|
2387
|
+
if (!["type", "key", "env"].includes(key))
|
|
2388
|
+
fail(child(at, key), "is not a field of an api_key credential");
|
|
2389
|
+
if (o.key !== undefined)
|
|
2390
|
+
template(o.key, child(at, "key"));
|
|
2391
|
+
if (o.env !== undefined)
|
|
2392
|
+
variables(o.env, child(at, "env"));
|
|
2393
|
+
} else if (o.type === "oauth") {
|
|
2394
|
+
nonEmpty(o.access, child(at, "access"));
|
|
2395
|
+
nonEmpty(o.refresh, child(at, "refresh"));
|
|
2396
|
+
number(o.expires, child(at, "expires"));
|
|
2397
|
+
if (o.env !== undefined)
|
|
2398
|
+
variables(o.env, child(at, "env"));
|
|
2399
|
+
} else
|
|
2400
|
+
fail(child(at, "type"), 'must be "api_key" or "oauth"');
|
|
2401
|
+
};
|
|
2402
|
+
var AUTH_JSON = record(credential);
|
|
2403
|
+
function piJsonc(input) {
|
|
2404
|
+
let stripped = "";
|
|
2405
|
+
let quoted = false;
|
|
2406
|
+
let escaped = false;
|
|
2407
|
+
for (let i = 0;i < input.length; i++) {
|
|
2408
|
+
const char = input[i];
|
|
2409
|
+
if (!quoted && char === "/" && input[i + 1] === "/") {
|
|
2410
|
+
while (i < input.length && input[i] !== `
|
|
2411
|
+
`)
|
|
2412
|
+
i++;
|
|
2413
|
+
stripped += `
|
|
2414
|
+
`;
|
|
2415
|
+
continue;
|
|
2416
|
+
}
|
|
2417
|
+
stripped += char;
|
|
2418
|
+
if (quoted) {
|
|
2419
|
+
if (escaped)
|
|
2420
|
+
escaped = false;
|
|
2421
|
+
else if (char === "\\")
|
|
2422
|
+
escaped = true;
|
|
2423
|
+
else if (char === '"')
|
|
2424
|
+
quoted = false;
|
|
2425
|
+
} else if (char === '"')
|
|
2426
|
+
quoted = true;
|
|
2427
|
+
}
|
|
2428
|
+
let normalized = "";
|
|
2429
|
+
quoted = false;
|
|
2430
|
+
escaped = false;
|
|
2431
|
+
for (let i = 0;i < stripped.length; i++) {
|
|
2432
|
+
const char = stripped[i];
|
|
2433
|
+
if (!quoted && char === ",") {
|
|
2434
|
+
let next = i + 1;
|
|
2435
|
+
while (/\s/.test(stripped[next] ?? "") && next < stripped.length)
|
|
2436
|
+
next++;
|
|
2437
|
+
if (stripped[next] === "}" || stripped[next] === "]")
|
|
2438
|
+
continue;
|
|
2439
|
+
}
|
|
2440
|
+
normalized += char;
|
|
2441
|
+
if (quoted) {
|
|
2442
|
+
if (escaped)
|
|
2443
|
+
escaped = false;
|
|
2444
|
+
else if (char === "\\")
|
|
2445
|
+
escaped = true;
|
|
2446
|
+
else if (char === '"')
|
|
2447
|
+
quoted = false;
|
|
2448
|
+
} else if (char === '"')
|
|
2449
|
+
quoted = true;
|
|
2450
|
+
}
|
|
2451
|
+
return normalized;
|
|
2452
|
+
}
|
|
2453
|
+
function fileReason(path, directory) {
|
|
2454
|
+
let st;
|
|
2455
|
+
try {
|
|
2456
|
+
st = lstatSync3(path);
|
|
2457
|
+
} catch {
|
|
2458
|
+
return directory ? "does not exist; run pi once to create it, or select another --agent-dir" : "cannot be read";
|
|
2459
|
+
}
|
|
2460
|
+
if (st.isSymbolicLink())
|
|
2461
|
+
return "is a symbolic link; Cadence reads only the real file or directory, not a link to it";
|
|
2462
|
+
if (directory ? !st.isDirectory() : !st.isFile())
|
|
2463
|
+
return directory ? "is not a directory" : "is not a regular file";
|
|
2464
|
+
if (!directory && st.nlink !== 1)
|
|
2465
|
+
return `has ${st.nlink} hard links; Cadence reads only a file with a single link`;
|
|
2466
|
+
if (!directory && st.size > CONFIG_BYTES)
|
|
2467
|
+
return "is larger than 1 MiB";
|
|
2468
|
+
if (process.platform !== "win32" && process.getuid && st.uid !== process.getuid())
|
|
2469
|
+
return "is owned by another user";
|
|
2470
|
+
return directory ? "has a parent directory Cadence cannot use (a symbolic link loop or another user's directory)" : "changed while Cadence was reading it; try again";
|
|
2471
|
+
}
|
|
2472
|
+
function readSource(source, file) {
|
|
2473
|
+
const path = file === "auth.json" ? source.authPath : source.modelsPath;
|
|
2474
|
+
try {
|
|
2475
|
+
return source.files.read(path, CONFIG_BYTES);
|
|
2476
|
+
} catch (error) {
|
|
2477
|
+
throw new PiSourceRefusal({ file, check: "file", field: null, reason: fileReason(path, false) }, error instanceof ContractError ? error.code : "unavailable");
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
function parseSource(snapshot, file) {
|
|
2481
|
+
const refuse2 = (reason) => {
|
|
2482
|
+
throw new PiSourceRefusal({ file, check: "json", field: null, reason });
|
|
2483
|
+
};
|
|
2484
|
+
let text2 = "";
|
|
2485
|
+
try {
|
|
2486
|
+
text2 = new TextDecoder("utf-8", { fatal: true }).decode(snapshot.bytes);
|
|
2487
|
+
} catch {
|
|
2488
|
+
refuse2("is not valid UTF-8 text");
|
|
2489
|
+
}
|
|
2490
|
+
if (file === "models.json")
|
|
2491
|
+
text2 = piJsonc(text2);
|
|
2492
|
+
try {
|
|
2493
|
+
return parseWireJson(text2, CONFIG_BYTES);
|
|
2494
|
+
} catch {
|
|
2495
|
+
const extra = file === "models.json" ? " (beyond JSON, models.json allows only // line comments and trailing commas)" : "";
|
|
2496
|
+
try {
|
|
2497
|
+
JSON.parse(text2);
|
|
2498
|
+
} catch (error) {
|
|
2499
|
+
const line = /\(line (\d+) column \d+\)$/.exec(error instanceof Error ? error.message : "")?.[1];
|
|
2500
|
+
return refuse2(`is not valid JSON${line ? ` near line ${line}` : ""}${extra}`);
|
|
2501
|
+
}
|
|
2502
|
+
return refuse2("has a duplicate key, a NUL character, an unpaired surrogate or nesting deeper than 64 levels");
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
function schemaCheck(file, check, value) {
|
|
2506
|
+
try {
|
|
2507
|
+
check(value, "");
|
|
2508
|
+
} catch (error) {
|
|
2509
|
+
if (!(error instanceof FieldRefusal))
|
|
2510
|
+
throw error;
|
|
2511
|
+
throw new PiSourceRefusal({
|
|
2512
|
+
file,
|
|
2513
|
+
check: "schema",
|
|
2514
|
+
field: error.field || null,
|
|
2515
|
+
reason: error.reason
|
|
2516
|
+
}, error.code);
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
function readPiSnapshot(source) {
|
|
2520
|
+
const { auth, credentials } = readPiAuth(source);
|
|
2521
|
+
const { models: models2, providers } = readPiModels(source);
|
|
2522
|
+
return { auth, models: models2, credentials, providers };
|
|
2523
|
+
}
|
|
2524
|
+
function readPiAuth(source) {
|
|
2525
|
+
const auth = readSource(source, "auth.json");
|
|
2526
|
+
if (!auth)
|
|
2527
|
+
throw new PiSourceRefusal({
|
|
2528
|
+
file: "auth.json",
|
|
2529
|
+
check: "file",
|
|
2530
|
+
field: null,
|
|
2531
|
+
reason: "does not exist; sign in with Pi first (pi, then /login)"
|
|
2532
|
+
});
|
|
2533
|
+
const value = parseSource(auth, "auth.json");
|
|
2534
|
+
schemaCheck("auth.json", AUTH_JSON, value);
|
|
2535
|
+
const credentials = Object.create(null);
|
|
2536
|
+
for (const [provider, credential2] of Object.entries(data(value)))
|
|
2537
|
+
credentials[provider] = data(credential2);
|
|
2538
|
+
return { auth, credentials };
|
|
2539
|
+
}
|
|
2540
|
+
function readPiModels(source) {
|
|
2541
|
+
const models2 = readSource(source, "models.json");
|
|
2542
|
+
const providers = Object.create(null);
|
|
2543
|
+
if (models2) {
|
|
2544
|
+
const value = parseSource(models2, "models.json");
|
|
2545
|
+
schemaCheck("models.json", MODELS_JSON, value);
|
|
2546
|
+
for (const [id, provider] of Object.entries(data(data(value).providers)))
|
|
2547
|
+
providers[id] = data(provider);
|
|
2548
|
+
}
|
|
2549
|
+
return { models: models2, providers };
|
|
2550
|
+
}
|
|
2551
|
+
function sdkRefusal(message) {
|
|
2552
|
+
const problem = (field, reason) => new PiSourceRefusal({ file: "models.json", check: "sdk", field, reason });
|
|
2553
|
+
const schema = /^Invalid models\.json schema:\n {2}- ([A-Za-z0-9_$.:@/+-]{1,200}): (must [A-Za-z0-9 ,'"_=<>.-]{1,120})$/m.exec(message);
|
|
2554
|
+
if (schema)
|
|
2555
|
+
return problem(schema[1], schema[2]);
|
|
2556
|
+
const provider = /^Provider "?([A-Za-z0-9_.:@/+-]{1,64})"?[:,]/m.exec(message)?.[1];
|
|
2557
|
+
const known = [
|
|
2558
|
+
[
|
|
2559
|
+
/no "api" specified/,
|
|
2560
|
+
'has a model with no "api"; set it on the provider or on the model'
|
|
2561
|
+
],
|
|
2562
|
+
[
|
|
2563
|
+
/"baseUrl" is required when defining custom models/,
|
|
2564
|
+
'defines models but has no "baseUrl"'
|
|
2565
|
+
],
|
|
2566
|
+
[
|
|
2567
|
+
/"baseUrl" is required when "oauth" is set/,
|
|
2568
|
+
'sets "oauth" but has no "baseUrl"'
|
|
2569
|
+
],
|
|
2570
|
+
[
|
|
2571
|
+
/must specify "baseUrl"/,
|
|
2572
|
+
"must set baseUrl, headers, compat, modelOverrides or models"
|
|
2573
|
+
],
|
|
2574
|
+
[/invalid contextWindow/, "has a model with an invalid contextWindow"],
|
|
2575
|
+
[/invalid maxTokens/, "has a model with an invalid maxTokens"]
|
|
2576
|
+
];
|
|
2577
|
+
for (const [pattern, reason] of known)
|
|
2578
|
+
if (pattern.test(message))
|
|
2579
|
+
return problem(provider ? child("providers", provider) : null, reason);
|
|
2580
|
+
return problem(null, "was refused by the Pi SDK; run pi in a terminal to see its own message");
|
|
2581
|
+
}
|
|
2582
|
+
function sourceIdentity(snapshot, provider) {
|
|
2583
|
+
const credential2 = snapshot.credentials[provider];
|
|
2584
|
+
if (credential2?.type === "oauth") {
|
|
2585
|
+
const { access: _a, refresh: _r, expires: _e, ...identity } = credential2;
|
|
2586
|
+
return stablePrivate(identity);
|
|
2587
|
+
}
|
|
2588
|
+
return stablePrivate(credential2 ?? null);
|
|
2589
|
+
}
|
|
2590
|
+
function selectedEnvironment(snapshot, provider, model2, launch) {
|
|
2591
|
+
const credential2 = snapshot.credentials[provider];
|
|
2592
|
+
const scoped = credential2?.env === undefined ? {} : environment(credential2.env);
|
|
2593
|
+
const config = snapshot.providers[provider];
|
|
2594
|
+
const values = [];
|
|
2595
|
+
if (credential2?.type === "api_key" && credential2.key !== undefined)
|
|
2596
|
+
values.push(credential2.key);
|
|
2597
|
+
if (config?.apiKey !== undefined)
|
|
2598
|
+
values.push(config.apiKey);
|
|
2599
|
+
if (config?.headers)
|
|
2600
|
+
values.push(...Object.values(data(config.headers)));
|
|
2601
|
+
const definition = Array.isArray(config?.models) ? config.models.find((m) => data(m).id === model2) : undefined;
|
|
2602
|
+
const override = config?.modelOverrides ? data(config.modelOverrides)[model2] : undefined;
|
|
2603
|
+
for (const entry of [definition, override])
|
|
2604
|
+
if (entry && data(entry).headers)
|
|
2605
|
+
values.push(...Object.values(data(data(entry).headers)));
|
|
2606
|
+
const env = { ...scoped };
|
|
2607
|
+
for (const value of values) {
|
|
2608
|
+
if (value === "")
|
|
2609
|
+
continue;
|
|
2610
|
+
for (const name of templateNames(value)) {
|
|
2611
|
+
if (/(?:_FILE|_PATH|_CREDENTIALS)$/.test(name))
|
|
2612
|
+
throw new ContractError("unsupported-context");
|
|
2613
|
+
const selected = scoped[name] || launch[name];
|
|
2614
|
+
if (!selected)
|
|
2615
|
+
throw new ContractError("auth-unavailable");
|
|
2616
|
+
env[name] = selected;
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
return env;
|
|
2620
|
+
}
|
|
2621
|
+
function sameModels(a, b) {
|
|
2622
|
+
return a.models?.identity === b.models?.identity && a.models?.stamp === b.models?.stamp;
|
|
2623
|
+
}
|
|
2624
|
+
function stablePrivate(value) {
|
|
2625
|
+
const sorted = (v) => {
|
|
2626
|
+
if (Array.isArray(v))
|
|
2627
|
+
return v.map(sorted);
|
|
2628
|
+
if (v && typeof v === "object")
|
|
2629
|
+
return Object.fromEntries(Object.entries(data(v)).sort(([a], [b]) => a.localeCompare(b)).map(([k, entry]) => [k, sorted(entry)]));
|
|
2630
|
+
return v;
|
|
2631
|
+
};
|
|
2632
|
+
return JSON.stringify(sorted(value));
|
|
2633
|
+
}
|
|
2634
|
+
function clonePrivate(value) {
|
|
2635
|
+
let count = 0;
|
|
2636
|
+
const visit = (v, depth) => {
|
|
2637
|
+
if (++count > 16384 || depth > 32)
|
|
2638
|
+
throw new ContractError("oversize");
|
|
2639
|
+
if (v === undefined || v === null || typeof v === "boolean" || typeof v === "string")
|
|
2640
|
+
return v;
|
|
2641
|
+
if (typeof v === "number" && Number.isFinite(v))
|
|
2642
|
+
return v;
|
|
2643
|
+
if (Array.isArray(v)) {
|
|
2644
|
+
if (v.length > 16384 || Reflect.ownKeys(v).length !== v.length + 1)
|
|
2645
|
+
refuse();
|
|
2646
|
+
const out2 = [];
|
|
2647
|
+
for (let i = 0;i < v.length; i++) {
|
|
2648
|
+
const d = Object.getOwnPropertyDescriptor(v, String(i));
|
|
2649
|
+
if (!d || !("value" in d))
|
|
2650
|
+
refuse();
|
|
2651
|
+
out2.push(visit(d.value, depth + 1));
|
|
2652
|
+
}
|
|
2653
|
+
return out2;
|
|
2654
|
+
}
|
|
2655
|
+
const out = Object.create(null);
|
|
2656
|
+
for (const [k, entry] of Object.entries(data(v)))
|
|
2657
|
+
out[k] = visit(entry, depth + 1);
|
|
2658
|
+
return out;
|
|
2659
|
+
};
|
|
2660
|
+
const encoded = JSON.stringify(visit(value, 0));
|
|
2661
|
+
if (Buffer.byteLength(encoded) > CONFIG_BYTES)
|
|
2662
|
+
throw new ContractError("oversize");
|
|
2663
|
+
return parseWireJson(encoded, CONFIG_BYTES);
|
|
2664
|
+
}
|
|
2665
|
+
function snapshotLiterals(snapshot, launch, routes = []) {
|
|
2666
|
+
const strings2 = (v, visit) => {
|
|
2667
|
+
if (typeof v === "string") {
|
|
2668
|
+
if (v)
|
|
2669
|
+
visit(v);
|
|
2670
|
+
} else if (v && typeof v === "object") {
|
|
2671
|
+
for (const key of Object.keys(v))
|
|
2672
|
+
strings2(v[key], visit);
|
|
2673
|
+
}
|
|
2674
|
+
};
|
|
2675
|
+
const literals = new Set;
|
|
2676
|
+
let literalBytes = 0;
|
|
2677
|
+
const add = (value) => {
|
|
2678
|
+
if (literals.has(value))
|
|
2679
|
+
return;
|
|
2680
|
+
const size = Buffer.byteLength(value);
|
|
2681
|
+
if (literalBytes + size > LIMITS.workerRequestBytes * 2)
|
|
2682
|
+
throw new ContractError("oversize");
|
|
2683
|
+
literalBytes += size;
|
|
2684
|
+
literals.add(value);
|
|
2685
|
+
};
|
|
2686
|
+
for (const route of routes)
|
|
2687
|
+
add(route);
|
|
2688
|
+
const templates = (value, provider) => {
|
|
2689
|
+
const scoped = environment(snapshot.credentials[provider]?.env ?? {});
|
|
2690
|
+
strings2(value, (literal2) => {
|
|
2691
|
+
add(literal2);
|
|
2692
|
+
for (const name of templateNames(literal2)) {
|
|
2693
|
+
const resolved = scoped[name] || launch[name];
|
|
2694
|
+
if (resolved)
|
|
2695
|
+
add(resolved);
|
|
2696
|
+
}
|
|
2697
|
+
});
|
|
2698
|
+
};
|
|
2699
|
+
for (const [provider, credential2] of Object.entries(snapshot.credentials)) {
|
|
2700
|
+
strings2(credential2.type === "api_key" ? credential2.key : credential2.access, add);
|
|
2701
|
+
strings2(credential2.type === "oauth" ? credential2.refresh : null, add);
|
|
2702
|
+
strings2(credential2.env, add);
|
|
2703
|
+
if (credential2.type === "api_key")
|
|
2704
|
+
templates(credential2.key, provider);
|
|
2705
|
+
}
|
|
2706
|
+
for (const [provider, config] of Object.entries(snapshot.providers)) {
|
|
2707
|
+
templates(config.apiKey, provider);
|
|
2708
|
+
templates(config.headers, provider);
|
|
2709
|
+
for (const model2 of Array.isArray(config.models) ? config.models : [])
|
|
2710
|
+
templates(data(model2).headers, provider);
|
|
2711
|
+
if (config.modelOverrides)
|
|
2712
|
+
for (const model2 of Object.values(data(config.modelOverrides)))
|
|
2713
|
+
templates(data(model2).headers, provider);
|
|
2714
|
+
}
|
|
2715
|
+
for (const [key, value] of Object.entries(launch))
|
|
2716
|
+
if (/(?:KEY|TOKEN|SECRET|PASS|AUTH|COOKIE)/i.test(key) && value)
|
|
2717
|
+
add(value);
|
|
2718
|
+
return [...literals];
|
|
2719
|
+
}
|
|
2720
|
+
|
|
2721
|
+
// src/cadence-preferences.ts
|
|
2722
|
+
import { realpathSync as realpathSync3 } from "node:fs";
|
|
2723
|
+
import { basename, dirname as dirname4, join as join4, resolve as resolve4 } from "node:path";
|
|
2724
|
+
function agentNamespace(agentDir) {
|
|
2725
|
+
let at = resolve4(agentDir);
|
|
2726
|
+
const missing2 = [];
|
|
2727
|
+
for (;; ) {
|
|
2728
|
+
try {
|
|
2729
|
+
return join4(realpathSync3(at), ...missing2.reverse());
|
|
2730
|
+
} catch {
|
|
2731
|
+
const parent = dirname4(at);
|
|
2732
|
+
if (parent === at)
|
|
2733
|
+
return resolve4(agentDir);
|
|
2734
|
+
missing2.push(basename(at));
|
|
2735
|
+
at = parent;
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
|
|
2740
|
+
class CadencePreferences {
|
|
2741
|
+
path;
|
|
2742
|
+
files;
|
|
2743
|
+
constructor(agentDir) {
|
|
2744
|
+
const namespace = agentNamespace(agentDir);
|
|
2745
|
+
this.path = join4(namespace, "cadence", "settings.json");
|
|
2746
|
+
this.files = new PrivateFiles(namespace, false);
|
|
2747
|
+
}
|
|
2748
|
+
read() {
|
|
2749
|
+
const saved = this.files.read(this.path);
|
|
2750
|
+
if (!saved)
|
|
2751
|
+
return null;
|
|
2752
|
+
const o = closed(parseWireJson(saved.bytes.toString("utf8")), [
|
|
2753
|
+
"schema",
|
|
2754
|
+
"model"
|
|
2755
|
+
]);
|
|
2756
|
+
if (o.schema !== "cadence-preferences/1")
|
|
2757
|
+
throw new Error("Unsupported Cadence preferences");
|
|
2758
|
+
return decodeModelSelector(o.model);
|
|
2759
|
+
}
|
|
2760
|
+
encode(model2) {
|
|
2761
|
+
return canonicalJson({
|
|
2762
|
+
schema: "cadence-preferences/1",
|
|
2763
|
+
model: decodeModelSelector(model2)
|
|
2764
|
+
});
|
|
2765
|
+
}
|
|
2766
|
+
save(model2) {
|
|
2767
|
+
const selected = decodeModelSelector(model2);
|
|
2768
|
+
const previous = this.files.read(this.path);
|
|
2769
|
+
if (previous && canonicalJson(this.read()) === canonicalJson(selected))
|
|
2770
|
+
return;
|
|
2771
|
+
const bytes = this.encode(selected);
|
|
2772
|
+
if (previous)
|
|
2773
|
+
this.files.replace(this.path, previous, bytes);
|
|
2774
|
+
else
|
|
2775
|
+
this.files.create(this.path, bytes);
|
|
2776
|
+
}
|
|
2777
|
+
choose(model2) {
|
|
2778
|
+
const bytes = this.encode(model2);
|
|
2779
|
+
const previous = this.files.read(this.path);
|
|
2780
|
+
if (previous?.bytes.toString("utf8") === bytes)
|
|
2781
|
+
return;
|
|
2782
|
+
if (previous)
|
|
2783
|
+
this.files.replace(this.path, previous, bytes);
|
|
2784
|
+
else
|
|
2785
|
+
this.files.create(this.path, bytes);
|
|
2786
|
+
}
|
|
2787
|
+
}
|
|
2788
|
+
|
|
2789
|
+
// src/verification-diagnostics.ts
|
|
2790
|
+
function diagnosticText(value, maximum = 4096, secrets = []) {
|
|
2791
|
+
maximum = Math.max(0, Math.floor(maximum));
|
|
2792
|
+
let clean = value;
|
|
2793
|
+
for (const secret of [...new Set(secrets)].filter(Boolean).sort((a, b) => b.length - a.length))
|
|
2794
|
+
clean = clean.split(secret).join("[redacted]");
|
|
2795
|
+
clean = clean.replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").replace(/(Bearer\s+)\S+/gi, "$1[redacted]").replace(/((?:api[_-]?key|token|password|secret)\s*[:=]\s*)[^\s,;]+/gi, "$1[redacted]").replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, "$1[redacted]@");
|
|
2796
|
+
if (Buffer.byteLength(clean) <= maximum)
|
|
2797
|
+
return clean;
|
|
2798
|
+
const marker = maximum >= 12 ? `
|
|
2799
|
+
[truncated]` : ".".repeat(maximum);
|
|
2800
|
+
const bytes = Buffer.from(clean).subarray(0, Math.max(0, maximum - Buffer.byteLength(marker)));
|
|
2801
|
+
return bytes.toString("utf8").replace(/\ufffd$/, "") + marker;
|
|
2802
|
+
}
|
|
2803
|
+
|
|
2804
|
+
// src/worker-redaction.mjs
|
|
2805
|
+
var marker = "[redacted]";
|
|
2806
|
+
class TextSanitizer {
|
|
2807
|
+
constructor(secrets = []) {
|
|
2808
|
+
if (secrets.some((s) => typeof s !== "string") || secrets.reduce((n, s) => n + utf8Bytes(s), 0) > LIMITS.workerRequestBytes * 2)
|
|
2809
|
+
throw new ContractError("oversize");
|
|
2810
|
+
this.secrets = [];
|
|
2811
|
+
this.addSecrets(secrets);
|
|
2812
|
+
this.pending = "";
|
|
2813
|
+
this.heuristic = "";
|
|
2814
|
+
this.escape = "";
|
|
2815
|
+
this.skipping = false;
|
|
2816
|
+
this.redacted = false;
|
|
2817
|
+
this.ended = false;
|
|
2818
|
+
}
|
|
2819
|
+
addSecrets(secrets) {
|
|
2820
|
+
if (this.ended || !Array.isArray(secrets))
|
|
2821
|
+
throw new ContractError;
|
|
2822
|
+
let incoming = 0;
|
|
2823
|
+
for (const s of secrets) {
|
|
2824
|
+
if (typeof s !== "string")
|
|
2825
|
+
throw new ContractError;
|
|
2826
|
+
incoming += utf8Bytes(s);
|
|
2827
|
+
if (incoming > LIMITS.workerRequestBytes * 2)
|
|
2828
|
+
throw new ContractError("oversize");
|
|
2829
|
+
}
|
|
2830
|
+
let bytes = this.secrets.reduce((n, s) => n + utf8Bytes(s), 0);
|
|
2831
|
+
const added = new Set;
|
|
2832
|
+
for (const s of secrets) {
|
|
2833
|
+
if (!s || this.secrets.includes(s) || added.has(s))
|
|
2834
|
+
continue;
|
|
2835
|
+
bytes += utf8Bytes(s);
|
|
2836
|
+
if (bytes > LIMITS.workerRequestBytes * 2)
|
|
2837
|
+
throw new ContractError("oversize");
|
|
2838
|
+
added.add(s);
|
|
2839
|
+
}
|
|
2840
|
+
this.secrets = this.secrets.concat([...added]).sort((a, b) => b.length - a.length);
|
|
2841
|
+
}
|
|
2842
|
+
get retainedBytes() {
|
|
2843
|
+
return utf8Bytes(this.pending + this.heuristic + this.escape);
|
|
2844
|
+
}
|
|
2845
|
+
write(input, final = false) {
|
|
2846
|
+
if (this.ended || typeof input !== "string")
|
|
2847
|
+
throw new ContractError;
|
|
2848
|
+
let plain = "";
|
|
2849
|
+
for (const ch of input) {
|
|
2850
|
+
if (this.escape) {
|
|
2851
|
+
this.escape += ch;
|
|
2852
|
+
if (this.escape.length > 8192)
|
|
2853
|
+
throw new ContractError("oversize");
|
|
2854
|
+
if (this.escape.startsWith("\x1B[") && this.escape.length > 2 && /[@-~]/.test(ch) || this.escape.startsWith("\x1B]") && (ch === "\x07" || this.escape.endsWith("\x1B\\")) || this.escape.length === 2 && !"[]".includes(ch))
|
|
2855
|
+
this.escape = "";
|
|
2856
|
+
this.redacted = true;
|
|
2857
|
+
} else if (ch === "\x1B")
|
|
2858
|
+
this.escape = ch;
|
|
2859
|
+
else if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/.test(ch))
|
|
2860
|
+
this.redacted = true;
|
|
2861
|
+
else
|
|
2862
|
+
plain += ch;
|
|
2863
|
+
}
|
|
2864
|
+
this.pending += plain;
|
|
2865
|
+
let literal2 = "";
|
|
2866
|
+
let at = 0;
|
|
2867
|
+
while (at < this.pending.length) {
|
|
2868
|
+
const rest = this.pending.slice(at);
|
|
2869
|
+
if (!final && this.secrets.some((s) => s.length > rest.length && s.startsWith(rest)))
|
|
2870
|
+
break;
|
|
2871
|
+
const match = this.secrets.find((s) => rest.startsWith(s));
|
|
2872
|
+
if (match) {
|
|
2873
|
+
literal2 += marker;
|
|
2874
|
+
at += match.length;
|
|
2875
|
+
this.redacted = true;
|
|
2876
|
+
} else {
|
|
2877
|
+
const code = this.pending.charCodeAt(at);
|
|
2878
|
+
if (!final && at + 1 === this.pending.length && code >= 55296 && code <= 56319)
|
|
2879
|
+
break;
|
|
2880
|
+
const cp = this.pending.codePointAt(at);
|
|
2881
|
+
if (cp >= 55296 && cp <= 57343)
|
|
2882
|
+
throw new ContractError;
|
|
2883
|
+
literal2 += String.fromCodePoint(cp);
|
|
2884
|
+
at += cp > 65535 ? 2 : 1;
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
this.pending = this.pending.slice(at);
|
|
2888
|
+
this.heuristic += literal2;
|
|
2889
|
+
let output = "";
|
|
2890
|
+
while (this.heuristic) {
|
|
2891
|
+
if (this.skipping) {
|
|
2892
|
+
const end = this.heuristic.search(/[\s,;"'<>]/);
|
|
2893
|
+
if (end < 0) {
|
|
2894
|
+
this.heuristic = "";
|
|
2895
|
+
break;
|
|
2896
|
+
}
|
|
2897
|
+
this.heuristic = this.heuristic.slice(end);
|
|
2898
|
+
this.skipping = false;
|
|
2899
|
+
}
|
|
2900
|
+
const match = /\b(?:Bearer\s+|(?:api[-_]?key|access[-_]?token|refresh[-_]?token|password|passwd|secret|token|authorization)\s*[:=]\s*)/i.exec(this.heuristic);
|
|
2901
|
+
const url = /https?:\/\//i.exec(this.heuristic);
|
|
2902
|
+
if (url && (!match || url.index < match.index)) {
|
|
2903
|
+
output += this.heuristic.slice(0, url.index);
|
|
2904
|
+
this.heuristic = this.heuristic.slice(url.index);
|
|
2905
|
+
const start = url[0].length;
|
|
2906
|
+
const end = this.heuristic.slice(start).search(/[/\s?#"'<>]/);
|
|
2907
|
+
if (end < 0 && !final) {
|
|
2908
|
+
if (utf8Bytes(this.heuristic) > 8192)
|
|
2909
|
+
throw new ContractError("oversize");
|
|
2910
|
+
break;
|
|
2911
|
+
}
|
|
2912
|
+
const size = end < 0 ? this.heuristic.length : start + end;
|
|
2913
|
+
const authority = this.heuristic.slice(start, size);
|
|
2914
|
+
const pos = authority.lastIndexOf("@");
|
|
2915
|
+
output += this.heuristic.slice(0, start) + (pos < 0 ? authority : `${marker}@${authority.slice(pos + 1)}`);
|
|
2916
|
+
this.redacted ||= pos >= 0;
|
|
2917
|
+
this.heuristic = this.heuristic.slice(size);
|
|
2918
|
+
} else if (match) {
|
|
2919
|
+
if (!final && match.index + match[0].length === this.heuristic.length) {
|
|
2920
|
+
output += this.heuristic.slice(0, match.index);
|
|
2921
|
+
this.heuristic = this.heuristic.slice(match.index);
|
|
2922
|
+
if (utf8Bytes(this.heuristic) > 8192)
|
|
2923
|
+
throw new ContractError("oversize");
|
|
2924
|
+
break;
|
|
2925
|
+
}
|
|
2926
|
+
output += this.heuristic.slice(0, match.index) + match[0] + marker;
|
|
2927
|
+
this.heuristic = this.heuristic.slice(match.index + match[0].length);
|
|
2928
|
+
this.skipping = true;
|
|
2929
|
+
this.redacted = true;
|
|
2930
|
+
} else {
|
|
2931
|
+
const candidate = /(?:Bearer|api[-_]?key|access[-_]?token|refresh[-_]?token|password|passwd|secret|token|authorization)\s*$/i.exec(this.heuristic);
|
|
2932
|
+
const keep = final ? 0 : Math.max(64, candidate ? this.heuristic.length - candidate.index : 0);
|
|
2933
|
+
if (keep > 8192)
|
|
2934
|
+
throw new ContractError("oversize");
|
|
2935
|
+
let take = Math.max(0, this.heuristic.length - keep);
|
|
2936
|
+
const before = this.heuristic.charCodeAt(take - 1);
|
|
2937
|
+
if (before >= 55296 && before <= 56319)
|
|
2938
|
+
take--;
|
|
2939
|
+
output += this.heuristic.slice(0, take);
|
|
2940
|
+
this.heuristic = this.heuristic.slice(take);
|
|
2941
|
+
break;
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
if (final) {
|
|
2945
|
+
this.ended = true;
|
|
2946
|
+
this.escape = "";
|
|
2947
|
+
}
|
|
2948
|
+
return output;
|
|
2949
|
+
}
|
|
2950
|
+
end() {
|
|
2951
|
+
return this.write("", true);
|
|
2952
|
+
}
|
|
2953
|
+
}
|
|
2954
|
+
function sanitizeText(value, secrets = []) {
|
|
2955
|
+
const sanitizer = new TextSanitizer(secrets);
|
|
2956
|
+
return sanitizer.write(value, true);
|
|
2957
|
+
}
|
|
2958
|
+
|
|
2959
|
+
// src/service/model-catalog.ts
|
|
2960
|
+
function publicModelIdentifier(value, literals) {
|
|
2961
|
+
return !/[\p{Cc}\p{Cf}\p{Cs}]/u.test(value) && diagnosticText(value, 512, literals) === value && sanitizeText(value, literals) === value;
|
|
2962
|
+
}
|
|
2963
|
+
function exactEnvironment(launch, selected, snapshot) {
|
|
2964
|
+
const scoped = snapshot.credentials[selected.selection.provider]?.env;
|
|
2965
|
+
const local = scoped === undefined ? {} : environment(scoped);
|
|
2966
|
+
for (const [name, value] of Object.entries(selected.env)) {
|
|
2967
|
+
if (local[name])
|
|
2968
|
+
continue;
|
|
2969
|
+
const d = Object.getOwnPropertyDescriptor(process.env, name);
|
|
2970
|
+
if (!d || !("value" in d) || d.value !== value || launch[name] !== value)
|
|
2971
|
+
throw new ContractError("stale");
|
|
2972
|
+
}
|
|
2973
|
+
}
|
|
2974
|
+
function validateCatalogModel(runtime, thinking, input, current, launch, literals) {
|
|
2975
|
+
if (!runtime || !thinking)
|
|
2976
|
+
throw new ContractError("unavailable");
|
|
2977
|
+
if (runtime.getError() || runtime.getRegisteredNativeProvider(input.provider) || runtime.getRegisteredProviderConfig(input.provider))
|
|
2978
|
+
throw new ContractError("unsupported-context");
|
|
2979
|
+
const model2 = runtime.getModel(input.provider, input.model);
|
|
2980
|
+
if (!model2 || model2.api !== input.api || model2.provider !== input.provider || model2.id !== input.model || !thinking(model2).includes(input.thinking))
|
|
2981
|
+
throw new ContractError("unsupported-context");
|
|
2982
|
+
if (!publicModelIdentifier(input.provider, literals) || !publicModelIdentifier(input.model, literals))
|
|
2983
|
+
throw new ContractError("unsupported-context");
|
|
2984
|
+
const credential2 = current.credentials[input.provider];
|
|
2985
|
+
const provider = runtime.getProvider(input.provider);
|
|
2986
|
+
if (credential2?.type === "oauth" ? !provider?.auth.oauth : !provider?.auth.apiKey)
|
|
2987
|
+
throw new ContractError("unsupported-context");
|
|
2988
|
+
if (credential2?.type === "api_key" ? !credential2.key : !credential2 && !current.providers[input.provider]?.apiKey)
|
|
2989
|
+
throw new ContractError("auth-unavailable");
|
|
2990
|
+
const selected = {
|
|
2991
|
+
model: model2,
|
|
2992
|
+
sourceIdentity: sourceIdentity(current, input.provider),
|
|
2993
|
+
credentialIdentity: stablePrivate(credential2 ?? null),
|
|
2994
|
+
env: selectedEnvironment(current, input.provider, input.model, launch)
|
|
2995
|
+
};
|
|
2996
|
+
exactEnvironment(launch, { ...selected, selection: input }, current);
|
|
2997
|
+
return selected;
|
|
2998
|
+
}
|
|
2999
|
+
function projectModelCatalog(runtime, supportedThinking, current, literals, validate) {
|
|
3000
|
+
const providers = [
|
|
3001
|
+
...new Set([
|
|
3002
|
+
...Object.keys(current.credentials),
|
|
3003
|
+
...Object.keys(current.providers)
|
|
3004
|
+
])
|
|
3005
|
+
].sort();
|
|
3006
|
+
let count = 0;
|
|
3007
|
+
for (const provider of providers) {
|
|
3008
|
+
if (runtime.getRegisteredNativeProvider(provider) || runtime.getRegisteredProviderConfig(provider))
|
|
3009
|
+
throw new ContractError("unsupported-context");
|
|
3010
|
+
count += runtime.getModels(provider).length;
|
|
3011
|
+
if (count > LIMITS.maxPageEntries)
|
|
3012
|
+
return { status: "capacity", entries: [], withheld: 0 };
|
|
3013
|
+
}
|
|
3014
|
+
const entries = [];
|
|
3015
|
+
let withheld = 0;
|
|
3016
|
+
for (const provider of providers) {
|
|
3017
|
+
const models2 = runtime.getModels(provider);
|
|
3018
|
+
if (entries.length + withheld + models2.length > LIMITS.maxPageEntries)
|
|
3019
|
+
throw new ContractError("capacity");
|
|
3020
|
+
for (const model2 of models2) {
|
|
3021
|
+
if (model2.provider !== provider)
|
|
3022
|
+
throw new ContractError("unsupported-context");
|
|
3023
|
+
if (!publicModelIdentifier(provider, literals) || !publicModelIdentifier(model2.id, literals)) {
|
|
3024
|
+
withheld++;
|
|
3025
|
+
continue;
|
|
3026
|
+
}
|
|
3027
|
+
const api = modelApis.find((api2) => api2 === model2.api) ?? null;
|
|
3028
|
+
const levels2 = supportedThinking(model2);
|
|
3029
|
+
if (levels2.length > 7)
|
|
3030
|
+
throw new ContractError("unsupported-context");
|
|
3031
|
+
let eligibility = "candidate";
|
|
3032
|
+
const thinking = levels2.map((level) => ({
|
|
3033
|
+
level,
|
|
3034
|
+
selectable: api !== null && thinkingLevels.some((t) => t === level)
|
|
3035
|
+
}));
|
|
3036
|
+
const supported = thinking.find((t) => t.selectable);
|
|
3037
|
+
if (!api || !supported)
|
|
3038
|
+
eligibility = "unsupported";
|
|
3039
|
+
else {
|
|
3040
|
+
try {
|
|
3041
|
+
validate(decodeModelSelector({
|
|
3042
|
+
provider,
|
|
3043
|
+
model: model2.id,
|
|
3044
|
+
api,
|
|
3045
|
+
thinking: supported.level
|
|
3046
|
+
}), current);
|
|
3047
|
+
} catch (error) {
|
|
3048
|
+
if (!(error instanceof ContractError))
|
|
3049
|
+
throw error;
|
|
3050
|
+
if (error.code === "auth-unavailable")
|
|
3051
|
+
eligibility = "auth-unavailable";
|
|
3052
|
+
else if (error.code === "unsupported-context")
|
|
3053
|
+
eligibility = "unsupported";
|
|
3054
|
+
else
|
|
3055
|
+
throw error;
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
3058
|
+
entries.push(decodeModelCandidate({
|
|
3059
|
+
provider,
|
|
3060
|
+
model: model2.id,
|
|
3061
|
+
api,
|
|
3062
|
+
thinking: thinking.map((t) => ({
|
|
3063
|
+
...t,
|
|
3064
|
+
selectable: t.selectable && eligibility === "candidate"
|
|
3065
|
+
})),
|
|
3066
|
+
images: model2.input.includes("image"),
|
|
3067
|
+
eligibility
|
|
3068
|
+
}));
|
|
3069
|
+
}
|
|
3070
|
+
}
|
|
3071
|
+
return { status: "complete", entries, withheld };
|
|
3072
|
+
}
|
|
3073
|
+
|
|
3074
|
+
// src/service/model-preview.ts
|
|
3075
|
+
async function readModelPreview(input) {
|
|
3076
|
+
const source = piSource(input.agentDir, input.home, input.cwd, input.environment);
|
|
3077
|
+
const before = readPiSnapshot(source);
|
|
3078
|
+
const credentials = {
|
|
3079
|
+
async read(provider) {
|
|
3080
|
+
const value = before.credentials[provider];
|
|
3081
|
+
return value ? clonePrivate(value) : undefined;
|
|
3082
|
+
},
|
|
3083
|
+
async list() {
|
|
3084
|
+
return Object.entries(before.credentials).map(([providerId, credential2]) => ({ providerId, type: credential2.type }));
|
|
3085
|
+
},
|
|
3086
|
+
async modify() {
|
|
3087
|
+
throw new ContractError("forbidden");
|
|
3088
|
+
},
|
|
3089
|
+
async delete() {
|
|
3090
|
+
throw new ContractError("forbidden");
|
|
3091
|
+
}
|
|
3092
|
+
};
|
|
3093
|
+
const [
|
|
3094
|
+
{ ModelRuntime },
|
|
3095
|
+
{ InMemoryModelsStore, getSupportedThinkingLevels }
|
|
3096
|
+
] = await Promise.all([
|
|
3097
|
+
import("@earendil-works/pi-coding-agent"),
|
|
3098
|
+
import("@earendil-works/pi-ai")
|
|
3099
|
+
]);
|
|
3100
|
+
const runtime = await ModelRuntime.create({
|
|
3101
|
+
credentials,
|
|
3102
|
+
modelsPath: source.modelsPath,
|
|
3103
|
+
modelsStore: new InMemoryModelsStore,
|
|
3104
|
+
allowModelNetwork: false,
|
|
3105
|
+
refreshOnCreate: false
|
|
3106
|
+
});
|
|
3107
|
+
const error = runtime.getError();
|
|
3108
|
+
if (error)
|
|
3109
|
+
throw sdkRefusal(error);
|
|
3110
|
+
const literals = snapshotLiterals(before, input.environment, input.secrets ?? []);
|
|
3111
|
+
const catalog = projectModelCatalog(runtime, getSupportedThinkingLevels, before, literals, (selector, snapshot) => validateCatalogModel(runtime, getSupportedThinkingLevels, selector, snapshot, input.environment, literals));
|
|
3112
|
+
let remembered = null;
|
|
3113
|
+
try {
|
|
3114
|
+
const saved = new CadencePreferences(source.directory).read();
|
|
3115
|
+
if (saved && catalogOffers(catalog.entries, saved))
|
|
3116
|
+
remembered = saved;
|
|
3117
|
+
} catch {}
|
|
3118
|
+
const after = readPiSnapshot(source);
|
|
3119
|
+
if (!sameModels(before, after) || before.auth.stamp !== after.auth.stamp || before.auth.identity !== after.auth.identity)
|
|
3120
|
+
throw new ContractError("stale");
|
|
3121
|
+
return decodeModelPreview({ ...catalog, remembered });
|
|
3122
|
+
}
|
|
3123
|
+
|
|
3124
|
+
// src/service/model-preview-protocol.ts
|
|
3125
|
+
import { isAbsolute as isAbsolute4 } from "node:path";
|
|
3126
|
+
var PREVIEW_INPUT_BYTES = 1024 * 1024;
|
|
3127
|
+
var PREVIEW_TIMEOUT_MS = 15000;
|
|
3128
|
+
function decodeModelPreviewInput(value) {
|
|
3129
|
+
canonicalJson(value, PREVIEW_INPUT_BYTES);
|
|
3130
|
+
const o = closed(value, ["kind", "agentDir", "home", "cwd", "secrets"]);
|
|
3131
|
+
const path = (v) => {
|
|
3132
|
+
const p = text(v, 4096, true);
|
|
3133
|
+
if (!isAbsolute4(p))
|
|
3134
|
+
throw new ContractError("invalid");
|
|
3135
|
+
return p;
|
|
3136
|
+
};
|
|
3137
|
+
return {
|
|
3138
|
+
kind: literal(o.kind, "cadence-model-preview/1"),
|
|
3139
|
+
agentDir: path(o.agentDir),
|
|
3140
|
+
home: path(o.home),
|
|
3141
|
+
cwd: path(o.cwd),
|
|
3142
|
+
secrets: list(o.secrets, 4096, (v) => text(v, PREVIEW_INPUT_BYTES, true))
|
|
3143
|
+
};
|
|
3144
|
+
}
|
|
3145
|
+
|
|
3146
|
+
// src/model-preview-entry.mjs
|
|
3147
|
+
if (!process.connected)
|
|
3148
|
+
process.exit(1);
|
|
3149
|
+
process.once("disconnect", () => process.exit(1));
|
|
3150
|
+
process.stdout.on("error", () => process.exit(1));
|
|
3151
|
+
var deadline = setTimeout(() => process.exit(1), PREVIEW_TIMEOUT_MS);
|
|
3152
|
+
var reply;
|
|
3153
|
+
try {
|
|
3154
|
+
const chunks = [];
|
|
3155
|
+
let size = 0;
|
|
3156
|
+
for await (const chunk of process.stdin) {
|
|
3157
|
+
size += chunk.length;
|
|
3158
|
+
if (size > PREVIEW_INPUT_BYTES)
|
|
3159
|
+
throw new ContractError("oversize");
|
|
3160
|
+
chunks.push(chunk);
|
|
3161
|
+
}
|
|
3162
|
+
const input = decodeModelPreviewInput(parseWireJson(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)), PREVIEW_INPUT_BYTES));
|
|
3163
|
+
const { kind: _kind, ...source } = input;
|
|
3164
|
+
reply = {
|
|
3165
|
+
kind: "ok",
|
|
3166
|
+
value: await readModelPreview({
|
|
3167
|
+
...source,
|
|
3168
|
+
environment: captureEnvironment(process.env)
|
|
3169
|
+
})
|
|
3170
|
+
};
|
|
3171
|
+
} catch (error) {
|
|
3172
|
+
reply = {
|
|
3173
|
+
kind: "error",
|
|
3174
|
+
error: publicError(error instanceof ContractError ? error.code : "unavailable", "none")
|
|
3175
|
+
};
|
|
3176
|
+
}
|
|
3177
|
+
process.stdout.write(canonicalJson(reply, LIMITS.pageBytes), () => {
|
|
3178
|
+
clearTimeout(deadline);
|
|
3179
|
+
process.exit(0);
|
|
3180
|
+
});
|