@compivia/runner-platform 0.0.35 → 0.0.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +1397 -298
- package/package.json +2 -2
package/dist/bin.mjs
CHANGED
|
@@ -37,9 +37,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
37
37
|
mod
|
|
38
38
|
));
|
|
39
39
|
|
|
40
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
40
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js
|
|
41
41
|
var require_constants = __commonJS({
|
|
42
|
-
"../../node_modules/.pnpm/ws@8.
|
|
42
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js"(exports, module) {
|
|
43
43
|
"use strict";
|
|
44
44
|
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
|
|
45
45
|
var hasBlob = typeof Blob !== "undefined";
|
|
@@ -60,10 +60,11 @@ var require_constants = __commonJS({
|
|
|
60
60
|
}
|
|
61
61
|
});
|
|
62
62
|
|
|
63
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
63
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/buffer-util.js
|
|
64
64
|
var require_buffer_util = __commonJS({
|
|
65
|
-
"../../node_modules/.pnpm/ws@8.
|
|
65
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/buffer-util.js"(exports, module) {
|
|
66
66
|
"use strict";
|
|
67
|
+
var { websocketMask, websocketUnmask } = __require("http");
|
|
67
68
|
var { EMPTY_BUFFER } = require_constants();
|
|
68
69
|
var FastBuffer = Buffer[Symbol.species];
|
|
69
70
|
function concat(list, totalLength) {
|
|
@@ -118,7 +119,16 @@ var require_buffer_util = __commonJS({
|
|
|
118
119
|
toBuffer,
|
|
119
120
|
unmask: _unmask
|
|
120
121
|
};
|
|
121
|
-
if (
|
|
122
|
+
if (websocketMask) {
|
|
123
|
+
module.exports.mask = function(source, mask, output, offset, length) {
|
|
124
|
+
if (length < 24) _mask(source, mask, output, offset, length);
|
|
125
|
+
else websocketMask(source, mask, output, offset, length);
|
|
126
|
+
};
|
|
127
|
+
module.exports.unmask = function(buffer, mask) {
|
|
128
|
+
if (buffer.length < 24) _unmask(buffer, mask);
|
|
129
|
+
else websocketUnmask(buffer, mask);
|
|
130
|
+
};
|
|
131
|
+
} else if (!process.env.WS_NO_BUFFER_UTIL) {
|
|
122
132
|
try {
|
|
123
133
|
const bufferUtil = __require("bufferutil");
|
|
124
134
|
module.exports.mask = function(source, mask, output, offset, length) {
|
|
@@ -135,9 +145,9 @@ var require_buffer_util = __commonJS({
|
|
|
135
145
|
}
|
|
136
146
|
});
|
|
137
147
|
|
|
138
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
148
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/limiter.js
|
|
139
149
|
var require_limiter = __commonJS({
|
|
140
|
-
"../../node_modules/.pnpm/ws@8.
|
|
150
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/limiter.js"(exports, module) {
|
|
141
151
|
"use strict";
|
|
142
152
|
var kDone = /* @__PURE__ */ Symbol("kDone");
|
|
143
153
|
var kRun = /* @__PURE__ */ Symbol("kRun");
|
|
@@ -185,9 +195,9 @@ var require_limiter = __commonJS({
|
|
|
185
195
|
}
|
|
186
196
|
});
|
|
187
197
|
|
|
188
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
198
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js
|
|
189
199
|
var require_permessage_deflate = __commonJS({
|
|
190
|
-
"../../node_modules/.pnpm/ws@8.
|
|
200
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
|
|
191
201
|
"use strict";
|
|
192
202
|
var zlib = __require("zlib");
|
|
193
203
|
var bufferUtil = require_buffer_util();
|
|
@@ -568,9 +578,9 @@ var require_permessage_deflate = __commonJS({
|
|
|
568
578
|
}
|
|
569
579
|
});
|
|
570
580
|
|
|
571
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
581
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js
|
|
572
582
|
var require_validation = __commonJS({
|
|
573
|
-
"../../node_modules/.pnpm/ws@8.
|
|
583
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js"(exports, module) {
|
|
574
584
|
"use strict";
|
|
575
585
|
var { isUtf8 } = __require("buffer");
|
|
576
586
|
var { hasBlob } = require_constants();
|
|
@@ -769,9 +779,9 @@ var require_validation = __commonJS({
|
|
|
769
779
|
}
|
|
770
780
|
});
|
|
771
781
|
|
|
772
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
782
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/receiver.js
|
|
773
783
|
var require_receiver = __commonJS({
|
|
774
|
-
"../../node_modules/.pnpm/ws@8.
|
|
784
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/receiver.js"(exports, module) {
|
|
775
785
|
"use strict";
|
|
776
786
|
var { Writable } = __require("stream");
|
|
777
787
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -1181,6 +1191,7 @@ var require_receiver = __commonJS({
|
|
|
1181
1191
|
unmask(data, this._mask);
|
|
1182
1192
|
}
|
|
1183
1193
|
}
|
|
1194
|
+
this._mask = void 0;
|
|
1184
1195
|
if (this._opcode > 7) {
|
|
1185
1196
|
this.controlMessage(data, cb);
|
|
1186
1197
|
return;
|
|
@@ -1392,9 +1403,9 @@ var require_receiver = __commonJS({
|
|
|
1392
1403
|
}
|
|
1393
1404
|
});
|
|
1394
1405
|
|
|
1395
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
1406
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/sender.js
|
|
1396
1407
|
var require_sender = __commonJS({
|
|
1397
|
-
"../../node_modules/.pnpm/ws@8.
|
|
1408
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/sender.js"(exports, module) {
|
|
1398
1409
|
"use strict";
|
|
1399
1410
|
var { Duplex } = __require("stream");
|
|
1400
1411
|
var { randomFillSync } = __require("crypto");
|
|
@@ -1513,12 +1524,15 @@ var require_sender = __commonJS({
|
|
|
1513
1524
|
target[2] = target[3] = 0;
|
|
1514
1525
|
target.writeUIntBE(dataLength, 4, 6);
|
|
1515
1526
|
}
|
|
1516
|
-
if (!options.mask)
|
|
1527
|
+
if (!options.mask) {
|
|
1528
|
+
return dataLength ? [target, data] : [target];
|
|
1529
|
+
}
|
|
1517
1530
|
target[1] |= 128;
|
|
1518
1531
|
target[offset - 4] = mask[0];
|
|
1519
1532
|
target[offset - 3] = mask[1];
|
|
1520
1533
|
target[offset - 2] = mask[2];
|
|
1521
1534
|
target[offset - 1] = mask[3];
|
|
1535
|
+
if (!dataLength) return [target];
|
|
1522
1536
|
if (skipMasking) return [target, data];
|
|
1523
1537
|
if (merge) {
|
|
1524
1538
|
applyMask(data, mask, target, offset, dataLength);
|
|
@@ -1885,9 +1899,9 @@ var require_sender = __commonJS({
|
|
|
1885
1899
|
}
|
|
1886
1900
|
});
|
|
1887
1901
|
|
|
1888
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
1902
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/event-target.js
|
|
1889
1903
|
var require_event_target = __commonJS({
|
|
1890
|
-
"../../node_modules/.pnpm/ws@8.
|
|
1904
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/event-target.js"(exports, module) {
|
|
1891
1905
|
"use strict";
|
|
1892
1906
|
var { kForOnEventAttribute, kListener } = require_constants();
|
|
1893
1907
|
var kCode = /* @__PURE__ */ Symbol("kCode");
|
|
@@ -2114,9 +2128,9 @@ var require_event_target = __commonJS({
|
|
|
2114
2128
|
}
|
|
2115
2129
|
});
|
|
2116
2130
|
|
|
2117
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
2131
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/extension.js
|
|
2118
2132
|
var require_extension = __commonJS({
|
|
2119
|
-
"../../node_modules/.pnpm/ws@8.
|
|
2133
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/extension.js"(exports, module) {
|
|
2120
2134
|
"use strict";
|
|
2121
2135
|
var { tokenChars } = require_validation();
|
|
2122
2136
|
function push(dest, name, elem) {
|
|
@@ -2267,16 +2281,17 @@ var require_extension = __commonJS({
|
|
|
2267
2281
|
}
|
|
2268
2282
|
});
|
|
2269
2283
|
|
|
2270
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
2284
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket.js
|
|
2271
2285
|
var require_websocket = __commonJS({
|
|
2272
|
-
"../../node_modules/.pnpm/ws@8.
|
|
2286
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket.js"(exports, module) {
|
|
2273
2287
|
"use strict";
|
|
2274
2288
|
var EventEmitter = __require("events");
|
|
2275
2289
|
var https = __require("https");
|
|
2276
2290
|
var http = __require("http");
|
|
2277
2291
|
var net = __require("net");
|
|
2292
|
+
var querystring = __require("querystring");
|
|
2278
2293
|
var tls = __require("tls");
|
|
2279
|
-
var { randomBytes: randomBytes2, createHash:
|
|
2294
|
+
var { randomBytes: randomBytes2, createHash: createHash7 } = __require("crypto");
|
|
2280
2295
|
var { Duplex, Readable } = __require("stream");
|
|
2281
2296
|
var { URL: URL2 } = __require("url");
|
|
2282
2297
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -2353,12 +2368,17 @@ var require_websocket = __commonJS({
|
|
|
2353
2368
|
protocols = [protocols];
|
|
2354
2369
|
}
|
|
2355
2370
|
}
|
|
2356
|
-
initAsClient(this, address, protocols, options);
|
|
2371
|
+
options = initAsClient(this, address, protocols, options);
|
|
2357
2372
|
} else {
|
|
2358
|
-
this._autoPong = options.autoPong;
|
|
2359
|
-
this._closeTimeout = options.closeTimeout;
|
|
2360
2373
|
this._isServer = true;
|
|
2361
2374
|
}
|
|
2375
|
+
if (options.autoPong) {
|
|
2376
|
+
this._autoPong = true;
|
|
2377
|
+
this._autoPongComplete = () => autoPongComplete(this);
|
|
2378
|
+
this._pendingAutoPongs = 0;
|
|
2379
|
+
this._maxPendingAutoPongs = options.maxPendingAutoPongs | 0;
|
|
2380
|
+
}
|
|
2381
|
+
this._closeTimeout = options.closeTimeout;
|
|
2362
2382
|
}
|
|
2363
2383
|
/**
|
|
2364
2384
|
* For historical reasons, the custom "nodebuffer" type is used by the default
|
|
@@ -2769,6 +2789,7 @@ var require_websocket = __commonJS({
|
|
|
2769
2789
|
maxBufferedChunks: 256 * 1024,
|
|
2770
2790
|
maxFragments: 16 * 1024,
|
|
2771
2791
|
maxPayload: 100 * 1024 * 1024,
|
|
2792
|
+
maxPendingAutoPongs: 60,
|
|
2772
2793
|
skipUTF8Validation: false,
|
|
2773
2794
|
perMessageDeflate: true,
|
|
2774
2795
|
followRedirects: false,
|
|
@@ -2784,8 +2805,6 @@ var require_websocket = __commonJS({
|
|
|
2784
2805
|
path: void 0,
|
|
2785
2806
|
port: void 0
|
|
2786
2807
|
};
|
|
2787
|
-
websocket._autoPong = opts.autoPong;
|
|
2788
|
-
websocket._closeTimeout = opts.closeTimeout;
|
|
2789
2808
|
if (!protocolVersions.includes(opts.protocolVersion)) {
|
|
2790
2809
|
throw new RangeError(
|
|
2791
2810
|
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
|
|
@@ -2801,10 +2820,9 @@ var require_websocket = __commonJS({
|
|
|
2801
2820
|
throw new SyntaxError(`Invalid URL: ${address}`);
|
|
2802
2821
|
}
|
|
2803
2822
|
}
|
|
2804
|
-
if (parsedUrl.protocol === "http:") {
|
|
2805
|
-
parsedUrl
|
|
2806
|
-
|
|
2807
|
-
parsedUrl.protocol = "wss:";
|
|
2823
|
+
if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") {
|
|
2824
|
+
parsedUrl = new URL2(parsedUrl);
|
|
2825
|
+
parsedUrl.protocol = parsedUrl.protocol === "http:" ? "ws:" : "wss:";
|
|
2808
2826
|
}
|
|
2809
2827
|
websocket._url = parsedUrl.href;
|
|
2810
2828
|
const isSecure = parsedUrl.protocol === "wss:";
|
|
@@ -2873,12 +2891,19 @@ var require_websocket = __commonJS({
|
|
|
2873
2891
|
}
|
|
2874
2892
|
}
|
|
2875
2893
|
if (parsedUrl.username || parsedUrl.password) {
|
|
2876
|
-
|
|
2894
|
+
const username = querystring.unescape(parsedUrl.username);
|
|
2895
|
+
const password = querystring.unescape(parsedUrl.password);
|
|
2896
|
+
opts.auth = `${username}:${password}`;
|
|
2877
2897
|
}
|
|
2878
2898
|
if (isIpcUrl) {
|
|
2879
|
-
const
|
|
2880
|
-
|
|
2881
|
-
|
|
2899
|
+
const i = opts.path.indexOf(":");
|
|
2900
|
+
if (i === -1) {
|
|
2901
|
+
opts.socketPath = opts.path;
|
|
2902
|
+
opts.path = "";
|
|
2903
|
+
} else {
|
|
2904
|
+
opts.socketPath = opts.path.slice(0, i);
|
|
2905
|
+
opts.path = opts.path.slice(i + 1);
|
|
2906
|
+
}
|
|
2882
2907
|
}
|
|
2883
2908
|
let req;
|
|
2884
2909
|
if (opts.followRedirects) {
|
|
@@ -2957,7 +2982,7 @@ var require_websocket = __commonJS({
|
|
|
2957
2982
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
2958
2983
|
return;
|
|
2959
2984
|
}
|
|
2960
|
-
const digest =
|
|
2985
|
+
const digest = createHash7("sha1").update(key + GUID).digest("base64");
|
|
2961
2986
|
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
2962
2987
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
2963
2988
|
return;
|
|
@@ -3022,6 +3047,7 @@ var require_websocket = __commonJS({
|
|
|
3022
3047
|
} else {
|
|
3023
3048
|
req.end();
|
|
3024
3049
|
}
|
|
3050
|
+
return opts;
|
|
3025
3051
|
}
|
|
3026
3052
|
function emitErrorAndClose(websocket, err) {
|
|
3027
3053
|
websocket._readyState = WebSocket2.CLOSING;
|
|
@@ -3073,8 +3099,13 @@ var require_websocket = __commonJS({
|
|
|
3073
3099
|
function receiverOnConclude(code, reason) {
|
|
3074
3100
|
const websocket = this[kWebSocket];
|
|
3075
3101
|
websocket._closeFrameReceived = true;
|
|
3076
|
-
websocket._closeMessage = reason;
|
|
3077
3102
|
websocket._closeCode = code;
|
|
3103
|
+
if (reason.length === 0) {
|
|
3104
|
+
websocket._closeMessage = EMPTY_BUFFER;
|
|
3105
|
+
} else {
|
|
3106
|
+
websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
|
|
3107
|
+
websocket._closeMessage.set(reason);
|
|
3108
|
+
}
|
|
3078
3109
|
if (websocket._socket[kWebSocket] === void 0) return;
|
|
3079
3110
|
websocket._socket.removeListener("data", socketOnData);
|
|
3080
3111
|
process.nextTick(resume, websocket._socket);
|
|
@@ -3105,9 +3136,19 @@ var require_websocket = __commonJS({
|
|
|
3105
3136
|
}
|
|
3106
3137
|
function receiverOnPing(data) {
|
|
3107
3138
|
const websocket = this[kWebSocket];
|
|
3108
|
-
if (websocket._autoPong
|
|
3139
|
+
if (websocket._autoPong && websocket.readyState === WebSocket2.OPEN) {
|
|
3140
|
+
if (websocket._maxPendingAutoPongs > 0 && websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs) {
|
|
3141
|
+
websocket.terminate();
|
|
3142
|
+
} else {
|
|
3143
|
+
websocket._pendingAutoPongs++;
|
|
3144
|
+
websocket.pong(data, !this._isServer, websocket._autoPongComplete);
|
|
3145
|
+
}
|
|
3146
|
+
}
|
|
3109
3147
|
websocket.emit("ping", data);
|
|
3110
3148
|
}
|
|
3149
|
+
function autoPongComplete(websocket) {
|
|
3150
|
+
websocket._pendingAutoPongs--;
|
|
3151
|
+
}
|
|
3111
3152
|
function receiverOnPong(data) {
|
|
3112
3153
|
this[kWebSocket].emit("pong", data);
|
|
3113
3154
|
}
|
|
@@ -3176,9 +3217,9 @@ var require_websocket = __commonJS({
|
|
|
3176
3217
|
}
|
|
3177
3218
|
});
|
|
3178
3219
|
|
|
3179
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
3220
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/stream.js
|
|
3180
3221
|
var require_stream = __commonJS({
|
|
3181
|
-
"../../node_modules/.pnpm/ws@8.
|
|
3222
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/stream.js"(exports, module) {
|
|
3182
3223
|
"use strict";
|
|
3183
3224
|
var WebSocket2 = require_websocket();
|
|
3184
3225
|
var { Duplex } = __require("stream");
|
|
@@ -3274,9 +3315,9 @@ var require_stream = __commonJS({
|
|
|
3274
3315
|
}
|
|
3275
3316
|
});
|
|
3276
3317
|
|
|
3277
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
3318
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/subprotocol.js
|
|
3278
3319
|
var require_subprotocol = __commonJS({
|
|
3279
|
-
"../../node_modules/.pnpm/ws@8.
|
|
3320
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/subprotocol.js"(exports, module) {
|
|
3280
3321
|
"use strict";
|
|
3281
3322
|
var { tokenChars } = require_validation();
|
|
3282
3323
|
function parse(header) {
|
|
@@ -3319,14 +3360,14 @@ var require_subprotocol = __commonJS({
|
|
|
3319
3360
|
}
|
|
3320
3361
|
});
|
|
3321
3362
|
|
|
3322
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
3363
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket-server.js
|
|
3323
3364
|
var require_websocket_server = __commonJS({
|
|
3324
|
-
"../../node_modules/.pnpm/ws@8.
|
|
3365
|
+
"../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket-server.js"(exports, module) {
|
|
3325
3366
|
"use strict";
|
|
3326
3367
|
var EventEmitter = __require("events");
|
|
3327
3368
|
var http = __require("http");
|
|
3328
3369
|
var { Duplex } = __require("stream");
|
|
3329
|
-
var { createHash:
|
|
3370
|
+
var { createHash: createHash7 } = __require("crypto");
|
|
3330
3371
|
var extension2 = require_extension();
|
|
3331
3372
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
3332
3373
|
var subprotocol2 = require_subprotocol();
|
|
@@ -3361,6 +3402,8 @@ var require_websocket_server = __commonJS({
|
|
|
3361
3402
|
* fragments
|
|
3362
3403
|
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
3363
3404
|
* size
|
|
3405
|
+
* @param {Number} [options.maxPendingAutoPongs=60] The maximum number of
|
|
3406
|
+
* pending automatic pongs
|
|
3364
3407
|
* @param {Boolean} [options.noServer=false] Enable no server mode
|
|
3365
3408
|
* @param {String} [options.path] Accept only connections matching this path
|
|
3366
3409
|
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
|
|
@@ -3383,6 +3426,7 @@ var require_websocket_server = __commonJS({
|
|
|
3383
3426
|
maxBufferedChunks: 256 * 1024,
|
|
3384
3427
|
maxFragments: 16 * 1024,
|
|
3385
3428
|
maxPayload: 100 * 1024 * 1024,
|
|
3429
|
+
maxPendingAutoPongs: 60,
|
|
3386
3430
|
skipUTF8Validation: false,
|
|
3387
3431
|
perMessageDeflate: false,
|
|
3388
3432
|
handleProtocols: null,
|
|
@@ -3633,7 +3677,7 @@ var require_websocket_server = __commonJS({
|
|
|
3633
3677
|
);
|
|
3634
3678
|
}
|
|
3635
3679
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
3636
|
-
const digest =
|
|
3680
|
+
const digest = createHash7("sha1").update(key + GUID).digest("base64");
|
|
3637
3681
|
const headers = [
|
|
3638
3682
|
"HTTP/1.1 101 Switching Protocols",
|
|
3639
3683
|
"Upgrade: websocket",
|
|
@@ -6151,6 +6195,7 @@ function serialize(value, level, depth) {
|
|
|
6151
6195
|
var LEVEL_ORDER = { trace: 0, debug: 1, info: 2, warn: 3, error: 4 };
|
|
6152
6196
|
var LEVELS = new Set(Object.keys(LEVEL_ORDER));
|
|
6153
6197
|
var KEY_WORKTREE_ID = "worktree_id";
|
|
6198
|
+
var KEY_ENV_KEY_COUNT = "env_key_count";
|
|
6154
6199
|
var PROTECTED_KEYS = /* @__PURE__ */ new Set(["ts", "level", "msg", "component"]);
|
|
6155
6200
|
function resolveLogLevel(raw) {
|
|
6156
6201
|
if (raw === void 0) return "info";
|
|
@@ -6304,7 +6349,7 @@ var HARNESS_AGENTS = {
|
|
|
6304
6349
|
pi: { id: "pi", name: "Pi" }
|
|
6305
6350
|
};
|
|
6306
6351
|
|
|
6307
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
6352
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/wrapper.mjs
|
|
6308
6353
|
var import_stream = __toESM(require_stream(), 1);
|
|
6309
6354
|
var import_extension = __toESM(require_extension(), 1);
|
|
6310
6355
|
var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
|
|
@@ -6407,11 +6452,13 @@ function validateHelloAck(payload) {
|
|
|
6407
6452
|
const { protocolVersion, engineEpoch, ackedSeq } = record;
|
|
6408
6453
|
if (!isCounter(protocolVersion, 1) || !isCounter(engineEpoch, 1) || !isCounter(ackedSeq, 0)) return null;
|
|
6409
6454
|
if (typeof record.engineVersion !== "string" || record.engineVersion === "") return null;
|
|
6455
|
+
const { fingerprintSalt } = record;
|
|
6410
6456
|
return {
|
|
6411
6457
|
protocolVersion,
|
|
6412
6458
|
engineVersion: record.engineVersion,
|
|
6413
6459
|
engineEpoch,
|
|
6414
|
-
ackedSeq
|
|
6460
|
+
ackedSeq,
|
|
6461
|
+
...typeof fingerprintSalt === "string" && fingerprintSalt !== "" && fingerprintSalt.length <= 128 ? { fingerprintSalt } : {}
|
|
6415
6462
|
};
|
|
6416
6463
|
}
|
|
6417
6464
|
function isCounter(value, min) {
|
|
@@ -7762,18 +7809,18 @@ function logSafe(logger, level, msg, fields) {
|
|
|
7762
7809
|
var REPOSITORY_PATTERN = /^[^/\s]+\/[^/\s]+$/;
|
|
7763
7810
|
function repoCommandHandlers(service, hooks, logger = noopLogger) {
|
|
7764
7811
|
const mutate = hooks?.mutate ?? ((operation) => operation());
|
|
7765
|
-
const
|
|
7812
|
+
const invalid2 = (field) => {
|
|
7766
7813
|
logSafe(logger, "warn", "repo command rejected: bad params", { field, reason: "bad_params" });
|
|
7767
7814
|
throw new CommandRejection("invalid", { reason: "bad_params" });
|
|
7768
7815
|
};
|
|
7769
7816
|
const repositoryParam = (params) => {
|
|
7770
7817
|
const value = params["repository"];
|
|
7771
|
-
if (typeof value !== "string" || !REPOSITORY_PATTERN.test(value)) return
|
|
7818
|
+
if (typeof value !== "string" || !REPOSITORY_PATTERN.test(value)) return invalid2("repository");
|
|
7772
7819
|
return value;
|
|
7773
7820
|
};
|
|
7774
7821
|
const pathParam = (params) => {
|
|
7775
7822
|
const value = params["path"];
|
|
7776
|
-
if (typeof value !== "string" || value === "" || !isAbsolute(value)) return
|
|
7823
|
+
if (typeof value !== "string" || value === "" || !isAbsolute(value)) return invalid2("path");
|
|
7777
7824
|
return value;
|
|
7778
7825
|
};
|
|
7779
7826
|
return {
|
|
@@ -7916,7 +7963,7 @@ function isTurnCursor(value) {
|
|
|
7916
7963
|
return value.fingerprint === null || typeof value.fingerprint === "string";
|
|
7917
7964
|
}
|
|
7918
7965
|
function agentCommandHandlers(service, logger = noopLogger) {
|
|
7919
|
-
const
|
|
7966
|
+
const invalid2 = (reason, fields = {}, msg = "agent command rejected: invalid params") => {
|
|
7920
7967
|
logSafe2(logger, "warn", msg, { reason, ...fields });
|
|
7921
7968
|
return new CommandRejection("invalid", { reason });
|
|
7922
7969
|
};
|
|
@@ -7930,13 +7977,13 @@ function agentCommandHandlers(service, logger = noopLogger) {
|
|
|
7930
7977
|
"agent.final": async (params) => {
|
|
7931
7978
|
const value = isRecord(params) ? params : {};
|
|
7932
7979
|
if (typeof value.harness !== "string" || typeof value.sessionId !== "string") {
|
|
7933
|
-
throw
|
|
7980
|
+
throw invalid2("final_params_required", {
|
|
7934
7981
|
harness_present: typeof value.harness === "string",
|
|
7935
7982
|
session_id_present: typeof value.sessionId === "string"
|
|
7936
7983
|
}, "agent.final rejected: invalid params");
|
|
7937
7984
|
}
|
|
7938
7985
|
if (value.turnCursor !== void 0 && !isTurnCursor(value.turnCursor)) {
|
|
7939
|
-
throw
|
|
7986
|
+
throw invalid2("invalid_turn_cursor", {}, "agent.final rejected: invalid turn cursor");
|
|
7940
7987
|
}
|
|
7941
7988
|
const turnCursor = value.turnCursor;
|
|
7942
7989
|
return service.final({
|
|
@@ -7948,7 +7995,7 @@ function agentCommandHandlers(service, logger = noopLogger) {
|
|
|
7948
7995
|
"agent.session": async (params) => {
|
|
7949
7996
|
const value = isRecord(params) ? params : {};
|
|
7950
7997
|
if (typeof value.harness !== "string" || typeof value.sessionId !== "string") {
|
|
7951
|
-
throw
|
|
7998
|
+
throw invalid2("session_params_required");
|
|
7952
7999
|
}
|
|
7953
8000
|
return service.lastModelRequestAt({ harness: value.harness, sessionId: value.sessionId });
|
|
7954
8001
|
}
|
|
@@ -8206,6 +8253,7 @@ function logSafe5(logger, level, msg, fields) {
|
|
|
8206
8253
|
var execFileAsync2 = promisify2(execFile2);
|
|
8207
8254
|
var PS_PROBE_TIMEOUT_MS = 5e3;
|
|
8208
8255
|
var PS_PROBE_MAX_OUTPUT_BYTES = 8 * 1024;
|
|
8256
|
+
var PS_PROBE_SIGNAL_ATTEMPTS = 3;
|
|
8209
8257
|
async function runProbeProcess(cmd, args) {
|
|
8210
8258
|
const child = spawn(cmd, args, { detached: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
8211
8259
|
child.unref();
|
|
@@ -8222,8 +8270,10 @@ async function runProbeProcess(cmd, args) {
|
|
|
8222
8270
|
stderr = appendCapped(stderr, chunk);
|
|
8223
8271
|
});
|
|
8224
8272
|
let spawnError;
|
|
8273
|
+
let endedBy;
|
|
8225
8274
|
const code = await new Promise((resolve11) => {
|
|
8226
8275
|
const timer = setTimeout(() => {
|
|
8276
|
+
endedBy = "timeout";
|
|
8227
8277
|
child.kill("SIGKILL");
|
|
8228
8278
|
resolve11(null);
|
|
8229
8279
|
}, PS_PROBE_TIMEOUT_MS);
|
|
@@ -8235,9 +8285,12 @@ async function runProbeProcess(cmd, args) {
|
|
|
8235
8285
|
spawnError = error;
|
|
8236
8286
|
done(null);
|
|
8237
8287
|
});
|
|
8238
|
-
child.once("close", (exitCode, signal) =>
|
|
8288
|
+
child.once("close", (exitCode, signal) => {
|
|
8289
|
+
if (signal !== null && endedBy === void 0) endedBy = `signal ${signal}`;
|
|
8290
|
+
done(signal !== null ? null : exitCode);
|
|
8291
|
+
});
|
|
8239
8292
|
});
|
|
8240
|
-
return { code, stdout, stderr, ...spawnError === void 0 ? {} : { spawnError } };
|
|
8293
|
+
return { code, stdout, stderr, ...endedBy === void 0 ? {} : { endedBy }, ...spawnError === void 0 ? {} : { spawnError } };
|
|
8241
8294
|
}
|
|
8242
8295
|
var toolCache = /* @__PURE__ */ new Map();
|
|
8243
8296
|
async function resolveToolCached(name, candidates, logger) {
|
|
@@ -8260,12 +8313,17 @@ async function probePs(pid, logger) {
|
|
|
8260
8313
|
if (!ps) {
|
|
8261
8314
|
throw new Error("required tool 'ps' not found");
|
|
8262
8315
|
}
|
|
8263
|
-
const
|
|
8316
|
+
const args = ["-o", "pid=,pgid=,etime=,stat=,comm=", "-p", String(pid)];
|
|
8317
|
+
let run = await runProbeProcess(ps, args);
|
|
8318
|
+
for (let attempt = 1; attempt < PS_PROBE_SIGNAL_ATTEMPTS && run.endedBy?.startsWith("signal ") === true; attempt += 1) {
|
|
8319
|
+
logSafe5(logger, "debug", "ps probe killed by a signal, retrying", { pid, attempt, reason: run.endedBy });
|
|
8320
|
+
run = await runProbeProcess(ps, args);
|
|
8321
|
+
}
|
|
8264
8322
|
if (run.code === 1) return null;
|
|
8265
8323
|
if (run.code !== 0) {
|
|
8266
8324
|
const detail = run.stderr.split("\n").find((line) => line.trim() !== "") ?? "";
|
|
8267
8325
|
throw new Error(
|
|
8268
|
-
`ps probe for pid ${pid} did not complete (code=${String(run.code)})${detail === "" ? "" : `: ${detail}`}`,
|
|
8326
|
+
`ps probe for pid ${pid} did not complete (code=${String(run.code)}${run.endedBy === void 0 ? "" : `, ended by ${run.endedBy}`})${detail === "" ? "" : `: ${detail}`}`,
|
|
8269
8327
|
run.spawnError === void 0 ? void 0 : { cause: run.spawnError }
|
|
8270
8328
|
);
|
|
8271
8329
|
}
|
|
@@ -11276,6 +11334,7 @@ async function recoverAgents(deps) {
|
|
|
11276
11334
|
if (reservation.phase === "reserved" || agent === null || wrapper === null) {
|
|
11277
11335
|
blocked += 1;
|
|
11278
11336
|
deps.logger.error("agent.reservation_blocked_stale", {
|
|
11337
|
+
operation: "agent_recovery.reservation",
|
|
11279
11338
|
run_id: reservation.runId,
|
|
11280
11339
|
phase: reservation.phase,
|
|
11281
11340
|
owner_pid: reservation.owner.pid,
|
|
@@ -12752,6 +12811,90 @@ var HarnessDetectError = class extends Error {
|
|
|
12752
12811
|
meta;
|
|
12753
12812
|
};
|
|
12754
12813
|
|
|
12814
|
+
// ../../core/packages/runner-core/src/inventory/config-source.ts
|
|
12815
|
+
import { basename as basename8 } from "node:path";
|
|
12816
|
+
import { readFileSync, statSync as statSync5 } from "node:fs";
|
|
12817
|
+
var CONFIG_SOURCE_MAX_VARS = 32;
|
|
12818
|
+
var INSTANCE_ENV_MAX_BYTES = 65536;
|
|
12819
|
+
var INSTANCE_ENV_MAX_KEYS = 256;
|
|
12820
|
+
var NATIVE_CONFIG_MAX_BYTES = 65536;
|
|
12821
|
+
var PROVIDER_ENV_SUFFIXES = ["_API_KEY", "_AUTH_TOKEN", "_OAUTH_TOKEN", "_BASE_URL", "_MODEL"];
|
|
12822
|
+
var NON_PROVIDER_ENV_DENY = /* @__PURE__ */ new Set(["GH_TOKEN", "GITHUB_TOKEN", "COMPIVIA_RUNNER_CREDENTIALS", "COMPIVIA_DASHBOARD_TOKEN"]);
|
|
12823
|
+
var VAR_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
12824
|
+
var WIRE_PATH_SEGMENT = /^[A-Za-z0-9._-]*[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
|
|
12825
|
+
function nativeClaudeConfigSource(input) {
|
|
12826
|
+
if (input.configDir !== void 0 && input.configDir.includes("{{")) return null;
|
|
12827
|
+
const absolute = input.configDir !== void 0 ? `${input.configDir}/settings.json` : `${input.homeDir}/.claude/settings.json`;
|
|
12828
|
+
const relative3 = relativeUnderHome(absolute, input.homeDir);
|
|
12829
|
+
if (relative3 === null || relative3.length > 256 || !relative3.split("/").every((segment) => WIRE_PATH_SEGMENT.test(segment))) return null;
|
|
12830
|
+
let parsed;
|
|
12831
|
+
try {
|
|
12832
|
+
if (statSync5(absolute).size > NATIVE_CONFIG_MAX_BYTES) return null;
|
|
12833
|
+
parsed = JSON.parse(readFileSync(absolute, "utf8"));
|
|
12834
|
+
} catch {
|
|
12835
|
+
return null;
|
|
12836
|
+
}
|
|
12837
|
+
const env = parsed?.env;
|
|
12838
|
+
if (env === null || typeof env !== "object" || Array.isArray(env)) return null;
|
|
12839
|
+
const vars = Object.keys(env).filter((name) => VAR_NAME_PATTERN.test(name)).sort().slice(0, CONFIG_SOURCE_MAX_VARS);
|
|
12840
|
+
if (vars.length === 0) return null;
|
|
12841
|
+
return { kind: "native_file", file: `~/${relative3}`, section: "env", vars };
|
|
12842
|
+
}
|
|
12843
|
+
function readEnvFileVarNames(path) {
|
|
12844
|
+
if (!isInstancePath(path)) return null;
|
|
12845
|
+
let raw;
|
|
12846
|
+
try {
|
|
12847
|
+
if (statSync5(path).size > INSTANCE_ENV_MAX_BYTES) return null;
|
|
12848
|
+
raw = readFileSync(path, "utf8");
|
|
12849
|
+
} catch {
|
|
12850
|
+
return null;
|
|
12851
|
+
}
|
|
12852
|
+
const names = /* @__PURE__ */ new Set();
|
|
12853
|
+
for (const line of raw.split("\n")) {
|
|
12854
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
|
|
12855
|
+
if (match === null || match[1] === void 0) continue;
|
|
12856
|
+
names.add(match[1]);
|
|
12857
|
+
if (names.size > INSTANCE_ENV_MAX_KEYS) return null;
|
|
12858
|
+
}
|
|
12859
|
+
if (names.size === 0) return null;
|
|
12860
|
+
return [...names].sort().slice(0, CONFIG_SOURCE_MAX_VARS);
|
|
12861
|
+
}
|
|
12862
|
+
function providerEnvVarNames(env) {
|
|
12863
|
+
const names = Object.keys(env).filter((name) => PROVIDER_ENV_SUFFIXES.some((suffix) => name.endsWith(suffix)) && !NON_PROVIDER_ENV_DENY.has(name) && !name.startsWith("COMPIVIA_"));
|
|
12864
|
+
return [...new Set(names)].sort().slice(0, CONFIG_SOURCE_MAX_VARS);
|
|
12865
|
+
}
|
|
12866
|
+
function resolveAmbientConfigSource(input) {
|
|
12867
|
+
if (input.instanceEnvFile !== void 0) {
|
|
12868
|
+
const vars = readEnvFileVarNames(input.instanceEnvFile);
|
|
12869
|
+
const file = vars !== null ? instanceDisplayPath(input.instanceEnvFile) : null;
|
|
12870
|
+
if (vars !== null && file !== null) return { kind: "instance_env_file", file, vars };
|
|
12871
|
+
}
|
|
12872
|
+
if (input.processEnv !== void 0) {
|
|
12873
|
+
const vars = providerEnvVarNames(input.processEnv);
|
|
12874
|
+
if (vars.length > 0) return { kind: "process_env", vars };
|
|
12875
|
+
}
|
|
12876
|
+
return { kind: "none" };
|
|
12877
|
+
}
|
|
12878
|
+
function resolveAgentConfigSource(input) {
|
|
12879
|
+
const native = nativeClaudeConfigSource(input);
|
|
12880
|
+
if (native !== null) return native;
|
|
12881
|
+
return resolveAmbientConfigSource(input);
|
|
12882
|
+
}
|
|
12883
|
+
function relativeUnderHome(absolute, homeDir) {
|
|
12884
|
+
const prefix = homeDir.endsWith("/") ? homeDir : `${homeDir}/`;
|
|
12885
|
+
if (!absolute.startsWith(prefix)) return null;
|
|
12886
|
+
return absolute.slice(prefix.length);
|
|
12887
|
+
}
|
|
12888
|
+
function isInstancePath(path) {
|
|
12889
|
+
return basename8(path) === "env" && path.split("/").includes("instances");
|
|
12890
|
+
}
|
|
12891
|
+
function instanceDisplayPath(path) {
|
|
12892
|
+
const parts = path.split("/");
|
|
12893
|
+
const start = parts.lastIndexOf("instances");
|
|
12894
|
+
if (start === -1) return null;
|
|
12895
|
+
return `instances/${parts.slice(start + 1).join("/")}`;
|
|
12896
|
+
}
|
|
12897
|
+
|
|
12755
12898
|
// ../../core/packages/runner-core/src/inventory/clone-scan.ts
|
|
12756
12899
|
import { lstat as lstat2, readdir } from "node:fs/promises";
|
|
12757
12900
|
import { join as join3, resolve as resolve3 } from "node:path";
|
|
@@ -13486,11 +13629,13 @@ var ProbedHarnessDetector = class {
|
|
|
13486
13629
|
this.runner = runner;
|
|
13487
13630
|
this.timeoutMs = opts?.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
|
|
13488
13631
|
this.logger = opts?.logger ?? noopLogger;
|
|
13632
|
+
if (opts?.probeEnv !== void 0) this.probeEnv = opts.probeEnv;
|
|
13489
13633
|
}
|
|
13490
13634
|
config;
|
|
13491
13635
|
runner;
|
|
13492
13636
|
timeoutMs;
|
|
13493
13637
|
logger;
|
|
13638
|
+
probeEnv;
|
|
13494
13639
|
async detect() {
|
|
13495
13640
|
const startedAt = Date.now();
|
|
13496
13641
|
let versionResult;
|
|
@@ -13499,6 +13644,7 @@ var ProbedHarnessDetector = class {
|
|
|
13499
13644
|
versionArgs: this.config.versionArgs,
|
|
13500
13645
|
runner: this.runner,
|
|
13501
13646
|
timeoutMs: this.timeoutMs,
|
|
13647
|
+
...this.probeEnv !== void 0 ? { env: this.probeEnv } : {},
|
|
13502
13648
|
onResult: (result) => {
|
|
13503
13649
|
versionResult = result;
|
|
13504
13650
|
}
|
|
@@ -13520,6 +13666,7 @@ var ProbedHarnessDetector = class {
|
|
|
13520
13666
|
args: this.config.signinProbe.args,
|
|
13521
13667
|
runner: this.runner,
|
|
13522
13668
|
timeoutMs: this.timeoutMs,
|
|
13669
|
+
...this.probeEnv !== void 0 ? { env: this.probeEnv } : {},
|
|
13523
13670
|
onResult: (result) => {
|
|
13524
13671
|
signinResult = result;
|
|
13525
13672
|
}
|
|
@@ -13541,6 +13688,9 @@ var ProbedHarnessDetector = class {
|
|
|
13541
13688
|
}
|
|
13542
13689
|
};
|
|
13543
13690
|
|
|
13691
|
+
// ../../core/packages/runner-core/src/harness/detect-claude.ts
|
|
13692
|
+
import { homedir } from "node:os";
|
|
13693
|
+
|
|
13544
13694
|
// ../../core/packages/runner-core/src/harness/detect-shared.ts
|
|
13545
13695
|
var INTERNAL_DEADLINE_MS = 5e3;
|
|
13546
13696
|
async function withDeadline(meta, op) {
|
|
@@ -13570,9 +13720,10 @@ function machineEnvValue(launchEnv, key) {
|
|
|
13570
13720
|
if (value === void 0) return { kind: "absent" };
|
|
13571
13721
|
return value.includes("{{") ? { kind: "placeholder" } : { kind: "static", value };
|
|
13572
13722
|
}
|
|
13573
|
-
function buildAgentInventory(input, status, models, version) {
|
|
13723
|
+
function buildAgentInventory(input, status, models, version, configSource) {
|
|
13574
13724
|
const agent = { id: input.id, name: input.name ?? input.id, status, models: [...models] };
|
|
13575
13725
|
if (version !== void 0) agent.version = version;
|
|
13726
|
+
if (configSource !== void 0) agent.configSource = configSource;
|
|
13576
13727
|
return agent;
|
|
13577
13728
|
}
|
|
13578
13729
|
|
|
@@ -13599,7 +13750,13 @@ async function claudeAgentInventory(input) {
|
|
|
13599
13750
|
throw new HarnessDetectError({ id: input.id, stage: "auth", reason: "invocation_context_required" });
|
|
13600
13751
|
}
|
|
13601
13752
|
const status = signinProbe !== void 0 ? await signinProbeStatus({ command: input.command, args: signinProbe.args, runner: input.runner, timeoutMs, env }) : await nativeAuthStatus(input, env, timeoutMs);
|
|
13602
|
-
|
|
13753
|
+
const configSource = resolveAgentConfigSource({
|
|
13754
|
+
homeDir: input.homeDir ?? homedir(),
|
|
13755
|
+
...input.configDir !== void 0 ? { configDir: input.configDir } : {},
|
|
13756
|
+
...input.instanceEnvFile !== void 0 ? { instanceEnvFile: input.instanceEnvFile } : {},
|
|
13757
|
+
...input.processEnv !== void 0 ? { processEnv: input.processEnv } : {}
|
|
13758
|
+
});
|
|
13759
|
+
return buildAgentInventory({ id: input.id, name: input.name }, status, input.overrides?.models ?? [], version.version, configSource);
|
|
13603
13760
|
}
|
|
13604
13761
|
async function nativeAuthStatus(input, env, timeoutMs) {
|
|
13605
13762
|
const run = await input.runner.run({
|
|
@@ -13670,7 +13827,7 @@ var CodexHarnessDetector = class {
|
|
|
13670
13827
|
|
|
13671
13828
|
// ../../core/packages/runner-core/src/harness/detect-pi.ts
|
|
13672
13829
|
import { readFile as readFile3, stat as stat3 } from "node:fs/promises";
|
|
13673
|
-
import { homedir } from "node:os";
|
|
13830
|
+
import { homedir as homedir2 } from "node:os";
|
|
13674
13831
|
import { join as join6 } from "node:path";
|
|
13675
13832
|
var ENV_AGENT_DIR = "PI_CODING_AGENT_DIR";
|
|
13676
13833
|
var BUILTIN_ENV_KEYS = {
|
|
@@ -13763,7 +13920,7 @@ function agentDirOf(input) {
|
|
|
13763
13920
|
if (fromEnv.includes("{{")) throw invocationContextRequired(input.id);
|
|
13764
13921
|
return fromEnv;
|
|
13765
13922
|
}
|
|
13766
|
-
return join6(input.homeDir ??
|
|
13923
|
+
return join6(input.homeDir ?? homedir2(), ".pi", "agent");
|
|
13767
13924
|
}
|
|
13768
13925
|
function invocationContextRequired(id) {
|
|
13769
13926
|
return new HarnessDetectError({ id, stage: "auth", reason: "invocation_context_required" });
|
|
@@ -13966,8 +14123,8 @@ var PiHarnessDetector = class {
|
|
|
13966
14123
|
|
|
13967
14124
|
// ../../core/packages/runner-core/src/harness/claude.ts
|
|
13968
14125
|
import { readdir as readdir2, stat as stat6 } from "node:fs/promises";
|
|
13969
|
-
import { writeFileSync } from "node:fs";
|
|
13970
|
-
import { homedir as
|
|
14126
|
+
import { existsSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
|
|
14127
|
+
import { homedir as homedir3 } from "node:os";
|
|
13971
14128
|
import { join as join7 } from "node:path";
|
|
13972
14129
|
|
|
13973
14130
|
// ../../core/packages/runner-core/src/harness/transcript-read.ts
|
|
@@ -14787,6 +14944,8 @@ var ClaudeHarnessAdapter = class {
|
|
|
14787
14944
|
/** Machine-launch.env (пути скриптов, CLAUDE_CONFIG_DIR, изоляция);
|
|
14788
14945
|
* подстановки применяются при запуске. */
|
|
14789
14946
|
launchEnv;
|
|
14947
|
+
/** #873: env-файл экземпляра — нижний слой detect- и autonomy-проб. */
|
|
14948
|
+
agentEnv;
|
|
14790
14949
|
// Вынос разбора транскриптов из event loop (#141 §4.3); не задан —
|
|
14791
14950
|
// in-process.
|
|
14792
14951
|
executor;
|
|
@@ -14805,10 +14964,11 @@ var ClaudeHarnessAdapter = class {
|
|
|
14805
14964
|
constructor(opts) {
|
|
14806
14965
|
this.id = opts.id;
|
|
14807
14966
|
this.command = opts.command;
|
|
14808
|
-
this.homeDir = opts.homeDir ??
|
|
14967
|
+
this.homeDir = opts.homeDir ?? homedir3();
|
|
14809
14968
|
this.configDir = opts.configDir ?? opts.launchEnv?.CLAUDE_CONFIG_DIR;
|
|
14810
14969
|
this.prependArgs = opts.prependArgs ?? [];
|
|
14811
14970
|
this.launchEnv = opts.launchEnv ?? {};
|
|
14971
|
+
if (opts.agentEnv !== void 0) this.agentEnv = opts.agentEnv;
|
|
14812
14972
|
if (opts.executor !== void 0) this.executor = opts.executor;
|
|
14813
14973
|
this.probeRunner = opts.runner;
|
|
14814
14974
|
this.probeOverrides = opts.probeOverrides;
|
|
@@ -14829,8 +14989,10 @@ var ClaudeHarnessAdapter = class {
|
|
|
14829
14989
|
runner: this.probeRunner ?? new ExecCommandRunner({ logger: this.probeLogger ?? noopLogger }),
|
|
14830
14990
|
logger: this.logger ?? this.probeLogger ?? noopLogger,
|
|
14831
14991
|
...this.probeOverrides !== void 0 ? { overrides: this.probeOverrides } : {},
|
|
14832
|
-
|
|
14992
|
+
// #873: карта экземпляра под статическим launch.env.
|
|
14993
|
+
probeEnv: { ...this.agentEnv ?? {}, ...staticProbeEnv(this.launchEnv) },
|
|
14833
14994
|
launchEnv: this.launchEnv,
|
|
14995
|
+
homeDir: this.homeDir,
|
|
14834
14996
|
...this.configDir !== void 0 ? { configDir: this.configDir } : {}
|
|
14835
14997
|
});
|
|
14836
14998
|
}
|
|
@@ -15062,6 +15224,7 @@ var ClaudeHarnessAdapter = class {
|
|
|
15062
15224
|
PATH: process.env.PATH ?? "",
|
|
15063
15225
|
HOME: process.env.HOME ?? ""
|
|
15064
15226
|
};
|
|
15227
|
+
for (const [key, value] of Object.entries(this.agentEnv ?? {})) env[key] = value;
|
|
15065
15228
|
for (const [key, value] of Object.entries(this.launchEnv)) env[key] = substituteTokens(value, substitutions);
|
|
15066
15229
|
const logFile = join7(sandboxDir, "probe.log");
|
|
15067
15230
|
let identity;
|
|
@@ -15118,9 +15281,17 @@ var ClaudeHarnessAdapter = class {
|
|
|
15118
15281
|
}
|
|
15119
15282
|
/** Статические факты автономности (#661 §4.2): режим из машинных аргументов
|
|
15120
15283
|
* и детерминированный вердикт по таблице спеки; процессов не спавнит.
|
|
15121
|
-
* Режим не задан или вердикта нет — решает autonomy-проба.
|
|
15284
|
+
* Режим не задан или вердикта нет — решает autonomy-проба.
|
|
15285
|
+
* Онбординг (#872): `~/.claude.json` без `hasCompletedOnboarding: true` —
|
|
15286
|
+
* постоянный вердикт `onboarding_required`, сильнее режимов разрешений. */
|
|
15122
15287
|
autonomy() {
|
|
15123
15288
|
const mode = permissionModeOf(this.prependArgs);
|
|
15289
|
+
if (readOnboardingFlag(this.homeDir) === false) {
|
|
15290
|
+
return {
|
|
15291
|
+
...mode !== void 0 ? { permissionMode: mode } : {},
|
|
15292
|
+
verdict: { status: "needs_setup", reason: "onboarding_required" }
|
|
15293
|
+
};
|
|
15294
|
+
}
|
|
15124
15295
|
if (mode === void 0) return {};
|
|
15125
15296
|
const facts = { permissionMode: mode };
|
|
15126
15297
|
if (mode === "plan") facts.verdict = { status: "needs_setup", reason: "permission_mode_readonly" };
|
|
@@ -15134,6 +15305,26 @@ var ClaudeHarnessAdapter = class {
|
|
|
15134
15305
|
return facts;
|
|
15135
15306
|
}
|
|
15136
15307
|
};
|
|
15308
|
+
function readOnboardingFlag(homeDir) {
|
|
15309
|
+
try {
|
|
15310
|
+
if (!existsSync(homeDir)) return null;
|
|
15311
|
+
} catch {
|
|
15312
|
+
return null;
|
|
15313
|
+
}
|
|
15314
|
+
const file = join7(homeDir, ".claude.json");
|
|
15315
|
+
let raw;
|
|
15316
|
+
try {
|
|
15317
|
+
if (!existsSync(file)) return existsSync(homeDir) ? false : null;
|
|
15318
|
+
raw = readFileSync2(file, "utf8");
|
|
15319
|
+
} catch (error) {
|
|
15320
|
+
return error.code === "ENOENT" ? false : null;
|
|
15321
|
+
}
|
|
15322
|
+
try {
|
|
15323
|
+
return JSON.parse(raw).hasCompletedOnboarding === true;
|
|
15324
|
+
} catch {
|
|
15325
|
+
return null;
|
|
15326
|
+
}
|
|
15327
|
+
}
|
|
15137
15328
|
|
|
15138
15329
|
// ../../core/packages/runner-core/src/harness/jsonl.ts
|
|
15139
15330
|
import { lstat as lstat5, mkdir, stat as stat7, symlink } from "node:fs/promises";
|
|
@@ -15144,6 +15335,8 @@ var JsonlHarnessAdapter = class {
|
|
|
15144
15335
|
sessionsRoot;
|
|
15145
15336
|
launchArgs;
|
|
15146
15337
|
launchEnv;
|
|
15338
|
+
/** #873: env-файл экземпляра — нижний слой detect-пробы. */
|
|
15339
|
+
agentEnv;
|
|
15147
15340
|
// Вынос разбора транскриптов из event loop (#141 §4.3); не задан —
|
|
15148
15341
|
// in-process.
|
|
15149
15342
|
executor;
|
|
@@ -15160,6 +15353,7 @@ var JsonlHarnessAdapter = class {
|
|
|
15160
15353
|
this.sessionsRoot = opts.sessionsRoot;
|
|
15161
15354
|
this.launchArgs = opts.launchArgs ?? [];
|
|
15162
15355
|
this.launchEnv = opts.launchEnv ?? {};
|
|
15356
|
+
if (opts.agentEnv !== void 0) this.agentEnv = opts.agentEnv;
|
|
15163
15357
|
if (opts.executor !== void 0) this.executor = opts.executor;
|
|
15164
15358
|
this.probeRunner = opts.runner;
|
|
15165
15359
|
this.probeOverrides = opts.probeOverrides;
|
|
@@ -15171,7 +15365,7 @@ var JsonlHarnessAdapter = class {
|
|
|
15171
15365
|
* generic-основе. ExecCommandRunner — ленивый дефолт изолированного
|
|
15172
15366
|
* использования; композиция передаёт общий runner. */
|
|
15173
15367
|
detect() {
|
|
15174
|
-
const probeEnv = staticProbeEnv(this.launchEnv);
|
|
15368
|
+
const probeEnv = { ...this.agentEnv ?? {}, ...staticProbeEnv(this.launchEnv) };
|
|
15175
15369
|
const logger = this.probeLogger ?? noopLogger;
|
|
15176
15370
|
const runner = this.probeRunner ?? new ExecCommandRunner({ logger });
|
|
15177
15371
|
const optional = {
|
|
@@ -15215,7 +15409,9 @@ var JsonlHarnessAdapter = class {
|
|
|
15215
15409
|
...overrides?.signinProbe !== void 0 ? { signinProbe: overrides.signinProbe } : {},
|
|
15216
15410
|
...overrides?.models !== void 0 ? { models: overrides.models } : {}
|
|
15217
15411
|
},
|
|
15218
|
-
runner
|
|
15412
|
+
runner,
|
|
15413
|
+
// C0/A0: generic-ветка базовой ветки не передавала env вовсе.
|
|
15414
|
+
{ ...this.agentEnv !== void 0 && Object.keys(this.agentEnv).length > 0 ? { probeEnv } : {} }
|
|
15219
15415
|
);
|
|
15220
15416
|
return detector.detect();
|
|
15221
15417
|
}
|
|
@@ -15247,10 +15443,10 @@ var JsonlHarnessAdapter = class {
|
|
|
15247
15443
|
prepare = async () => {
|
|
15248
15444
|
await mkdir(this.sessionsRoot, { recursive: true });
|
|
15249
15445
|
await mkdir(dirname(writerPath), { recursive: true });
|
|
15250
|
-
const logSymlink = (
|
|
15446
|
+
const logSymlink = (link4, target) => {
|
|
15251
15447
|
(this.probeLogger ?? noopLogger).debug("transcript symlink created", {
|
|
15252
15448
|
invocation_id: input.invocationId,
|
|
15253
|
-
link_path:
|
|
15449
|
+
link_path: link4,
|
|
15254
15450
|
target_path: target,
|
|
15255
15451
|
operation: "symlink"
|
|
15256
15452
|
});
|
|
@@ -15425,9 +15621,11 @@ function harnessAdaptersOf(harnesses, deps) {
|
|
|
15425
15621
|
id: harness.id,
|
|
15426
15622
|
command: harness.command,
|
|
15427
15623
|
...configDir !== void 0 ? { configDir } : {},
|
|
15624
|
+
...deps.homeDir !== void 0 ? { homeDir: deps.homeDir } : {},
|
|
15428
15625
|
...harness.launch?.args !== void 0 ? { prependArgs: harness.launch.args } : {},
|
|
15429
15626
|
...harness.launch?.env !== void 0 ? { launchEnv: harness.launch.env } : {},
|
|
15430
15627
|
...probeOpts,
|
|
15628
|
+
...deps.agentEnv !== void 0 ? { agentEnv: deps.agentEnv } : {},
|
|
15431
15629
|
logger: deps.logger
|
|
15432
15630
|
}));
|
|
15433
15631
|
} else if (harness.launch?.sessionsRoot !== void 0) {
|
|
@@ -15437,7 +15635,8 @@ function harnessAdaptersOf(harnesses, deps) {
|
|
|
15437
15635
|
sessionsRoot: harness.launch.sessionsRoot,
|
|
15438
15636
|
...harness.launch.args !== void 0 ? { launchArgs: harness.launch.args } : {},
|
|
15439
15637
|
...harness.launch.env !== void 0 ? { launchEnv: harness.launch.env } : {},
|
|
15440
|
-
...probeOpts
|
|
15638
|
+
...probeOpts,
|
|
15639
|
+
...deps.agentEnv !== void 0 ? { agentEnv: deps.agentEnv } : {}
|
|
15441
15640
|
}));
|
|
15442
15641
|
}
|
|
15443
15642
|
if (!adapters.has(harness.id)) {
|
|
@@ -15461,32 +15660,44 @@ function inventoryDetectorFor(harness, adapters, deps) {
|
|
|
15461
15660
|
command: harness.command,
|
|
15462
15661
|
...harness.name !== void 0 ? { probeName: harness.name } : {},
|
|
15463
15662
|
...configDir !== void 0 ? { configDir } : {},
|
|
15663
|
+
...deps.homeDir !== void 0 ? { homeDir: deps.homeDir } : {},
|
|
15464
15664
|
...harness.launch?.args !== void 0 ? { prependArgs: harness.launch.args } : {},
|
|
15465
15665
|
...harness.launch?.env !== void 0 ? { launchEnv: harness.launch.env } : {},
|
|
15466
15666
|
runner: deps.runner,
|
|
15467
15667
|
...overridesOpt,
|
|
15668
|
+
...deps.agentEnv !== void 0 ? { agentEnv: deps.agentEnv } : {},
|
|
15468
15669
|
probeLogger: deps.logger
|
|
15469
15670
|
});
|
|
15470
15671
|
}
|
|
15672
|
+
const probeEnv = { ...deps.agentEnv ?? {}, ...staticProbeEnv(harness.launch?.env) };
|
|
15471
15673
|
const family = {
|
|
15472
15674
|
id: harness.id,
|
|
15473
15675
|
command: harness.command,
|
|
15474
15676
|
...harness.name !== void 0 ? { name: harness.name } : {},
|
|
15475
15677
|
runner: deps.runner,
|
|
15476
15678
|
...overridesOpt,
|
|
15477
|
-
|
|
15679
|
+
// #873: карта экземпляра — нижний слой под статическим launch.env.
|
|
15680
|
+
probeEnv,
|
|
15478
15681
|
launchEnv: harness.launch?.env,
|
|
15479
15682
|
launchArgs: harness.launch?.args,
|
|
15480
15683
|
logger: deps.logger
|
|
15481
15684
|
};
|
|
15482
15685
|
if (harness.id === HARNESS_AGENTS.codex.id) return new CodexHarnessDetector(family);
|
|
15483
15686
|
if (harness.id === HARNESS_AGENTS.pi.id) return new PiHarnessDetector(family);
|
|
15484
|
-
return new ProbedHarnessDetector(harness, deps.runner, {
|
|
15687
|
+
return new ProbedHarnessDetector(harness, deps.runner, {
|
|
15688
|
+
logger: deps.logger,
|
|
15689
|
+
// C0/A0: без карты generic-проба вообще не получала env — сохраняем
|
|
15690
|
+
// побайтовое поведение базовой ветки; слой включается только после env set.
|
|
15691
|
+
...deps.agentEnv !== void 0 && Object.keys(deps.agentEnv).length > 0 ? { probeEnv } : {}
|
|
15692
|
+
});
|
|
15485
15693
|
}
|
|
15486
15694
|
|
|
15695
|
+
// ../../core/packages/runner-core/src/harness/detector-set.ts
|
|
15696
|
+
import { statSync as statSync6 } from "node:fs";
|
|
15697
|
+
|
|
15487
15698
|
// ../../core/packages/runner-core/src/harness/parse-executor.ts
|
|
15488
15699
|
import { spawn as nodeSpawn } from "node:child_process";
|
|
15489
|
-
import { existsSync } from "node:fs";
|
|
15700
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
15490
15701
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
15491
15702
|
var InProcessExecutor = class {
|
|
15492
15703
|
async checks(task) {
|
|
@@ -15502,7 +15713,7 @@ var InProcessExecutor = class {
|
|
|
15502
15713
|
}
|
|
15503
15714
|
};
|
|
15504
15715
|
function resolvePoolBootstrap(argv1 = process.argv[1] ?? "") {
|
|
15505
|
-
return argv1.endsWith("vite-node.mjs") &&
|
|
15716
|
+
return argv1.endsWith("vite-node.mjs") && existsSync2(argv1) ? argv1 : null;
|
|
15506
15717
|
}
|
|
15507
15718
|
var POOL_SIZE = 2;
|
|
15508
15719
|
var QUEUE_LIMIT = 16;
|
|
@@ -15745,12 +15956,12 @@ function createDefaultExecutor(logger) {
|
|
|
15745
15956
|
|
|
15746
15957
|
// ../../core/packages/runner-core/src/plugin/scan.ts
|
|
15747
15958
|
var import_semver = __toESM(require_semver2(), 1);
|
|
15748
|
-
import { existsSync as
|
|
15749
|
-
import { basename as
|
|
15959
|
+
import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync3 } from "node:fs";
|
|
15960
|
+
import { basename as basename9, join as join9 } from "node:path";
|
|
15750
15961
|
|
|
15751
15962
|
// ../../core/packages/plugin-sdk/src/const.ts
|
|
15752
15963
|
var SUPPORTED_PLUGIN_API_VERSIONS = [1];
|
|
15753
|
-
var CONTRIBUTION_KINDS = ["harness", "reporter"];
|
|
15964
|
+
var CONTRIBUTION_KINDS = ["harness", "reporter", "slug"];
|
|
15754
15965
|
var CONTRIBUTION_ID_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
|
|
15755
15966
|
var CONTRIBUTION_KEY_PATTERN = /^[a-z]+:[a-z][a-z0-9-]{0,31}$/;
|
|
15756
15967
|
|
|
@@ -15796,7 +16007,8 @@ function parseContribution(value, index) {
|
|
|
15796
16007
|
if (typeof kind !== "string" || !CONTRIBUTION_KINDS.includes(kind)) {
|
|
15797
16008
|
throw new PluginManifestError(`${path}.kind: expected one of ${CONTRIBUTION_KINDS.join(", ")}`);
|
|
15798
16009
|
}
|
|
15799
|
-
|
|
16010
|
+
const allowlist = kind === "harness" ? ["kind", "id", "name", "module", "optionsSchema"] : ["kind", "id", "name", "module", "optionsSchema", "secrets"];
|
|
16011
|
+
unknownFields(value, allowlist, path);
|
|
15800
16012
|
if (typeof value.id !== "string" || !CONTRIBUTION_ID_PATTERN.test(value.id)) {
|
|
15801
16013
|
throw new PluginManifestError(`${path}.id: expected a lowercase identifier (max 32 chars)`);
|
|
15802
16014
|
}
|
|
@@ -15816,6 +16028,16 @@ function parseContribution(value, index) {
|
|
|
15816
16028
|
...optionsSchema !== void 0 ? { optionsSchema } : {}
|
|
15817
16029
|
};
|
|
15818
16030
|
}
|
|
16031
|
+
if (kind === "slug") {
|
|
16032
|
+
return {
|
|
16033
|
+
kind: "slug",
|
|
16034
|
+
id: value.id,
|
|
16035
|
+
module: value.module,
|
|
16036
|
+
...value.name !== void 0 ? { name: value.name } : {},
|
|
16037
|
+
...optionsSchema !== void 0 ? { optionsSchema } : {},
|
|
16038
|
+
...value.secrets !== void 0 ? { secrets: parseSecrets(value.secrets, `${path}.secrets`) } : {}
|
|
16039
|
+
};
|
|
16040
|
+
}
|
|
15819
16041
|
return {
|
|
15820
16042
|
kind: "reporter",
|
|
15821
16043
|
id: value.id,
|
|
@@ -15994,7 +16216,7 @@ function mergePluginSettings(machine, user) {
|
|
|
15994
16216
|
|
|
15995
16217
|
// ../../core/packages/runner-core/src/plugin/host-manager.ts
|
|
15996
16218
|
import { spawn as spawn4 } from "node:child_process";
|
|
15997
|
-
import { existsSync as
|
|
16219
|
+
import { existsSync as existsSync3, mkdirSync } from "node:fs";
|
|
15998
16220
|
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
15999
16221
|
|
|
16000
16222
|
// ../../core/packages/runner-core/src/plugin/protocol.ts
|
|
@@ -16070,7 +16292,7 @@ function resolveHostEntryPath() {
|
|
|
16070
16292
|
fileURLToPath3(new URL("./host-entry.mjs", import.meta.url)),
|
|
16071
16293
|
fileURLToPath3(new URL("./plugin/host-entry.mjs", import.meta.url))
|
|
16072
16294
|
];
|
|
16073
|
-
return candidates.find((candidate) =>
|
|
16295
|
+
return candidates.find((candidate) => existsSync3(candidate)) ?? candidates[0];
|
|
16074
16296
|
}
|
|
16075
16297
|
var PluginHostDownError = class extends Error {
|
|
16076
16298
|
constructor(reason, message) {
|
|
@@ -16230,7 +16452,12 @@ var PluginHostManager = class {
|
|
|
16230
16452
|
}
|
|
16231
16453
|
this.state = "ready";
|
|
16232
16454
|
this.readyInfo = message.contribution;
|
|
16233
|
-
this.send({
|
|
16455
|
+
this.send({
|
|
16456
|
+
type: "init",
|
|
16457
|
+
options: this.specRef.options,
|
|
16458
|
+
envNames: this.specRef.envNames,
|
|
16459
|
+
...this.specRef.subscription !== void 0 ? { subscription: this.specRef.subscription } : {}
|
|
16460
|
+
});
|
|
16234
16461
|
for (const waiter of this.readyWaiters) {
|
|
16235
16462
|
clearTimeout(waiter.timer);
|
|
16236
16463
|
waiter.resolve(message.contribution);
|
|
@@ -16435,6 +16662,9 @@ var PluginHarnessAdapter = class {
|
|
|
16435
16662
|
};
|
|
16436
16663
|
|
|
16437
16664
|
// ../../core/packages/runner-core/src/plugin/scan.ts
|
|
16665
|
+
function scanInstalledPlugins(pluginsRoot) {
|
|
16666
|
+
return activeVersions(scanRoot(pluginsRoot));
|
|
16667
|
+
}
|
|
16438
16668
|
var MAX_PACKAGE_SEGMENT_DEPTH = 3;
|
|
16439
16669
|
async function disposePluginHosts(managers) {
|
|
16440
16670
|
await Promise.all(managers.map((manager) => manager.dispose()));
|
|
@@ -16444,7 +16674,7 @@ function buildPluginAdapters(opts) {
|
|
|
16444
16674
|
const managers = [];
|
|
16445
16675
|
if (opts.pluginsRoot === void 0) return { adapters, managers };
|
|
16446
16676
|
const effective = mergePluginSettings(opts.machinePlugins, opts.userPlugins);
|
|
16447
|
-
for (const installed of
|
|
16677
|
+
for (const installed of scanInstalledPlugins(opts.pluginsRoot)) {
|
|
16448
16678
|
if ("error" in installed) {
|
|
16449
16679
|
opts.logger.warn("plugin package skipped", { root: opts.pluginsRoot, dir: installed.dir, reason: installed.error });
|
|
16450
16680
|
continue;
|
|
@@ -16488,7 +16718,7 @@ function activeVersions(installed) {
|
|
|
16488
16718
|
continue;
|
|
16489
16719
|
}
|
|
16490
16720
|
if (entry.package === "") {
|
|
16491
|
-
results.push({ dir: entry.dir, error: "package.json: missing name" });
|
|
16721
|
+
results.push({ dir: entry.dir, error: "package.json: missing name", package: "" });
|
|
16492
16722
|
continue;
|
|
16493
16723
|
}
|
|
16494
16724
|
const current = best.get(entry.package);
|
|
@@ -16503,12 +16733,12 @@ function activeVersions(installed) {
|
|
|
16503
16733
|
}
|
|
16504
16734
|
function scanRoot(root) {
|
|
16505
16735
|
const results = [];
|
|
16506
|
-
if (!
|
|
16736
|
+
if (!existsSync4(root)) return results;
|
|
16507
16737
|
walk(root, 0);
|
|
16508
16738
|
return results;
|
|
16509
16739
|
function walk(dir, depth) {
|
|
16510
16740
|
if (depth > MAX_PACKAGE_SEGMENT_DEPTH + 1) return;
|
|
16511
|
-
if (
|
|
16741
|
+
if (existsSync4(join9(dir, "package.json")) && (0, import_semver.valid)(basename9(dir)) !== null) {
|
|
16512
16742
|
results.push(readEntry(dir));
|
|
16513
16743
|
return;
|
|
16514
16744
|
}
|
|
@@ -16524,16 +16754,18 @@ function scanRoot(root) {
|
|
|
16524
16754
|
}
|
|
16525
16755
|
}
|
|
16526
16756
|
function readEntry(dir) {
|
|
16757
|
+
let name;
|
|
16527
16758
|
try {
|
|
16528
|
-
const pkg = JSON.parse(
|
|
16759
|
+
const pkg = JSON.parse(readFileSync3(join9(dir, "package.json"), "utf8"));
|
|
16760
|
+
name = typeof pkg.name === "string" ? pkg.name : void 0;
|
|
16529
16761
|
return {
|
|
16530
|
-
package:
|
|
16762
|
+
package: name ?? "",
|
|
16531
16763
|
version: typeof pkg.version === "string" ? pkg.version : "",
|
|
16532
16764
|
dir,
|
|
16533
16765
|
manifest: parsePluginManifest(pkg)
|
|
16534
16766
|
};
|
|
16535
16767
|
} catch (error) {
|
|
16536
|
-
return { dir, error: error instanceof Error ? error.message : String(error) };
|
|
16768
|
+
return { dir, error: error instanceof Error ? error.message : String(error), ...name === void 0 ? {} : { package: name } };
|
|
16537
16769
|
}
|
|
16538
16770
|
}
|
|
16539
16771
|
}
|
|
@@ -16550,7 +16782,9 @@ function buildHarnessDetectorSet(options) {
|
|
|
16550
16782
|
runner: options.runner,
|
|
16551
16783
|
logger,
|
|
16552
16784
|
executor,
|
|
16553
|
-
host
|
|
16785
|
+
host,
|
|
16786
|
+
...options.homeDir !== void 0 ? { homeDir: options.homeDir } : {},
|
|
16787
|
+
...options.agentEnv !== void 0 ? { agentEnv: options.agentEnv } : {}
|
|
16554
16788
|
});
|
|
16555
16789
|
const scan = buildPluginAdapters({
|
|
16556
16790
|
pluginsRoot: options.pluginsRoot,
|
|
@@ -16571,21 +16805,53 @@ function buildHarnessDetectorSet(options) {
|
|
|
16571
16805
|
adapters.set(id, adapter);
|
|
16572
16806
|
pluginDetectors.set(id, adapter);
|
|
16573
16807
|
}
|
|
16574
|
-
const
|
|
16808
|
+
const rawDetectors = [
|
|
16575
16809
|
...options.harnesses.map(
|
|
16576
|
-
(harness) => inventoryDetectorFor(harness, adapters, {
|
|
16810
|
+
(harness) => inventoryDetectorFor(harness, adapters, {
|
|
16811
|
+
runner: options.runner,
|
|
16812
|
+
logger,
|
|
16813
|
+
...options.homeDir !== void 0 ? { homeDir: options.homeDir } : {},
|
|
16814
|
+
...options.agentEnv !== void 0 ? { agentEnv: options.agentEnv } : {}
|
|
16815
|
+
})
|
|
16577
16816
|
),
|
|
16578
16817
|
...pluginDetectors.values()
|
|
16579
16818
|
];
|
|
16580
16819
|
const detectorIds = [...options.harnesses.map((harness) => harness.id), ...pluginDetectors.keys()];
|
|
16820
|
+
let ambientCache = null;
|
|
16821
|
+
const ambient = () => {
|
|
16822
|
+
let key = "no-file";
|
|
16823
|
+
if (options.instanceEnvFile !== void 0) {
|
|
16824
|
+
try {
|
|
16825
|
+
const stats = statSync6(options.instanceEnvFile);
|
|
16826
|
+
key = `${stats.mtimeMs}:${stats.size}`;
|
|
16827
|
+
} catch {
|
|
16828
|
+
key = "absent";
|
|
16829
|
+
}
|
|
16830
|
+
}
|
|
16831
|
+
if (ambientCache !== null && ambientCache.key === key) return ambientCache.source;
|
|
16832
|
+
const source = resolveAmbientConfigSource({
|
|
16833
|
+
...options.instanceEnvFile !== void 0 ? { instanceEnvFile: options.instanceEnvFile } : {},
|
|
16834
|
+
processEnv: options.baseEnv
|
|
16835
|
+
});
|
|
16836
|
+
ambientCache = { key, source };
|
|
16837
|
+
return source;
|
|
16838
|
+
};
|
|
16839
|
+
const withAmbient = (inventory) => {
|
|
16840
|
+
const own = inventory.configSource;
|
|
16841
|
+
if (own !== void 0 && own.kind !== "none") return inventory;
|
|
16842
|
+
return { ...inventory, configSource: ambient() };
|
|
16843
|
+
};
|
|
16844
|
+
const wrapped = rawDetectors.map((detector) => ({
|
|
16845
|
+
detect: async () => withAmbient(await detector.detect())
|
|
16846
|
+
}));
|
|
16581
16847
|
let disposed = false;
|
|
16582
16848
|
return {
|
|
16583
16849
|
adapters,
|
|
16584
|
-
detectors,
|
|
16850
|
+
detectors: wrapped,
|
|
16585
16851
|
detectorIds,
|
|
16586
16852
|
async detect() {
|
|
16587
16853
|
return Promise.all(
|
|
16588
|
-
|
|
16854
|
+
wrapped.map(async (detector, index) => {
|
|
16589
16855
|
try {
|
|
16590
16856
|
return { kind: "agent", agent: await detector.detect() };
|
|
16591
16857
|
} catch (error) {
|
|
@@ -16611,12 +16877,12 @@ function buildHarnessDetectorSet(options) {
|
|
|
16611
16877
|
}
|
|
16612
16878
|
|
|
16613
16879
|
// ../../core/packages/runner-core/src/plugin/user-settings.ts
|
|
16614
|
-
import { existsSync as
|
|
16880
|
+
import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
|
|
16615
16881
|
function readPluginsSectionFromUser(file) {
|
|
16616
|
-
if (file === void 0 || !
|
|
16882
|
+
if (file === void 0 || !existsSync5(file)) return void 0;
|
|
16617
16883
|
let raw;
|
|
16618
16884
|
try {
|
|
16619
|
-
raw =
|
|
16885
|
+
raw = readFileSync4(file, "utf8");
|
|
16620
16886
|
} catch (error) {
|
|
16621
16887
|
throw new Error(`${file}: unreadable (${error.code ?? (error instanceof Error ? error.name : "unknown")})`);
|
|
16622
16888
|
}
|
|
@@ -16722,6 +16988,65 @@ function parseHarness(value, index) {
|
|
|
16722
16988
|
}
|
|
16723
16989
|
return harness;
|
|
16724
16990
|
}
|
|
16991
|
+
var REPORTER_ENTRY_FIELDS = ["subscription", "package", "reporter", "intervalMinutes", "timeoutSeconds", "options", "env"];
|
|
16992
|
+
var ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
16993
|
+
function parseReporterEntry(value, index) {
|
|
16994
|
+
const field = `reporters[${index}]`;
|
|
16995
|
+
if (!isPlainObject5(value)) throw new MachineConfigError(`${field}: expected an object`);
|
|
16996
|
+
for (const key of Object.keys(value)) {
|
|
16997
|
+
if (!REPORTER_ENTRY_FIELDS.includes(key)) {
|
|
16998
|
+
throw new MachineConfigError(`${field}.${key}: unknown field`);
|
|
16999
|
+
}
|
|
17000
|
+
}
|
|
17001
|
+
if (!nonEmptyString(value.subscription)) throw new MachineConfigError(`${field}.subscription: expected a non-empty string`);
|
|
17002
|
+
if (!nonEmptyString(value.package)) throw new MachineConfigError(`${field}.package: expected a non-empty string`);
|
|
17003
|
+
const entry = {
|
|
17004
|
+
subscription: value.subscription,
|
|
17005
|
+
package: value.package,
|
|
17006
|
+
intervalMinutes: 10,
|
|
17007
|
+
timeoutSeconds: 30,
|
|
17008
|
+
options: {},
|
|
17009
|
+
env: []
|
|
17010
|
+
};
|
|
17011
|
+
if (value.reporter !== void 0) {
|
|
17012
|
+
if (!nonEmptyString(value.reporter)) throw new MachineConfigError(`${field}.reporter: expected a non-empty string`);
|
|
17013
|
+
entry.reporter = value.reporter;
|
|
17014
|
+
}
|
|
17015
|
+
for (const [key, min] of [["intervalMinutes", 1], ["timeoutSeconds", 1]]) {
|
|
17016
|
+
const raw = value[key];
|
|
17017
|
+
if (raw === void 0) continue;
|
|
17018
|
+
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < min) {
|
|
17019
|
+
throw new MachineConfigError(`${field}.${key}: expected an integer >= ${min}`);
|
|
17020
|
+
}
|
|
17021
|
+
entry[key] = raw;
|
|
17022
|
+
}
|
|
17023
|
+
if (value.options !== void 0) {
|
|
17024
|
+
if (!isPlainObject5(value.options)) throw new MachineConfigError(`${field}.options: expected an object`);
|
|
17025
|
+
entry.options = value.options;
|
|
17026
|
+
}
|
|
17027
|
+
if (value.env !== void 0) {
|
|
17028
|
+
if (!Array.isArray(value.env)) throw new MachineConfigError(`${field}.env: expected an array of env names`);
|
|
17029
|
+
entry.env = value.env.map((name, envIndex) => {
|
|
17030
|
+
if (typeof name !== "string" || !ENV_NAME_PATTERN.test(name)) {
|
|
17031
|
+
throw new MachineConfigError(`${field}.env[${envIndex}]: expected a valid env name`);
|
|
17032
|
+
}
|
|
17033
|
+
return name;
|
|
17034
|
+
});
|
|
17035
|
+
}
|
|
17036
|
+
return entry;
|
|
17037
|
+
}
|
|
17038
|
+
function parseReportersSection(value) {
|
|
17039
|
+
if (!Array.isArray(value)) throw new MachineConfigError("reporters: expected an array");
|
|
17040
|
+
const entries = value.map(parseReporterEntry);
|
|
17041
|
+
const seen = /* @__PURE__ */ new Set();
|
|
17042
|
+
for (const [index, reporter] of entries.entries()) {
|
|
17043
|
+
if (seen.has(reporter.subscription)) {
|
|
17044
|
+
throw new MachineConfigError(`reporters[${index}].subscription: duplicate subscription ${JSON.stringify(reporter.subscription)}`);
|
|
17045
|
+
}
|
|
17046
|
+
seen.add(reporter.subscription);
|
|
17047
|
+
}
|
|
17048
|
+
return entries;
|
|
17049
|
+
}
|
|
16725
17050
|
async function loadMachineInventoryConfig(path, logger = noopLogger) {
|
|
16726
17051
|
if (path === void 0) return emptyMachineInventoryConfig();
|
|
16727
17052
|
let raw;
|
|
@@ -16810,6 +17135,9 @@ async function loadMachineInventoryConfig(path, logger = noopLogger) {
|
|
|
16810
17135
|
}
|
|
16811
17136
|
config.plugins = parsed.plugins;
|
|
16812
17137
|
}
|
|
17138
|
+
if (parsed.reporters !== void 0) {
|
|
17139
|
+
config.reporters = parseReportersSection(parsed.reporters);
|
|
17140
|
+
}
|
|
16813
17141
|
logger.info("machine config loaded", {
|
|
16814
17142
|
path,
|
|
16815
17143
|
harnesses_count: config.harnesses.length,
|
|
@@ -16820,8 +17148,198 @@ async function loadMachineInventoryConfig(path, logger = noopLogger) {
|
|
|
16820
17148
|
return config;
|
|
16821
17149
|
}
|
|
16822
17150
|
|
|
17151
|
+
// ../../core/packages/runner-core/src/inventory/machine-bootstrap.ts
|
|
17152
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
17153
|
+
import { chmod as chmod2, link, mkdir as mkdir2, readFile as readFile5, rename, stat as stat8, unlink, writeFile } from "node:fs/promises";
|
|
17154
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
17155
|
+
import { dirname as dirname2, isAbsolute as isAbsolute6 } from "node:path";
|
|
17156
|
+
var HARNESS_DEFAULT_COMMANDS = {
|
|
17157
|
+
claudeCode: "claude",
|
|
17158
|
+
codex: "codex",
|
|
17159
|
+
pi: "pi"
|
|
17160
|
+
};
|
|
17161
|
+
function starterHarnessEntries() {
|
|
17162
|
+
return Object.keys(HARNESS_AGENTS).map((key) => {
|
|
17163
|
+
const agent = HARNESS_AGENTS[key];
|
|
17164
|
+
const entry = { id: agent.id, name: agent.name, command: HARNESS_DEFAULT_COMMANDS[key] };
|
|
17165
|
+
if (agent.id === HARNESS_AGENTS.claudeCode.id) entry.launch = { args: ["--permission-mode", "auto"] };
|
|
17166
|
+
return entry;
|
|
17167
|
+
});
|
|
17168
|
+
}
|
|
17169
|
+
async function detectStarterHarnesses(options) {
|
|
17170
|
+
const logger = options.logger ?? noopLogger;
|
|
17171
|
+
const entries = starterHarnessEntries();
|
|
17172
|
+
const runner = options.runner ?? new ExecCommandRunner({ logger });
|
|
17173
|
+
const setOptions = {
|
|
17174
|
+
harnesses: entries,
|
|
17175
|
+
runner,
|
|
17176
|
+
instanceDataDir: options.instanceDataDir,
|
|
17177
|
+
baseEnv: options.baseEnv,
|
|
17178
|
+
...options.pluginsRoot !== void 0 ? { pluginsRoot: options.pluginsRoot } : {},
|
|
17179
|
+
...options.machinePlugins !== void 0 ? { machinePlugins: options.machinePlugins } : {},
|
|
17180
|
+
...options.userPlugins !== void 0 ? { userPlugins: options.userPlugins } : {},
|
|
17181
|
+
...options.homeDir !== void 0 ? { homeDir: options.homeDir } : {},
|
|
17182
|
+
...options.agentEnv !== void 0 ? { agentEnv: options.agentEnv } : {},
|
|
17183
|
+
...options.instanceEnvFile !== void 0 ? { instanceEnvFile: options.instanceEnvFile } : {},
|
|
17184
|
+
...options.logger !== void 0 ? { logger: options.logger } : {},
|
|
17185
|
+
...options.pluginHostOptions !== void 0 ? { pluginHostOptions: options.pluginHostOptions } : {}
|
|
17186
|
+
};
|
|
17187
|
+
const set = options.detectorSetFactory !== void 0 ? options.detectorSetFactory(setOptions) : buildHarnessDetectorSet(setOptions);
|
|
17188
|
+
let results;
|
|
17189
|
+
try {
|
|
17190
|
+
results = await set.detect();
|
|
17191
|
+
} finally {
|
|
17192
|
+
await set.dispose().catch((disposeError) => {
|
|
17193
|
+
logger.warn("starter detector set dispose failed", { reason: "dispose_failed", err: disposeError });
|
|
17194
|
+
});
|
|
17195
|
+
}
|
|
17196
|
+
return classifyDetectionResults(results, entries, logger);
|
|
17197
|
+
}
|
|
17198
|
+
function classifyDetectionResults(results, entries, logger) {
|
|
17199
|
+
const entryById = new Map(entries.map((entry) => [entry.id, entry]));
|
|
17200
|
+
const detection = { agents: [], pluginHarnesses: [], skipped: [] };
|
|
17201
|
+
for (const result of results) {
|
|
17202
|
+
if (result.kind === "detect_failed") {
|
|
17203
|
+
detection.skipped.push({ id: result.id, skipped: "detect_failed", stage: result.stage, reason: result.reason });
|
|
17204
|
+
logger.warn("starter harness skipped", { harness: result.id, reason: "detect_failed", stage: result.stage });
|
|
17205
|
+
continue;
|
|
17206
|
+
}
|
|
17207
|
+
const entry = entryById.get(result.agent.id);
|
|
17208
|
+
if (entry !== void 0) {
|
|
17209
|
+
if (result.agent.status !== "not_installed") detection.agents.push({ entry, agent: result.agent });
|
|
17210
|
+
else {
|
|
17211
|
+
detection.skipped.push({ id: result.agent.id, skipped: "not_installed" });
|
|
17212
|
+
logger.warn("starter harness skipped", { harness: result.agent.id, reason: "not_installed" });
|
|
17213
|
+
}
|
|
17214
|
+
continue;
|
|
17215
|
+
}
|
|
17216
|
+
if (result.agent.status !== "not_installed") {
|
|
17217
|
+
detection.pluginHarnesses.push({
|
|
17218
|
+
id: result.agent.id,
|
|
17219
|
+
name: result.agent.name,
|
|
17220
|
+
status: result.agent.status,
|
|
17221
|
+
models: result.agent.models,
|
|
17222
|
+
...result.agent.version !== void 0 ? { version: result.agent.version } : {}
|
|
17223
|
+
});
|
|
17224
|
+
} else {
|
|
17225
|
+
detection.skipped.push({ id: result.agent.id, skipped: "not_installed" });
|
|
17226
|
+
}
|
|
17227
|
+
}
|
|
17228
|
+
return detection;
|
|
17229
|
+
}
|
|
17230
|
+
function buildStarterMachineConfig(detection, params) {
|
|
17231
|
+
const cloneRoots = [...params.cloneRoots];
|
|
17232
|
+
for (const [index, root] of cloneRoots.entries()) {
|
|
17233
|
+
if (!isAbsolute6(root)) throw new MachineConfigError(`cloneRoots[${index}]: expected an absolute path`);
|
|
17234
|
+
}
|
|
17235
|
+
return {
|
|
17236
|
+
slots: { total: Math.max(1, params.slotsTotal ?? 1) },
|
|
17237
|
+
capabilities: [],
|
|
17238
|
+
cloneRoots,
|
|
17239
|
+
harnesses: detection.agents.map(({ entry }) => ({ ...entry }))
|
|
17240
|
+
};
|
|
17241
|
+
}
|
|
17242
|
+
async function writeMachineConfigIfAbsent(path, document) {
|
|
17243
|
+
const dir = dirname2(path);
|
|
17244
|
+
const dirExisted = existsSync6(dir);
|
|
17245
|
+
await mkdir2(dir, { recursive: true });
|
|
17246
|
+
if (!dirExisted) await chmod2(dir, 448);
|
|
17247
|
+
const tmp = `${path}.${randomUUID5()}.tmp`;
|
|
17248
|
+
try {
|
|
17249
|
+
await writeFile(tmp, `${JSON.stringify(document, null, 2)}
|
|
17250
|
+
`, { mode: 384 });
|
|
17251
|
+
try {
|
|
17252
|
+
await link(tmp, path);
|
|
17253
|
+
return { created: true, path };
|
|
17254
|
+
} catch (error) {
|
|
17255
|
+
if (errnoOf(error) === "EEXIST") return { created: false, path };
|
|
17256
|
+
throw error;
|
|
17257
|
+
}
|
|
17258
|
+
} finally {
|
|
17259
|
+
await unlink(tmp).catch(() => void 0);
|
|
17260
|
+
}
|
|
17261
|
+
}
|
|
17262
|
+
function machineConfigEmptySections(config) {
|
|
17263
|
+
return machineConfigWarningTexts(config, "").map((entry) => entry.section);
|
|
17264
|
+
}
|
|
17265
|
+
function machineConfigWarningTexts(config, path) {
|
|
17266
|
+
const texts = [];
|
|
17267
|
+
if (config.slots.total === 0) {
|
|
17268
|
+
texts.push({ section: "slots", text: `no slots are configured in ${path}; set "slots": {"total": N} (N >= 1)` });
|
|
17269
|
+
}
|
|
17270
|
+
if (config.cloneRoots.length === 0) {
|
|
17271
|
+
texts.push({ section: "cloneRoots", text: `no cloneRoots are configured in ${path}; add absolute paths to the "cloneRoots" array` });
|
|
17272
|
+
}
|
|
17273
|
+
if (config.harnesses.length === 0) {
|
|
17274
|
+
texts.push({ section: "harnesses", text: `no harnesses are configured in ${path}; add a "harnesses" entry or run compivia engine create / compivia runner pair` });
|
|
17275
|
+
}
|
|
17276
|
+
return texts;
|
|
17277
|
+
}
|
|
17278
|
+
async function classifyExistingConfigWarnings(path, logger) {
|
|
17279
|
+
try {
|
|
17280
|
+
const existing = await loadMachineInventoryConfig(path, logger);
|
|
17281
|
+
return {
|
|
17282
|
+
config: existing,
|
|
17283
|
+
warnings: machineConfigWarningTexts(existing, path).map((entry) => entry.text)
|
|
17284
|
+
};
|
|
17285
|
+
} catch (error) {
|
|
17286
|
+
logger.warn("machine config not written", {
|
|
17287
|
+
path,
|
|
17288
|
+
reason: error instanceof MachineConfigError ? "invalid_json_left_as_is" : "unreadable_left_as_is",
|
|
17289
|
+
err: error
|
|
17290
|
+
});
|
|
17291
|
+
const text = error instanceof MachineConfigError ? `existing machine config at ${path} is not valid JSON; left as-is` : `existing machine config at ${path} was not readable (${errnoOf(error)}); left as-is`;
|
|
17292
|
+
return { config: emptyMachineInventoryConfig(), warnings: [text] };
|
|
17293
|
+
}
|
|
17294
|
+
}
|
|
17295
|
+
async function bootstrapMachineConfig(options) {
|
|
17296
|
+
const logger = options.logger ?? noopLogger;
|
|
17297
|
+
if (existsSync6(options.path)) {
|
|
17298
|
+
const { config: config2, warnings: warnings2 } = await classifyExistingConfigWarnings(options.path, logger);
|
|
17299
|
+
logger.info("machine config bootstrap finished", {
|
|
17300
|
+
path: options.path,
|
|
17301
|
+
created: false,
|
|
17302
|
+
agents: 0,
|
|
17303
|
+
skipped: 0,
|
|
17304
|
+
plugin_harnesses: 0
|
|
17305
|
+
});
|
|
17306
|
+
return { path: options.path, created: false, config: config2, detection: { agents: [], pluginHarnesses: [], skipped: [] }, warnings: warnings2 };
|
|
17307
|
+
}
|
|
17308
|
+
const detection = await detectStarterHarnesses(options);
|
|
17309
|
+
const config = buildStarterMachineConfig(detection, {
|
|
17310
|
+
cloneRoots: options.cloneRoots,
|
|
17311
|
+
...options.slotsTotal !== void 0 ? { slotsTotal: options.slotsTotal } : {}
|
|
17312
|
+
});
|
|
17313
|
+
let created;
|
|
17314
|
+
try {
|
|
17315
|
+
created = (await writeMachineConfigIfAbsent(options.path, config)).created;
|
|
17316
|
+
} catch (error) {
|
|
17317
|
+
const errno = errnoOf(error);
|
|
17318
|
+
logger.warn("machine config not written", { path: options.path, reason: "write_failed", errno, err: error });
|
|
17319
|
+
return {
|
|
17320
|
+
path: options.path,
|
|
17321
|
+
created: false,
|
|
17322
|
+
config,
|
|
17323
|
+
detection,
|
|
17324
|
+
warnings: [
|
|
17325
|
+
...machineConfigWarningTexts(config, options.path).map((entry) => entry.text),
|
|
17326
|
+
`machine config was not written to ${options.path}: ${errno}`
|
|
17327
|
+
]
|
|
17328
|
+
};
|
|
17329
|
+
}
|
|
17330
|
+
const warnings = created ? machineConfigWarningTexts(config, options.path).map((entry) => entry.text) : (await classifyExistingConfigWarnings(options.path, logger)).warnings;
|
|
17331
|
+
logger.info("machine config bootstrap finished", {
|
|
17332
|
+
path: options.path,
|
|
17333
|
+
created,
|
|
17334
|
+
agents: detection.agents.length,
|
|
17335
|
+
skipped: detection.skipped.length,
|
|
17336
|
+
plugin_harnesses: detection.pluginHarnesses.length
|
|
17337
|
+
});
|
|
17338
|
+
return { path: options.path, created, config, detection, warnings };
|
|
17339
|
+
}
|
|
17340
|
+
|
|
16823
17341
|
// ../../core/packages/runner-core/src/inventory/packs.ts
|
|
16824
|
-
import { lstat as lstat6, readFile as
|
|
17342
|
+
import { lstat as lstat6, readFile as readFile6, readdir as readdir3 } from "node:fs/promises";
|
|
16825
17343
|
import { join as join10 } from "node:path";
|
|
16826
17344
|
var DirectoryPackCatalog = class {
|
|
16827
17345
|
constructor(opts) {
|
|
@@ -16843,7 +17361,7 @@ var DirectoryPackCatalog = class {
|
|
|
16843
17361
|
throw error;
|
|
16844
17362
|
}
|
|
16845
17363
|
const packs = [];
|
|
16846
|
-
let
|
|
17364
|
+
let invalid2 = 0;
|
|
16847
17365
|
for (const dirent of dirents) {
|
|
16848
17366
|
if (!dirent.isDirectory() || dirent.isSymbolicLink()) {
|
|
16849
17367
|
this.opts.logger.debug("pack candidate skipped: not a directory", { root, entry: dirent.name });
|
|
@@ -16851,10 +17369,10 @@ var DirectoryPackCatalog = class {
|
|
|
16851
17369
|
}
|
|
16852
17370
|
const entry = await this.packAt(join10(root, dirent.name));
|
|
16853
17371
|
if (entry !== void 0) packs.push(entry);
|
|
16854
|
-
else
|
|
17372
|
+
else invalid2++;
|
|
16855
17373
|
}
|
|
16856
17374
|
const result = packs.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
16857
|
-
this.opts.logger.debug("packs listed", { root, packs_count: result.length, invalid_count:
|
|
17375
|
+
this.opts.logger.debug("packs listed", { root, packs_count: result.length, invalid_count: invalid2 });
|
|
16858
17376
|
return result;
|
|
16859
17377
|
}
|
|
16860
17378
|
async packAt(dir) {
|
|
@@ -16875,7 +17393,7 @@ var DirectoryPackCatalog = class {
|
|
|
16875
17393
|
}
|
|
16876
17394
|
let raw;
|
|
16877
17395
|
try {
|
|
16878
|
-
raw = await
|
|
17396
|
+
raw = await readFile6(manifestPath, "utf8");
|
|
16879
17397
|
} catch (error) {
|
|
16880
17398
|
if (errnoOf(error) !== "ENOENT") {
|
|
16881
17399
|
this.opts.logger.error("pack manifest read failed", { dir, err: error });
|
|
@@ -16911,19 +17429,19 @@ var DirectoryPackCatalog = class {
|
|
|
16911
17429
|
};
|
|
16912
17430
|
|
|
16913
17431
|
// ../../core/packages/runner-core/src/inventory/repo-bindings.ts
|
|
16914
|
-
import { chmodSync as chmodSync4, statSync as
|
|
17432
|
+
import { chmodSync as chmodSync4, statSync as statSync7 } from "node:fs";
|
|
16915
17433
|
import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
|
|
16916
17434
|
var GIT_ACCESS_VALUES = ["ok", "auth_failed", "unreachable"];
|
|
16917
17435
|
function isGitAccess(value) {
|
|
16918
17436
|
return GIT_ACCESS_VALUES.includes(value);
|
|
16919
17437
|
}
|
|
16920
17438
|
function ensureOwnerOnly4(path, logger) {
|
|
16921
|
-
const mode =
|
|
17439
|
+
const mode = statSync7(path).mode & 511;
|
|
16922
17440
|
if (mode !== 384) {
|
|
16923
17441
|
logger.warn("bindings file mode corrected", { path, from_mode: mode.toString(8) });
|
|
16924
17442
|
chmodSync4(path, 384);
|
|
16925
17443
|
}
|
|
16926
|
-
if ((
|
|
17444
|
+
if ((statSync7(path).mode & 511) !== 384) {
|
|
16927
17445
|
throw new Error(`repo bindings file ${path} is not owner-only`);
|
|
16928
17446
|
}
|
|
16929
17447
|
}
|
|
@@ -17022,7 +17540,7 @@ var RepoBindingsStore = class _RepoBindingsStore {
|
|
|
17022
17540
|
};
|
|
17023
17541
|
|
|
17024
17542
|
// ../../core/packages/runner-core/src/inventory/repo-bind-service.ts
|
|
17025
|
-
import { isAbsolute as
|
|
17543
|
+
import { isAbsolute as isAbsolute7, resolve as resolve6 } from "node:path";
|
|
17026
17544
|
|
|
17027
17545
|
// ../../core/packages/runner-core/src/inventory/repo-identity.ts
|
|
17028
17546
|
function repositoryFromRemoteUrl(url) {
|
|
@@ -17060,7 +17578,7 @@ var RepoBindingService = class {
|
|
|
17060
17578
|
}
|
|
17061
17579
|
opts;
|
|
17062
17580
|
async check(repository, rawPath) {
|
|
17063
|
-
if (typeof rawPath !== "string" || !REPOSITORY_PATTERN2.test(repository) || rawPath === "" || !
|
|
17581
|
+
if (typeof rawPath !== "string" || !REPOSITORY_PATTERN2.test(repository) || rawPath === "" || !isAbsolute7(rawPath)) {
|
|
17064
17582
|
this.opts.logger.warn("bind params rejected", {
|
|
17065
17583
|
repository,
|
|
17066
17584
|
field: !REPOSITORY_PATTERN2.test(repository) ? "repository" : "path"
|
|
@@ -17302,7 +17820,8 @@ var InventoryService = class {
|
|
|
17302
17820
|
hooks,
|
|
17303
17821
|
slots: { total: this.opts.slots.total, busy },
|
|
17304
17822
|
capabilities: [...this.opts.capabilities],
|
|
17305
|
-
bindings
|
|
17823
|
+
bindings,
|
|
17824
|
+
reporters: this.opts.reporters?.() ?? []
|
|
17306
17825
|
};
|
|
17307
17826
|
this.lastBuilt = snapshot;
|
|
17308
17827
|
this.logger.debug("inventory snapshot built", {
|
|
@@ -17434,11 +17953,11 @@ var InventoryService = class {
|
|
|
17434
17953
|
};
|
|
17435
17954
|
|
|
17436
17955
|
// ../../core/packages/runner-core/src/worktree/service.ts
|
|
17437
|
-
import { createHash as createHash4, randomUUID as
|
|
17956
|
+
import { createHash as createHash4, randomUUID as randomUUID6 } from "node:crypto";
|
|
17438
17957
|
import { chmodSync as chmodSync5 } from "node:fs";
|
|
17439
17958
|
import { constants as fsConstants3 } from "node:fs";
|
|
17440
|
-
import { lstat as lstat10, mkdir as
|
|
17441
|
-
import { basename as
|
|
17959
|
+
import { lstat as lstat10, mkdir as mkdir6, open as open5, readFile as readFile7, readdir as readdir4, realpath as realpath6, rename as rename2, stat as statFile, writeFile as writeFile3 } from "node:fs/promises";
|
|
17960
|
+
import { basename as basename12, dirname as dirname6, join as join16, relative as relative2, resolve as resolve9, sep as sep3 } from "node:path";
|
|
17442
17961
|
import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
|
|
17443
17962
|
|
|
17444
17963
|
// ../../core/packages/runner-core/src/worktree/service-helpers.ts
|
|
@@ -17612,7 +18131,7 @@ async function baseRevisionOf(svc, clone, base) {
|
|
|
17612
18131
|
}
|
|
17613
18132
|
|
|
17614
18133
|
// ../../core/packages/runner-core/src/worktree/checkpoint.ts
|
|
17615
|
-
import { mkdir as
|
|
18134
|
+
import { mkdir as mkdir3, writeFile as writeFile2 } from "node:fs/promises";
|
|
17616
18135
|
import { join as join11 } from "node:path";
|
|
17617
18136
|
function stderrTail(stderr) {
|
|
17618
18137
|
if (stderr === void 0 || stderr === "") return void 0;
|
|
@@ -17649,8 +18168,8 @@ async function savePatch(run, opts) {
|
|
|
17649
18168
|
if (diff.stdout === "") return void 0;
|
|
17650
18169
|
const target = join11(opts.patchDir, `checkpoint-${opts.patchStem}.patch`);
|
|
17651
18170
|
try {
|
|
17652
|
-
await
|
|
17653
|
-
await
|
|
18171
|
+
await mkdir3(opts.patchDir, { recursive: true });
|
|
18172
|
+
await writeFile2(target, Buffer.from(diff.stdout, "latin1"));
|
|
17654
18173
|
return target;
|
|
17655
18174
|
} catch (error) {
|
|
17656
18175
|
opts.onPatchError?.(`patch write failed: ${error instanceof Error ? error.message : "non-error"}`);
|
|
@@ -17708,8 +18227,8 @@ async function checkpointOf(path, message, run, opts = {}) {
|
|
|
17708
18227
|
import { execFile as execFile4 } from "node:child_process";
|
|
17709
18228
|
import { createHash as createHash3 } from "node:crypto";
|
|
17710
18229
|
import { constants as constants3, createReadStream } from "node:fs";
|
|
17711
|
-
import { chmod as
|
|
17712
|
-
import { basename as
|
|
18230
|
+
import { chmod as chmod3, copyFile, glob, link as link2, lstat as lstat7, mkdir as mkdir4, opendir, rmdir, unlink as unlink2 } from "node:fs/promises";
|
|
18231
|
+
import { basename as basename10, dirname as dirname3, isAbsolute as isAbsolute8, join as join12, resolve as resolve7 } from "node:path";
|
|
17713
18232
|
var excluded = /* @__PURE__ */ new Set(["node_modules", "build", "dist", "target", "vendor", ".git", ".gradle", ".cache", "coverage"]);
|
|
17714
18233
|
function ignoredPaths(clone, paths, logger) {
|
|
17715
18234
|
return new Promise((resolve11, reject10) => {
|
|
@@ -17739,7 +18258,7 @@ function ignoredPaths(clone, paths, logger) {
|
|
|
17739
18258
|
});
|
|
17740
18259
|
}
|
|
17741
18260
|
function safeRelative2(path) {
|
|
17742
|
-
return path.length > 0 && !
|
|
18261
|
+
return path.length > 0 && !isAbsolute8(path) && !path.includes("\\") && !path.includes("\0") && !path.split("/").includes("..");
|
|
17743
18262
|
}
|
|
17744
18263
|
async function noSymlinks(path, logger, allowMissing = false) {
|
|
17745
18264
|
let current = resolve7(path);
|
|
@@ -17752,7 +18271,7 @@ async function noSymlinks(path, logger, allowMissing = false) {
|
|
|
17752
18271
|
return false;
|
|
17753
18272
|
}
|
|
17754
18273
|
}
|
|
17755
|
-
const parent =
|
|
18274
|
+
const parent = dirname3(current);
|
|
17756
18275
|
if (parent === current) return true;
|
|
17757
18276
|
current = parent;
|
|
17758
18277
|
}
|
|
@@ -17763,7 +18282,7 @@ async function fingerprint2(path) {
|
|
|
17763
18282
|
return hash.digest("hex");
|
|
17764
18283
|
}
|
|
17765
18284
|
async function cleanupConfigStaging(clone, worktree, logger = noopLogger) {
|
|
17766
|
-
const namespace =
|
|
18285
|
+
const namespace = basename10(worktree);
|
|
17767
18286
|
const directory = join12(clone, ".git", "compivia", "config-staging", namespace);
|
|
17768
18287
|
try {
|
|
17769
18288
|
if (namespace === "" || namespace === "." || namespace === "..") throw new Error("unsafe_staging");
|
|
@@ -17772,7 +18291,7 @@ async function cleanupConfigStaging(clone, worktree, logger = noopLogger) {
|
|
|
17772
18291
|
if (!entry.isFile() || !/^[a-f0-9]{64}$/.test(entry.name)) throw new Error("unsafe_staging");
|
|
17773
18292
|
const path = join12(directory, entry.name);
|
|
17774
18293
|
if (!await noSymlinks(path, logger) || !(await lstat7(path)).isFile()) throw new Error("unsafe_staging");
|
|
17775
|
-
await
|
|
18294
|
+
await unlink2(path);
|
|
17776
18295
|
}
|
|
17777
18296
|
if (!await noSymlinks(directory, logger)) throw new Error("unsafe_staging");
|
|
17778
18297
|
await rmdir(directory);
|
|
@@ -17817,13 +18336,13 @@ async function copyIgnoredConfigs(clone, worktree, globs = ["**/.env", "**/*.env
|
|
|
17817
18336
|
skipped++;
|
|
17818
18337
|
continue;
|
|
17819
18338
|
}
|
|
17820
|
-
const stagingDirectory = join12(clone, ".git", "compivia", "config-staging",
|
|
18339
|
+
const stagingDirectory = join12(clone, ".git", "compivia", "config-staging", basename10(worktree));
|
|
17821
18340
|
const staging = join12(stagingDirectory, createHash3("sha256").update(relative3).digest("hex"));
|
|
17822
18341
|
if (!await noSymlinks(staging, logger, true)) throw new Error("unsafe_staging");
|
|
17823
18342
|
try {
|
|
17824
18343
|
const stale = await lstat7(staging);
|
|
17825
18344
|
if (!stale.isFile()) throw new Error("unsafe_staging");
|
|
17826
|
-
await
|
|
18345
|
+
await unlink2(staging);
|
|
17827
18346
|
} catch (error) {
|
|
17828
18347
|
if (errnoOf(error) !== "ENOENT") throw error;
|
|
17829
18348
|
}
|
|
@@ -17837,22 +18356,22 @@ async function copyIgnoredConfigs(clone, worktree, globs = ["**/.env", "**/*.env
|
|
|
17837
18356
|
}
|
|
17838
18357
|
const sourceHash = await fingerprint2(source);
|
|
17839
18358
|
await persistFingerprint?.(relative3, sourceHash);
|
|
17840
|
-
await
|
|
18359
|
+
await mkdir4(stagingDirectory, { recursive: true, mode: 448 });
|
|
17841
18360
|
if (!await noSymlinks(stagingDirectory, logger)) throw new Error("unsafe_staging");
|
|
17842
|
-
await
|
|
18361
|
+
await chmod3(stagingDirectory, 448);
|
|
17843
18362
|
try {
|
|
17844
18363
|
if (!await noSymlinks(source, logger) || !(await lstat7(source)).isFile() || !await noSymlinks(staging, logger, true)) throw new Error("unsafe_staging");
|
|
17845
18364
|
await copyFile(source, staging, constants3.COPYFILE_EXCL);
|
|
17846
|
-
await
|
|
18365
|
+
await chmod3(staging, 384);
|
|
17847
18366
|
const copiedHash = await fingerprint2(staging);
|
|
17848
18367
|
if (copiedHash !== sourceHash) {
|
|
17849
18368
|
logger.warn("config source changed during copy", { path: relative3 });
|
|
17850
18369
|
await persistFingerprint?.(relative3, copiedHash);
|
|
17851
18370
|
}
|
|
17852
18371
|
if (!await noSymlinks(destination, logger, true) || !await noSymlinks(staging, logger)) throw new Error("unsafe_staging");
|
|
17853
|
-
await
|
|
18372
|
+
await mkdir4(dirname3(destination), { recursive: true });
|
|
17854
18373
|
try {
|
|
17855
|
-
await
|
|
18374
|
+
await link2(staging, destination);
|
|
17856
18375
|
} catch (error) {
|
|
17857
18376
|
if (errnoOf(error) === "EEXIST") {
|
|
17858
18377
|
logger.debug("ignored config skipped", { path: relative3, reason: "destination_exists" });
|
|
@@ -17866,7 +18385,7 @@ async function copyIgnoredConfigs(clone, worktree, globs = ["**/.env", "**/*.env
|
|
|
17866
18385
|
} finally {
|
|
17867
18386
|
if (!await noSymlinks(staging, logger, true)) throw new Error("unsafe_staging");
|
|
17868
18387
|
try {
|
|
17869
|
-
await
|
|
18388
|
+
await unlink2(staging);
|
|
17870
18389
|
} catch (error) {
|
|
17871
18390
|
if (errnoOf(error) !== "ENOENT") {
|
|
17872
18391
|
logger.error("config staging cleanup failed", { path: staging, err: error });
|
|
@@ -17954,10 +18473,10 @@ async function onlyCopiedConfigsInDirectory(worktree, directory, fingerprints, l
|
|
|
17954
18473
|
if (!safeRelative2(relative3) || relative3.split("/").some((part) => part === "" || part === ".")) return false;
|
|
17955
18474
|
if (!relative3.startsWith(`${directory}/`)) continue;
|
|
17956
18475
|
files.add(relative3);
|
|
17957
|
-
let parent =
|
|
18476
|
+
let parent = dirname3(relative3);
|
|
17958
18477
|
while (parent !== directory) {
|
|
17959
18478
|
directories.add(parent);
|
|
17960
|
-
parent =
|
|
18479
|
+
parent = dirname3(parent);
|
|
17961
18480
|
}
|
|
17962
18481
|
}
|
|
17963
18482
|
if (files.size === 0) return false;
|
|
@@ -17984,8 +18503,8 @@ async function onlyCopiedConfigsInDirectory(worktree, directory, fingerprints, l
|
|
|
17984
18503
|
}
|
|
17985
18504
|
|
|
17986
18505
|
// ../../core/packages/runner-core/src/worktree/root.ts
|
|
17987
|
-
import { lstat as lstat8, realpath as realpath4, stat as
|
|
17988
|
-
import { basename as
|
|
18506
|
+
import { lstat as lstat8, realpath as realpath4, stat as stat9 } from "node:fs/promises";
|
|
18507
|
+
import { basename as basename11, dirname as dirname4, join as join13, sep as sep2 } from "node:path";
|
|
17989
18508
|
var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
17990
18509
|
var DEFAULT_WORKTREE_ROOT_DIR = ".compivia-worktrees";
|
|
17991
18510
|
function unsafe() {
|
|
@@ -18007,9 +18526,9 @@ async function realpathOfWorktreeRoot(root) {
|
|
|
18007
18526
|
const tail = [];
|
|
18008
18527
|
let current = root;
|
|
18009
18528
|
for (; ; ) {
|
|
18010
|
-
const parent =
|
|
18529
|
+
const parent = dirname4(current);
|
|
18011
18530
|
if (parent === current) unsafe();
|
|
18012
|
-
tail.unshift(
|
|
18531
|
+
tail.unshift(basename11(current));
|
|
18013
18532
|
current = parent;
|
|
18014
18533
|
try {
|
|
18015
18534
|
const real = await realpath4(current);
|
|
@@ -18024,7 +18543,7 @@ function overlaps(a, b) {
|
|
|
18024
18543
|
return a === b || a.startsWith(`${b}${sep2}`) || b.startsWith(`${a}${sep2}`);
|
|
18025
18544
|
}
|
|
18026
18545
|
async function resolveWorktreeRoot(input) {
|
|
18027
|
-
const root = input.configuredRoot ?? join13(
|
|
18546
|
+
const root = input.configuredRoot ?? join13(dirname4(input.clone), DEFAULT_WORKTREE_ROOT_DIR);
|
|
18028
18547
|
const segments2 = input.repository.toLowerCase().split("/");
|
|
18029
18548
|
if (segments2.length !== 2 || segments2.some((segment) => !SEGMENT.test(segment))) unsafe();
|
|
18030
18549
|
if (!/^[a-f0-9-]{36}$/.test(input.worktreeId)) unsafe();
|
|
@@ -18037,7 +18556,7 @@ async function resolveWorktreeRoot(input) {
|
|
|
18037
18556
|
}
|
|
18038
18557
|
const uid = input.uid ?? process.getuid?.();
|
|
18039
18558
|
if (uid !== void 0) {
|
|
18040
|
-
const info = await
|
|
18559
|
+
const info = await stat9(resolvedRoot).catch(() => void 0);
|
|
18041
18560
|
if (info !== void 0 && info.uid !== uid) unsafe();
|
|
18042
18561
|
}
|
|
18043
18562
|
return { root: resolvedRoot, recordPath };
|
|
@@ -18046,11 +18565,11 @@ function effectiveConfiguredWorktreeRoot(cliRoot, machineRoot) {
|
|
|
18046
18565
|
return cliRoot ?? machineRoot;
|
|
18047
18566
|
}
|
|
18048
18567
|
function worktreeRootOfPath(recordPath) {
|
|
18049
|
-
return
|
|
18568
|
+
return dirname4(dirname4(dirname4(recordPath)));
|
|
18050
18569
|
}
|
|
18051
18570
|
|
|
18052
18571
|
// ../../core/packages/runner-core/src/worktree/release-steps.ts
|
|
18053
|
-
import { unlink as
|
|
18572
|
+
import { unlink as unlink3 } from "node:fs/promises";
|
|
18054
18573
|
import { join as join14 } from "node:path";
|
|
18055
18574
|
function releasePolicyVerdict(record, input) {
|
|
18056
18575
|
if (record.phase !== "releasing") return { conflict: false, upgrade: false };
|
|
@@ -18063,7 +18582,7 @@ async function forcedRemove(host, record) {
|
|
|
18063
18582
|
await host.git(record.clone, ["worktree", "remove", "--force", host.pathOf(record)]);
|
|
18064
18583
|
}
|
|
18065
18584
|
async function ordinaryRemove(host, record, untrackedConfigs, recheckClean) {
|
|
18066
|
-
for (const path of untrackedConfigs) await
|
|
18585
|
+
for (const path of untrackedConfigs) await unlink3(join14(host.pathOf(record), path));
|
|
18067
18586
|
try {
|
|
18068
18587
|
await host.git(record.clone, ["worktree", "remove", host.pathOf(record)]);
|
|
18069
18588
|
} catch (error) {
|
|
@@ -18668,7 +19187,7 @@ async function runSyncBase(ops, record, input) {
|
|
|
18668
19187
|
// ../../core/packages/runner-core/src/worktree/setup-contract.ts
|
|
18669
19188
|
import { constants as fsConstants2 } from "node:fs";
|
|
18670
19189
|
import { lstat as lstat9, open as open4, realpath as realpath5 } from "node:fs/promises";
|
|
18671
|
-
import { dirname as
|
|
19190
|
+
import { dirname as dirname5, join as join15 } from "node:path";
|
|
18672
19191
|
var COMPIVIA_DIR = ".compivia";
|
|
18673
19192
|
var SETUP_SCRIPT = "setup.sh";
|
|
18674
19193
|
var TEARDOWN_SCRIPT = "teardown.sh";
|
|
@@ -18782,7 +19301,7 @@ async function readRunEnvFile(worktree) {
|
|
|
18782
19301
|
if (!st.isFile()) return { ok: false, reason: "unsafe_path" };
|
|
18783
19302
|
if (st.size > RUN_ENV_MAX_BYTES) return { ok: false, reason: "too_large" };
|
|
18784
19303
|
const [realDir, realFile] = await Promise.all([realpath5(dir), realpath5(path)]);
|
|
18785
|
-
if (
|
|
19304
|
+
if (dirname5(realFile) !== realDir) return { ok: false, reason: "unsafe_path" };
|
|
18786
19305
|
const handle = await open4(path, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW | fsConstants2.O_NONBLOCK);
|
|
18787
19306
|
try {
|
|
18788
19307
|
const { size } = await handle.stat();
|
|
@@ -19239,7 +19758,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
19239
19758
|
created = cas.created;
|
|
19240
19759
|
startRevision = cas.startRevision;
|
|
19241
19760
|
baseVerified = cas.baseVerified;
|
|
19242
|
-
const worktreeId =
|
|
19761
|
+
const worktreeId = randomUUID6();
|
|
19243
19762
|
this.logger.info("worktree prepare started", {
|
|
19244
19763
|
worktree_id: worktreeId,
|
|
19245
19764
|
repository,
|
|
@@ -19262,7 +19781,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
19262
19781
|
boundClones
|
|
19263
19782
|
});
|
|
19264
19783
|
await this.safePath(resolved.root, resolved.recordPath, true);
|
|
19265
|
-
await
|
|
19784
|
+
await mkdir6(resolved.root, { recursive: true, mode: 448 });
|
|
19266
19785
|
await this.safePath(resolved.root, resolved.root);
|
|
19267
19786
|
record.path = resolved.recordPath;
|
|
19268
19787
|
} catch (error) {
|
|
@@ -19768,14 +20287,14 @@ var WorktreeService = class _WorktreeService {
|
|
|
19768
20287
|
// сверяются по дескриптору, усечение даёт детерминированный file_changed.
|
|
19769
20288
|
async guardedRead(root, file, maxBytes) {
|
|
19770
20289
|
const full = join16(root, file);
|
|
19771
|
-
const parent = join16(root,
|
|
20290
|
+
const parent = join16(root, dirname6(file));
|
|
19772
20291
|
await this.safePath(root, parent);
|
|
19773
20292
|
let actualParent;
|
|
19774
20293
|
try {
|
|
19775
20294
|
actualParent = await realpath6(parent);
|
|
19776
20295
|
} catch (error) {
|
|
19777
20296
|
this.logger.warn("worktree path canonicalization failed", {
|
|
19778
|
-
worktree_id:
|
|
20297
|
+
worktree_id: basename12(root),
|
|
19779
20298
|
path: file,
|
|
19780
20299
|
errno: error.code,
|
|
19781
20300
|
err: error
|
|
@@ -19789,7 +20308,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
19789
20308
|
handle = await open5(full, fsConstants3.O_RDONLY | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK);
|
|
19790
20309
|
} catch (error) {
|
|
19791
20310
|
this.logger.warn("worktree file open refused", {
|
|
19792
|
-
worktree_id:
|
|
20311
|
+
worktree_id: basename12(root),
|
|
19793
20312
|
path: file,
|
|
19794
20313
|
errno: error.code
|
|
19795
20314
|
});
|
|
@@ -19802,7 +20321,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
19802
20321
|
const stats = await handle.stat();
|
|
19803
20322
|
if (!stats.isFile()) {
|
|
19804
20323
|
this.logger.warn("worktree path is not a regular file", {
|
|
19805
|
-
worktree_id:
|
|
20324
|
+
worktree_id: basename12(root),
|
|
19806
20325
|
path: file,
|
|
19807
20326
|
file_type: stats.isDirectory() ? "directory" : stats.isSymbolicLink() ? "symlink" : "other"
|
|
19808
20327
|
});
|
|
@@ -19813,7 +20332,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
19813
20332
|
openedParent = await realpath6(parent);
|
|
19814
20333
|
} catch (error) {
|
|
19815
20334
|
this.logger.warn("worktree file stat failed", {
|
|
19816
|
-
worktree_id:
|
|
20335
|
+
worktree_id: basename12(root),
|
|
19817
20336
|
path: file,
|
|
19818
20337
|
errno: error.code
|
|
19819
20338
|
});
|
|
@@ -19826,7 +20345,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
19826
20345
|
pathStats = await statFile(full);
|
|
19827
20346
|
} catch (error) {
|
|
19828
20347
|
this.logger.warn("worktree file stat failed", {
|
|
19829
|
-
worktree_id:
|
|
20348
|
+
worktree_id: basename12(root),
|
|
19830
20349
|
path: file,
|
|
19831
20350
|
errno: error.code
|
|
19832
20351
|
});
|
|
@@ -19834,12 +20353,12 @@ var WorktreeService = class _WorktreeService {
|
|
|
19834
20353
|
reject2("unsafe_path");
|
|
19835
20354
|
}
|
|
19836
20355
|
if (pathStats.dev !== stats.dev || pathStats.ino !== stats.ino) {
|
|
19837
|
-
this.logger.warn("worktree file replaced during read", { worktree_id:
|
|
20356
|
+
this.logger.warn("worktree file replaced during read", { worktree_id: basename12(root), path: file });
|
|
19838
20357
|
reject2("unsafe_path");
|
|
19839
20358
|
}
|
|
19840
20359
|
if (stats.size > maxBytes) {
|
|
19841
20360
|
this.logger.warn("worktree file too large", {
|
|
19842
|
-
worktree_id:
|
|
20361
|
+
worktree_id: basename12(root),
|
|
19843
20362
|
path: file,
|
|
19844
20363
|
size_bytes: stats.size,
|
|
19845
20364
|
limit_bytes: maxBytes
|
|
@@ -19855,7 +20374,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
19855
20374
|
}
|
|
19856
20375
|
if (read !== stats.size) {
|
|
19857
20376
|
this.logger.warn("worktree file shrank during read", {
|
|
19858
|
-
worktree_id:
|
|
20377
|
+
worktree_id: basename12(root),
|
|
19859
20378
|
path: file,
|
|
19860
20379
|
expected_bytes: stats.size,
|
|
19861
20380
|
read_bytes: read
|
|
@@ -20115,7 +20634,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
20115
20634
|
if (managed(path)) remove.run(record.worktreeId, path);
|
|
20116
20635
|
}
|
|
20117
20636
|
for (const file of files) {
|
|
20118
|
-
const hash = createHash4("sha256").update(await
|
|
20637
|
+
const hash = createHash4("sha256").update(await readFile7(file.path)).digest("hex");
|
|
20119
20638
|
put.run(record.worktreeId, file.relative, hash);
|
|
20120
20639
|
}
|
|
20121
20640
|
await this.writeSetupExclude(record);
|
|
@@ -20124,10 +20643,10 @@ var WorktreeService = class _WorktreeService {
|
|
|
20124
20643
|
const gitDir = join16(record.clone, ".git");
|
|
20125
20644
|
await this.safePath(record.clone, gitDir);
|
|
20126
20645
|
const info = join16(gitDir, "info");
|
|
20127
|
-
await
|
|
20646
|
+
await mkdir6(info, { recursive: true });
|
|
20128
20647
|
let existing = "";
|
|
20129
20648
|
try {
|
|
20130
|
-
existing = await
|
|
20649
|
+
existing = await readFile7(join16(info, "exclude"), "utf8");
|
|
20131
20650
|
} catch (error) {
|
|
20132
20651
|
if (error.code !== "ENOENT") throw error;
|
|
20133
20652
|
}
|
|
@@ -20136,9 +20655,9 @@ var WorktreeService = class _WorktreeService {
|
|
|
20136
20655
|
lines.add(pattern);
|
|
20137
20656
|
}
|
|
20138
20657
|
const target = join16(info, "exclude");
|
|
20139
|
-
const temp = join16(info, `exclude.${
|
|
20140
|
-
await
|
|
20141
|
-
await
|
|
20658
|
+
const temp = join16(info, `exclude.${randomUUID6()}.tmp`);
|
|
20659
|
+
await writeFile3(temp, [...lines].join("\n") + "\n", { mode: 384 });
|
|
20660
|
+
await rename2(temp, target);
|
|
20142
20661
|
}
|
|
20143
20662
|
/** Окружение агента читается только из durable-записи, не из файла worktree:
|
|
20144
20663
|
* агент мог подменить run.env между рестартами (#654 §5). */
|
|
@@ -20327,7 +20846,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
20327
20846
|
const gitFile = join16(this.path(record), ".git");
|
|
20328
20847
|
const stats = await lstat10(gitFile);
|
|
20329
20848
|
if (!stats.isFile() || stats.isSymbolicLink()) refuseIndirection("gitfile");
|
|
20330
|
-
const content = await
|
|
20849
|
+
const content = await readFile7(gitFile, "utf8");
|
|
20331
20850
|
if (!content.startsWith("gitdir: ")) refuseIndirection("gitfile");
|
|
20332
20851
|
const gitDir = resolve9(this.path(record), content.slice(8).trim());
|
|
20333
20852
|
const rel = relative2(join16(record.clone, ".git", "worktrees"), gitDir);
|
|
@@ -20336,11 +20855,11 @@ var WorktreeService = class _WorktreeService {
|
|
|
20336
20855
|
if (record.phase === "preparing" && await this.pathExists(join16(gitDir, "locked"))) reject2("worktree_incomplete", "failed");
|
|
20337
20856
|
const commonFile = join16(gitDir, "commondir");
|
|
20338
20857
|
const commonStat = await lstat10(commonFile);
|
|
20339
|
-
if (!commonStat.isFile() || commonStat.isSymbolicLink() || resolve9(gitDir, (await
|
|
20858
|
+
if (!commonStat.isFile() || commonStat.isSymbolicLink() || resolve9(gitDir, (await readFile7(commonFile, "utf8")).trim()) !== join16(record.clone, ".git")) refuseIndirection("commondir");
|
|
20340
20859
|
const localConfig = join16(gitDir, "config.worktree");
|
|
20341
20860
|
if (await this.pathExists(localConfig)) {
|
|
20342
|
-
const
|
|
20343
|
-
if (!
|
|
20861
|
+
const stat12 = await lstat10(localConfig);
|
|
20862
|
+
if (!stat12.isFile() || stat12.isSymbolicLink()) reject2("unsafe_path");
|
|
20344
20863
|
const keys = await this.git(record.clone, ["config", "--file", localConfig, "--no-includes", "--name-only", "--list"]);
|
|
20345
20864
|
const allowed = /^(?:user\.(?:name|email)|core\.(?:filemode|autocrlf|eol|safecrlf)|remote\..*\.(?:url|pushurl)|url\..*\.(?:insteadof|pushinsteadof))$/;
|
|
20346
20865
|
const badKey = keys.split("\n").filter(Boolean).find((key) => !allowed.test(key));
|
|
@@ -20372,8 +20891,8 @@ var WorktreeService = class _WorktreeService {
|
|
|
20372
20891
|
for (const part of ["", ...rel.split(sep3).filter(Boolean)]) {
|
|
20373
20892
|
current = join16(current, part);
|
|
20374
20893
|
try {
|
|
20375
|
-
const
|
|
20376
|
-
if (
|
|
20894
|
+
const stat12 = await lstat10(current);
|
|
20895
|
+
if (stat12.isSymbolicLink() || !stat12.isDirectory()) reject2("unsafe_path");
|
|
20377
20896
|
} catch (error) {
|
|
20378
20897
|
if (missing && error.code === "ENOENT") return;
|
|
20379
20898
|
this.logger.warn("path safety check failed", {
|
|
@@ -20471,7 +20990,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
20471
20990
|
});
|
|
20472
20991
|
if (path !== void 0) {
|
|
20473
20992
|
this.logger.debug("git command finished", {
|
|
20474
|
-
worktree_id:
|
|
20993
|
+
worktree_id: basename12(path),
|
|
20475
20994
|
subcommand: subcommandOf2(args),
|
|
20476
20995
|
exit_code: result.kind === "exited" ? result.exitCode : void 0,
|
|
20477
20996
|
kind: result.kind,
|
|
@@ -20503,7 +21022,7 @@ var WorktreeService = class _WorktreeService {
|
|
|
20503
21022
|
if (r.stdoutTruncated) reject2("git_output_truncated", "failed");
|
|
20504
21023
|
if (r.exitCode !== 0) {
|
|
20505
21024
|
this.logger.warn("git command failed", {
|
|
20506
|
-
worktree_id:
|
|
21025
|
+
worktree_id: basename12(path),
|
|
20507
21026
|
subcommand: subcommandOf2(args),
|
|
20508
21027
|
exit_code: r.exitCode,
|
|
20509
21028
|
reason,
|
|
@@ -20623,7 +21142,7 @@ var EvidenceService = class {
|
|
|
20623
21142
|
/** Форма `evidence.collect` — публичная: обработчик команд проверяет её до
|
|
20624
21143
|
* accepted; семантические отказы (неизвестные id/ревизия) — в run. */
|
|
20625
21144
|
validateCollect(input) {
|
|
20626
|
-
const
|
|
21145
|
+
const invalid2 = (reason, field) => {
|
|
20627
21146
|
this.opts.logger.warn("evidence.collect rejected: invalid params", {
|
|
20628
21147
|
reason,
|
|
20629
21148
|
field,
|
|
@@ -20631,25 +21150,25 @@ var EvidenceService = class {
|
|
|
20631
21150
|
});
|
|
20632
21151
|
throw new CommandRejection("invalid", { reason });
|
|
20633
21152
|
};
|
|
20634
|
-
if (input.invocationId === void 0 === (input.sessionId === void 0))
|
|
20635
|
-
if (input.invocationId !== void 0 && (typeof input.invocationId !== "string" || !INVOCATION_ID.test(input.invocationId)))
|
|
21153
|
+
if (input.invocationId === void 0 === (input.sessionId === void 0)) invalid2("bad_params", "session");
|
|
21154
|
+
if (input.invocationId !== void 0 && (typeof input.invocationId !== "string" || !INVOCATION_ID.test(input.invocationId))) invalid2("bad_params", "invocation_id");
|
|
20636
21155
|
if (input.sessionId !== void 0) {
|
|
20637
21156
|
const sessionId = input.sessionId;
|
|
20638
|
-
if (typeof sessionId !== "string" || sessionId.length === 0 || sessionId.length > 128 || sessionId.includes("/") || sessionId.includes("\\") || sessionId === "." || sessionId === "..")
|
|
21157
|
+
if (typeof sessionId !== "string" || sessionId.length === 0 || sessionId.length > 128 || sessionId.includes("/") || sessionId.includes("\\") || sessionId === "." || sessionId === "..") invalid2("bad_params", "session_id");
|
|
20639
21158
|
}
|
|
20640
|
-
if (typeof input.worktreeId !== "string" || !UUID2.test(input.worktreeId))
|
|
20641
|
-
if (typeof input.fromRevision !== "string" || !SHA2.test(input.fromRevision))
|
|
20642
|
-
if (!Array.isArray(input.planPaths) || input.planPaths.length > MAX_PLAN_PATHS)
|
|
21159
|
+
if (typeof input.worktreeId !== "string" || !UUID2.test(input.worktreeId)) invalid2("bad_params", "worktree_id");
|
|
21160
|
+
if (typeof input.fromRevision !== "string" || !SHA2.test(input.fromRevision)) invalid2("bad_params", "from_revision");
|
|
21161
|
+
if (!Array.isArray(input.planPaths) || input.planPaths.length > MAX_PLAN_PATHS) invalid2("bad_params", "plan_paths");
|
|
20643
21162
|
const seenPlans = /* @__PURE__ */ new Set();
|
|
20644
21163
|
for (const path of input.planPaths) {
|
|
20645
|
-
if (typeof path !== "string" || !safeRelative(path) || path.length > 1024)
|
|
20646
|
-
if (seenPlans.has(path))
|
|
21164
|
+
if (typeof path !== "string" || !safeRelative(path) || path.length > 1024) invalid2("bad_params", "plan_path");
|
|
21165
|
+
if (seenPlans.has(path)) invalid2("bad_params", "plan_path");
|
|
20647
21166
|
seenPlans.add(path);
|
|
20648
21167
|
}
|
|
20649
21168
|
if (input.docsPaths !== void 0) {
|
|
20650
|
-
if (!Array.isArray(input.docsPaths) || input.docsPaths.length > MAX_DOCS_PATHS)
|
|
21169
|
+
if (!Array.isArray(input.docsPaths) || input.docsPaths.length > MAX_DOCS_PATHS) invalid2("bad_params", "docs_paths");
|
|
20651
21170
|
for (const path of input.docsPaths) {
|
|
20652
|
-
if (typeof path !== "string" || !safeRelative(path) || path.length > 1024)
|
|
21171
|
+
if (typeof path !== "string" || !safeRelative(path) || path.length > 1024) invalid2("bad_params", "docs_path");
|
|
20653
21172
|
}
|
|
20654
21173
|
}
|
|
20655
21174
|
}
|
|
@@ -20907,7 +21426,7 @@ var EvidenceService = class {
|
|
|
20907
21426
|
|
|
20908
21427
|
// ../../core/packages/runner-core/src/transcript/filter.ts
|
|
20909
21428
|
import { Buffer as Buffer2 } from "node:buffer";
|
|
20910
|
-
import { readFile as
|
|
21429
|
+
import { readFile as readFile8, readdir as readdir5 } from "node:fs/promises";
|
|
20911
21430
|
import { join as join17 } from "node:path";
|
|
20912
21431
|
var SUMMARY_LIMIT_BYTES = 2048;
|
|
20913
21432
|
var FRAME_BUDGET_BYTES = 8192;
|
|
@@ -20972,7 +21491,7 @@ async function envValuesFromRoot(root) {
|
|
|
20972
21491
|
}
|
|
20973
21492
|
const contents = [];
|
|
20974
21493
|
for (const name of names) {
|
|
20975
|
-
const content = await
|
|
21494
|
+
const content = await readFile8(join17(root, name), "utf8").catch(() => null);
|
|
20976
21495
|
if (content !== null) contents.push(content);
|
|
20977
21496
|
}
|
|
20978
21497
|
return TranscriptRedactor.envValuesOf(contents);
|
|
@@ -21456,9 +21975,9 @@ function transcriptCommandHandlers(input) {
|
|
|
21456
21975
|
}
|
|
21457
21976
|
|
|
21458
21977
|
// ../../core/packages/runner-core/src/invocation/service.ts
|
|
21459
|
-
import { randomUUID as
|
|
21460
|
-
import { mkdir as
|
|
21461
|
-
import { isAbsolute as
|
|
21978
|
+
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
21979
|
+
import { mkdir as mkdir7, readFile as readFile9, realpath as realpath7, rm, stat as stat10, writeFile as writeFile4 } from "node:fs/promises";
|
|
21980
|
+
import { isAbsolute as isAbsolute9, join as join18, sep as sep4 } from "node:path";
|
|
21462
21981
|
|
|
21463
21982
|
// ../../core/packages/runner-core/src/invocation/denial-summary.ts
|
|
21464
21983
|
var LOG_TAIL_BYTES = 256 * 1024;
|
|
@@ -21637,6 +22156,7 @@ async function appendCheckpointRecord(outcome, invocationId, payload) {
|
|
|
21637
22156
|
}
|
|
21638
22157
|
|
|
21639
22158
|
// ../../core/packages/runner-core/src/invocation/service.ts
|
|
22159
|
+
var ONBOARDING_REQUIRED_REASON = "onboarding_required";
|
|
21640
22160
|
function logSafe9(logger, level, msg, fields) {
|
|
21641
22161
|
try {
|
|
21642
22162
|
logger[level](msg, fields);
|
|
@@ -21802,7 +22322,7 @@ var InvocationService = class {
|
|
|
21802
22322
|
const adapter = this.adapterOf(params.harness);
|
|
21803
22323
|
await this.assertLaunchable(params);
|
|
21804
22324
|
const scratchDir = join18(this.opts.scratchRoot, params.invocationId);
|
|
21805
|
-
await
|
|
22325
|
+
await mkdir7(scratchDir, { recursive: true, mode: 448 });
|
|
21806
22326
|
return await this.startIn(scratchDir, params, adapter, outcome);
|
|
21807
22327
|
});
|
|
21808
22328
|
} catch (error) {
|
|
@@ -21831,7 +22351,7 @@ var InvocationService = class {
|
|
|
21831
22351
|
async spawnStart(scratchDir, params, adapter, externalDir) {
|
|
21832
22352
|
const { launch, sessionId, logFile, cwd, promptFile, contract } = await this.writeLaunchInputs(scratchDir, params, adapter, externalDir);
|
|
21833
22353
|
if (launch.transcriptPath !== null) {
|
|
21834
|
-
await
|
|
22354
|
+
await mkdir7(join18(launch.transcriptPath, ".."), { recursive: true }).catch((error) => this.bestEffortUndefined(error, "mkdir", params.invocationId));
|
|
21835
22355
|
}
|
|
21836
22356
|
const track = {
|
|
21837
22357
|
invocationId: params.invocationId,
|
|
@@ -21863,7 +22383,7 @@ var InvocationService = class {
|
|
|
21863
22383
|
|
|
21864
22384
|
${contract.preamble}
|
|
21865
22385
|
`;
|
|
21866
|
-
await
|
|
22386
|
+
await writeFile4(promptFile, prompt, { mode: 384 });
|
|
21867
22387
|
let outputSchemaText = null;
|
|
21868
22388
|
if (params.outputSchema !== void 0) {
|
|
21869
22389
|
outputSchemaText = JSON.stringify(params.outputSchema);
|
|
@@ -21873,10 +22393,10 @@ ${contract.preamble}
|
|
|
21873
22393
|
}
|
|
21874
22394
|
const outputSchemaFile = outputSchemaText === null ? null : await (async () => {
|
|
21875
22395
|
const path = join18(scratchDir, "output-schema.json");
|
|
21876
|
-
await
|
|
22396
|
+
await writeFile4(path, outputSchemaText, { mode: 384 });
|
|
21877
22397
|
return path;
|
|
21878
22398
|
})();
|
|
21879
|
-
const sessionId = params.resume !== void 0 ? params.resume.sessionId :
|
|
22399
|
+
const sessionId = params.resume !== void 0 ? params.resume.sessionId : randomUUID7();
|
|
21880
22400
|
const logFile = join18(scratchDir, "wrapper.log");
|
|
21881
22401
|
const cwd = externalDir !== void 0 ? externalDir : await this.resolveCwd(params.worktreeId, scratchDir);
|
|
21882
22402
|
const launchInput = {
|
|
@@ -22102,7 +22622,7 @@ ${contract.preamble}
|
|
|
22102
22622
|
/** Сайдкар-манифест старта: phaseRunId/worktreeId переживают рестарт
|
|
22103
22623
|
* runner'а (checkpoint и snapshot/heartbeat после подхвата). */
|
|
22104
22624
|
async writeStartManifest(invocationId, scratchDir, params) {
|
|
22105
|
-
await
|
|
22625
|
+
await writeFile4(join18(scratchDir, "invocation.json"), JSON.stringify({
|
|
22106
22626
|
...params.phaseRunId !== void 0 ? { phaseRunId: params.phaseRunId } : {},
|
|
22107
22627
|
...params.worktreeId !== void 0 ? { worktreeId: params.worktreeId } : {}
|
|
22108
22628
|
}), { mode: 384 }).catch((error) => {
|
|
@@ -22144,7 +22664,7 @@ ${contract.preamble}
|
|
|
22144
22664
|
/** Форма `agent.start` — публичная: обработчик команд делегирует её сюда,
|
|
22145
22665
|
* чтобы правила формы не расходились между слоями. */
|
|
22146
22666
|
validateStart(params) {
|
|
22147
|
-
const
|
|
22667
|
+
const invalid2 = (reason) => {
|
|
22148
22668
|
logSafe9(this.logger, "warn", "agent.start rejected: invalid params", {
|
|
22149
22669
|
reason,
|
|
22150
22670
|
invocation_id: typeof params.invocationId === "string" ? params.invocationId : null,
|
|
@@ -22153,13 +22673,13 @@ ${contract.preamble}
|
|
|
22153
22673
|
});
|
|
22154
22674
|
throw new CommandRejection("invalid", { reason });
|
|
22155
22675
|
};
|
|
22156
|
-
if (typeof params.invocationId !== "string" || params.invocationId === "") return
|
|
22157
|
-
if (!ID_PATTERN.test(params.invocationId)) return
|
|
22158
|
-
if (!ACTIVE_MODES.has(params.mode)) return
|
|
22159
|
-
if (params.resume !== void 0 && (typeof params.resume.sessionId !== "string" || params.resume.sessionId === "")) return
|
|
22160
|
-
if (params.resume !== void 0 && !ID_PATTERN.test(params.resume.sessionId)) return
|
|
22161
|
-
if (params.systemPrompt !== void 0 && params.mode !== "sessionless") return
|
|
22162
|
-
if (typeof params.prompt !== "string" || params.prompt === "") return
|
|
22676
|
+
if (typeof params.invocationId !== "string" || params.invocationId === "") return invalid2("invocationId_required");
|
|
22677
|
+
if (!ID_PATTERN.test(params.invocationId)) return invalid2("invocationId_invalid");
|
|
22678
|
+
if (!ACTIVE_MODES.has(params.mode)) return invalid2("mode_invalid");
|
|
22679
|
+
if (params.resume !== void 0 && (typeof params.resume.sessionId !== "string" || params.resume.sessionId === "")) return invalid2("resume_session_required");
|
|
22680
|
+
if (params.resume !== void 0 && !ID_PATTERN.test(params.resume.sessionId)) return invalid2("resume_session_invalid");
|
|
22681
|
+
if (params.systemPrompt !== void 0 && params.mode !== "sessionless") return invalid2("system_prompt_sessionless_only");
|
|
22682
|
+
if (typeof params.prompt !== "string" || params.prompt === "") return invalid2("prompt_required");
|
|
22163
22683
|
}
|
|
22164
22684
|
adapterOf(harness) {
|
|
22165
22685
|
const adapter = this.opts.adapters.get(harness);
|
|
@@ -22270,7 +22790,7 @@ ${contract.preamble}
|
|
|
22270
22790
|
if (typeof dir !== "string" || dir === "") {
|
|
22271
22791
|
throw new CommandRejection("invalid", { reason: "dir_required" });
|
|
22272
22792
|
}
|
|
22273
|
-
if (!
|
|
22793
|
+
if (!isAbsolute9(dir)) throw new CommandRejection("invalid", { reason: "dir_not_absolute" });
|
|
22274
22794
|
let real;
|
|
22275
22795
|
try {
|
|
22276
22796
|
real = await realpath7(dir);
|
|
@@ -22282,7 +22802,7 @@ ${contract.preamble}
|
|
|
22282
22802
|
});
|
|
22283
22803
|
throw new CommandRejection("invalid", { reason: "dir_not_found" });
|
|
22284
22804
|
}
|
|
22285
|
-
const info = await
|
|
22805
|
+
const info = await stat10(real).catch((error) => {
|
|
22286
22806
|
logSafe9(this.logger, "warn", "invocation.external_dir_stat_failed", {
|
|
22287
22807
|
err_code: errnoOf(error),
|
|
22288
22808
|
reason: "dir_stat_failed",
|
|
@@ -22624,7 +23144,7 @@ ${contract.preamble}
|
|
|
22624
23144
|
this.externalSinks.set(params.invocationId, outcome);
|
|
22625
23145
|
const scratchDir = join18(this.opts.scratchRoot, params.invocationId);
|
|
22626
23146
|
try {
|
|
22627
|
-
await
|
|
23147
|
+
await mkdir7(scratchDir, { recursive: true, mode: 448 });
|
|
22628
23148
|
return await this.spawnStart(scratchDir, params, adapter, dir);
|
|
22629
23149
|
} catch (error) {
|
|
22630
23150
|
await this.abandonFailedStart(params.invocationId, error, true);
|
|
@@ -22653,6 +23173,14 @@ ${contract.preamble}
|
|
|
22653
23173
|
throw new CommandRejection("unavailable", { reason: "harness_signin_needed" });
|
|
22654
23174
|
}
|
|
22655
23175
|
}
|
|
23176
|
+
if (this.opts.harnessVerdict !== void 0) {
|
|
23177
|
+
const verdicts = await this.opts.harnessVerdict();
|
|
23178
|
+
const verdict = verdicts?.get(params.harness);
|
|
23179
|
+
if (verdict?.compatibility === "needs_setup" && verdict.compatibilityReason === ONBOARDING_REQUIRED_REASON) {
|
|
23180
|
+
logSafe9(this.logger, "warn", "agent.start rejected: harness needs setup", { harness: params.harness, reason: "harness_needs_setup" });
|
|
23181
|
+
throw new CommandRejection("unavailable", { reason: "harness_needs_setup" });
|
|
23182
|
+
}
|
|
23183
|
+
}
|
|
22656
23184
|
const active = await this.busyCount();
|
|
22657
23185
|
if (active >= this.opts.slotsTotal) {
|
|
22658
23186
|
logSafe9(this.logger, "warn", "agent.start rejected: no free slot", {
|
|
@@ -23165,7 +23693,7 @@ ${contract.preamble}
|
|
|
23165
23693
|
// agent.stop
|
|
23166
23694
|
/** Форма `agent.stop` — публичная: обработчик команд делегирует её сюда. */
|
|
23167
23695
|
validateStop(params) {
|
|
23168
|
-
const
|
|
23696
|
+
const invalid2 = (reason) => {
|
|
23169
23697
|
logSafe9(this.logger, "warn", "agent.stop rejected: invalid params", {
|
|
23170
23698
|
reason,
|
|
23171
23699
|
invocation_id: typeof params.invocationId === "string" ? params.invocationId : null,
|
|
@@ -23173,8 +23701,8 @@ ${contract.preamble}
|
|
|
23173
23701
|
});
|
|
23174
23702
|
throw new CommandRejection("invalid", { reason });
|
|
23175
23703
|
};
|
|
23176
|
-
if (typeof params.invocationId !== "string" || params.invocationId === "") return
|
|
23177
|
-
if (params.mode !== "graceful" && params.mode !== "hard") return
|
|
23704
|
+
if (typeof params.invocationId !== "string" || params.invocationId === "") return invalid2("invocationId_required");
|
|
23705
|
+
if (params.mode !== "graceful" && params.mode !== "hard") return invalid2("mode_invalid");
|
|
23178
23706
|
}
|
|
23179
23707
|
/** Форма agent.stop — диспетчер над тремя путями (раунд 1 Architecture:
|
|
23180
23708
|
* lost-receipt, acknowledgment доставленного терминала, обычная лестница);
|
|
@@ -23799,7 +24327,7 @@ ${contract.preamble}
|
|
|
23799
24327
|
if (opts.remove === true) await this.opts.registry.remove(record.processId).catch((error) => this.bestEffortUndefined(error));
|
|
23800
24328
|
}
|
|
23801
24329
|
async readManifest(invocationId) {
|
|
23802
|
-
const raw = await
|
|
24330
|
+
const raw = await readFile9(join18(this.opts.scratchRoot, invocationId, "invocation.json"), "utf8").catch((error) => this.bestEffortNull(error, "readManifest", invocationId));
|
|
23803
24331
|
if (raw === null) return null;
|
|
23804
24332
|
try {
|
|
23805
24333
|
const parsed = JSON.parse(raw);
|
|
@@ -23843,16 +24371,16 @@ function clipFinal(text, invocationId, logger) {
|
|
|
23843
24371
|
}
|
|
23844
24372
|
|
|
23845
24373
|
// ../../core/packages/runner-core/src/runner-cli.ts
|
|
23846
|
-
import { existsSync as
|
|
23847
|
-
import { isAbsolute as
|
|
23848
|
-
import { dirname as
|
|
24374
|
+
import { existsSync as existsSync7, statSync as statSync9 } from "node:fs";
|
|
24375
|
+
import { isAbsolute as isAbsolute10 } from "node:path";
|
|
24376
|
+
import { dirname as dirname9, join as join22, resolve as resolve10 } from "node:path";
|
|
23849
24377
|
import { parseArgs } from "node:util";
|
|
23850
24378
|
|
|
23851
24379
|
// ../../core/packages/runner-core/src/runner-process.ts
|
|
23852
|
-
import { dirname as
|
|
24380
|
+
import { dirname as dirname8, join as join21 } from "node:path";
|
|
23853
24381
|
|
|
23854
24382
|
// ../../core/packages/runner-core/src/inventory/auto-bind.ts
|
|
23855
|
-
import { readFile as
|
|
24383
|
+
import { readFile as readFile10, stat as stat11 } from "node:fs/promises";
|
|
23856
24384
|
var AutoBinder = class {
|
|
23857
24385
|
constructor(options) {
|
|
23858
24386
|
this.options = options;
|
|
@@ -23927,7 +24455,7 @@ var AutoBinder = class {
|
|
|
23927
24455
|
if (this.options.repositoriesPath === void 0) return [];
|
|
23928
24456
|
let stats;
|
|
23929
24457
|
try {
|
|
23930
|
-
stats = await
|
|
24458
|
+
stats = await stat11(this.options.repositoriesPath);
|
|
23931
24459
|
} catch (error) {
|
|
23932
24460
|
if (errnoOf(error) === "ENOENT") {
|
|
23933
24461
|
this.cache = null;
|
|
@@ -23943,7 +24471,7 @@ var AutoBinder = class {
|
|
|
23943
24471
|
}
|
|
23944
24472
|
let parsed;
|
|
23945
24473
|
try {
|
|
23946
|
-
parsed = JSON.parse(await
|
|
24474
|
+
parsed = JSON.parse(await readFile10(this.options.repositoriesPath, "utf8"));
|
|
23947
24475
|
} catch {
|
|
23948
24476
|
this.options.logger.warn("runner repositories file ignored", { reason: "malformed_json" });
|
|
23949
24477
|
this.cache = { mtimeMs: stats.mtimeMs, size: stats.size, repositories: this.lastValid };
|
|
@@ -23974,9 +24502,9 @@ var AutoBinder = class {
|
|
|
23974
24502
|
|
|
23975
24503
|
// ../../core/packages/runner-core/src/inventory/autonomy.ts
|
|
23976
24504
|
import { createHash as createHash5 } from "node:crypto";
|
|
23977
|
-
import { mkdirSync as mkdirSync2, readFileSync as
|
|
23978
|
-
import { join as join19, dirname as
|
|
23979
|
-
import { randomUUID as
|
|
24505
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
24506
|
+
import { join as join19, dirname as dirname7 } from "node:path";
|
|
24507
|
+
import { randomUUID as randomUUID8 } from "node:crypto";
|
|
23980
24508
|
var TRANSIENT_REASONS = /* @__PURE__ */ new Set(["agent_error", "probe_timeout", "probe_unavailable"]);
|
|
23981
24509
|
var REASON_PATTERN = /^[a-z][a-z0-9_]{2,63}$/;
|
|
23982
24510
|
var PROBE_PROMPT = "Create a file named probe.txt containing exactly the text probe-ok in the current directory, then commit it with the message probe. Do not read or change anything else.";
|
|
@@ -23999,7 +24527,7 @@ function policyOf(harness) {
|
|
|
23999
24527
|
function readCache(cachePath, logger) {
|
|
24000
24528
|
let raw;
|
|
24001
24529
|
try {
|
|
24002
|
-
raw =
|
|
24530
|
+
raw = readFileSync5(cachePath, "utf8");
|
|
24003
24531
|
} catch (error) {
|
|
24004
24532
|
const code = error.code;
|
|
24005
24533
|
if (code !== void 0 && code !== "ENOENT") logger.warn("inventory.autonomy_cache_unreadable", { code });
|
|
@@ -24030,8 +24558,8 @@ function readCache(cachePath, logger) {
|
|
|
24030
24558
|
}
|
|
24031
24559
|
}
|
|
24032
24560
|
function writeCache(cachePath, cache) {
|
|
24033
|
-
const tmp = `${cachePath}.${
|
|
24034
|
-
mkdirSync2(
|
|
24561
|
+
const tmp = `${cachePath}.${randomUUID8()}.tmp`;
|
|
24562
|
+
mkdirSync2(dirname7(cachePath), { recursive: true });
|
|
24035
24563
|
writeFileSync2(tmp, `${JSON.stringify(cache)}
|
|
24036
24564
|
`, { mode: 384 });
|
|
24037
24565
|
renameSync(tmp, cachePath);
|
|
@@ -24088,7 +24616,7 @@ function autonomyProbesOf(deps) {
|
|
|
24088
24616
|
try {
|
|
24089
24617
|
const adapter = adapters.get(harness.id);
|
|
24090
24618
|
if (adapter?.autonomyCheck === void 0) return;
|
|
24091
|
-
const sandbox = join19(probeRoot, `${sandboxNameOf(harness.id)}-${
|
|
24619
|
+
const sandbox = join19(probeRoot, `${sandboxNameOf(harness.id)}-${randomUUID8()}`);
|
|
24092
24620
|
try {
|
|
24093
24621
|
mkdirSync2(sandbox, { recursive: true, mode: 448 });
|
|
24094
24622
|
mkdirSync2(join19(sandbox, ".git", "info"), { recursive: true });
|
|
@@ -24118,7 +24646,7 @@ function autonomyProbesOf(deps) {
|
|
|
24118
24646
|
verdict = verdictOf(outcome, () => {
|
|
24119
24647
|
let probeText;
|
|
24120
24648
|
try {
|
|
24121
|
-
probeText =
|
|
24649
|
+
probeText = readFileSync5(join19(sandbox, "probe.txt"), "utf8");
|
|
24122
24650
|
} catch {
|
|
24123
24651
|
probeText = void 0;
|
|
24124
24652
|
}
|
|
@@ -24217,6 +24745,395 @@ function autonomyProbesOf(deps) {
|
|
|
24217
24745
|
};
|
|
24218
24746
|
}
|
|
24219
24747
|
|
|
24748
|
+
// ../../core/packages/runner-core/src/reporter/host.ts
|
|
24749
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
24750
|
+
import { join as join20 } from "node:path";
|
|
24751
|
+
function reporterHostDataDir(instanceDataDir, entry) {
|
|
24752
|
+
const identity = `${entry.package}@${entry.version}#${entry.subscription}`;
|
|
24753
|
+
const suffix = createHash6("sha256").update(identity).digest("hex").slice(0, 16);
|
|
24754
|
+
const slug = entry.package.replace(/^@/, "").replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 40);
|
|
24755
|
+
return join20(instanceDataDir, "plugin-host", `reporter-${slug || "package"}-${suffix}`);
|
|
24756
|
+
}
|
|
24757
|
+
function createReporterHost(entry, opts) {
|
|
24758
|
+
const manager = new PluginHostManager(
|
|
24759
|
+
{
|
|
24760
|
+
package: entry.package,
|
|
24761
|
+
version: entry.version,
|
|
24762
|
+
kind: "reporter",
|
|
24763
|
+
id: entry.reporterId,
|
|
24764
|
+
dir: entry.dir,
|
|
24765
|
+
options: entry.options,
|
|
24766
|
+
envNames: entry.envNames,
|
|
24767
|
+
secrets: entry.secrets,
|
|
24768
|
+
subscription: entry.subscription,
|
|
24769
|
+
dataDir: reporterHostDataDir(opts.instanceDataDir, entry)
|
|
24770
|
+
},
|
|
24771
|
+
{ baseEnv: opts.baseEnv, ...opts.hostOptions },
|
|
24772
|
+
opts.logger
|
|
24773
|
+
);
|
|
24774
|
+
return {
|
|
24775
|
+
probe: (timeoutMs) => manager.call("probe", {}, timeoutMs),
|
|
24776
|
+
dispose: () => manager.dispose()
|
|
24777
|
+
};
|
|
24778
|
+
}
|
|
24779
|
+
|
|
24780
|
+
// ../../core/packages/runner-core/src/reporter/resolve.ts
|
|
24781
|
+
var import_semver2 = __toESM(require_semver2(), 1);
|
|
24782
|
+
import { basename as basename13 } from "node:path";
|
|
24783
|
+
function reporterRefOf(pkg, version, reporterId) {
|
|
24784
|
+
return version === void 0 ? `${pkg}#${reporterId}` : `${pkg}@${version}#${reporterId}`;
|
|
24785
|
+
}
|
|
24786
|
+
function contributionIdOf(config) {
|
|
24787
|
+
return config.reporter ?? config.subscription;
|
|
24788
|
+
}
|
|
24789
|
+
function dirVersionOf(dir) {
|
|
24790
|
+
return (0, import_semver2.valid)(basename13(dir)) ?? void 0;
|
|
24791
|
+
}
|
|
24792
|
+
function validateOptionsAgainstSchema(options, schema) {
|
|
24793
|
+
if (schema === void 0) return { ok: true };
|
|
24794
|
+
const props = schema.properties ?? {};
|
|
24795
|
+
if (schema.additionalProperties === false) {
|
|
24796
|
+
for (const key of Object.keys(options)) {
|
|
24797
|
+
if (!(key in props)) return { ok: false, detail: `options.${key}: unknown field` };
|
|
24798
|
+
}
|
|
24799
|
+
}
|
|
24800
|
+
for (const key of schema.required ?? []) {
|
|
24801
|
+
if (!(key in options)) return { ok: false, detail: `options.${key}: required` };
|
|
24802
|
+
}
|
|
24803
|
+
for (const [key, raw] of Object.entries(options)) {
|
|
24804
|
+
const prop = props[key];
|
|
24805
|
+
if (prop === null || typeof prop !== "object") continue;
|
|
24806
|
+
const expected = prop.type;
|
|
24807
|
+
if (typeof expected !== "string") continue;
|
|
24808
|
+
const actual = Array.isArray(raw) ? "array" : raw === null ? "null" : typeof raw;
|
|
24809
|
+
const match = expected === "integer" ? typeof raw === "number" && Number.isInteger(raw) : actual === expected;
|
|
24810
|
+
if (!match) return { ok: false, detail: `options.${key}: expected ${expected}` };
|
|
24811
|
+
}
|
|
24812
|
+
return { ok: true };
|
|
24813
|
+
}
|
|
24814
|
+
function resolveReporters(opts) {
|
|
24815
|
+
if (opts.config.length === 0) return { entries: [], failed: [] };
|
|
24816
|
+
const installed = opts.pluginsRoot !== void 0 && opts.pluginsRoot !== "" ? scanInstalledPlugins(opts.pluginsRoot) : [];
|
|
24817
|
+
const entries = [];
|
|
24818
|
+
const failed = [];
|
|
24819
|
+
for (const config of opts.config) {
|
|
24820
|
+
const result = resolveOne(config, installed, opts);
|
|
24821
|
+
if ("entry" in result) entries.push(result.entry);
|
|
24822
|
+
else failed.push(result.failed);
|
|
24823
|
+
}
|
|
24824
|
+
return { entries, failed };
|
|
24825
|
+
}
|
|
24826
|
+
function unavailableFailure(config, installed, opts) {
|
|
24827
|
+
const broken = installed.find((candidate) => "error" in candidate && candidate.package === config.package);
|
|
24828
|
+
if (broken === void 0 || !("error" in broken)) {
|
|
24829
|
+
return { subscription: config.subscription, reporter: reporterRefOf(config.package, void 0, contributionIdOf(config)), status: { failed: "not_installed" } };
|
|
24830
|
+
}
|
|
24831
|
+
const reason = broken.error.includes("apiVersion") ? "incompatible_api" : "load_failed";
|
|
24832
|
+
opts.logger.warn("reporter package unreadable", { subscription: config.subscription, package: config.package, reason });
|
|
24833
|
+
return {
|
|
24834
|
+
subscription: config.subscription,
|
|
24835
|
+
reporter: reporterRefOf(config.package, dirVersionOf(broken.dir), contributionIdOf(config)),
|
|
24836
|
+
status: { failed: reason }
|
|
24837
|
+
};
|
|
24838
|
+
}
|
|
24839
|
+
function reporterContribution(config, present) {
|
|
24840
|
+
const reporters = present.manifest.contributions.filter((candidate) => candidate.kind === "reporter");
|
|
24841
|
+
if (config.reporter !== void 0) return reporters.find((candidate) => candidate.id === config.reporter);
|
|
24842
|
+
return reporters.length === 1 ? reporters[0] : void 0;
|
|
24843
|
+
}
|
|
24844
|
+
function resolveOne(config, installed, opts) {
|
|
24845
|
+
const present = installed.find((candidate) => "package" in candidate && "manifest" in candidate && candidate.package === config.package);
|
|
24846
|
+
if (present === void 0) return { failed: unavailableFailure(config, installed, opts) };
|
|
24847
|
+
const contribution = reporterContribution(config, present);
|
|
24848
|
+
const ref = (id) => reporterRefOf(config.package, present.version, id);
|
|
24849
|
+
if (contribution === void 0) {
|
|
24850
|
+
return { failed: { subscription: config.subscription, reporter: ref(contributionIdOf(config)), status: { failed: "load_failed" } } };
|
|
24851
|
+
}
|
|
24852
|
+
const options = validateOptionsAgainstSchema(config.options, contribution.optionsSchema);
|
|
24853
|
+
if (!options.ok) {
|
|
24854
|
+
opts.logger.warn("reporter options rejected", { subscription: config.subscription, package: config.package, id: contribution.id, reason: "invalid_options" });
|
|
24855
|
+
return { failed: { subscription: config.subscription, reporter: ref(contribution.id), status: { failed: "invalid_options" } } };
|
|
24856
|
+
}
|
|
24857
|
+
const missingEnv = config.env.filter((name) => opts.baseEnv[name] === void 0);
|
|
24858
|
+
if (missingEnv.length > 0) {
|
|
24859
|
+
opts.logger.warn("reporter env missing", { subscription: config.subscription, package: config.package, id: contribution.id, names: missingEnv.join(",") });
|
|
24860
|
+
return { failed: { subscription: config.subscription, reporter: ref(contribution.id), status: { failed: "missing_env" } } };
|
|
24861
|
+
}
|
|
24862
|
+
return {
|
|
24863
|
+
entry: {
|
|
24864
|
+
subscription: config.subscription,
|
|
24865
|
+
package: config.package,
|
|
24866
|
+
version: present.version,
|
|
24867
|
+
reporterId: contribution.id,
|
|
24868
|
+
dir: present.dir,
|
|
24869
|
+
options: config.options,
|
|
24870
|
+
envNames: config.env,
|
|
24871
|
+
secrets: contribution.secrets ?? [],
|
|
24872
|
+
intervalMinutes: config.intervalMinutes,
|
|
24873
|
+
timeoutSeconds: config.timeoutSeconds
|
|
24874
|
+
}
|
|
24875
|
+
};
|
|
24876
|
+
}
|
|
24877
|
+
|
|
24878
|
+
// ../../core/packages/runner-core/src/reporter/fingerprint.ts
|
|
24879
|
+
import { createHmac } from "node:crypto";
|
|
24880
|
+
function accountFingerprint(salt, accountId) {
|
|
24881
|
+
return createHmac("sha256", salt).update(accountId).digest("hex");
|
|
24882
|
+
}
|
|
24883
|
+
function fingerprintOf2(report, salt) {
|
|
24884
|
+
if (salt === void 0 || report.accountId === void 0) return void 0;
|
|
24885
|
+
return accountFingerprint(salt, report.accountId);
|
|
24886
|
+
}
|
|
24887
|
+
|
|
24888
|
+
// ../../core/packages/runner-core/src/reporter/report.ts
|
|
24889
|
+
var RFC33393 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
24890
|
+
function isPlainObject6(value) {
|
|
24891
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24892
|
+
}
|
|
24893
|
+
function invalid(detail) {
|
|
24894
|
+
return { ok: false, reason: "invalid_report", detail };
|
|
24895
|
+
}
|
|
24896
|
+
function validateWindow(raw, index, seen) {
|
|
24897
|
+
const at = `report.windows[${index}]`;
|
|
24898
|
+
if (!isPlainObject6(raw)) return { ok: false, detail: `${at}: expected an object` };
|
|
24899
|
+
for (const key of Object.keys(raw)) {
|
|
24900
|
+
if (!["id", "usedPercent", "resetsAt", "durationSec", "label"].includes(key)) {
|
|
24901
|
+
return { ok: false, detail: `${at}.${key}: unknown field` };
|
|
24902
|
+
}
|
|
24903
|
+
}
|
|
24904
|
+
if (typeof raw.id !== "string" || raw.id === "") return { ok: false, detail: `${at}.id: expected a non-empty string` };
|
|
24905
|
+
if (seen.has(raw.id)) return { ok: false, detail: `${at}.id: duplicate id` };
|
|
24906
|
+
seen.add(raw.id);
|
|
24907
|
+
if (typeof raw.usedPercent !== "number" || !Number.isFinite(raw.usedPercent) || raw.usedPercent < 0 || raw.usedPercent > 100) {
|
|
24908
|
+
return { ok: false, detail: `${at}.usedPercent: expected a finite number in 0..100` };
|
|
24909
|
+
}
|
|
24910
|
+
const window = { id: raw.id, usedPercent: raw.usedPercent };
|
|
24911
|
+
if (raw.resetsAt !== void 0) {
|
|
24912
|
+
if (typeof raw.resetsAt !== "string" || !RFC33393.test(raw.resetsAt)) return { ok: false, detail: `${at}.resetsAt: expected an RFC 3339 timestamp` };
|
|
24913
|
+
window.resetsAt = raw.resetsAt;
|
|
24914
|
+
}
|
|
24915
|
+
if (raw.durationSec !== void 0) {
|
|
24916
|
+
if (typeof raw.durationSec !== "number" || !Number.isSafeInteger(raw.durationSec) || raw.durationSec < 1) {
|
|
24917
|
+
return { ok: false, detail: `${at}.durationSec: expected a positive safe integer` };
|
|
24918
|
+
}
|
|
24919
|
+
window.durationSec = raw.durationSec;
|
|
24920
|
+
}
|
|
24921
|
+
if (raw.label !== void 0) {
|
|
24922
|
+
if (typeof raw.label !== "string" || raw.label === "") return { ok: false, detail: `${at}.label: expected a non-empty string` };
|
|
24923
|
+
window.label = raw.label;
|
|
24924
|
+
}
|
|
24925
|
+
return { ok: true, window };
|
|
24926
|
+
}
|
|
24927
|
+
function validateUsageReport(report, opts) {
|
|
24928
|
+
if (!isPlainObject6(report)) return invalid("report: expected an object");
|
|
24929
|
+
for (const key of Object.keys(report)) {
|
|
24930
|
+
if (!["windows", "observedAt", "accountId"].includes(key)) return invalid(`report.${key}: unknown field`);
|
|
24931
|
+
}
|
|
24932
|
+
if (!Array.isArray(report.windows)) return invalid("report.windows: expected an array");
|
|
24933
|
+
if (opts.apiVersion === 1 && report.windows.length === 0) return invalid("report.windows: expected a non-empty array for apiVersion 1");
|
|
24934
|
+
const windows2 = [];
|
|
24935
|
+
const seen = /* @__PURE__ */ new Set();
|
|
24936
|
+
for (const raw of report.windows) {
|
|
24937
|
+
const result = validateWindow(raw, windows2.length, seen);
|
|
24938
|
+
if (!result.ok) return invalid(result.detail);
|
|
24939
|
+
windows2.push(result.window);
|
|
24940
|
+
}
|
|
24941
|
+
const validated = { windows: windows2 };
|
|
24942
|
+
if (report.observedAt !== void 0) {
|
|
24943
|
+
if (typeof report.observedAt !== "string" || !RFC33393.test(report.observedAt)) return invalid("report.observedAt: expected an RFC 3339 timestamp");
|
|
24944
|
+
validated.observedAt = report.observedAt;
|
|
24945
|
+
}
|
|
24946
|
+
if (report.accountId !== void 0) {
|
|
24947
|
+
if (typeof report.accountId !== "string" || report.accountId === "") return invalid("report.accountId: expected a non-empty string");
|
|
24948
|
+
validated.accountId = report.accountId;
|
|
24949
|
+
}
|
|
24950
|
+
return { ok: true, report: validated };
|
|
24951
|
+
}
|
|
24952
|
+
|
|
24953
|
+
// ../../core/packages/runner-core/src/reporter/scheduler.ts
|
|
24954
|
+
var MAX_INTERVAL_MS = 60 * 6e4;
|
|
24955
|
+
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
24956
|
+
var realTimers = {
|
|
24957
|
+
setTimeout: (fn, ms) => {
|
|
24958
|
+
const handle = globalThis.setTimeout(fn, ms);
|
|
24959
|
+
handle.unref?.();
|
|
24960
|
+
return handle;
|
|
24961
|
+
},
|
|
24962
|
+
clearTimeout: (handle) => globalThis.clearTimeout(handle)
|
|
24963
|
+
};
|
|
24964
|
+
var ReporterScheduler = class {
|
|
24965
|
+
constructor(opts) {
|
|
24966
|
+
this.opts = opts;
|
|
24967
|
+
this.timers = opts.timers ?? realTimers;
|
|
24968
|
+
this.maxIntervalMs = opts.maxIntervalMs ?? MAX_INTERVAL_MS;
|
|
24969
|
+
this.states = opts.entries.map((entry) => ({
|
|
24970
|
+
entry,
|
|
24971
|
+
intervalMs: entry.intervalMinutes * 6e4,
|
|
24972
|
+
probing: false,
|
|
24973
|
+
timer: void 0,
|
|
24974
|
+
host: opts.createHost(entry),
|
|
24975
|
+
disposed: false
|
|
24976
|
+
}));
|
|
24977
|
+
}
|
|
24978
|
+
opts;
|
|
24979
|
+
states;
|
|
24980
|
+
timers;
|
|
24981
|
+
maxIntervalMs;
|
|
24982
|
+
disposed = false;
|
|
24983
|
+
started = false;
|
|
24984
|
+
/** Первый тик каждой записи — немедленно по плану §5.2. */
|
|
24985
|
+
start() {
|
|
24986
|
+
if (this.started) return;
|
|
24987
|
+
this.started = true;
|
|
24988
|
+
for (const state of this.states) this.schedule(state, 0);
|
|
24989
|
+
}
|
|
24990
|
+
/** Таймеры стоп, хосты dispose (grace 5 с у manager); идемпотентен. */
|
|
24991
|
+
async dispose() {
|
|
24992
|
+
if (this.disposed) return;
|
|
24993
|
+
this.disposed = true;
|
|
24994
|
+
for (const state of this.states) {
|
|
24995
|
+
state.disposed = true;
|
|
24996
|
+
if (state.timer !== void 0) {
|
|
24997
|
+
this.timers.clearTimeout(state.timer);
|
|
24998
|
+
state.timer = void 0;
|
|
24999
|
+
}
|
|
25000
|
+
}
|
|
25001
|
+
await Promise.all(this.states.map((state) => state.host.dispose()));
|
|
25002
|
+
}
|
|
25003
|
+
schedule(state, delayMs) {
|
|
25004
|
+
if (this.disposed || state.disposed) return;
|
|
25005
|
+
state.timer = this.timers.setTimeout(() => {
|
|
25006
|
+
state.timer = void 0;
|
|
25007
|
+
void this.tick(state);
|
|
25008
|
+
}, Math.min(Math.max(0, delayMs), MAX_TIMER_DELAY_MS));
|
|
25009
|
+
}
|
|
25010
|
+
tick(state) {
|
|
25011
|
+
if (this.disposed || state.disposed || state.probing) return;
|
|
25012
|
+
state.probing = true;
|
|
25013
|
+
void this.probeOnce(state).catch((error) => {
|
|
25014
|
+
this.opts.logger.warn("reporter probe cycle failed", {
|
|
25015
|
+
subscription: state.entry.subscription,
|
|
25016
|
+
err: error
|
|
25017
|
+
});
|
|
25018
|
+
}).finally(() => {
|
|
25019
|
+
state.probing = false;
|
|
25020
|
+
if (!this.disposed && !state.disposed) this.schedule(state, state.intervalMs);
|
|
25021
|
+
});
|
|
25022
|
+
}
|
|
25023
|
+
async probeOnce(state) {
|
|
25024
|
+
const { entry } = state;
|
|
25025
|
+
const reporter = reporterRefOf(entry.package, entry.version, entry.reporterId);
|
|
25026
|
+
let report;
|
|
25027
|
+
try {
|
|
25028
|
+
report = await state.host.probe(entry.timeoutSeconds * 1e3);
|
|
25029
|
+
} catch (error) {
|
|
25030
|
+
this.onFailure(state, error instanceof PluginHostDownError ? `host_${error.reason}` : "probe_error");
|
|
25031
|
+
return;
|
|
25032
|
+
}
|
|
25033
|
+
if (report === null) {
|
|
25034
|
+
this.setStatus(entry.subscription, "idle");
|
|
25035
|
+
return;
|
|
25036
|
+
}
|
|
25037
|
+
const validated = validateUsageReport(report, { apiVersion: 1 });
|
|
25038
|
+
if (!validated.ok) {
|
|
25039
|
+
this.onFailure(state, "invalid_report");
|
|
25040
|
+
return;
|
|
25041
|
+
}
|
|
25042
|
+
await this.recordSnapshot(state, validated.report, reporter);
|
|
25043
|
+
}
|
|
25044
|
+
async recordSnapshot(state, report, reporter) {
|
|
25045
|
+
const { entry } = state;
|
|
25046
|
+
if (await this.opts.journal.isFull()) {
|
|
25047
|
+
this.opts.logger.warn("reporter snapshot skipped: journal full", { subscription: entry.subscription, reporter });
|
|
25048
|
+
return;
|
|
25049
|
+
}
|
|
25050
|
+
const fingerprint3 = fingerprintOf2(report, this.opts.salt());
|
|
25051
|
+
const payload = {
|
|
25052
|
+
subscription: entry.subscription,
|
|
25053
|
+
observedAt: report.observedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
25054
|
+
windows: report.windows,
|
|
25055
|
+
...fingerprint3 !== void 0 ? { accountFingerprint: fingerprint3 } : {},
|
|
25056
|
+
source: { kind: "probe", reporter }
|
|
25057
|
+
};
|
|
25058
|
+
const record = { type: "limits.snapshot", payload };
|
|
25059
|
+
try {
|
|
25060
|
+
await this.opts.journal.append(record);
|
|
25061
|
+
} catch (error) {
|
|
25062
|
+
this.opts.logger.warn("reporter snapshot append failed", { subscription: entry.subscription, reporter, err: error });
|
|
25063
|
+
this.setStatus(entry.subscription, "degraded");
|
|
25064
|
+
return;
|
|
25065
|
+
}
|
|
25066
|
+
state.intervalMs = state.entry.intervalMinutes * 6e4;
|
|
25067
|
+
this.setStatus(entry.subscription, "ok");
|
|
25068
|
+
}
|
|
25069
|
+
onFailure(state, reason) {
|
|
25070
|
+
state.intervalMs = Math.min(state.intervalMs * 2, this.maxIntervalMs);
|
|
25071
|
+
this.opts.logger.warn("reporter probe failed", {
|
|
25072
|
+
subscription: state.entry.subscription,
|
|
25073
|
+
reporter: reporterRefOf(state.entry.package, state.entry.version, state.entry.reporterId),
|
|
25074
|
+
reason
|
|
25075
|
+
});
|
|
25076
|
+
this.setStatus(state.entry.subscription, "degraded");
|
|
25077
|
+
}
|
|
25078
|
+
setStatus(subscription, status) {
|
|
25079
|
+
this.opts.onStatus(subscription, status);
|
|
25080
|
+
}
|
|
25081
|
+
};
|
|
25082
|
+
|
|
25083
|
+
// ../../core/packages/runner-core/src/reporter/wiring.ts
|
|
25084
|
+
function mountReporters(opts) {
|
|
25085
|
+
const resolved = resolveReporters({
|
|
25086
|
+
config: opts.config,
|
|
25087
|
+
pluginsRoot: opts.pluginsRoot,
|
|
25088
|
+
baseEnv: opts.baseEnv,
|
|
25089
|
+
logger: opts.logger
|
|
25090
|
+
});
|
|
25091
|
+
const statuses = new Map(
|
|
25092
|
+
resolved.failed.map((failed) => [failed.subscription, failed])
|
|
25093
|
+
);
|
|
25094
|
+
const reporterSalt = { value: void 0 };
|
|
25095
|
+
let scheduler;
|
|
25096
|
+
if (resolved.entries.length > 0) {
|
|
25097
|
+
scheduler = new ReporterScheduler({
|
|
25098
|
+
entries: resolved.entries,
|
|
25099
|
+
journal: opts.journal,
|
|
25100
|
+
createHost: opts.createHost ?? ((entry) => createReporterHost(entry, {
|
|
25101
|
+
instanceDataDir: opts.instanceDataDir,
|
|
25102
|
+
baseEnv: opts.baseEnv,
|
|
25103
|
+
logger: opts.logger
|
|
25104
|
+
})),
|
|
25105
|
+
salt: () => reporterSalt.value,
|
|
25106
|
+
onStatus: (subscription, status) => {
|
|
25107
|
+
const entry = resolved.entries.find((candidate) => candidate.subscription === subscription);
|
|
25108
|
+
if (entry === void 0) return;
|
|
25109
|
+
statuses.set(subscription, {
|
|
25110
|
+
subscription,
|
|
25111
|
+
reporter: reporterRefOf(entry.package, entry.version, entry.reporterId),
|
|
25112
|
+
status
|
|
25113
|
+
});
|
|
25114
|
+
opts.onStatus?.(subscription, status);
|
|
25115
|
+
},
|
|
25116
|
+
logger: opts.logger,
|
|
25117
|
+
...opts.timers !== void 0 ? { timers: opts.timers } : {}
|
|
25118
|
+
});
|
|
25119
|
+
}
|
|
25120
|
+
return { scheduler, statuses, reporterSalt };
|
|
25121
|
+
}
|
|
25122
|
+
function setupReporters(opts) {
|
|
25123
|
+
return mountReporters({ ...opts, ...opts.refresh === void 0 ? {} : { onStatus: opts.refresh } });
|
|
25124
|
+
}
|
|
25125
|
+
function applyReporterSalt(holder, ack) {
|
|
25126
|
+
holder.value = ack.fingerprintSalt;
|
|
25127
|
+
}
|
|
25128
|
+
async function disposeReporters(scheduler, logger) {
|
|
25129
|
+
if (scheduler === void 0) return;
|
|
25130
|
+
try {
|
|
25131
|
+
await scheduler.dispose();
|
|
25132
|
+
} catch (error) {
|
|
25133
|
+
logger.warn("reporter.dispose_failed", { err: error });
|
|
25134
|
+
}
|
|
25135
|
+
}
|
|
25136
|
+
|
|
24220
25137
|
// ../../core/packages/runner-core/src/worktree/setup-teardown-wiring.ts
|
|
24221
25138
|
function wireSetupTeardown(invocations, worktrees, logger) {
|
|
24222
25139
|
return invocations.onTerminal((terminal) => {
|
|
@@ -24369,6 +25286,9 @@ async function runRunnerProcess(start, io) {
|
|
|
24369
25286
|
bindings.close();
|
|
24370
25287
|
return 1;
|
|
24371
25288
|
}
|
|
25289
|
+
for (const section of machineConfigEmptySections(machine)) {
|
|
25290
|
+
io.logger.warn("machine config section is empty", { path: config.machineConfigPath, section, reason: "empty" });
|
|
25291
|
+
}
|
|
24372
25292
|
let userPlugins;
|
|
24373
25293
|
if (config.userSettingsPath !== void 0) {
|
|
24374
25294
|
try {
|
|
@@ -24376,7 +25296,8 @@ async function runRunnerProcess(start, io) {
|
|
|
24376
25296
|
} catch (error) {
|
|
24377
25297
|
io.logger.error("user settings unreadable", {
|
|
24378
25298
|
file: config.userSettingsPath,
|
|
24379
|
-
detail: error instanceof Error ? error.message : "unknown"
|
|
25299
|
+
detail: error instanceof Error ? error.message : "unknown",
|
|
25300
|
+
err: error
|
|
24380
25301
|
});
|
|
24381
25302
|
bindings.close();
|
|
24382
25303
|
registry?.close();
|
|
@@ -24418,7 +25339,7 @@ async function runRunnerProcess(start, io) {
|
|
|
24418
25339
|
// `worktree.root`; отсутствие обоих — дефолт сервиса рядом с клоном.
|
|
24419
25340
|
...worktreeRoot !== void 0 ? { worktreeRoot } : {},
|
|
24420
25341
|
// Патчи checkpoint'ов — рядом с журналом: один каталог данных runner'а (#564).
|
|
24421
|
-
checkpointsDir:
|
|
25342
|
+
checkpointsDir: join21(dirname8(config.journalPath), "checkpoints"),
|
|
24422
25343
|
activeWorktreeInvocations: async (worktreeId) => (await invocationsRef?.snapshot() ?? { invocations: [] }).invocations.some((entry) => entry.worktreeId === worktreeId),
|
|
24423
25344
|
// Контракт .compivia (#654): валидация harness'а машины и окружение
|
|
24424
25345
|
// скрипта без секретов runner'а (deny-list по имени).
|
|
@@ -24455,18 +25376,40 @@ async function runRunnerProcess(start, io) {
|
|
|
24455
25376
|
pluginsRoot: config.pluginsRoot,
|
|
24456
25377
|
machinePlugins: machine.plugins,
|
|
24457
25378
|
userPlugins,
|
|
24458
|
-
instanceDataDir:
|
|
24459
|
-
|
|
25379
|
+
instanceDataDir: dirname8(config.journalPath),
|
|
25380
|
+
// #872: env-файл для configSource — путь #873 (envPath = $COMPIVIA_INSTANCE_DIR/env),
|
|
25381
|
+
// композитор ставит его из --agent-env; нет флага — instance-источника нет (R0 #873).
|
|
25382
|
+
...config.instanceEnvFile !== void 0 ? { instanceEnvFile: config.instanceEnvFile } : {},
|
|
25383
|
+
...config.homeDir !== void 0 ? { homeDir: config.homeDir } : {},
|
|
25384
|
+
// #873: карта экземпляра — нижний слой и для инвентаря/проб, и для хостов
|
|
25385
|
+
// плагинов (host-manager берёт envNames из baseEnv).
|
|
25386
|
+
baseEnv: { ...process.env, ...start.agentEnv ?? {} },
|
|
25387
|
+
...start.agentEnv !== void 0 ? { agentEnv: start.agentEnv } : {},
|
|
24460
25388
|
logger: io.logger
|
|
24461
25389
|
});
|
|
25390
|
+
if (start.agentEnv !== void 0) {
|
|
25391
|
+
io.logger.debug("agent env applied", { [KEY_ENV_KEY_COUNT]: Object.keys(start.agentEnv).length });
|
|
25392
|
+
}
|
|
24462
25393
|
const adapters = detectorSet.adapters;
|
|
25394
|
+
let refreshReporterInventory = () => void 0;
|
|
25395
|
+
const mountedReporters = setupReporters({
|
|
25396
|
+
config: machine.reporters ?? [],
|
|
25397
|
+
pluginsRoot: config.pluginsRoot,
|
|
25398
|
+
baseEnv: process.env,
|
|
25399
|
+
instanceDataDir: dirname8(config.journalPath),
|
|
25400
|
+
journal,
|
|
25401
|
+
logger: io.logger,
|
|
25402
|
+
refresh: () => refreshReporterInventory()
|
|
25403
|
+
});
|
|
25404
|
+
const reporters = mountedReporters.scheduler;
|
|
25405
|
+
const reporterSalt = mountedReporters.reporterSalt;
|
|
24463
25406
|
let inventoryRef;
|
|
24464
25407
|
let invocations;
|
|
24465
25408
|
const probes = autonomyProbesOf({
|
|
24466
25409
|
harnesses: machine.harnesses,
|
|
24467
25410
|
adapters,
|
|
24468
|
-
cachePath:
|
|
24469
|
-
probeRoot:
|
|
25411
|
+
cachePath: join21(dirname8(config.journalPath), "harness-autonomy.json"),
|
|
25412
|
+
probeRoot: join21(dirname8(config.journalPath), "autonomy-probe"),
|
|
24470
25413
|
runner: commandRunner,
|
|
24471
25414
|
refresh: () => refreshInventory(),
|
|
24472
25415
|
logger: io.logger,
|
|
@@ -24484,12 +25427,25 @@ async function runRunnerProcess(start, io) {
|
|
|
24484
25427
|
stallTimeoutMsByHarness: new Map(machine.harnesses.map((harness) => [harness.id, (harness.stallTimeoutMinutes ?? 20) * 6e4])),
|
|
24485
25428
|
slotsTotal: machine.slots.total,
|
|
24486
25429
|
scratchRoot: `${config.bindingsPath}.scratch`,
|
|
24487
|
-
|
|
25430
|
+
// #873: env-файл экземпляра ложится поверх PATH/HOME; специализированные
|
|
25431
|
+
// слои run.env/launch.env/identity накладываются выше в buildLaunchEnv.
|
|
25432
|
+
baseEnv: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", ...start.agentEnv ?? {} },
|
|
24488
25433
|
harnessStatus: async () => {
|
|
24489
25434
|
const snapshot = inventoryRef?.lastSnapshot();
|
|
24490
25435
|
if (snapshot === void 0 || snapshot === null) return null;
|
|
24491
25436
|
return new Map(snapshot.agents.map((agent) => [agent.id, agent.status]));
|
|
24492
25437
|
},
|
|
25438
|
+
// Вердикты автономности (#872 D6): постоянная needs_setup-причина
|
|
25439
|
+
// отклоняет agent.start, включая лестницу повторов движка. Тот же снимок
|
|
25440
|
+
// инвентаря, что и harnessStatus — без повторных проб и лишнего чтения.
|
|
25441
|
+
harnessVerdict: async () => {
|
|
25442
|
+
const snapshot = inventoryRef?.lastSnapshot();
|
|
25443
|
+
if (snapshot === void 0 || snapshot === null) return null;
|
|
25444
|
+
return new Map(snapshot.agents.map((agent) => [agent.id, {
|
|
25445
|
+
compatibility: agent.compatibility,
|
|
25446
|
+
compatibilityReason: agent.compatibilityReason
|
|
25447
|
+
}]));
|
|
25448
|
+
},
|
|
24493
25449
|
worktrees: {
|
|
24494
25450
|
resolvePath: (worktreeId) => worktrees.resolvePath(worktreeId),
|
|
24495
25451
|
checkpoint: (worktreeId, message, hint) => worktrees.checkpoint(worktreeId, message, hint),
|
|
@@ -24524,6 +25480,8 @@ async function runRunnerProcess(start, io) {
|
|
|
24524
25480
|
capabilities: runnerCapabilities(machine),
|
|
24525
25481
|
// Привязки в снимке и refresh статусов git-доступа (задача #14).
|
|
24526
25482
|
bindings: repoBindings,
|
|
25483
|
+
// Статусы репортеров (#130 §9): смена триггерит inventory.changed.
|
|
25484
|
+
reporters: () => [...mountedReporters.statuses.values()],
|
|
24527
25485
|
autoBind: autoBinder === void 0 ? void 0 : (clones) => autoBinder.run(clones),
|
|
24528
25486
|
journal,
|
|
24529
25487
|
logger: io.logger,
|
|
@@ -24591,6 +25549,7 @@ async function runRunnerProcess(start, io) {
|
|
|
24591
25549
|
void flight.catch(() => void 0);
|
|
24592
25550
|
}
|
|
24593
25551
|
};
|
|
25552
|
+
refreshReporterInventory = refreshInventory;
|
|
24594
25553
|
const testHandlers = testCommandHandlers();
|
|
24595
25554
|
const inventoryHandlers = inventoryCommandHandlers(inventory);
|
|
24596
25555
|
const agentHandlers = agentCommandHandlers(invocations, io.logger);
|
|
@@ -24648,14 +25607,15 @@ async function runRunnerProcess(start, io) {
|
|
|
24648
25607
|
});
|
|
24649
25608
|
commands.start();
|
|
24650
25609
|
io.logger.info("runner.channel_started", { channel: "commands" });
|
|
25610
|
+
const heartbeatIntervalMs = config.heartbeatIntervalMs ?? RUN_HEARTBEAT_INTERVAL_MS;
|
|
24651
25611
|
const heartbeats = new HeartbeatChannel({
|
|
24652
25612
|
connection: engineConnection,
|
|
24653
25613
|
invocations: () => invocations.heartbeatInvocations(),
|
|
24654
|
-
intervalMs:
|
|
25614
|
+
intervalMs: heartbeatIntervalMs,
|
|
24655
25615
|
logger: io.logger
|
|
24656
25616
|
});
|
|
24657
25617
|
heartbeats.start();
|
|
24658
|
-
io.logger.info("runner.channel_started", { channel: "heartbeats", interval_ms:
|
|
25618
|
+
io.logger.info("runner.channel_started", { channel: "heartbeats", interval_ms: heartbeatIntervalMs });
|
|
24659
25619
|
refreshInventory();
|
|
24660
25620
|
const inventoryTimer = setInterval(refreshInventory, config.inventoryIntervalMs);
|
|
24661
25621
|
inventoryTimer.unref();
|
|
@@ -24672,6 +25632,8 @@ async function runRunnerProcess(start, io) {
|
|
|
24672
25632
|
connectedStatus = snapshot.status;
|
|
24673
25633
|
});
|
|
24674
25634
|
engineConnection.onHelloAck((ack) => {
|
|
25635
|
+
applyReporterSalt(reporterSalt, ack);
|
|
25636
|
+
reporters?.start();
|
|
24675
25637
|
io.logger.info("connection.hello_ack", {
|
|
24676
25638
|
runner_id: connection.runnerId,
|
|
24677
25639
|
runner_version: runnerVersion,
|
|
@@ -24716,6 +25678,8 @@ async function runRunnerProcess(start, io) {
|
|
|
24716
25678
|
io.write(mode === "keep-agents" ? `stopping\u2026${count} agent(s) left running for adoption
|
|
24717
25679
|
` : `stopping\u2026${count} agent(s)
|
|
24718
25680
|
`);
|
|
25681
|
+
step = "reporters_dispose";
|
|
25682
|
+
await disposeReporters(reporters, io.logger);
|
|
24719
25683
|
step = "stop_all";
|
|
24720
25684
|
try {
|
|
24721
25685
|
await (mode === "keep-agents" ? invocations.detachAll() : invocations.stopAll());
|
|
@@ -24794,6 +25758,7 @@ var START_OPTIONS = {
|
|
|
24794
25758
|
"machine-config": { type: "string" },
|
|
24795
25759
|
repositories: { type: "string" },
|
|
24796
25760
|
"inventory-interval-ms": { type: "string" },
|
|
25761
|
+
"heartbeat-interval-ms": { type: "string" },
|
|
24797
25762
|
"user-settings": { type: "string" },
|
|
24798
25763
|
"plugins-root": { type: "string" },
|
|
24799
25764
|
"worktree-root": { type: "string" }
|
|
@@ -24832,25 +25797,25 @@ function parseRunnerStartArgs(argv, env, extraOptions) {
|
|
|
24832
25797
|
if (journalPath === void 0 || journalPath === "") {
|
|
24833
25798
|
throw new RunnerCliUsageError("--journal: runner journal file path is required (the runner syncs its journal with the engine)");
|
|
24834
25799
|
}
|
|
24835
|
-
const commandsPath = stringValue(values.commands) ??
|
|
24836
|
-
const bindingsPath = stringValue(values.bindings) ??
|
|
25800
|
+
const commandsPath = stringValue(values.commands) ?? join22(dirname9(journalPath), "runner-commands.sqlite");
|
|
25801
|
+
const bindingsPath = stringValue(values.bindings) ?? join22(dirname9(journalPath), "runner-bindings.sqlite");
|
|
24837
25802
|
const machineConfigFlag = stringValue(values["machine-config"]);
|
|
24838
|
-
const machineConfigPath = machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG ??
|
|
24839
|
-
if ((machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG) !== void 0 && !
|
|
25803
|
+
const machineConfigPath = machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG ?? join22(dirname9(journalPath), "machine.json");
|
|
25804
|
+
if ((machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG) !== void 0 && !existsSync7(machineConfigPath)) {
|
|
24840
25805
|
throw new RunnerCliUsageError(`--machine-config: file not found: ${machineConfigPath}`);
|
|
24841
25806
|
}
|
|
24842
25807
|
const repositoriesFlag = stringValue(values.repositories);
|
|
24843
25808
|
const repositoriesPath = repositoriesFlag ?? env.COMPIVIA_RUNNER_REPOSITORIES;
|
|
24844
|
-
if (repositoriesPath !== void 0 && repositoriesPath !== "" && !
|
|
25809
|
+
if (repositoriesPath !== void 0 && repositoriesPath !== "" && !existsSync7(repositoriesPath)) {
|
|
24845
25810
|
throw new RunnerCliUsageError(`--repositories: file not found: ${repositoriesPath}`);
|
|
24846
25811
|
}
|
|
24847
25812
|
const userSettingsPath = stringValue(values["user-settings"]) ?? env.COMPIVIA_RUNNER_USER_SETTINGS;
|
|
24848
|
-
if (userSettingsPath !== void 0 && !
|
|
25813
|
+
if (userSettingsPath !== void 0 && !existsSync7(userSettingsPath)) {
|
|
24849
25814
|
throw new RunnerCliUsageError(`--user-settings: file not found: ${userSettingsPath}`);
|
|
24850
25815
|
}
|
|
24851
25816
|
const pluginsRootFlag = stringValue(values["plugins-root"]) ?? env.COMPIVIA_RUNNER_PLUGINS_ROOT;
|
|
24852
|
-
const pluginsRoot = pluginsRootFlag ?? ((machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG) !== void 0 ?
|
|
24853
|
-
if (pluginsRootFlag !== void 0 && pluginsRoot !== void 0 && !
|
|
25817
|
+
const pluginsRoot = pluginsRootFlag ?? ((machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG) !== void 0 ? join22(dirname9(machineConfigPath), "plugins") : void 0);
|
|
25818
|
+
if (pluginsRootFlag !== void 0 && pluginsRoot !== void 0 && !existsSync7(pluginsRoot)) {
|
|
24854
25819
|
throw new RunnerCliUsageError(`--plugins-root: directory not found: ${pluginsRoot}`);
|
|
24855
25820
|
}
|
|
24856
25821
|
const backoff = {
|
|
@@ -24861,7 +25826,7 @@ function parseRunnerStartArgs(argv, env, extraOptions) {
|
|
|
24861
25826
|
throw new RunnerCliUsageError("--backoff-max-ms: must not be smaller than --backoff-initial-ms");
|
|
24862
25827
|
}
|
|
24863
25828
|
const worktreeRootFlag = stringValue(values["worktree-root"]) ?? env.COMPIVIA_RUNNER_WORKTREE_ROOT;
|
|
24864
|
-
if (worktreeRootFlag !== void 0 && (worktreeRootFlag === "" || !
|
|
25829
|
+
if (worktreeRootFlag !== void 0 && (worktreeRootFlag === "" || !isAbsolute10(worktreeRootFlag))) {
|
|
24865
25830
|
throw new RunnerCliUsageError("--worktree-root: expected an absolute path");
|
|
24866
25831
|
}
|
|
24867
25832
|
return {
|
|
@@ -24873,6 +25838,7 @@ function parseRunnerStartArgs(argv, env, extraOptions) {
|
|
|
24873
25838
|
machineConfigPath,
|
|
24874
25839
|
...repositoriesPath === "" ? {} : { repositoriesPath },
|
|
24875
25840
|
inventoryIntervalMs: parseMs(stringValue(values["inventory-interval-ms"]), "--inventory-interval-ms", 6e4),
|
|
25841
|
+
heartbeatIntervalMs: parseMs(stringValue(values["heartbeat-interval-ms"]), "--heartbeat-interval-ms", 15e3),
|
|
24876
25842
|
...userSettingsPath !== void 0 && userSettingsPath !== "" ? { userSettingsPath } : {},
|
|
24877
25843
|
...pluginsRoot !== void 0 && pluginsRoot !== "" ? { pluginsRoot } : {},
|
|
24878
25844
|
...worktreeRootFlag !== void 0 ? { worktreeRoot: worktreeRootFlag } : {}
|
|
@@ -24923,14 +25889,15 @@ async function runConfigCheck(argv, io, env) {
|
|
|
24923
25889
|
};
|
|
24924
25890
|
if (explicit) {
|
|
24925
25891
|
try {
|
|
24926
|
-
|
|
25892
|
+
statSync9(path);
|
|
24927
25893
|
} catch (error) {
|
|
24928
25894
|
const errno = errnoOf(error);
|
|
24929
25895
|
io.logger.warn("runner.machine_config_check_failed", { path, errno, err: error });
|
|
24930
25896
|
return fail(errno === "ENOENT" ? `file not found: ${path}` : `machine config is unreadable: ${errno}`);
|
|
24931
25897
|
}
|
|
24932
|
-
} else if (!
|
|
24933
|
-
|
|
25898
|
+
} else if (!existsSync7(path)) {
|
|
25899
|
+
const warnings = machineConfigWarningTexts(emptyMachineInventoryConfig(), path).map((entry) => entry.text);
|
|
25900
|
+
io.write(`${JSON.stringify({ ok: true, path, empty: true, permissionModes: {}, warnings })}
|
|
24934
25901
|
`);
|
|
24935
25902
|
return 0;
|
|
24936
25903
|
}
|
|
@@ -24950,7 +25917,9 @@ async function runConfigCheck(argv, io, env) {
|
|
|
24950
25917
|
cloneRoots: config.cloneRoots.length,
|
|
24951
25918
|
// Presence-флаг корня worktree'ов (#660 §4.1): значение не выводится.
|
|
24952
25919
|
worktreeRoot: config.worktree?.root !== void 0,
|
|
24953
|
-
permissionModes
|
|
25920
|
+
permissionModes,
|
|
25921
|
+
// #995: пустые секции — warnings в ok-отчёте (D9), код выхода не меняется.
|
|
25922
|
+
warnings: machineConfigWarningTexts(config, path).map((entry) => entry.text)
|
|
24954
25923
|
})}
|
|
24955
25924
|
`
|
|
24956
25925
|
);
|
|
@@ -24962,6 +25931,7 @@ async function runConfigCheck(argv, io, env) {
|
|
|
24962
25931
|
}
|
|
24963
25932
|
|
|
24964
25933
|
// src/commands.ts
|
|
25934
|
+
import { existsSync as existsSync9 } from "node:fs";
|
|
24965
25935
|
import { parseArgs as parseArgs2 } from "node:util";
|
|
24966
25936
|
|
|
24967
25937
|
// src/pairing.ts
|
|
@@ -25259,9 +26229,9 @@ async function journalHasUnconfirmedEvents(journalPath, runnerId, logger = noopL
|
|
|
25259
26229
|
|
|
25260
26230
|
// src/token-store.ts
|
|
25261
26231
|
import { randomBytes } from "node:crypto";
|
|
25262
|
-
import { lstat as lstat11, link as
|
|
25263
|
-
import { homedir as
|
|
25264
|
-
import { basename as
|
|
26232
|
+
import { lstat as lstat11, link as link3, mkdir as mkdir8, open as open7, readFile as readFile11, unlink as unlink4 } from "node:fs/promises";
|
|
26233
|
+
import { homedir as homedir4 } from "node:os";
|
|
26234
|
+
import { basename as basename14, dirname as dirname10, join as join23 } from "node:path";
|
|
25265
26235
|
var TokenStoreError = class extends Error {
|
|
25266
26236
|
constructor(message, options) {
|
|
25267
26237
|
super(message, options);
|
|
@@ -25269,8 +26239,8 @@ var TokenStoreError = class extends Error {
|
|
|
25269
26239
|
}
|
|
25270
26240
|
};
|
|
25271
26241
|
var RUNNER_ID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
25272
|
-
function defaultCredentialsPath(home =
|
|
25273
|
-
return
|
|
26242
|
+
function defaultCredentialsPath(home = homedir4()) {
|
|
26243
|
+
return join23(home, ".compivia", "runner-platform", "credentials.json");
|
|
25274
26244
|
}
|
|
25275
26245
|
async function credentialsFileExists(path) {
|
|
25276
26246
|
try {
|
|
@@ -25307,9 +26277,9 @@ async function assertPrivateDir(dir, logger = noopLogger) {
|
|
|
25307
26277
|
}
|
|
25308
26278
|
}
|
|
25309
26279
|
async function prepareCredentialsDir(path, logger = noopLogger) {
|
|
25310
|
-
const dir =
|
|
26280
|
+
const dir = dirname10(path);
|
|
25311
26281
|
try {
|
|
25312
|
-
await
|
|
26282
|
+
await mkdir8(dir, { recursive: true, mode: 448 });
|
|
25313
26283
|
await assertPrivateDir(dir, logger);
|
|
25314
26284
|
} catch (error) {
|
|
25315
26285
|
if (error instanceof TokenStoreError) throw error;
|
|
@@ -25337,8 +26307,8 @@ async function assertSafeRegularFile(path, logger = noopLogger) {
|
|
|
25337
26307
|
}
|
|
25338
26308
|
}
|
|
25339
26309
|
async function publishAtomically(path, contents, logger) {
|
|
25340
|
-
const dir =
|
|
25341
|
-
const base =
|
|
26310
|
+
const dir = dirname10(path);
|
|
26311
|
+
const base = join23(dir, `.${basename14(path)}.tmp-${randomBytes(8).toString("hex")}`);
|
|
25342
26312
|
try {
|
|
25343
26313
|
let handle;
|
|
25344
26314
|
try {
|
|
@@ -25349,7 +26319,7 @@ async function publishAtomically(path, contents, logger) {
|
|
|
25349
26319
|
await handle?.close();
|
|
25350
26320
|
}
|
|
25351
26321
|
try {
|
|
25352
|
-
await
|
|
26322
|
+
await link3(base, path);
|
|
25353
26323
|
} catch (error) {
|
|
25354
26324
|
if (error.code === "EEXIST") {
|
|
25355
26325
|
throw new TokenStoreError(`credentials file already exists: ${path}`);
|
|
@@ -25367,7 +26337,7 @@ async function publishAtomically(path, contents, logger) {
|
|
|
25367
26337
|
}
|
|
25368
26338
|
}
|
|
25369
26339
|
} finally {
|
|
25370
|
-
await
|
|
26340
|
+
await unlink4(base).catch((error) => {
|
|
25371
26341
|
logger.warn("temporary credentials file cleanup failed", {
|
|
25372
26342
|
err: error,
|
|
25373
26343
|
operation: "unlink",
|
|
@@ -25377,8 +26347,8 @@ async function publishAtomically(path, contents, logger) {
|
|
|
25377
26347
|
}
|
|
25378
26348
|
}
|
|
25379
26349
|
async function createCredentialsFile(path, value, logger = noopLogger) {
|
|
25380
|
-
const dir =
|
|
25381
|
-
await
|
|
26350
|
+
const dir = dirname10(path);
|
|
26351
|
+
await mkdir8(dir, { recursive: true, mode: 448 });
|
|
25382
26352
|
await assertPrivateDir(dir, logger);
|
|
25383
26353
|
const contents = `${JSON.stringify(value, null, 2)}
|
|
25384
26354
|
`;
|
|
@@ -25389,7 +26359,7 @@ async function createCredentialsFile(path, value, logger = noopLogger) {
|
|
|
25389
26359
|
}
|
|
25390
26360
|
async function readCredentialsFile(path, logger = noopLogger) {
|
|
25391
26361
|
await assertSafeRegularFile(path, logger);
|
|
25392
|
-
const raw = await
|
|
26362
|
+
const raw = await readFile11(path, "utf8");
|
|
25393
26363
|
let parsed;
|
|
25394
26364
|
try {
|
|
25395
26365
|
parsed = JSON.parse(raw);
|
|
@@ -25429,8 +26399,8 @@ async function readCredentialsFile(path, logger = noopLogger) {
|
|
|
25429
26399
|
}
|
|
25430
26400
|
|
|
25431
26401
|
// src/manifest.ts
|
|
25432
|
-
import { readFileSync as
|
|
25433
|
-
import { dirname as
|
|
26402
|
+
import { readFileSync as readFileSync6 } from "node:fs";
|
|
26403
|
+
import { dirname as dirname11 } from "node:path";
|
|
25434
26404
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
25435
26405
|
var ManifestError = class extends Error {
|
|
25436
26406
|
constructor(message) {
|
|
@@ -25441,7 +26411,7 @@ var ManifestError = class extends Error {
|
|
|
25441
26411
|
var MODE_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
|
|
25442
26412
|
var COMMAND_WORD_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
25443
26413
|
var MANIFEST_FIELDS = /* @__PURE__ */ new Set(["mode", "wrapperCompat", "description", "commands"]);
|
|
25444
|
-
function readOwnPackage(baseDir =
|
|
26414
|
+
function readOwnPackage(baseDir = dirname11(fileURLToPath4(import.meta.url))) {
|
|
25445
26415
|
const pkg = readJsonFile2(`${baseDir}/../package.json`);
|
|
25446
26416
|
if (pkg !== null) {
|
|
25447
26417
|
if (typeof pkg.name !== "string" || typeof pkg.version !== "string") {
|
|
@@ -25461,7 +26431,7 @@ function readOwnPackage(baseDir = dirname10(fileURLToPath4(import.meta.url))) {
|
|
|
25461
26431
|
}
|
|
25462
26432
|
function readJsonFile2(path) {
|
|
25463
26433
|
try {
|
|
25464
|
-
const parsed = JSON.parse(
|
|
26434
|
+
const parsed = JSON.parse(readFileSync6(path, "utf8"));
|
|
25465
26435
|
return typeof parsed === "object" && parsed !== null ? parsed : null;
|
|
25466
26436
|
} catch {
|
|
25467
26437
|
return null;
|
|
@@ -25537,15 +26507,15 @@ function runnerPlatformVersion() {
|
|
|
25537
26507
|
}
|
|
25538
26508
|
|
|
25539
26509
|
// src/instance.ts
|
|
25540
|
-
import { readFileSync as
|
|
25541
|
-
import { chmod as
|
|
25542
|
-
import { basename as
|
|
26510
|
+
import { readFileSync as readFileSync7 } from "node:fs";
|
|
26511
|
+
import { chmod as chmod4, mkdir as mkdir9, writeFile as writeFile5 } from "node:fs/promises";
|
|
26512
|
+
import { basename as basename15, dirname as dirname12, join as join24 } from "node:path";
|
|
25543
26513
|
var CREDENTIALS_ENV = "COMPIVIA_RUNNER_CREDENTIALS";
|
|
25544
26514
|
function resolveInstance(env, flags) {
|
|
25545
26515
|
const instanceDir = nonEmpty(env.COMPIVIA_INSTANCE_DIR) ?? null;
|
|
25546
|
-
const instanceId = nonEmpty(env.COMPIVIA_INSTANCE) ?? (instanceDir !== null ?
|
|
25547
|
-
const credentialsPath = nonEmpty(flags?.credentials) ?? nonEmpty(env[CREDENTIALS_ENV]) ?? (instanceDir !== null ?
|
|
25548
|
-
const dataDir = nonEmpty(flags?.dataDir) ?? nonEmpty(env.COMPIVIA_DATA_DIR) ?? (instanceDir !== null ?
|
|
26516
|
+
const instanceId = nonEmpty(env.COMPIVIA_INSTANCE) ?? (instanceDir !== null ? basename15(instanceDir) : null);
|
|
26517
|
+
const credentialsPath = nonEmpty(flags?.credentials) ?? nonEmpty(env[CREDENTIALS_ENV]) ?? (instanceDir !== null ? join24(instanceDir, "credentials.json") : defaultCredentialsPath());
|
|
26518
|
+
const dataDir = nonEmpty(flags?.dataDir) ?? nonEmpty(env.COMPIVIA_DATA_DIR) ?? (instanceDir !== null ? join24(instanceDir, "data") : null);
|
|
25549
26519
|
return { instanceId, instanceDir, credentialsPath, dataDir };
|
|
25550
26520
|
}
|
|
25551
26521
|
function nonEmpty(value) {
|
|
@@ -25556,17 +26526,17 @@ function resolveJournalPath(env, flags, paths) {
|
|
|
25556
26526
|
if (fromFlags !== void 0) return fromFlags;
|
|
25557
26527
|
const fromEnv = nonEmpty(env.COMPIVIA_RUNNER_JOURNAL);
|
|
25558
26528
|
if (fromEnv !== void 0) return fromEnv;
|
|
25559
|
-
if (paths.dataDir !== null) return
|
|
25560
|
-
return
|
|
26529
|
+
if (paths.dataDir !== null) return join24(paths.dataDir, "runner-journal.sqlite");
|
|
26530
|
+
return join24(dirname12(paths.credentialsPath), "runner-journal.sqlite");
|
|
25561
26531
|
}
|
|
25562
26532
|
async function ensurePrivateDir(dir) {
|
|
25563
|
-
await
|
|
25564
|
-
await
|
|
26533
|
+
await mkdir9(dir, { recursive: true, mode: 448 });
|
|
26534
|
+
await chmod4(dir, 448);
|
|
25565
26535
|
}
|
|
25566
26536
|
function readLocalJson(dataDir) {
|
|
25567
26537
|
let raw;
|
|
25568
26538
|
try {
|
|
25569
|
-
raw =
|
|
26539
|
+
raw = readFileSync7(join24(dataDir, "local.json"), "utf8");
|
|
25570
26540
|
} catch {
|
|
25571
26541
|
return null;
|
|
25572
26542
|
}
|
|
@@ -25584,8 +26554,8 @@ function readLocalJson(dataDir) {
|
|
|
25584
26554
|
return value;
|
|
25585
26555
|
}
|
|
25586
26556
|
async function writeLocalJson(dataDir, value) {
|
|
25587
|
-
await
|
|
25588
|
-
await
|
|
26557
|
+
await mkdir9(dataDir, { recursive: true });
|
|
26558
|
+
await writeFile5(join24(dataDir, "local.json"), `${JSON.stringify(value)}
|
|
25589
26559
|
`, { encoding: "utf8", mode: 384 });
|
|
25590
26560
|
}
|
|
25591
26561
|
function resolveWrapperVersion(env) {
|
|
@@ -25594,7 +26564,7 @@ function resolveWrapperVersion(env) {
|
|
|
25594
26564
|
const home = nonEmpty(env.COMPIVIA_HOME);
|
|
25595
26565
|
if (home === void 0) return void 0;
|
|
25596
26566
|
try {
|
|
25597
|
-
const raw = JSON.parse(
|
|
26567
|
+
const raw = JSON.parse(readFileSync7(join24(home, "current", "set.json"), "utf8"));
|
|
25598
26568
|
if (typeof raw !== "object" || raw === null) return void 0;
|
|
25599
26569
|
const wrapper = raw.wrapper;
|
|
25600
26570
|
if (typeof wrapper !== "object" || wrapper === null) return void 0;
|
|
@@ -25605,6 +26575,94 @@ function resolveWrapperVersion(env) {
|
|
|
25605
26575
|
}
|
|
25606
26576
|
}
|
|
25607
26577
|
|
|
26578
|
+
// src/machine-config.ts
|
|
26579
|
+
import { existsSync as existsSync8 } from "node:fs";
|
|
26580
|
+
import { mkdtemp, rm as rm2 } from "node:fs/promises";
|
|
26581
|
+
import { homedir as homedir5, tmpdir } from "node:os";
|
|
26582
|
+
import { join as join25 } from "node:path";
|
|
26583
|
+
var MACHINE_CONFIG_ENV = "COMPIVIA_RUNNER_MACHINE_CONFIG";
|
|
26584
|
+
var HOME_ENV = "COMPIVIA_HOME";
|
|
26585
|
+
function resolveHome(env) {
|
|
26586
|
+
const fromEnv = nonEmpty2(env[HOME_ENV]);
|
|
26587
|
+
return fromEnv ?? join25(homedir5(), ".compivia");
|
|
26588
|
+
}
|
|
26589
|
+
function resolveMachineConfigPath(argv, env, home) {
|
|
26590
|
+
return scanFlagValue(argv, "--machine-config") ?? nonEmpty2(env[MACHINE_CONFIG_ENV]) ?? join25(home, "machine.json");
|
|
26591
|
+
}
|
|
26592
|
+
function hasExplicitMachineConfig(argv, env) {
|
|
26593
|
+
return argv.some((token) => token === "--machine-config" || token.startsWith("--machine-config=")) || nonEmpty2(env[MACHINE_CONFIG_ENV]) !== void 0;
|
|
26594
|
+
}
|
|
26595
|
+
function defaultCloneRoots(env, home) {
|
|
26596
|
+
const instanceDir = resolveInstance(env).instanceDir;
|
|
26597
|
+
return [instanceDir !== null ? join25(instanceDir, "work") : join25(home, "clones")];
|
|
26598
|
+
}
|
|
26599
|
+
async function ensureCloudMachineConfig(options) {
|
|
26600
|
+
const logger = options.logger;
|
|
26601
|
+
const pluginsRoot = join25(options.home, "plugins");
|
|
26602
|
+
const instanceDataDir = await mkdtemp(join25(tmpdir(), "compivia-runner-bootstrap-"));
|
|
26603
|
+
logger.debug("machine config detection dir prepared", { path: instanceDataDir });
|
|
26604
|
+
try {
|
|
26605
|
+
const result = await bootstrapMachineConfig({
|
|
26606
|
+
path: options.path,
|
|
26607
|
+
cloneRoots: defaultCloneRoots(options.env, options.home),
|
|
26608
|
+
baseEnv: options.env,
|
|
26609
|
+
instanceDataDir,
|
|
26610
|
+
...existsSync8(pluginsRoot) ? { pluginsRoot } : {},
|
|
26611
|
+
logger,
|
|
26612
|
+
...options.detectorSetFactory !== void 0 ? { detectorSetFactory: options.detectorSetFactory } : {}
|
|
26613
|
+
});
|
|
26614
|
+
return { path: result.path, created: result.created, warnings: result.warnings };
|
|
26615
|
+
} finally {
|
|
26616
|
+
const removed = await rm2(instanceDataDir, { recursive: true, force: true }).then(
|
|
26617
|
+
() => true,
|
|
26618
|
+
() => false
|
|
26619
|
+
);
|
|
26620
|
+
logger.debug("machine config detection dir cleaned", { path: instanceDataDir, removed });
|
|
26621
|
+
}
|
|
26622
|
+
}
|
|
26623
|
+
async function ensureMachineConfigForCommand(options) {
|
|
26624
|
+
const home = resolveHome(options.env);
|
|
26625
|
+
const path = resolveMachineConfigPath(options.argv, options.env, home);
|
|
26626
|
+
try {
|
|
26627
|
+
const result = await ensureCloudMachineConfig({
|
|
26628
|
+
env: options.env,
|
|
26629
|
+
home,
|
|
26630
|
+
path,
|
|
26631
|
+
logger: options.logger,
|
|
26632
|
+
...options.detectorSetFactory !== void 0 ? { detectorSetFactory: options.detectorSetFactory } : {}
|
|
26633
|
+
});
|
|
26634
|
+
for (const warning of result.warnings) {
|
|
26635
|
+
options.logger.warn("machine config warning", { path: result.path, warning });
|
|
26636
|
+
}
|
|
26637
|
+
if (!existsSync8(result.path)) {
|
|
26638
|
+
options.logger.warn("machine config not written", { path: result.path, reason: "write_failed" });
|
|
26639
|
+
}
|
|
26640
|
+
return { result, failure: null };
|
|
26641
|
+
} catch (error) {
|
|
26642
|
+
options.logger.warn("machine config ensure failed", { path, reason: "bootstrap_failed", err: error });
|
|
26643
|
+
return { result: null, failure: { path, reason: "bootstrap_failed", error } };
|
|
26644
|
+
}
|
|
26645
|
+
}
|
|
26646
|
+
function machineConfigCheckEnv(argv, env) {
|
|
26647
|
+
if (argv[0] !== "config") return env;
|
|
26648
|
+
if (hasExplicitMachineConfig(argv, env)) return env;
|
|
26649
|
+
const machinePath = resolveMachineConfigPath(argv, env, resolveHome(env));
|
|
26650
|
+
if (!existsSync8(machinePath)) return env;
|
|
26651
|
+
return { ...env, [MACHINE_CONFIG_ENV]: machinePath };
|
|
26652
|
+
}
|
|
26653
|
+
function scanFlagValue(argv, flag) {
|
|
26654
|
+
let value;
|
|
26655
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
26656
|
+
const token = argv[index];
|
|
26657
|
+
if (token === flag) value = argv[index + 1];
|
|
26658
|
+
if (token?.startsWith(`${flag}=`)) value = token.slice(flag.length + 1);
|
|
26659
|
+
}
|
|
26660
|
+
return value;
|
|
26661
|
+
}
|
|
26662
|
+
function nonEmpty2(value) {
|
|
26663
|
+
return value !== void 0 && value !== "" ? value : void 0;
|
|
26664
|
+
}
|
|
26665
|
+
|
|
25608
26666
|
// src/healthz.ts
|
|
25609
26667
|
import { createServer } from "node:http";
|
|
25610
26668
|
var HealthzError = class extends Error {
|
|
@@ -25728,10 +26786,22 @@ async function resolveCloudConnection(argv, env, io) {
|
|
|
25728
26786
|
adapter: cloudAdapter(credentialsPath, journalPath, credentials.runnerId, io.logger)
|
|
25729
26787
|
};
|
|
25730
26788
|
}
|
|
25731
|
-
async function platformRunnerStart(argv, env, io) {
|
|
26789
|
+
async function platformRunnerStart(argv, env, io, options) {
|
|
25732
26790
|
const hasJournalFlag = argv.some((token) => token === "--journal" || token.startsWith("--journal="));
|
|
25733
26791
|
const journalDefault = resolveJournalPath(env, {}, resolveInstance(env, { credentials: scanFlagValue(argv, "--credentials") }));
|
|
25734
|
-
|
|
26792
|
+
let envForParse = hasJournalFlag || env.COMPIVIA_RUNNER_JOURNAL !== void 0 ? env : { ...env, COMPIVIA_RUNNER_JOURNAL: journalDefault };
|
|
26793
|
+
if (!hasExplicitMachineConfig(argv, env)) {
|
|
26794
|
+
const ensured = await ensureMachineConfigForCommand({
|
|
26795
|
+
argv,
|
|
26796
|
+
env,
|
|
26797
|
+
logger: io.logger,
|
|
26798
|
+
...options?.detectorSetFactory !== void 0 ? { detectorSetFactory: options.detectorSetFactory } : {}
|
|
26799
|
+
});
|
|
26800
|
+
const ensuredPath = ensured.result?.path;
|
|
26801
|
+
if (ensuredPath !== void 0 && existsSync9(ensuredPath)) {
|
|
26802
|
+
envForParse = { ...envForParse, COMPIVIA_RUNNER_MACHINE_CONFIG: ensuredPath };
|
|
26803
|
+
}
|
|
26804
|
+
}
|
|
25735
26805
|
const { config, values } = parseRunnerStartArgs(argv, envForParse, {
|
|
25736
26806
|
options: { credentials: { type: "string", envName: CREDENTIALS_ENV2 }, "api-port": { type: "string" } }
|
|
25737
26807
|
});
|
|
@@ -25795,20 +26865,11 @@ async function prepareInstanceServices(argv, env, apiPort, io) {
|
|
|
25795
26865
|
return null;
|
|
25796
26866
|
}
|
|
25797
26867
|
}
|
|
25798
|
-
function
|
|
25799
|
-
let value;
|
|
25800
|
-
for (let index = 0; index < argv.length; index += 1) {
|
|
25801
|
-
const token = argv[index];
|
|
25802
|
-
if (token === flag) value = argv[index + 1];
|
|
25803
|
-
if (token?.startsWith(`${flag}=`)) value = token.slice(flag.length + 1);
|
|
25804
|
-
}
|
|
25805
|
-
return value;
|
|
25806
|
-
}
|
|
25807
|
-
function pairCommand() {
|
|
26868
|
+
function pairCommand(options) {
|
|
25808
26869
|
return {
|
|
25809
26870
|
name: "pair",
|
|
25810
26871
|
run: async (argv, io) => {
|
|
25811
|
-
const args = parsePairArgs(argv, process.env);
|
|
26872
|
+
const args = parsePairArgs(argv, options?.env ?? process.env);
|
|
25812
26873
|
let enrolledOrigin;
|
|
25813
26874
|
const fail = (message, err) => {
|
|
25814
26875
|
io.logger.error(message, {
|
|
@@ -25825,7 +26886,15 @@ function pairCommand() {
|
|
|
25825
26886
|
const code = normalizePairingCode(args.rawCode);
|
|
25826
26887
|
const origin = resolveEnrollOrigin(args.rawUrl);
|
|
25827
26888
|
enrolledOrigin = origin;
|
|
25828
|
-
return await enrollAndSave(
|
|
26889
|
+
return await enrollAndSave(
|
|
26890
|
+
{ ...args, code, origin },
|
|
26891
|
+
io,
|
|
26892
|
+
fail,
|
|
26893
|
+
{
|
|
26894
|
+
...options?.env !== void 0 ? { env: options.env } : {},
|
|
26895
|
+
...options?.detectorSetFactory !== void 0 ? { detectorSetFactory: options.detectorSetFactory } : {}
|
|
26896
|
+
}
|
|
26897
|
+
);
|
|
25829
26898
|
} catch (error) {
|
|
25830
26899
|
if (error instanceof RunnerCliUsageError) throw error;
|
|
25831
26900
|
if (error instanceof PairingError || error instanceof TokenStoreError) {
|
|
@@ -25866,7 +26935,7 @@ function parsePairArgs(argv, pairEnv) {
|
|
|
25866
26935
|
instanceId: paths.instanceId
|
|
25867
26936
|
};
|
|
25868
26937
|
}
|
|
25869
|
-
async function enrollAndSave(task, io, fail) {
|
|
26938
|
+
async function enrollAndSave(task, io, fail, bootstrapOptions) {
|
|
25870
26939
|
if (task.instanceDir !== null) {
|
|
25871
26940
|
await ensurePrivateDir(task.instanceDir);
|
|
25872
26941
|
if (task.dataDir === null || task.instanceId === null) {
|
|
@@ -25915,6 +26984,24 @@ async function enrollAndSave(task, io, fail) {
|
|
|
25915
26984
|
` : `${JSON.stringify({ ok: true, runnerId, credentials: task.file })}
|
|
25916
26985
|
`
|
|
25917
26986
|
);
|
|
26987
|
+
const outcome = await ensureMachineConfigForCommand({
|
|
26988
|
+
argv: [],
|
|
26989
|
+
env: bootstrapOptions?.env ?? process.env,
|
|
26990
|
+
logger: io.logger,
|
|
26991
|
+
...bootstrapOptions?.detectorSetFactory !== void 0 ? { detectorSetFactory: bootstrapOptions.detectorSetFactory } : {}
|
|
26992
|
+
});
|
|
26993
|
+
if (outcome.result?.created) {
|
|
26994
|
+
io.logger.info("machine config created", { path: outcome.result.path });
|
|
26995
|
+
process.stderr.write(`compivia-runner-platform: machine config created at ${outcome.result.path}
|
|
26996
|
+
`);
|
|
26997
|
+
}
|
|
26998
|
+
for (const warning of outcome.result?.warnings ?? []) {
|
|
26999
|
+
process.stderr.write(`compivia-runner-platform: machine config warning: ${warning}
|
|
27000
|
+
`);
|
|
27001
|
+
}
|
|
27002
|
+
if (outcome.failure !== null) {
|
|
27003
|
+
process.stderr.write("compivia-runner-platform: machine config could not be ensured; see the log for details\n");
|
|
27004
|
+
}
|
|
25918
27005
|
return 0;
|
|
25919
27006
|
}
|
|
25920
27007
|
function parseArgsStrict2(argv) {
|
|
@@ -26003,6 +27090,12 @@ function helpText(pkg) {
|
|
|
26003
27090
|
];
|
|
26004
27091
|
const lines = [`compivia runner <command> [args]`, "", "Commands:"];
|
|
26005
27092
|
for (const entry of commands) lines.push(` ${entry.name.padEnd(23)} ${entry.description}`);
|
|
27093
|
+
lines.push(
|
|
27094
|
+
"",
|
|
27095
|
+
"Machine configuration: <COMPIVIA_HOME|~/.compivia>/machine.json",
|
|
27096
|
+
" created automatically by pair/start; override the path with --machine-config",
|
|
27097
|
+
" or COMPIVIA_RUNNER_MACHINE_CONFIG; validate it with `config check`."
|
|
27098
|
+
);
|
|
26006
27099
|
return `${lines.join("\n")}
|
|
26007
27100
|
`;
|
|
26008
27101
|
}
|
|
@@ -26014,7 +27107,7 @@ function createCliStderrLogger(env = process.env) {
|
|
|
26014
27107
|
}
|
|
26015
27108
|
|
|
26016
27109
|
// src/status.ts
|
|
26017
|
-
import { existsSync as
|
|
27110
|
+
import { existsSync as existsSync10 } from "node:fs";
|
|
26018
27111
|
import { parseArgs as parseArgs3 } from "node:util";
|
|
26019
27112
|
function formatStatusReport(report) {
|
|
26020
27113
|
return JSON.stringify(report);
|
|
@@ -26027,7 +27120,7 @@ function statusCommand() {
|
|
|
26027
27120
|
const env = process.env;
|
|
26028
27121
|
const paths = resolveCloudPaths(argv, env);
|
|
26029
27122
|
const wrapperVersion = resolveWrapperVersion(env);
|
|
26030
|
-
const paired =
|
|
27123
|
+
const paired = existsSync10(paths.credentialsPath);
|
|
26031
27124
|
let runnerId = null;
|
|
26032
27125
|
if (paired) {
|
|
26033
27126
|
try {
|
|
@@ -26084,7 +27177,7 @@ function parseStatusArgs(argv) {
|
|
|
26084
27177
|
}
|
|
26085
27178
|
|
|
26086
27179
|
// src/unpair.ts
|
|
26087
|
-
import { existsSync as
|
|
27180
|
+
import { existsSync as existsSync11, unlink as unlink5 } from "node:fs";
|
|
26088
27181
|
import { parseArgs as parseArgs4, promisify as promisify4 } from "node:util";
|
|
26089
27182
|
|
|
26090
27183
|
// src/revoke.ts
|
|
@@ -26143,7 +27236,7 @@ async function drainAndClose(response) {
|
|
|
26143
27236
|
}
|
|
26144
27237
|
|
|
26145
27238
|
// src/unpair.ts
|
|
26146
|
-
var unlinkAsync = promisify4(
|
|
27239
|
+
var unlinkAsync = promisify4(unlink5);
|
|
26147
27240
|
function unpairCommand(deps) {
|
|
26148
27241
|
const revoke = deps?.revoke ?? revokeToken;
|
|
26149
27242
|
const removeCredentials = deps?.removeCredentials ?? ((path) => unlinkAsync(path));
|
|
@@ -26152,7 +27245,7 @@ function unpairCommand(deps) {
|
|
|
26152
27245
|
run: async (argv, io) => {
|
|
26153
27246
|
const args = parseUnpairArgs(argv);
|
|
26154
27247
|
const paths = resolveCloudPaths(argv, process.env);
|
|
26155
|
-
if (!
|
|
27248
|
+
if (!existsSync11(paths.credentialsPath)) {
|
|
26156
27249
|
io.logger.error("not paired \u2014 nothing to revoke", { file: paths.credentialsPath });
|
|
26157
27250
|
return 1;
|
|
26158
27251
|
}
|
|
@@ -26215,7 +27308,7 @@ function parseUnpairArgs(argv) {
|
|
|
26215
27308
|
}
|
|
26216
27309
|
|
|
26217
27310
|
// src/verify.ts
|
|
26218
|
-
import { existsSync as
|
|
27311
|
+
import { existsSync as existsSync12 } from "node:fs";
|
|
26219
27312
|
import { parseArgs as parseArgs5 } from "node:util";
|
|
26220
27313
|
function formatVerifyReport(report) {
|
|
26221
27314
|
return JSON.stringify(report);
|
|
@@ -26237,7 +27330,7 @@ function verifyCommand(deps) {
|
|
|
26237
27330
|
wrapperVersion: wrapperVersion ?? null,
|
|
26238
27331
|
instance: paths.instanceId
|
|
26239
27332
|
};
|
|
26240
|
-
if (!
|
|
27333
|
+
if (!existsSync12(paths.credentialsPath)) {
|
|
26241
27334
|
return finish({ ...base, reason: "not_paired", runnerId: null }, args, io);
|
|
26242
27335
|
}
|
|
26243
27336
|
let credentials;
|
|
@@ -26409,11 +27502,17 @@ if (front.type === "metadata") {
|
|
|
26409
27502
|
void runnerCli({
|
|
26410
27503
|
argv,
|
|
26411
27504
|
io,
|
|
27505
|
+
// #223 C2: config check reads the existing machine-level machine.json via
|
|
27506
|
+
// an injected env (read-only, D5); other invocations keep the env.
|
|
27507
|
+
env: machineConfigCheckEnv(argv, process.env),
|
|
26412
27508
|
start: (startArgv) => {
|
|
26413
27509
|
armSignals();
|
|
26414
27510
|
return platformRunnerStart(startArgv, process.env, io);
|
|
26415
27511
|
},
|
|
26416
|
-
|
|
27512
|
+
// #223: the pair environment is threaded from the composition root the
|
|
27513
|
+
// same way the start path receives its env; the machine-config bootstrap
|
|
27514
|
+
// inside pair resolves its paths from it.
|
|
27515
|
+
extraCommands: [pairCommand({ env: process.env }), verifyCommand(), unpairCommand(), statusCommand()]
|
|
26417
27516
|
}).then(
|
|
26418
27517
|
(code) => {
|
|
26419
27518
|
logger.info("runner exited", { exit_code: code });
|