dsh-crowdtest 0.0.0-stage → 0.2.22
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/README.md +13 -2
- package/cordis.patch.yml +4 -0
- package/icon.png +0 -0
- package/lib/client.js +411 -0
- package/lib/index.js +1194 -0
- package/package.json +77 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,1194 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __knownSymbol = (name2, symbol) => (symbol = Symbol[name2]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name2);
|
|
6
|
+
var __typeError = (msg) => {
|
|
7
|
+
throw TypeError(msg);
|
|
8
|
+
};
|
|
9
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
10
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
11
|
+
var __esm = (fn, res, err) => function __init() {
|
|
12
|
+
if (err) throw err[0];
|
|
13
|
+
try {
|
|
14
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
15
|
+
} catch (e) {
|
|
16
|
+
throw err = [e], e;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
var __export = (target, all) => {
|
|
20
|
+
for (var name2 in all)
|
|
21
|
+
__defProp(target, name2, { get: all[name2], enumerable: true });
|
|
22
|
+
};
|
|
23
|
+
var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
|
|
24
|
+
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
|
|
25
|
+
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
|
|
26
|
+
var __decoratorContext = (kind, name2, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name: name2, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
|
|
27
|
+
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
|
|
28
|
+
var __runInitializers = (array, flags, self, value) => {
|
|
29
|
+
for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
|
|
30
|
+
return value;
|
|
31
|
+
};
|
|
32
|
+
var __decorateElement = (array, flags, name2, decorators, target, extra) => {
|
|
33
|
+
var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
|
|
34
|
+
var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
|
|
35
|
+
var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
|
|
36
|
+
var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name2]() {
|
|
37
|
+
return __privateGet(this, extra);
|
|
38
|
+
}, set [name2](x) {
|
|
39
|
+
return __privateSet(this, extra, x);
|
|
40
|
+
} }, name2));
|
|
41
|
+
k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name2) : __name(target, name2);
|
|
42
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
43
|
+
ctx = __decoratorContext(k, name2, done = {}, array[3], extraInitializers);
|
|
44
|
+
if (k) {
|
|
45
|
+
ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name2 in x };
|
|
46
|
+
if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name2];
|
|
47
|
+
if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name2] = y;
|
|
48
|
+
}
|
|
49
|
+
it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
|
|
50
|
+
if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
|
|
51
|
+
else if (typeof it !== "object" || it === null) __typeError("Object expected");
|
|
52
|
+
else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
|
|
53
|
+
}
|
|
54
|
+
return k || __decoratorMetadata(array, target), desc && __defProp(target, name2, desc), p ? k ^ 4 ? extra : desc : target;
|
|
55
|
+
};
|
|
56
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
57
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
58
|
+
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
|
|
59
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
60
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
61
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
62
|
+
|
|
63
|
+
// src/bridge.ts
|
|
64
|
+
function object(value) {
|
|
65
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("invalid sync payload");
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
function parseRequest(value) {
|
|
69
|
+
const request = object(value);
|
|
70
|
+
if (Object.keys(request).length !== 1 || typeof request.sessionId !== "string" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(request.sessionId)) throw new Error("invalid session id");
|
|
71
|
+
return { sessionId: request.sessionId };
|
|
72
|
+
}
|
|
73
|
+
function parseView(value) {
|
|
74
|
+
if (value === null) return null;
|
|
75
|
+
const view = object(value);
|
|
76
|
+
const keys = ["sessionId", "taskId", "runId", "bindingEpoch", "revision", "phase", "uploadedAtMs", "lastSyncedAtMs"];
|
|
77
|
+
if (Object.keys(view).length !== keys.length || keys.some((key) => !Object.hasOwn(view, key))) throw new Error("invalid sync view");
|
|
78
|
+
const { sessionId } = parseRequest({ sessionId: view.sessionId });
|
|
79
|
+
const integer = (value2) => {
|
|
80
|
+
if (typeof value2 !== "number" || !Number.isSafeInteger(value2) || value2 < 0) throw new Error("invalid sync identity");
|
|
81
|
+
return value2;
|
|
82
|
+
};
|
|
83
|
+
const phase = view.phase;
|
|
84
|
+
if (phase !== "checking" && phase !== "synced" && phase !== "dirty" && phase !== "uploading" && phase !== "failed" && phase !== "unknown") throw new Error("invalid sync phase");
|
|
85
|
+
const uploadedAtMs = view.uploadedAtMs;
|
|
86
|
+
if (uploadedAtMs !== null && (typeof uploadedAtMs !== "number" || !Number.isSafeInteger(uploadedAtMs) || uploadedAtMs <= 0)) throw new Error("invalid sync timestamp");
|
|
87
|
+
const lastSyncedAtMs = view.lastSyncedAtMs;
|
|
88
|
+
if (lastSyncedAtMs !== null && (typeof lastSyncedAtMs !== "number" || !Number.isSafeInteger(lastSyncedAtMs) || lastSyncedAtMs <= 0)) throw new Error("invalid sync timestamp");
|
|
89
|
+
return { sessionId, taskId: integer(view.taskId), runId: integer(view.runId), bindingEpoch: integer(view.bindingEpoch), revision: integer(view.revision), phase, uploadedAtMs, lastSyncedAtMs };
|
|
90
|
+
}
|
|
91
|
+
var descriptors, contribution;
|
|
92
|
+
var init_bridge = __esm({
|
|
93
|
+
"src/bridge.ts"() {
|
|
94
|
+
"use strict";
|
|
95
|
+
descriptors = ["inspect", "sync"].map((method) => ({
|
|
96
|
+
id: `dsh-crowdtest#crowdtestSync/${method}`,
|
|
97
|
+
service: "crowdtestSync",
|
|
98
|
+
namespace: "crowdtestSync",
|
|
99
|
+
method,
|
|
100
|
+
invocation: { kind: "direct" },
|
|
101
|
+
parameters: [{ name: "request", wire: "request", source: "json", codec: { mode: "strict", typeSymbol: "SyncRequest", create: () => ({ parse: parseRequest }) } }],
|
|
102
|
+
cancellation: { parameter: "signal" },
|
|
103
|
+
result: { mode: "strict", typeSymbol: "SyncView", create: () => ({ parse: parseView }), decode: parseView }
|
|
104
|
+
}));
|
|
105
|
+
contribution = { package: "dsh-crowdtest", descriptors };
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// src/remote-host.ts
|
|
110
|
+
var remote_host_exports = {};
|
|
111
|
+
__export(remote_host_exports, {
|
|
112
|
+
installRemote: () => installRemote
|
|
113
|
+
});
|
|
114
|
+
async function installRemote(ctx, backups) {
|
|
115
|
+
var _sync_dec, _inspect_dec, _a, _init;
|
|
116
|
+
const cordis = "@deepseek-ai/cordis";
|
|
117
|
+
const protocol = "@deepseek-ai/dsh-typert-protocol";
|
|
118
|
+
const { Service } = await import(cordis);
|
|
119
|
+
const { bindTypertRemote, Remote } = await import(protocol);
|
|
120
|
+
class CrowdtestSync extends (_a = Service, _inspect_dec = [Remote({ resources: { session: (request) => request.sessionId } })], _sync_dec = [Remote({ resources: { session: (request) => request.sessionId } })], _a) {
|
|
121
|
+
constructor() {
|
|
122
|
+
super(ctx, "crowdtestSync");
|
|
123
|
+
__runInitializers(_init, 5, this);
|
|
124
|
+
__publicField(this, "typertRemote");
|
|
125
|
+
this.typertRemote = bindTypertRemote(this, "crowdtestSync");
|
|
126
|
+
}
|
|
127
|
+
inspect(request, signal) {
|
|
128
|
+
signal.throwIfAborted();
|
|
129
|
+
return backups.inspect(parseRequest(request).sessionId);
|
|
130
|
+
}
|
|
131
|
+
sync(request, signal) {
|
|
132
|
+
signal.throwIfAborted();
|
|
133
|
+
return backups.sync(parseRequest(request).sessionId);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
_init = __decoratorStart(_a);
|
|
137
|
+
__decorateElement(_init, 1, "inspect", _inspect_dec, CrowdtestSync);
|
|
138
|
+
__decorateElement(_init, 1, "sync", _sync_dec, CrowdtestSync);
|
|
139
|
+
__decoratorMetadata(_init, CrowdtestSync);
|
|
140
|
+
new CrowdtestSync();
|
|
141
|
+
ctx.typert?.register({ package: "dsh-crowdtest", face: "host", schemas: [], model: { services: [], events: [], objects: [] }, invocations: contribution.descriptors });
|
|
142
|
+
}
|
|
143
|
+
var init_remote_host = __esm({
|
|
144
|
+
"src/remote-host.ts"() {
|
|
145
|
+
"use strict";
|
|
146
|
+
init_bridge();
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
// src/index.ts
|
|
151
|
+
import { createHash as createHash3, randomUUID } from "node:crypto";
|
|
152
|
+
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
|
|
153
|
+
import { homedir as homedir3 } from "node:os";
|
|
154
|
+
import { join as join4 } from "node:path";
|
|
155
|
+
|
|
156
|
+
// src/archive.ts
|
|
157
|
+
import { createHash } from "node:crypto";
|
|
158
|
+
import { gzipSync } from "node:zlib";
|
|
159
|
+
|
|
160
|
+
// src/native-session.ts
|
|
161
|
+
import { constants } from "node:fs";
|
|
162
|
+
import { lstat, open } from "node:fs/promises";
|
|
163
|
+
import { homedir } from "node:os";
|
|
164
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
165
|
+
import { zstdDecompressSync } from "node:zlib";
|
|
166
|
+
var NATIVE_SESSION_NAME = "session.v4.jsonl.zstd";
|
|
167
|
+
var MAX_DECODED_BYTES = 128 * 1024 * 1024;
|
|
168
|
+
var MAX_FRAMES = 65536;
|
|
169
|
+
function encodeSegment(raw) {
|
|
170
|
+
if (raw.length === 0) throw new Error("\u4F1A\u8BDD\u8DEF\u5F84\u4E3A\u7A7A");
|
|
171
|
+
if (raw === "." || raw === "..") return raw.replaceAll(".", "~002E");
|
|
172
|
+
let encoded = "";
|
|
173
|
+
for (let i = 0; i < raw.length; i++) {
|
|
174
|
+
const ch = raw[i];
|
|
175
|
+
encoded += /^[A-Za-z0-9._-]$/.test(ch) ? ch : `~${raw.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")}`;
|
|
176
|
+
}
|
|
177
|
+
return encoded;
|
|
178
|
+
}
|
|
179
|
+
function projectKey(cwd) {
|
|
180
|
+
let readable = "";
|
|
181
|
+
let separatorRun = false;
|
|
182
|
+
for (let i = 0; i < cwd.length; i++) {
|
|
183
|
+
const ch = cwd[i];
|
|
184
|
+
if (ch === "/" || ch === "\\" || ch === ":") {
|
|
185
|
+
if (!separatorRun) readable += "-";
|
|
186
|
+
separatorRun = true;
|
|
187
|
+
} else {
|
|
188
|
+
readable += /^[A-Za-z0-9._-]$/.test(ch) ? ch : `~${cwd.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")}`;
|
|
189
|
+
separatorRun = false;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const slug = readable.replace(/^-+/, "") || "root";
|
|
193
|
+
return `--${slug.slice(0, 251)}--`;
|
|
194
|
+
}
|
|
195
|
+
function sessionIdentity(value, sessionId) {
|
|
196
|
+
if (typeof value !== "object" || value === null || !("id" in value) || value.id !== sessionId) {
|
|
197
|
+
throw new Error("\u539F\u751F\u4F1A\u8BDD\u8EAB\u4EFD\u4E0E\u5F53\u524D\u8FD0\u884C\u4E0D\u5339\u914D");
|
|
198
|
+
}
|
|
199
|
+
if ("cwd" in value && value.cwd !== void 0) {
|
|
200
|
+
if (typeof value.cwd !== "string" || !isAbsolute(value.cwd)) throw new Error("\u539F\u751F\u4F1A\u8BDD\u76EE\u5F55\u65E0\u6548");
|
|
201
|
+
return { id: sessionId, cwd: value.cwd };
|
|
202
|
+
}
|
|
203
|
+
return { id: sessionId };
|
|
204
|
+
}
|
|
205
|
+
function fileRevision(identity) {
|
|
206
|
+
if (!identity.isFile()) throw new Error("\u539F\u751F\u4F1A\u8BDD\u4E0D\u662F\u666E\u901A\u6587\u4EF6");
|
|
207
|
+
return [identity.dev, identity.ino, identity.size, identity.mtimeNs, identity.ctimeNs].join(":");
|
|
208
|
+
}
|
|
209
|
+
async function fileStat(path) {
|
|
210
|
+
return lstat(path, { bigint: true });
|
|
211
|
+
}
|
|
212
|
+
function resolveNativeSessionRoot(root) {
|
|
213
|
+
return resolve(root ?? join(process.env.DSH_HOME || join(homedir(), ".dsh"), "sessions"));
|
|
214
|
+
}
|
|
215
|
+
async function source(options) {
|
|
216
|
+
const snapshot = await options.persistence.stat(options.sessionId);
|
|
217
|
+
if (!snapshot) throw new Error("\u672A\u627E\u5230\u5F53\u524D\u539F\u751F\u4F1A\u8BDD");
|
|
218
|
+
const header = sessionIdentity(snapshot.header, options.sessionId);
|
|
219
|
+
const root = resolveNativeSessionRoot(options.nativeSessionRoot);
|
|
220
|
+
const path = join(root, header.cwd === void 0 ? "_no-cwd" : projectKey(header.cwd), encodeSegment(header.id), NATIVE_SESSION_NAME);
|
|
221
|
+
return { path, header, revision: String(snapshot.revision) };
|
|
222
|
+
}
|
|
223
|
+
async function nativeSessionRevision(options) {
|
|
224
|
+
const current = await source(options);
|
|
225
|
+
return `${current.revision}:${fileRevision(await fileStat(current.path))}`;
|
|
226
|
+
}
|
|
227
|
+
function standardFrameEnd(bytes, start) {
|
|
228
|
+
if (start + 4 > bytes.length || bytes.readUInt32LE(start) !== 4247762216) {
|
|
229
|
+
throw new Error("\u539F\u751F\u4F1A\u8BDD\u5305\u542B\u975E\u6807\u51C6\u538B\u7F29\u5E27");
|
|
230
|
+
}
|
|
231
|
+
const descriptor = bytes[start + 4];
|
|
232
|
+
if (descriptor === void 0 || (descriptor & 8) !== 0) throw new Error("\u539F\u751F\u4F1A\u8BDD\u538B\u7F29\u5E27\u5934\u65E0\u6548");
|
|
233
|
+
const singleSegment = (descriptor & 32) !== 0;
|
|
234
|
+
const windowDescriptorBytes = singleSegment ? 0 : 1;
|
|
235
|
+
const dictionaryIdBytes = [0, 1, 2, 4][descriptor & 3];
|
|
236
|
+
const contentSizeBytes = [singleSegment ? 1 : 0, 2, 4, 8][descriptor >>> 6];
|
|
237
|
+
let cursor = start + 5 + windowDescriptorBytes + dictionaryIdBytes + contentSizeBytes;
|
|
238
|
+
for (; ; ) {
|
|
239
|
+
if (cursor + 3 > bytes.length) throw new Error("\u539F\u751F\u4F1A\u8BDD\u538B\u7F29\u5757\u5934\u4E0D\u5B8C\u6574");
|
|
240
|
+
const block = bytes.readUIntLE(cursor, 3);
|
|
241
|
+
const blockType = block >>> 1 & 3;
|
|
242
|
+
if (blockType === 3) throw new Error("\u539F\u751F\u4F1A\u8BDD\u538B\u7F29\u5757\u7C7B\u578B\u65E0\u6548");
|
|
243
|
+
const lastBlock = (block & 1) !== 0;
|
|
244
|
+
const payloadBytes = blockType === 1 ? 1 : block >>> 3;
|
|
245
|
+
cursor += 3 + payloadBytes;
|
|
246
|
+
if (lastBlock && (descriptor & 4) !== 0) cursor += 4;
|
|
247
|
+
if (cursor > bytes.length) throw new Error("\u539F\u751F\u4F1A\u8BDD\u538B\u7F29\u5E27\u4E0D\u5B8C\u6574");
|
|
248
|
+
if (lastBlock) return cursor;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function decodeNativeSession(bytes, maxBytes = MAX_DECODED_BYTES) {
|
|
252
|
+
const input = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
253
|
+
const chunks = [];
|
|
254
|
+
let offset = 0;
|
|
255
|
+
let total = 0;
|
|
256
|
+
while (offset < input.length) {
|
|
257
|
+
if (chunks.length >= MAX_FRAMES) throw new Error("\u539F\u751F\u4F1A\u8BDD\u538B\u7F29\u5E27\u8D85\u8FC7\u4E0A\u9650");
|
|
258
|
+
const end = standardFrameEnd(input, offset);
|
|
259
|
+
const frame = input.subarray(offset, end);
|
|
260
|
+
const decoded = zstdDecompressSync(frame, { info: true, maxOutputLength: Math.max(1, maxBytes - total) });
|
|
261
|
+
if (typeof decoded !== "object" || decoded === null || !("buffer" in decoded) || !Buffer.isBuffer(decoded.buffer) || !("engine" in decoded) || typeof decoded.engine !== "object" || decoded.engine === null || !("bytesWritten" in decoded.engine) || decoded.engine.bytesWritten !== frame.length) {
|
|
262
|
+
throw new Error("\u539F\u751F\u4F1A\u8BDD\u538B\u7F29\u5E27\u65E0\u6548");
|
|
263
|
+
}
|
|
264
|
+
total += decoded.buffer.length;
|
|
265
|
+
if (total > maxBytes) throw new Error("\u539F\u751F\u4F1A\u8BDD\u89E3\u538B\u540E\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
|
|
266
|
+
chunks.push(decoded.buffer);
|
|
267
|
+
offset = end;
|
|
268
|
+
}
|
|
269
|
+
if (offset === 0) throw new Error("\u539F\u751F\u4F1A\u8BDD\u4E3A\u7A7A");
|
|
270
|
+
return Buffer.concat(chunks, total);
|
|
271
|
+
}
|
|
272
|
+
function containsSecret(value, secret) {
|
|
273
|
+
if (!secret) return false;
|
|
274
|
+
const pending = [value];
|
|
275
|
+
while (pending.length > 0) {
|
|
276
|
+
const next = pending.pop();
|
|
277
|
+
if (typeof next === "string" && next.includes(secret)) return true;
|
|
278
|
+
if (next !== null && typeof next === "object") {
|
|
279
|
+
for (const [key, child] of Object.entries(next)) {
|
|
280
|
+
if (key.includes(secret)) return true;
|
|
281
|
+
pending.push(child);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
function validateNativeSession(bytes, header, secret) {
|
|
288
|
+
if (secret && Buffer.from(bytes).includes(secret)) throw new Error("\u4F1A\u8BDD\u4E2D\u51FA\u73B0\u4E86\u5E73\u53F0\u51ED\u8BC1\u539F\u6587\uFF0C\u5DF2\u505C\u6B62\u4E0A\u4F20\uFF1B\u8BF7\u8054\u7CFB\u9879\u76EE\u7BA1\u7406\u5458\u5904\u7406");
|
|
289
|
+
let text2;
|
|
290
|
+
try {
|
|
291
|
+
text2 = new TextDecoder("utf-8", { fatal: true }).decode(decodeNativeSession(bytes));
|
|
292
|
+
} catch {
|
|
293
|
+
throw new Error("\u539F\u751F\u4F1A\u8BDD\u538B\u7F29\u5185\u5BB9\u65E0\u6548\u6216\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
|
|
294
|
+
}
|
|
295
|
+
if (secret && text2.includes(secret)) throw new Error("\u4F1A\u8BDD\u4E2D\u51FA\u73B0\u4E86\u5E73\u53F0\u51ED\u8BC1\u539F\u6587\uFF0C\u5DF2\u505C\u6B62\u4E0A\u4F20\uFF1B\u8BF7\u8054\u7CFB\u9879\u76EE\u7BA1\u7406\u5458\u5904\u7406");
|
|
296
|
+
let first = true;
|
|
297
|
+
for (const line of text2.split("\n")) {
|
|
298
|
+
if (line === "") continue;
|
|
299
|
+
let record2;
|
|
300
|
+
try {
|
|
301
|
+
record2 = JSON.parse(line);
|
|
302
|
+
} catch {
|
|
303
|
+
throw new Error("\u539F\u751F\u4F1A\u8BDD JSONL \u65E0\u6548");
|
|
304
|
+
}
|
|
305
|
+
if (first) {
|
|
306
|
+
const identity = sessionIdentity(record2, header.id);
|
|
307
|
+
if (typeof record2 !== "object" || record2 === null || !("type" in record2) || record2.type !== "session" || !("version" in record2) || record2.version !== 4 || identity.cwd !== header.cwd) {
|
|
308
|
+
throw new Error("\u539F\u751F\u4F1A\u8BDD\u5934\u4E0E\u5F53\u524D\u8FD0\u884C\u4E0D\u5339\u914D");
|
|
309
|
+
}
|
|
310
|
+
first = false;
|
|
311
|
+
}
|
|
312
|
+
if (containsSecret(record2, secret)) throw new Error("\u4F1A\u8BDD\u4E2D\u51FA\u73B0\u4E86\u5E73\u53F0\u51ED\u8BC1\u539F\u6587\uFF0C\u5DF2\u505C\u6B62\u4E0A\u4F20\uFF1B\u8BF7\u8054\u7CFB\u9879\u76EE\u7BA1\u7406\u5458\u5904\u7406");
|
|
313
|
+
}
|
|
314
|
+
if (first) throw new Error("\u539F\u751F\u4F1A\u8BDD\u7F3A\u5C11\u4F1A\u8BDD\u5934");
|
|
315
|
+
}
|
|
316
|
+
async function captureNativeSession(options) {
|
|
317
|
+
const current = await source(options);
|
|
318
|
+
const handle = await open(current.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
319
|
+
let bytes;
|
|
320
|
+
let revision;
|
|
321
|
+
try {
|
|
322
|
+
const before = await handle.stat({ bigint: true });
|
|
323
|
+
revision = fileRevision(before);
|
|
324
|
+
if (before.size <= 0 || before.size > BigInt(Math.min(options.maxBytes, MAX_DECODED_BYTES))) throw new Error("\u539F\u751F\u4F1A\u8BDD\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
|
|
325
|
+
bytes = Buffer.alloc(Number(before.size) + 1);
|
|
326
|
+
let offset = 0;
|
|
327
|
+
while (offset < bytes.length) {
|
|
328
|
+
const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);
|
|
329
|
+
if (bytesRead === 0) break;
|
|
330
|
+
offset += bytesRead;
|
|
331
|
+
}
|
|
332
|
+
if (offset !== Number(before.size) || fileRevision(await handle.stat({ bigint: true })) !== revision || fileRevision(await fileStat(current.path)) !== revision) throw new Error("\u539F\u751F\u4F1A\u8BDD\u5728\u8BFB\u53D6\u671F\u95F4\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5");
|
|
333
|
+
bytes = bytes.subarray(0, offset);
|
|
334
|
+
} finally {
|
|
335
|
+
await handle.close();
|
|
336
|
+
}
|
|
337
|
+
const sourceRevision = `${current.revision}:${revision}`;
|
|
338
|
+
validateNativeSession(bytes, current.header, options.secret);
|
|
339
|
+
if (await nativeSessionRevision(options) !== sourceRevision) throw new Error("\u539F\u751F\u4F1A\u8BDD\u5728\u8BFB\u53D6\u671F\u95F4\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5");
|
|
340
|
+
return { name: NATIVE_SESSION_NAME, bytes, sourceRevision };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// src/archive.ts
|
|
344
|
+
var BLOCK = 512;
|
|
345
|
+
function writeOctal(header, offset, length, value) {
|
|
346
|
+
const text2 = value.toString(8).padStart(length - 1, "0");
|
|
347
|
+
header.set(new TextEncoder().encode(`${text2}\0`), offset);
|
|
348
|
+
}
|
|
349
|
+
function buildTar(files) {
|
|
350
|
+
const encoder = new TextEncoder();
|
|
351
|
+
const chunks = [];
|
|
352
|
+
for (const file of files) {
|
|
353
|
+
const name2 = encoder.encode(file.path);
|
|
354
|
+
if (name2.length > 100) throw new Error(`tar member path is longer than 100 bytes: ${file.path}`);
|
|
355
|
+
const header = new Uint8Array(BLOCK);
|
|
356
|
+
header.set(name2, 0);
|
|
357
|
+
writeOctal(header, 100, 8, 384);
|
|
358
|
+
writeOctal(header, 108, 8, 0);
|
|
359
|
+
writeOctal(header, 116, 8, 0);
|
|
360
|
+
writeOctal(header, 124, 12, file.content.length);
|
|
361
|
+
writeOctal(header, 136, 12, 0);
|
|
362
|
+
header.fill(32, 148, 156);
|
|
363
|
+
header[156] = 48;
|
|
364
|
+
header.set(encoder.encode("ustar\0"), 257);
|
|
365
|
+
header.set(encoder.encode("00"), 263);
|
|
366
|
+
const checksum = header.reduce((sum, byte) => sum + byte, 0);
|
|
367
|
+
header.set(encoder.encode(`${checksum.toString(8).padStart(6, "0")}\0 `), 148);
|
|
368
|
+
chunks.push(header, file.content);
|
|
369
|
+
const padding = (BLOCK - file.content.length % BLOCK) % BLOCK;
|
|
370
|
+
if (padding > 0) chunks.push(new Uint8Array(padding));
|
|
371
|
+
}
|
|
372
|
+
chunks.push(new Uint8Array(BLOCK * 2));
|
|
373
|
+
const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
374
|
+
const tar = new Uint8Array(total);
|
|
375
|
+
let offset = 0;
|
|
376
|
+
for (const chunk of chunks) {
|
|
377
|
+
tar.set(chunk, offset);
|
|
378
|
+
offset += chunk.length;
|
|
379
|
+
}
|
|
380
|
+
return tar;
|
|
381
|
+
}
|
|
382
|
+
function validArchiveSessionId(id) {
|
|
383
|
+
return typeof id === "string" && /^[A-Za-z0-9_-]+$/.test(id) && id.length + 1 + NATIVE_SESSION_NAME.length <= 100;
|
|
384
|
+
}
|
|
385
|
+
function buildSessionArchive(sessionId, file) {
|
|
386
|
+
if (!validArchiveSessionId(sessionId)) throw new Error("\u4F1A\u8BDD\u6807\u8BC6\u65E0\u6548");
|
|
387
|
+
const bytes = new Uint8Array(gzipSync(buildTar([{ path: `${sessionId}/${file.name}`, content: file.bytes }]), { level: 9 }));
|
|
388
|
+
return { bytes, sha256: createHash("sha256").update(bytes).digest("hex"), size: bytes.length };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// src/version.ts
|
|
392
|
+
var PLUGIN_VERSION = "0.2.22";
|
|
393
|
+
|
|
394
|
+
// src/bff.ts
|
|
395
|
+
var PROTOCOL_VERSION = "crowdtest-dsh/v1";
|
|
396
|
+
var CLIENT_VERSION = PLUGIN_VERSION;
|
|
397
|
+
function record(value) {
|
|
398
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
399
|
+
}
|
|
400
|
+
function text(value) {
|
|
401
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
402
|
+
}
|
|
403
|
+
function nonnegative(value) {
|
|
404
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
405
|
+
}
|
|
406
|
+
function positive(value) {
|
|
407
|
+
return nonnegative(value) && value > 0;
|
|
408
|
+
}
|
|
409
|
+
function validModel(model) {
|
|
410
|
+
if (!record(model) || !text(model.alias) || !text(model.apiType) || !text(model.baseUrl)) return false;
|
|
411
|
+
if (model.protocol !== "openai-completions" && model.protocol !== "openai-responses" && model.protocol !== "anthropic-messages") return false;
|
|
412
|
+
if (!Array.isArray(model.input) || !model.input.length || !model.input.every((input) => input === "text" || input === "image")) return false;
|
|
413
|
+
if (model.contextWindow !== void 0 && !positive(model.contextWindow)) return false;
|
|
414
|
+
if (model.maxTokens !== void 0 && !positive(model.maxTokens)) return false;
|
|
415
|
+
if (model.reasoningEffort !== void 0 && !text(model.reasoningEffort)) return false;
|
|
416
|
+
const efforts = model.reasoningEfforts;
|
|
417
|
+
if (efforts !== void 0 && efforts !== false && !(record(efforts) && Object.entries(efforts).every(([key, value]) => text(key) && text(value)))) return false;
|
|
418
|
+
normalizeServerBaseUrl(model.baseUrl);
|
|
419
|
+
return true;
|
|
420
|
+
}
|
|
421
|
+
function validAttachment(file) {
|
|
422
|
+
if (!record(file) || !text(file.name) || !nonnegative(file.size) || !text(file.contentType) || !text(file.url)) return false;
|
|
423
|
+
if (/^[.-]|[/\\\x00-\x1f\x7f]/u.test(file.name) || Buffer.byteLength(file.name) > 255) return false;
|
|
424
|
+
if (file.sha256 !== null && !(typeof file.sha256 === "string" && /^[a-f0-9]{64}$/.test(file.sha256))) return false;
|
|
425
|
+
platformUrl(file.url, true);
|
|
426
|
+
return true;
|
|
427
|
+
}
|
|
428
|
+
function parseManifest(value) {
|
|
429
|
+
if (!record(value)) throw new Error("\u4EFB\u52A1\u6E05\u5355\u65E0\u6548");
|
|
430
|
+
if (value.protocol !== PROTOCOL_VERSION) throw new Error(`\u5E73\u53F0\u534F\u8BAE\u4E0E\u63D2\u4EF6\u652F\u6301\u7684 ${PROTOCOL_VERSION} \u4E0D\u4E00\u81F4\uFF0C\u8BF7\u66F4\u65B0 CrowdTest \u63D2\u4EF6`);
|
|
431
|
+
const { projectId, taskId, taskModelRunId, sessionId, title, prompt, serviceName, projectEndTime, model, sessionBackup, attachments } = value;
|
|
432
|
+
if (value.harness !== "dsh" || !positive(projectId) || !positive(taskId) || !positive(taskModelRunId) || !validArchiveSessionId(sessionId)) {
|
|
433
|
+
throw new Error("\u4EFB\u52A1\u6E05\u5355\u4E2D\u7684\u8FD0\u884C\u6216\u4F1A\u8BDD\u6807\u8BC6\u65E0\u6548");
|
|
434
|
+
}
|
|
435
|
+
if (typeof title !== "string" || typeof prompt !== "string" || !text(serviceName) || !nonnegative(projectEndTime) || !validModel(model)) {
|
|
436
|
+
throw new Error("\u4EFB\u52A1\u6E05\u5355\u4E2D\u7684\u4EFB\u52A1\u6216\u6A21\u578B\u914D\u7F6E\u65E0\u6548");
|
|
437
|
+
}
|
|
438
|
+
if (!record(sessionBackup) || sessionBackup.format !== "dsh-session-tree-tar-gzip" || !positive(sessionBackup.maxBytes)) {
|
|
439
|
+
throw new Error("\u4EFB\u52A1\u6E05\u5355\u4E2D\u7684\u5907\u4EFD\u914D\u7F6E\u65E0\u6548");
|
|
440
|
+
}
|
|
441
|
+
if (!Array.isArray(attachments) || !attachments.every(validAttachment)) throw new Error("\u4EFB\u52A1\u6E05\u5355\u4E2D\u7684\u9644\u4EF6\u4FE1\u606F\u65E0\u6548");
|
|
442
|
+
const names = attachments.map((file) => file.name.normalize("NFC").toLowerCase());
|
|
443
|
+
if (new Set(names).size !== names.length) throw new Error("\u4EFB\u52A1\u6E05\u5355\u4E2D\u7684\u9644\u4EF6\u6587\u4EF6\u540D\u91CD\u590D");
|
|
444
|
+
return {
|
|
445
|
+
protocol: PROTOCOL_VERSION,
|
|
446
|
+
harness: "dsh",
|
|
447
|
+
projectId,
|
|
448
|
+
taskId,
|
|
449
|
+
taskModelRunId,
|
|
450
|
+
sessionId,
|
|
451
|
+
title,
|
|
452
|
+
prompt,
|
|
453
|
+
serviceName,
|
|
454
|
+
projectEndTime,
|
|
455
|
+
model,
|
|
456
|
+
attachments,
|
|
457
|
+
sessionBackup: { format: sessionBackup.format, maxBytes: sessionBackup.maxBytes }
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
function parseBackup(value) {
|
|
461
|
+
if (typeof value !== "object" || value === null || !("backup" in value) || Object.keys(value).length !== 1) throw new Error("invalid backup status");
|
|
462
|
+
const backup = value.backup;
|
|
463
|
+
if (backup === null) return null;
|
|
464
|
+
if (typeof backup !== "object" || !("sha256" in backup) || !("size" in backup) || !("format" in backup) || !("uploadedAtMs" in backup) || Object.keys(backup).length !== 4) throw new Error("invalid backup metadata");
|
|
465
|
+
if (typeof backup.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(backup.sha256) || typeof backup.size !== "number" || !Number.isSafeInteger(backup.size) || backup.size <= 0 || typeof backup.format !== "string" || backup.format !== "dsh-session-tree-tar-gzip" || backup.uploadedAtMs !== null && (typeof backup.uploadedAtMs !== "number" || !Number.isSafeInteger(backup.uploadedAtMs) || backup.uploadedAtMs <= 0)) throw new Error("invalid backup metadata");
|
|
466
|
+
return { sha256: backup.sha256, size: backup.size, format: backup.format, uploadedAtMs: backup.uploadedAtMs };
|
|
467
|
+
}
|
|
468
|
+
var CrowdtestRequestError = class extends Error {
|
|
469
|
+
constructor(status, message) {
|
|
470
|
+
super(message);
|
|
471
|
+
this.status = status;
|
|
472
|
+
this.name = "CrowdtestRequestError";
|
|
473
|
+
}
|
|
474
|
+
status;
|
|
475
|
+
};
|
|
476
|
+
async function failure(response, action) {
|
|
477
|
+
let detail = "";
|
|
478
|
+
try {
|
|
479
|
+
const body = await response.json();
|
|
480
|
+
if (typeof body === "object" && body !== null) {
|
|
481
|
+
if ("detail" in body && typeof body.detail === "string") detail = body.detail;
|
|
482
|
+
else if ("message" in body && typeof body.message === "string") detail = body.message;
|
|
483
|
+
}
|
|
484
|
+
} catch {
|
|
485
|
+
}
|
|
486
|
+
return new CrowdtestRequestError(response.status, `${action}\u5931\u8D25\uFF08HTTP ${response.status}${detail ? `\uFF1A${detail}` : ""}\uFF09`);
|
|
487
|
+
}
|
|
488
|
+
function platformUrl(value, allowQuery) {
|
|
489
|
+
let url;
|
|
490
|
+
try {
|
|
491
|
+
url = new URL(value);
|
|
492
|
+
} catch {
|
|
493
|
+
throw new Error("\u5E73\u53F0\u5730\u5740\u65E0\u6548");
|
|
494
|
+
}
|
|
495
|
+
const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost";
|
|
496
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) throw new Error("\u5E73\u53F0\u5730\u5740\u5FC5\u987B\u4F7F\u7528 HTTPS");
|
|
497
|
+
if (url.username || url.password || url.hash || !allowQuery && url.search) throw new Error("\u5E73\u53F0\u5730\u5740\u5305\u542B\u4E0D\u652F\u6301\u7684\u8D26\u53F7\u3001\u67E5\u8BE2\u53C2\u6570\u6216\u7247\u6BB5");
|
|
498
|
+
return url;
|
|
499
|
+
}
|
|
500
|
+
function normalizeServerBaseUrl(value) {
|
|
501
|
+
const url = platformUrl(value, false);
|
|
502
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
503
|
+
}
|
|
504
|
+
var CrowdtestBffClient = class {
|
|
505
|
+
constructor(serverBaseUrl, fetchImpl = fetch) {
|
|
506
|
+
this.serverBaseUrl = serverBaseUrl;
|
|
507
|
+
this.fetchImpl = fetchImpl;
|
|
508
|
+
}
|
|
509
|
+
serverBaseUrl;
|
|
510
|
+
fetchImpl;
|
|
511
|
+
url(path) {
|
|
512
|
+
return `${this.serverBaseUrl}/api/crowdtest/local-runs${path}`;
|
|
513
|
+
}
|
|
514
|
+
async sessionStatus(token, signal) {
|
|
515
|
+
const response = await this.fetchImpl(this.url("/session/status"), { headers: { authorization: `Bearer ${token}` }, cache: "no-store", signal });
|
|
516
|
+
if (!response.ok) throw await failure(response, "\u68C0\u67E5\u4F1A\u8BDD\u5907\u4EFD");
|
|
517
|
+
return parseBackup(await response.json());
|
|
518
|
+
}
|
|
519
|
+
async exchangeTicket(ticket, signal) {
|
|
520
|
+
const response = await this.fetchImpl(this.url("/dsh/ticket/exchange"), {
|
|
521
|
+
method: "POST",
|
|
522
|
+
headers: { "content-type": "application/json" },
|
|
523
|
+
body: JSON.stringify({ ticket }),
|
|
524
|
+
signal
|
|
525
|
+
});
|
|
526
|
+
if (!response.ok) throw await failure(response, "\u5151\u6362\u9886\u53D6\u53E3\u4EE4");
|
|
527
|
+
const value = await response.json();
|
|
528
|
+
if (!record(value) || !text(value.token) || !positive(value.tokenExpiresAt) || value.tokenExpiresAt <= Date.now()) {
|
|
529
|
+
throw new Error("\u5E73\u53F0\u8FD4\u56DE\u7684\u8FD0\u884C\u51ED\u8BC1\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u9886\u53D6");
|
|
530
|
+
}
|
|
531
|
+
return { token: value.token, tokenExpiresAt: value.tokenExpiresAt };
|
|
532
|
+
}
|
|
533
|
+
async manifest(token, signal) {
|
|
534
|
+
const response = await this.fetchImpl(this.url("/dsh/manifest"), {
|
|
535
|
+
headers: { authorization: `Bearer ${token}`, "x-autocase-client-version": CLIENT_VERSION },
|
|
536
|
+
signal
|
|
537
|
+
});
|
|
538
|
+
if (!response.ok) throw await failure(response, "\u62C9\u53D6\u4EFB\u52A1\u6E05\u5355");
|
|
539
|
+
return parseManifest(await response.json());
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Upload one session backup: request an exact-size signed POST, send the archive to TOS, then let the BFF verify it.
|
|
543
|
+
* @param token - local-run Router Token.
|
|
544
|
+
* @param archive - complete archive bytes.
|
|
545
|
+
* @param descriptor - size, SHA-256 and format the BFF signs and verifies.
|
|
546
|
+
* @param signal - cancellation.
|
|
547
|
+
*/
|
|
548
|
+
async uploadSessionBackup(token, archive, descriptor, signal) {
|
|
549
|
+
const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
|
|
550
|
+
const signed = await this.fetchImpl(this.url("/session/upload-url"), {
|
|
551
|
+
method: "POST",
|
|
552
|
+
headers,
|
|
553
|
+
body: JSON.stringify(descriptor),
|
|
554
|
+
signal
|
|
555
|
+
});
|
|
556
|
+
if (!signed.ok) throw await failure(signed, "\u7533\u8BF7\u4F1A\u8BDD\u4E0A\u4F20\u5730\u5740");
|
|
557
|
+
const post = await signed.json();
|
|
558
|
+
const form = new FormData();
|
|
559
|
+
for (const [key, value] of Object.entries(post.formFields)) form.append(key, value);
|
|
560
|
+
form.append(post.fileField, new Blob([archive], { type: "application/gzip" }), "session.tar.gz");
|
|
561
|
+
const uploaded = await this.fetchImpl(post.signedPostUrl, { method: "POST", body: form, signal });
|
|
562
|
+
if (!uploaded.ok) throw await failure(uploaded, "\u4E0A\u4F20\u4F1A\u8BDD\u5F52\u6863");
|
|
563
|
+
const verified = await this.fetchImpl(this.url("/session/verify"), {
|
|
564
|
+
method: "POST",
|
|
565
|
+
headers,
|
|
566
|
+
body: JSON.stringify(descriptor),
|
|
567
|
+
signal
|
|
568
|
+
});
|
|
569
|
+
if (!verified.ok) throw await failure(verified, "\u6821\u9A8C\u4F1A\u8BDD\u5907\u4EFD");
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
// src/state.ts
|
|
574
|
+
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
|
575
|
+
import { homedir as homedir2 } from "node:os";
|
|
576
|
+
import { dirname, join as join3, relative, resolve as resolve2 } from "node:path";
|
|
577
|
+
|
|
578
|
+
// src/run.ts
|
|
579
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
580
|
+
import { join as join2 } from "node:path";
|
|
581
|
+
function identityKey(run) {
|
|
582
|
+
return JSON.stringify([run.serverBaseUrl, run.projectId, run.taskId, run.taskModelRunId, run.sessionId]);
|
|
583
|
+
}
|
|
584
|
+
function scopedResources(identity, workspaceRoot) {
|
|
585
|
+
const key = createHash2("sha256").update(identityKey(identity)).digest("hex");
|
|
586
|
+
return {
|
|
587
|
+
credentialRef: `CROWDTEST_RUN_${key.toUpperCase()}_TOKEN`,
|
|
588
|
+
provider: `crowdtest-run-${key}`,
|
|
589
|
+
workspace: join2(workspaceRoot, `${identity.projectId}-${identity.taskId}-${identity.taskModelRunId}-${key}`)
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
function parseJoinArguments(rawInput, configuredBaseUrl) {
|
|
593
|
+
const [input, explicitUrl, extra] = rawInput.trim().split(/\s+/);
|
|
594
|
+
const match = /^(?:([A-Z])-)?([A-Z2-9]{4})-?([A-Z2-9]{4})$/.exec(input?.toUpperCase() ?? "");
|
|
595
|
+
if (!match || extra !== void 0) throw new Error("\u7528\u6CD5\uFF1A/crowdtest <\u9886\u53D6\u53E3\u4EE4> <\u5E73\u53F0\u5730\u5740>\uFF0C\u8BF7\u4ECE\u8BC4\u6D4B\u9875\u590D\u5236\u5B8C\u6574\u547D\u4EE4");
|
|
596
|
+
if (match[1] && match[1] !== "S" && match[1] !== "B") throw new Error("\u53E3\u4EE4\u524D\u7F00\u65E0\u6CD5\u8BC6\u522B\uFF0C\u8BF7\u4ECE\u8BC4\u6D4B\u9875\u590D\u5236\u5B8C\u6574\u547D\u4EE4");
|
|
597
|
+
const base = explicitUrl ?? configuredBaseUrl;
|
|
598
|
+
if (!base) throw new Error("\u7F3A\u5C11\u5E73\u53F0\u5730\u5740\uFF0C\u8BF7\u4ECE\u8BC4\u6D4B\u9875\u590D\u5236\u5B8C\u6574\u547D\u4EE4 /crowdtest <\u9886\u53D6\u53E3\u4EE4> <\u5E73\u53F0\u5730\u5740>");
|
|
599
|
+
return { ticket: `${match[2]}-${match[3]}`, serverBaseUrl: normalizeServerBaseUrl(base) };
|
|
600
|
+
}
|
|
601
|
+
function piAiProviderProfile(manifest, resources) {
|
|
602
|
+
const model = manifest.model;
|
|
603
|
+
const entry = { id: model.alias, name: model.alias, input: [...model.input] };
|
|
604
|
+
if (model.contextWindow !== void 0) entry.contextWindow = model.contextWindow;
|
|
605
|
+
if (model.maxTokens !== void 0) entry.maxTokens = model.maxTokens;
|
|
606
|
+
if (model.reasoningEfforts !== void 0) entry.reasoningEfforts = model.reasoningEfforts;
|
|
607
|
+
return {
|
|
608
|
+
displayName: `CrowdTest #${manifest.taskModelRunId}`,
|
|
609
|
+
apiKeyEnv: resources.credentialRef,
|
|
610
|
+
api: model.protocol,
|
|
611
|
+
baseURL: model.baseUrl,
|
|
612
|
+
models: [entry]
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
function runModelSelection(manifest, resources) {
|
|
616
|
+
const selection = { provider: resources.provider, model: manifest.model.alias };
|
|
617
|
+
if (manifest.model.reasoningEffort !== void 0) selection.reasoningEffort = manifest.model.reasoningEffort;
|
|
618
|
+
return selection;
|
|
619
|
+
}
|
|
620
|
+
function isRunRoute(model, provider, config) {
|
|
621
|
+
return config.provider === provider && config.model === model.alias;
|
|
622
|
+
}
|
|
623
|
+
function firstTaskMessage(prompt, attachmentPaths) {
|
|
624
|
+
const sections = [
|
|
625
|
+
"<crowdtest-runtime-contract>",
|
|
626
|
+
"\u6BCF\u8F6E\u56DE\u7B54\u7ED3\u675F\u4E0D\u4EE3\u8868\u4EFB\u52A1\u5B8C\u6210\u3002\u8BF7\u5148\u8BFB\u53D6\u9644\u4EF6\u5E76\u5B8C\u6210\u5168\u90E8\u5B9E\u73B0\u4E0E\u9A8C\u8BC1\uFF1B\u5B8C\u6210\u540E\uFF0C\u5411\u7528\u6237\u6C47\u62A5\u5B8C\u6210\u5185\u5BB9\u548C\u9A8C\u8BC1\u7ED3\u679C\u3002",
|
|
627
|
+
"\u4EFB\u52A1\u4EA7\u7269\u7531\u7528\u6237\u672C\u4EBA\u5728 CrowdTest \u5E73\u53F0\u7684\u8BC4\u6D4B\u9875\u4E0A\u4F20\u5E76\u63D0\u4EA4\u8BC4\u6D4B\uFF0C\u4E0D\u8981\u81EA\u884C\u4E0A\u4F20\uFF0C\u4E5F\u4E0D\u8981\u8BFB\u53D6\u3001\u6253\u5370\u6216\u5C55\u793A\u5E73\u53F0\u51ED\u636E\u3002",
|
|
628
|
+
"\u4F1A\u8BDD\u7531 CrowdTest \u63D2\u4EF6\u81EA\u52A8\u5907\u4EFD\uFF0C\u65E0\u9700\u4E5F\u4E0D\u5F97\u7531\u6A21\u578B\u81EA\u884C\u4E0A\u4F20\u3002\u9700\u8981\u7528\u6237\u8F93\u5165\u65F6\uFF0C\u76F4\u63A5\u5728\u5F53\u524D\u4F1A\u8BDD\u4E2D\u63D0\u95EE\u5E76\u7B49\u5F85\u3002",
|
|
629
|
+
"</crowdtest-runtime-contract>",
|
|
630
|
+
"",
|
|
631
|
+
"<task>",
|
|
632
|
+
prompt,
|
|
633
|
+
"</task>"
|
|
634
|
+
];
|
|
635
|
+
if (attachmentPaths.length > 0) {
|
|
636
|
+
sections.push(
|
|
637
|
+
"",
|
|
638
|
+
"<attachments>",
|
|
639
|
+
"\u9644\u4EF6\u5DF2\u4E0B\u8F7D\u5230\u4EE5\u4E0B\u8DEF\u5F84\uFF0C\u8BF7\u5148\u8BFB\u53D6\u5E76\u7ED3\u5408\u9644\u4EF6\u5B8C\u6210\u4EFB\u52A1\uFF1A",
|
|
640
|
+
...attachmentPaths.map((path) => `- ${path}`),
|
|
641
|
+
"\u4E0A\u8FF0\u8DEF\u5F84\u662F\u539F\u59CB\u9644\u4EF6\uFF1B\u5982\u9700\u89E3\u538B\u6216\u8F6C\u6362\uFF0C\u8BF7\u5199\u5165\u5DE5\u4F5C\u533A\u5176\u4ED6\u4F4D\u7F6E\uFF0C\u4E0D\u8981\u4FEE\u6539\u9644\u4EF6\u76EE\u5F55\u3002",
|
|
642
|
+
"</attachments>"
|
|
643
|
+
);
|
|
644
|
+
}
|
|
645
|
+
return sections.join("\n");
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// src/state.ts
|
|
649
|
+
var RECLAIM_MESSAGE = "\u6B64\u4F1A\u8BDD\u7684\u8FD0\u884C\u8D44\u6E90\u5F52\u5C5E\u4E0D\u660E\u786E\uFF0C\u8BF7\u4ECE\u5E73\u53F0\u91CD\u65B0\u9886\u53D6\u4EFB\u52A1";
|
|
650
|
+
function defaultStateFile() {
|
|
651
|
+
return join3(process.env.DSH_HOME || join3(homedir2(), ".dsh"), "crowdtest", "runs.json");
|
|
652
|
+
}
|
|
653
|
+
async function workspaceKey(workspace) {
|
|
654
|
+
const path = resolve2(workspace);
|
|
655
|
+
let ancestor = path;
|
|
656
|
+
for (; ; ) {
|
|
657
|
+
try {
|
|
658
|
+
const directory = await stat(ancestor, { bigint: true });
|
|
659
|
+
return `${directory.dev}:${directory.ino}/${relative(ancestor, path)}`;
|
|
660
|
+
} catch (error) {
|
|
661
|
+
const parent = dirname(ancestor);
|
|
662
|
+
if (error.code !== "ENOENT" || parent === ancestor) return void 0;
|
|
663
|
+
ancestor = parent;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
var RunBindings = class {
|
|
668
|
+
constructor(file) {
|
|
669
|
+
this.file = file;
|
|
670
|
+
}
|
|
671
|
+
file;
|
|
672
|
+
bindings = /* @__PURE__ */ new Map();
|
|
673
|
+
duplicateOwners = [];
|
|
674
|
+
writing = Promise.resolve();
|
|
675
|
+
async load() {
|
|
676
|
+
let text2;
|
|
677
|
+
try {
|
|
678
|
+
text2 = await readFile(this.file, "utf8");
|
|
679
|
+
} catch (error) {
|
|
680
|
+
if (error.code === "ENOENT") return;
|
|
681
|
+
throw error;
|
|
682
|
+
}
|
|
683
|
+
const { runs } = JSON.parse(text2);
|
|
684
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
685
|
+
const byCredential = /* @__PURE__ */ new Map();
|
|
686
|
+
const byProvider = /* @__PURE__ */ new Map();
|
|
687
|
+
const byWorkspace = /* @__PURE__ */ new Map();
|
|
688
|
+
const blocked = /* @__PURE__ */ new Set();
|
|
689
|
+
const sharedWorkspaces = /* @__PURE__ */ new Set();
|
|
690
|
+
const rows = runs.map((row) => ({
|
|
691
|
+
...row,
|
|
692
|
+
serverBaseUrl: normalizeServerBaseUrl(row.serverBaseUrl),
|
|
693
|
+
provider: row.provider ?? `crowdtest-run-${row.taskModelRunId}`,
|
|
694
|
+
resourceStatus: row.resourceStatus ?? "ready"
|
|
695
|
+
}));
|
|
696
|
+
for (const binding of rows) {
|
|
697
|
+
const workspace = await workspaceKey(binding.workspace);
|
|
698
|
+
if (workspace === void 0) sharedWorkspaces.add(binding.sessionId);
|
|
699
|
+
else {
|
|
700
|
+
const previous = byWorkspace.get(workspace);
|
|
701
|
+
if (!previous) byWorkspace.set(workspace, binding);
|
|
702
|
+
else if (identityKey(previous) !== identityKey(binding)) {
|
|
703
|
+
sharedWorkspaces.add(binding.sessionId);
|
|
704
|
+
sharedWorkspaces.add(previous.sessionId);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
for (const [index, key] of [[bySession, binding.sessionId], [byCredential, binding.credentialRef], [byProvider, binding.provider]]) {
|
|
708
|
+
const previous = index.get(key);
|
|
709
|
+
if (!previous) {
|
|
710
|
+
index.set(key, binding);
|
|
711
|
+
} else if (identityKey(previous) !== identityKey(binding)) {
|
|
712
|
+
blocked.add(previous.sessionId);
|
|
713
|
+
blocked.add(binding.sessionId);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
for (const binding of rows) {
|
|
718
|
+
if (sharedWorkspaces.has(binding.sessionId)) binding.workspaceConflict = true;
|
|
719
|
+
if (blocked.has(binding.sessionId) || binding.workspaceConflict) binding.resourceStatus = "reclaim-required";
|
|
720
|
+
const owner = bySession.get(binding.sessionId);
|
|
721
|
+
if (owner === binding) this.bindings.set(binding.sessionId, binding);
|
|
722
|
+
else if (identityKey(owner) !== identityKey(binding)) this.duplicateOwners.push(binding);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
get(sessionId) {
|
|
726
|
+
return this.bindings.get(sessionId);
|
|
727
|
+
}
|
|
728
|
+
ownerForClaim(identity) {
|
|
729
|
+
const saved = this.get(identity.sessionId);
|
|
730
|
+
if (this.duplicateOwners.some((run) => run.sessionId === identity.sessionId)) {
|
|
731
|
+
throw new Error("\u6B64\u4F1A\u8BDD\u6807\u8BC6\u5BF9\u5E94\u591A\u4E2A\u4F17\u6D4B\u8FD0\u884C\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u6838\u5BF9\u5F52\u5C5E\u540E\u91CD\u65B0\u9886\u53D6");
|
|
732
|
+
}
|
|
733
|
+
if (saved && identityKey(saved) !== identityKey(identity)) {
|
|
734
|
+
throw new Error("\u6B64\u4F1A\u8BDD\u5DF2\u7ED1\u5B9A\u5176\u4ED6\u4F17\u6D4B\u8FD0\u884C\uFF0C\u65E0\u6CD5\u9886\u53D6");
|
|
735
|
+
}
|
|
736
|
+
return saved;
|
|
737
|
+
}
|
|
738
|
+
put(binding) {
|
|
739
|
+
this.writing = this.writing.catch(() => void 0).then(async () => {
|
|
740
|
+
const next = new Map(this.bindings);
|
|
741
|
+
const previous = next.get(binding.sessionId);
|
|
742
|
+
if (previous && identityKey(previous) === identityKey(binding)) {
|
|
743
|
+
binding.lastUploadedSha256 ??= previous.lastUploadedSha256;
|
|
744
|
+
binding.lastUploadedAt ??= previous.lastUploadedAt;
|
|
745
|
+
binding.lastSyncedAtMs ??= previous.lastSyncedAtMs;
|
|
746
|
+
}
|
|
747
|
+
next.set(binding.sessionId, binding);
|
|
748
|
+
await this.write([...next.values()]);
|
|
749
|
+
this.bindings.set(binding.sessionId, binding);
|
|
750
|
+
});
|
|
751
|
+
return this.writing;
|
|
752
|
+
}
|
|
753
|
+
recordSuccessfulSync({ binding, confirmedAtMs, uploadedSha256, isCurrent }) {
|
|
754
|
+
let recorded = false;
|
|
755
|
+
this.writing = this.writing.catch(() => void 0).then(async () => {
|
|
756
|
+
if (!isCurrent()) return;
|
|
757
|
+
const confirmed = {
|
|
758
|
+
...binding,
|
|
759
|
+
lastSyncedAtMs: confirmedAtMs,
|
|
760
|
+
...uploadedSha256 === void 0 ? {} : { lastUploadedSha256: uploadedSha256, lastUploadedAt: confirmedAtMs }
|
|
761
|
+
};
|
|
762
|
+
await this.write([...this.bindings.values()].map((run) => run === binding ? confirmed : run));
|
|
763
|
+
if (!isCurrent()) {
|
|
764
|
+
await this.write([...this.bindings.values()]);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
Object.assign(binding, confirmed);
|
|
768
|
+
recorded = true;
|
|
769
|
+
});
|
|
770
|
+
return this.writing.then(() => recorded);
|
|
771
|
+
}
|
|
772
|
+
async write(runs) {
|
|
773
|
+
const snapshot = JSON.stringify({ version: 1, runs: [...runs, ...this.duplicateOwners] }, null, 2);
|
|
774
|
+
await mkdir(dirname(this.file), { recursive: true, mode: 448 });
|
|
775
|
+
const temporary = `${this.file}.${process.pid}.tmp`;
|
|
776
|
+
await writeFile(temporary, snapshot, { mode: 384 });
|
|
777
|
+
await rename(temporary, this.file);
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
// src/session-backups.ts
|
|
782
|
+
var SessionBackups = class {
|
|
783
|
+
constructor(ctx, bindings, options = {}) {
|
|
784
|
+
this.ctx = ctx;
|
|
785
|
+
this.bindings = bindings;
|
|
786
|
+
this.options = options;
|
|
787
|
+
this.nativeSessionRoot = resolveNativeSessionRoot(options.nativeSessionRoot);
|
|
788
|
+
}
|
|
789
|
+
ctx;
|
|
790
|
+
bindings;
|
|
791
|
+
options;
|
|
792
|
+
lanes = /* @__PURE__ */ new Map();
|
|
793
|
+
epoch = 0;
|
|
794
|
+
closed = false;
|
|
795
|
+
nativeSessionRoot;
|
|
796
|
+
lane(id) {
|
|
797
|
+
if (this.closed) return void 0;
|
|
798
|
+
const binding = this.bindings.get(id);
|
|
799
|
+
const previous = this.lanes.get(id);
|
|
800
|
+
if (previous?.binding === binding) return previous;
|
|
801
|
+
if (previous) {
|
|
802
|
+
previous.abort.abort();
|
|
803
|
+
clearTimeout(previous.timer);
|
|
804
|
+
}
|
|
805
|
+
if (!binding) {
|
|
806
|
+
this.lanes.delete(id);
|
|
807
|
+
return void 0;
|
|
808
|
+
}
|
|
809
|
+
const lane = {
|
|
810
|
+
binding,
|
|
811
|
+
abort: new AbortController(),
|
|
812
|
+
contentRevision: 0,
|
|
813
|
+
syncing: false,
|
|
814
|
+
trailing: false,
|
|
815
|
+
view: { sessionId: id, taskId: binding.taskId, runId: binding.taskModelRunId, bindingEpoch: ++this.epoch, revision: 0, phase: "checking", uploadedAtMs: null, lastSyncedAtMs: binding.lastSyncedAtMs ?? null }
|
|
816
|
+
};
|
|
817
|
+
this.lanes.set(id, lane);
|
|
818
|
+
return lane;
|
|
819
|
+
}
|
|
820
|
+
active(lane) {
|
|
821
|
+
return !this.closed && !lane.abort.signal.aborted && this.bindings.get(lane.binding.sessionId) === lane.binding;
|
|
822
|
+
}
|
|
823
|
+
publish(lane, phase, uploadedAtMs = lane.view.uploadedAtMs) {
|
|
824
|
+
if (!this.active(lane)) return null;
|
|
825
|
+
lane.view = { ...lane.view, revision: lane.view.revision + 1, phase, uploadedAtMs, lastSyncedAtMs: lane.binding.lastSyncedAtMs ?? null };
|
|
826
|
+
return lane.view;
|
|
827
|
+
}
|
|
828
|
+
dirtyPhase(lane) {
|
|
829
|
+
return lane.view.phase === "failed" ? "failed" : "dirty";
|
|
830
|
+
}
|
|
831
|
+
changed(id, completedTurn = false) {
|
|
832
|
+
const lane = this.lane(id);
|
|
833
|
+
if (!lane) return;
|
|
834
|
+
lane.contentRevision++;
|
|
835
|
+
this.publish(lane, lane.syncing ? "uploading" : this.dirtyPhase(lane));
|
|
836
|
+
if (!completedTurn || this.options.autoUpload === false) return;
|
|
837
|
+
if (lane.syncing) {
|
|
838
|
+
lane.trailing = true;
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
this.schedule(lane);
|
|
842
|
+
}
|
|
843
|
+
schedule(lane) {
|
|
844
|
+
clearTimeout(lane.timer);
|
|
845
|
+
lane.timer = setTimeout(() => {
|
|
846
|
+
lane.timer = void 0;
|
|
847
|
+
void this.sync(lane.binding.sessionId).catch((error) => this.ctx.logger.warn(`crowdtest: automatic upload failed for session ${lane.binding.sessionId}: ${error instanceof Error ? error.message : String(error)}`));
|
|
848
|
+
}, this.options.uploadDebounceMs ?? 3e3);
|
|
849
|
+
}
|
|
850
|
+
inspect(id) {
|
|
851
|
+
const lane = this.lane(id);
|
|
852
|
+
if (!lane) return Promise.resolve(null);
|
|
853
|
+
if (lane.syncing) return Promise.resolve(lane.view);
|
|
854
|
+
if (lane.operation) return lane.operation;
|
|
855
|
+
return this.start(lane, false);
|
|
856
|
+
}
|
|
857
|
+
sync(id) {
|
|
858
|
+
const lane = this.lane(id);
|
|
859
|
+
if (!lane) return Promise.resolve(null);
|
|
860
|
+
if (lane.syncing && lane.operation) return lane.operation;
|
|
861
|
+
clearTimeout(lane.timer);
|
|
862
|
+
lane.timer = void 0;
|
|
863
|
+
const prior = lane.operation;
|
|
864
|
+
lane.syncing = true;
|
|
865
|
+
this.publish(lane, "uploading");
|
|
866
|
+
return this.start(lane, true, prior);
|
|
867
|
+
}
|
|
868
|
+
start(lane, upload, prior) {
|
|
869
|
+
const operation = (async () => {
|
|
870
|
+
if (prior) await prior.catch(() => void 0);
|
|
871
|
+
if (upload) this.publish(lane, "uploading");
|
|
872
|
+
let confirmation;
|
|
873
|
+
do {
|
|
874
|
+
lane.trailing = false;
|
|
875
|
+
confirmation = await this.check(lane, upload);
|
|
876
|
+
} while (upload && lane.trailing && this.active(lane));
|
|
877
|
+
if (upload && confirmation) await this.confirm(lane, confirmation);
|
|
878
|
+
return this.active(lane) ? lane.view : null;
|
|
879
|
+
})().catch((error) => {
|
|
880
|
+
this.publish(lane, upload || lane.view.phase === "failed" ? "failed" : "unknown");
|
|
881
|
+
if (upload) throw error;
|
|
882
|
+
return this.active(lane) ? lane.view : null;
|
|
883
|
+
}).finally(() => {
|
|
884
|
+
if (lane.operation === operation) {
|
|
885
|
+
lane.operation = void 0;
|
|
886
|
+
lane.syncing = false;
|
|
887
|
+
if (lane.trailing && this.active(lane)) {
|
|
888
|
+
lane.trailing = false;
|
|
889
|
+
this.schedule(lane);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
});
|
|
893
|
+
lane.operation = operation;
|
|
894
|
+
return operation;
|
|
895
|
+
}
|
|
896
|
+
async confirm(lane, confirmation) {
|
|
897
|
+
const current = () => this.active(lane) && lane.contentRevision === confirmation.revision;
|
|
898
|
+
if (!current()) return;
|
|
899
|
+
if (await this.sourceRevision(lane) !== confirmation.sourceRevision) {
|
|
900
|
+
this.publish(lane, this.dirtyPhase(lane));
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
if (!current()) return;
|
|
904
|
+
const recorded = await this.bindings.recordSuccessfulSync({ binding: lane.binding, confirmedAtMs: confirmation.confirmedAtMs, uploadedSha256: confirmation.uploadedSha256, isCurrent: current });
|
|
905
|
+
const sourceCurrent = await this.sourceRevision(lane) === confirmation.sourceRevision;
|
|
906
|
+
if (!recorded || !current() || !sourceCurrent) {
|
|
907
|
+
this.publish(lane, this.dirtyPhase(lane), confirmation.uploadedAtMs);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
this.publish(lane, "synced", confirmation.uploadedAtMs);
|
|
911
|
+
}
|
|
912
|
+
async check(lane, upload) {
|
|
913
|
+
if (!this.active(lane)) return;
|
|
914
|
+
const { binding } = lane;
|
|
915
|
+
if (binding.resourceStatus !== "ready") throw new Error(RECLAIM_MESSAGE);
|
|
916
|
+
const resolved = await this.ctx.credentials.resolve(binding.credentialRef);
|
|
917
|
+
if (!this.active(lane)) return;
|
|
918
|
+
if (!resolved) throw new Error("\u672A\u627E\u5230\u672C\u6B21\u8FD0\u884C\u7684\u5E73\u53F0\u51ED\u8BC1\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C\u9886\u53D6\u53E3\u4EE4");
|
|
919
|
+
const revision = lane.contentRevision;
|
|
920
|
+
await this.ctx.sessionPersistence.flush();
|
|
921
|
+
if (!this.active(lane)) return;
|
|
922
|
+
const file = await captureNativeSession({
|
|
923
|
+
persistence: this.ctx.sessionPersistence,
|
|
924
|
+
sessionId: binding.sessionId,
|
|
925
|
+
nativeSessionRoot: this.nativeSessionRoot,
|
|
926
|
+
secret: resolved.value,
|
|
927
|
+
maxBytes: binding.backupMaxBytes
|
|
928
|
+
});
|
|
929
|
+
if (!this.active(lane)) return;
|
|
930
|
+
const archive = buildSessionArchive(binding.sessionId, file);
|
|
931
|
+
if (archive.size > binding.backupMaxBytes) throw new Error("\u4F1A\u8BDD\u5F52\u6863\u8D85\u8FC7\u5E73\u53F0\u4E0A\u9650");
|
|
932
|
+
if (revision !== lane.contentRevision) {
|
|
933
|
+
this.publish(lane, this.dirtyPhase(lane));
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
const client = new CrowdtestBffClient(binding.serverBaseUrl);
|
|
937
|
+
const equal = (backup2) => backup2 !== null && backup2.sha256 === archive.sha256 && backup2.size === archive.size && backup2.format === binding.backupFormat;
|
|
938
|
+
let backup = await client.sessionStatus(resolved.value, lane.abort.signal);
|
|
939
|
+
if (!this.active(lane)) return;
|
|
940
|
+
let uploadedSha256;
|
|
941
|
+
if (upload && !equal(backup)) {
|
|
942
|
+
if (revision !== lane.contentRevision || await this.sourceRevision(lane) !== file.sourceRevision) {
|
|
943
|
+
this.publish(lane, this.dirtyPhase(lane));
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
if (!this.active(lane)) return;
|
|
947
|
+
await client.uploadSessionBackup(resolved.value, archive.bytes, { size: archive.size, sha256: archive.sha256, format: binding.backupFormat }, lane.abort.signal);
|
|
948
|
+
if (!this.active(lane)) return;
|
|
949
|
+
backup = await client.sessionStatus(resolved.value, lane.abort.signal);
|
|
950
|
+
if (!this.active(lane)) return;
|
|
951
|
+
if (!equal(backup)) throw new Error("\u5E73\u53F0\u5C1A\u672A\u786E\u8BA4\u672C\u6B21\u4F1A\u8BDD\u5907\u4EFD\uFF0C\u8BF7\u91CD\u8BD5");
|
|
952
|
+
uploadedSha256 = archive.sha256;
|
|
953
|
+
}
|
|
954
|
+
const sourceCurrent = await this.sourceRevision(lane) === file.sourceRevision;
|
|
955
|
+
if (!this.active(lane)) return;
|
|
956
|
+
const synced = equal(backup) && revision === lane.contentRevision && sourceCurrent;
|
|
957
|
+
if (upload && synced) return { revision, sourceRevision: file.sourceRevision, confirmedAtMs: Date.now(), uploadedAtMs: backup?.uploadedAtMs ?? null, uploadedSha256 };
|
|
958
|
+
this.publish(lane, synced ? "synced" : this.dirtyPhase(lane), backup?.uploadedAtMs ?? null);
|
|
959
|
+
}
|
|
960
|
+
sourceRevision(lane) {
|
|
961
|
+
return nativeSessionRevision({ persistence: this.ctx.sessionPersistence, sessionId: lane.binding.sessionId, nativeSessionRoot: this.nativeSessionRoot });
|
|
962
|
+
}
|
|
963
|
+
async dispose() {
|
|
964
|
+
this.closed = true;
|
|
965
|
+
const pending = [];
|
|
966
|
+
for (const lane of this.lanes.values()) {
|
|
967
|
+
clearTimeout(lane.timer);
|
|
968
|
+
lane.abort.abort();
|
|
969
|
+
if (lane.operation) pending.push(lane.operation);
|
|
970
|
+
}
|
|
971
|
+
await Promise.allSettled(pending);
|
|
972
|
+
this.lanes.clear();
|
|
973
|
+
}
|
|
974
|
+
};
|
|
975
|
+
|
|
976
|
+
// src/index.ts
|
|
977
|
+
var name = "crowdtest";
|
|
978
|
+
var inject = [
|
|
979
|
+
"typert",
|
|
980
|
+
"commands",
|
|
981
|
+
"credentials",
|
|
982
|
+
"settings",
|
|
983
|
+
"workspaceController",
|
|
984
|
+
"sessionController",
|
|
985
|
+
"agentDefaultModel",
|
|
986
|
+
"sessionPersistence",
|
|
987
|
+
"agents"
|
|
988
|
+
];
|
|
989
|
+
var PLUGIN_RECORD_BINDING = "plugin:dsh-crowdtest/binding";
|
|
990
|
+
function errorText(error) {
|
|
991
|
+
return error instanceof Error ? error.message : String(error);
|
|
992
|
+
}
|
|
993
|
+
async function sha256File(path) {
|
|
994
|
+
try {
|
|
995
|
+
return createHash3("sha256").update(await readFile2(path)).digest("hex");
|
|
996
|
+
} catch (error) {
|
|
997
|
+
if (error.code === "ENOENT") return void 0;
|
|
998
|
+
throw error;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
async function downloadAttachment(directory, attachment, signal) {
|
|
1002
|
+
const fileName = attachment.name;
|
|
1003
|
+
const target = join4(directory, fileName);
|
|
1004
|
+
const existing = await sha256File(target);
|
|
1005
|
+
if (existing !== void 0 && attachment.sha256 !== null && existing === attachment.sha256) return fileName;
|
|
1006
|
+
const response = await fetch(attachment.url, { signal });
|
|
1007
|
+
if (!response.ok) throw new Error(`\u4E0B\u8F7D\u9644\u4EF6 ${fileName} \u5931\u8D25\uFF08HTTP ${response.status}\uFF09`);
|
|
1008
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
1009
|
+
if (bytes.length !== attachment.size) throw new Error(`\u9644\u4EF6 ${fileName} \u5927\u5C0F\u6821\u9A8C\u5931\u8D25`);
|
|
1010
|
+
const digest = createHash3("sha256").update(bytes).digest("hex");
|
|
1011
|
+
if (attachment.sha256 !== null && digest !== attachment.sha256) throw new Error(`\u9644\u4EF6 ${fileName} SHA-256 \u6821\u9A8C\u5931\u8D25`);
|
|
1012
|
+
await writeFile2(target, bytes, { mode: 256 });
|
|
1013
|
+
return fileName;
|
|
1014
|
+
}
|
|
1015
|
+
async function sessionExists(ctx, sessionId) {
|
|
1016
|
+
if (ctx.agents.get(sessionId) !== void 0) return true;
|
|
1017
|
+
try {
|
|
1018
|
+
const handle = await ctx.sessionPersistence.open(sessionId, "read");
|
|
1019
|
+
await handle.close();
|
|
1020
|
+
return true;
|
|
1021
|
+
} catch (error) {
|
|
1022
|
+
if (error instanceof Error && error.name === "SessionPersistenceNotFoundError") return false;
|
|
1023
|
+
throw error;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
async function recordCreation(ctx, manifest, provider, claimNonce) {
|
|
1027
|
+
const agent = ctx.agents.get(manifest.sessionId);
|
|
1028
|
+
if (!agent) throw new Error("\u672A\u627E\u5230\u521A\u521B\u5EFA\u7684\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u8BB0\u5F55\u4F17\u6D4B\u5F52\u5C5E");
|
|
1029
|
+
const specifier = "@deepseek-ai/dsh-session";
|
|
1030
|
+
const { appendPluginRecord } = await import(specifier);
|
|
1031
|
+
appendPluginRecord(agent.session, PLUGIN_RECORD_BINDING, {
|
|
1032
|
+
projectId: manifest.projectId,
|
|
1033
|
+
taskId: manifest.taskId,
|
|
1034
|
+
taskModelRunId: manifest.taskModelRunId,
|
|
1035
|
+
provider,
|
|
1036
|
+
model: manifest.model.alias,
|
|
1037
|
+
claimNonce
|
|
1038
|
+
});
|
|
1039
|
+
await ctx.sessionPersistence.flush();
|
|
1040
|
+
}
|
|
1041
|
+
async function matchesCreationRecord(ctx, saved) {
|
|
1042
|
+
if (!saved.claimNonce) return false;
|
|
1043
|
+
const handle = await ctx.sessionPersistence.open(saved.sessionId, "read");
|
|
1044
|
+
try {
|
|
1045
|
+
const { events } = await handle.read();
|
|
1046
|
+
return events.some((event) => event.ignorable === true && event.type === PLUGIN_RECORD_BINDING && typeof event.data === "object" && event.data !== null && "claimNonce" in event.data && event.data.claimNonce === saved.claimNonce);
|
|
1047
|
+
} finally {
|
|
1048
|
+
await handle.close();
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
async function pinRunModel(ctx, sessionId, selection) {
|
|
1052
|
+
const previous = ctx.agentDefaultModel.currentSelection();
|
|
1053
|
+
await ctx.sessionController.selectModel({ sessionId, ...selection });
|
|
1054
|
+
const deadline = Date.now() + 5e3;
|
|
1055
|
+
while (Date.now() < deadline) {
|
|
1056
|
+
const current = ctx.agentDefaultModel.currentSelection();
|
|
1057
|
+
if (current.provider === selection.provider && current.model === selection.model && current.reasoningEffort === selection.reasoningEffort) break;
|
|
1058
|
+
await new Promise((resolve3) => setTimeout(resolve3, 100));
|
|
1059
|
+
}
|
|
1060
|
+
if (previous.provider !== selection.provider || previous.model !== selection.model || previous.reasoningEffort !== selection.reasoningEffort) {
|
|
1061
|
+
await ctx.agentDefaultModel.saveSelection(previous);
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
async function apply(ctx, config = {}) {
|
|
1065
|
+
const bindings = new RunBindings(config.stateFile ?? defaultStateFile());
|
|
1066
|
+
await bindings.load();
|
|
1067
|
+
const llmEntryId = config.llmEntryId ?? "llm-pi-ai";
|
|
1068
|
+
const workspaceRoot = config.workspaceRoot ?? join4(homedir3(), "CrowdTest");
|
|
1069
|
+
const backups = new SessionBackups(ctx, bindings, config);
|
|
1070
|
+
ctx.effect(() => () => backups.dispose());
|
|
1071
|
+
if (ctx.typert) {
|
|
1072
|
+
const { installRemote: installRemote2 } = await Promise.resolve().then(() => (init_remote_host(), remote_host_exports));
|
|
1073
|
+
await installRemote2(ctx, backups);
|
|
1074
|
+
}
|
|
1075
|
+
ctx.effect(() => ctx.on("session/event", (session, event) => {
|
|
1076
|
+
backups.changed(session.id, event.type === "turn/end");
|
|
1077
|
+
}));
|
|
1078
|
+
ctx.effect(() => ctx.on("agent/request", async (payload, next) => {
|
|
1079
|
+
const saved = bindings.get(payload.agent.id);
|
|
1080
|
+
if (saved && saved.resourceStatus !== "ready") throw new Error(RECLAIM_MESSAGE);
|
|
1081
|
+
const resolved = await next();
|
|
1082
|
+
const binding = bindings.get(payload.agent.id);
|
|
1083
|
+
if (binding !== void 0 && !isRunRoute(binding.model, binding.provider, resolved)) {
|
|
1084
|
+
throw new Error(`CrowdTest \u4EFB\u52A1\u4F1A\u8BDD\u53EA\u80FD\u4F7F\u7528\u5E73\u53F0\u4E0B\u53D1\u7684\u6A21\u578B ${binding.model.alias}\uFF0C\u8BF7\u5207\u6362\u56DE\u8BE5\u6A21\u578B\u540E\u91CD\u8BD5`);
|
|
1085
|
+
}
|
|
1086
|
+
return resolved;
|
|
1087
|
+
}));
|
|
1088
|
+
async function claim(rawInput, signal) {
|
|
1089
|
+
const { ticket, serverBaseUrl } = parseJoinArguments(rawInput, config.serverBaseUrl);
|
|
1090
|
+
signal.throwIfAborted();
|
|
1091
|
+
const client = new CrowdtestBffClient(serverBaseUrl);
|
|
1092
|
+
const { token } = await client.exchangeTicket(ticket, signal);
|
|
1093
|
+
const manifest = await client.manifest(token, signal);
|
|
1094
|
+
const { projectId, taskId, taskModelRunId, sessionId } = manifest;
|
|
1095
|
+
const identity = { serverBaseUrl, projectId, taskId, taskModelRunId, sessionId };
|
|
1096
|
+
const saved = bindings.ownerForClaim(identity);
|
|
1097
|
+
const existing = await sessionExists(ctx, sessionId);
|
|
1098
|
+
if (existing && !saved) throw new Error("\u5E73\u53F0\u5206\u914D\u7684\u4F1A\u8BDD\u6807\u8BC6\u5DF2\u88AB\u666E\u901A\u4F1A\u8BDD\u5360\u7528\uFF0C\u65E0\u6CD5\u9886\u53D6");
|
|
1099
|
+
if (existing && saved?.workspaceConflict) throw new Error("\u6B64\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u533A\u4E0E\u5176\u4ED6\u8FD0\u884C\u5171\u7528\uFF0C\u8BF7\u4ECE\u5E73\u53F0\u91CD\u65B0\u521B\u5EFA\u672C\u673A\u8FD0\u884C");
|
|
1100
|
+
const recovering = saved?.resourceStatus === "creating" || saved?.claimNonce !== void 0;
|
|
1101
|
+
if (existing && saved && recovering && !await matchesCreationRecord(ctx, saved)) {
|
|
1102
|
+
throw new Error("\u65E0\u6CD5\u6838\u5B9E\u6B64\u4F1A\u8BDD\u7684\u521B\u5EFA\u8BB0\u5F55\uFF0C\u8BF7\u4ECE\u5E73\u53F0\u91CD\u65B0\u521B\u5EFA\u672C\u673A\u8FD0\u884C");
|
|
1103
|
+
}
|
|
1104
|
+
const resources = saved && saved.resourceStatus !== "reclaim-required" ? saved : scopedResources(identity, workspaceRoot);
|
|
1105
|
+
const { credentialRef, provider } = resources;
|
|
1106
|
+
const workspace = saved && !saved.workspaceConflict ? saved.workspace : resources.workspace;
|
|
1107
|
+
const binding = {
|
|
1108
|
+
...identity,
|
|
1109
|
+
credentialRef,
|
|
1110
|
+
provider,
|
|
1111
|
+
workspace,
|
|
1112
|
+
resourceStatus: "ready",
|
|
1113
|
+
model: manifest.model,
|
|
1114
|
+
backupFormat: manifest.sessionBackup.format,
|
|
1115
|
+
backupMaxBytes: manifest.sessionBackup.maxBytes
|
|
1116
|
+
};
|
|
1117
|
+
const claimNonce = existing ? void 0 : saved?.claimNonce ?? randomUUID();
|
|
1118
|
+
if (claimNonce) await bindings.put({ ...binding, resourceStatus: "creating", claimNonce });
|
|
1119
|
+
await ctx.credentials.set(credentialRef, token);
|
|
1120
|
+
await ctx.settings.mutate(llmEntryId, [
|
|
1121
|
+
{ op: "set", path: ["providers", provider], value: piAiProviderProfile(manifest, resources) }
|
|
1122
|
+
]);
|
|
1123
|
+
const attachmentDirectory = join4(workspace, "attachments");
|
|
1124
|
+
await mkdir2(workspace, { recursive: true });
|
|
1125
|
+
const attachmentPaths = [];
|
|
1126
|
+
if (manifest.attachments.length > 0) {
|
|
1127
|
+
await mkdir2(attachmentDirectory, { recursive: true });
|
|
1128
|
+
for (const attachment of manifest.attachments) {
|
|
1129
|
+
attachmentPaths.push(`attachments/${await downloadAttachment(attachmentDirectory, attachment, signal)}`);
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
if (claimNonce) {
|
|
1133
|
+
const { workspace: registered } = await ctx.workspaceController.create({ path: workspace });
|
|
1134
|
+
const created = await ctx.sessionController.create({ workspaceId: registered.workspaceId, sessionId });
|
|
1135
|
+
if (created.sessionId !== sessionId) throw new Error("\u521B\u5EFA\u7684\u4F1A\u8BDD\u6807\u8BC6\u4E0E\u5E73\u53F0\u5206\u914D\u7684\u4E0D\u4E00\u81F4\uFF0C\u65E0\u6CD5\u7ED1\u5B9A\u4F17\u6D4B\u8FD0\u884C");
|
|
1136
|
+
await recordCreation(ctx, manifest, provider, claimNonce);
|
|
1137
|
+
}
|
|
1138
|
+
await pinRunModel(ctx, sessionId, runModelSelection(manifest, resources));
|
|
1139
|
+
await bindings.put(binding);
|
|
1140
|
+
if (existing && !recovering) return `\u5DF2\u66F4\u65B0\u4EFB\u52A1\u300C${manifest.title}\u300D\u7684\u8FD0\u884C\u51ED\u8BC1\u4E0E\u6A21\u578B\u8DEF\u7531\u3002\u8BF7\u5728\u4FA7\u680F\u6253\u5F00\u5DE5\u4F5C\u533A ${workspace} \u4E2D\u7684\u4F1A\u8BDD\u7EE7\u7EED\u3002`;
|
|
1141
|
+
const message = firstTaskMessage(manifest.prompt, attachmentPaths);
|
|
1142
|
+
if (config.autoSendPrompt === false) {
|
|
1143
|
+
return `\u5DF2\u9886\u53D6\u4EFB\u52A1\u300C${manifest.title}\u300D\uFF0C\u5DE5\u4F5C\u533A ${workspace}\u3002\u8BF7\u5728\u65B0\u4F1A\u8BDD\u4E2D\u53D1\u9001\u4EFB\u52A1\uFF1A
|
|
1144
|
+
|
|
1145
|
+
${message}`;
|
|
1146
|
+
}
|
|
1147
|
+
await ctx.sessionController.prompt({
|
|
1148
|
+
requestId: randomUUID(),
|
|
1149
|
+
sessionId: manifest.sessionId,
|
|
1150
|
+
mode: "queue",
|
|
1151
|
+
content: [{ type: "text", text: message }]
|
|
1152
|
+
}, signal);
|
|
1153
|
+
return `\u5DF2\u9886\u53D6\u4EFB\u52A1\u300C${manifest.title}\u300D\uFF1A\u5DE5\u4F5C\u533A ${workspace}\uFF0C\u6A21\u578B ${manifest.model.alias}\u3002\u9996\u8F6E\u4EFB\u52A1\u5DF2\u5728\u65B0\u4F1A\u8BDD\u4E2D\u53D1\u9001\uFF0C\u6BCF\u8F6E\u7ED3\u675F\u540E\u4F1A\u81EA\u52A8\u4E0A\u4F20\u4F1A\u8BDD\u5907\u4EFD\u3002`;
|
|
1154
|
+
}
|
|
1155
|
+
let claimQueue = Promise.resolve();
|
|
1156
|
+
ctx.effect(() => ctx.commands.register({
|
|
1157
|
+
name: "crowdtest",
|
|
1158
|
+
description: "\u9886\u53D6 CrowdTest \u4F17\u6D4B\u4EFB\u52A1\uFF1A\u914D\u7F6E\u6D4B\u8BD5\u6A21\u578B\u3001\u4E0B\u8F7D\u9644\u4EF6\u5E76\u5728\u65B0\u4F1A\u8BDD\u4E2D\u5F00\u59CB\u4EFB\u52A1",
|
|
1159
|
+
input: { hint: "<\u9886\u53D6\u53E3\u4EE4> <\u5E73\u53F0\u5730\u5740>" },
|
|
1160
|
+
// The ticket is a one-time credential; keep it out of the Session log.
|
|
1161
|
+
recordInput: false,
|
|
1162
|
+
handler: async ({ rawInput, signal }) => {
|
|
1163
|
+
try {
|
|
1164
|
+
const result = claimQueue.then(() => claim(rawInput, signal));
|
|
1165
|
+
claimQueue = result.then(() => void 0, () => void 0);
|
|
1166
|
+
return { kind: "success", text: await result };
|
|
1167
|
+
} catch (error) {
|
|
1168
|
+
return { kind: "error", text: `\u9886\u53D6 CrowdTest \u4EFB\u52A1\u5931\u8D25\uFF1A${errorText(error)}` };
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}));
|
|
1172
|
+
ctx.effect(() => ctx.commands.register({
|
|
1173
|
+
name: "crowdtest-upload",
|
|
1174
|
+
description: "\u7ACB\u5373\u628A\u5F53\u524D CrowdTest \u4EFB\u52A1\u4F1A\u8BDD\u4E0A\u4F20\u5230\u5E73\u53F0",
|
|
1175
|
+
handler: async ({ agent }) => {
|
|
1176
|
+
const binding = bindings.get(agent.id);
|
|
1177
|
+
if (binding === void 0) {
|
|
1178
|
+
return { kind: "error", text: "\u5F53\u524D\u4F1A\u8BDD\u4E0D\u662F CrowdTest \u4EFB\u52A1\u4F1A\u8BDD\uFF0C\u8BF7\u5728\u9886\u53D6\u4EFB\u52A1\u65F6\u521B\u5EFA\u7684\u4F1A\u8BDD\u4E2D\u6267\u884C" };
|
|
1179
|
+
}
|
|
1180
|
+
try {
|
|
1181
|
+
const view = await backups.sync(binding.sessionId);
|
|
1182
|
+
if (view === null) return { kind: "error", text: "\u540C\u6B65\u5DF2\u53D6\u6D88" };
|
|
1183
|
+
return { kind: "success", text: view.phase === "synced" ? "\u4F1A\u8BDD\u5907\u4EFD\u5DF2\u540C\u6B65\u5230\u5E73\u53F0" : "\u4F1A\u8BDD\u53C8\u6709\u65B0\u5185\u5BB9\uFF0C\u5C1A\u672A\u5168\u90E8\u540C\u6B65\uFF0C\u8BF7\u518D\u6B21\u540C\u6B65" };
|
|
1184
|
+
} catch (error) {
|
|
1185
|
+
return { kind: "error", text: `\u4E0A\u4F20\u4F1A\u8BDD\u5907\u4EFD\u5931\u8D25\uFF1A${errorText(error)}` };
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
}));
|
|
1189
|
+
}
|
|
1190
|
+
export {
|
|
1191
|
+
apply,
|
|
1192
|
+
inject,
|
|
1193
|
+
name
|
|
1194
|
+
};
|