wildcrane-runner 0.6.116 → 0.6.117

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/runner.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.116 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.117 — built by runner/scripts/build.mjs. Do not edit.
2
2
  import { createRequire as __ai4kanbanRequire } from 'node:module'
3
3
  const require = __ai4kanbanRequire(import.meta.url)
4
4
  var __create = Object.create;
@@ -232,9 +232,9 @@ var require_timers = __commonJS({
232
232
  * before the specified function or code is executed.
233
233
  * @param {*} arg
234
234
  */
235
- constructor(callback2, delay4, arg) {
235
+ constructor(callback2, delay5, arg) {
236
236
  this._onTimeout = callback2;
237
- this._idleTimeout = delay4;
237
+ this._idleTimeout = delay5;
238
238
  this._timerArg = arg;
239
239
  this.refresh();
240
240
  }
@@ -279,8 +279,8 @@ var require_timers = __commonJS({
279
279
  * when the timer expires.
280
280
  * @returns {NodeJS.Timeout|FastTimer}
281
281
  */
282
- setTimeout(callback2, delay4, arg) {
283
- return delay4 <= RESOLUTION_MS ? setTimeout(callback2, delay4, arg) : new FastTimer(callback2, delay4, arg);
282
+ setTimeout(callback2, delay5, arg) {
283
+ return delay5 <= RESOLUTION_MS ? setTimeout(callback2, delay5, arg) : new FastTimer(callback2, delay5, arg);
284
284
  },
285
285
  /**
286
286
  * The clearTimeout method cancels an instantiated Timer previously created
@@ -306,8 +306,8 @@ var require_timers = __commonJS({
306
306
  * when the timer expires.
307
307
  * @returns {FastTimer}
308
308
  */
309
- setFastTimeout(callback2, delay4, arg) {
310
- return new FastTimer(callback2, delay4, arg);
309
+ setFastTimeout(callback2, delay5, arg) {
310
+ return new FastTimer(callback2, delay5, arg);
311
311
  },
312
312
  /**
313
313
  * The clearTimeout method cancels an instantiated FastTimer previously
@@ -333,8 +333,8 @@ var require_timers = __commonJS({
333
333
  * @deprecated
334
334
  * @param {number} [delay=0] The delay in milliseconds to add to the now value.
335
335
  */
336
- tick(delay4 = 0) {
337
- fastNow += delay4 - RESOLUTION_MS + 1;
336
+ tick(delay5 = 0) {
337
+ fastNow += delay5 - RESOLUTION_MS + 1;
338
338
  onTick();
339
339
  onTick();
340
340
  },
@@ -4054,8 +4054,8 @@ var require_infra = __commonJS({
4054
4054
  assert2(!invalidIsomorphicEncodeValueRegex.test(input2));
4055
4055
  return input2;
4056
4056
  }
4057
- function parseJSONFromBytes(bytes2) {
4058
- return JSON.parse(utf8DecodeBytes(bytes2));
4057
+ function parseJSONFromBytes(bytes) {
4058
+ return JSON.parse(utf8DecodeBytes(bytes));
4059
4059
  }
4060
4060
  function removeASCIIWhitespace(str5, leading = true, trailing = true) {
4061
4061
  return removeChars(str5, leading, trailing, isASCIIWhitespace);
@@ -4101,7 +4101,7 @@ var require_data_url = __commonJS({
4101
4101
  "use strict";
4102
4102
  var assert2 = __require("node:assert");
4103
4103
  var { forgivingBase64, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, isomorphicDecode, removeASCIIWhitespace, removeChars } = require_infra();
4104
- var encoder = new TextEncoder();
4104
+ var encoder3 = new TextEncoder();
4105
4105
  var HTTP_TOKEN_CODEPOINTS = /^[-!#$%&'*+.^_|~A-Za-z0-9]+$/u;
4106
4106
  var HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/u;
4107
4107
  var HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/u;
@@ -4155,8 +4155,8 @@ var require_data_url = __commonJS({
4155
4155
  return serialized;
4156
4156
  }
4157
4157
  function stringPercentDecode(input2) {
4158
- const bytes2 = encoder.encode(input2);
4159
- return percentDecode(bytes2);
4158
+ const bytes = encoder3.encode(input2);
4159
+ return percentDecode(bytes);
4160
4160
  }
4161
4161
  function isHexCharByte(byte) {
4162
4162
  return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102;
@@ -4842,10 +4842,10 @@ var require_webidl = __commonJS({
4842
4842
  if (jsArrayBuffer.detached) {
4843
4843
  return new Uint8Array(0);
4844
4844
  }
4845
- const bytes2 = new Uint8Array(length);
4845
+ const bytes = new Uint8Array(length);
4846
4846
  const view = new Uint8Array(jsArrayBuffer, offset, length);
4847
- bytes2.set(view);
4848
- return bytes2;
4847
+ bytes.set(view);
4848
+ return bytes;
4849
4849
  };
4850
4850
  webidl.converters.DOMString = function(V3, prefix, argument, flags2) {
4851
4851
  if (V3 === null && webidl.util.HasFlag(flags2, webidl.attributes.LegacyNullToEmptyString)) {
@@ -5561,19 +5561,19 @@ var require_util2 = __commonJS({
5561
5561
  }
5562
5562
  async function readAllBytes(reader, successSteps, failureSteps) {
5563
5563
  try {
5564
- const bytes2 = [];
5564
+ const bytes = [];
5565
5565
  let byteLength = 0;
5566
5566
  do {
5567
5567
  const { done, value: chunk } = await reader.read();
5568
5568
  if (done) {
5569
- successSteps(Buffer.concat(bytes2, byteLength));
5569
+ successSteps(Buffer.concat(bytes, byteLength));
5570
5570
  return;
5571
5571
  }
5572
5572
  if (!isUint8Array(chunk)) {
5573
5573
  failureSteps(new TypeError("Received non-Uint8Array chunk"));
5574
5574
  return;
5575
5575
  }
5576
- bytes2.push(chunk);
5576
+ bytes.push(chunk);
5577
5577
  byteLength += chunk.length;
5578
5578
  } while (true);
5579
5579
  } catch (e2) {
@@ -6018,7 +6018,7 @@ var require_formdata_parser = __commonJS({
6018
6018
  var assert2 = __require("node:assert");
6019
6019
  var { isomorphicDecode } = require_infra();
6020
6020
  var dd = Buffer.from("--");
6021
- var decoder = new TextDecoder();
6021
+ var decoder2 = new TextDecoder();
6022
6022
  var decoderIgnoreBOM = new TextDecoder("utf-8", { ignoreBOM: true });
6023
6023
  function isAsciiString(chars) {
6024
6024
  for (let i = 0; i < chars.length; ++i) {
@@ -6150,7 +6150,7 @@ var require_formdata_parser = __commonJS({
6150
6150
  headerValue[4] !== 56) {
6151
6151
  throw parsingError("unknown encoding, expected utf-8''");
6152
6152
  }
6153
- value = decodeURIComponent(decoder.decode(headerValue.subarray(7)));
6153
+ value = decodeURIComponent(decoder2.decode(headerValue.subarray(7)));
6154
6154
  } else if (input2[position.position] === 34) {
6155
6155
  position.position++;
6156
6156
  const quotedValue = collectASequenceOfBytes(
@@ -6163,7 +6163,7 @@ var require_formdata_parser = __commonJS({
6163
6163
  throw parsingError("Closing quote not found");
6164
6164
  }
6165
6165
  position.position++;
6166
- value = decoder.decode(quotedValue).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
6166
+ value = decoder2.decode(quotedValue).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
6167
6167
  } else {
6168
6168
  const tokenValue = collectASequenceOfBytes(
6169
6169
  (char) => isToken(char) && char !== 59,
@@ -6171,7 +6171,7 @@ var require_formdata_parser = __commonJS({
6171
6171
  input2,
6172
6172
  position
6173
6173
  );
6174
- value = decoder.decode(tokenValue);
6174
+ value = decoder2.decode(tokenValue);
6175
6175
  }
6176
6176
  return { name: attrNameStr, value, extended: isExtended };
6177
6177
  }
@@ -6532,19 +6532,19 @@ Content-Type: ${value.type || "application/octet-stream"}\r
6532
6532
  function bodyMixinMethods(instance, getInternalState) {
6533
6533
  const methods = {
6534
6534
  blob() {
6535
- return consumeBody(this, (bytes2) => {
6535
+ return consumeBody(this, (bytes) => {
6536
6536
  let mimeType = bodyMimeType(getInternalState(this));
6537
6537
  if (mimeType === null) {
6538
6538
  mimeType = "";
6539
6539
  } else if (mimeType) {
6540
6540
  mimeType = serializeAMimeType(mimeType);
6541
6541
  }
6542
- return new Blob([bytes2], { type: mimeType });
6542
+ return new Blob([bytes], { type: mimeType });
6543
6543
  }, instance, getInternalState);
6544
6544
  },
6545
6545
  arrayBuffer() {
6546
- return consumeBody(this, (bytes2) => {
6547
- return new Uint8Array(bytes2).buffer;
6546
+ return consumeBody(this, (bytes) => {
6547
+ return new Uint8Array(bytes).buffer;
6548
6548
  }, instance, getInternalState);
6549
6549
  },
6550
6550
  text() {
@@ -6580,8 +6580,8 @@ Content-Type: ${value.type || "application/octet-stream"}\r
6580
6580
  }, instance, getInternalState);
6581
6581
  },
6582
6582
  bytes() {
6583
- return consumeBody(this, (bytes2) => {
6584
- return new Uint8Array(bytes2);
6583
+ return consumeBody(this, (bytes) => {
6584
+ return new Uint8Array(bytes);
6585
6585
  }, instance, getInternalState);
6586
6586
  }
6587
6587
  };
@@ -6852,21 +6852,21 @@ var require_client_h1 = __commonJS({
6852
6852
  this.connection = "";
6853
6853
  this.maxResponseSize = client[kMaxResponseSize];
6854
6854
  }
6855
- setTimeout(delay4, type) {
6856
- if (delay4 !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
6855
+ setTimeout(delay5, type) {
6856
+ if (delay5 !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
6857
6857
  if (this.timeout) {
6858
6858
  timers.clearTimeout(this.timeout);
6859
6859
  this.timeout = null;
6860
6860
  }
6861
- if (delay4) {
6861
+ if (delay5) {
6862
6862
  if (type & USE_FAST_TIMER) {
6863
- this.timeout = timers.setFastTimeout(onParserTimeout, delay4, this.timeoutWeakRef);
6863
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay5, this.timeoutWeakRef);
6864
6864
  } else {
6865
- this.timeout = setTimeout(onParserTimeout, delay4, this.timeoutWeakRef);
6865
+ this.timeout = setTimeout(onParserTimeout, delay5, this.timeoutWeakRef);
6866
6866
  this.timeout?.unref();
6867
6867
  }
6868
6868
  }
6869
- this.timeoutValue = delay4;
6869
+ this.timeoutValue = delay5;
6870
6870
  } else if (this.timeout) {
6871
6871
  if (this.timeout.refresh) {
6872
6872
  this.timeout.refresh();
@@ -13032,7 +13032,7 @@ var require_mock_utils = __commonJS({
13032
13032
  if (mockDispatch2.data.callback) {
13033
13033
  mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
13034
13034
  }
13035
- const { data: { statusCode, data, headers, trailers, error: error62 }, delay: delay4, persist } = mockDispatch2;
13035
+ const { data: { statusCode, data, headers, trailers, error: error62 }, delay: delay5, persist } = mockDispatch2;
13036
13036
  const { timesInvoked, times } = mockDispatch2;
13037
13037
  mockDispatch2.consumed = !persist && timesInvoked >= times;
13038
13038
  mockDispatch2.pending = timesInvoked < times;
@@ -13055,11 +13055,11 @@ var require_mock_utils = __commonJS({
13055
13055
  handler.onError(err);
13056
13056
  }
13057
13057
  handler.onConnect?.(abort, null);
13058
- if (typeof delay4 === "number" && delay4 > 0) {
13058
+ if (typeof delay5 === "number" && delay5 > 0) {
13059
13059
  timer = setTimeout(() => {
13060
13060
  timer = null;
13061
13061
  handleReply(this[kDispatches]);
13062
- }, delay4);
13062
+ }, delay5);
13063
13063
  } else {
13064
13064
  handleReply(this[kDispatches]);
13065
13065
  }
@@ -13896,8 +13896,8 @@ var require_snapshot_utils = __commonJS({
13896
13896
  match: new Set(matchHeaders.map((header) => caseSensitive ? header : header.toLowerCase()))
13897
13897
  };
13898
13898
  }
13899
- var crypto17 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
13900
- var hashId = crypto17?.hash ? (value) => crypto17.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
13899
+ var crypto18 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
13900
+ var hashId = crypto18?.hash ? (value) => crypto18.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
13901
13901
  function isUndiciHeaders(headers) {
13902
13902
  return Array.isArray(headers) && (headers.length & 1) === 0;
13903
13903
  }
@@ -19950,10 +19950,10 @@ var require_response = __commonJS({
19950
19950
  if (init !== null) {
19951
19951
  init = webidl.converters.ResponseInit(init);
19952
19952
  }
19953
- const bytes2 = textEncoder.encode(
19953
+ const bytes = textEncoder.encode(
19954
19954
  serializeJavascriptValueToJSONString(data)
19955
19955
  );
19956
- const body = extractBody(bytes2);
19956
+ const body = extractBody(bytes);
19957
19957
  const responseObject = fromInnerResponse(makeResponse({}), "response");
19958
19958
  initializeResponse(responseObject, init, { body: body[0], type: "application/json" });
19959
19959
  return responseObject;
@@ -21095,10 +21095,10 @@ var require_subresource_integrity = __commonJS({
21095
21095
  var { runtimeFeatures } = require_runtime_features();
21096
21096
  var { asciiLowercase } = require_infra();
21097
21097
  var validSRIHashAlgorithmTokenSet = /* @__PURE__ */ new Map([["sha256", 0], ["sha384", 1], ["sha512", 2]]);
21098
- var crypto17;
21098
+ var crypto18;
21099
21099
  if (runtimeFeatures.has("crypto")) {
21100
- crypto17 = __require("node:crypto");
21101
- const cryptoHashes = crypto17.getHashes();
21100
+ crypto18 = __require("node:crypto");
21101
+ const cryptoHashes = crypto18.getHashes();
21102
21102
  if (cryptoHashes.length === 0) {
21103
21103
  validSRIHashAlgorithmTokenSet.clear();
21104
21104
  }
@@ -21117,7 +21117,7 @@ var require_subresource_integrity = __commonJS({
21117
21117
  )
21118
21118
  );
21119
21119
  var isValidSRIHashAlgorithm = (algorithm) => validSRIHashAlgorithmTokenSet.has(asciiLowercase(algorithm));
21120
- var bytesMatch = runtimeFeatures.has("crypto") === false || validSRIHashAlgorithmTokenSet.size === 0 ? () => true : (bytes2, metadataList) => {
21120
+ var bytesMatch = runtimeFeatures.has("crypto") === false || validSRIHashAlgorithmTokenSet.size === 0 ? () => true : (bytes, metadataList) => {
21121
21121
  const parsedMetadata = parseMetadata(metadataList);
21122
21122
  if (parsedMetadata.length === 0) {
21123
21123
  return true;
@@ -21126,7 +21126,7 @@ var require_subresource_integrity = __commonJS({
21126
21126
  for (const item of metadata) {
21127
21127
  const algorithm = item.alg;
21128
21128
  const expectedValue = item.val;
21129
- const actualValue = applyAlgorithmToBytes(algorithm, bytes2);
21129
+ const actualValue = applyAlgorithmToBytes(algorithm, bytes);
21130
21130
  if (caseSensitiveMatch(actualValue, expectedValue)) {
21131
21131
  return true;
21132
21132
  }
@@ -21185,8 +21185,8 @@ var require_subresource_integrity = __commonJS({
21185
21185
  }
21186
21186
  return result;
21187
21187
  }
21188
- var applyAlgorithmToBytes = (algorithm, bytes2) => {
21189
- return crypto17.hash(algorithm, bytes2, "base64");
21188
+ var applyAlgorithmToBytes = (algorithm, bytes) => {
21189
+ return crypto18.hash(algorithm, bytes, "base64");
21190
21190
  };
21191
21191
  function caseSensitiveMatch(actualValue, expectedValue) {
21192
21192
  let actualValueLength = actualValue.length;
@@ -21597,12 +21597,12 @@ var require_fetch = __commonJS({
21597
21597
  processBodyError(response.error);
21598
21598
  return;
21599
21599
  }
21600
- const processBody = (bytes2) => {
21601
- if (!bytesMatch(bytes2, request2.integrity)) {
21600
+ const processBody = (bytes) => {
21601
+ if (!bytesMatch(bytes, request2.integrity)) {
21602
21602
  processBodyError("integrity mismatch");
21603
21603
  return;
21604
21604
  }
21605
- response.body = safelyExtractBody(bytes2)[0];
21605
+ response.body = safelyExtractBody(bytes)[0];
21606
21606
  fetchFinale(fetchParams, response);
21607
21607
  };
21608
21608
  fullyReadBody(response.body, processBody, processBodyError);
@@ -22045,12 +22045,12 @@ var require_fetch = __commonJS({
22045
22045
  if (request2.body == null && fetchParams.processRequestEndOfBody) {
22046
22046
  queueMicrotask(() => fetchParams.processRequestEndOfBody());
22047
22047
  } else if (request2.body != null) {
22048
- const processBodyChunk = async function* (bytes2) {
22048
+ const processBodyChunk = async function* (bytes) {
22049
22049
  if (isCancelled(fetchParams)) {
22050
22050
  return;
22051
22051
  }
22052
- yield bytes2;
22053
- fetchParams.processRequestBodyChunkLength?.(bytes2.byteLength);
22052
+ yield bytes;
22053
+ fetchParams.processRequestBodyChunkLength?.(bytes.byteLength);
22054
22054
  };
22055
22055
  const processEndOfBody = () => {
22056
22056
  if (isCancelled(fetchParams)) {
@@ -22072,8 +22072,8 @@ var require_fetch = __commonJS({
22072
22072
  };
22073
22073
  requestBody = (async function* () {
22074
22074
  try {
22075
- for await (const bytes2 of request2.body.stream) {
22076
- yield* processBodyChunk(bytes2);
22075
+ for await (const bytes of request2.body.stream) {
22076
+ yield* processBodyChunk(bytes);
22077
22077
  }
22078
22078
  processEndOfBody();
22079
22079
  } catch (err) {
@@ -22121,33 +22121,33 @@ var require_fetch = __commonJS({
22121
22121
  }
22122
22122
  fetchParams.controller.resume = async () => {
22123
22123
  while (true) {
22124
- let bytes2;
22124
+ let bytes;
22125
22125
  let isFailure;
22126
22126
  try {
22127
22127
  const { done, value } = await fetchParams.controller.next();
22128
22128
  if (isAborted(fetchParams)) {
22129
22129
  break;
22130
22130
  }
22131
- bytes2 = done ? void 0 : value;
22131
+ bytes = done ? void 0 : value;
22132
22132
  } catch (err) {
22133
22133
  if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
22134
- bytes2 = void 0;
22134
+ bytes = void 0;
22135
22135
  } else {
22136
- bytes2 = err;
22136
+ bytes = err;
22137
22137
  isFailure = true;
22138
22138
  }
22139
22139
  }
22140
- if (bytes2 === void 0) {
22140
+ if (bytes === void 0) {
22141
22141
  readableStreamClose(fetchParams.controller.controller);
22142
22142
  finalizeResponse(fetchParams, response);
22143
22143
  return;
22144
22144
  }
22145
- timingInfo.decodedBodySize += bytes2?.byteLength ?? 0;
22145
+ timingInfo.decodedBodySize += bytes?.byteLength ?? 0;
22146
22146
  if (isFailure) {
22147
- fetchParams.controller.terminate(bytes2);
22147
+ fetchParams.controller.terminate(bytes);
22148
22148
  return;
22149
22149
  }
22150
- const buffer = new Uint8Array(bytes2);
22150
+ const buffer = new Uint8Array(bytes);
22151
22151
  if (buffer.byteLength) {
22152
22152
  fetchParams.controller.controller.enqueue(buffer);
22153
22153
  }
@@ -22287,9 +22287,9 @@ var require_fetch = __commonJS({
22287
22287
  if (fetchParams.controller.dump) {
22288
22288
  return;
22289
22289
  }
22290
- const bytes2 = chunk;
22291
- timingInfo.encodedBodySize += bytes2.byteLength;
22292
- return this.body.push(bytes2);
22290
+ const bytes = chunk;
22291
+ timingInfo.encodedBodySize += bytes.byteLength;
22292
+ return this.body.push(bytes);
22293
22293
  },
22294
22294
  onComplete() {
22295
22295
  if (this.abort) {
@@ -22620,9 +22620,9 @@ var require_cache3 = __commonJS({
22620
22620
  // 16.
22621
22621
  };
22622
22622
  operations.push(operation);
22623
- const bytes2 = await bodyReadPromise.promise;
22623
+ const bytes = await bodyReadPromise.promise;
22624
22624
  if (clonedResponse.body != null) {
22625
- clonedResponse.body.source = bytes2;
22625
+ clonedResponse.body.source = bytes;
22626
22626
  }
22627
22627
  const cacheJobPromise = createDeferredPromise();
22628
22628
  let errorData = null;
@@ -24174,7 +24174,7 @@ var require_connection = __commonJS({
24174
24174
  var { WebsocketFrameSend } = require_frame();
24175
24175
  var assert2 = __require("node:assert");
24176
24176
  var { runtimeFeatures } = require_runtime_features();
24177
- var crypto17 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
24177
+ var crypto18 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
24178
24178
  var warningEmitted = false;
24179
24179
  function establishWebSocketConnection(url2, protocols, client, handler, options) {
24180
24180
  const requestURL = url2;
@@ -24194,7 +24194,7 @@ var require_connection = __commonJS({
24194
24194
  const headersList = getHeadersList(new Headers2(options.headers));
24195
24195
  request2.headersList = headersList;
24196
24196
  }
24197
- const keyValue = crypto17.randomBytes(16).toString("base64");
24197
+ const keyValue = crypto18.randomBytes(16).toString("base64");
24198
24198
  request2.headersList.append("sec-websocket-key", keyValue, true);
24199
24199
  request2.headersList.append("sec-websocket-version", "13", true);
24200
24200
  for (const protocol of protocols) {
@@ -24234,7 +24234,7 @@ var require_connection = __commonJS({
24234
24234
  return;
24235
24235
  }
24236
24236
  const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
24237
- const digest2 = crypto17.hash("sha1", keyValue + uid, "base64");
24237
+ const digest2 = crypto18.hash("sha1", keyValue + uid, "base64");
24238
24238
  if (secWSAccept !== digest2) {
24239
24239
  failHandshake(handler, response, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
24240
24240
  return;
@@ -26696,7 +26696,7 @@ var require_identity = __commonJS({
26696
26696
  var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type");
26697
26697
  var isAlias = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === ALIAS;
26698
26698
  var isDocument = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === DOC;
26699
- var isMap = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === MAP;
26699
+ var isMap2 = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === MAP;
26700
26700
  var isPair = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === PAIR;
26701
26701
  var isScalar = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === SCALAR;
26702
26702
  var isSeq = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === SEQ;
@@ -26732,7 +26732,7 @@ var require_identity = __commonJS({
26732
26732
  exports.isAlias = isAlias;
26733
26733
  exports.isCollection = isCollection;
26734
26734
  exports.isDocument = isDocument;
26735
- exports.isMap = isMap;
26735
+ exports.isMap = isMap2;
26736
26736
  exports.isNode = isNode;
26737
26737
  exports.isPair = isPair;
26738
26738
  exports.isScalar = isScalar;
@@ -30844,9 +30844,9 @@ var require_resolve_flow_collection = __commonJS({
30844
30844
  var blockMsg = "Block collections are not allowed within flow collections";
30845
30845
  var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
30846
30846
  function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
30847
- const isMap = fc.start.source === "{";
30848
- const fcName = isMap ? "flow map" : "flow sequence";
30849
- const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
30847
+ const isMap2 = fc.start.source === "{";
30848
+ const fcName = isMap2 ? "flow map" : "flow sequence";
30849
+ const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
30850
30850
  const coll = new NodeClass(ctx.schema);
30851
30851
  coll.flow = true;
30852
30852
  const atRoot = ctx.atRoot;
@@ -30882,7 +30882,7 @@ var require_resolve_flow_collection = __commonJS({
30882
30882
  offset = props.end;
30883
30883
  continue;
30884
30884
  }
30885
- if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
30885
+ if (!isMap2 && ctx.options.strict && utilContainsNewline.containsNewline(key))
30886
30886
  onError(
30887
30887
  key,
30888
30888
  // checked by containsNewline()
@@ -30922,7 +30922,7 @@ var require_resolve_flow_collection = __commonJS({
30922
30922
  }
30923
30923
  }
30924
30924
  }
30925
- if (!isMap && !sep && !props.found) {
30925
+ if (!isMap2 && !sep && !props.found) {
30926
30926
  const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError);
30927
30927
  coll.items.push(valueNode);
30928
30928
  offset = valueNode.range[2];
@@ -30945,7 +30945,7 @@ var require_resolve_flow_collection = __commonJS({
30945
30945
  startOnNewline: false
30946
30946
  });
30947
30947
  if (valueProps.found) {
30948
- if (!isMap && !props.found && ctx.options.strict) {
30948
+ if (!isMap2 && !props.found && ctx.options.strict) {
30949
30949
  if (sep)
30950
30950
  for (const st2 of sep) {
30951
30951
  if (st2 === valueProps.found)
@@ -30977,7 +30977,7 @@ var require_resolve_flow_collection = __commonJS({
30977
30977
  const pair = new Pair.Pair(keyNode, valueNode);
30978
30978
  if (ctx.options.keepSourceTokens)
30979
30979
  pair.srcToken = collItem;
30980
- if (isMap) {
30980
+ if (isMap2) {
30981
30981
  const map3 = coll;
30982
30982
  if (utilMapIncludes.mapIncludes(ctx, map3.items, keyNode))
30983
30983
  onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
@@ -30993,7 +30993,7 @@ var require_resolve_flow_collection = __commonJS({
30993
30993
  offset = valueNode ? valueNode.range[2] : valueProps.end;
30994
30994
  }
30995
30995
  }
30996
- const expectedEnd = isMap ? "}" : "]";
30996
+ const expectedEnd = isMap2 ? "}" : "]";
30997
30997
  const [ce2, ...ee3] = fc.end;
30998
30998
  let cePos = offset;
30999
30999
  if (ce2?.source === expectedEnd)
@@ -34013,16 +34013,6 @@ var require_dist = __commonJS({
34013
34013
  }
34014
34014
  });
34015
34015
 
34016
- // ../cli/src/lib/shared/file-limits.ts
34017
- var BOARD_FILE_LIMIT, ASSET_FILE_LIMIT;
34018
- var init_file_limits = __esm({
34019
- "../cli/src/lib/shared/file-limits.ts"() {
34020
- "use strict";
34021
- BOARD_FILE_LIMIT = 10 * 1024 * 1024;
34022
- ASSET_FILE_LIMIT = 100 * 1024 * 1024;
34023
- }
34024
- });
34025
-
34026
34016
  // ../cli/node_modules/ajv/dist/compile/codegen/code.js
34027
34017
  var require_code = __commonJS({
34028
34018
  "../cli/node_modules/ajv/dist/compile/codegen/code.js"(exports) {
@@ -39100,8 +39090,8 @@ var require_multipleOf = __commonJS({
39100
39090
  const { gen, data, schemaCode, it: it2 } = cxt;
39101
39091
  const prec = it2.opts.multipleOfPrecision;
39102
39092
  const res = gen.let("res");
39103
- const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
39104
- cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
39093
+ const invalid2 = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
39094
+ cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid2}))`);
39105
39095
  }
39106
39096
  };
39107
39097
  exports.default = def;
@@ -40928,6 +40918,16 @@ var require_ajv = __commonJS({
40928
40918
  }
40929
40919
  });
40930
40920
 
40921
+ // ../cli/src/lib/shared/file-limits.ts
40922
+ var BOARD_FILE_LIMIT, ASSET_FILE_LIMIT;
40923
+ var init_file_limits = __esm({
40924
+ "../cli/src/lib/shared/file-limits.ts"() {
40925
+ "use strict";
40926
+ BOARD_FILE_LIMIT = 10 * 1024 * 1024;
40927
+ ASSET_FILE_LIMIT = 100 * 1024 * 1024;
40928
+ }
40929
+ });
40930
+
40931
40931
  // ../cli/src/lib/dress-page.ts
40932
40932
  import fs43 from "node:fs";
40933
40933
  import path45 from "node:path";
@@ -43201,9 +43201,9 @@ var require_react_dom_server_legacy_node_production = __commonJS({
43201
43201
  var isArrayImpl = Array.isArray;
43202
43202
  function murmurhash3_32_gc(key, seed) {
43203
43203
  var remainder = key.length & 3;
43204
- var bytes2 = key.length - remainder;
43204
+ var bytes = key.length - remainder;
43205
43205
  var h1 = seed;
43206
- for (seed = 0; seed < bytes2; ) {
43206
+ for (seed = 0; seed < bytes; ) {
43207
43207
  var k1 = key.charCodeAt(seed) & 255 | (key.charCodeAt(++seed) & 255) << 8 | (key.charCodeAt(++seed) & 255) << 16 | (key.charCodeAt(++seed) & 255) << 24;
43208
43208
  ++seed;
43209
43209
  k1 = 3432918353 * (k1 & 65535) + ((3432918353 * (k1 >>> 16) & 65535) << 16) & 4294967295;
@@ -48423,7 +48423,7 @@ var require_react_dom_server_node_production = __commonJS({
48423
48423
  "../cli/node_modules/react-dom/cjs/react-dom-server.node.production.js"(exports) {
48424
48424
  "use strict";
48425
48425
  var util = __require("util");
48426
- var crypto17 = __require("crypto");
48426
+ var crypto18 = __require("crypto");
48427
48427
  var async_hooks = __require("async_hooks");
48428
48428
  var React4 = require_react();
48429
48429
  var ReactDOM = require_react_dom();
@@ -51288,7 +51288,7 @@ var require_react_dom_server_node_production = __commonJS({
51288
51288
  function createPostbackActionStateKey(permalink, componentKeyPath, hookIndex) {
51289
51289
  if (void 0 !== permalink) return "p" + permalink;
51290
51290
  permalink = JSON.stringify([componentKeyPath, null, hookIndex]);
51291
- componentKeyPath = crypto17.createHash("md5");
51291
+ componentKeyPath = crypto18.createHash("md5");
51292
51292
  componentKeyPath.update(permalink);
51293
51293
  return "k" + componentKeyPath.digest("hex");
51294
51294
  }
@@ -54711,9 +54711,9 @@ var require_react_dom_server_legacy_node_development = __commonJS({
54711
54711
  }
54712
54712
  function murmurhash3_32_gc(key, seed) {
54713
54713
  var remainder = key.length & 3;
54714
- var bytes2 = key.length - remainder;
54714
+ var bytes = key.length - remainder;
54715
54715
  var h1 = seed;
54716
- for (seed = 0; seed < bytes2; ) {
54716
+ for (seed = 0; seed < bytes; ) {
54717
54717
  var k1 = key.charCodeAt(seed) & 255 | (key.charCodeAt(++seed) & 255) << 8 | (key.charCodeAt(++seed) & 255) << 16 | (key.charCodeAt(++seed) & 255) << 24;
54718
54718
  ++seed;
54719
54719
  k1 = 3432918353 * (k1 & 65535) + ((3432918353 * (k1 >>> 16) & 65535) << 16) & 4294967295;
@@ -65282,7 +65282,7 @@ var require_react_dom_server_node_development = __commonJS({
65282
65282
  function createPostbackActionStateKey(permalink, componentKeyPath, hookIndex) {
65283
65283
  if (void 0 !== permalink) return "p" + permalink;
65284
65284
  permalink = JSON.stringify([componentKeyPath, null, hookIndex]);
65285
- componentKeyPath = crypto17.createHash("md5");
65285
+ componentKeyPath = crypto18.createHash("md5");
65286
65286
  componentKeyPath.update(permalink);
65287
65287
  return "k" + componentKeyPath.digest("hex");
65288
65288
  }
@@ -68944,7 +68944,7 @@ var require_react_dom_server_node_development = __commonJS({
68944
68944
  }
68945
68945
  };
68946
68946
  }
68947
- var util = __require("util"), crypto17 = __require("crypto"), async_hooks = __require("async_hooks"), React4 = require_react(), ReactDOM = require_react_dom(), stream = __require("stream"), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_SCOPE_TYPE = /* @__PURE__ */ Symbol.for("react.scope"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_LEGACY_HIDDEN_TYPE = /* @__PURE__ */ Symbol.for("react.legacy_hidden"), REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel"), REACT_VIEW_TRANSITION_TYPE = /* @__PURE__ */ Symbol.for("react.view_transition"), REACT_RECOVERABLE_TYPE = /* @__PURE__ */ Symbol.for("react.recoverable"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, ASYNC_ITERATOR = Symbol.asyncIterator, REACT_OPTIMISTIC_KEY = /* @__PURE__ */ Symbol.for("react.optimistic_key"), isArrayImpl = Array.isArray, jsxPropsParents = /* @__PURE__ */ new WeakMap(), jsxChildrenParents = /* @__PURE__ */ new WeakMap(), CLIENT_REFERENCE_TAG = /* @__PURE__ */ Symbol.for("react.client.reference"), hasOwnProperty = Object.prototype.hasOwnProperty, supportsArrayBufferDetached = hasOwnProperty.call(
68947
+ var util = __require("util"), crypto18 = __require("crypto"), async_hooks = __require("async_hooks"), React4 = require_react(), ReactDOM = require_react_dom(), stream = __require("stream"), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_SCOPE_TYPE = /* @__PURE__ */ Symbol.for("react.scope"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_LEGACY_HIDDEN_TYPE = /* @__PURE__ */ Symbol.for("react.legacy_hidden"), REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel"), REACT_VIEW_TRANSITION_TYPE = /* @__PURE__ */ Symbol.for("react.view_transition"), REACT_RECOVERABLE_TYPE = /* @__PURE__ */ Symbol.for("react.recoverable"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, ASYNC_ITERATOR = Symbol.asyncIterator, REACT_OPTIMISTIC_KEY = /* @__PURE__ */ Symbol.for("react.optimistic_key"), isArrayImpl = Array.isArray, jsxPropsParents = /* @__PURE__ */ new WeakMap(), jsxChildrenParents = /* @__PURE__ */ new WeakMap(), CLIENT_REFERENCE_TAG = /* @__PURE__ */ Symbol.for("react.client.reference"), hasOwnProperty = Object.prototype.hasOwnProperty, supportsArrayBufferDetached = hasOwnProperty.call(
68948
68948
  ArrayBuffer.prototype,
68949
68949
  "detached"
68950
68950
  ), didWarnAboutMissingArrayBufferDetached = false, scheduleMicrotask = queueMicrotask, currentView = null, writtenBytes = 0, destinationHasCapacity$1 = true, textEncoder = new util.TextEncoder(), assign = Object.assign, VALID_ATTRIBUTE_NAME_REGEX = RegExp(
@@ -127502,8 +127502,8 @@ var require_lib = __commonJS({
127502
127502
  this.p = null;
127503
127503
  }
127504
127504
  };
127505
- Unzip2.prototype.register = function(decoder) {
127506
- this.o[decoder.compression] = decoder;
127505
+ Unzip2.prototype.register = function(decoder2) {
127506
+ this.o[decoder2.compression] = decoder2;
127507
127507
  };
127508
127508
  return Unzip2;
127509
127509
  })();
@@ -127981,14 +127981,14 @@ var require_base64 = __commonJS({
127981
127981
  lookup[chars.charCodeAt(i)] = i;
127982
127982
  }
127983
127983
  var i;
127984
- exports.encodeToBase64 = function(bytes2) {
127984
+ exports.encodeToBase64 = function(bytes) {
127985
127985
  var base643 = "";
127986
- var len = bytes2.length;
127986
+ var len = bytes.length;
127987
127987
  for (var i2 = 0; i2 < len; i2 += 3) {
127988
- base643 += chars[bytes2[i2] >> 2];
127989
- base643 += chars[(bytes2[i2] & 3) << 4 | bytes2[i2 + 1] >> 4];
127990
- base643 += chars[(bytes2[i2 + 1] & 15) << 2 | bytes2[i2 + 2] >> 6];
127991
- base643 += chars[bytes2[i2 + 2] & 63];
127988
+ base643 += chars[bytes[i2] >> 2];
127989
+ base643 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
127990
+ base643 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
127991
+ base643 += chars[bytes[i2 + 2] & 63];
127992
127992
  }
127993
127993
  if (len % 3 === 2) {
127994
127994
  base643 = base643.substring(0, base643.length - 1) + "=";
@@ -128012,17 +128012,17 @@ var require_base64 = __commonJS({
128012
128012
  bufferLength--;
128013
128013
  }
128014
128014
  }
128015
- var bytes2 = new Uint8Array(bufferLength);
128015
+ var bytes = new Uint8Array(bufferLength);
128016
128016
  for (i2 = 0; i2 < len; i2 += 4) {
128017
128017
  encoded1 = lookup[base643.charCodeAt(i2)];
128018
128018
  encoded2 = lookup[base643.charCodeAt(i2 + 1)];
128019
128019
  encoded3 = lookup[base643.charCodeAt(i2 + 2)];
128020
128020
  encoded4 = lookup[base643.charCodeAt(i2 + 3)];
128021
- bytes2[p2++] = encoded1 << 2 | encoded2 >> 4;
128022
- bytes2[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2;
128023
- bytes2[p2++] = (encoded3 & 3) << 6 | encoded4 & 63;
128021
+ bytes[p2++] = encoded1 << 2 | encoded2 >> 4;
128022
+ bytes[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2;
128023
+ bytes[p2++] = (encoded3 & 3) << 6 | encoded4 & 63;
128024
128024
  }
128025
- return bytes2;
128025
+ return bytes;
128026
128026
  };
128027
128027
  var DATA_URI_PREFIX_REGEX = /^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i;
128028
128028
  exports.decodeFromBase64DataUri = function(dataUri) {
@@ -128463,17 +128463,17 @@ var require_unicode = __commonJS({
128463
128463
  return first << 8 | second;
128464
128464
  throw new Error("Invalid byteOrder: " + byteOrder);
128465
128465
  };
128466
- var readBOM = function(bytes2) {
128467
- return hasUtf16BigEndianBOM(bytes2) ? ByteOrder.BigEndian : hasUtf16LittleEndianBOM(bytes2) ? ByteOrder.LittleEndian : ByteOrder.BigEndian;
128466
+ var readBOM = function(bytes) {
128467
+ return hasUtf16BigEndianBOM(bytes) ? ByteOrder.BigEndian : hasUtf16LittleEndianBOM(bytes) ? ByteOrder.LittleEndian : ByteOrder.BigEndian;
128468
128468
  };
128469
- var hasUtf16BigEndianBOM = function(bytes2) {
128470
- return bytes2[0] === 254 && bytes2[1] === 255;
128469
+ var hasUtf16BigEndianBOM = function(bytes) {
128470
+ return bytes[0] === 254 && bytes[1] === 255;
128471
128471
  };
128472
- var hasUtf16LittleEndianBOM = function(bytes2) {
128473
- return bytes2[0] === 255 && bytes2[1] === 254;
128472
+ var hasUtf16LittleEndianBOM = function(bytes) {
128473
+ return bytes[0] === 255 && bytes[1] === 254;
128474
128474
  };
128475
- exports.hasUtf16BOM = function(bytes2) {
128476
- return hasUtf16BigEndianBOM(bytes2) || hasUtf16LittleEndianBOM(bytes2);
128475
+ exports.hasUtf16BOM = function(bytes) {
128476
+ return hasUtf16BigEndianBOM(bytes) || hasUtf16LittleEndianBOM(bytes);
128477
128477
  };
128478
128478
  }
128479
128479
  });
@@ -128511,11 +128511,11 @@ var require_numbers = __commonJS({
128511
128511
  return Math.ceil(n.toString(2).length / 8);
128512
128512
  };
128513
128513
  exports.bytesFor = function(n) {
128514
- var bytes2 = new Uint8Array(exports.sizeInBytes(n));
128515
- for (var i = 1; i <= bytes2.length; i++) {
128516
- bytes2[i - 1] = n >> (bytes2.length - i) * 8;
128514
+ var bytes = new Uint8Array(exports.sizeInBytes(n));
128515
+ for (var i = 1; i <= bytes.length; i++) {
128516
+ bytes[i - 1] = n >> (bytes.length - i) * 8;
128517
128517
  }
128518
- return bytes2;
128518
+ return bytes;
128519
128519
  };
128520
128520
  }
128521
128521
  });
@@ -129302,16 +129302,16 @@ var require_crc32 = __commonJS({
129302
129302
  }
129303
129303
  return table;
129304
129304
  }
129305
- var crcTable = makeTable();
129306
- function crc32(crc, buf, len, pos) {
129307
- var t2 = crcTable, end2 = pos + len;
129305
+ var crcTable2 = makeTable();
129306
+ function crc322(crc, buf, len, pos) {
129307
+ var t2 = crcTable2, end2 = pos + len;
129308
129308
  crc ^= -1;
129309
129309
  for (var i = pos; i < end2; i++) {
129310
129310
  crc = crc >>> 8 ^ t2[(crc ^ buf[i]) & 255];
129311
129311
  }
129312
129312
  return crc ^ -1;
129313
129313
  }
129314
- module.exports = crc32;
129314
+ module.exports = crc322;
129315
129315
  }
129316
129316
  });
129317
129317
 
@@ -129349,7 +129349,7 @@ var require_deflate = __commonJS({
129349
129349
  var utils = require_common();
129350
129350
  var trees = require_trees();
129351
129351
  var adler32 = require_adler32();
129352
- var crc32 = require_crc32();
129352
+ var crc322 = require_crc32();
129353
129353
  var msg = require_messages();
129354
129354
  var Z_NO_FLUSH = 0;
129355
129355
  var Z_PARTIAL_FLUSH = 1;
@@ -129452,7 +129452,7 @@ var require_deflate = __commonJS({
129452
129452
  if (strm.state.wrap === 1) {
129453
129453
  strm.adler = adler32(strm.adler, buf, len, start);
129454
129454
  } else if (strm.state.wrap === 2) {
129455
- strm.adler = crc32(strm.adler, buf, len, start);
129455
+ strm.adler = crc322(strm.adler, buf, len, start);
129456
129456
  }
129457
129457
  strm.next_in += len;
129458
129458
  strm.total_in += len;
@@ -130094,7 +130094,7 @@ var require_deflate = __commonJS({
130094
130094
  put_byte(s, s.gzhead.extra.length >> 8 & 255);
130095
130095
  }
130096
130096
  if (s.gzhead.hcrc) {
130097
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
130097
+ strm.adler = crc322(strm.adler, s.pending_buf, s.pending, 0);
130098
130098
  }
130099
130099
  s.gzindex = 0;
130100
130100
  s.status = EXTRA_STATE;
@@ -130131,7 +130131,7 @@ var require_deflate = __commonJS({
130131
130131
  while (s.gzindex < (s.gzhead.extra.length & 65535)) {
130132
130132
  if (s.pending === s.pending_buf_size) {
130133
130133
  if (s.gzhead.hcrc && s.pending > beg) {
130134
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
130134
+ strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);
130135
130135
  }
130136
130136
  flush_pending(strm);
130137
130137
  beg = s.pending;
@@ -130143,7 +130143,7 @@ var require_deflate = __commonJS({
130143
130143
  s.gzindex++;
130144
130144
  }
130145
130145
  if (s.gzhead.hcrc && s.pending > beg) {
130146
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
130146
+ strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);
130147
130147
  }
130148
130148
  if (s.gzindex === s.gzhead.extra.length) {
130149
130149
  s.gzindex = 0;
@@ -130159,7 +130159,7 @@ var require_deflate = __commonJS({
130159
130159
  do {
130160
130160
  if (s.pending === s.pending_buf_size) {
130161
130161
  if (s.gzhead.hcrc && s.pending > beg) {
130162
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
130162
+ strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);
130163
130163
  }
130164
130164
  flush_pending(strm);
130165
130165
  beg = s.pending;
@@ -130176,7 +130176,7 @@ var require_deflate = __commonJS({
130176
130176
  put_byte(s, val);
130177
130177
  } while (val !== 0);
130178
130178
  if (s.gzhead.hcrc && s.pending > beg) {
130179
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
130179
+ strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);
130180
130180
  }
130181
130181
  if (val === 0) {
130182
130182
  s.gzindex = 0;
@@ -130192,7 +130192,7 @@ var require_deflate = __commonJS({
130192
130192
  do {
130193
130193
  if (s.pending === s.pending_buf_size) {
130194
130194
  if (s.gzhead.hcrc && s.pending > beg) {
130195
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
130195
+ strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);
130196
130196
  }
130197
130197
  flush_pending(strm);
130198
130198
  beg = s.pending;
@@ -130209,7 +130209,7 @@ var require_deflate = __commonJS({
130209
130209
  put_byte(s, val);
130210
130210
  } while (val !== 0);
130211
130211
  if (s.gzhead.hcrc && s.pending > beg) {
130212
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
130212
+ strm.adler = crc322(strm.adler, s.pending_buf, s.pending - beg, beg);
130213
130213
  }
130214
130214
  if (val === 0) {
130215
130215
  s.status = HCRC_STATE;
@@ -131267,7 +131267,7 @@ var require_inflate = __commonJS({
131267
131267
  "use strict";
131268
131268
  var utils = require_common();
131269
131269
  var adler32 = require_adler32();
131270
- var crc32 = require_crc32();
131270
+ var crc322 = require_crc32();
131271
131271
  var inflate_fast = require_inffast();
131272
131272
  var inflate_table = require_inftrees();
131273
131273
  var CODES = 0;
@@ -131571,7 +131571,7 @@ var require_inflate = __commonJS({
131571
131571
  state.check = 0;
131572
131572
  hbuf[0] = hold2 & 255;
131573
131573
  hbuf[1] = hold2 >>> 8 & 255;
131574
- state.check = crc32(state.check, hbuf, 2, 0);
131574
+ state.check = crc322(state.check, hbuf, 2, 0);
131575
131575
  hold2 = 0;
131576
131576
  bits = 0;
131577
131577
  state.mode = FLAGS;
@@ -131634,7 +131634,7 @@ var require_inflate = __commonJS({
131634
131634
  if (state.flags & 512) {
131635
131635
  hbuf[0] = hold2 & 255;
131636
131636
  hbuf[1] = hold2 >>> 8 & 255;
131637
- state.check = crc32(state.check, hbuf, 2, 0);
131637
+ state.check = crc322(state.check, hbuf, 2, 0);
131638
131638
  }
131639
131639
  hold2 = 0;
131640
131640
  bits = 0;
@@ -131657,7 +131657,7 @@ var require_inflate = __commonJS({
131657
131657
  hbuf[1] = hold2 >>> 8 & 255;
131658
131658
  hbuf[2] = hold2 >>> 16 & 255;
131659
131659
  hbuf[3] = hold2 >>> 24 & 255;
131660
- state.check = crc32(state.check, hbuf, 4, 0);
131660
+ state.check = crc322(state.check, hbuf, 4, 0);
131661
131661
  }
131662
131662
  hold2 = 0;
131663
131663
  bits = 0;
@@ -131679,7 +131679,7 @@ var require_inflate = __commonJS({
131679
131679
  if (state.flags & 512) {
131680
131680
  hbuf[0] = hold2 & 255;
131681
131681
  hbuf[1] = hold2 >>> 8 & 255;
131682
- state.check = crc32(state.check, hbuf, 2, 0);
131682
+ state.check = crc322(state.check, hbuf, 2, 0);
131683
131683
  }
131684
131684
  hold2 = 0;
131685
131685
  bits = 0;
@@ -131702,7 +131702,7 @@ var require_inflate = __commonJS({
131702
131702
  if (state.flags & 512) {
131703
131703
  hbuf[0] = hold2 & 255;
131704
131704
  hbuf[1] = hold2 >>> 8 & 255;
131705
- state.check = crc32(state.check, hbuf, 2, 0);
131705
+ state.check = crc322(state.check, hbuf, 2, 0);
131706
131706
  }
131707
131707
  hold2 = 0;
131708
131708
  bits = 0;
@@ -131735,7 +131735,7 @@ var require_inflate = __commonJS({
131735
131735
  );
131736
131736
  }
131737
131737
  if (state.flags & 512) {
131738
- state.check = crc32(state.check, input2, copy2, next);
131738
+ state.check = crc322(state.check, input2, copy2, next);
131739
131739
  }
131740
131740
  have -= copy2;
131741
131741
  next += copy2;
@@ -131761,7 +131761,7 @@ var require_inflate = __commonJS({
131761
131761
  }
131762
131762
  } while (len && copy2 < have);
131763
131763
  if (state.flags & 512) {
131764
- state.check = crc32(state.check, input2, copy2, next);
131764
+ state.check = crc322(state.check, input2, copy2, next);
131765
131765
  }
131766
131766
  have -= copy2;
131767
131767
  next += copy2;
@@ -131787,7 +131787,7 @@ var require_inflate = __commonJS({
131787
131787
  }
131788
131788
  } while (len && copy2 < have);
131789
131789
  if (state.flags & 512) {
131790
- state.check = crc32(state.check, input2, copy2, next);
131790
+ state.check = crc322(state.check, input2, copy2, next);
131791
131791
  }
131792
131792
  have -= copy2;
131793
131793
  next += copy2;
@@ -132362,7 +132362,7 @@ var require_inflate = __commonJS({
132362
132362
  state.total += _out;
132363
132363
  if (_out) {
132364
132364
  strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/
132365
- state.flags ? crc32(state.check, output3, _out, put - _out) : adler32(state.check, output3, _out, put - _out);
132365
+ state.flags ? crc322(state.check, output3, _out, put - _out) : adler32(state.check, output3, _out, put - _out);
132366
132366
  }
132367
132367
  _out = left;
132368
132368
  if ((state.flags ? hold2 : zswap32(hold2)) !== state.check) {
@@ -132428,7 +132428,7 @@ var require_inflate = __commonJS({
132428
132428
  state.total += _out;
132429
132429
  if (state.wrap && _out) {
132430
132430
  strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
132431
- state.flags ? crc32(state.check, output3, _out, strm.next_out - _out) : adler32(state.check, output3, _out, strm.next_out - _out);
132431
+ state.flags ? crc322(state.check, output3, _out, strm.next_out - _out) : adler32(state.check, output3, _out, strm.next_out - _out);
132432
132432
  }
132433
132433
  strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
132434
132434
  if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) {
@@ -132785,17 +132785,17 @@ var require_utils3 = __commonJS({
132785
132785
  bufferLength--;
132786
132786
  }
132787
132787
  }
132788
- var bytes2 = new Uint8Array(bufferLength);
132788
+ var bytes = new Uint8Array(bufferLength);
132789
132789
  for (i2 = 0; i2 < len; i2 += 4) {
132790
132790
  encoded1 = lookup[base643.charCodeAt(i2)];
132791
132791
  encoded2 = lookup[base643.charCodeAt(i2 + 1)];
132792
132792
  encoded3 = lookup[base643.charCodeAt(i2 + 2)];
132793
132793
  encoded4 = lookup[base643.charCodeAt(i2 + 3)];
132794
- bytes2[p2++] = encoded1 << 2 | encoded2 >> 4;
132795
- bytes2[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2;
132796
- bytes2[p2++] = (encoded3 & 3) << 6 | encoded4 & 63;
132794
+ bytes[p2++] = encoded1 << 2 | encoded2 >> 4;
132795
+ bytes[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2;
132796
+ bytes[p2++] = (encoded3 & 3) << 6 | encoded4 & 63;
132797
132797
  }
132798
- return bytes2;
132798
+ return bytes;
132799
132799
  };
132800
132800
  var arrayToString = function(array2) {
132801
132801
  var str5 = "";
@@ -133341,10 +133341,10 @@ var require_pdfDocEncoding = __commonJS({
133341
133341
  pdfDocEncodingToUnicode[159] = strings_1.toCharCode("\uFFFD");
133342
133342
  pdfDocEncodingToUnicode[160] = strings_1.toCharCode("\u20AC");
133343
133343
  pdfDocEncodingToUnicode[173] = strings_1.toCharCode("\uFFFD");
133344
- exports.pdfDocEncodingDecode = function(bytes2) {
133345
- var codePoints = new Array(bytes2.length);
133346
- for (var idx2 = 0, len = bytes2.length; idx2 < len; idx2++) {
133347
- codePoints[idx2] = pdfDocEncodingToUnicode[bytes2[idx2]];
133344
+ exports.pdfDocEncodingDecode = function(bytes) {
133345
+ var codePoints = new Array(bytes.length);
133346
+ for (var idx2 = 0, len = bytes.length; idx2 < len; idx2++) {
133347
+ codePoints[idx2] = pdfDocEncodingToUnicode[bytes[idx2]];
133348
133348
  }
133349
133349
  return String.fromCodePoint.apply(String, codePoints);
133350
133350
  };
@@ -134300,12 +134300,12 @@ var require_PDFName = __commonJS({
134300
134300
  return _this;
134301
134301
  }
134302
134302
  PDFName2.prototype.asBytes = function() {
134303
- var bytes2 = [];
134303
+ var bytes = [];
134304
134304
  var hex3 = "";
134305
134305
  var escaped = false;
134306
134306
  var pushByte = function(byte2) {
134307
134307
  if (byte2 !== void 0)
134308
- bytes2.push(byte2);
134308
+ bytes.push(byte2);
134309
134309
  escaped = false;
134310
134310
  };
134311
134311
  for (var idx = 1, len = this.encodedName.length; idx < len; idx++) {
@@ -134329,11 +134329,11 @@ var require_PDFName = __commonJS({
134329
134329
  }
134330
134330
  }
134331
134331
  }
134332
- return new Uint8Array(bytes2);
134332
+ return new Uint8Array(bytes);
134333
134333
  };
134334
134334
  PDFName2.prototype.decodeText = function() {
134335
- var bytes2 = this.asBytes();
134336
- return String.fromCharCode.apply(String, Array.from(bytes2));
134335
+ var bytes = this.asBytes();
134336
+ return String.fromCharCode.apply(String, Array.from(bytes));
134337
134337
  };
134338
134338
  PDFName2.prototype.asString = function() {
134339
134339
  return this.encodedName;
@@ -136403,22 +136403,22 @@ var require_PDFHexString = __commonJS({
136403
136403
  PDFHexString2.prototype.asBytes = function() {
136404
136404
  var hex3 = this.value + (this.value.length % 2 === 1 ? "0" : "");
136405
136405
  var hexLength = hex3.length;
136406
- var bytes2 = new Uint8Array(hex3.length / 2);
136406
+ var bytes = new Uint8Array(hex3.length / 2);
136407
136407
  var hexOffset = 0;
136408
136408
  var bytesOffset = 0;
136409
136409
  while (hexOffset < hexLength) {
136410
136410
  var byte = parseInt(hex3.substring(hexOffset, hexOffset + 2), 16);
136411
- bytes2[bytesOffset] = byte;
136411
+ bytes[bytesOffset] = byte;
136412
136412
  hexOffset += 2;
136413
136413
  bytesOffset += 1;
136414
136414
  }
136415
- return bytes2;
136415
+ return bytes;
136416
136416
  };
136417
136417
  PDFHexString2.prototype.decodeText = function() {
136418
- var bytes2 = this.asBytes();
136419
- if (utils_1.hasUtf16BOM(bytes2))
136420
- return utils_1.utf16Decode(bytes2);
136421
- return utils_1.pdfDocEncodingDecode(bytes2);
136418
+ var bytes = this.asBytes();
136419
+ if (utils_1.hasUtf16BOM(bytes))
136420
+ return utils_1.utf16Decode(bytes);
136421
+ return utils_1.pdfDocEncodingDecode(bytes);
136422
136422
  };
136423
136423
  PDFHexString2.prototype.decodeDate = function() {
136424
136424
  var text4 = this.decodeText();
@@ -136670,12 +136670,12 @@ var require_PDFString = __commonJS({
136670
136670
  return _this;
136671
136671
  }
136672
136672
  PDFString2.prototype.asBytes = function() {
136673
- var bytes2 = [];
136673
+ var bytes = [];
136674
136674
  var octal = "";
136675
136675
  var escaped = false;
136676
136676
  var pushByte = function(byte2) {
136677
136677
  if (byte2 !== void 0)
136678
- bytes2.push(byte2);
136678
+ bytes.push(byte2);
136679
136679
  escaped = false;
136680
136680
  };
136681
136681
  for (var idx = 0, len = this.value.length; idx < len; idx++) {
@@ -136719,13 +136719,13 @@ var require_PDFString = __commonJS({
136719
136719
  }
136720
136720
  }
136721
136721
  }
136722
- return new Uint8Array(bytes2);
136722
+ return new Uint8Array(bytes);
136723
136723
  };
136724
136724
  PDFString2.prototype.decodeText = function() {
136725
- var bytes2 = this.asBytes();
136726
- if (utils_1.hasUtf16BOM(bytes2))
136727
- return utils_1.utf16Decode(bytes2);
136728
- return utils_1.pdfDocEncodingDecode(bytes2);
136725
+ var bytes = this.asBytes();
136726
+ if (utils_1.hasUtf16BOM(bytes))
136727
+ return utils_1.utf16Decode(bytes);
136728
+ return utils_1.pdfDocEncodingDecode(bytes);
136729
136729
  };
136730
136730
  PDFString2.prototype.decodeDate = function() {
136731
136731
  var text4 = this.decodeText();
@@ -137074,8 +137074,8 @@ var require_CustomFontSubsetEmbedder = __commonJS({
137074
137074
  var _this = this;
137075
137075
  return new Promise(function(resolve2, reject) {
137076
137076
  var parts = [];
137077
- _this.subset.encodeStream().on("data", function(bytes2) {
137078
- return parts.push(bytes2);
137077
+ _this.subset.encodeStream().on("data", function(bytes) {
137078
+ return parts.push(bytes);
137079
137079
  }).on("end", function() {
137080
137080
  return resolve2(utils_1.mergeUint8Arrays(parts));
137081
137081
  }).on("error", function(err) {
@@ -137121,11 +137121,11 @@ var require_FileEmbedder = __commonJS({
137121
137121
  this.fileName = fileName;
137122
137122
  this.options = options;
137123
137123
  }
137124
- FileEmbedder2.for = function(bytes2, fileName, options) {
137124
+ FileEmbedder2.for = function(bytes, fileName, options) {
137125
137125
  if (options === void 0) {
137126
137126
  options = {};
137127
137127
  }
137128
- return new FileEmbedder2(bytes2, fileName, options);
137128
+ return new FileEmbedder2(bytes, fileName, options);
137129
137129
  };
137130
137130
  FileEmbedder2.prototype.embedIntoContext = function(context, ref) {
137131
137131
  return tslib_1.__awaiter(this, void 0, void 0, function() {
@@ -138961,11 +138961,11 @@ var require_Stream = __commonJS({
138961
138961
  if (forceClamped === void 0) {
138962
138962
  forceClamped = false;
138963
138963
  }
138964
- var bytes2 = this.bytes;
138964
+ var bytes = this.bytes;
138965
138965
  var pos = this.pos;
138966
138966
  var strEnd = this.end;
138967
138967
  if (!length) {
138968
- var subarray = bytes2.subarray(pos, strEnd);
138968
+ var subarray = bytes.subarray(pos, strEnd);
138969
138969
  return forceClamped ? new Uint8ClampedArray(subarray) : subarray;
138970
138970
  } else {
138971
138971
  var end2 = pos + length;
@@ -138973,7 +138973,7 @@ var require_Stream = __commonJS({
138973
138973
  end2 = strEnd;
138974
138974
  }
138975
138975
  this.pos = end2;
138976
- var subarray = bytes2.subarray(pos, end2);
138976
+ var subarray = bytes.subarray(pos, end2);
138977
138977
  return forceClamped ? new Uint8ClampedArray(subarray) : subarray;
138978
138978
  }
138979
138979
  };
@@ -138986,9 +138986,9 @@ var require_Stream = __commonJS({
138986
138986
  if (forceClamped === void 0) {
138987
138987
  forceClamped = false;
138988
138988
  }
138989
- var bytes2 = this.getBytes(length, forceClamped);
138990
- this.pos -= bytes2.length;
138991
- return bytes2;
138989
+ var bytes = this.getBytes(length, forceClamped);
138990
+ this.pos -= bytes.length;
138991
+ return bytes;
138992
138992
  };
138993
138993
  Stream2.prototype.skip = function(n) {
138994
138994
  if (!n) {
@@ -139109,9 +139109,9 @@ var require_DecodeStream = __commonJS({
139109
139109
  if (forceClamped === void 0) {
139110
139110
  forceClamped = false;
139111
139111
  }
139112
- var bytes2 = this.getBytes(length, forceClamped);
139113
- this.pos -= bytes2.length;
139114
- return bytes2;
139112
+ var bytes = this.getBytes(length, forceClamped);
139113
+ this.pos -= bytes.length;
139114
+ return bytes;
139115
139115
  };
139116
139116
  DecodeStream2.prototype.skip = function(n) {
139117
139117
  if (!n) {
@@ -139267,17 +139267,17 @@ var require_AsciiHexStream = __commonJS({
139267
139267
  }
139268
139268
  AsciiHexStream2.prototype.readBlock = function() {
139269
139269
  var UPSTREAM_BLOCK_SIZE = 8e3;
139270
- var bytes2 = this.stream.getBytes(UPSTREAM_BLOCK_SIZE);
139271
- if (!bytes2.length) {
139270
+ var bytes = this.stream.getBytes(UPSTREAM_BLOCK_SIZE);
139271
+ if (!bytes.length) {
139272
139272
  this.eof = true;
139273
139273
  return;
139274
139274
  }
139275
- var maxDecodeLength = bytes2.length + 1 >> 1;
139275
+ var maxDecodeLength = bytes.length + 1 >> 1;
139276
139276
  var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
139277
139277
  var bufferLength = this.bufferLength;
139278
139278
  var firstDigit = this.firstDigit;
139279
- for (var i = 0, ii2 = bytes2.length; i < ii2; i++) {
139280
- var ch = bytes2[i];
139279
+ for (var i = 0, ii2 = bytes.length; i < ii2; i++) {
139280
+ var ch = bytes[i];
139281
139281
  var digit = void 0;
139282
139282
  if (ch >= 48 && ch <= 57) {
139283
139283
  digit = ch & 15;
@@ -142594,11 +142594,11 @@ var require_BaseParser = __commonJS({
142594
142594
  var BaseParser = (
142595
142595
  /** @class */
142596
142596
  (function() {
142597
- function BaseParser2(bytes2, capNumbers) {
142597
+ function BaseParser2(bytes, capNumbers) {
142598
142598
  if (capNumbers === void 0) {
142599
142599
  capNumbers = false;
142600
142600
  }
142601
- this.bytes = bytes2;
142601
+ this.bytes = bytes;
142602
142602
  this.capNumbers = capNumbers;
142603
142603
  }
142604
142604
  BaseParser2.prototype.parseRawInt = function() {
@@ -142705,11 +142705,11 @@ var require_ByteStream = __commonJS({
142705
142705
  var ByteStream = (
142706
142706
  /** @class */
142707
142707
  (function() {
142708
- function ByteStream2(bytes2) {
142708
+ function ByteStream2(bytes) {
142709
142709
  this.idx = 0;
142710
142710
  this.line = 0;
142711
142711
  this.column = 0;
142712
- this.bytes = bytes2;
142712
+ this.bytes = bytes;
142713
142713
  this.length = this.bytes.length;
142714
142714
  }
142715
142715
  ByteStream2.prototype.moveTo = function(offset) {
@@ -142752,8 +142752,8 @@ var require_ByteStream = __commonJS({
142752
142752
  ByteStream2.prototype.position = function() {
142753
142753
  return { line: this.line, column: this.column, offset: this.idx };
142754
142754
  };
142755
- ByteStream2.of = function(bytes2) {
142756
- return new ByteStream2(bytes2);
142755
+ ByteStream2.of = function(bytes) {
142756
+ return new ByteStream2(bytes);
142757
142757
  };
142758
142758
  ByteStream2.fromPDFRawStream = function(rawStream) {
142759
142759
  return ByteStream2.of(decode_1.decodePDFRawStream(rawStream).decode());
@@ -143060,8 +143060,8 @@ var require_PDFObjectParser = __commonJS({
143060
143060
  throw new errors_1.PDFStreamParsingError(startPos);
143061
143061
  return end2;
143062
143062
  };
143063
- PDFObjectParser2.forBytes = function(bytes2, context, capNumbers) {
143064
- return new PDFObjectParser2(ByteStream_1.default.of(bytes2), context, capNumbers);
143063
+ PDFObjectParser2.forBytes = function(bytes, context, capNumbers) {
143064
+ return new PDFObjectParser2(ByteStream_1.default.of(bytes), context, capNumbers);
143065
143065
  };
143066
143066
  PDFObjectParser2.forByteStream = function(byteStream, context, capNumbers) {
143067
143067
  if (capNumbers === void 0) {
@@ -148054,7 +148054,7 @@ var require_PDFDocument = __commonJS({
148054
148054
  options = {};
148055
148055
  }
148056
148056
  return tslib_1.__awaiter(this, void 0, void 0, function() {
148057
- var _a4, ignoreEncryption, _b, parseSpeed, _c, throwOnInvalidObject, _d, updateMetadata, _e2, capNumbers, bytes2, context;
148057
+ var _a4, ignoreEncryption, _b, parseSpeed, _c, throwOnInvalidObject, _d, updateMetadata, _e2, capNumbers, bytes, context;
148058
148058
  return tslib_1.__generator(this, function(_f) {
148059
148059
  switch (_f.label) {
148060
148060
  case 0:
@@ -148063,8 +148063,8 @@ var require_PDFDocument = __commonJS({
148063
148063
  utils_1.assertIs(ignoreEncryption, "ignoreEncryption", ["boolean"]);
148064
148064
  utils_1.assertIs(parseSpeed, "parseSpeed", ["number"]);
148065
148065
  utils_1.assertIs(throwOnInvalidObject, "throwOnInvalidObject", ["boolean"]);
148066
- bytes2 = utils_1.toUint8Array(pdf);
148067
- return [4, core_1.PDFParser.forBytesWithOptions(bytes2, parseSpeed, throwOnInvalidObject, capNumbers).parseDocument()];
148066
+ bytes = utils_1.toUint8Array(pdf);
148067
+ return [4, core_1.PDFParser.forBytesWithOptions(bytes, parseSpeed, throwOnInvalidObject, capNumbers).parseDocument()];
148068
148068
  case 1:
148069
148069
  context = _f.sent();
148070
148070
  return [2, new PDFDocument3(context, ignoreEncryption, updateMetadata)];
@@ -148331,7 +148331,7 @@ var require_PDFDocument = __commonJS({
148331
148331
  options = {};
148332
148332
  }
148333
148333
  return tslib_1.__awaiter(this, void 0, void 0, function() {
148334
- var bytes2, embedder, ref, embeddedFile;
148334
+ var bytes, embedder, ref, embeddedFile;
148335
148335
  return tslib_1.__generator(this, function(_a4) {
148336
148336
  utils_1.assertIs(attachment, "attachment", ["string", Uint8Array, ArrayBuffer]);
148337
148337
  utils_1.assertIs(name, "name", ["string"]);
@@ -148342,8 +148342,8 @@ var require_PDFDocument = __commonJS({
148342
148342
  Date
148343
148343
  ]);
148344
148344
  utils_1.assertIsOneOfOrUndefined(options.afRelationship, "options.afRelationship", FileEmbedder_1.AFRelationship);
148345
- bytes2 = utils_1.toUint8Array(attachment);
148346
- embedder = FileEmbedder_1.default.for(bytes2, name, options);
148345
+ bytes = utils_1.toUint8Array(attachment);
148346
+ embedder = FileEmbedder_1.default.for(bytes, name, options);
148347
148347
  ref = this.context.nextRef();
148348
148348
  embeddedFile = PDFEmbeddedFile_1.default.of(ref, this, embedder);
148349
148349
  this.embeddedFiles.push(embeddedFile);
@@ -148359,7 +148359,7 @@ var require_PDFDocument = __commonJS({
148359
148359
  options = {};
148360
148360
  }
148361
148361
  return tslib_1.__awaiter(this, void 0, void 0, function() {
148362
- var _a4, subset, customName, features, embedder, bytes2, fontkit, _b, ref, pdfFont;
148362
+ var _a4, subset, customName, features, embedder, bytes, fontkit, _b, ref, pdfFont;
148363
148363
  return tslib_1.__generator(this, function(_c) {
148364
148364
  switch (_c.label) {
148365
148365
  case 0:
@@ -148371,15 +148371,15 @@ var require_PDFDocument = __commonJS({
148371
148371
  return [3, 7];
148372
148372
  case 1:
148373
148373
  if (!utils_1.canBeConvertedToUint8Array(font)) return [3, 6];
148374
- bytes2 = utils_1.toUint8Array(font);
148374
+ bytes = utils_1.toUint8Array(font);
148375
148375
  fontkit = this.assertFontkit();
148376
148376
  if (!subset) return [3, 3];
148377
- return [4, core_1.CustomFontSubsetEmbedder.for(fontkit, bytes2, customName, features)];
148377
+ return [4, core_1.CustomFontSubsetEmbedder.for(fontkit, bytes, customName, features)];
148378
148378
  case 2:
148379
148379
  _b = _c.sent();
148380
148380
  return [3, 5];
148381
148381
  case 3:
148382
- return [4, core_1.CustomFontEmbedder.for(fontkit, bytes2, customName, features)];
148382
+ return [4, core_1.CustomFontEmbedder.for(fontkit, bytes, customName, features)];
148383
148383
  case 4:
148384
148384
  _b = _c.sent();
148385
148385
  _c.label = 5;
@@ -148410,13 +148410,13 @@ var require_PDFDocument = __commonJS({
148410
148410
  };
148411
148411
  PDFDocument3.prototype.embedJpg = function(jpg) {
148412
148412
  return tslib_1.__awaiter(this, void 0, void 0, function() {
148413
- var bytes2, embedder, ref, pdfImage;
148413
+ var bytes, embedder, ref, pdfImage;
148414
148414
  return tslib_1.__generator(this, function(_a4) {
148415
148415
  switch (_a4.label) {
148416
148416
  case 0:
148417
148417
  utils_1.assertIs(jpg, "jpg", ["string", Uint8Array, ArrayBuffer]);
148418
- bytes2 = utils_1.toUint8Array(jpg);
148419
- return [4, core_1.JpegEmbedder.for(bytes2)];
148418
+ bytes = utils_1.toUint8Array(jpg);
148419
+ return [4, core_1.JpegEmbedder.for(bytes)];
148420
148420
  case 1:
148421
148421
  embedder = _a4.sent();
148422
148422
  ref = this.context.nextRef();
@@ -148429,13 +148429,13 @@ var require_PDFDocument = __commonJS({
148429
148429
  };
148430
148430
  PDFDocument3.prototype.embedPng = function(png) {
148431
148431
  return tslib_1.__awaiter(this, void 0, void 0, function() {
148432
- var bytes2, embedder, ref, pdfImage;
148432
+ var bytes, embedder, ref, pdfImage;
148433
148433
  return tslib_1.__generator(this, function(_a4) {
148434
148434
  switch (_a4.label) {
148435
148435
  case 0:
148436
148436
  utils_1.assertIs(png, "png", ["string", Uint8Array, ArrayBuffer]);
148437
- bytes2 = utils_1.toUint8Array(png);
148438
- return [4, core_1.PngEmbedder.for(bytes2)];
148437
+ bytes = utils_1.toUint8Array(png);
148438
+ return [4, core_1.PngEmbedder.for(bytes)];
148439
148439
  case 1:
148440
148440
  embedder = _a4.sent();
148441
148441
  ref = this.context.nextRef();
@@ -148606,7 +148606,7 @@ var require_PDFDocument = __commonJS({
148606
148606
  options = {};
148607
148607
  }
148608
148608
  return tslib_1.__awaiter(this, void 0, void 0, function() {
148609
- var _a4, dataUri, otherOptions, bytes2, base643;
148609
+ var _a4, dataUri, otherOptions, bytes, base643;
148610
148610
  return tslib_1.__generator(this, function(_b) {
148611
148611
  switch (_b.label) {
148612
148612
  case 0:
@@ -148614,8 +148614,8 @@ var require_PDFDocument = __commonJS({
148614
148614
  utils_1.assertIs(dataUri, "dataUri", ["boolean"]);
148615
148615
  return [4, this.save(otherOptions)];
148616
148616
  case 1:
148617
- bytes2 = _b.sent();
148618
- base643 = utils_1.encodeToBase64(bytes2);
148617
+ bytes = _b.sent();
148618
+ base643 = utils_1.encodeToBase64(bytes);
148619
148619
  return [2, dataUri ? "data:application/pdf;base64," + base643 : base643];
148620
148620
  }
148621
148621
  });
@@ -151549,11 +151549,11 @@ function installedOffice() {
151549
151549
  const onPath2 = (process.env.PATH ?? "").split(path48.delimiter).filter(Boolean).map((dir) => path48.join(dir, executable));
151550
151550
  return [...onPath2, ...candidates].find((file3) => existsSync2(file3)) ?? executable;
151551
151551
  }
151552
- function checkPackage(bytes2, mainPart) {
151552
+ function checkPackage(bytes, mainPart) {
151553
151553
  let hasMainPart = false;
151554
151554
  let expanded = 0;
151555
151555
  let relationshipSize = 0;
151556
- const relationships = (0, import_fflate.unzipSync)(bytes2, { filter: (entry) => {
151556
+ const relationships = (0, import_fflate.unzipSync)(bytes, { filter: (entry) => {
151557
151557
  hasMainPart ||= entry.name === mainPart && entry.originalSize > 0;
151558
151558
  expanded += entry.originalSize;
151559
151559
  if (expanded > 5 * ASSET_FILE_LIMIT) throw Error("Office package exceeds the preview size limit");
@@ -151600,15 +151600,15 @@ function convert(command, args2, timeout) {
151600
151600
  });
151601
151601
  });
151602
151602
  }
151603
- async function renderOfficePdf(bytes2, ext, command = installedOffice(), timeout = 3e4) {
151603
+ async function renderOfficePdf(bytes, ext, command = installedOffice(), timeout = 3e4) {
151604
151604
  const format = formats[ext];
151605
- checkPackage(bytes2, format.part);
151605
+ checkPackage(bytes, format.part);
151606
151606
  const dir = await mkdtemp(path48.join(tmpdir(), "wildcrane-document-"));
151607
151607
  try {
151608
151608
  const user = path48.join(dir, "profile", "user");
151609
151609
  const input2 = path48.join(dir, `source${ext}`);
151610
151610
  await mkdir(user, { recursive: true });
151611
- await Promise.all([writeFile(input2, bytes2), writeFile(path48.join(user, "registrymodifications.xcu"), profile)]);
151611
+ await Promise.all([writeFile(input2, bytes), writeFile(path48.join(user, "registrymodifications.xcu"), profile)]);
151612
151612
  await convert(command, [
151613
151613
  `-env:UserInstallation=${pathToFileURL2(path48.dirname(user)).href}`,
151614
151614
  "--headless",
@@ -152470,8 +152470,8 @@ function deferRefresh(session, error62, { after, transport = false } = {}) {
152470
152470
  const seconds = after?.trim() ? Number(after) : NaN;
152471
152471
  const serverDelay = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(after ?? "") - Date.now();
152472
152472
  const backoff = (transport ? 5e3 : REFRESH_BACKOFF_MS) * 2 ** (attempt - 1);
152473
- const delay4 = Math.max(Math.min(backoff, transport ? 3e4 : 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
152474
- const retry2 = { key: refreshKey(session), until: Date.now() + delay4, attempt, error: error62 };
152473
+ const delay5 = Math.max(Math.min(backoff, transport ? 3e4 : 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
152474
+ const retry2 = { key: refreshKey(session), until: Date.now() + delay5, attempt, error: error62 };
152475
152475
  if (transport) transportRetry = { ...retry2, file: retryFile() };
152476
152476
  else {
152477
152477
  const temporary = `${retryFile()}.${process.pid}.tmp`;
@@ -152635,7 +152635,7 @@ function alive(pid) {
152635
152635
  var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
152636
152636
 
152637
152637
  // src/home.ts
152638
- import crypto from "node:crypto";
152638
+ import crypto2 from "node:crypto";
152639
152639
  import fs2 from "node:fs";
152640
152640
  import os3 from "node:os";
152641
152641
  import path3 from "node:path";
@@ -152734,7 +152734,7 @@ function machineId() {
152734
152734
  if (held5.id && /^[0-9a-f-]{36}$/i.test(held5.id)) return held5.id;
152735
152735
  } catch {
152736
152736
  }
152737
- const id2 = crypto.randomUUID();
152737
+ const id2 = crypto2.randomUUID();
152738
152738
  fs2.mkdirSync(runnerHome(), { recursive: true, mode: 448 });
152739
152739
  fs2.writeFileSync(file3, `${JSON.stringify({ id: id2 })}
152740
152740
  `);
@@ -152792,9 +152792,9 @@ function status(line) {
152792
152792
  }
152793
152793
 
152794
152794
  // src/protocol.ts
152795
- var VERSION = true ? "0.6.116" : "0.0.0";
152796
- var AKB_VERSION = true ? "0.11.98" : "0.0.0";
152797
- var AKB_CONTRACT = true ? 32 : 0;
152795
+ var VERSION = true ? "0.6.117" : "0.0.0";
152796
+ var AKB_VERSION = true ? "0.11.99" : "0.0.0";
152797
+ var AKB_CONTRACT = true ? 33 : 0;
152798
152798
  var EXIT_REFUSED = 10;
152799
152799
  var EXIT_OUTDATED = 11;
152800
152800
  var EXIT_UPDATE = 12;
@@ -153723,12 +153723,12 @@ function mergeRetryHistory(...histories) {
153723
153723
  return [...new Map(records.map((record2) => [JSON.stringify(record2), record2])).values()].sort((a2, b2) => a2.at.localeCompare(b2.at));
153724
153724
  }
153725
153725
  async function waitForRetry(at2, stopped2) {
153726
- const delay4 = Math.max(0, at2 - Date.now());
153727
- if (!delay4) return;
153726
+ const delay5 = Math.max(0, at2 - Date.now());
153727
+ if (!delay5) return;
153728
153728
  let timer;
153729
153729
  try {
153730
153730
  await Promise.race([new Promise((resolve2) => {
153731
- timer = setTimeout(resolve2, delay4);
153731
+ timer = setTimeout(resolve2, delay5);
153732
153732
  }), ...stopped2 ? [stopped2] : []]);
153733
153733
  } finally {
153734
153734
  clearTimeout(timer);
@@ -153799,10 +153799,10 @@ function planRetry(failure3, attempt, now = Date.now(), backoff = backoffMs, tas
153799
153799
  return { pause: "authorization" };
153800
153800
  }
153801
153801
  if (attempt > of) return { pause: "limit" };
153802
- const delay4 = failure3.retryAfterMs;
153803
- const valid = delay4 !== void 0 && !Number.isNaN(delay4) && delay4 >= 0;
153802
+ const delay5 = failure3.retryAfterMs;
153803
+ const valid = delay5 !== void 0 && !Number.isNaN(delay5) && delay5 >= 0;
153804
153804
  const immediate = failure3.source === "validation";
153805
- const wait3 = valid ? delay4 : immediate ? 0 : backoff(attempt + 1);
153805
+ const wait3 = valid ? delay5 : immediate ? 0 : backoff(attempt + 1);
153806
153806
  const cap = task && failure3.code === "rate_limited" && valid ? 24 * 60 * 6e4 : CAP_MS;
153807
153807
  if (wait3 > cap) return { pause: "wait_too_long" };
153808
153808
  return { plan: { at: now + wait3, of, failure: failure3 } };
@@ -154042,12 +154042,12 @@ function bounded(work, ms, reason) {
154042
154042
  }
154043
154043
 
154044
154044
  // ../cli/src/lib/shared/reply-parts.ts
154045
- function imageMime(bytes2) {
154046
- const at2 = (...v) => v.every((n, i) => bytes2[i] === n);
154047
- const text4 = (a2, b2) => String.fromCharCode(...bytes2.slice(a2, b2));
154048
- if (bytes2.length >= 24 && at2(137, 80, 78, 71, 13, 10, 26, 10) && text4(12, 16) === "IHDR" && bytes2.slice(16, 20).some(Boolean) && bytes2.slice(20, 24).some(Boolean)) return "image/png";
154045
+ function imageMime(bytes) {
154046
+ const at2 = (...v) => v.every((n, i) => bytes[i] === n);
154047
+ const text4 = (a2, b2) => String.fromCharCode(...bytes.slice(a2, b2));
154048
+ if (bytes.length >= 24 && at2(137, 80, 78, 71, 13, 10, 26, 10) && text4(12, 16) === "IHDR" && bytes.slice(16, 20).some(Boolean) && bytes.slice(20, 24).some(Boolean)) return "image/png";
154049
154049
  if (at2(255, 216, 255)) return "image/jpeg";
154050
- if (bytes2.length >= 13 && ["GIF87a", "GIF89a"].includes(text4(0, 6)) && (bytes2[6] || bytes2[7]) && (bytes2[8] || bytes2[9])) return "image/gif";
154050
+ if (bytes.length >= 13 && ["GIF87a", "GIF89a"].includes(text4(0, 6)) && (bytes[6] || bytes[7]) && (bytes[8] || bytes[9])) return "image/gif";
154051
154051
  if (text4(0, 4) === "RIFF" && text4(8, 12) === "WEBP") return "image/webp";
154052
154052
  return void 0;
154053
154053
  }
@@ -154372,8 +154372,8 @@ function createTail(log) {
154372
154372
  // ../cli/package.json
154373
154373
  var package_default = {
154374
154374
  name: "wildcrane",
154375
- version: "0.11.98",
154376
- akbContract: 32,
154375
+ version: "0.11.99",
154376
+ akbContract: 33,
154377
154377
  canonicalCommands: true,
154378
154378
  description: "WildCrane's `akb` command \u2014 scaffold the Markdown board under docs/kanban/, put an agent on a card, and carry the flows the agent works by.",
154379
154379
  keywords: [
@@ -154666,9 +154666,9 @@ async function oneTurn(io, options) {
154666
154666
  const images = [];
154667
154667
  const files = [];
154668
154668
  for (const file3 of io.imageFiles ?? []) {
154669
- const bytes2 = caps.image === true ? fs13.readFileSync(file3) : void 0;
154670
- const mimeType = bytes2 && imageMime(bytes2);
154671
- if (mimeType) images.push({ type: "image", mimeType, data: bytes2.toString("base64") });
154669
+ const bytes = caps.image === true ? fs13.readFileSync(file3) : void 0;
154670
+ const mimeType = bytes && imageMime(bytes);
154671
+ if (mimeType) images.push({ type: "image", mimeType, data: bytes.toString("base64") });
154672
154672
  else files.push(file3);
154673
154673
  }
154674
154674
  if (Date.now() >= preparingUntil) throw Error("ACP preparation timed out.");
@@ -154847,30 +154847,30 @@ import { existsSync } from "node:fs";
154847
154847
  function antigravityConversationFile(session) {
154848
154848
  if (/^[a-f0-9-]{36}$/i.test(session)) return home(".gemini", "antigravity-cli", "conversations", `${session}.db`);
154849
154849
  }
154850
- function varint(bytes2, offset) {
154850
+ function varint(bytes, offset) {
154851
154851
  let value = 0;
154852
- for (let shift = 0; shift < 70 && offset.value < bytes2.length; shift += 7) {
154853
- const byte = bytes2[offset.value++];
154852
+ for (let shift = 0; shift < 70 && offset.value < bytes.length; shift += 7) {
154853
+ const byte = bytes[offset.value++];
154854
154854
  value += (byte & 127) * 2 ** shift;
154855
154855
  if (byte < 128) return value;
154856
154856
  }
154857
154857
  throw new Error("Invalid Antigravity conversation metadata");
154858
154858
  }
154859
- function* fields(bytes2) {
154859
+ function* fields(bytes) {
154860
154860
  const offset = { value: 0 };
154861
- while (offset.value < bytes2.length) {
154862
- const tag = varint(bytes2, offset);
154861
+ while (offset.value < bytes.length) {
154862
+ const tag = varint(bytes, offset);
154863
154863
  const number4 = Math.floor(tag / 8);
154864
154864
  const wire = tag % 8;
154865
154865
  if (number4 < 1 || number4 >= 2 ** 29) throw new Error("Invalid Antigravity conversation metadata");
154866
154866
  if (wire === 0) {
154867
- yield [number4, varint(bytes2, offset)];
154867
+ yield [number4, varint(bytes, offset)];
154868
154868
  continue;
154869
154869
  }
154870
- const size = wire === 2 ? varint(bytes2, offset) : wire === 1 ? 8 : wire === 5 ? 4 : -1;
154870
+ const size = wire === 2 ? varint(bytes, offset) : wire === 1 ? 8 : wire === 5 ? 4 : -1;
154871
154871
  const end2 = offset.value + size;
154872
- if (size < 0 || end2 > bytes2.length) throw new Error("Invalid Antigravity conversation metadata");
154873
- if (wire === 2) yield [number4, bytes2.subarray(offset.value, end2)];
154872
+ if (size < 0 || end2 > bytes.length) throw new Error("Invalid Antigravity conversation metadata");
154873
+ if (wire === 2) yield [number4, bytes.subarray(offset.value, end2)];
154874
154874
  offset.value = end2;
154875
154875
  }
154876
154876
  }
@@ -154902,7 +154902,7 @@ function recordedContextLimit(data) {
154902
154902
  const limit = varintField(bytesField(bytesField(bytesField(data, 1), 9), 10), 4);
154903
154903
  return limit !== void 0 && Number.isSafeInteger(limit) && limit > 0 ? limit : void 0;
154904
154904
  }
154905
- var utf8 = (bytes2) => bytes2 && Buffer.from(bytes2).toString("utf8");
154905
+ var utf8 = (bytes) => bytes && Buffer.from(bytes).toString("utf8");
154906
154906
  function stepUuid(stepRow, index) {
154907
154907
  if (!Number.isSafeInteger(index) || index < 0) return;
154908
154908
  const id2 = bytesField(stepRow.get(index)?.metadata, 12);
@@ -156155,9 +156155,9 @@ function readIndex() {
156155
156155
  entries.delete(sessionId);
156156
156156
  continue;
156157
156157
  }
156158
- const sessionDir = str2(record2.sessionDir).trim();
156158
+ const sessionDir2 = str2(record2.sessionDir).trim();
156159
156159
  const workDir = str2(record2.workDir).trim();
156160
- if (sessionDir && workDir) entries.set(sessionId, { sessionId, sessionDir, workDir });
156160
+ if (sessionDir2 && workDir) entries.set(sessionId, { sessionId, sessionDir: sessionDir2, workDir });
156161
156161
  }
156162
156162
  return entries;
156163
156163
  }
@@ -156177,13 +156177,13 @@ function findKimiSession(cwd, since) {
156177
156177
  }
156178
156178
  return newest2?.id;
156179
156179
  }
156180
- function wireFiles(sessionDir) {
156181
- const agents = join3(sessionDir, "agents");
156180
+ function wireFiles(sessionDir2) {
156181
+ const agents = join3(sessionDir2, "agents");
156182
156182
  let names2;
156183
156183
  try {
156184
156184
  names2 = readdirSync2(agents);
156185
156185
  } catch {
156186
- return [{ path: join3(sessionDir, "wire.jsonl"), main: true }];
156186
+ return [{ path: join3(sessionDir2, "wire.jsonl"), main: true }];
156187
156187
  }
156188
156188
  const ordered = names2.sort((a2, b2) => Number(b2 === "main") - Number(a2 === "main"));
156189
156189
  return ordered.map((name) => ({ path: join3(agents, name, "wire.jsonl"), main: name === "main" }));
@@ -156763,19 +156763,19 @@ var settle_background_default = "Wait for and collect needed results from this t
156763
156763
 
156764
156764
  // ../cli/src/lib/agent/wire/codex-background.ts
156765
156765
  var CODEX_SETTLE_MS = { turn: 6e4, verify: 1e4 };
156766
- function summary(text4, bytes2 = 1800) {
156767
- if (Buffer.byteLength(text4) <= bytes2) return text4;
156768
- return Buffer.from(text4).subarray(0, bytes2).toString("utf8") + " [truncated; see the original thread item in the run log]";
156766
+ function summary(text4, bytes = 1800) {
156767
+ if (Buffer.byteLength(text4) <= bytes) return text4;
156768
+ return Buffer.from(text4).subarray(0, bytes).toString("utf8") + " [truncated; see the original thread item in the run log]";
156769
156769
  }
156770
156770
  function batch(work) {
156771
156771
  const result = [];
156772
- let bytes2 = 0;
156772
+ let bytes = 0;
156773
156773
  for (const entry of work) {
156774
156774
  const size = Buffer.byteLength(JSON.stringify(entry));
156775
156775
  if (size > 15e3) throw Error("A Codex background identifier exceeds the snapshot limit.");
156776
- if (bytes2 + size > 15e3) break;
156776
+ if (bytes + size > 15e3) break;
156777
156777
  result.push(entry);
156778
- bytes2 += size;
156778
+ bytes += size;
156779
156779
  }
156780
156780
  return result;
156781
156781
  }
@@ -159145,6 +159145,665 @@ __export(api_exports, {
159145
159145
  uploadReplyImage: () => uploadReplyImage
159146
159146
  });
159147
159147
 
159148
+ // ../cli/src/lib/shared/studio-files.ts
159149
+ var import_yaml3 = __toESM(require_dist(), 1);
159150
+
159151
+ // ../cli/src/lib/agent/studio-def.ts
159152
+ var import_ajv = __toESM(require_ajv(), 1);
159153
+ var import_yaml = __toESM(require_dist(), 1);
159154
+
159155
+ // ../cli/src/lib/agents/icon.ts
159156
+ var ICON_NAMES = [
159157
+ "file",
159158
+ "text",
159159
+ "article",
159160
+ "outline",
159161
+ "script",
159162
+ "prompt",
159163
+ "email",
159164
+ "image",
159165
+ "post-image",
159166
+ "social-image",
159167
+ "cover",
159168
+ "carousel",
159169
+ "carousel-outline",
159170
+ "slides",
159171
+ "wireframe",
159172
+ "screen",
159173
+ "video",
159174
+ "storyboard",
159175
+ "template",
159176
+ "shots",
159177
+ "api",
159178
+ "schema",
159179
+ "compare",
159180
+ "stack",
159181
+ "studio",
159182
+ "code",
159183
+ "checklist",
159184
+ "card",
159185
+ "plan",
159186
+ "proposal",
159187
+ "dismissed",
159188
+ "inbox",
159189
+ "notebook",
159190
+ "squeeze",
159191
+ "folder",
159192
+ "reply",
159193
+ "feedback",
159194
+ "software",
159195
+ "product-video",
159196
+ "social-post",
159197
+ "blog",
159198
+ "deck",
159199
+ "video-clone",
159200
+ "studio-kit"
159201
+ ];
159202
+ var ICON_COLORS = ["k", "w", "c", "g", "o", "p", "s", "m", "l", "r", "y"];
159203
+ var PATH = /^[MmLlHhVvCcSsQqTtAaZz0-9.,\s-]+$/;
159204
+ var isColor = (v) => ICON_COLORS.includes(v);
159205
+ function readIcon(raw) {
159206
+ if (raw === void 0 || raw === "") return void 0;
159207
+ if (typeof raw === "string") return ICON_NAMES.includes(raw.trim()) ? raw.trim() : { problem: `"${raw}" is not a glyph name` };
159208
+ if (!Array.isArray(raw) || !raw.length || raw.length > 12) return { problem: "the value is neither a glyph name nor a list of 1 to 12 parts" };
159209
+ const parts = [];
159210
+ for (const [i, item] of raw.entries()) {
159211
+ const at2 = `part ${i + 1}`;
159212
+ if (!item || typeof item !== "object" || Array.isArray(item)) return { problem: `${at2} is not a map of \`d\`, \`f\`, \`o\`, \`s\`, \`w\`` };
159213
+ const { d: d2, f: f2, o: o3, s, w: w2, ...extra } = item;
159214
+ if (Object.keys(extra).length) return { problem: `${at2} has \`${Object.keys(extra).join("`, `")}\`` };
159215
+ if (typeof d2 !== "string" || !PATH.test(d2)) return { problem: `${at2} has no \`d\` of SVG path commands and numbers` };
159216
+ const part = { d: d2.trim() };
159217
+ for (const [key, value] of [["f", f2], ["s", s]]) {
159218
+ if (value === void 0) continue;
159219
+ if (typeof value !== "string" || !isColor(value)) return { problem: `${at2} colours \`${key}\` with "${String(value)}"` };
159220
+ part[key] = value;
159221
+ }
159222
+ if (o3 !== void 0) {
159223
+ if (o3 !== "true") return { problem: `${at2} has \`o: ${String(o3)}\`, not \`true\`` };
159224
+ part.o = true;
159225
+ }
159226
+ if (w2 !== void 0) {
159227
+ const width = typeof w2 === "string" ? Number(w2) : NaN;
159228
+ if (!(width > 0 && width <= 3)) return { problem: `${at2} has \`w: ${String(w2)}\`, not above 0 and up to 3` };
159229
+ part.w = width;
159230
+ }
159231
+ parts.push(part);
159232
+ }
159233
+ return parts;
159234
+ }
159235
+
159236
+ // ../cli/src/lib/shared/preview-blocks.ts
159237
+ var PREVIEW_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
159238
+ function sourcePosition(source2, offset) {
159239
+ const before = source2.slice(0, offset);
159240
+ return { line: before.split("\n").length, column: offset - before.lastIndexOf("\n") };
159241
+ }
159242
+ function withoutCode(source2) {
159243
+ const blank2 = (s) => s.replace(/[^\n\r]/g, " ");
159244
+ let fence;
159245
+ let indented = false, afterBlank = true, inList = false;
159246
+ return source2.split(/(?<=\n)/).map((line) => {
159247
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)/.exec(line);
159248
+ if (fence) {
159249
+ if (marker && marker[1][0] === fence.char && marker[1].length >= fence.length && !marker[2].trim()) fence = void 0;
159250
+ return blank2(line);
159251
+ }
159252
+ if (marker) {
159253
+ fence = { char: marker[1][0], length: marker[1].length };
159254
+ return blank2(line);
159255
+ }
159256
+ if (!line.trim()) {
159257
+ afterBlank = true;
159258
+ return line;
159259
+ }
159260
+ const hasIndent = /^(?: {4}|\t)/.test(line);
159261
+ if (!hasIndent) indented = false;
159262
+ if (/^ {0,3}(?:[-+*]|\d+[.)])\s/.test(line)) inList = true;
159263
+ else if (/^\S/.test(line)) inList = false;
159264
+ if (hasIndent && (indented || afterBlank && !inList)) {
159265
+ indented = true;
159266
+ return blank2(line);
159267
+ }
159268
+ afterBlank = false;
159269
+ return line;
159270
+ }).join("").replace(/(`+)([^]*?)\1(?!`)/g, blank2);
159271
+ }
159272
+ function agentSectionOffset(source2) {
159273
+ return /^<!--[ \t]*agent[ \t]*-->/m.exec(withoutCode(source2))?.index ?? source2.length;
159274
+ }
159275
+ function parsePreviewBlocks(source2, file3 = "STUDIO.md") {
159276
+ const blocks = [], problems = [];
159277
+ const masked = withoutCode(source2);
159278
+ let open2;
159279
+ const seen = /* @__PURE__ */ new Set();
159280
+ const fail = (offset, id2, code, message, hint2) => problems.push({ file: file3, ...sourcePosition(source2, offset), path: id2 ? `previews.${id2}` : "previews", code, message, hint: hint2 });
159281
+ for (const tag of masked.matchAll(/<\/?Preview\b[^>]*(?:>|$)/g)) {
159282
+ const offset = tag.index, text4 = tag[0];
159283
+ const closing = /^<\/Preview\s*>$/.test(text4);
159284
+ if (closing) {
159285
+ if (!open2) fail(offset, "", "preview-unexpected-close", "Preview has no opening tag", "Remove it or restore its opening tag.");
159286
+ else {
159287
+ const instructions = source2.slice(open2.content, offset).trim();
159288
+ if (!instructions) fail(open2.start, open2.id, "preview-empty", `Preview ${open2.id} is empty`, "Describe the requested output inside the block.");
159289
+ blocks.push({ id: open2.id, instructions, start: open2.start, end: offset + text4.length });
159290
+ open2 = void 0;
159291
+ }
159292
+ continue;
159293
+ }
159294
+ const opening = /^<Preview\s+id=(?:"([^"]*)"|'([^']*)')\s*>$/.exec(text4);
159295
+ if (!opening || open2) {
159296
+ fail(offset, open2?.id ?? "", "preview-tag", "Malformed or nested Preview tag", 'Use one non-nested <Preview id="stable-id"> block with only id.');
159297
+ continue;
159298
+ }
159299
+ const id2 = opening[1] ?? opening[2];
159300
+ if (!PREVIEW_ID.test(id2) || seen.has(id2)) fail(offset, id2, "preview-id", `Invalid or repeated Preview ID ${id2}`, "Use a unique lowercase ID with digits and dashes.");
159301
+ seen.add(id2);
159302
+ open2 = { id: id2, start: offset, content: offset + text4.length };
159303
+ }
159304
+ if (open2) fail(open2.start, open2.id, "preview-unclosed", `Preview ${open2.id} is not closed`, "Add </Preview> after this block.");
159305
+ return { blocks, problems };
159306
+ }
159307
+
159308
+ // ../cli/src/lib/yaml.ts
159309
+ function yamlScalar(s) {
159310
+ const text4 = String(s);
159311
+ if (text4 === "") return '""';
159312
+ if (/^[-?:,[\]{}#&*!|>'"%@`]/.test(text4) || /:\s/.test(text4) || /[\n"]/.test(text4) || /^\s|\s$/.test(text4)) {
159313
+ return JSON.stringify(text4);
159314
+ }
159315
+ return text4;
159316
+ }
159317
+ function unquote(v) {
159318
+ const text4 = String(v).trim();
159319
+ if (text4.startsWith('"') && text4.endsWith('"')) {
159320
+ try {
159321
+ return JSON.parse(text4);
159322
+ } catch {
159323
+ return text4.slice(1, -1);
159324
+ }
159325
+ }
159326
+ if (text4.startsWith("'") && text4.endsWith("'")) return text4.slice(1, -1);
159327
+ return text4;
159328
+ }
159329
+
159330
+ // ../cli/src/lib/agent/studio-def.ts
159331
+ var STUDIO_ID = PREVIEW_ID;
159332
+ var titles = { type: "object", minProperties: 1, propertyNames: { pattern: "^[a-z]{2,3}(?:-[A-Za-z0-9]+)*$" }, additionalProperties: { type: "string", minLength: 1, pattern: "\\S" } };
159333
+ var icon = { anyOf: [
159334
+ { type: "string", enum: ICON_NAMES },
159335
+ { type: "array", minItems: 1, maxItems: 12, items: { type: "object", required: ["d"], additionalProperties: false, properties: {
159336
+ d: { type: "string", minLength: 1, pattern: "^[MmLlHhVvCcSsQqTtAaZz0-9.,\\s-]+$" },
159337
+ f: { enum: ICON_COLORS },
159338
+ o: { const: true },
159339
+ s: { enum: ICON_COLORS },
159340
+ w: { type: "number", exclusiveMinimum: 0, maximum: 3 }
159341
+ } } }
159342
+ ] };
159343
+ var STUDIO_SCHEMA = {
159344
+ type: "object",
159345
+ required: ["name"],
159346
+ additionalProperties: false,
159347
+ properties: {
159348
+ name: { type: "string", minLength: 1, pattern: "\\S" },
159349
+ names: titles,
159350
+ description: { type: "string" },
159351
+ summaries: titles,
159352
+ entrypoints: { type: "array", minItems: 1, maxItems: 10, uniqueItems: true, items: { type: "string", pattern: PREVIEW_ID.source } },
159353
+ needsArtifact: { type: "boolean" },
159354
+ icon,
159355
+ previews: { type: "object", propertyNames: { pattern: PREVIEW_ID.source }, additionalProperties: {
159356
+ type: "object",
159357
+ additionalProperties: false,
159358
+ properties: { title: titles, description: titles, icon }
159359
+ } }
159360
+ }
159361
+ };
159362
+ var validate = new import_ajv.Ajv({ allErrors: true, meta: false, validateSchema: false }).compile(STUDIO_SCHEMA);
159363
+ var comments = /<!--[^]*?(?:-->|$)/g;
159364
+ var blank = (text4) => text4.replace(/[^\r\n]/g, " ");
159365
+ var headingsOf = (body) => [...withoutCode(body).replace(comments, blank).matchAll(/^ {0,3}#{1,2}(?=[ \t\r\n]|$)[^\r\n]*/gm)];
159366
+ function studioSetup(body) {
159367
+ const headings = headingsOf(body);
159368
+ const index = headings.findIndex((h3) => /^ {0,3}##[ \t]+Setup(?:[ \t]+#+)?[ \t]*$/.test(body.slice(h3.index, h3.index + h3[0].length)));
159369
+ if (index === -1) return "";
159370
+ const heading = headings[index];
159371
+ const section = body.slice(heading.index + heading[0].length, headings[index + 1]?.index).trim();
159372
+ return section.replace(comments, "").trim() ? section : "";
159373
+ }
159374
+ function landSections(body, previews) {
159375
+ let visible = "", at2 = 0;
159376
+ for (const { start, end: end2 } of previews) {
159377
+ visible += body.slice(at2, start) + blank(body.slice(start, end2));
159378
+ at2 = end2;
159379
+ }
159380
+ visible += body.slice(at2);
159381
+ const headings = headingsOf(visible);
159382
+ return headings.flatMap((heading, index) => {
159383
+ const start = heading.index;
159384
+ const end2 = start + heading[0].length;
159385
+ if (!/^ {0,3}##[ \t]+Land(?:[ \t]+#+)?[ \t]*$/.test(visible.slice(start, end2))) return [];
159386
+ return [{
159387
+ offset: start + heading[0].indexOf("#"),
159388
+ empty: !visible.slice(end2, headings[index + 1]?.index).replace(comments, "").trim()
159389
+ }];
159390
+ });
159391
+ }
159392
+ function parseStudioFile(id2, source2, from, { requirePreviewCopy = false, requireLand = false } = {}) {
159393
+ const problems = [];
159394
+ const fail = (offset, path88, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source2, offset), path: path88, code, message, hint: hint2 });
159395
+ const result = () => ({ problem: problems.map((p2) => `${p2.file}:${p2.line}:${p2.column} ${p2.path}: ${p2.code} \u2014 ${p2.message}. ${p2.hint}`).join("\n"), problems });
159396
+ if (!STUDIO_ID.test(id2)) fail(0, "id", "studio-schema", `Invalid Studio ID ${id2}`, "Use lowercase letters, digits and dashes.");
159397
+ const front = /^---\r?\n([^]*?)\r?\n---(?:\r?\n|$)/.exec(source2);
159398
+ if (!front) {
159399
+ fail(0, "", "yaml-syntax", "Missing YAML frontmatter", "Enclose metadata between --- lines.");
159400
+ return result();
159401
+ }
159402
+ const metaOffset = source2.indexOf("\n") + 1, bodyOffset = front[0].length;
159403
+ const counter = new import_yaml.LineCounter();
159404
+ const document = (0, import_yaml.parseDocument)(front[1], { lineCounter: counter, uniqueKeys: true, strict: true });
159405
+ for (const error62 of document.errors) fail(metaOffset + (error62.pos[0] ?? 0), "", error62.code === "DUPLICATE_KEY" ? "yaml-duplicate-key" : "yaml-syntax", error62.message.split("\n")[0], "Correct the indicated YAML location.");
159406
+ if (problems.length) return result();
159407
+ let raw;
159408
+ try {
159409
+ raw = document.toJS({ maxAliasCount: 0 });
159410
+ } catch {
159411
+ fail(metaOffset, "", "yaml-syntax", "YAML aliases are not supported", "Write metadata explicitly.");
159412
+ return result();
159413
+ }
159414
+ if (!validate(raw)) {
159415
+ for (const error62 of validate.errors ?? []) {
159416
+ const parts = error62.instancePath.split("/").slice(1);
159417
+ const key = error62.params.additionalProperty ?? error62.params.missingProperty;
159418
+ if (key) parts.push(String(key));
159419
+ const node2 = parts.length ? document.getIn(parts, true) : document.contents;
159420
+ fail(metaOffset + (node2?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error62.message}`, "Use only Studio metadata and previews: {id: {title?, description?, icon?}} with the declared field types.");
159421
+ }
159422
+ }
159423
+ const body = source2.slice(bodyOffset);
159424
+ const parsed = parsePreviewBlocks(body, from);
159425
+ problems.push(...parsed.problems.map((p2) => ({ ...p2, line: p2.line + source2.slice(0, bodyOffset).split("\n").length - 1 })));
159426
+ if (problems.length) return result();
159427
+ const map3 = raw.previews ?? {};
159428
+ for (const block of parsed.blocks) if (!Object.hasOwn(map3, block.id)) fail(bodyOffset + block.start, `previews.${block.id}`, "preview-metadata-missing", `Preview ${block.id} has no metadata entry`, "Add the ID under previews, using {} if needed.");
159429
+ for (const key of Object.keys(map3)) if (!parsed.blocks.some((b2) => b2.id === key)) fail(metaOffset + (document.getIn(["previews", key], true)?.range?.[0] ?? 0), `previews.${key}`, "preview-body-missing", `Preview ${key} has no body`, "Add its block or remove unused metadata.");
159430
+ if (requirePreviewCopy) for (const block of parsed.blocks) {
159431
+ const metadata = Object.hasOwn(map3, block.id) ? map3[block.id] : void 0;
159432
+ if (!metadata) continue;
159433
+ for (const field2 of ["title", "description"]) for (const lang of ["en", "zh"]) {
159434
+ if (metadata[field2]?.[lang]) continue;
159435
+ fail(
159436
+ bodyOffset + block.start,
159437
+ `previews.${block.id}.${field2}.${lang}`,
159438
+ "preview-display-missing",
159439
+ `Preview ${block.id} needs a ${lang} ${field2}`,
159440
+ "Add non-blank en and zh display text in the Preview metadata."
159441
+ );
159442
+ }
159443
+ }
159444
+ if (requireLand) {
159445
+ const sections = landSections(body, parsed.blocks);
159446
+ if (!sections.length) fail(bodyOffset, "Land", "studio-land-missing", "Missing ## Land section", "Add ## Land to the Studio body and describe delivery, checks and what to record.");
159447
+ for (const [index, { offset, empty }] of sections.entries()) {
159448
+ if (index) fail(bodyOffset + offset, "Land", "studio-land-duplicate", "Repeated ## Land section", "Combine delivery instructions under one ## Land heading.");
159449
+ if (empty) fail(bodyOffset + offset, "Land", "studio-land-empty", "The ## Land section is empty", "Describe delivery, checks and what to record under ## Land.");
159450
+ }
159451
+ }
159452
+ if (problems.length) return result();
159453
+ let rules = "", at2 = 0;
159454
+ for (const block of parsed.blocks) {
159455
+ rules += body.slice(at2, block.start);
159456
+ at2 = block.end;
159457
+ }
159458
+ rules += body.slice(at2);
159459
+ return { def: {
159460
+ id: id2,
159461
+ name: raw.name.trim(),
159462
+ ...raw.names ? { names: raw.names } : {},
159463
+ description: raw.description ?? "",
159464
+ needsArtifact: raw.needsArtifact ?? false,
159465
+ ...raw.summaries ? { summaries: raw.summaries } : {},
159466
+ ...raw.entrypoints ? { entrypoints: raw.entrypoints } : {},
159467
+ ...raw.icon ? { icon: raw.icon } : {},
159468
+ previews: parsed.blocks.map((b2) => ({ id: b2.id, instructions: b2.instructions, ...map3[b2.id] })),
159469
+ rules: rules.trim()
159470
+ } };
159471
+ }
159472
+
159473
+ // ../cli/src/lib/shared/guide-topics.ts
159474
+ var GUIDE_TOPICS = ["board", "writing", "add-task", "follow-up", "discuss-goal", "troubleshoot", "card-chat", "task-ui-en", "task-ui-zh", "update-studio", "implement", "settle-background", "archive", "update-questions", "refine", "revise", "resolve", "prune-memory", "review-memory", "describe-project", "review-rejections", "reflect", "write-agent", "write-prompt", "module-map"];
159475
+
159476
+ // ../cli/src/lib/shared/studio-files.ts
159477
+ var STUDIO_FILE = "STUDIO.md";
159478
+ var MCP_FILE = "mcp.json";
159479
+ var VERSION_FILE = "version.json";
159480
+ var PUBLICATION_FILE = ".publication.json";
159481
+ var STUDIO_CATALOG_FILE = "catalog.json";
159482
+ var KB = 1024;
159483
+ var FILE_LIMITS = { file: 2 * KB * KB, total: 10 * KB * KB, count: 500, path: 512 };
159484
+ var officialId = (folder2) => `wf_builtin_${folder2.replace(/-/g, "_")}`;
159485
+ var hashInput = (files) => JSON.stringify(Object.entries(files).sort(([a2], [b2]) => a2 < b2 ? -1 : 1));
159486
+ var landsOf = (_def) => ({ lands: true });
159487
+ var encoder = new TextEncoder();
159488
+ var safeStudioPath = (file3) => encoder.encode(file3).length <= FILE_LIMITS.path && !/[<>:"\\|?*\x00-\x1f\x7f]/.test(file3) && file3.split("/").every((part) => !!part && encoder.encode(part).length <= 255 && !/[. ]$/.test(part) && !/^(?:\.git$|(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$))/i.test(part));
159489
+ var SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
159490
+ var skillFile = (name) => "skills/" + name + "/SKILL.md";
159491
+ function skillMetadata(source2, directory3) {
159492
+ const front = /^\uFEFF?---[^\S\r\n]*\r?\n([\s\S]*?)^---[^\S\r\n]*(?:\r?\n|$)/m.exec(source2);
159493
+ if (!front || front.index !== 0) return "Start SKILL.md with YAML frontmatter";
159494
+ const doc = (0, import_yaml3.parseDocument)(front[1]);
159495
+ if (doc.errors.length || !(0, import_yaml3.isMap)(doc.contents)) return "Use valid YAML frontmatter with unique keys";
159496
+ let data;
159497
+ try {
159498
+ data = doc.toJS({ maxAliasCount: 0 });
159499
+ } catch {
159500
+ return "Use literal YAML metadata";
159501
+ }
159502
+ const { name, description, license, compatibility, metadata, "allowed-tools": allowedTools, ...extra } = data;
159503
+ if (name !== directory3 || !SKILL_NAME.test(directory3) || directory3.length > 64) return "Set name to match the containing skill directory (1\u201364 lowercase letters, digits and single hyphens)";
159504
+ if (typeof description !== "string" || !description.trim() || [...description].length > 1024) return "Set description to 1\u20131024 characters";
159505
+ if (license !== void 0 && typeof license !== "string") return "Set license to a string";
159506
+ if (compatibility !== void 0 && (typeof compatibility !== "string" || !compatibility.trim() || [...compatibility].length > 500)) return "Set compatibility to 1\u2013500 characters";
159507
+ if (metadata !== void 0 && (!metadata || typeof metadata !== "object" || Array.isArray(metadata) || Object.values(metadata).some((value) => typeof value !== "string"))) return "Set metadata to a map of strings";
159508
+ if (allowedTools !== void 0 && typeof allowedTools !== "string") return "Set allowed-tools to a string";
159509
+ if (Object.keys(extra).length) return "Use standard Agent Skills fields and put custom fields under metadata";
159510
+ return { name: directory3, description: description.trim().replace(/\s+/g, " ") };
159511
+ }
159512
+ function studioSkills(files) {
159513
+ return Object.keys(files).sort().flatMap((file3) => {
159514
+ const match = /^skills\/([^/]+)\/SKILL\.md$/.exec(file3);
159515
+ if (!match) return [];
159516
+ const skill = skillMetadata(files[file3], match[1]);
159517
+ return typeof skill === "string" ? [] : [skill];
159518
+ });
159519
+ }
159520
+ var isAboutFile = (file3) => /^ABOUT(\.[a-z]{2})?\.md$/.test(file3) || /^screenshots\/[\w.-]+\.(png|jpe?g|webp)$/.test(file3);
159521
+ var studioScreenshotPrefix = (path88) => "data:" + (path88.endsWith(".png") ? "image/png" : /\.jpe?g$/.test(path88) ? "image/jpeg" : "image/webp") + ";base64,";
159522
+ function studioFileBody(path88, text4) {
159523
+ if (path88.startsWith("screenshots/") && isAboutFile(path88)) {
159524
+ const prefix = studioScreenshotPrefix(path88);
159525
+ if (text4.startsWith(prefix)) {
159526
+ const data = text4.slice(prefix.length);
159527
+ if (/^[A-Za-z0-9+/]*={0,2}$/.test(data) && data.length % 4 === 0) {
159528
+ const raw = atob(data);
159529
+ if (btoa(raw) === data) return { bytes: Uint8Array.from(raw, (c2) => c2.charCodeAt(0)), binary: true };
159530
+ }
159531
+ }
159532
+ }
159533
+ const bytes = encoder.encode(text4);
159534
+ if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== text4) throw Error("Invalid UTF-8.");
159535
+ return { bytes, binary: false };
159536
+ }
159537
+ function studioSizeProblem(file3, size, total) {
159538
+ if (size > FILE_LIMITS.file) return { file: file3, reason: "is larger than 2 MiB", tooLarge: true };
159539
+ if (total > FILE_LIMITS.total) return { file: "files", reason: "are larger than 10 MiB together", tooLarge: true };
159540
+ }
159541
+ function mcpProblem(text4) {
159542
+ let read6;
159543
+ try {
159544
+ read6 = JSON.parse(text4);
159545
+ } catch {
159546
+ return "is not JSON";
159547
+ }
159548
+ const servers = read6?.mcpServers;
159549
+ if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "must hold `mcpServers`, an object of name \u2192 server";
159550
+ for (const [name, server] of Object.entries(servers)) {
159551
+ const { command, args: args2, ...rest } = server ?? {};
159552
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) return `names a server \`${name}\`; use lowercase letters, digits and dashes`;
159553
+ if (typeof command !== "string" || !command) return `server \`${name}\` needs a \`command\``;
159554
+ if (args2 !== void 0 && !(Array.isArray(args2) && args2.every((a2) => typeof a2 === "string"))) return `server \`${name}\`: \`args\` must be a list of strings`;
159555
+ if (Object.keys(rest).length) return `server \`${name}\` takes only \`command\` and \`args\``;
159556
+ }
159557
+ return null;
159558
+ }
159559
+ function formatStudioProblem({ file: file3, line, column, reason, hint: hint2 }) {
159560
+ const location = line === void 0 ? file3 : `${file3}:${line}:${column ?? 1}`;
159561
+ return `${location}: ${reason}${hint2 ? `. ${hint2}` : ""}`;
159562
+ }
159563
+ function checkStudioFiles(value, official = false, checks = {}) {
159564
+ const read6 = inspect(value, official, checks);
159565
+ const first = read6.problems[0];
159566
+ return first ? { ok: false, ...first, problems: read6.problems } : { ok: true, def: read6.def, files: read6.files };
159567
+ }
159568
+ function inspect(value, official, { allowLegacyPreviewCopy, allowLegacyLand } = {}) {
159569
+ const problems = [];
159570
+ const fail = (file3, reason, tooLarge = false) => {
159571
+ problems.push({ file: file3, reason, ...tooLarge ? { tooLarge } : {} });
159572
+ return { problems };
159573
+ };
159574
+ if (!value || typeof value !== "object" || Array.isArray(value)) return fail("files", "must be an object of path \u2192 text");
159575
+ const files = Object.assign(/* @__PURE__ */ Object.create(null), Object.fromEntries(Object.entries(value).filter(([file3]) => file3 !== VERSION_FILE && file3 !== PUBLICATION_FILE)));
159576
+ const entries = Object.entries(files);
159577
+ if (entries.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
159578
+ let total = 0;
159579
+ const skills = /* @__PURE__ */ new Set();
159580
+ const paths = new Map([VERSION_FILE, PUBLICATION_FILE].map((file3) => [file3, { path: file3, file: true }]));
159581
+ const pathProblem = (file3, reason) => problems.push({ file: file3, reason, code: "studio-path", hint: "Use a safe relative file path unique within the Studio." });
159582
+ for (const [file3, text4] of entries) {
159583
+ if (typeof text4 !== "string" || text4.includes("\0")) {
159584
+ fail(file3, "is not a text file");
159585
+ continue;
159586
+ }
159587
+ let size;
159588
+ try {
159589
+ size = studioFileBody(file3, text4).bytes.length;
159590
+ } catch {
159591
+ fail(file3, "is not valid UTF-8");
159592
+ continue;
159593
+ }
159594
+ total += size;
159595
+ const limit = studioSizeProblem(file3, size, total);
159596
+ if (limit) return fail(limit.file, limit.reason, true);
159597
+ if (!safeStudioPath(file3)) {
159598
+ pathProblem(file3, "Unsafe Studio path");
159599
+ continue;
159600
+ }
159601
+ const parts = file3.split("/");
159602
+ for (let i = 1; i <= parts.length; i++) {
159603
+ const at2 = parts.slice(0, i).join("/");
159604
+ const key = at2.normalize("NFC").toLowerCase();
159605
+ const prior = paths.get(key);
159606
+ if (prior && (prior.path !== at2 || prior.file || i === parts.length)) {
159607
+ pathProblem(file3, "Path conflicts with " + prior.path);
159608
+ break;
159609
+ }
159610
+ paths.set(key, { path: at2, file: i === parts.length });
159611
+ }
159612
+ if (file3.toLowerCase() === STUDIO_CATALOG_FILE && (!official || file3 !== STUDIO_CATALOG_FILE)) {
159613
+ pathProblem(file3, "The root catalog.json is reserved for official Studio metadata");
159614
+ }
159615
+ if (file3 === MCP_FILE) {
159616
+ const problem2 = official ? mcpProblem(text4) : "MCP servers are available to official Studios";
159617
+ if (problem2) fail(file3, problem2);
159618
+ }
159619
+ if (parts[0] === "skills") {
159620
+ const name = parts[1];
159621
+ if (parts.length < 3 || !name || !SKILL_NAME.test(name) || name.length > 64) {
159622
+ pathProblem(file3, "Expected skills/<name>/<path> with a valid Agent Skills name");
159623
+ } else skills.add(name);
159624
+ }
159625
+ }
159626
+ for (const name of skills) {
159627
+ const file3 = skillFile(name);
159628
+ const text4 = files[file3];
159629
+ const problem2 = text4 === void 0 ? "SKILL.md is missing" : typeof text4 === "string" ? skillMetadata(text4, name) : null;
159630
+ if (typeof problem2 === "string") problems.push({
159631
+ file: file3,
159632
+ line: 1,
159633
+ column: 1,
159634
+ code: "studio-skill",
159635
+ message: problem2,
159636
+ reason: problem2,
159637
+ hint: "Follow the Agent Skills specification at https://agentskills.io/specification."
159638
+ });
159639
+ }
159640
+ const source2 = files[STUDIO_FILE];
159641
+ const read6 = typeof source2 === "string" ? parseStudioFile("studio", source2, STUDIO_FILE, { requirePreviewCopy: !official && !allowLegacyPreviewCopy, requireLand: !allowLegacyLand }) : null;
159642
+ if (!read6) fail(STUDIO_FILE, "is missing");
159643
+ else if ("problem" in read6) for (const problem2 of read6.problems) problems.push({ ...problem2, reason: problem2.message });
159644
+ if (!read6 || "problem" in read6) return { problems };
159645
+ const def = read6.def;
159646
+ for (const [file3, text4] of Object.entries(files)) {
159647
+ if (typeof text4 !== "string" || !file3.endsWith(".md")) continue;
159648
+ const masked = withoutCode(text4);
159649
+ const reference = (offset, link, message) => problems.push({ file: file3, ...sourcePosition(text4, offset), path: link, code: "studio-reference", message, reason: message, hint: "Use an existing safe relative resource or a shipped AKB Guide." });
159650
+ for (const match of masked.matchAll(/!?\[[^\]]*\]\((<[^>\r\n]+>|[^\s)]+)(?:\s+[^)]*)?\)/g)) {
159651
+ const link = match[1].replace(/^<|>$/g, "");
159652
+ if (/^(?:https?:|mailto:|#)/i.test(link)) continue;
159653
+ let decoded;
159654
+ try {
159655
+ decoded = decodeURIComponent(link.split(/[?#]/)[0]);
159656
+ } catch {
159657
+ reference(match.index, link, "Invalid resource URL");
159658
+ continue;
159659
+ }
159660
+ if (/^(?:[a-z][\w+.-]*:|[/\\])|\\/i.test(decoded) || decoded.split("/").includes("..")) {
159661
+ reference(match.index, link, "Unsafe resource path");
159662
+ continue;
159663
+ }
159664
+ const target = [...file3.split("/").slice(0, -1), ...decoded.split("/").filter((p2) => p2 !== ".")].join("/");
159665
+ if (!Object.hasOwn(files, target)) reference(match.index, link, `Missing resource ${target}`);
159666
+ }
159667
+ for (const match of text4.matchAll(/akb guide ([a-z][a-z-]*)/g)) if (!GUIDE_TOPICS.includes(match[1])) reference(match.index, match[1], `Unknown AKB Guide ${match[1]}`);
159668
+ }
159669
+ return { problems, def, files };
159670
+ }
159671
+ function previewCatalog(files) {
159672
+ const read6 = parseStudioFile("studio", files[STUDIO_FILE] ?? "", STUDIO_FILE);
159673
+ if ("problem" in read6) throw new Error(read6.problem);
159674
+ return read6.def.previews;
159675
+ }
159676
+
159677
+ // ../cli/src/lib/shared/studio-package.ts
159678
+ var LOCAL = 30;
159679
+ var CENTRAL = 46;
159680
+ var END = 22;
159681
+ var UTF8 = 2048;
159682
+ var encoder2 = new TextEncoder();
159683
+ var decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
159684
+ var crcTable = Uint32Array.from({ length: 256 }, (_2, byte) => {
159685
+ for (let bit = 0; bit < 8; bit++) byte = byte >>> 1 ^ (byte & 1 ? 3988292384 : 0);
159686
+ return byte;
159687
+ });
159688
+ function crc32(bytes) {
159689
+ let crc = -1;
159690
+ for (const byte of bytes) crc = crc >>> 8 ^ crcTable[(crc ^ byte) & 255];
159691
+ return (crc ^ -1) >>> 0;
159692
+ }
159693
+ var STUDIO_ZIP_LIMIT = FILE_LIMITS.total + FILE_LIMITS.count * (LOCAL + CENTRAL + 2 * FILE_LIMITS.path) + END;
159694
+ var isDigest = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
159695
+ var validPath = (name) => name !== VERSION_FILE && safeStudioPath(name);
159696
+ function encodeStudioZip(files) {
159697
+ const names2 = Object.keys(files).sort();
159698
+ if (!names2.length || names2.length > FILE_LIMITS.count || names2.some((name) => !validPath(name))) throw Error("Invalid Studio ZIP paths.");
159699
+ const entries = names2.map((name) => ({ name: encoder2.encode(name), ...studioFileBody(name, files[name]) }));
159700
+ let expandedBytes = 0, localBytes = 0, directoryBytes = 0;
159701
+ for (const { name, bytes } of entries) {
159702
+ expandedBytes += bytes.length;
159703
+ localBytes += LOCAL + name.length + bytes.length;
159704
+ directoryBytes += CENTRAL + name.length;
159705
+ if (bytes.length > FILE_LIMITS.file) throw Error("A Studio file exceeds 2 MiB.");
159706
+ }
159707
+ if (!expandedBytes || expandedBytes > FILE_LIMITS.total) throw Error("Invalid Studio size. The package limit is 10 MiB.");
159708
+ const zip = new Uint8Array(localBytes + directoryBytes + END);
159709
+ const view = new DataView(zip.buffer);
159710
+ const u16 = (at2, value) => view.setUint16(at2, value, true);
159711
+ const u32 = (at2, value) => view.setUint32(at2, value, true);
159712
+ let local = 0, central = localBytes;
159713
+ for (const { name, bytes, binary } of entries) {
159714
+ const sum = crc32(bytes);
159715
+ u32(local, 67324752);
159716
+ u16(local + 4, 20);
159717
+ u16(local + 6, UTF8);
159718
+ u16(local + 12, 33);
159719
+ u32(local + 14, sum);
159720
+ u32(local + 18, bytes.length);
159721
+ u32(local + 22, bytes.length);
159722
+ u16(local + 26, name.length);
159723
+ zip.set(name, local + LOCAL);
159724
+ zip.set(bytes, local + LOCAL + name.length);
159725
+ u32(central, 33639248);
159726
+ u16(central + 4, 20);
159727
+ u16(central + 6, 20);
159728
+ u16(central + 8, UTF8);
159729
+ u16(central + 14, 33);
159730
+ u32(central + 16, sum);
159731
+ u32(central + 20, bytes.length);
159732
+ u32(central + 24, bytes.length);
159733
+ u16(central + 28, name.length);
159734
+ u16(central + 36, binary ? 0 : 1);
159735
+ u32(central + 42, local);
159736
+ zip.set(name, central + CENTRAL);
159737
+ local += LOCAL + name.length + bytes.length;
159738
+ central += CENTRAL + name.length;
159739
+ }
159740
+ u32(central, 101010256);
159741
+ u16(central + 8, entries.length);
159742
+ u16(central + 10, entries.length);
159743
+ u32(central + 12, directoryBytes);
159744
+ u32(central + 16, localBytes);
159745
+ return { zip, expandedBytes };
159746
+ }
159747
+ function decodeStudioZip(zip) {
159748
+ const invalid2 = () => Error("Invalid Studio ZIP.");
159749
+ if (zip.length < END || zip.length > STUDIO_ZIP_LIMIT) throw invalid2();
159750
+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
159751
+ const u16 = (at2) => view.getUint16(at2, true);
159752
+ const u32 = (at2) => view.getUint32(at2, true);
159753
+ const end2 = zip.length - END;
159754
+ const count3 = u16(end2 + 10);
159755
+ let central = u32(end2 + 16), local = 0, total = 0, previous = "";
159756
+ const start = central;
159757
+ if (u32(end2) !== 101010256 || !count3 || count3 > FILE_LIMITS.count || start > end2) throw invalid2();
159758
+ const files = [];
159759
+ for (let index = 0; index < count3; index++) {
159760
+ if (central + CENTRAL > end2 || local + LOCAL > start) throw invalid2();
159761
+ const length = u16(central + 28), size = u32(central + 24);
159762
+ const from = local + LOCAL + length;
159763
+ total += size;
159764
+ if (central + CENTRAL + length > end2 || from + size > start || size > FILE_LIMITS.file || total > FILE_LIMITS.total) throw invalid2();
159765
+ const name = decoder.decode(zip.subarray(central + CENTRAL, central + CENTRAL + length));
159766
+ if (!validPath(name) || name <= previous) throw invalid2();
159767
+ const bytes = zip.subarray(from, from + size);
159768
+ const binary = u16(central + 36) === 0;
159769
+ if (binary && !(name.startsWith("screenshots/") && isAboutFile(name))) throw invalid2();
159770
+ let text4 = "";
159771
+ if (binary) {
159772
+ for (let at2 = 0; at2 < bytes.length; at2 += 32768) text4 += String.fromCharCode(...bytes.subarray(at2, at2 + 32768));
159773
+ text4 = studioScreenshotPrefix(name) + btoa(text4);
159774
+ } else {
159775
+ text4 = decoder.decode(bytes);
159776
+ if (text4.includes("\0")) throw invalid2();
159777
+ }
159778
+ files.push([name, text4]);
159779
+ previous = name;
159780
+ central += CENTRAL + length;
159781
+ local = from + size;
159782
+ }
159783
+ const result = Object.fromEntries(files);
159784
+ const canonical = encodeStudioZip(result).zip;
159785
+ if (canonical.length !== zip.length || !canonical.every((byte, i) => zip[i] === byte)) throw invalid2();
159786
+ return result;
159787
+ }
159788
+ async function readStudioDownload(response, size) {
159789
+ if (!response.body || Number(response.headers.get("content-length")) !== size) throw Error("Invalid Studio package length.");
159790
+ const reader = response.body.getReader();
159791
+ const bytes = new Uint8Array(size);
159792
+ let offset = 0;
159793
+ try {
159794
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
159795
+ if (offset + chunk.value.length > size) throw Error("Invalid Studio package length.");
159796
+ bytes.set(chunk.value, offset);
159797
+ offset += chunk.value.length;
159798
+ }
159799
+ if (offset !== size) throw Error("Incomplete Studio package.");
159800
+ return bytes;
159801
+ } finally {
159802
+ await reader.cancel().catch(() => {
159803
+ });
159804
+ }
159805
+ }
159806
+
159148
159807
  // ../cli/src/lib/shared/goal.ts
159149
159808
  function goalRoute(discussion, goal) {
159150
159809
  return `/v1/discussions/${encodeURIComponent(discussion)}/goals/${encodeURIComponent(goal)}`;
@@ -159373,23 +160032,23 @@ async function request(method, route, body, signedIn = true) {
159373
160032
  return sent.ok ? answerOf(sent.value) : sent;
159374
160033
  }
159375
160034
  var FILE_TIMEOUT_MS = 10 * 6e4;
159376
- async function download(route) {
159377
- const sent = await send("GET", route, void 0, true, FILE_TIMEOUT_MS);
160035
+ async function download(route, studioBytes) {
160036
+ const sent = await send("GET", route, void 0, true, studioBytes === void 0 ? FILE_TIMEOUT_MS : 45e3);
159378
160037
  if (!sent.ok) return sent;
159379
160038
  if (!sent.value.ok) return answerOf(sent.value);
159380
160039
  try {
159381
- return { ok: true, value: new Uint8Array(await sent.value.arrayBuffer()) };
160040
+ return { ok: true, value: studioBytes === void 0 ? new Uint8Array(await sent.value.arrayBuffer()) : await readStudioDownload(sent.value, studioBytes) };
159382
160041
  } catch (e2) {
159383
160042
  return { ok: false, error: e2 instanceof Error ? e2.message : String(e2) };
159384
160043
  }
159385
160044
  }
159386
- async function upload(route, bytes2, type) {
159387
- const sent = await send("PUT", route, bytes2, true, FILE_TIMEOUT_MS, type);
160045
+ async function upload(route, bytes, type) {
160046
+ const sent = await send("PUT", route, bytes, true, FILE_TIMEOUT_MS, type);
159388
160047
  return sent.ok ? answerOf(sent.value) : sent;
159389
160048
  }
159390
- async function uploadReplyImage(machine, job, key, bytes2, mime) {
160049
+ async function uploadReplyImage(machine, job, key, bytes, mime) {
159391
160050
  const route = `/v1/runner/jobs/${encodeURIComponent(job)}/images/${key}?machine=${encodeURIComponent(machine)}`;
159392
- const sent = await send("PUT", route, bytes2, true, 9e4, mime);
160051
+ const sent = await send("PUT", route, bytes, true, 9e4, mime);
159393
160052
  return sent.ok ? answerOf(sent.value) : sent;
159394
160053
  }
159395
160054
  var register = (r2) => request("POST", "/v1/runner", { ...r2, secrets: secretsSet(), protocol: PROTOCOL, akbContract: AKB_CONTRACT });
@@ -159796,7 +160455,7 @@ import fs23 from "node:fs";
159796
160455
  import path25 from "node:path";
159797
160456
 
159798
160457
  // src/codex-native.ts
159799
- import crypto2 from "node:crypto";
160458
+ import crypto3 from "node:crypto";
159800
160459
  import diagnosticsChannel from "node:diagnostics_channel";
159801
160460
  import fs22 from "node:fs";
159802
160461
  import os6 from "node:os";
@@ -159850,13 +160509,13 @@ var CODEX_TIMEOUT = 1e4;
159850
160509
  var nativeDirectory = () => path24.join(runnerCwd(), "codex-native");
159851
160510
  var codexRecordFile = () => path24.join(nativeDirectory(), "runner.json");
159852
160511
  var backendFile = (key) => path24.join(nativeDirectory(), `${key}.json`);
159853
- var leaseFile = (backend, thread) => path24.join(nativeDirectory(), "threads", backend.instance, `${crypto2.createHash("sha256").update(thread).digest("hex")}.json`);
160512
+ var leaseFile = (backend, thread) => path24.join(nativeDirectory(), "threads", backend.instance, `${crypto3.createHash("sha256").update(thread).digest("hex")}.json`);
159854
160513
  var liveBackend = (backend) => !connectionStopped(backend);
159855
160514
  var liveLease = (lease) => !connectionStopped(lease);
159856
160515
  var processIdentity = () => ({ pid: process.pid, identity: connectionIdentity(process.pid) });
159857
160516
  function writePrivate(file3, value) {
159858
160517
  fs22.mkdirSync(path24.dirname(file3), { recursive: true, mode: 448 });
159859
- const temporary = `${file3}.${crypto2.randomUUID()}.tmp`;
160518
+ const temporary = `${file3}.${crypto3.randomUUID()}.tmp`;
159860
160519
  fs22.writeFileSync(temporary, JSON.stringify(value), { mode: 384 });
159861
160520
  fs22.renameSync(temporary, file3);
159862
160521
  }
@@ -159869,10 +160528,10 @@ function readPrivate(file3) {
159869
160528
  }
159870
160529
  }
159871
160530
  function nativeEndpoint(key) {
159872
- const directory3 = path24.join(os6.tmpdir(), `wc-codex-${crypto2.createHash("sha256").update(runnerCwd()).digest("hex").slice(0, 12)}`);
160531
+ const directory3 = path24.join(os6.tmpdir(), `wc-codex-${crypto3.createHash("sha256").update(runnerCwd()).digest("hex").slice(0, 12)}`);
159873
160532
  fs22.mkdirSync(directory3, { recursive: true, mode: 448 });
159874
160533
  fs22.chmodSync(directory3, 448);
159875
- return `unix://${path24.join(directory3, `${key.slice(0, 12)}-${crypto2.randomBytes(6).toString("hex")}.sock`)}`;
160534
+ return `unix://${path24.join(directory3, `${key.slice(0, 12)}-${crypto3.randomBytes(6).toString("hex")}.sock`)}`;
159876
160535
  }
159877
160536
  function nativeErrorText(error62) {
159878
160537
  if (!error62) return "";
@@ -160547,143 +161206,11 @@ import { execFile } from "node:child_process";
160547
161206
  import fs35 from "node:fs";
160548
161207
  import path37 from "node:path";
160549
161208
 
160550
- // src/akb.ts
160551
- import { spawn as spawn3 } from "node:child_process";
160552
- import fs26 from "node:fs";
160553
- import path28 from "node:path";
160554
- import { fileURLToPath, pathToFileURL } from "node:url";
160555
- var akbHome = () => path28.join(runnerHome(), "bin", "akb");
160556
- var BUNDLED_SHIM = `bundled-${AKB_VERSION}`;
160557
- var HERE = path28.dirname(fileURLToPath(import.meta.url));
160558
- function akbArgs(entry, dist = HERE) {
160559
- const preload = path28.join(dist, "akb-proxy.mjs");
160560
- return fs26.existsSync(preload) ? ["--import", pathToFileURL(preload).href, entry] : [entry];
160561
- }
160562
- var bundledAkb = (dist = HERE) => ({
160563
- command: process.execPath,
160564
- args: akbArgs(path28.join(dist, "akb", "bin", "ai4kanban.mjs"), dist),
160565
- version: AKB_VERSION,
160566
- canonicalCommands: true,
160567
- shim: path28.join(akbHome(), BUNDLED_SHIM)
160568
- });
160569
- var quote = (s) => /^[\w./:@=-]+$/.test(s) ? s : `"${s}"`;
160570
- function shimDir(akb) {
160571
- const dir = akb.shim;
160572
- const line = [akb.command, ...akb.args].map(quote).join(" ");
160573
- const [file3, text4] = process.platform === "win32" ? [path28.join(dir, "akb.cmd"), `@${line} %*\r
160574
- `] : [path28.join(dir, "akb"), `#!/bin/sh
160575
- exec ${line} "$@"
160576
- `];
160577
- if (process.platform === "win32") {
160578
- fs26.mkdirSync(dir, { recursive: true });
160579
- const shellLine = [akb.command, ...akb.args].map((s) => `'${s.replaceAll("\\", "/").replaceAll("'", "'\\''")}'`).join(" ");
160580
- fs26.writeFileSync(path28.join(dir, "akb"), `#!/bin/sh
160581
- exec ${shellLine} "$@"
160582
- `, { mode: 493 });
160583
- }
160584
- try {
160585
- if (fs26.readFileSync(file3, "utf8") === text4) return dir;
160586
- } catch {
160587
- }
160588
- fs26.mkdirSync(dir, { recursive: true });
160589
- fs26.writeFileSync(file3, text4, { mode: 493 });
160590
- return dir;
160591
- }
160592
- function akbEnv(akb, board, task, language2, base = process.env) {
160593
- const env2 = {};
160594
- const dropped = ["AI4KANBAN_PREVIEW_BRIDGE", "AI4KANBAN_REPLY_APPROVAL", "AI4KANBAN_BOARD", "AI4KANBAN_TASK", "AI4KANBAN_EXECUTION", "AI4KANBAN_SCHEDULED_AGENTS", LANGUAGE_ENV, SESSION_COST_ENV, EXECUTION_RUNTIMES_ENV];
160595
- for (const [k2, v] of Object.entries({ ...proxyEnv(), ...base })) if (!k2.startsWith("KANBAN_") && !dropped.includes(k2)) env2[k2] = v;
160596
- const key = Object.keys(env2).find((k2) => k2.toUpperCase() === "PATH") ?? "PATH";
160597
- env2[key] = [shimDir(akb), env2[key]].filter(Boolean).join(path28.delimiter);
160598
- if (Object.keys(proxyEnv()).some((k2) => !/^no_proxy$/i.test(k2)) && env2.NODE_USE_ENV_PROXY === void 0) env2.NODE_USE_ENV_PROXY = "1";
160599
- env2[HOST_PROXY_ENV] = JSON.stringify(hostProxy());
160600
- env2.AI4KANBAN_COMMAND = "akb";
160601
- if (board) env2.AI4KANBAN_BOARD = board;
160602
- if (task) env2.AI4KANBAN_TASK = task;
160603
- if (language2 !== void 0) env2[LANGUAGE_ENV] = language2 ?? "";
160604
- return env2;
160605
- }
160606
- var KEEP = 256 * 1024;
160607
- function compatibleArgs(akb, args2) {
160608
- if (akb.canonicalCommands) return args2;
160609
- const [group, verb, ...rest] = args2;
160610
- if (group === "run" || group === "delivery") return ["raw", ...args2];
160611
- if (group === "task" && verb && ["refine", "revise", "resolve", "implement"].includes(verb)) return ["raw", "card", verb, ...rest];
160612
- if (group === "memory" && verb === "describe-project") return ["raw", verb, ...rest];
160613
- if (group === "memory" && verb === "review") return ["raw", ...args2];
160614
- return args2;
160615
- }
160616
- function runAkb(akb, args2, opts) {
160617
- return new Promise((resolve2) => {
160618
- let out = "";
160619
- let last2 = "";
160620
- const note = (text4) => {
160621
- const line = text4.split("\n").map((l2) => l2.trim()).filter(Boolean).at(-1);
160622
- if (line) last2 = line;
160623
- };
160624
- let child;
160625
- try {
160626
- child = spawn3(akb.command, [...akb.args, ...compatibleArgs(akb, args2)], { cwd: opts.cwd, env: { ...akbEnv(akb, opts.board, opts.task, opts.language), ...opts.env }, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
160627
- } catch (e2) {
160628
- return resolve2({ code: null, out: "", last: e2 instanceof Error ? e2.message : String(e2) });
160629
- }
160630
- opts.track?.(child);
160631
- child.stdout.setEncoding("utf8");
160632
- child.stderr.setEncoding("utf8");
160633
- child.stdout.on("data", (chunk) => {
160634
- out = (out + chunk).slice(-KEEP);
160635
- note(chunk);
160636
- opts.show?.(chunk);
160637
- });
160638
- child.stderr.on("data", (chunk) => {
160639
- note(chunk);
160640
- opts.show?.(chunk);
160641
- });
160642
- child.on("error", (e2) => resolve2({ code: null, out, last: e2.message }));
160643
- child.on("close", (code) => resolve2({ code, out, last: last2 }));
160644
- });
160645
- }
160646
- function answerOf2(ran) {
160647
- const line = ran.out.trim().split("\n").at(-1) ?? "";
160648
- try {
160649
- return JSON.parse(line);
160650
- } catch {
160651
- return null;
160652
- }
160653
- }
160654
-
160655
- // ../cli/src/lib/shared/board-conflicts.ts
160656
- var import_yaml8 = __toESM(require_dist(), 1);
160657
-
160658
- // ../cli/src/lib/agents/shared-memory.ts
160659
- import fs31 from "node:fs";
160660
- import path33 from "node:path";
160661
-
160662
161209
  // ../cli/src/lib/agent/cloud-studios.ts
160663
- import fs30 from "node:fs";
160664
- import path32 from "node:path";
160665
-
160666
- // ../cli/src/lib/yaml.ts
160667
- function yamlScalar(s) {
160668
- const text4 = String(s);
160669
- if (text4 === "") return '""';
160670
- if (/^[-?:,[\]{}#&*!|>'"%@`]/.test(text4) || /:\s/.test(text4) || /[\n"]/.test(text4) || /^\s|\s$/.test(text4)) {
160671
- return JSON.stringify(text4);
160672
- }
160673
- return text4;
160674
- }
160675
- function unquote(v) {
160676
- const text4 = String(v).trim();
160677
- if (text4.startsWith('"') && text4.endsWith('"')) {
160678
- try {
160679
- return JSON.parse(text4);
160680
- } catch {
160681
- return text4.slice(1, -1);
160682
- }
160683
- }
160684
- if (text4.startsWith("'") && text4.endsWith("'")) return text4.slice(1, -1);
160685
- return text4;
160686
- }
161210
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
161211
+ import { setTimeout as delay2 } from "node:timers/promises";
161212
+ import fs29 from "node:fs";
161213
+ import path31 from "node:path";
160687
161214
 
160688
161215
  // ../cli/src/lib/question-block.ts
160689
161216
  var MODES = ["single", "multi"];
@@ -160971,475 +161498,53 @@ function cardFront(body) {
160971
161498
  }
160972
161499
 
160973
161500
  // ../official/pack.ts
160974
- import crypto3 from "node:crypto";
160975
- import fs28 from "node:fs";
160976
- import path30 from "node:path";
160977
- import { fileURLToPath as fileURLToPath2 } from "node:url";
160978
-
160979
- // ../cli/src/lib/agent/studio-def.ts
160980
- var import_ajv = __toESM(require_ajv(), 1);
160981
- var import_yaml3 = __toESM(require_dist(), 1);
160982
-
160983
- // ../cli/src/lib/agents/icon.ts
160984
- var ICON_NAMES = [
160985
- "file",
160986
- "text",
160987
- "article",
160988
- "outline",
160989
- "script",
160990
- "prompt",
160991
- "email",
160992
- "image",
160993
- "post-image",
160994
- "social-image",
160995
- "cover",
160996
- "carousel",
160997
- "carousel-outline",
160998
- "slides",
160999
- "wireframe",
161000
- "screen",
161001
- "video",
161002
- "storyboard",
161003
- "template",
161004
- "shots",
161005
- "api",
161006
- "schema",
161007
- "compare",
161008
- "stack",
161009
- "studio",
161010
- "code",
161011
- "checklist",
161012
- "card",
161013
- "plan",
161014
- "proposal",
161015
- "dismissed",
161016
- "inbox",
161017
- "notebook",
161018
- "squeeze",
161019
- "folder",
161020
- "reply",
161021
- "feedback",
161022
- "software",
161023
- "product-video",
161024
- "social-post",
161025
- "blog",
161026
- "deck",
161027
- "video-clone",
161028
- "studio-kit"
161029
- ];
161030
- var ICON_COLORS = ["k", "w", "c", "g", "o", "p", "s", "m", "l", "r", "y"];
161031
- var PATH = /^[MmLlHhVvCcSsQqTtAaZz0-9.,\s-]+$/;
161032
- var isColor = (v) => ICON_COLORS.includes(v);
161033
- function readIcon(raw) {
161034
- if (raw === void 0 || raw === "") return void 0;
161035
- if (typeof raw === "string") return ICON_NAMES.includes(raw.trim()) ? raw.trim() : { problem: `"${raw}" is not a glyph name` };
161036
- if (!Array.isArray(raw) || !raw.length || raw.length > 12) return { problem: "the value is neither a glyph name nor a list of 1 to 12 parts" };
161037
- const parts = [];
161038
- for (const [i, item] of raw.entries()) {
161039
- const at2 = `part ${i + 1}`;
161040
- if (!item || typeof item !== "object" || Array.isArray(item)) return { problem: `${at2} is not a map of \`d\`, \`f\`, \`o\`, \`s\`, \`w\`` };
161041
- const { d: d2, f: f2, o: o3, s, w: w2, ...extra } = item;
161042
- if (Object.keys(extra).length) return { problem: `${at2} has \`${Object.keys(extra).join("`, `")}\`` };
161043
- if (typeof d2 !== "string" || !PATH.test(d2)) return { problem: `${at2} has no \`d\` of SVG path commands and numbers` };
161044
- const part = { d: d2.trim() };
161045
- for (const [key, value] of [["f", f2], ["s", s]]) {
161046
- if (value === void 0) continue;
161047
- if (typeof value !== "string" || !isColor(value)) return { problem: `${at2} colours \`${key}\` with "${String(value)}"` };
161048
- part[key] = value;
161049
- }
161050
- if (o3 !== void 0) {
161051
- if (o3 !== "true") return { problem: `${at2} has \`o: ${String(o3)}\`, not \`true\`` };
161052
- part.o = true;
161053
- }
161054
- if (w2 !== void 0) {
161055
- const width = typeof w2 === "string" ? Number(w2) : NaN;
161056
- if (!(width > 0 && width <= 3)) return { problem: `${at2} has \`w: ${String(w2)}\`, not above 0 and up to 3` };
161057
- part.w = width;
161058
- }
161059
- parts.push(part);
161060
- }
161061
- return parts;
161062
- }
161063
-
161064
- // ../cli/src/lib/shared/preview-blocks.ts
161065
- var PREVIEW_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
161066
- function sourcePosition(source2, offset) {
161067
- const before = source2.slice(0, offset);
161068
- return { line: before.split("\n").length, column: offset - before.lastIndexOf("\n") };
161069
- }
161070
- function withoutCode(source2) {
161071
- const blank2 = (s) => s.replace(/[^\n\r]/g, " ");
161072
- let fence;
161073
- let indented = false, afterBlank = true, inList = false;
161074
- return source2.split(/(?<=\n)/).map((line) => {
161075
- const marker = /^ {0,3}(`{3,}|~{3,})(.*)/.exec(line);
161076
- if (fence) {
161077
- if (marker && marker[1][0] === fence.char && marker[1].length >= fence.length && !marker[2].trim()) fence = void 0;
161078
- return blank2(line);
161079
- }
161080
- if (marker) {
161081
- fence = { char: marker[1][0], length: marker[1].length };
161082
- return blank2(line);
161083
- }
161084
- if (!line.trim()) {
161085
- afterBlank = true;
161086
- return line;
161087
- }
161088
- const hasIndent = /^(?: {4}|\t)/.test(line);
161089
- if (!hasIndent) indented = false;
161090
- if (/^ {0,3}(?:[-+*]|\d+[.)])\s/.test(line)) inList = true;
161091
- else if (/^\S/.test(line)) inList = false;
161092
- if (hasIndent && (indented || afterBlank && !inList)) {
161093
- indented = true;
161094
- return blank2(line);
161095
- }
161096
- afterBlank = false;
161097
- return line;
161098
- }).join("").replace(/(`+)([^]*?)\1(?!`)/g, blank2);
161099
- }
161100
- function agentSectionOffset(source2) {
161101
- return /^<!--[ \t]*agent[ \t]*-->/m.exec(withoutCode(source2))?.index ?? source2.length;
161102
- }
161103
- function parsePreviewBlocks(source2, file3 = "STUDIO.md") {
161104
- const blocks = [], problems = [];
161105
- const masked = withoutCode(source2);
161106
- let open2;
161107
- const seen = /* @__PURE__ */ new Set();
161108
- const fail = (offset, id2, code, message, hint2) => problems.push({ file: file3, ...sourcePosition(source2, offset), path: id2 ? `previews.${id2}` : "previews", code, message, hint: hint2 });
161109
- for (const tag of masked.matchAll(/<\/?Preview\b[^>]*(?:>|$)/g)) {
161110
- const offset = tag.index, text4 = tag[0];
161111
- const closing = /^<\/Preview\s*>$/.test(text4);
161112
- if (closing) {
161113
- if (!open2) fail(offset, "", "preview-unexpected-close", "Preview has no opening tag", "Remove it or restore its opening tag.");
161114
- else {
161115
- const instructions = source2.slice(open2.content, offset).trim();
161116
- if (!instructions) fail(open2.start, open2.id, "preview-empty", `Preview ${open2.id} is empty`, "Describe the requested output inside the block.");
161117
- blocks.push({ id: open2.id, instructions, start: open2.start, end: offset + text4.length });
161118
- open2 = void 0;
161119
- }
161120
- continue;
161121
- }
161122
- const opening = /^<Preview\s+id=(?:"([^"]*)"|'([^']*)')\s*>$/.exec(text4);
161123
- if (!opening || open2) {
161124
- fail(offset, open2?.id ?? "", "preview-tag", "Malformed or nested Preview tag", 'Use one non-nested <Preview id="stable-id"> block with only id.');
161125
- continue;
161126
- }
161127
- const id2 = opening[1] ?? opening[2];
161128
- if (!PREVIEW_ID.test(id2) || seen.has(id2)) fail(offset, id2, "preview-id", `Invalid or repeated Preview ID ${id2}`, "Use a unique lowercase ID with digits and dashes.");
161129
- seen.add(id2);
161130
- open2 = { id: id2, start: offset, content: offset + text4.length };
161131
- }
161132
- if (open2) fail(open2.start, open2.id, "preview-unclosed", `Preview ${open2.id} is not closed`, "Add </Preview> after this block.");
161133
- return { blocks, problems };
161134
- }
161135
-
161136
- // ../cli/src/lib/agent/studio-def.ts
161137
- var STUDIO_ID = PREVIEW_ID;
161138
- var titles = { type: "object", minProperties: 1, propertyNames: { pattern: "^[a-z]{2,3}(?:-[A-Za-z0-9]+)*$" }, additionalProperties: { type: "string", minLength: 1, pattern: "\\S" } };
161139
- var icon = { anyOf: [
161140
- { type: "string", enum: ICON_NAMES },
161141
- { type: "array", minItems: 1, maxItems: 12, items: { type: "object", required: ["d"], additionalProperties: false, properties: {
161142
- d: { type: "string", minLength: 1, pattern: "^[MmLlHhVvCcSsQqTtAaZz0-9.,\\s-]+$" },
161143
- f: { enum: ICON_COLORS },
161144
- o: { const: true },
161145
- s: { enum: ICON_COLORS },
161146
- w: { type: "number", exclusiveMinimum: 0, maximum: 3 }
161147
- } } }
161148
- ] };
161149
- var STUDIO_SCHEMA = {
161150
- type: "object",
161151
- required: ["name"],
161152
- additionalProperties: false,
161153
- properties: {
161154
- name: { type: "string", minLength: 1, pattern: "\\S" },
161155
- names: titles,
161156
- description: { type: "string" },
161157
- summaries: titles,
161158
- entrypoints: { type: "array", minItems: 1, maxItems: 10, uniqueItems: true, items: { type: "string", pattern: PREVIEW_ID.source } },
161159
- needsArtifact: { type: "boolean" },
161160
- icon,
161161
- previews: { type: "object", propertyNames: { pattern: PREVIEW_ID.source }, additionalProperties: {
161162
- type: "object",
161163
- additionalProperties: false,
161164
- properties: { title: titles, description: titles, icon }
161165
- } }
161166
- }
161167
- };
161168
- var validate = new import_ajv.Ajv({ allErrors: true, meta: false, validateSchema: false }).compile(STUDIO_SCHEMA);
161169
- var comments = /<!--[^]*?(?:-->|$)/g;
161170
- var blank = (text4) => text4.replace(/[^\r\n]/g, " ");
161171
- var headingsOf = (body) => [...withoutCode(body).replace(comments, blank).matchAll(/^ {0,3}#{1,2}(?=[ \t\r\n]|$)[^\r\n]*/gm)];
161172
- function studioSetup(body) {
161173
- const headings = headingsOf(body);
161174
- const index = headings.findIndex((h3) => /^ {0,3}##[ \t]+Setup(?:[ \t]+#+)?[ \t]*$/.test(body.slice(h3.index, h3.index + h3[0].length)));
161175
- if (index === -1) return "";
161176
- const heading = headings[index];
161177
- const section = body.slice(heading.index + heading[0].length, headings[index + 1]?.index).trim();
161178
- return section.replace(comments, "").trim() ? section : "";
161179
- }
161180
- function landSections(body, previews) {
161181
- let visible = "", at2 = 0;
161182
- for (const { start, end: end2 } of previews) {
161183
- visible += body.slice(at2, start) + blank(body.slice(start, end2));
161184
- at2 = end2;
161185
- }
161186
- visible += body.slice(at2);
161187
- const headings = headingsOf(visible);
161188
- return headings.flatMap((heading, index) => {
161189
- const start = heading.index;
161190
- const end2 = start + heading[0].length;
161191
- if (!/^ {0,3}##[ \t]+Land(?:[ \t]+#+)?[ \t]*$/.test(visible.slice(start, end2))) return [];
161192
- return [{
161193
- offset: start + heading[0].indexOf("#"),
161194
- empty: !visible.slice(end2, headings[index + 1]?.index).replace(comments, "").trim()
161195
- }];
161196
- });
161197
- }
161198
- function parseStudioFile(id2, source2, from, { requirePreviewCopy = false, requireLand = false } = {}) {
161199
- const problems = [];
161200
- const fail = (offset, path88, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source2, offset), path: path88, code, message, hint: hint2 });
161201
- const result = () => ({ problem: problems.map((p2) => `${p2.file}:${p2.line}:${p2.column} ${p2.path}: ${p2.code} \u2014 ${p2.message}. ${p2.hint}`).join("\n"), problems });
161202
- if (!STUDIO_ID.test(id2)) fail(0, "id", "studio-schema", `Invalid Studio ID ${id2}`, "Use lowercase letters, digits and dashes.");
161203
- const front = /^---\r?\n([^]*?)\r?\n---(?:\r?\n|$)/.exec(source2);
161204
- if (!front) {
161205
- fail(0, "", "yaml-syntax", "Missing YAML frontmatter", "Enclose metadata between --- lines.");
161206
- return result();
161207
- }
161208
- const metaOffset = source2.indexOf("\n") + 1, bodyOffset = front[0].length;
161209
- const counter = new import_yaml3.LineCounter();
161210
- const document = (0, import_yaml3.parseDocument)(front[1], { lineCounter: counter, uniqueKeys: true, strict: true });
161211
- for (const error62 of document.errors) fail(metaOffset + (error62.pos[0] ?? 0), "", error62.code === "DUPLICATE_KEY" ? "yaml-duplicate-key" : "yaml-syntax", error62.message.split("\n")[0], "Correct the indicated YAML location.");
161212
- if (problems.length) return result();
161213
- let raw;
161214
- try {
161215
- raw = document.toJS({ maxAliasCount: 0 });
161216
- } catch {
161217
- fail(metaOffset, "", "yaml-syntax", "YAML aliases are not supported", "Write metadata explicitly.");
161218
- return result();
161219
- }
161220
- if (!validate(raw)) {
161221
- for (const error62 of validate.errors ?? []) {
161222
- const parts = error62.instancePath.split("/").slice(1);
161223
- const key = error62.params.additionalProperty ?? error62.params.missingProperty;
161224
- if (key) parts.push(String(key));
161225
- const node2 = parts.length ? document.getIn(parts, true) : document.contents;
161226
- fail(metaOffset + (node2?.range?.[0] ?? 0), parts.join("."), "studio-schema", `${parts.join(".") || "metadata"} ${error62.message}`, "Use only Studio metadata and previews: {id: {title?, description?, icon?}} with the declared field types.");
161227
- }
161228
- }
161229
- const body = source2.slice(bodyOffset);
161230
- const parsed = parsePreviewBlocks(body, from);
161231
- problems.push(...parsed.problems.map((p2) => ({ ...p2, line: p2.line + source2.slice(0, bodyOffset).split("\n").length - 1 })));
161232
- if (problems.length) return result();
161233
- const map3 = raw.previews ?? {};
161234
- for (const block of parsed.blocks) if (!Object.hasOwn(map3, block.id)) fail(bodyOffset + block.start, `previews.${block.id}`, "preview-metadata-missing", `Preview ${block.id} has no metadata entry`, "Add the ID under previews, using {} if needed.");
161235
- for (const key of Object.keys(map3)) if (!parsed.blocks.some((b2) => b2.id === key)) fail(metaOffset + (document.getIn(["previews", key], true)?.range?.[0] ?? 0), `previews.${key}`, "preview-body-missing", `Preview ${key} has no body`, "Add its block or remove unused metadata.");
161236
- if (requirePreviewCopy) for (const block of parsed.blocks) {
161237
- const metadata = Object.hasOwn(map3, block.id) ? map3[block.id] : void 0;
161238
- if (!metadata) continue;
161239
- for (const field2 of ["title", "description"]) for (const lang of ["en", "zh"]) {
161240
- if (metadata[field2]?.[lang]) continue;
161241
- fail(
161242
- bodyOffset + block.start,
161243
- `previews.${block.id}.${field2}.${lang}`,
161244
- "preview-display-missing",
161245
- `Preview ${block.id} needs a ${lang} ${field2}`,
161246
- "Add non-blank en and zh display text in the Preview metadata."
161247
- );
161248
- }
161249
- }
161250
- if (requireLand) {
161251
- const sections = landSections(body, parsed.blocks);
161252
- if (!sections.length) fail(bodyOffset, "Land", "studio-land-missing", "Missing ## Land section", "Add ## Land to the Studio body and describe delivery, checks and what to record.");
161253
- for (const [index, { offset, empty }] of sections.entries()) {
161254
- if (index) fail(bodyOffset + offset, "Land", "studio-land-duplicate", "Repeated ## Land section", "Combine delivery instructions under one ## Land heading.");
161255
- if (empty) fail(bodyOffset + offset, "Land", "studio-land-empty", "The ## Land section is empty", "Describe delivery, checks and what to record under ## Land.");
161256
- }
161257
- }
161258
- if (problems.length) return result();
161259
- let rules = "", at2 = 0;
161260
- for (const block of parsed.blocks) {
161261
- rules += body.slice(at2, block.start);
161262
- at2 = block.end;
161263
- }
161264
- rules += body.slice(at2);
161265
- return { def: {
161266
- id: id2,
161267
- name: raw.name.trim(),
161268
- ...raw.names ? { names: raw.names } : {},
161269
- description: raw.description ?? "",
161270
- needsArtifact: raw.needsArtifact ?? false,
161271
- ...raw.summaries ? { summaries: raw.summaries } : {},
161272
- ...raw.entrypoints ? { entrypoints: raw.entrypoints } : {},
161273
- ...raw.icon ? { icon: raw.icon } : {},
161274
- previews: parsed.blocks.map((b2) => ({ id: b2.id, instructions: b2.instructions, ...map3[b2.id] })),
161275
- rules: rules.trim()
161276
- } };
161277
- }
161278
-
161279
- // ../cli/src/lib/agent/studio-folder.ts
161501
+ import crypto4 from "node:crypto";
161280
161502
  import fs27 from "node:fs";
161281
161503
  import path29 from "node:path";
161282
-
161283
- // ../cli/src/lib/shared/studio-files.ts
161284
- var import_yaml5 = __toESM(require_dist(), 1);
161285
-
161286
- // ../cli/src/lib/shared/guide-topics.ts
161287
- var GUIDE_TOPICS = ["board", "writing", "add-task", "follow-up", "discuss-goal", "troubleshoot", "card-chat", "task-ui-en", "task-ui-zh", "update-studio", "implement", "settle-background", "archive", "update-questions", "refine", "revise", "resolve", "prune-memory", "review-memory", "describe-project", "review-rejections", "reflect", "write-agent", "write-prompt", "module-map"];
161288
-
161289
- // ../cli/src/lib/shared/studio-files.ts
161290
- var STUDIO_FILE = "STUDIO.md";
161291
- var MCP_FILE = "mcp.json";
161292
- var CARD_TEMPLATE_FILE = "CARD.md";
161293
- var VERSION_FILE = "version.json";
161294
- var KB = 1024;
161295
- var FILE_LIMITS = { file: 2 * KB * KB, total: 2 * KB * KB, count: 500, path: 512 };
161296
- var officialId = (folder2) => `wf_builtin_${folder2.replace(/-/g, "_")}`;
161297
- var hashInput = (files) => JSON.stringify(Object.entries(files).sort(([a2], [b2]) => a2 < b2 ? -1 : 1));
161298
- var landsOf = (_def) => ({ lands: true });
161299
- var SEGMENT = /^[\w.-]+$/;
161300
- var isAboutFile = (file3) => /^ABOUT(\.[a-z]{2})?\.md$/.test(file3) || /^screenshots\/[\w.-]+\.(png|jpe?g|webp)$/.test(file3);
161301
- var bytes = (text4) => new TextEncoder().encode(text4).length;
161302
- var isSharedFile = (file3) => {
161303
- const parts = file3.split("/");
161304
- return parts.length > 1 && parts[0] === "shared" && parts.slice(1).every((p2) => SEGMENT.test(p2) && p2 !== "." && p2 !== "..");
161305
- };
161306
- function folderPath(file3, top) {
161307
- const parts = file3.split("/");
161308
- if (parts.length < 3 || parts[0] !== top || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(parts[1])) return null;
161309
- if (parts.slice(2).some((p2) => !SEGMENT.test(p2) || p2 === "." || p2 === "..")) return null;
161310
- return [parts[1], parts.slice(2).join("/")];
161311
- }
161312
- function mcpProblem(text4) {
161313
- let read6;
161314
- try {
161315
- read6 = JSON.parse(text4);
161316
- } catch {
161317
- return "is not JSON";
161318
- }
161319
- const servers = read6?.mcpServers;
161320
- if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "must hold `mcpServers`, an object of name \u2192 server";
161321
- for (const [name, server] of Object.entries(servers)) {
161322
- const { command, args: args2, ...rest } = server ?? {};
161323
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) return `names a server \`${name}\`; use lowercase letters, digits and dashes`;
161324
- if (typeof command !== "string" || !command) return `server \`${name}\` needs a \`command\``;
161325
- if (args2 !== void 0 && !(Array.isArray(args2) && args2.every((a2) => typeof a2 === "string"))) return `server \`${name}\`: \`args\` must be a list of strings`;
161326
- if (Object.keys(rest).length) return `server \`${name}\` takes only \`command\` and \`args\``;
161327
- }
161328
- return null;
161329
- }
161330
- function formatStudioProblem({ file: file3, line, column, reason, hint: hint2 }) {
161331
- const location = line === void 0 ? file3 : `${file3}:${line}:${column ?? 1}`;
161332
- return `${location}: ${reason}${hint2 ? `. ${hint2}` : ""}`;
161333
- }
161334
- function checkStudioFiles(value, official = false, checks = {}) {
161335
- const read6 = inspect(value, official, checks);
161336
- const first = read6.problems[0];
161337
- return first ? { ok: false, ...first, problems: read6.problems } : { ok: true, def: read6.def, files: read6.files };
161338
- }
161339
- function inspect(value, official, { allowLegacyPreviewCopy, allowLegacyLand } = {}) {
161340
- const problems = [];
161341
- const fail = (file3, reason, tooLarge = false) => {
161342
- problems.push({ file: file3, reason, ...tooLarge ? { tooLarge } : {} });
161343
- return { problems };
161344
- };
161345
- if (!value || typeof value !== "object" || Array.isArray(value)) return fail("files", "must be an object of path \u2192 text");
161346
- const files = Object.fromEntries(Object.entries(value).filter(([file3]) => file3 !== VERSION_FILE));
161347
- const entries = Object.entries(files);
161348
- if (entries.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
161349
- let total = 0;
161350
- const skills = /* @__PURE__ */ new Set();
161351
- for (const [file3, text4] of entries) {
161352
- if (typeof text4 !== "string" || text4.includes("\0")) {
161353
- fail(file3, "is not a text file");
161354
- continue;
161355
- }
161356
- if (file3.length > FILE_LIMITS.path) {
161357
- fail(file3, `the path is longer than ${FILE_LIMITS.path} characters`);
161358
- continue;
161359
- }
161360
- const size = bytes(text4);
161361
- if (size > FILE_LIMITS.file) return fail(file3, `is larger than ${FILE_LIMITS.file / KB} KB`, true);
161362
- total += size;
161363
- if (total > FILE_LIMITS.total) return fail("files", `are larger than ${FILE_LIMITS.total / KB / KB} MB together`, true);
161364
- if (file3 === STUDIO_FILE || file3 === CARD_TEMPLATE_FILE) continue;
161365
- if (official && file3 === MCP_FILE) {
161366
- const problem2 = mcpProblem(text4);
161367
- if (problem2) fail(file3, problem2);
161368
- continue;
161369
- }
161370
- if (official && isAboutFile(file3)) continue;
161371
- if (official && file3.startsWith("skills/")) {
161372
- if (!folderPath(file3, "skills")) fail(file3, "is not inside skills/<name>/");
161373
- else skills.add(file3.split("/")[1]);
161374
- continue;
161375
- }
161376
- if (isSharedFile(file3)) continue;
161377
- if (/^(?:references|scripts)\//.test(file3) && file3.split("/").every((p2) => SEGMENT.test(p2) && p2 !== "." && p2 !== "..")) continue;
161378
- fail(file3, `use ${STUDIO_FILE}, ${CARD_TEMPLATE_FILE}, references/, scripts/ or shared/`);
161379
- }
161380
- for (const name of skills) {
161381
- if (files[`skills/${name}/SKILL.md`] === void 0) fail(`skills/${name}/SKILL.md`, "is missing");
161382
- }
161383
- const source2 = files[STUDIO_FILE];
161384
- const read6 = typeof source2 === "string" ? parseStudioFile("studio", source2, STUDIO_FILE, { requirePreviewCopy: !official && !allowLegacyPreviewCopy, requireLand: !allowLegacyLand }) : null;
161385
- if (!read6) fail(STUDIO_FILE, "is missing");
161386
- else if ("problem" in read6) for (const problem2 of read6.problems) problems.push({ ...problem2, reason: problem2.message });
161387
- if (!read6 || "problem" in read6) return { problems };
161388
- const def = read6.def;
161389
- for (const [file3, text4] of Object.entries(files)) {
161390
- if (typeof text4 !== "string" || !file3.endsWith(".md")) continue;
161391
- const masked = withoutCode(text4);
161392
- const reference = (offset, link, message) => problems.push({ file: file3, ...sourcePosition(text4, offset), path: link, code: "studio-reference", message, reason: message, hint: "Use an existing safe relative resource or a shipped AKB Guide." });
161393
- for (const match of masked.matchAll(/!?\[[^\]]*\]\(([^\s)]+)(?:\s+[^)]*)?\)/g)) {
161394
- const link = match[1].replace(/^<|>$/g, "");
161395
- if (/^(?:https?:|mailto:|#)/i.test(link)) continue;
161396
- let decoded;
161397
- try {
161398
- decoded = decodeURIComponent(link.split(/[?#]/)[0]);
161399
- } catch {
161400
- reference(match.index, link, "Invalid resource URL");
161401
- continue;
161402
- }
161403
- if (/^(?:[a-z][\w+.-]*:|[/\\])|\\/i.test(decoded) || decoded.split("/").includes("..")) {
161404
- reference(match.index, link, "Unsafe resource path");
161405
- continue;
161406
- }
161407
- const target = [...file3.split("/").slice(0, -1), ...decoded.split("/").filter((p2) => p2 !== ".")].join("/");
161408
- if (!Object.hasOwn(files, target)) reference(match.index, link, `Missing resource ${target}`);
161409
- }
161410
- for (const match of text4.matchAll(/akb guide ([a-z][a-z-]*)/g)) if (!GUIDE_TOPICS.includes(match[1])) reference(match.index, match[1], `Unknown AKB Guide ${match[1]}`);
161411
- }
161412
- return { problems, def, files };
161413
- }
161414
- function previewCatalog(files) {
161415
- const read6 = parseStudioFile("studio", files[STUDIO_FILE] ?? "", STUDIO_FILE);
161416
- if ("problem" in read6) throw new Error(read6.problem);
161417
- return read6.def.previews;
161418
- }
161504
+ import { fileURLToPath } from "node:url";
161419
161505
 
161420
161506
  // ../cli/src/lib/agent/studio-folder.ts
161507
+ import fs26 from "node:fs";
161508
+ import path28 from "node:path";
161421
161509
  var MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
161422
161510
  function filesOf(dir, base = dir) {
161423
- return fs27.readdirSync(dir, { withFileTypes: true }).filter((e2) => !e2.name.startsWith(".")).flatMap((e2) => {
161424
- const full = path29.join(dir, e2.name);
161425
- if (e2.isSymbolicLink()) throw new Error(`${full}: symbolic links are not allowed`);
161426
- return e2.isDirectory() ? filesOf(full, base) : [path29.relative(base, full).split(path29.sep).join("/")];
161511
+ return fs26.readdirSync(dir, { withFileTypes: true }).filter((e2) => e2.name.toLowerCase() !== ".git" && (dir !== base || e2.name !== PUBLICATION_FILE)).flatMap((e2) => {
161512
+ const full = path28.join(dir, e2.name);
161513
+ if (!e2.isFile() && !e2.isDirectory()) throw new Error(full + ": only regular files and directories are allowed");
161514
+ return e2.isDirectory() ? filesOf(full, base) : [path28.relative(base, full).split(path28.sep).join("/")];
161427
161515
  });
161428
161516
  }
161429
161517
  function readStudioFile(dir, file3) {
161430
- const full = path29.join(dir, file3);
161431
- return isAboutFile(file3) && !file3.endsWith(".md") ? `data:${MIME[path29.extname(file3)]};base64,${fs27.readFileSync(full).toString("base64")}` : fs27.readFileSync(full, "utf8");
161518
+ const full = path28.join(dir, file3);
161519
+ const bytes = fs26.readFileSync(full);
161520
+ if (isAboutFile(file3) && !file3.endsWith(".md")) return "data:" + MIME[path28.extname(file3)] + ";base64," + bytes.toString("base64");
161521
+ try {
161522
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
161523
+ } catch {
161524
+ throw new Error(file3 + ": expected a UTF-8 text file");
161525
+ }
161526
+ }
161527
+ function readStudioFolder(dir) {
161528
+ const files = filesOf(dir).sort();
161529
+ if (files.filter((file3) => file3 !== VERSION_FILE).length > FILE_LIMITS.count) throw new Error("Studio file count limit exceeded");
161530
+ let total = 0;
161531
+ return Object.fromEntries(files.map((file3) => {
161532
+ const size = fs26.statSync(path28.join(dir, file3)).size;
161533
+ if (file3 !== VERSION_FILE) total += size;
161534
+ const problem2 = studioSizeProblem(file3, size, total);
161535
+ if (problem2) throw new Error(problem2.file + ": " + problem2.reason);
161536
+ return [file3, readStudioFile(dir, file3)];
161537
+ }));
161432
161538
  }
161433
- var readStudioFolder = (dir) => Object.fromEntries(filesOf(dir).sort().map((f2) => [f2, readStudioFile(dir, f2)]));
161434
161539
 
161435
161540
  // ../official/pack.ts
161436
- var OFFICIAL = path30.dirname(fileURLToPath2(import.meta.url));
161437
- var dirs = (dir) => fs28.readdirSync(dir, { withFileTypes: true }).filter((e2) => e2.isDirectory()).map((e2) => e2.name).sort();
161438
- var hashOf = (files) => crypto3.createHash("sha256").update(hashInput(files)).digest("hex");
161541
+ var OFFICIAL = path29.dirname(fileURLToPath(import.meta.url));
161542
+ var dirs = (dir) => fs27.readdirSync(dir, { withFileTypes: true }).filter((e2) => e2.isDirectory()).map((e2) => e2.name).sort();
161543
+ var hashOf = (files) => crypto4.createHash("sha256").update(hashInput(files)).digest("hex");
161439
161544
  function packOfficial(root2 = OFFICIAL, loose = false) {
161440
- const studiosDir = path30.join(root2, "studios");
161545
+ const studiosDir = path29.join(root2, "studios");
161441
161546
  return dirs(studiosDir).map((folder2) => {
161442
- const files = readStudioFolder(path30.join(studiosDir, folder2));
161547
+ const files = readStudioFolder(path29.join(studiosDir, folder2));
161443
161548
  const parsed = parseStudioFile(folder2, files[STUDIO_FILE] ?? "", STUDIO_FILE);
161444
161549
  if ("problem" in parsed) throw new Error(parsed.problem);
161445
161550
  const def = parsed.def;
@@ -161460,14 +161565,14 @@ function packOfficial(root2 = OFFICIAL, loose = false) {
161460
161565
  }
161461
161566
 
161462
161567
  // ../cli/src/lib/cloud/tasks.ts
161463
- import fs29 from "node:fs";
161464
- import path31 from "node:path";
161568
+ import fs28 from "node:fs";
161569
+ import path30 from "node:path";
161465
161570
  var TASK_ENV = "AI4KANBAN_TASK";
161466
161571
  function workspaceTask() {
161467
161572
  const id2 = process.env[TASK_ENV];
161468
161573
  return id2 && id2.trim() ? id2.trim() : null;
161469
161574
  }
161470
- async function call(method, route, body, key, { allowResultError = false } = {}) {
161575
+ async function call(method, route, body, key, { allowResultError = false, downloadBytes } = {}) {
161471
161576
  if (!cloudConfigured()) return { ok: false, error: NOT_CONFIGURED, code: "bad_request" };
161472
161577
  const token = await accessToken();
161473
161578
  if (!token.ok) {
@@ -161488,21 +161593,28 @@ async function call(method, route, body, key, { allowResultError = false } = {})
161488
161593
  } catch (e2) {
161489
161594
  return { ok: false, error: `Cloud could not be reached: ${e2 instanceof Error ? e2.message : String(e2)}`, code: "unreachable", retryable: true };
161490
161595
  }
161596
+ if (response.ok && downloadBytes !== void 0) {
161597
+ try {
161598
+ return { ok: true, value: await readStudioDownload(response, downloadBytes) };
161599
+ } catch (error62) {
161600
+ return { ok: false, error: error62.message, code: "invalid_response" };
161601
+ }
161602
+ }
161491
161603
  const parsed = await readCloudJson(response);
161492
161604
  const problem2 = (response.ok && allowResultError ? null : cloudProblem(response, parsed)) ?? (isRecord(parsed) ? null : invalidResponse("a valid JSON response"));
161493
161605
  if (problem2) return { ok: false, ...problem2, error: problem2.message };
161494
161606
  return { ok: true, value: parsed, replayed: response.headers.get("idempotent-replayed") === "true" };
161495
161607
  }
161496
161608
  function runnerProject(board) {
161497
- if (path31.basename(board) !== "kanban" || path31.basename(path31.dirname(board)) !== ".akb") return null;
161498
- const linked = linkedProject(board, path31.dirname(path31.dirname(board)));
161609
+ if (path30.basename(board) !== "kanban" || path30.basename(path30.dirname(board)) !== ".akb") return null;
161610
+ const linked = linkedProject(board, path30.dirname(path30.dirname(board)));
161499
161611
  return linked.ok ? linked.value : null;
161500
161612
  }
161501
161613
  function linkedProject(board, root2) {
161502
- const file3 = path31.join(root2, ".akb", "base.json");
161503
- if (!fs29.existsSync(file3)) return { ok: true, value: null };
161614
+ const file3 = path30.join(root2, ".akb", "base.json");
161615
+ if (!fs28.existsSync(file3)) return { ok: true, value: null };
161504
161616
  try {
161505
- const base = JSON.parse(fs29.readFileSync(file3, "utf8"));
161617
+ const base = JSON.parse(fs28.readFileSync(file3, "utf8"));
161506
161618
  if (!base || typeof base !== "object" || base.project !== void 0 && (typeof base.project !== "string" || !base.project.trim()) || base.files !== void 0 && (!base.files || typeof base.files !== "object" || Array.isArray(base.files))) throw new Error();
161507
161619
  const projects = new Set(Object.keys(base.files ?? {}).flatMap((p2) => /^projects\/([^/]+)\//.exec(p2)?.[1] ?? []));
161508
161620
  if (typeof base.project === "string") projects.add(base.project);
@@ -161514,66 +161626,131 @@ function linkedProject(board, root2) {
161514
161626
  }
161515
161627
 
161516
161628
  // ../cli/src/lib/agent/cloud-studios.ts
161629
+ var STUDIO_SNAPSHOT_ENV = "AI4KANBAN_STUDIO_SNAPSHOT";
161517
161630
  var DEV = "AI4KANBAN_STUDIOS";
161518
- var root = () => path32.join(machineHome(), "studios");
161631
+ var root = () => path31.join(machineHome(), "studios");
161519
161632
  var safe = (name) => name.replace(/[^\w.@-]/g, "_");
161520
- var versionFile = (id2, version2) => path32.join(root(), "versions", `${safe(id2)}@${version2}.json`);
161521
- var listFile = (project) => path32.join(root(), "lists", `${safe(project)}.json`);
161522
- var pinFile = (task) => path32.join(root(), "tasks", `${safe(task)}.json`);
161633
+ var versionFile = (id2, version2) => path31.join(root(), "versions", `${safe(id2)}@${version2}.json`);
161634
+ var listFile = (project) => path31.join(root(), "lists", `${safe(project)}.json`);
161635
+ var pinFile = (task) => path31.join(root(), "tasks", `${safe(task)}.json`);
161636
+ var sessionDir = (task) => path31.join(root(), "sessions", safe(task));
161637
+ var sessionFileOf = (task, session) => path31.join(sessionDir(task), createHash5("sha256").update(session).digest("hex") + ".json");
161638
+ var skillDir = (id2, version2) => path31.join(root(), "bundles", safe(id2) + "@" + version2);
161523
161639
  function readJson(file3) {
161524
161640
  try {
161525
- return JSON.parse(fs30.readFileSync(file3, "utf8"));
161641
+ return JSON.parse(fs29.readFileSync(file3, "utf8"));
161526
161642
  } catch {
161527
161643
  return null;
161528
161644
  }
161529
161645
  }
161530
161646
  function writeJson(file3, value) {
161531
- fs30.mkdirSync(path32.dirname(file3), { recursive: true });
161532
- const tmp = `${file3}.${process.pid}.tmp`;
161533
- fs30.writeFileSync(tmp, `${JSON.stringify(value)}
161534
- `);
161535
- fs30.renameSync(tmp, file3);
161647
+ fs29.mkdirSync(path31.dirname(file3), { recursive: true });
161648
+ const tmp = `${file3}.${randomUUID5()}.tmp`;
161649
+ try {
161650
+ fs29.writeFileSync(tmp, JSON.stringify(value) + "\n", { mode: 384 });
161651
+ fs29.renameSync(tmp, file3);
161652
+ } finally {
161653
+ fs29.rmSync(tmp, { force: true });
161654
+ }
161536
161655
  }
161537
- var readVersion2 = (id2, version2) => readJson(versionFile(id2, version2));
161656
+ var filesHash = (files) => createHash5("sha256").update(hashInput(files)).digest("hex");
161657
+ var readVersion2 = (id2, version2) => {
161658
+ const held5 = readJson(versionFile(id2, version2));
161659
+ return held5?.id === id2 && held5.version === version2 && isStudioFiles(held5.files) && (!held5.filesSha256 || filesHash(held5.files) === held5.filesSha256) ? held5 : null;
161660
+ };
161538
161661
  function heldStudioName(name) {
161539
161662
  let files;
161540
161663
  try {
161541
- files = fs30.readdirSync(path32.join(root(), "versions"));
161664
+ files = fs29.readdirSync(path31.join(root(), "versions"));
161542
161665
  } catch {
161543
161666
  return "";
161544
161667
  }
161545
161668
  const held5 = files.filter((f2) => f2.endsWith(".json")).map((f2) => f2.slice(0, f2.lastIndexOf("@"))).find((id2) => studioName(id2) === name);
161546
161669
  if (!held5) return "";
161547
161670
  const file3 = files.filter((f2) => f2.startsWith(`${held5}@`)).sort().pop();
161548
- return readJson(path32.join(root(), "versions", file3))?.name ?? "";
161671
+ return readJson(path31.join(root(), "versions", file3))?.name ?? "";
161549
161672
  }
161550
161673
  function saveVersion(held5) {
161551
161674
  const file3 = versionFile(held5.id, held5.version);
161552
- writeJson(file3, { id: held5.id, version: held5.version, name: held5.name, names: held5.names, files: held5.files });
161675
+ writeJson(file3, { id: held5.id, version: held5.version, name: held5.name, names: held5.names, files: held5.files, filesSha256: held5.filesSha256 });
161553
161676
  }
161554
- function savePin(task, held5) {
161555
- saveVersion(held5);
161677
+ function savePin(task, held5, saved = false) {
161678
+ if (!saved) saveVersion(held5);
161556
161679
  writeJson(pinFile(task), { studio: held5.id, version: held5.version, historicalPreviews: held5.historicalPreviews });
161557
161680
  }
161558
161681
  var readPin = (task) => readJson(pinFile(task));
161682
+ var readStudioSession = (task, session) => readJson(sessionFileOf(task, session));
161683
+ function saveStudioSession(task, session, pin) {
161684
+ const file3 = sessionFileOf(task, session);
161685
+ if (!fs29.existsSync(file3)) writeJson(file3, pin);
161686
+ }
161687
+ function studioSkillBlock(skills, folder2) {
161688
+ if (!skills.length) return "";
161689
+ return [
161690
+ "When a skill applies, read its listed SKILL.md and resolve its relative references from the skill directory.",
161691
+ "",
161692
+ "## Skills",
161693
+ "",
161694
+ "### Available skills",
161695
+ ...skills.map(({ name, description }) => "- " + name + ": " + description + " (file: " + path31.join(folder2, skillFile(name)) + ")")
161696
+ ].join("\n");
161697
+ }
161698
+ function cachedStudioSkillBlock(held5) {
161699
+ const skills = studioSkills(held5.files);
161700
+ if (!skills.length) return "";
161701
+ const folder2 = path31.resolve(skillDir(held5.id, held5.version));
161702
+ if (!fs29.existsSync(folder2)) {
161703
+ const parent = path31.dirname(folder2);
161704
+ fs29.mkdirSync(parent, { recursive: true, mode: 448 });
161705
+ const temp = fs29.mkdtempSync(path31.join(parent, ".studio-"));
161706
+ try {
161707
+ const prefixes = new Set(skills.map(({ name }) => "skills/" + name + "/"));
161708
+ for (const [file3, text4] of Object.entries(held5.files)) {
161709
+ if (!safeStudioPath(file3) || !prefixes.has(file3.split("/").slice(0, 2).join("/") + "/")) continue;
161710
+ const target = path31.join(temp, file3);
161711
+ fs29.mkdirSync(path31.dirname(target), { recursive: true });
161712
+ fs29.writeFileSync(target, text4, { flag: "wx", mode: 292 });
161713
+ }
161714
+ try {
161715
+ fs29.renameSync(temp, folder2);
161716
+ } catch (error62) {
161717
+ if (!fs29.existsSync(folder2)) throw error62;
161718
+ }
161719
+ } finally {
161720
+ fs29.rmSync(temp, { recursive: true, force: true });
161721
+ }
161722
+ }
161723
+ return studioSkillBlock(skills, folder2);
161724
+ }
161559
161725
  var jsonIn = (dir) => {
161560
161726
  try {
161561
- return fs30.readdirSync(path32.join(root(), dir)).filter((f2) => f2.endsWith(".json"));
161727
+ return fs29.readdirSync(path31.join(root(), dir)).filter((f2) => f2.endsWith(".json"));
161562
161728
  } catch {
161563
161729
  return [];
161564
161730
  }
161565
161731
  };
161566
161732
  async function sweepVersions(ended) {
161567
161733
  const keep2 = /* @__PURE__ */ new Set();
161568
- const held5 = (id2, version2) => keep2.add(path32.basename(versionFile(id2, version2)));
161569
- for (const file3 of jsonIn("tasks")) {
161570
- const at2 = path32.join(root(), "tasks", file3);
161571
- const pin = readJson(at2);
161572
- if (!pin || await ended(file3.slice(0, -".json".length))) fs30.rmSync(at2, { force: true });
161573
- else held5(pin.studio, pin.version);
161734
+ const held5 = (id2, version2) => keep2.add(path31.basename(versionFile(id2, version2)));
161735
+ const tasks = new Set(jsonIn("tasks").map((file3) => file3.slice(0, -".json".length)));
161736
+ const dir = path31.join(root(), "sessions");
161737
+ if (fs29.existsSync(dir)) for (const task of fs29.readdirSync(dir)) tasks.add(task);
161738
+ for (const task of tasks) {
161739
+ const pin = readPin(task);
161740
+ const finished = await ended(task);
161741
+ if (finished) fs29.rmSync(pinFile(task), { force: true });
161742
+ else if (pin) held5(pin.studio, pin.version);
161743
+ if (finished === "gone") {
161744
+ fs29.rmSync(sessionDir(task), { recursive: true, force: true });
161745
+ continue;
161746
+ }
161747
+ for (const file3 of jsonIn("sessions/" + safe(task))) {
161748
+ const bound = readJson(path31.join(sessionDir(task), file3));
161749
+ if (bound) held5(bound.studio, bound.version);
161750
+ }
161574
161751
  }
161575
161752
  for (const file3 of jsonIn("lists")) {
161576
- for (const w2 of readJson(path32.join(root(), "lists", file3))?.studios ?? []) held5(w2.id, w2.version);
161753
+ for (const w2 of readJson(path31.join(root(), "lists", file3))?.studios ?? []) held5(w2.id, w2.version);
161577
161754
  }
161578
161755
  const versions = jsonIn("versions");
161579
161756
  const newest2 = /* @__PURE__ */ new Map();
@@ -161583,11 +161760,106 @@ async function sweepVersions(ended) {
161583
161760
  if (version2 > (newest2.get(id2) ?? -1)) newest2.set(id2, version2);
161584
161761
  }
161585
161762
  const gone = versions.filter((file3) => !keep2.has(file3) && newest2.get(parts(file3).id) !== parts(file3).version);
161586
- for (const file3 of gone) fs30.rmSync(path32.join(root(), "versions", file3), { force: true });
161763
+ for (const file3 of gone) {
161764
+ fs29.rmSync(path31.join(root(), "versions", file3), { force: true });
161765
+ const { id: id2, version: version2 } = parts(file3);
161766
+ fs29.rmSync(skillDir(id2, version2), { recursive: true, force: true });
161767
+ }
161587
161768
  return gone;
161588
161769
  }
161589
161770
  var boardProject = () => KANBAN ? runnerProject(KANBAN) : null;
161590
161771
  var devFolder = () => process.env[DEV]?.trim() || "";
161772
+ function invalid(expected) {
161773
+ const problem2 = invalidResponse(expected);
161774
+ return { ...problem2, ok: false, error: problem2.message };
161775
+ }
161776
+ var isStudioVersion = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
161777
+ function isStudioFiles(value) {
161778
+ return isRecord(value) && hasText(value["STUDIO.md"]) && Object.entries(value).every(([file3, text4]) => typeof text4 === "string" && safeStudioPath(file3));
161779
+ }
161780
+ var downloads = /* @__PURE__ */ new Map();
161781
+ function checkedPackage(pack, version2) {
161782
+ return pack.version === version2 && isDigest(pack.zipSha256) && isDigest(pack.filesSha256) && Number.isSafeInteger(pack.zipBytes) && pack.zipBytes > 0 && pack.zipBytes <= STUDIO_ZIP_LIMIT && typeof pack.downloadUrl === "string" && new RegExp("^/v1/(studios/[A-Za-z0-9_-]+|tasks/[A-Za-z0-9_-]+/studio)/versions/" + version2 + "/package$").test(pack.downloadUrl);
161783
+ }
161784
+ async function cachedPackage(held5, pack, download2) {
161785
+ const file3 = versionFile(held5.id, held5.version);
161786
+ const cached3 = () => {
161787
+ const local = readVersion2(held5.id, held5.version);
161788
+ if (!local) return null;
161789
+ const { [VERSION_FILE]: _stamp, ...files } = local.files;
161790
+ return (local.filesSha256 ?? filesHash(files)) === pack.filesSha256 ? { ...held5, files, filesSha256: pack.filesSha256 } : null;
161791
+ };
161792
+ const existing = cached3();
161793
+ if (existing) return { ok: true, value: existing };
161794
+ const key = file3 + ":" + pack.filesSha256;
161795
+ let work = downloads.get(key);
161796
+ if (!work) {
161797
+ work = (async () => {
161798
+ const deadline = Date.now() + 6e4;
161799
+ let release2;
161800
+ while (!(release2 = tryLock(file3 + ".lock"))) {
161801
+ if (Date.now() >= deadline) return { ok: false, code: "studio_cache_busy", error: "The Studio package is still being downloaded." };
161802
+ await delay2(50);
161803
+ }
161804
+ try {
161805
+ const local = cached3();
161806
+ if (local) return { ok: true, value: local };
161807
+ const read6 = await download2(pack.downloadUrl, pack.zipBytes);
161808
+ if (!read6.ok) return read6;
161809
+ const zip = read6.value;
161810
+ if (zip.length !== pack.zipBytes || createHash5("sha256").update(zip).digest("hex") !== pack.zipSha256) return invalid("the Studio ZIP digest");
161811
+ let files;
161812
+ try {
161813
+ files = decodeStudioZip(zip);
161814
+ } catch {
161815
+ return invalid("a valid Studio ZIP");
161816
+ }
161817
+ if (!isStudioFiles(files) || filesHash(files) !== pack.filesSha256) return invalid("the Studio files digest");
161818
+ const value = { ...held5, files, filesSha256: pack.filesSha256 };
161819
+ saveVersion(value);
161820
+ return { ok: true, value };
161821
+ } finally {
161822
+ release2();
161823
+ }
161824
+ })().finally(() => downloads.delete(key));
161825
+ downloads.set(key, work);
161826
+ }
161827
+ const got = await work;
161828
+ return got.ok ? { ok: true, value: { ...got.value, ...held5 } } : got;
161829
+ }
161830
+ async function loadPublishedStudio(route, read6, download2, pin) {
161831
+ const metadata = await read6(route + "?view=metadata" + (pin ? "&version=" + pin.version : ""));
161832
+ if (!metadata.ok) return metadata;
161833
+ if (!isRecord(metadata.value)) return invalid("Studio metadata");
161834
+ let row = metadata.value;
161835
+ if (row.deleted) return { ok: true, value: null };
161836
+ const pack = row.package;
161837
+ if (!pack && !row.files) {
161838
+ const legacy2 = await read6(route);
161839
+ if (!legacy2.ok) return legacy2;
161840
+ row = legacy2.value;
161841
+ if (row.deleted) return { ok: true, value: null };
161842
+ }
161843
+ const id2 = row.id ?? row.studio;
161844
+ if (!hasText(id2) || !/^wf_[A-Za-z0-9_-]+$/.test(id2)) return invalid("the Studio id");
161845
+ const version2 = row.version ?? 1;
161846
+ if (!isStudioVersion(version2) || pin && (pin.studio !== id2 || pin.version !== version2)) return invalid("the Studio version");
161847
+ const held5 = { id: id2, version: version2, name: row.name ?? id2, names: row.names, historicalPreviews: row.historicalPreviews };
161848
+ if (pack) return checkedPackage(pack, version2) ? cachedPackage(held5, pack, download2) : invalid("the Studio package reference");
161849
+ if (!isStudioFiles(row.files)) return invalid("the Studio files");
161850
+ const value = { ...held5, files: row.files };
161851
+ saveVersion(value);
161852
+ return { ok: true, value };
161853
+ }
161854
+ var missingStudioVersion = (pin) => "Cannot recover Studio " + studioName(pin.studio) + " v" + pin.version + ". Its saved version is missing.";
161855
+ function executionSnapshot() {
161856
+ try {
161857
+ const value = JSON.parse(process.env[STUDIO_SNAPSHOT_ENV] ?? "null");
161858
+ if (hasText(value?.studio) && isStudioVersion(value.version)) return value;
161859
+ } catch {
161860
+ }
161861
+ }
161862
+ var activeStudioPin = (task) => executionSnapshot() ?? readPin(task);
161591
161863
  var flowOf = (held5) => {
161592
161864
  const id2 = studioName(held5.id);
161593
161865
  const read6 = parseStudioFile(id2, held5.files["STUDIO.md"] ?? "", `the \`${id2}\` studio`);
@@ -161607,17 +161879,23 @@ function readFlows() {
161607
161879
  return held5 ? flowOf(held5) ?? [] : [];
161608
161880
  });
161609
161881
  const task = workspaceTask();
161610
- const pin = task ? readPin(task) : null;
161882
+ const pin = task ? activeStudioPin(task) : null;
161611
161883
  const pinned = pin && readVersion2(pin.studio, pin.version);
161612
161884
  const mine = pinned && flowOf(pinned);
161613
- if (!mine) return flows2;
161885
+ if (!mine) return pin ? flows2.filter((flow) => flow.cloudId !== pin.studio) : flows2;
161614
161886
  return [mine, ...flows2.filter((f2) => f2.cloudId !== mine.cloudId)];
161615
161887
  }
161616
161888
  var sources2 = () => {
161617
161889
  if (devFolder()) return [devFolder()];
161618
161890
  const project = boardProject();
161619
161891
  const task = workspaceTask();
161620
- return [sessionFile(), ...project ? [listFile(project)] : [], ...task ? [pinFile(task)] : []];
161892
+ const pin = task && activeStudioPin(task);
161893
+ return [
161894
+ sessionFile(),
161895
+ ...project ? [listFile(project)] : [],
161896
+ ...task ? [pinFile(task)] : [],
161897
+ ...pin ? [versionFile(pin.studio, pin.version)] : []
161898
+ ];
161621
161899
  };
161622
161900
  var flows = memoByFiles(sources2, readFlows);
161623
161901
  var cloudStudioSources = sources2;
@@ -161626,7 +161904,7 @@ function cloudAgentFiles() {
161626
161904
  const files = {};
161627
161905
  const official = /* @__PURE__ */ new Set();
161628
161906
  const owner2 = /* @__PURE__ */ new Map();
161629
- for (const flow of cloudFlows()) {
161907
+ for (const flow of devFolder() ? cloudFlows() : []) {
161630
161908
  for (const [name, text4] of Object.entries(flow.files)) {
161631
161909
  const at2 = /^agents\/([^/]+)\/(.+)$/.exec(name);
161632
161910
  if (!at2) continue;
@@ -161640,6 +161918,118 @@ function cloudAgentFiles() {
161640
161918
  return { files, official };
161641
161919
  }
161642
161920
 
161921
+ // src/akb.ts
161922
+ import { spawn as spawn3 } from "node:child_process";
161923
+ import fs30 from "node:fs";
161924
+ import path32 from "node:path";
161925
+ import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
161926
+ var akbHome = () => path32.join(runnerHome(), "bin", "akb");
161927
+ var BUNDLED_SHIM = `bundled-${AKB_VERSION}`;
161928
+ var HERE = path32.dirname(fileURLToPath2(import.meta.url));
161929
+ function akbArgs(entry, dist = HERE) {
161930
+ const preload = path32.join(dist, "akb-proxy.mjs");
161931
+ return fs30.existsSync(preload) ? ["--import", pathToFileURL(preload).href, entry] : [entry];
161932
+ }
161933
+ var bundledAkb = (dist = HERE) => ({
161934
+ command: process.execPath,
161935
+ args: akbArgs(path32.join(dist, "akb", "bin", "ai4kanban.mjs"), dist),
161936
+ version: AKB_VERSION,
161937
+ canonicalCommands: true,
161938
+ shim: path32.join(akbHome(), BUNDLED_SHIM)
161939
+ });
161940
+ var quote = (s) => /^[\w./:@=-]+$/.test(s) ? s : `"${s}"`;
161941
+ function shimDir(akb) {
161942
+ const dir = akb.shim;
161943
+ const line = [akb.command, ...akb.args].map(quote).join(" ");
161944
+ const [file3, text4] = process.platform === "win32" ? [path32.join(dir, "akb.cmd"), `@${line} %*\r
161945
+ `] : [path32.join(dir, "akb"), `#!/bin/sh
161946
+ exec ${line} "$@"
161947
+ `];
161948
+ if (process.platform === "win32") {
161949
+ fs30.mkdirSync(dir, { recursive: true });
161950
+ const shellLine = [akb.command, ...akb.args].map((s) => `'${s.replaceAll("\\", "/").replaceAll("'", "'\\''")}'`).join(" ");
161951
+ fs30.writeFileSync(path32.join(dir, "akb"), `#!/bin/sh
161952
+ exec ${shellLine} "$@"
161953
+ `, { mode: 493 });
161954
+ }
161955
+ try {
161956
+ if (fs30.readFileSync(file3, "utf8") === text4) return dir;
161957
+ } catch {
161958
+ }
161959
+ fs30.mkdirSync(dir, { recursive: true });
161960
+ fs30.writeFileSync(file3, text4, { mode: 493 });
161961
+ return dir;
161962
+ }
161963
+ function akbEnv(akb, board, task, language2, base = process.env) {
161964
+ const env2 = {};
161965
+ const dropped = ["AI4KANBAN_PREVIEW_BRIDGE", "AI4KANBAN_REPLY_APPROVAL", "AI4KANBAN_BOARD", "AI4KANBAN_TASK", "AI4KANBAN_EXECUTION", "AI4KANBAN_SCHEDULED_AGENTS", STUDIO_SNAPSHOT_ENV, LANGUAGE_ENV, SESSION_COST_ENV, EXECUTION_RUNTIMES_ENV];
161966
+ for (const [k2, v] of Object.entries({ ...proxyEnv(), ...base })) if (!k2.startsWith("KANBAN_") && !dropped.includes(k2)) env2[k2] = v;
161967
+ const key = Object.keys(env2).find((k2) => k2.toUpperCase() === "PATH") ?? "PATH";
161968
+ env2[key] = [shimDir(akb), env2[key]].filter(Boolean).join(path32.delimiter);
161969
+ if (Object.keys(proxyEnv()).some((k2) => !/^no_proxy$/i.test(k2)) && env2.NODE_USE_ENV_PROXY === void 0) env2.NODE_USE_ENV_PROXY = "1";
161970
+ env2[HOST_PROXY_ENV] = JSON.stringify(hostProxy());
161971
+ env2.AI4KANBAN_COMMAND = "akb";
161972
+ if (board) env2.AI4KANBAN_BOARD = board;
161973
+ if (task) env2.AI4KANBAN_TASK = task;
161974
+ if (language2 !== void 0) env2[LANGUAGE_ENV] = language2 ?? "";
161975
+ return env2;
161976
+ }
161977
+ var KEEP = 256 * 1024;
161978
+ function compatibleArgs(akb, args2) {
161979
+ if (akb.canonicalCommands) return args2;
161980
+ const [group, verb, ...rest] = args2;
161981
+ if (group === "run" || group === "delivery") return ["raw", ...args2];
161982
+ if (group === "task" && verb && ["refine", "revise", "resolve", "implement"].includes(verb)) return ["raw", "card", verb, ...rest];
161983
+ if (group === "memory" && verb === "describe-project") return ["raw", verb, ...rest];
161984
+ if (group === "memory" && verb === "review") return ["raw", ...args2];
161985
+ return args2;
161986
+ }
161987
+ function runAkb(akb, args2, opts) {
161988
+ return new Promise((resolve2) => {
161989
+ let out = "";
161990
+ let last2 = "";
161991
+ const note = (text4) => {
161992
+ const line = text4.split("\n").map((l2) => l2.trim()).filter(Boolean).at(-1);
161993
+ if (line) last2 = line;
161994
+ };
161995
+ let child;
161996
+ try {
161997
+ child = spawn3(akb.command, [...akb.args, ...compatibleArgs(akb, args2)], { cwd: opts.cwd, env: { ...akbEnv(akb, opts.board, opts.task, opts.language), ...opts.env }, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
161998
+ } catch (e2) {
161999
+ return resolve2({ code: null, out: "", last: e2 instanceof Error ? e2.message : String(e2) });
162000
+ }
162001
+ opts.track?.(child);
162002
+ child.stdout.setEncoding("utf8");
162003
+ child.stderr.setEncoding("utf8");
162004
+ child.stdout.on("data", (chunk) => {
162005
+ out = (out + chunk).slice(-KEEP);
162006
+ note(chunk);
162007
+ opts.show?.(chunk);
162008
+ });
162009
+ child.stderr.on("data", (chunk) => {
162010
+ note(chunk);
162011
+ opts.show?.(chunk);
162012
+ });
162013
+ child.on("error", (e2) => resolve2({ code: null, out, last: e2.message }));
162014
+ child.on("close", (code) => resolve2({ code, out, last: last2 }));
162015
+ });
162016
+ }
162017
+ function answerOf2(ran) {
162018
+ const line = ran.out.trim().split("\n").at(-1) ?? "";
162019
+ try {
162020
+ return JSON.parse(line);
162021
+ } catch {
162022
+ return null;
162023
+ }
162024
+ }
162025
+
162026
+ // ../cli/src/lib/shared/board-conflicts.ts
162027
+ var import_yaml8 = __toESM(require_dist(), 1);
162028
+
162029
+ // ../cli/src/lib/agents/shared-memory.ts
162030
+ import fs31 from "node:fs";
162031
+ import path33 from "node:path";
162032
+
161643
162033
  // ../cli/src/lib/agents/bundled.ts
161644
162034
  var shippedAgentFiles = () => cloudAgentFiles().files;
161645
162035
  var officialAgent = (name) => cloudAgentFiles().official.has(name);
@@ -161931,7 +162321,7 @@ function matcher(entry) {
161931
162321
  }
161932
162322
 
161933
162323
  // ../cli/src/lib/shared/board-conflicts.ts
161934
- import crypto4 from "node:crypto";
162324
+ import crypto5 from "node:crypto";
161935
162325
  import fs32 from "node:fs";
161936
162326
  import path34 from "node:path";
161937
162327
 
@@ -162017,7 +162407,7 @@ var fileOf = (board, id2) => {
162017
162407
  };
162018
162408
  function atomicJson(file3, data) {
162019
162409
  fs32.mkdirSync(path34.dirname(file3), { recursive: true });
162020
- const temp = `${file3}.${crypto4.randomUUID()}.tmp`;
162410
+ const temp = `${file3}.${crypto5.randomUUID()}.tmp`;
162021
162411
  const fd = fs32.openSync(temp, "wx", 384);
162022
162412
  try {
162023
162413
  fs32.writeFileSync(fd, JSON.stringify(data));
@@ -162076,7 +162466,7 @@ function conflictPrompt(board, work = "Continue the original work from its saved
162076
162466
  function captureConflict(board, project, files) {
162077
162467
  const pending = pendingConflicts(board)[0];
162078
162468
  if (pending) return pending;
162079
- const record2 = { id: `c_${crypto4.randomUUID().replaceAll("-", "")}`, project, state: "open", files, receipt: null };
162469
+ const record2 = { id: `c_${crypto5.randomUUID().replaceAll("-", "")}`, project, state: "open", files, receipt: null };
162080
162470
  save(board, record2);
162081
162471
  return record2;
162082
162472
  }
@@ -162096,7 +162486,7 @@ async function withSyncLock(board, work) {
162096
162486
  }
162097
162487
 
162098
162488
  // src/cache.ts
162099
- import crypto5 from "node:crypto";
162489
+ import crypto6 from "node:crypto";
162100
162490
  import fs33 from "node:fs";
162101
162491
  import path35 from "node:path";
162102
162492
  var IDLE_MS2 = 7 * 24 * 60 * 6e4;
@@ -162131,7 +162521,7 @@ function markUnsent(dir, unsent2) {
162131
162521
  }
162132
162522
  var holds = /* @__PURE__ */ new Map();
162133
162523
  var holdsDir = () => path35.join(runnerHome(), "holds");
162134
- var holdFile = (dir) => path35.join(holdsDir(), `${crypto5.createHash("sha256").update(dir).digest("hex")}.${process.pid}`);
162524
+ var holdFile = (dir) => path35.join(holdsDir(), `${crypto6.createHash("sha256").update(dir).digest("hex")}.${process.pid}`);
162135
162525
  function hold(dir) {
162136
162526
  fs33.mkdirSync(holdsDir(), { recursive: true, mode: 448 });
162137
162527
  fs33.writeFileSync(holdFile(dir), "", { mode: 384 });
@@ -162247,7 +162637,7 @@ async function sweepCache(machineId2, now = Date.now()) {
162247
162637
  var sweepStudios = () => sweepVersions(async (task) => {
162248
162638
  const read6 = await readTask(task);
162249
162639
  if (read6.ok) return read6.value.status === "done" || read6.value.status === "cancelled";
162250
- return read6.code === "not_found" ? true : null;
162640
+ return read6.code === "not_found" ? "gone" : null;
162251
162641
  });
162252
162642
  function removeLegacy() {
162253
162643
  const home4 = runnerHome();
@@ -162267,7 +162657,7 @@ function removeLegacy() {
162267
162657
  }
162268
162658
 
162269
162659
  // src/update.ts
162270
- import crypto6 from "node:crypto";
162660
+ import crypto7 from "node:crypto";
162271
162661
  import fs34 from "node:fs";
162272
162662
  import path36 from "node:path";
162273
162663
  import zlib from "node:zlib";
@@ -162295,7 +162685,7 @@ async function installPackage(pkg, version2, nodeVersion = process.versions.node
162295
162685
  return { ok: false, why: "unreachable", detail: e2 instanceof Error ? e2.message : String(e2) };
162296
162686
  }
162297
162687
  const expected = /^sha512-(.+)$/.exec(meta3.dist.integrity ?? "")?.[1];
162298
- const actual = crypto6.createHash("sha512").update(tarball).digest("base64");
162688
+ const actual = crypto7.createHash("sha512").update(tarball).digest("base64");
162299
162689
  if (!expected || expected !== actual) return { ok: false, why: "integrity", detail: "sha512 mismatch" };
162300
162690
  const staging = `${dir}.${process.pid}.tmp`;
162301
162691
  try {
@@ -162856,7 +163246,7 @@ function kindOf2(ext) {
162856
163246
  var TEXT_LIMIT = 1024 * 1024;
162857
163247
 
162858
163248
  // ../cli/src/components/Asset.md
162859
- var Asset_default = '# Asset\n\nShow a file as a Preview with `<Asset src=".assets/<card id>/<file>" label="..." />` alone in a paragraph.\nInline and fenced examples remain text.\n\n- **Label**: use a few words; an image\'s optional `alt` is its shipped caption and cannot contain `<`, `>` or its enclosing quote.\n- **Device**: use a separate tag for each device view, with `device="mobile"` or `device="desktop"`; both may reference the same responsive page.\n- **Variants**: versions of the same content on the same device share one tag with `variants=\'{"English": ".assets/<card id>/page.en.html", "\u4E2D\u6587": ".assets/<card id>/page.zh.html"}\'`, with `src` shown first; alternatives stay separate tags.\n- **Loop**: add `loop` for muted, looping video without controls.\n- **Captions**: `captions` binds a UTF-8 SRT or WebVTT file to an audio or video Asset. The timecoded list seeks the player and highlights the current line. Both original files are available in the Asset menu.\n- **Video overlay**: `overlay=".assets/42/overlay.html"` shares a transparent HTML layer across versions. Use a JSON object keyed by exact `variants` labels for separate `.html` or `.htm` files. A missing or failed overlay leaves the video playable.\n- **Tiled map**: a `.tmx` or `.tmj` `src` draws as a map; keep its `.tsx`/`.tsj` tilesets and images beside it, at the relative paths it names.\n- **Sprite animation**: a TexturePacker JSON (Hash or Array) `src` plays as an animation; keep its sheet image beside it, at the relative path `meta.image` names.\n- **Web page**: an `.html` or `.htm` `src` loads only the relative paths named in its tags and styles.\n- **Mermaid**: a `.mmd` or `.mermaid` `src` draws a diagram and shows its source if it cannot render.\n- **Documents**: PDF, DOCX, and PPTX open in a read-only viewer with page and zoom controls. DOCX and PPTX previews use LibreOffice and the fonts installed on the Runner. The original remains downloadable.\n- **3D models**: a self-contained `.glb` or a `.blend` with saved meshes opens in a read-only viewer with rotation, zoom, reset, and original-file download.\n- **Excel**: a `.xlsx` draws a read-only workbook with sheet tabs, formulas, and saved results.\n- **Text**: code and other text files show as highlighted text; a `.diff` or `.patch` shows its added and removed lines.\n\n### Audio and video captions\n\nSave the media and caption files with the task and add an Asset in its Preview. Video captions appear in the timecoded list. An optional `overlay` still controls the video layer.\n\n```html\n<Asset src=".assets/42/interview.mp3" captions=".assets/42/interview.vtt" label="Interview" />\n```\n\nFor `variants`, give `captions` exactly the same labels and a caption path for each version.\n\n```html\n<Asset src=".assets/42/demo.en.mp4" variants=\'{"English":".assets/42/demo.en.mp4","\u4E2D\u6587":".assets/42/demo.zh.mp4"}\' captions=\'{"English":".assets/42/demo.en.srt","\u4E2D\u6587":".assets/42/demo.zh.srt"}\' label="Demo" />\n```\n\n### Video overlay\n\nOverlay HTML and CSS use the video\'s original dimensions. Keep images, stylesheets and fonts at paths relative to the HTML file. Scripts are disabled. Time bounds are in seconds, with the start included and the end excluded. Omit either bound to start at zero or continue through the end. Elements without time bounds are displayed as authored.\n\n```html\n<Asset src=".assets/42/demo.mp4" label="Demo" overlay=".assets/42/overlay.html" />\n```\n\nIn `overlay.html`:\n\n```html\n<div data-overlay-start="1.25" data-overlay-end="3.5"\n style="position:absolute; left:6%; bottom:12%; font-size:48px; color:white">\n <img src="images/star.png" width="48" alt=""> <strong style="color:gold">New</strong> chapter\n</div>\n```\n';
163249
+ var Asset_default = '# Asset\n\nShow a file as a Preview with `<Asset src=".assets/<card id>/<file>" label="..." />` alone in a paragraph.\nInline and fenced examples remain text.\n\n- **Label**: use a few words; an image\'s optional `alt` is its shipped caption and cannot contain `<`, `>` or its enclosing quote.\n- **Device**: use a separate tag for each device view, with `device="mobile"` or `device="desktop"`; both may reference the same responsive page.\n- **Variants**: versions of the same content on the same device share one tag with `variants=\'{"English": ".assets/<card id>/page.en.html", "\u4E2D\u6587": ".assets/<card id>/page.zh.html"}\'`, with `src` shown first; alternatives stay separate tags.\n- **Loop**: add `loop` for muted, looping video without controls.\n- **Playable**: add `playable` for an interactive HTML game in a 16:9 sandboxed viewport with click-to-focus keyboard capture and fullscreen pointer lock.\n- **Captions**: `captions` binds a UTF-8 SRT or WebVTT file to an audio or video Asset. The timecoded list seeks the player and highlights the current line. Both original files are available in the Asset menu.\n- **Video overlay**: `overlay=".assets/42/overlay.html"` shares a transparent HTML layer across versions. Use a JSON object keyed by exact `variants` labels for separate `.html` or `.htm` files. A missing or failed overlay leaves the video playable.\n- **Tiled map**: a `.tmx` or `.tmj` `src` draws as a map; keep its `.tsx`/`.tsj` tilesets and images beside it, at the relative paths it names.\n- **Sprite animation**: a TexturePacker JSON (Hash or Array) `src` plays as an animation; keep its sheet image beside it, at the relative path `meta.image` names.\n- **Web page**: an `.html` or `.htm` `src` loads only the relative paths named in its tags and styles.\n- **Mermaid**: a `.mmd` or `.mermaid` `src` draws a diagram and shows its source if it cannot render.\n- **Documents**: PDF, DOCX, and PPTX open in a read-only viewer with page and zoom controls. DOCX and PPTX previews use LibreOffice and the fonts installed on the Runner. The original remains downloadable.\n- **3D models**: a self-contained `.glb` or a `.blend` with saved meshes opens in a read-only viewer with rotation, zoom, reset, and original-file download.\n- **Excel**: a `.xlsx` draws a read-only workbook with sheet tabs, formulas, and saved results.\n- **Text**: code and other text files show as highlighted text; a `.diff` or `.patch` shows its added and removed lines.\n\n### Audio and video captions\n\nSave the media and caption files with the task and add an Asset in its Preview. Video captions appear in the timecoded list. An optional `overlay` still controls the video layer.\n\n```html\n<Asset src=".assets/42/interview.mp3" captions=".assets/42/interview.vtt" label="Interview" />\n```\n\nFor `variants`, give `captions` exactly the same labels and a caption path for each version.\n\n```html\n<Asset src=".assets/42/demo.en.mp4" variants=\'{"English":".assets/42/demo.en.mp4","\u4E2D\u6587":".assets/42/demo.zh.mp4"}\' captions=\'{"English":".assets/42/demo.en.srt","\u4E2D\u6587":".assets/42/demo.zh.srt"}\' label="Demo" />\n```\n\n### Video overlay\n\nOverlay HTML and CSS use the video\'s original dimensions. Keep images, stylesheets and fonts at paths relative to the HTML file. Scripts are disabled. Time bounds are in seconds, with the start included and the end excluded. Omit either bound to start at zero or continue through the end. Elements without time bounds are displayed as authored.\n\n```html\n<Asset src=".assets/42/demo.mp4" label="Demo" overlay=".assets/42/overlay.html" />\n```\n\nIn `overlay.html`:\n\n```html\n<div data-overlay-start="1.25" data-overlay-end="3.5"\n style="position:absolute; left:6%; bottom:12%; font-size:48px; color:white">\n <img src="images/star.png" width="48" alt=""> <strong style="color:gold">New</strong> chapter\n</div>\n```\n';
162860
163250
 
162861
163251
  // ../cli/src/components/Compare.md
162862
163252
  var Compare_default = '# Compare\n\nShow two files with `<Compare a="<src>" b="<src>" label="..." a-label="..." b-label="..." />` alone in a paragraph; never render a side-by-side file for it. Inline and fenced examples remain text.\n\n- **Sides**: either side may be anything an Asset shows, of different kinds, but not another compare; two images or two videos share one viewer, any other pair shows as two Assets.\n- **Video shots**: add `shots="<src>"`, a JSON list of `{ "id": "S1", "start": 0, "end": 2.25, "name": "..." }` covering video A in order, or a storyboard of A.\n- **Storyboard pairing**: beside video A, B may be a storyboard of it; it shows the shot with the id A is on, beside that shot of a storyboard `shots`.\n- **Data contract**: follow the producing agent\'s file contract and validator for storyboards.\n';
@@ -163753,7 +164143,7 @@ var tiled_default = `{
163753
164143
  var video_default = '{ "name": "video", "title": { "en": "Video", "zh": "\u89C6\u9891" }, "types": ["video"] }\n';
163754
164144
 
163755
164145
  // ../artifact-sdk/src/builtin/studio.json
163756
- var studio_default = '{\n "name": "studio",\n "title": {\n "en": "Studio",\n "zh": "\\u5de5\\u4f5c\\u53f0"\n },\n "types": [\n "studio"\n ],\n "schema": {\n "anyOf": [\n {\n "type": "object",\n "required": [\n "rounds",\n "land",\n "scheduled"\n ],\n "properties": {\n "rounds": {\n "type": "array",\n "items": {\n "type": "array",\n "minItems": 1,\n "items": {\n "type": "object",\n "required": [\n "agent",\n "title"\n ],\n "properties": {\n "agent": {\n "type": "string"\n },\n "title": {\n "type": "object",\n "required": [\n "en"\n ]\n }\n }\n }\n }\n },\n "land": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "agent",\n "title"\n ]\n }\n },\n "scheduled": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "agent",\n "title"\n ]\n }\n },\n "version": {\n "enum": [\n 1\n ]\n }\n }\n },\n {\n "type": "object",\n "required": [\n "version",\n "base",\n "fingerprint",\n "files"\n ],\n "properties": {\n "version": {\n "const": 2\n },\n "base": {\n "anyOf": [\n {\n "type": "null"\n },\n {\n "type": "object",\n "required": [\n "id",\n "version",\n "fingerprint"\n ],\n "properties": {\n "id": {\n "type": "string",\n "minLength": 1\n },\n "version": {\n "type": "integer",\n "minimum": 1\n },\n "fingerprint": {\n "type": "string",\n "minLength": 1\n }\n }\n }\n ]\n },\n "fingerprint": {\n "type": "string",\n "minLength": 1\n },\n "agents": {\n "type": "array",\n "maxItems": 500,\n "items": {\n "type": "object",\n "required": [\n "agent",\n "title"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "title": {\n "type": "object",\n "required": [\n "en"\n ],\n "properties": {\n "en": {\n "type": "string",\n "minLength": 1\n },\n "zh": {\n "type": "string"\n }\n }\n }\n }\n }\n },\n "files": {\n "type": "array",\n "maxItems": 1000,\n "items": {\n "type": "object",\n "required": [\n "path",\n "before",\n "after"\n ],\n "properties": {\n "path": {\n "type": "string",\n "minLength": 1\n },\n "before": {\n "anyOf": [\n {\n "type": "string",\n "minLength": 1\n },\n {\n "type": "null"\n }\n ]\n },\n "after": {\n "anyOf": [\n {\n "type": "string",\n "minLength": 1\n },\n {\n "type": "null"\n }\n ]\n },\n "diff": {\n "type": "string",\n "minLength": 1\n }\n }\n }\n },\n "results": {\n "type": "array",\n "maxItems": 500,\n "items": {\n "anyOf": [\n {\n "type": "object",\n "required": [\n "agent",\n "component",\n "src"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "component": {\n "const": "Asset"\n },\n "src": {\n "type": "string",\n "minLength": 1\n },\n "label": {\n "type": "string"\n },\n "alt": {\n "type": "string"\n },\n "device": {\n "enum": [\n "mobile",\n "desktop"\n ]\n },\n "loop": {\n "type": "boolean"\n },\n "variants": {\n "type": "object",\n "additionalProperties": {\n "type": "string",\n "minLength": 1\n }\n }\n }\n },\n {\n "type": "object",\n "required": [\n "agent",\n "component",\n "label",\n "items"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "component": {\n "const": "Set"\n },\n "label": {\n "type": "string"\n },\n "items": {\n "type": "array",\n "minItems": 1,\n "maxItems": 500,\n "items": {\n "type": "object",\n "required": [\n "src"\n ],\n "properties": {\n "src": {\n "type": "string",\n "minLength": 1\n },\n "label": {\n "type": "string"\n },\n "alt": {\n "type": "string"\n },\n "device": {\n "enum": [\n "mobile",\n "desktop"\n ]\n },\n "loop": {\n "type": "boolean"\n },\n "variants": {\n "type": "object",\n "additionalProperties": {\n "type": "string",\n "minLength": 1\n }\n }\n }\n }\n }\n }\n },\n {\n "type": "object",\n "required": [\n "agent",\n "component",\n "a",\n "b"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "component": {\n "const": "Compare"\n },\n "a": {\n "type": "string",\n "minLength": 1\n },\n "b": {\n "type": "string",\n "minLength": 1\n },\n "shots": {\n "type": "string",\n "minLength": 1\n },\n "label": {\n "type": "string"\n },\n "a-label": {\n "type": "string"\n },\n "b-label": {\n "type": "string"\n }\n }\n },\n {\n "type": "object",\n "required": [\n "agent",\n "component",\n "src"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "component": {\n "const": "Storyboard"\n },\n "src": {\n "type": "string",\n "minLength": 1\n },\n "label": {\n "type": "string"\n }\n }\n }\n ]\n }\n }\n }\n }\n ]\n },\n "references": [\n {\n "json": "/files/*/before"\n },\n {\n "json": "/files/*/after"\n },\n {\n "json": "/files/*/diff"\n },\n {\n "json": "/results/*/src",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/variants/*",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/a",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/b",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/shots",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/src",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/variants/*",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/a",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/b",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/shots",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n }\n ]\n}\n';
164146
+ var studio_default = '{\n "name": "studio",\n "title": {\n "en": "Studio",\n "zh": "\\u5de5\\u4f5c\\u53f0"\n },\n "types": [\n "studio"\n ],\n "schema": {\n "anyOf": [\n {\n "type": "object",\n "required": [\n "rounds",\n "land",\n "scheduled"\n ],\n "properties": {\n "rounds": {\n "type": "array",\n "items": {\n "type": "array",\n "minItems": 1,\n "items": {\n "type": "object",\n "required": [\n "agent",\n "title"\n ],\n "properties": {\n "agent": {\n "type": "string"\n },\n "title": {\n "type": "object",\n "required": [\n "en"\n ]\n }\n }\n }\n }\n },\n "land": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "agent",\n "title"\n ]\n }\n },\n "scheduled": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "agent",\n "title"\n ]\n }\n },\n "version": {\n "enum": [\n 1\n ]\n }\n }\n },\n {\n "type": "object",\n "required": [\n "version",\n "base",\n "fingerprint",\n "files"\n ],\n "properties": {\n "version": {\n "const": 2\n },\n "base": {\n "anyOf": [\n {\n "type": "null"\n },\n {\n "type": "object",\n "required": [\n "id",\n "version",\n "fingerprint"\n ],\n "properties": {\n "id": {\n "type": "string",\n "minLength": 1\n },\n "version": {\n "type": "integer",\n "minimum": 1\n },\n "fingerprint": {\n "type": "string",\n "minLength": 1\n }\n }\n }\n ]\n },\n "fingerprint": {\n "type": "string",\n "minLength": 1\n },\n "agents": {\n "type": "array",\n "maxItems": 500,\n "items": {\n "type": "object",\n "required": [\n "agent",\n "title"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "title": {\n "type": "object",\n "required": [\n "en"\n ],\n "properties": {\n "en": {\n "type": "string",\n "minLength": 1\n },\n "zh": {\n "type": "string"\n }\n }\n }\n }\n }\n },\n "files": {\n "type": "array",\n "maxItems": 1000,\n "items": {\n "type": "object",\n "required": [\n "path",\n "before",\n "after"\n ],\n "properties": {\n "path": {\n "type": "string",\n "minLength": 1\n },\n "before": {\n "anyOf": [\n {\n "type": "string",\n "minLength": 1\n },\n {\n "type": "null"\n }\n ]\n },\n "after": {\n "anyOf": [\n {\n "type": "string",\n "minLength": 1\n },\n {\n "type": "null"\n }\n ]\n },\n "diff": {\n "type": "string",\n "minLength": 1\n }\n }\n }\n },\n "results": {\n "type": "array",\n "maxItems": 500,\n "items": {\n "anyOf": [\n {\n "type": "object",\n "required": [\n "agent",\n "component",\n "src"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "component": {\n "const": "Asset"\n },\n "src": {\n "type": "string",\n "minLength": 1\n },\n "label": {\n "type": "string"\n },\n "alt": {\n "type": "string"\n },\n "device": {\n "enum": [\n "mobile",\n "desktop"\n ]\n },\n "loop": {\n "type": "boolean"\n },\n "playable": {\n "type": "boolean"\n },\n "variants": {\n "type": "object",\n "additionalProperties": {\n "type": "string",\n "minLength": 1\n }\n }\n }\n },\n {\n "type": "object",\n "required": [\n "agent",\n "component",\n "label",\n "items"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "component": {\n "const": "Set"\n },\n "label": {\n "type": "string"\n },\n "items": {\n "type": "array",\n "minItems": 1,\n "maxItems": 500,\n "items": {\n "type": "object",\n "required": [\n "src"\n ],\n "properties": {\n "src": {\n "type": "string",\n "minLength": 1\n },\n "label": {\n "type": "string"\n },\n "alt": {\n "type": "string"\n },\n "device": {\n "enum": [\n "mobile",\n "desktop"\n ]\n },\n "loop": {\n "type": "boolean"\n },\n "playable": {\n "type": "boolean"\n },\n "variants": {\n "type": "object",\n "additionalProperties": {\n "type": "string",\n "minLength": 1\n }\n }\n }\n }\n }\n }\n },\n {\n "type": "object",\n "required": [\n "agent",\n "component",\n "a",\n "b"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "component": {\n "const": "Compare"\n },\n "a": {\n "type": "string",\n "minLength": 1\n },\n "b": {\n "type": "string",\n "minLength": 1\n },\n "shots": {\n "type": "string",\n "minLength": 1\n },\n "label": {\n "type": "string"\n },\n "a-label": {\n "type": "string"\n },\n "b-label": {\n "type": "string"\n }\n }\n },\n {\n "type": "object",\n "required": [\n "agent",\n "component",\n "src"\n ],\n "properties": {\n "agent": {\n "type": "string",\n "minLength": 1\n },\n "component": {\n "const": "Storyboard"\n },\n "src": {\n "type": "string",\n "minLength": 1\n },\n "label": {\n "type": "string"\n }\n }\n }\n ]\n }\n }\n }\n }\n ]\n },\n "references": [\n {\n "json": "/files/*/before"\n },\n {\n "json": "/files/*/after"\n },\n {\n "json": "/files/*/diff"\n },\n {\n "json": "/results/*/src",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/variants/*",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/a",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/b",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/shots",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/src",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/variants/*",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/a",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/b",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n },\n {\n "json": "/results/*/items/*/shots",\n "types": [\n "storyboard",\n "compare",\n "spritesheet",\n "studio",\n "asset"\n ]\n }\n ]\n}\n';
163757
164147
 
163758
164148
  // ../artifact-sdk/src/builtin/index.ts
163759
164149
  var read2 = (m) => typeof m === "string" ? JSON.parse(m) : m;
@@ -163822,9 +164212,9 @@ function schemaProblem(schema, value, at2 = "") {
163822
164212
  var text2 = (v) => typeof v === "string" && v.length > 0;
163823
164213
  var source = (v) => text2(v) && !/^(?:[a-z][\w+.-]*:|\/|#)|\\|[\u0000-\u001f]/i.test(v);
163824
164214
  var icon2 = (v) => v === void 0 || typeof v === "string" || Array.isArray(v) && v.length > 0 && v.length <= 12 && v.every((p2) => isObject(p2) && text2(p2.d) && /^[MmLlHhVvCcSsQqTtAaZz0-9.,\s-]+$/.test(p2.d) && ["f", "s"].every((k2) => p2[k2] === void 0 || typeof p2[k2] === "string" && /^[kwcgopsmlry]$/.test(p2[k2])) && (p2.o === void 0 || p2.o === true) && (p2.w === void 0 || typeof p2.w === "number" && p2.w > 0 && p2.w <= 3));
163825
- var relativePath = (v) => source(v) && v.split("/").every((p2) => p2 && p2 !== "." && p2 !== "..");
164215
+ var relativePath = (v) => text2(v) && !/^(?:[a-z][\w+.-]*:|\/)|\\|[\u0000-\u001f]/i.test(v) && v.split("/").every((p2) => p2 && p2 !== "." && p2 !== "..");
163826
164216
  var optionalText = (v, keys) => keys.every((k2) => v[k2] === void 0 || typeof v[k2] === "string");
163827
- var asset2 = (v) => isObject(v) && source(v.src) && optionalText(v, ["label", "alt"]) && (v.alt === void 0 || !/[<>]/.test(v.alt)) && (v.device === void 0 || v.device === "desktop" || v.device === "mobile") && (v.loop === void 0 || typeof v.loop === "boolean") && (v.variants === void 0 || isObject(v.variants) && Object.values(v.variants).every(source));
164217
+ var asset2 = (v) => isObject(v) && source(v.src) && optionalText(v, ["label", "alt"]) && (v.alt === void 0 || !/[<>]/.test(v.alt)) && (v.device === void 0 || v.device === "desktop" || v.device === "mobile") && (v.loop === void 0 || typeof v.loop === "boolean") && (v.playable === void 0 || typeof v.playable === "boolean") && (v.variants === void 0 || isObject(v.variants) && Object.values(v.variants).every(source));
163828
164218
  function resultProblem(value, agents) {
163829
164219
  if (!Array.isArray(value) || value.length > 500) return "/results";
163830
164220
  for (let i = 0; i < value.length; i++) {
@@ -163849,7 +164239,7 @@ function reviewProblem(v) {
163849
164239
  const paths = /* @__PURE__ */ new Set();
163850
164240
  for (const f2 of v.files) {
163851
164241
  if (!isObject(f2) || !relativePath(f2.path) || paths.has(f2.path) || !(f2.before === null || source(f2.before)) || !(f2.after === null || source(f2.after)) || f2.before === null && f2.after === null || f2.diff !== void 0 && !source(f2.diff) || (f2.before === null || f2.after === null) && !f2.diff) return "/files";
163852
- if (f2.path.startsWith("agents/") && !agents.has(f2.path.split("/")[1])) return "/files";
164242
+ if (v.agents !== void 0 && f2.path.startsWith("agents/") && !agents.has(f2.path.split("/")[1])) return "/files";
163853
164243
  paths.add(f2.path);
163854
164244
  }
163855
164245
  return v.results === void 0 ? null : resultProblem(v.results, agents);
@@ -164034,8 +164424,8 @@ function collectSources(sources3, card, host) {
164034
164424
 
164035
164425
  // src/task-folder.ts
164036
164426
  init_file_limits();
164037
- import { setTimeout as delay2 } from "node:timers/promises";
164038
- import crypto7 from "node:crypto";
164427
+ import { setTimeout as delay3 } from "node:timers/promises";
164428
+ import crypto8 from "node:crypto";
164039
164429
  import fs46 from "node:fs";
164040
164430
  import path49 from "node:path";
164041
164431
  import { isDeepStrictEqual } from "node:util";
@@ -164372,8 +164762,8 @@ function logSync(event2, fields2 = {}) {
164372
164762
  if (syncDebug) console.error("[sync-debug]", JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString(), pid: process.pid, event: event2, ...fields2 }));
164373
164763
  }
164374
164764
  if (syncDebug) {
164375
- const delay4 = monitorEventLoopDelay({ resolution: 20 });
164376
- delay4.enable();
164765
+ const delay5 = monitorEventLoopDelay({ resolution: 20 });
164766
+ delay5.enable();
164377
164767
  let cpu = process.cpuUsage();
164378
164768
  let at2 = performance.now();
164379
164769
  setInterval(() => {
@@ -164381,14 +164771,14 @@ if (syncDebug) {
164381
164771
  const used = process.cpuUsage(cpu);
164382
164772
  logSync("health", {
164383
164773
  cpuPercent: Math.round((used.user + used.system) / (now - at2) / 10),
164384
- delayMaxMs: Math.round(delay4.max / 1e6),
164385
- delayP99Ms: Math.round(delay4.percentile(99) / 1e6),
164774
+ delayMaxMs: Math.round(delay5.max / 1e6),
164775
+ delayP99Ms: Math.round(delay5.percentile(99) / 1e6),
164386
164776
  ...counts
164387
164777
  });
164388
164778
  for (const name of Object.keys(counts)) delete counts[name];
164389
164779
  cpu = process.cpuUsage();
164390
164780
  at2 = now;
164391
- delay4.reset();
164781
+ delay5.reset();
164392
164782
  }, 5e3).unref();
164393
164783
  }
164394
164784
 
@@ -164601,7 +164991,7 @@ function writeBase(ws, base) {
164601
164991
  fs46.writeFileSync(`${file3}.tmp`, JSON.stringify(base));
164602
164992
  fs46.renameSync(`${file3}.tmp`, file3);
164603
164993
  }
164604
- var hashOf2 = (bytes2) => crypto7.createHash("sha256").update(bytes2).digest("hex");
164994
+ var hashOf2 = (bytes) => crypto8.createHash("sha256").update(bytes).digest("hex");
164605
164995
  function hashFile(file3) {
164606
164996
  try {
164607
164997
  return hashOf2(fs46.readFileSync(file3));
@@ -164609,9 +164999,9 @@ function hashFile(file3) {
164609
164999
  return null;
164610
165000
  }
164611
165001
  }
164612
- function write(file3, bytes2) {
165002
+ function write(file3, bytes) {
164613
165003
  fs46.mkdirSync(path49.dirname(file3), { recursive: true });
164614
- fs46.writeFileSync(file3, bytes2);
165004
+ fs46.writeFileSync(file3, bytes);
164615
165005
  }
164616
165006
  function readText(file3) {
164617
165007
  try {
@@ -164660,53 +165050,79 @@ var localFiles = (ws, base) => {
164660
165050
  const assets = /* @__PURE__ */ new Set([...assetFiles(ws, assetsListOf(ws, base)), ...assetFiles(ws, readText(path49.join(ws.board, assetsFile(ws.task))))]);
164661
165051
  return filesUnder(ws.board, ws.board, path49.join(ws.board, "deliveries")).filter((p2) => kept3(p2) && !assets.has(p2));
164662
165052
  };
164663
- var SKILL_PATH = /^skills\/([a-z0-9]+(?:-[a-z0-9]+)*)\/((?:[\w.-]+\/)*[\w.-]+)$/;
164664
- function pullTools(ws, record2, files) {
164665
- const held5 = record2.tools?.skills ?? {};
164666
- const ours = new Set(Object.keys(held5).map((name) => name.split("/")[1]));
164667
- const theirs = (skill) => !ours.has(skill) && SKILL_ROOTS.some((root2) => fs46.existsSync(path49.join(ws.cwd, root2, skill)));
164668
- const kept4 = Object.keys(files).map((name) => SKILL_PATH.exec(name)?.[1]).filter((skill) => skill && !theirs(skill));
164669
- const skills = {};
164670
- for (const [name, text4] of Object.entries(files)) {
164671
- const at2 = SKILL_PATH.exec(name);
164672
- if (!at2 || at2[1] === "kanban" || !kept4.includes(at2[1]) || at2[2].split("/").includes("..")) continue;
164673
- skills[name] = hashOf2(text4);
164674
- for (const root2 of SKILL_ROOTS) {
164675
- const file3 = path49.join(ws.cwd, root2, at2[1], at2[2]);
164676
- if (held5[name] !== skills[name] || hashFile(file3) !== skills[name]) write(file3, text4);
164677
- }
164678
- }
164679
- for (const name of Object.keys(held5)) {
164680
- if (skills[name]) continue;
164681
- const [, skill, rest] = SKILL_PATH.exec(name) ?? [];
164682
- if (!skill || !rest) continue;
165053
+ function removePlacedSkills(ws, held5) {
165054
+ for (const [name, hash2] of Object.entries(held5)) {
165055
+ const [top, skill, ...rest] = name.split("/");
165056
+ if (top !== "skills" || !skill || skill === "kanban" || !rest.length || !safeStudioPath(name)) continue;
164683
165057
  for (const root2 of SKILL_ROOTS) {
164684
- fs46.rmSync(path49.join(ws.cwd, root2, skill, rest), { force: true });
164685
- if (!Object.keys(skills).some((n) => n.startsWith(`skills/${skill}/`))) fs46.rmSync(path49.join(ws.cwd, root2, skill), { recursive: true, force: true });
165058
+ const boundary = path49.join(ws.cwd, root2);
165059
+ const file3 = path49.join(boundary, skill, ...rest);
165060
+ let current2 = ws.cwd;
165061
+ const safe3 = [...root2.split("/"), skill, ...rest].every((part) => {
165062
+ current2 = path49.join(current2, part);
165063
+ const entry = fs46.lstatSync(current2, { throwIfNoEntry: false });
165064
+ return current2 === file3 ? entry?.isFile() : entry?.isDirectory();
165065
+ });
165066
+ if (!safe3 || hashFile(file3) !== hash2) continue;
165067
+ fs46.rmSync(file3, { force: true });
165068
+ for (let dir = path49.dirname(file3); dir !== boundary; dir = path49.dirname(dir)) {
165069
+ try {
165070
+ fs46.rmdirSync(dir);
165071
+ } catch {
165072
+ break;
165073
+ }
165074
+ }
164686
165075
  }
164687
165076
  }
164688
- const names2 = [...new Set(Object.keys(skills).map((name) => name.split("/")[1]))];
164689
- if (names2.length) keepOutOfGit(ws.cwd, SKILL_ROOTS.flatMap((root2) => names2.map((n) => `${root2}/${n}`)));
164690
- let mcp = {};
165077
+ }
165078
+ function studioMcp(files) {
164691
165079
  try {
164692
- mcp = JSON.parse(files["mcp.json"] ?? "{}").mcpServers ?? {};
165080
+ return JSON.parse(files["mcp.json"] ?? "{}").mcpServers ?? {};
164693
165081
  } catch {
165082
+ return {};
164694
165083
  }
164695
- record2.tools = { skills, mcp };
164696
165084
  }
164697
- var mcpServersOf = (ws) => readRecord(ws).tools?.mcp ?? {};
164698
- async function studioFiles(task) {
164699
- const read6 = await readTaskStudio(task);
164700
- if (!read6.ok) return read6;
164701
- savePin(task, { id: read6.value.studio, version: read6.value.version ?? 1, name: read6.value.name ?? read6.value.studio, files: read6.value.files, historicalPreviews: read6.value.historicalPreviews });
164702
- return { ok: true, value: read6.value.files };
165085
+ var mcpServersOf = (ws) => {
165086
+ const pin = ws.studioSnapshot;
165087
+ const held5 = pin && readVersion2(pin.studio, pin.version);
165088
+ return held5 ? studioMcp(held5.files) : readRecord(ws).tools?.mcp ?? {};
165089
+ };
165090
+ async function studioFiles(ws) {
165091
+ const requested = ws.studioSnapshot;
165092
+ const route = "/v1/tasks/" + encodeURIComponent(ws.task) + "/studio";
165093
+ const read6 = await loadPublishedStudio(route, (route2) => request("GET", route2), download, requested);
165094
+ if (!read6.ok) {
165095
+ if (!requested || !["not_found", "invalid_response"].includes(read6.code ?? "")) return read6;
165096
+ const cached3 = readVersion2(requested.studio, requested.version);
165097
+ if (!cached3) return { ok: false, error: missingStudioVersion(requested), code: "studio_version_missing" };
165098
+ ws.bindStudio?.(requested);
165099
+ return { ok: true, value: cached3.files };
165100
+ }
165101
+ if (!read6.value) {
165102
+ const pin = ws.studioSnapshot ?? readPin(ws.task);
165103
+ const held6 = pin && readVersion2(pin.studio, pin.version);
165104
+ if (requested) {
165105
+ if (!held6) return { ok: false, code: "studio_version_missing", error: missingStudioVersion(requested) };
165106
+ ws.bindStudio?.(requested);
165107
+ }
165108
+ return { ok: true, value: held6?.files ?? {} };
165109
+ }
165110
+ const held5 = read6.value;
165111
+ const snapshot = { studio: held5.id, version: held5.version, historicalPreviews: held5.historicalPreviews };
165112
+ ws.studioSnapshot = snapshot;
165113
+ ws.bindStudio?.(snapshot);
165114
+ if (!requested) savePin(ws.task, held5, true);
165115
+ return { ok: true, value: held5.files };
164703
165116
  }
164704
165117
  async function pullStudio(ws, record2) {
164705
165118
  if (ws.cloudTask === ws.task) {
164706
165119
  record2.builtin = ws.studio?.startsWith("wf_builtin_") ?? false;
164707
- const files = await studioFiles(ws.task);
164708
- if (!files.ok && files.code !== "not_found") return files;
164709
- if (files.ok) pullTools(ws, record2, files.value);
165120
+ const files = await studioFiles(ws);
165121
+ if (!files.ok && (ws.studioSnapshot || files.code !== "not_found")) return files;
165122
+ if (files.ok) {
165123
+ removePlacedSkills(ws, record2.tools?.skills ?? {});
165124
+ record2.tools = { skills: {}, mcp: studioMcp(files.value) };
165125
+ }
164710
165126
  }
164711
165127
  dropPlacedAgents(ws);
164712
165128
  for (const name of Object.keys(record2.agents ?? {})) fs46.rmSync(path49.join(ws.board, name), { force: true });
@@ -165128,14 +165544,14 @@ async function pullAssets(ws, record2, assets, preserve = false, stopped2) {
165128
165544
  out[name] = { ...held5, kind };
165129
165545
  continue;
165130
165546
  }
165131
- const bytes2 = await readAsset(ref.artifact, version2);
165132
- if (!bytes2.ok && unavailable2(bytes2)) continue;
165133
- if (!bytes2.ok && bytes2.code === "not_found") {
165547
+ const bytes = await readAsset(ref.artifact, version2);
165548
+ if (!bytes.ok && unavailable2(bytes)) continue;
165549
+ if (!bytes.ok && bytes.code === "not_found") {
165134
165550
  if (held5) out[name] = held5;
165135
165551
  continue;
165136
165552
  }
165137
- if (!bytes2.ok) return bytes2;
165138
- let local = bytes2.value;
165553
+ if (!bytes.ok) return bytes;
165554
+ let local = bytes.value;
165139
165555
  const dependencies = [];
165140
165556
  const manifest = fileManifest(kind, name);
165141
165557
  let data;
@@ -165189,7 +165605,7 @@ async function pullAssets(ws, record2, assets, preserve = false, stopped2) {
165189
165605
  continue;
165190
165606
  }
165191
165607
  write(target, local);
165192
- const hash2 = hashOf2(typeof data === "string" ? local : bytes2.value);
165608
+ const hash2 = hashOf2(typeof data === "string" ? local : bytes.value);
165193
165609
  out[name] = { ...held5, kind, dependencies: [...new Set(dependencies)], artifact: ref.artifact, version: version2, hash: hash2, localHash: hashOf2(local) };
165194
165610
  }
165195
165611
  record2.assets = out;
@@ -165250,19 +165666,19 @@ function undrawn(ws, reason) {
165250
165666
  }
165251
165667
  return reason.replace(/ \(at [^)]*file:\/\/[^)]*\)$/, "").slice(0, 500);
165252
165668
  }
165253
- async function uploadAsset(artifact, { bytes: bytes2, type }) {
165254
- const upload2 = await createUpload(artifact, type, Math.max(bytes2.length, 1));
165669
+ async function uploadAsset(artifact, { bytes, type }) {
165670
+ const upload2 = await createUpload(artifact, type, Math.max(bytes.length, 1));
165255
165671
  if (!upload2.ok) return upload2;
165256
165672
  const { id: id2, url: url2, parts } = upload2.value;
165257
165673
  if (parts) {
165258
165674
  for (let part = 1; part <= parts.count; part++) {
165259
- const put = await upload(parts.url.replace("{part}", String(part)), bytes2.subarray((part - 1) * parts.size, part * parts.size), type);
165675
+ const put = await upload(parts.url.replace("{part}", String(part)), bytes.subarray((part - 1) * parts.size, part * parts.size), type);
165260
165676
  if (!put.ok) return put;
165261
165677
  }
165262
165678
  const done = await completeUpload(url2 ?? `/v1/uploads/${encodeURIComponent(id2)}/complete`);
165263
165679
  if (!done.ok) return done;
165264
165680
  } else {
165265
- const put = await upload(url2 ?? `/v1/uploads/${encodeURIComponent(id2)}`, bytes2, type);
165681
+ const put = await upload(url2 ?? `/v1/uploads/${encodeURIComponent(id2)}`, bytes, type);
165266
165682
  if (!put.ok) return put;
165267
165683
  }
165268
165684
  return { ok: true, value: id2 };
@@ -165288,19 +165704,19 @@ async function pushDocumentPreview(ws, record2, key, ext, source2) {
165288
165704
  record2.pendingVersions ??= {};
165289
165705
  let pending = record2.pendingVersions[key];
165290
165706
  if (!pending) {
165291
- let bytes2;
165707
+ let bytes;
165292
165708
  try {
165293
165709
  const { renderOfficePdf: renderOfficePdf2 } = await Promise.resolve().then(() => (init_document_preview(), document_preview_exports));
165294
- bytes2 = await renderOfficePdf2(source2, ext);
165710
+ bytes = await renderOfficePdf2(source2, ext);
165295
165711
  } catch (error62) {
165296
165712
  logSync("assets.documentPreviewUnavailable", { project: ws.project, task: ws.task, reason: error62 instanceof Error ? error62.message : String(error62) });
165297
165713
  return { ok: true, value: void 0 };
165298
165714
  }
165299
165715
  const made = await createArtifact(ws.cloudTask, key, "asset", artifactKey(ws.cloudTask, key, "asset"));
165300
165716
  if (!made.ok) return made;
165301
- const sent = await uploadAsset(made.value.id, { bytes: bytes2, type: PDF, kind: "asset" });
165717
+ const sent = await uploadAsset(made.value.id, { bytes, type: PDF, kind: "asset" });
165302
165718
  if (!sent.ok) return sent;
165303
- pending = record2.pendingVersions[key] = { artifact: made.value.id, hash: hashOf2(bytes2), upload: sent.value };
165719
+ pending = record2.pendingVersions[key] = { artifact: made.value.id, hash: hashOf2(bytes), upload: sent.value };
165304
165720
  writeRecord(ws, record2);
165305
165721
  }
165306
165722
  const version2 = await finishAssetVersion(ws, record2, key, pending);
@@ -165545,7 +165961,7 @@ async function whenPrepared(ws, cancelled, work, stopped2 = () => false) {
165545
165961
  if (!busy(preparationKey(ws))) return { value: await work() };
165546
165962
  });
165547
165963
  if (result) return result.value;
165548
- await delay2(100);
165964
+ await delay3(100);
165549
165965
  }
165550
165966
  return cancelled;
165551
165967
  }
@@ -166026,7 +166442,7 @@ async function reconcileArchives(ws, base, archives, pending, machine) {
166026
166442
  if (!archive || archive.content !== local || readText(path49.join(ws.board, list3)) !== (manifest?.content ?? null)) continue;
166027
166443
  cards.push({ task, path: p2, seq: archive.seq, assets_seq: manifest?.seq ?? 0 });
166028
166444
  }
166029
- const save2 = (changed) => {
166445
+ const save3 = (changed) => {
166030
166446
  const next = Object.fromEntries(pending);
166031
166447
  if (!changed && isDeepStrictEqual(next, base.pendingArchives ?? {})) return;
166032
166448
  base.pendingArchives = next;
@@ -166034,7 +166450,7 @@ async function reconcileArchives(ws, base, archives, pending, machine) {
166034
166450
  delete base.reconciledArchives;
166035
166451
  writeBase(ws, base);
166036
166452
  };
166037
- save2(false);
166453
+ save3(false);
166038
166454
  for (let i = 0; i < cards.length; i += ARCHIVE_COMPLETION_BATCH) {
166039
166455
  const batch2 = cards.slice(i, i + ARCHIVE_COMPLETION_BATCH);
166040
166456
  const result = await completeArchives(ws.project, machine, batch2);
@@ -166047,7 +166463,7 @@ async function reconcileArchives(ws, base, archives, pending, machine) {
166047
166463
  errors[card.task] = { error: `Archive ${card.task}: ${result.error}`, code, offline: retry2, blocking: false };
166048
166464
  }
166049
166465
  logSync("board.archive_completion", { project: ws.project, code, pending: pending.size });
166050
- save2(true);
166466
+ save3(true);
166051
166467
  break;
166052
166468
  }
166053
166469
  const received = /* @__PURE__ */ new Map();
@@ -166067,18 +166483,22 @@ async function reconcileArchives(ws, base, archives, pending, machine) {
166067
166483
  errors[task] = { error: `Archive ${task}: ${receipt.message}`, code: receipt.code, offline: receipt.status === "pending", blocking: false };
166068
166484
  }
166069
166485
  }
166070
- save2(true);
166486
+ save3(true);
166071
166487
  }
166072
166488
  return errors;
166073
166489
  }
166074
166490
  function taskStudio(ws) {
166075
166491
  if (!ws.cloudTask) return null;
166076
- const pin = readPin(ws.cloudTask), held5 = pin && readVersion2(pin.studio, pin.version);
166077
- if (!held5) throw new Error("The task Studio version is not downloaded.");
166492
+ const pin = ws.studioSnapshot ?? readPin(ws.cloudTask), held5 = pin && readVersion2(pin.studio, pin.version);
166493
+ if (!held5) throw new Error(pin ? missingStudioVersion(pin) : "The task Studio version is not downloaded.");
166078
166494
  const read6 = parseStudioFile(studioName(held5.id), held5.files["STUDIO.md"] ?? "", "STUDIO.md");
166079
166495
  if ("problem" in read6) throw new Error(read6.problem);
166080
166496
  return { held: held5, def: read6.def };
166081
166497
  }
166498
+ function taskStudioSkills(ws) {
166499
+ const studio2 = taskStudio(ws);
166500
+ return studio2 ? cachedStudioSkillBlock(studio2.held) : "";
166501
+ }
166082
166502
  var taskStudioPreviews = (ws) => taskStudio(ws)?.def.previews;
166083
166503
  var taskConfig = (ws, id2, setup) => studioConfigContext(id2, setup, (file3) => readText(path49.join(ws.board, file3)) ?? void 0);
166084
166504
  function taskSetupContext(ws) {
@@ -166324,10 +166744,10 @@ async function answerHint(machineId2, hint2) {
166324
166744
 
166325
166745
  // ../cli/src/lib/agent/stop.ts
166326
166746
  import { spawnSync as spawnSync7 } from "node:child_process";
166327
- import { randomUUID as randomUUID5 } from "node:crypto";
166747
+ import { randomUUID as randomUUID6 } from "node:crypto";
166328
166748
  import fs49 from "node:fs";
166329
166749
  var runMark = (sessionId, since) => ({ name: RUN_ENV, value: sessionId, ...since === void 0 ? {} : { since } });
166330
- var stopMark = () => ({ name: STOP_ENV, value: randomUUID5(), since: Date.now() });
166750
+ var stopMark = () => ({ name: STOP_ENV, value: randomUUID6(), since: Date.now() });
166331
166751
  var markEnv = (env2, mark) => ({ ...env2, [mark.name]: mark.value });
166332
166752
  var WINDOWS3 = process.platform === "win32";
166333
166753
  function markedInProc(entry, strict = false, since) {
@@ -167085,6 +167505,7 @@ function parseStore() {
167085
167505
  runs.push({
167086
167506
  sessionId: entry.sessionId,
167087
167507
  cloudExecution: executionOf(entry.cloudExecution ?? null),
167508
+ studioPin: typeof entry.studioPin?.studio === "string" && Number.isSafeInteger(entry.studioPin.version) && entry.studioPin.version > 0 ? entry.studioPin : void 0,
167088
167509
  pendingWrites: entry.pendingWrites === true || void 0,
167089
167510
  submitted: entry.submitted === true || void 0,
167090
167511
  cardId: typeof entry.cardId === "number" ? entry.cardId : null,
@@ -167786,7 +168207,7 @@ var TAG3 = /^<Storyboard\b([^<>]*?)\/>$/;
167786
168207
  var attr = (name) => new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`);
167787
168208
  var SRC_ATTR = attr("src");
167788
168209
  var LABEL_ATTR = attr("label");
167789
- var SEGMENT2 = /^(?!\.)[^/\\]+$/;
168210
+ var SEGMENT = /^(?!\.)[^/\\]+$/;
167790
168211
  function storyboardAttrs(raw) {
167791
168212
  const m = TAG3.exec(raw.trim());
167792
168213
  if (!m) return null;
@@ -167827,7 +168248,7 @@ function assetName(src, cardId, exts, nested = false) {
167827
168248
  const parts = src.split("/");
167828
168249
  if (parts[0] !== ".assets" || parts.length < 3 || !nested && parts.length !== 3) return { expected, actual: JSON.stringify(src) };
167829
168250
  if (parts[1] !== String(cardId)) return { expected, actual: `another card's folder ${JSON.stringify(parts[1])}` };
167830
- if (!parts.slice(2).every((part) => SEGMENT2.test(part))) return { expected, actual: JSON.stringify(src) };
168251
+ if (!parts.slice(2).every((part) => SEGMENT.test(part))) return { expected, actual: JSON.stringify(src) };
167831
168252
  const name = parts.slice(2).join("/");
167832
168253
  const ext = name.split(".").pop().toLowerCase();
167833
168254
  if (exts.length && (!name.includes(".") || !exts.includes(ext))) return { expected, actual: `file type ${JSON.stringify(name.includes(".") ? ext : "")}` };
@@ -169140,6 +169561,13 @@ function cmdAgentFile(askedName, askedFile) {
169140
169561
 
169141
169562
  // ../cli/src/lib/agent/studio-shared.ts
169142
169563
  function studioFiles2(studio2) {
169564
+ const task = workspaceTask();
169565
+ const pin = task ? activeStudioPin(task) : null;
169566
+ if (pin && (pin.studio === studio2 || studioName(pin.studio) === studio2)) {
169567
+ const held5 = readVersion2(pin.studio, pin.version);
169568
+ if (!held5) throw new Error(missingStudioVersion(pin));
169569
+ return held5.files;
169570
+ }
169143
169571
  const flow = cloudFlows().find((f2) => f2.def.id === studio2 || f2.cloudId === studio2);
169144
169572
  if (flow) return flow.files;
169145
169573
  return null;
@@ -169151,14 +169579,21 @@ function cmdStudioFile(askedStudio, askedFile) {
169151
169579
  const files = studioFiles2(studio2);
169152
169580
  if (!files) die(`no studio ${studio2}`, { kind: "no-such-studio", studio: studio2 });
169153
169581
  const file3 = askedFile.trim().replace(/^\.\//, "");
169154
- const readable = Object.keys(files).filter((f2) => f2 === STUDIO_FILE || f2.startsWith("shared/") || f2.startsWith("references/") || f2.startsWith("scripts/") || f2 === "CARD.md").sort();
169155
- if (!readable.includes(file3) || isAboutFile(file3)) {
169582
+ const readable = Object.keys(files).filter((f2) => safeStudioPath(f2) && f2 !== VERSION_FILE && !isAboutFile(f2)).sort();
169583
+ if (!readable.includes(file3)) {
169156
169584
  die(`${studio2} has no ${file3}. It has: ${readable.join(", ")}.`, { kind: "no-such-studio-file", studio: studio2, file: file3 });
169157
169585
  }
169158
169586
  const text4 = files[file3];
169159
169587
  say(text4);
169160
169588
  return { studio: studio2, file: file3, text: text4 };
169161
169589
  }
169590
+ function cmdStudioSkills(studio2) {
169591
+ const files = studioFiles2(studio2.trim());
169592
+ if (!files) die("no studio " + studio2, { kind: "no-such-studio", studio: studio2 });
169593
+ const skills = studioSkills(files);
169594
+ for (const { name, description } of skills) say(name + " " + description);
169595
+ return { skills };
169596
+ }
169162
169597
 
169163
169598
  // ../cli/src/lib/memories.ts
169164
169599
  import fs66 from "node:fs";
@@ -169374,6 +169809,7 @@ var MOVES = {
169374
169809
  reject: ({ args: args2, opts }) => cmdRemove(Number(args2[0]), "rejected", as(opts)),
169375
169810
  "agent-file": ({ args: args2 }) => cmdAgentFile(args2[0] ?? "", args2[1] ?? ""),
169376
169811
  file: ({ args: args2 }) => cmdStudioFile(args2[0] ?? "", args2[1] ?? ""),
169812
+ skills: ({ args: args2 }) => cmdStudioSkills(args2[0] ?? ""),
169377
169813
  "memory-file": ({ args: args2 }) => cmdMemoryFile(args2[0] ?? "")
169378
169814
  };
169379
169815
  var BOARD_MOVES = new Set(Object.keys(MOVES));
@@ -170678,16 +171114,16 @@ function cleanEnum(obj3) {
170678
171114
  }
170679
171115
  function base64ToUint8Array(base643) {
170680
171116
  const binaryString = atob(base643);
170681
- const bytes2 = new Uint8Array(binaryString.length);
171117
+ const bytes = new Uint8Array(binaryString.length);
170682
171118
  for (let i = 0; i < binaryString.length; i++) {
170683
- bytes2[i] = binaryString.charCodeAt(i);
171119
+ bytes[i] = binaryString.charCodeAt(i);
170684
171120
  }
170685
- return bytes2;
171121
+ return bytes;
170686
171122
  }
170687
- function uint8ArrayToBase64(bytes2) {
171123
+ function uint8ArrayToBase64(bytes) {
170688
171124
  let binaryString = "";
170689
- for (let i = 0; i < bytes2.length; i++) {
170690
- binaryString += String.fromCharCode(bytes2[i]);
171125
+ for (let i = 0; i < bytes.length; i++) {
171126
+ binaryString += String.fromCharCode(bytes[i]);
170691
171127
  }
170692
171128
  return btoa(binaryString);
170693
171129
  }
@@ -170696,22 +171132,22 @@ function base64urlToUint8Array(base64url4) {
170696
171132
  const padding = "=".repeat((4 - base643.length % 4) % 4);
170697
171133
  return base64ToUint8Array(base643 + padding);
170698
171134
  }
170699
- function uint8ArrayToBase64url(bytes2) {
170700
- return uint8ArrayToBase64(bytes2).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
171135
+ function uint8ArrayToBase64url(bytes) {
171136
+ return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
170701
171137
  }
170702
171138
  function hexToUint8Array(hex3) {
170703
171139
  const cleanHex = hex3.replace(/^0x/, "");
170704
171140
  if (cleanHex.length % 2 !== 0) {
170705
171141
  throw new Error("Invalid hex string length");
170706
171142
  }
170707
- const bytes2 = new Uint8Array(cleanHex.length / 2);
171143
+ const bytes = new Uint8Array(cleanHex.length / 2);
170708
171144
  for (let i = 0; i < cleanHex.length; i += 2) {
170709
- bytes2[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
171145
+ bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
170710
171146
  }
170711
- return bytes2;
171147
+ return bytes;
170712
171148
  }
170713
- function uint8ArrayToHex(bytes2) {
170714
- return Array.from(bytes2).map((b2) => b2.toString(16).padStart(2, "0")).join("");
171149
+ function uint8ArrayToHex(bytes) {
171150
+ return Array.from(bytes).map((b2) => b2.toString(16).padStart(2, "0")).join("");
170715
171151
  }
170716
171152
  var Class = class {
170717
171153
  constructor(..._args) {
@@ -189283,6 +189719,8 @@ function syncRefusal(job, failure3) {
189283
189719
  return zh ? "\u6BCF\u65E5\u5199\u5165\u989D\u5EA6\u4E8E UTC \u96F6\u70B9\u6062\u590D\u3002" : "The daily write allowance resets at midnight UTC.";
189284
189720
  case "bad_request":
189285
189721
  return failure3.failure?.source === "validation" ? failure3.error : zh ? "\u8BF7\u68C0\u67E5\u5361\u7247\u5185\u5BB9\u548C\u9884\u89C8\u9644\u4EF6\u3002" : "Check the card and its preview attachments.";
189722
+ case "review_outdated":
189723
+ return job.chat ? zh ? "\u4FDD\u5B58\u671F\u95F4\u9884\u89C8\u5DF2\u88AB\u518D\u6B21\u4FEE\u8BA2\u3002\u8BF7\u5F00\u542F\u4E00\u8F6E\u65B0\u56DE\u590D\u3002" : "The Preview was revised while this reply was saving. Start a new reply." : failure3.error;
189286
189724
  case "board_content_conflict":
189287
189725
  case "version_conflict":
189288
189726
  return zh ? "\u8BF7\u5904\u7406\u770B\u677F\u540C\u6B65\u51B2\u7A81\u3002" : "Resolve the board sync conflict.";
@@ -189323,7 +189761,7 @@ function sourceOf(pins, source2, owner2) {
189323
189761
  async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
189324
189762
  const sections = [];
189325
189763
  const contexts = /* @__PURE__ */ new Set();
189326
- const invalid = (name) => {
189764
+ const invalid2 = (name) => {
189327
189765
  const error62 = `Missing or invalid saved review evidence: ${name}`;
189328
189766
  return { ok: false, code: "bad_request", error: error62, failure: makeFailure("validation", error62) };
189329
189767
  };
@@ -189347,7 +189785,7 @@ async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
189347
189785
  };
189348
189786
  if (error62 || status2 === "pending" || status2 === "failed" || typeof artifact !== "string" || !artifactId.test(artifact) || typeof version2 !== "number" || !Number.isSafeInteger(version2) || version2 < 1) {
189349
189787
  const missingEvidence = review.plan?.length && types.length && !local2 && (error62 || status2 === "pending" || status2 === "failed" || !artifact);
189350
- if (conflicting.has(source2) || missingEvidence) return invalid(`${title} \xB7 ${source2}`);
189788
+ if (conflicting.has(source2) || missingEvidence) return invalid2(`${title} \xB7 ${source2}`);
189351
189789
  return saved(typeof error62 === "string" ? error62 : artifact ? "Missing approved asset version." : "Missing asset record.");
189352
189790
  }
189353
189791
  const extension = path70.posix.extname(splitFileReference(source2)[0]).toLowerCase();
@@ -189356,18 +189794,18 @@ async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
189356
189794
  let kind = types.includes("tiled") ? "tiled" : !extension ? localPin?.kind ?? detected : detected;
189357
189795
  const matches = local2 && localPin?.version === version2;
189358
189796
  const issue2 = ws.materialIssues?.[source2];
189359
- const bytes2 = matches ? { ok: true, value: fs69.readFileSync(local2.file) } : issue2 && !conflicting.has(source2) ? { ok: false, error: issue2, code: void 0 } : await readAsset(artifact, version2, kind === "html" ? "html" : void 0);
189360
- if (!bytes2.ok) {
189361
- if (["unauthenticated", "forbidden", "unauthorized", "permission_denied"].includes(bytes2.code ?? "")) return bytes2;
189362
- if (conflicting.has(source2)) return invalid(`${title} \xB7 ${source2} (version ${version2}): ${bytes2.error}`);
189363
- return saved(bytes2.error);
189797
+ const bytes = matches ? { ok: true, value: fs69.readFileSync(local2.file) } : issue2 && !conflicting.has(source2) ? { ok: false, error: issue2, code: void 0 } : await readAsset(artifact, version2, kind === "html" ? "html" : void 0);
189798
+ if (!bytes.ok) {
189799
+ if (["unauthenticated", "forbidden", "unauthorized", "permission_denied"].includes(bytes.code ?? "")) return bytes;
189800
+ if (conflicting.has(source2)) return invalid2(`${title} \xB7 ${source2} (version ${version2}): ${bytes.error}`);
189801
+ return saved(bytes.error);
189364
189802
  }
189365
189803
  const basename = path70.posix.basename(splitFileReference(source2)[0]).replace(/[^\w. -]/g, "_");
189366
189804
  const name = extension ? basename : basename + ({ html: ".html", storyboard: ".json", spritesheet: ".json", studio: ".json" }[kind] ?? "");
189367
189805
  const copy2 = path70.join(folder2, `${files.size + 1}-${name.replace(/\.tsx$/i, kind === "html" ? ".html" : ".tsx")}`);
189368
189806
  const entry = { file: matches ? local2.file : copy2, note: "" };
189369
189807
  files.set(source2, entry);
189370
- let content = bytes2.value;
189808
+ let content = bytes.value;
189371
189809
  const knownManifest = fileManifest(kind, source2);
189372
189810
  let data = knownManifest?.references || extension === ".json" || !extension && types.length ? Buffer.from(content).toString() : void 0;
189373
189811
  if (extension === ".json" || !extension && types.length) {
@@ -189442,7 +189880,7 @@ ${body}${attachments.length ? "\n\nPinned files:\n" + attachments.join("\n") : "
189442
189880
  const stages = new Map(review.stages.map((stage) => [stage.id, stage]));
189443
189881
  for (const node2 of review.plan) {
189444
189882
  const stage = stages.get(node2.id);
189445
- if (!stage || !["approved", "done"].includes(stage.status)) return invalid(node2.id);
189883
+ if (!stage || !["approved", "done"].includes(stage.status)) return invalid2(node2.id);
189446
189884
  const snapshot = stage.snapshot;
189447
189885
  if (!snapshot && !node2.previews.length) continue;
189448
189886
  const evidence = object2(snapshot?.evidence);
@@ -189460,7 +189898,7 @@ ${body}${attachments.length ? "\n\nPinned files:\n" + attachments.join("\n") : "
189460
189898
  for (const id2 of node2.previews) {
189461
189899
  const section = object2(own2(content, id2));
189462
189900
  const saved = typeof section.body === "string" ? section.body : blocks.find((block) => block.id === id2)?.instructions;
189463
- if (!saved?.trim()) return invalid(`${title} \xB7 ${id2}`);
189901
+ if (!saved?.trim()) return invalid2(`${title} \xB7 ${id2}`);
189464
189902
  const legacyPins = object2(frozen.find((preview) => preview.id === id2)?.assets);
189465
189903
  add2(`${title} \xB7 ${id2}`, saved, { ...legacyPins, ...pins }, section.sources);
189466
189904
  }
@@ -189517,9 +189955,9 @@ import fs70 from "node:fs";
189517
189955
  import path71 from "node:path";
189518
189956
 
189519
189957
  // ../cli/src/lib/signals/identity.ts
189520
- import { createHash as createHash5 } from "node:crypto";
189958
+ import { createHash as createHash6 } from "node:crypto";
189521
189959
  var DERIVED = "derived-";
189522
- var derivedSourceId = (seed) => `${DERIVED}${createHash5("sha256").update(seed).digest("hex").slice(0, 16)}`;
189960
+ var derivedSourceId = (seed) => `${DERIVED}${createHash6("sha256").update(seed).digest("hex").slice(0, 16)}`;
189523
189961
 
189524
189962
  // src/triage.ts
189525
189963
  var triageDir = (board) => path71.join(board, "triage");
@@ -189794,6 +190232,7 @@ function boardAkb(job, ws, deps, io, task) {
189794
190232
  AI4KANBAN_SYNC_DIAGNOSTIC: io.diagnostic,
189795
190233
  AI4KANBAN_REVIEW_STAGES: job.flow?.review_stages ? JSON.stringify(job.flow.review_stages) : void 0,
189796
190234
  AI4KANBAN_TASK_REVIEW: job.taskReview ? JSON.stringify(job.taskReview) : void 0,
190235
+ [STUDIO_SNAPSHOT_ENV]: task && ws.studioSnapshot ? JSON.stringify(ws.studioSnapshot) : void 0,
189797
190236
  AI4KANBAN_EXECUTION: JSON.stringify({ job: job.id, machine: deps.machineId })
189798
190237
  }
189799
190238
  });
@@ -190678,7 +191117,7 @@ function replySpent(checkpoint, runtime) {
190678
191117
  }
190679
191118
 
190680
191119
  // src/lock.ts
190681
- import crypto8 from "node:crypto";
191120
+ import crypto9 from "node:crypto";
190682
191121
  import fs74 from "node:fs";
190683
191122
  import net from "node:net";
190684
191123
  import path75 from "node:path";
@@ -190686,7 +191125,7 @@ var RunnerAlreadyRunning = class extends Error {
190686
191125
  };
190687
191126
  function lockPath() {
190688
191127
  const home4 = runnerHome();
190689
- if (process.platform === "win32") return `\\\\.\\pipe\\wildcrane-${crypto8.createHash("sha256").update(home4).digest("hex").slice(0, 16)}`;
191128
+ if (process.platform === "win32") return `\\\\.\\pipe\\wildcrane-${crypto9.createHash("sha256").update(home4).digest("hex").slice(0, 16)}`;
190690
191129
  return path75.join(home4, "runner.sock");
190691
191130
  }
190692
191131
  function socketIdentity(file3) {
@@ -190786,7 +191225,7 @@ function runnerSettingsSupport() {
190786
191225
  }
190787
191226
 
190788
191227
  // src/jobs.ts
190789
- import { createHash as createHash8 } from "node:crypto";
191228
+ import { createHash as createHash9 } from "node:crypto";
190790
191229
 
190791
191230
  // src/conversation-progress.ts
190792
191231
  function conversationProgress(attempt, send3, valid, unconfirmed) {
@@ -190885,7 +191324,7 @@ import fs75 from "node:fs";
190885
191324
  import path76 from "node:path";
190886
191325
  import os10 from "node:os";
190887
191326
  import { fileURLToPath as fileURLToPath4 } from "node:url";
190888
- import { createHash as createHash6 } from "node:crypto";
191327
+ import { createHash as createHash7 } from "node:crypto";
190889
191328
  init_file_limits();
190890
191329
  var inside2 = (root2, file3) => {
190891
191330
  const p2 = path76.relative(root2, file3);
@@ -190923,10 +191362,10 @@ function collectReplyImages(parts, cwd) {
190923
191362
  }));
190924
191363
  const image = (p2) => {
190925
191364
  const read6 = () => {
190926
- let bytes2;
191365
+ let bytes;
190927
191366
  if (p2.data !== void 0) {
190928
191367
  if (p2.data.length > ASSET_FILE_LIMIT * 4 / 3 + 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(p2.data)) throw Error();
190929
- bytes2 = Buffer.from(p2.data, "base64");
191368
+ bytes = Buffer.from(p2.data, "base64");
190930
191369
  } else {
190931
191370
  if (!p2.path) throw Error();
190932
191371
  const source2 = p2.path.startsWith("file:") ? fileURLToPath4(p2.path) : decodeURIComponent(p2.path);
@@ -190938,18 +191377,18 @@ function collectReplyImages(parts, cwd) {
190938
191377
  try {
190939
191378
  const stat2 = fs75.fstatSync(fd);
190940
191379
  if (!stat2.isFile() || stat2.size > ASSET_FILE_LIMIT) throw Error();
190941
- bytes2 = fs75.readFileSync(fd);
191380
+ bytes = fs75.readFileSync(fd);
190942
191381
  } finally {
190943
191382
  fs75.closeSync(fd);
190944
191383
  }
190945
191384
  }
190946
- return bytes2;
191385
+ return bytes;
190947
191386
  };
190948
191387
  try {
190949
- const bytes2 = read6();
190950
- const mime = imageMime(bytes2);
190951
- if (!mime || p2.mime && p2.mime !== mime || bytes2.length > ASSET_FILE_LIMIT) throw Error();
190952
- const id2 = `rim_${createHash6("sha256").update(bytes2).digest("hex")}`;
191388
+ const bytes = read6();
191389
+ const mime = imageMime(bytes);
191390
+ if (!mime || p2.mime && p2.mime !== mime || bytes.length > ASSET_FILE_LIMIT) throw Error();
191391
+ const id2 = `rim_${createHash7("sha256").update(bytes).digest("hex")}`;
190953
191392
  if (!files.has(id2)) files.set(id2, { read: read6, mime });
190954
191393
  return { type: "image", id: id2, mime, status: "saved" };
190955
191394
  } catch {
@@ -191001,15 +191440,15 @@ async function saveReplyImages(parts, cwd, upload2) {
191001
191440
  if (!read6.parts.some((p2) => p2.type === "image")) return void 0;
191002
191441
  const saved = /* @__PURE__ */ new Map();
191003
191442
  for (const [key, f2] of read6.files) {
191004
- let bytes2;
191443
+ let bytes;
191005
191444
  try {
191006
- bytes2 = f2.read();
191007
- if (`rim_${createHash6("sha256").update(bytes2).digest("hex")}` !== key || imageMime(bytes2) !== f2.mime) continue;
191445
+ bytes = f2.read();
191446
+ if (`rim_${createHash7("sha256").update(bytes).digest("hex")}` !== key || imageMime(bytes) !== f2.mime) continue;
191008
191447
  } catch {
191009
191448
  continue;
191010
191449
  }
191011
191450
  try {
191012
- saved.set(key, await upload2(key.slice(4), bytes2, f2.mime));
191451
+ saved.set(key, await upload2(key.slice(4), bytes, f2.mime));
191013
191452
  } catch {
191014
191453
  }
191015
191454
  }
@@ -191021,10 +191460,10 @@ async function saveReplyImages(parts, cwd, upload2) {
191021
191460
  }
191022
191461
 
191023
191462
  // src/reply-input.ts
191024
- import { createHash as createHash7 } from "node:crypto";
191463
+ import { createHash as createHash8 } from "node:crypto";
191025
191464
  import fs76 from "node:fs";
191026
191465
  import path77 from "node:path";
191027
- var fingerprint = (text4) => createHash7("sha256").update(text4).digest("hex");
191466
+ var fingerprint = (text4) => createHash8("sha256").update(text4).digest("hex");
191028
191467
  var CARD_CHAT_GUIDE = "Follow `akb guide card-chat`.";
191029
191468
  function replyPrompt(input2, turn2) {
191030
191469
  const parts = [...turn2.diagnostics];
@@ -191035,6 +191474,7 @@ function replyPrompt(input2, turn2) {
191035
191474
  const { task, initialize } = turn2;
191036
191475
  if (initialize) {
191037
191476
  parts.push(task ? CARD_CHAT_GUIDE : "Follow `akb guide discuss-goal` for this Goal discussion.");
191477
+ if (turn2.skills) parts.push(turn2.skills);
191038
191478
  if (task) parts.push(`Task card: ${task.card}`);
191039
191479
  if (turn2.historyFile) parts.push(`Consult the ${task ? "chat" : "discussion"} history at \`${turn2.historyFile}\` as needed.`);
191040
191480
  if (turn2.goals) parts.push(replyGoals(turn2.goals));
@@ -191091,7 +191531,7 @@ function replyGoals(goals) {
191091
191531
 
191092
191532
  // src/handoff.ts
191093
191533
  import { execFileSync as execFileSync2 } from "node:child_process";
191094
- import crypto9 from "node:crypto";
191534
+ import crypto10 from "node:crypto";
191095
191535
  import fs77 from "node:fs";
191096
191536
  import path78 from "node:path";
191097
191537
  var gitRead = (cwd, args2) => {
@@ -191106,7 +191546,7 @@ var gitRead = (cwd, args2) => {
191106
191546
  return null;
191107
191547
  }
191108
191548
  };
191109
- var digest = (value) => crypto9.createHash("sha256").update(value).digest("hex");
191549
+ var digest = (value) => crypto10.createHash("sha256").update(value).digest("hex");
191110
191550
  function authorizedFolder(folder2) {
191111
191551
  if (!folder2) return null;
191112
191552
  try {
@@ -191234,9 +191674,9 @@ import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
191234
191674
 
191235
191675
  // src/reply-approval.ts
191236
191676
  import http from "node:http";
191237
- import crypto10 from "node:crypto";
191677
+ import crypto11 from "node:crypto";
191238
191678
  async function replyApprovalBridge(task, number4, approve) {
191239
- const token = crypto10.randomBytes(32).toString("hex");
191679
+ const token = crypto11.randomBytes(32).toString("hex");
191240
191680
  let serial = Promise.resolve();
191241
191681
  const server = http.createServer((req, res) => {
191242
191682
  const answer = (status2, body) => {
@@ -191756,11 +192196,11 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191756
192196
  let report2 = before ? { ...before, ...said2 } : said2;
191757
192197
  if (reply && checkpoint.replyParts && report2) {
191758
192198
  const stream2 = watching();
191759
- const parts = await saveReplyImages(checkpoint.replyParts.parts, checkpoint.replyParts.cwd, async (key, bytes2, mime) => {
192199
+ const parts = await saveReplyImages(checkpoint.replyParts.parts, checkpoint.replyParts.cwd, async (key, bytes, mime) => {
191760
192200
  const saved = checkpoint.replyImages?.job === id2 ? checkpoint.replyImages.files[key] : void 0;
191761
192201
  if (saved) return saved;
191762
192202
  if (outcome !== "done" || report2?.stopped || checkpoint.syncFailure || stream2.asked() || stream2.lost()) return { status: "not_saved" };
191763
- const uploaded = await sync(`reply-image:${key}`, () => deps.api.uploadReplyImage(deps.machineId, id2, key, bytes2, mime));
192203
+ const uploaded = await sync(`reply-image:${key}`, () => deps.api.uploadReplyImage(deps.machineId, id2, key, bytes, mime));
191764
192204
  if (!uploaded.ok) return { status: "not_saved" };
191765
192205
  if (checkpoint.replyImages?.job !== id2) checkpoint.replyImages = { job: id2, files: {} };
191766
192206
  checkpoint.replyImages.files[key] = uploaded.value;
@@ -191773,7 +192213,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191773
192213
  }
191774
192214
  if (outcome === "failed" && checkpoint.syncFailure) {
191775
192215
  const { failure: failure4, pause, safe: safe3 } = checkpoint.syncFailure;
191776
- const recovery2 = reply && safe3 && (checkpoint.completed?.outcome === "done" || checkpoint.ending) ? { safe: false, resumable: true, stopped: true } : reply && safe3 ? replyRecovery(job, checkpoint, true) : void 0;
192216
+ const recovery2 = report2?.recovery ?? (reply && safe3 && (checkpoint.completed?.outcome === "done" || checkpoint.ending) ? { safe: false, resumable: true, stopped: true } : reply && safe3 ? replyRecovery(job, checkpoint, true) : void 0);
191777
192217
  report2 = { ...report2, failure: buildFailureDetail(failure4, pause, safe3), ...recovery2 ? { recovery: recovery2 } : {} };
191778
192218
  if (pause === "limit" && job.flow) reason = "task_retry_exhausted: " + failure4.summary;
191779
192219
  else reason = failure4.summary;
@@ -192296,11 +192736,13 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
192296
192736
  const stream2 = watching();
192297
192737
  return sendBack(publishingJob, deps, ws, completed, sync, stream2, finishClaimed, landed, async (pushed) => {
192298
192738
  const records = pushed.conflict ? pendingConflicts(ws.board) : [];
192299
- const facts = createHash8("sha256").update(JSON.stringify(pushed.conflict ? records.map((r2) => ({ id: r2.id, state: r2.state, files: r2.files })) : pushed.failure)).digest("hex");
192739
+ const facts = createHash9("sha256").update(JSON.stringify(pushed.conflict ? records.map((r2) => ({ id: r2.id, state: r2.state, files: r2.files })) : pushed.failure)).digest("hex");
192300
192740
  const failRepair = async (reason) => {
192301
192741
  if (!stream2.asked()) stream2.event({ kind: "error", data: { text: reason } });
192302
192742
  await stream2.end();
192303
- if (!stream2.lost()) return finishClaimed(stream2.asked() ? "stopped" : "failed", stream2.asked() ? "" : reason, completed);
192743
+ if (stream2.lost()) return;
192744
+ if (stream2.asked()) return finishClaimed("stopped", "", completed);
192745
+ return finishClaimed("failed", reason, writebackRecovery(job, completed));
192304
192746
  };
192305
192747
  if (pushed.conflict && !records.length) {
192306
192748
  console.error(JSON.stringify({ code: "board_conflict_missing", phase: "publish-result", job: id2, task: job.task, project: job.project }));
@@ -192392,6 +192834,13 @@ The original session is unavailable. Saved work was preserved.`);
192392
192834
  }
192393
192835
  } else if (task) {
192394
192836
  ws = openTaskFolder({ ...job, task }, folder2?.cwd ?? null);
192837
+ const sessionStudio = job.resume && !job.fork ? readStudioSession(task, job.resume) : null;
192838
+ ws.studioSnapshot = checkpoint.studioSnapshot ?? sessionStudio ?? (priorExecution || job.flow?.resume || job.resume && !job.fork ? readPin(task) ?? void 0 : void 0);
192839
+ ws.bindStudio = (snapshot) => {
192840
+ if (checkpoint.studioSnapshot?.studio === snapshot.studio && checkpoint.studioSnapshot.version === snapshot.version) return;
192841
+ checkpoint.studioSnapshot = snapshot;
192842
+ persist();
192843
+ };
192395
192844
  cwd = ws.cwd;
192396
192845
  keep2(cwd);
192397
192846
  if (usesBoardRun(job, checkpoint) && !verification && !await recoverBoard(ws)) {
@@ -192489,6 +192938,7 @@ The original session is unavailable. Saved work was preserved.`);
192489
192938
  const assembled = replyPrompt(replyInput, {
192490
192939
  initialize,
192491
192940
  historyFile,
192941
+ skills: !continuing && fresh && ws && job.chat ? taskStudioSkills(ws) : "",
192492
192942
  ...ws && job.chat ? { task: { card: cardFile(ws), review: job.taskReview, setup: continuing ? null : taskSetupContext(ws) } } : {},
192493
192943
  goals: discussion && (discussion.goals.length || historyFile || replay || job.sessionFallback || job.resume) ? discussion.goals : void 0,
192494
192944
  diagnostics: [syncDiagnostic, conflicts],
@@ -192507,7 +192957,7 @@ The original session is unavailable. Saved work was preserved.`);
192507
192957
 
192508
192958
  This task came out of a discussion. Read it for what the card leaves out: ${file3}` : "";
192509
192959
  const previews = ws && !job.agent && job.taskReview?.preview_definitions?.length ? taskStudioPreviews(ws) : void 0;
192510
- const head2 = (syncDiagnostic ? syncDiagnostic + "\n\n" : "") + (job.taskReview ? reviewBoundary(job.taskReview, void 0, previews) + "\n\n" : "") + folderLines(job.agent ? null : ws) + (conflicts ? "\n\n" + conflicts : "") + (ws && !job.agent ? "\n\n" + taskStudioContext(ws, !job.resume, deps.akb.canonicalCommands === true) : "");
192960
+ const head2 = (syncDiagnostic ? syncDiagnostic + "\n\n" : "") + (job.taskReview ? reviewBoundary(job.taskReview, void 0, previews) + "\n\n" : "") + folderLines(job.agent ? null : ws) + (conflicts ? "\n\n" + conflicts : "") + (ws && !job.agent ? "\n\n" + taskStudioContext(ws, !job.resume, deps.akb.canonicalCommands === true) : "") + (ws && !job.agent && (!resume || fork) ? "\n\n" + taskStudioSkills(ws) : "");
192511
192961
  const submitted = recoveringTurn && checkpoint.submitted === true;
192512
192962
  const body = recoveringTurn ? [submitted ? "" : job.prompt, recovery2].filter(Boolean).join("\n\n") : job.prompt;
192513
192963
  const withHead = (text4) => text4.trim() ? `${text4.trim()}
@@ -192526,7 +192976,7 @@ ${body}` : body;
192526
192976
  if (ws) p2 = { ...p2, env: akbEnv(deps.akb, ws.board, ws.cloudTask ?? void 0, cloudLanguage(job), p2.env) };
192527
192977
  if (scope.bridge) p2 = { ...p2, env: { ...p2.env, AI4KANBAN_REPLY_APPROVAL: scope.bridge.env } };
192528
192978
  if (goalFile) p2 = { ...p2, env: { ...akbEnv(deps.akb, discussed, void 0, cloudLanguage(job), p2.env), KANBAN_GOALS: goalFile } };
192529
- const env2 = { ...p2.env, AI4KANBAN_EXECUTION: JSON.stringify({ job: job.id, machine: deps.machineId }), AI4KANBAN_TASK: job.task ?? "" };
192979
+ const env2 = { ...p2.env, AI4KANBAN_EXECUTION: JSON.stringify({ job: job.id, machine: deps.machineId }), AI4KANBAN_TASK: job.task ?? "", [STUDIO_SNAPSHOT_ENV]: ws?.studioSnapshot && JSON.stringify(ws.studioSnapshot) };
192530
192980
  const fallback = p2.fallback;
192531
192981
  return { ...p2, env: env2, fallback: fallback && (() => configure(fallback())) };
192532
192982
  };
@@ -192642,6 +193092,12 @@ ${body}` : body;
192642
193092
  const progressValid = () => !stream.asked() && !stream.lost() && readSession()?.subject === account && accountGeneration() === generation;
192643
193093
  const subagents = trackSubagents();
192644
193094
  let idleWatch;
193095
+ let boundSession;
193096
+ const bindStudioSession = (session) => {
193097
+ if (!session || session === boundSession || !ws?.cloudTask || !ws.studioSnapshot) return;
193098
+ saveStudioSession(ws.cloudTask, session, ws.studioSnapshot);
193099
+ boundSession = session;
193100
+ };
192645
193101
  const remember = (event2) => {
192646
193102
  idleWatch?.event(event2);
192647
193103
  if (stream.lost()) return;
@@ -192660,7 +193116,10 @@ ${body}` : body;
192660
193116
  checkpoint.partialReply = messages.join("\n\n");
192661
193117
  }
192662
193118
  const session = run3?.session();
192663
- if (session && (!job.fork || session !== forkSource)) checkpoint.session = session;
193119
+ if (session && (!job.fork || session !== forkSource)) {
193120
+ checkpoint.session = session;
193121
+ bindStudioSession(session);
193122
+ }
192664
193123
  if (attempt && !run3?.converse) measure(report(job, run3));
192665
193124
  persist();
192666
193125
  stream.event(event2);
@@ -192699,6 +193158,7 @@ ${body}` : body;
192699
193158
  if (outcome === "failed" && stream.lost()) return;
192700
193159
  checkpoint.completed = { outcome, report: report2, reason };
192701
193160
  checkpoint.session = report2.session ?? checkpoint.session;
193161
+ bindStudioSession(report2.session);
192702
193162
  persist();
192703
193163
  };
192704
193164
  const told = (report2) => {
@@ -193170,11 +193630,17 @@ var held4 = (deps, lease) => {
193170
193630
  if (Math.max(Date.now() - lease.at, performance.now() - lease.monotonic) >= deps.leaseMs) lease.lost = true;
193171
193631
  return !lease.lost;
193172
193632
  };
193633
+ function writebackRecovery(job, report2) {
193634
+ return job.chat && !job.flow ? { ...report2, recovery: { safe: false, stopped: true, resumable: true, writeback: true } } : report2;
193635
+ }
193173
193636
  async function sendBack(job, deps, ws, report2, sync, stream, finish, landed, repair, confirm) {
193174
193637
  const closesTask = job.flow && !report2.review && (report2.deliveryCompleted ?? (job.flow.verb === "implement" || job.flow.verb === "create" && job.flow.skip_plan));
193638
+ const taskReply = job.chat && !job.flow;
193175
193639
  const result = await sync("publish", async () => {
193176
193640
  const pushed2 = await push(ws, { id: job.id, machineId: deps.machineId }, () => stream.asked() || stream.lost());
193177
- if (pushed2.ok && closesTask && !taskAssetsSynced(ws)) return { ok: false, code: "service_unavailable", error: "Office preview uploads are pending." };
193641
+ if (pushed2.ok && (taskReply || closesTask) && !taskAssetsSynced(ws)) {
193642
+ return { ok: false, code: "service_unavailable", error: "Preview uploads are pending." };
193643
+ }
193178
193644
  if (!pushed2.ok && writeBlock(pushed2)) return pushed2;
193179
193645
  return !pushed2.ok && pushed2.offline ? { ok: false, error: pushed2.error, code: "service_unavailable" } : { ok: true, value: pushed2 };
193180
193646
  });
@@ -193193,10 +193659,15 @@ async function sendBack(job, deps, ws, report2, sync, stream, finish, landed, re
193193
193659
  if (stream.asked()) return finish("stopped", "", report2);
193194
193660
  if (denied) {
193195
193661
  console.error("runner: task sync refused", { job: job.id, code: denied.code, error: denied.error });
193196
- return finish("failed", syncRefusal(job, denied), report2);
193662
+ return finish("failed", syncRefusal(job, denied), writebackRecovery(job, report2));
193197
193663
  }
193198
193664
  const archive = closesTask && report2.deliveryId ? syncedArchive(ws) : void 0;
193199
- return finish("done", "", { ...report2, ...archive ? { archive } : {}, ...readCheckpoint(job.id)?.approvalRequested ? { replyApprovalSynced: report2.replyApprovalSynced !== false && taskAssetsSynced(ws) } : {} }, landed);
193665
+ return finish("done", "", {
193666
+ ...report2,
193667
+ ...taskReply ? { replyWriteSynced: true } : {},
193668
+ ...archive ? { archive } : {},
193669
+ ...readCheckpoint(job.id)?.approvalRequested ? { replyApprovalSynced: report2.replyApprovalSynced !== false && taskAssetsSynced(ws) } : {}
193670
+ }, landed);
193200
193671
  }
193201
193672
  var settingsOf = (job) => ({ settings: job.settings, secrets: secretsOf(job.runtimeId) });
193202
193673
  async function runSecret(job, deps) {
@@ -193389,7 +193860,7 @@ function keepPresence(machineId2, pingMs = PING_MS, onJob) {
193389
193860
 
193390
193861
  // src/codex-server.ts
193391
193862
  import { spawn as spawn6 } from "node:child_process";
193392
- import crypto11 from "node:crypto";
193863
+ import crypto12 from "node:crypto";
193393
193864
  import fs80 from "node:fs";
193394
193865
  import net2 from "node:net";
193395
193866
  import path81 from "node:path";
@@ -193517,12 +193988,12 @@ async function reconcileCodexLeases(backend) {
193517
193988
 
193518
193989
  // src/codex-server.ts
193519
193990
  var entryOf3 = (name) => process.env.RUNNER_DIST ? path81.join(process.env.RUNNER_DIST, name) : fileURLToPath5(new URL(name, import.meta.url));
193520
- var delay3 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
193991
+ var delay4 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
193521
193992
  async function codexServer() {
193522
193993
  fs80.mkdirSync(nativeDirectory(), { recursive: true, mode: 448 });
193523
193994
  const generation = accountGeneration();
193524
- const token = crypto11.randomBytes(32).toString("hex");
193525
- const instance = crypto11.randomUUID();
193995
+ const token = crypto12.randomBytes(32).toString("hex");
193996
+ const instance = crypto12.randomUUID();
193526
193997
  const address = process.platform === "win32" ? `\\\\.\\pipe\\wc-codex-runner-${instance}` : nativeEndpoint(`runner-${instance}`).slice(7);
193527
193998
  const record2 = { path: address, token, pid: process.pid, instance, protocol: CODEX_PROTOCOL, generation };
193528
193999
  const pending = /* @__PURE__ */ new Map();
@@ -193534,7 +194005,7 @@ async function codexServer() {
193534
194005
  const config2 = threadConfig(argv, environment);
193535
194006
  const provider = Object.fromEntries(Object.entries(config2).filter(([key2]) => key2 === "model_provider" || key2.startsWith("model_providers.")));
193536
194007
  const credentials = providerCredentials(provider, environment);
193537
- const key = crypto11.createHash("sha256").update(JSON.stringify([argv[0], environment.CODEX_HOME ?? "", Object.entries(provider).sort(), credentials])).digest("hex");
194008
+ const key = crypto12.createHash("sha256").update(JSON.stringify([argv[0], environment.CODEX_HOME ?? "", Object.entries(provider).sort(), credentials])).digest("hex");
193538
194009
  if (pending.has(key)) return pending.get(key);
193539
194010
  const work = (async () => {
193540
194011
  const previous = readPrivate(backendFile(key));
@@ -193554,7 +194025,7 @@ async function codexServer() {
193554
194025
  }
193555
194026
  }
193556
194027
  if (previous && liveBackend(previous)) throw Error("Codex backend belongs to an expired account session; stop it before reconnecting.");
193557
- const backend = { ...processIdentity(), key, instance: crypto11.randomUUID(), generation, endpoint: nativeEndpoint(key) };
194028
+ const backend = { ...processIdentity(), key, instance: crypto12.randomUUID(), generation, endpoint: nativeEndpoint(key) };
193558
194029
  const extra = [];
193559
194030
  if (process.platform === "win32") {
193560
194031
  const reservation = net2.createServer();
@@ -193565,7 +194036,7 @@ async function codexServer() {
193565
194036
  const port = reservation.address().port;
193566
194037
  await new Promise((resolve2) => reservation.close(() => resolve2()));
193567
194038
  backend.endpoint = `ws://127.0.0.1:${port}`;
193568
- backend.token = crypto11.randomBytes(32).toString("hex");
194039
+ backend.token = crypto12.randomBytes(32).toString("hex");
193569
194040
  const file3 = path81.join(nativeDirectory(), `${key}.token`);
193570
194041
  fs80.writeFileSync(file3, backend.token, { mode: 384 });
193571
194042
  extra.push("--ws-auth", "capability-token", "--ws-token-file", file3);
@@ -193589,7 +194060,7 @@ async function codexServer() {
193589
194060
  if (failure3) throw failure3;
193590
194061
  if (child.exitCode !== null || child.signalCode !== null || Date.now() >= until) throw Error("Codex did not start its native listener. Update Codex to a version supporting persistent local App Server connections.");
193591
194062
  if (backend.endpoint.startsWith("unix://") && !fs80.existsSync(backend.endpoint.slice(7))) {
193592
- await delay3(25);
194063
+ await delay4(25);
193593
194064
  continue;
193594
194065
  }
193595
194066
  try {
@@ -193603,7 +194074,7 @@ async function codexServer() {
193603
194074
  break;
193604
194075
  } catch (error62) {
193605
194076
  if (Date.now() >= until) throw error62;
193606
- await delay3(50);
194077
+ await delay4(50);
193607
194078
  }
193608
194079
  }
193609
194080
  backend.identity = connectionIdentity(child.pid);
@@ -193733,10 +194204,11 @@ function retireLegacy(generation) {
193733
194204
 
193734
194205
  // src/flow-worker.ts
193735
194206
  import { spawn as spawn7 } from "node:child_process";
193736
- import crypto12 from "node:crypto";
194207
+ import crypto13 from "node:crypto";
193737
194208
  import fs81 from "node:fs";
193738
194209
  import path82 from "node:path";
193739
194210
  import { fileURLToPath as fileURLToPath6 } from "node:url";
194211
+ var CLAIM_BACKOFF_MS = [1e3, 2e3, 5e3, 1e4, 3e4];
193740
194212
  var FLOW_MARK = "WILDCRANE_FLOW_WORKER";
193741
194213
  var directory2 = () => path82.join(runnerHome(), "flow-workers");
193742
194214
  var fileOf3 = (id2) => path82.join(directory2(), `${encodeURIComponent(id2)}.json`);
@@ -193750,14 +194222,19 @@ function read4(id2) {
193750
194222
  return null;
193751
194223
  }
193752
194224
  }
194225
+ function save2(worker) {
194226
+ const file3 = fileOf3(worker.id);
194227
+ fs81.writeFileSync(`${file3}.${process.pid}.tmp`, JSON.stringify(worker), { mode: 384 });
194228
+ fs81.renameSync(`${file3}.${process.pid}.tmp`, file3);
194229
+ }
193753
194230
  function hasFlowWorker(id2) {
193754
194231
  return fs81.existsSync(fileOf3(id2));
193755
194232
  }
193756
- function launchFlowWorker(id2, machine, entry = flowWorkerEntry) {
194233
+ function launchFlowWorker(id2, machine, entry = flowWorkerEntry, claimAttempt = 1) {
193757
194234
  fs81.mkdirSync(directory2(), { recursive: true, mode: 448 });
193758
194235
  const account = readSession()?.subject;
193759
194236
  if (!account) throw new Error("\u8D26\u53F7\u5DF2\u9000\u51FA\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002");
193760
- const worker = { id: id2, token: crypto12.randomUUID(), machine, account, generation: accountGeneration(), at: Date.now(), markedAt: Date.now() };
194237
+ const worker = { id: id2, token: crypto13.randomUUID(), machine, account, generation: accountGeneration(), at: Date.now(), markedAt: Date.now(), claimAttempt };
193761
194238
  fs81.writeFileSync(fileOf3(id2), JSON.stringify(worker), { flag: "wx", mode: 384 });
193762
194239
  const log = fs81.openSync(`${fileOf3(id2)}.log`, "a", 384);
193763
194240
  try {
@@ -193794,6 +194271,8 @@ async function watchFlowWorker(id2, machine, detached) {
193794
194271
  const claim2 = await claimJob(machine, id2);
193795
194272
  if (claim2.ok && claim2.value.claimed && !detached()) {
193796
194273
  await finishJob(machine, id2, "failed", recoveryBlocked(remote3.value.job));
194274
+ } else if (!claim2.ok) {
194275
+ console.warn("runner: could not claim job with an unverified worker", { job: id2, reason: claim2.error, code: claim2.code });
193797
194276
  }
193798
194277
  }
193799
194278
  return;
@@ -193890,10 +194369,10 @@ async function reclaimFlowWorkerAfterExit(id2, machine, given, token) {
193890
194369
  }
193891
194370
  }
193892
194371
  var reclaiming;
193893
- async function reclaimFlowWorkers(machine, given, only) {
194372
+ async function reclaimFlowWorkers(machine, given, only, retryWaiting = false) {
193894
194373
  if (reclaiming) {
193895
194374
  await reclaiming;
193896
- if (only) return reclaimFlowWorkers(machine, given, only);
194375
+ if (only) return reclaimFlowWorkers(machine, given, only, retryWaiting);
193897
194376
  return;
193898
194377
  }
193899
194378
  const account = readSession()?.subject;
@@ -193913,7 +194392,7 @@ async function reclaimFlowWorkers(machine, given, only) {
193913
194392
  const file3 = path82.join(directory2(), name);
193914
194393
  const original = fs81.readFileSync(file3, "utf8");
193915
194394
  const worker = JSON.parse(original);
193916
- if (!worker || typeof worker.id !== "string" || name !== `${encodeURIComponent(worker.id)}.json` || typeof worker.token !== "string" || !worker.token || worker.machine !== machine || worker.account !== account || typeof worker.generation !== "string" || !Number.isFinite(worker.at)) continue;
194395
+ if (!worker || typeof worker.id !== "string" || name !== `${encodeURIComponent(worker.id)}.json` || typeof worker.token !== "string" || !worker.token || worker.machine !== machine || worker.account !== account || typeof worker.generation !== "string" || !Number.isFinite(worker.at) || worker.claimAttempt !== void 0 && (!Number.isSafeInteger(worker.claimAttempt) || worker.claimAttempt < 1) || worker.claimRetryAt !== void 0 && !Number.isFinite(worker.claimRetryAt)) continue;
193917
194396
  if (!writerStopped(worker)) {
193918
194397
  if (!only) void reclaimFlowWorkerAfterExit(worker.id, machine, given);
193919
194398
  continue;
@@ -193928,10 +194407,18 @@ async function reclaimFlowWorkers(machine, given, only) {
193928
194407
  if (!valid()) break;
193929
194408
  if (!remote3.ok || remote3.value.job.id !== worker.id || !canKeepFlow(remote3.value.job)) continue;
193930
194409
  const job = remote3.value.job;
194410
+ const checkpoint = job.state === "finished" ? null : readCheckpoint(worker.id);
194411
+ const updating = checkpoint?.updating && !checkpoint.pending.includes("unknown");
194412
+ const failedClaim = worker.ended && (worker.claimFailure || worker.claimAttempt === void 0 && !checkpoint && "Previous claim result was not recorded.");
194413
+ const attempt = worker.claimAttempt ?? 1;
194414
+ const retry2 = worker.generation === generation && job.state === "waiting" && (!checkpoint || updating) && failedClaim ? {
194415
+ attempt,
194416
+ at: worker.claimRetryAt ?? Date.now() + CLAIM_BACKOFF_MS[Math.min(attempt - 1, CLAIM_BACKOFF_MS.length - 1)],
194417
+ failure: failedClaim
194418
+ } : void 0;
193931
194419
  if (worker.generation === generation && (job.state === "claimed" || job.state === "interrupted")) {
193932
194420
  const runner = await readRunner();
193933
194421
  if (!runner.ok || runner.value.runner?.machineId && runner.value.runner.machineId !== machine || !valid()) continue;
193934
- const checkpoint = readCheckpoint(worker.id);
193935
194422
  const deps = given ?? defaultDeps(machine);
193936
194423
  const folder2 = job.projectDir ? folderFor(job) : null;
193937
194424
  if (folder2 && "refused" in folder2) continue;
@@ -193942,10 +194429,12 @@ async function reclaimFlowWorkers(machine, given, only) {
193942
194429
  checkpoint.flowRun = evidence.run;
193943
194430
  stopped2 = evidence.stopped;
193944
194431
  }
193945
- if (!valid() || !writerStopped(worker)) continue;
193946
- const recovered = await recoverInterruptedJob(machine, job, checkpoint, stopped2, valid);
194432
+ if (!valid() || !writerStopped(worker) || worker.claimFailure && !stopped2 || fs81.readFileSync(file3, "utf8") !== original) continue;
194433
+ const beforeExecution = worker.claimFailure && worker.ended ? { pending: [], started: false } : null;
194434
+ if (beforeExecution) console.info("runner: recovering after a failed job claim", { job: worker.id, attempt, reason: worker.claimFailure });
194435
+ const recovered = await recoverInterruptedJob(machine, job, checkpoint ?? beforeExecution, stopped2, valid);
193947
194436
  if (!recovered?.resumed && !recovered?.finished) continue;
193948
- } else if (job.state !== "finished" && !(job.state === "waiting" && readCheckpoint(job.id)?.updating)) continue;
194437
+ } else if (job.state !== "finished" && !retry2 && !(job.state === "waiting" && updating)) continue;
193949
194438
  if (!worker.markedAt) {
193950
194439
  const job2 = remote3.value.job;
193951
194440
  const folder2 = job2.projectDir ? folderFor(job2) : { cwd: path82.join(runnerHome(), "work", job2.id) };
@@ -193966,14 +194455,24 @@ async function reclaimFlowWorkers(machine, given, only) {
193966
194455
  job2,
193967
194456
  { ...deps, machineId: machine, akb: deps.akb() }
193968
194457
  )) continue;
193969
- const checkpoint = readCheckpoint(worker.id);
193970
- if (checkpoint && (!checkpoint.mark || !processesStopped(checkpoint.mark, checkpoint.process))) continue;
194458
+ const saved = readCheckpoint(worker.id);
194459
+ if (saved && (!saved.mark || !processesStopped(saved.mark, saved.process))) continue;
193971
194460
  }
193972
194461
  if (!writerStopped(worker) || !valid() || fs81.readFileSync(file3, "utf8") !== original) continue;
194462
+ if (retry2 && (worker.claimRetryAt === void 0 || !retryWaiting || retry2.at > Date.now())) {
194463
+ if (worker.claimRetryAt === void 0) {
194464
+ await renewJob(machine, worker.id, { taskRecovery: { code: "claim", attempt: retry2.attempt } });
194465
+ if (!valid() || fs81.readFileSync(file3, "utf8") !== original) continue;
194466
+ save2({ ...worker, claimRetryAt: retry2.at });
194467
+ }
194468
+ if (retryWaiting) return retry2;
194469
+ continue;
194470
+ }
193973
194471
  fs81.rmSync(`${file3}.log`, { force: true });
193974
194472
  fs81.rmSync(`${file3}.stop`, { force: true });
193975
194473
  fs81.unlinkSync(file3);
193976
194474
  if (job.state === "finished" && job.outcome === "done") clearCheckpoint(job.id);
194475
+ if (retry2) return retry2;
193977
194476
  } finally {
193978
194477
  release2();
193979
194478
  }
@@ -193984,7 +194483,7 @@ async function reclaimFlowWorkers(machine, given, only) {
193984
194483
  reclaiming = sweep().finally(() => {
193985
194484
  reclaiming = void 0;
193986
194485
  });
193987
- await reclaiming;
194486
+ return reclaiming;
193988
194487
  }
193989
194488
 
193990
194489
  // src/connect.ts
@@ -194011,6 +194510,8 @@ function startRunner(options, lock) {
194011
194510
  let timer = null;
194012
194511
  let claimRetry;
194013
194512
  let claimAttempts = 0;
194513
+ let flowClaimRetry;
194514
+ let flowClaimRetryAt = Infinity;
194014
194515
  let reading = false;
194015
194516
  let readAgain = false;
194016
194517
  let readDone = Promise.resolve();
@@ -194215,6 +194716,15 @@ function startRunner(options, lock) {
194215
194716
  console.info("reply-dispatch", { event: "hint", source: source2, job, at: (/* @__PURE__ */ new Date()).toISOString() });
194216
194717
  start(job, true);
194217
194718
  };
194719
+ const retryFlowClaimAt = (at2) => {
194720
+ if (at2 >= flowClaimRetryAt) return;
194721
+ clearTimeout(flowClaimRetry);
194722
+ flowClaimRetryAt = at2;
194723
+ flowClaimRetry = setTimeout(() => {
194724
+ flowClaimRetryAt = Infinity;
194725
+ void readJobs();
194726
+ }, Math.max(0, at2 - Date.now()));
194727
+ };
194218
194728
  const readJobs = async (source2 = "catchup") => {
194219
194729
  if (closed || preparing || !registration) return;
194220
194730
  if (reading) {
@@ -194249,8 +194759,14 @@ function startRunner(options, lock) {
194249
194759
  }
194250
194760
  if (job.flow && hasFlowWorker(job.id)) {
194251
194761
  if (!running.has(job.id)) {
194252
- await reclaimFlowWorkers(registration.machineId, options.deps, job.id);
194253
- if (!hasFlowWorker(job.id)) {
194762
+ const retry2 = await reclaimFlowWorkers(registration.machineId, options.deps, job.id, !!workerEntry && job.state === "waiting");
194763
+ if (closed || preparing || !validAccount()) break;
194764
+ if (hasFlowWorker(job.id)) {
194765
+ if (retry2) retryFlowClaimAt(retry2.at);
194766
+ } else if (retry2) {
194767
+ console.info("runner: retrying job claim", { job: job.id, attempt: retry2.attempt + 1, previousFailure: retry2.failure });
194768
+ startWorker(job, retry2.attempt + 1);
194769
+ } else {
194254
194770
  attempted.delete(job.id);
194255
194771
  readAgain = true;
194256
194772
  }
@@ -194351,7 +194867,7 @@ function startRunner(options, lock) {
194351
194867
  });
194352
194868
  jobs.add(job);
194353
194869
  };
194354
- const startWorker = (job) => {
194870
+ const startWorker = (job, claimAttempt = 1) => {
194355
194871
  const id2 = job.id;
194356
194872
  attempted.add(id2);
194357
194873
  workers.add(id2);
@@ -194359,7 +194875,7 @@ function startRunner(options, lock) {
194359
194875
  status(idle2());
194360
194876
  const watched = (async () => {
194361
194877
  try {
194362
- if (!hasFlowWorker(id2)) launchFlowWorker(id2, registration.machineId, workerEntry);
194878
+ if (!hasFlowWorker(id2)) launchFlowWorker(id2, registration.machineId, workerEntry, claimAttempt);
194363
194879
  await watchFlowWorker(id2, registration.machineId, () => closed);
194364
194880
  } catch {
194365
194881
  }
@@ -194403,6 +194919,7 @@ function startRunner(options, lock) {
194403
194919
  }
194404
194920
  if (timer) clearTimeout(timer);
194405
194921
  clearTimeout(claimRetry);
194922
+ clearTimeout(flowClaimRetry);
194406
194923
  if (agentsTimer) clearTimeout(agentsTimer);
194407
194924
  clearInterval(modelsTimer);
194408
194925
  stopModels();
@@ -194471,7 +194988,7 @@ function startRunner(options, lock) {
194471
194988
 
194472
194989
  // src/signin.ts
194473
194990
  import { spawn as spawn8 } from "node:child_process";
194474
- import crypto13 from "node:crypto";
194991
+ import crypto14 from "node:crypto";
194475
194992
  import http2 from "node:http";
194476
194993
  var WAIT_MS2 = 10 * 60 * 1e3;
194477
194994
  var CRANE = "M2 55.75C2 55.69 2.69 55.09 3.55 54.37L5.09 53.1L6.61 53.1L8.13 53.1L12.49 49.87C14.9 48.07 16.83 46.58 16.77 46.53C16.75 46.47 15.56 46.64 14.15 46.89C12.74 47.13 11.55 47.3 11.53 47.24C11.47 47.19 12.02 46.22 12.71 45.06L14.01 42.96L18.21 41.34C20.53 40.45 22.41 39.65 22.41 39.57C22.41 39.49 21.27 38.55 19.92 37.5C15.92 34.4 13.13 31.31 10.86 27.47L10.01 26.01L10.53 26.18C10.84 26.26 12.96 27.2 15.28 28.25C17.6 29.32 19.53 30.12 19.59 30.07C19.64 30.01 17.68 28.69 15.25 27.11C12.8 25.57 10.56 23.97 10.31 23.58C9.15 21.95 7.25 17.5 7.25 16.46C7.25 16.26 10.01 17.95 13.38 20.18C16.77 22.45 19.73 24.38 19.95 24.49C20.42 24.74 20.25 24.57 13.9 19.02L9.18 14.88L8.6 13.36C7.72 10.96 6.97 7.54 6.97 5.77L6.97 4.14L9.4 6.46C12.66 9.61 15.56 12.01 23.57 18.25C27.32 21.18 30.5 23.72 30.64 23.91C30.8 24.08 31.68 26.51 32.6 29.3L34.28 34.35L35.72 35.65C37.54 37.3 37.98 37.47 36.85 36.09L35.96 35.01L37.12 34.71C39.11 34.21 40.16 33.52 42.54 31.12L44.8 28.8L46.02 28.96C46.71 29.07 47.56 29.07 47.95 28.96L48.67 28.8L48.67 28.25L48.67 27.69L49.27 27.69C49.63 27.69 50.1 27.58 50.32 27.42L50.71 27.17L51.01 27.42C51.18 27.56 52.78 27.86 54.58 28.08C56.37 28.3 57.86 28.52 57.94 28.58C58 28.63 56.73 28.85 55.13 29.05C53.53 29.24 50.96 29.77 49.44 30.21C47.92 30.65 46.57 31.01 46.43 31.01C46.29 31.01 44.22 32.97 41.85 35.37C37.57 39.62 34.42 42.14 30.83 44.15L29.14 45.09L25.97 45.73L22.77 46.39L14.59 51.11L6.42 55.86L4.21 55.86C2.99 55.86 2 55.8 2 55.75Z";
@@ -194544,8 +195061,8 @@ var PAGE = (outcome, lang, links) => {
194544
195061
  };
194545
195062
  async function signIn(options = {}) {
194546
195063
  const generation = accountGeneration();
194547
- const verifier = base64url3(crypto13.randomBytes(32));
194548
- const challenge = base64url3(crypto13.createHash("sha256").update(verifier).digest());
195064
+ const verifier = base64url3(crypto14.randomBytes(32));
195065
+ const challenge = base64url3(crypto14.createHash("sha256").update(verifier).digest());
194549
195066
  let finish = () => {
194550
195067
  };
194551
195068
  const answered = new Promise((resolve2) => finish = resolve2);
@@ -194677,15 +195194,15 @@ function openBrowser(url2) {
194677
195194
  } catch {
194678
195195
  }
194679
195196
  }
194680
- var base64url3 = (bytes2) => bytes2.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
195197
+ var base64url3 = (bytes) => bytes.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
194681
195198
 
194682
195199
  // src/settings.ts
194683
- import crypto15 from "node:crypto";
195200
+ import crypto16 from "node:crypto";
194684
195201
  import fs84 from "node:fs";
194685
195202
  import path85 from "node:path";
194686
195203
 
194687
195204
  // src/preferences.ts
194688
- import crypto14 from "node:crypto";
195205
+ import crypto15 from "node:crypto";
194689
195206
  import fs83 from "node:fs";
194690
195207
  import path84 from "node:path";
194691
195208
  var file2 = () => path84.join(runnerHome(), "preferences.json");
@@ -194699,7 +195216,7 @@ function read5() {
194699
195216
  }
194700
195217
  var acceptAlphaUpdates = () => read5().acceptAlphaUpdates === true;
194701
195218
  function saveAlphaUpdates(value) {
194702
- const target = file2(), temporary = `${target}.${crypto14.randomUUID()}.tmp`;
195219
+ const target = file2(), temporary = `${target}.${crypto15.randomUUID()}.tmp`;
194703
195220
  fs83.mkdirSync(runnerHome(), { recursive: true, mode: 448 });
194704
195221
  try {
194705
195222
  fs83.writeFileSync(temporary, JSON.stringify({ ...read5(), acceptAlphaUpdates: value }) + "\n", { mode: 384 });
@@ -194745,7 +195262,7 @@ var callback = () => {
194745
195262
  };
194746
195263
  var notify = () => {
194747
195264
  fs84.mkdirSync(runnerHome(), { recursive: true, mode: 448 });
194748
- fs84.writeFileSync(path85.join(runnerHome(), "settings-refresh"), crypto15.randomUUID(), { mode: 384 });
195265
+ fs84.writeFileSync(path85.join(runnerHome(), "settings-refresh"), crypto16.randomUUID(), { mode: 384 });
194749
195266
  callback();
194750
195267
  };
194751
195268
  function startSignIn() {
@@ -194951,7 +195468,7 @@ async function settingsAction(action, body, context) {
194951
195468
  if ("error" in found) return found;
194952
195469
  if (found.folder) return { error: "folder_taken" };
194953
195470
  if (choice.subject !== readSession()?.subject) return { error: "signed_out" };
194954
- if (!choice.creation || choice.creation.name !== name || choice.creation.workspace !== body.workspace) choice.creation = { key: crypto15.randomUUID(), name, workspace: body.workspace };
195471
+ if (!choice.creation || choice.creation.name !== name || choice.creation.workspace !== body.workspace) choice.creation = { key: crypto16.randomUUID(), name, workspace: body.workspace };
194955
195472
  const created = choice.creation.project ? { ok: true, value: { id: choice.creation.project } } : await createProject(name, body.workspace, choice.creation.key);
194956
195473
  if (!created.ok) return failure2(created);
194957
195474
  project = created.value.id;
@@ -194968,7 +195485,7 @@ async function settingsAction(action, body, context) {
194968
195485
 
194969
195486
  // src/settings-server.ts
194970
195487
  import { spawn as spawn10 } from "node:child_process";
194971
- import crypto16 from "node:crypto";
195488
+ import crypto17 from "node:crypto";
194972
195489
  import fs86 from "node:fs";
194973
195490
  import http3 from "node:http";
194974
195491
  import path87 from "node:path";
@@ -195001,7 +195518,7 @@ var settings_client_default = '"use strict";(()=>{var Q6=Object.create;var Gf=Ob
195001
195518
  var recordFile2 = () => path87.join(runnerHome(), "settings-page.json");
195002
195519
  var sessionsFile = () => path87.join(runnerHome(), "settings-sessions.json");
195003
195520
  var sleep3 = (ms) => new Promise((r2) => setTimeout(r2, ms));
195004
- var random = () => crypto16.randomBytes(32).toString("hex");
195521
+ var random = () => crypto17.randomBytes(32).toString("hex");
195005
195522
  var PAGE_VERSION = process.env.WILDCRANE_SETTINGS_VERSION ?? VERSION;
195006
195523
  var own3 = null;
195007
195524
  var helper = null;