@ancha-labs/cli 0.4.15 → 0.4.16

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/lib/ancha.mjs CHANGED
@@ -24289,7 +24289,7 @@ var init_answer = __esm({
24289
24289
  not_contains: texts.optional().describe("Text the final answer must not contain"),
24290
24290
  numbers: external_exports.array(AnswerNumberSchema).min(1).optional().describe("Numbers the final answer must state, each within its tolerance; thousands separators, currency codes and symbols, minus signs and parentheses for negatives are read"),
24291
24291
  case: external_exports.enum(["insensitive", "sensitive"]).optional().describe("How contains and not_contains compare letters; default insensitive")
24292
- }).describe("Checks the agent's final answer (what it posts to ANCHA_DONE_URL, its HTTP reply, or the last block it prints on stdout): the text and numbers it states");
24292
+ }).describe("Checks the agent's final answer (what it posts to ANCHA_DONE_URL, its HTTP reply, or what it prints on stdout): the text and numbers it states");
24293
24293
  }
24294
24294
  });
24295
24295
 
@@ -48908,7 +48908,7 @@ function validate3(raw3, issues) {
48908
48908
  }
48909
48909
  if (raw3.agent.answer !== void 0) {
48910
48910
  if (ANSWER_MODES.includes(raw3.agent.answer)) agent.answer = raw3.agent.answer;
48911
- else issues.push({ path: "agent.answer", message: `expected auto, done, stdout or none, got ${got(raw3.agent.answer)}`, hint: "auto takes the answer the agent posts to ANCHA_DONE_URL, else an HTTP reply, else the last block of its stdout" });
48911
+ else issues.push({ path: "agent.answer", message: `expected auto, done, stdout or none, got ${got(raw3.agent.answer)}`, hint: "auto takes the answer the agent posts to ANCHA_DONE_URL, else an HTTP reply, else what it prints on stdout" });
48912
48912
  }
48913
48913
  if (raw3.agent.pass_env !== void 0) {
48914
48914
  const names5 = raw3.agent.pass_env;
@@ -68393,8 +68393,10 @@ function evaluateTrace(trace, calls2, tools2) {
68393
68393
  function finalAnswer(trace) {
68394
68394
  const entry3 = trace.findLast((e) => e.source === "agent" && e.service === "agent" && e.path === "/done");
68395
68395
  if (!entry3) return void 0;
68396
- const output2 = typeof entry3.request === "string" ? entry3.request : entry3.request?.output;
68397
- return { text: answerText(output2), seq: entry3.seq };
68396
+ const request2 = typeof entry3.request === "object" && entry3.request !== null ? entry3.request : void 0;
68397
+ const output2 = typeof entry3.request === "string" ? entry3.request : request2?.output;
68398
+ const source = request2?.source === "reply" || request2?.source === "stdout" ? request2.source : "done";
68399
+ return { text: answerText(output2), seq: entry3.seq, source, ...typeof request2?.printed === "number" && { printed: request2.printed } };
68398
68400
  }
68399
68401
  function evaluateAnswer(check4, trace) {
68400
68402
  const contains3 = asList(check4.contains), absent = asList(check4.not_contains), sensitive = check4.case === "sensitive";
@@ -68406,13 +68408,22 @@ function evaluateAnswer(check4, trace) {
68406
68408
  ];
68407
68409
  const expected = parts3.length ? `the final answer ${parts3.join("; ")}` : "a final answer";
68408
68410
  const answer = finalAnswer(trace);
68411
+ if (answer?.printed !== void 0) {
68412
+ return {
68413
+ passed: false,
68414
+ expected,
68415
+ actual: `${answer.printed.toLocaleString("en-US")} characters on stdout`,
68416
+ evidence: [answer.seq],
68417
+ explanation: `The agent printed ${answer.printed.toLocaleString("en-US")} characters on stdout, more than an answer can be, so it gave no final answer. An agent prints its logs on stderr, or posts its answer to ANCHA_DONE_URL, body {"output": <its answer>}.`
68418
+ };
68419
+ }
68409
68420
  if (!answer || answer.text.trim() === "") {
68410
68421
  return {
68411
68422
  passed: false,
68412
68423
  expected,
68413
68424
  actual: answer ? "an empty final answer" : "no final answer",
68414
68425
  evidence: answer ? [answer.seq] : [],
68415
- explanation: `The agent gave ${answer ? "an empty" : "no"} final answer. An agent answers with a POST to ANCHA_DONE_URL, body {"output": <its answer>}, or by printing it last on stdout.`
68426
+ explanation: `The agent gave ${answer ? "an empty" : "no"} final answer. An agent answers with a POST to ANCHA_DONE_URL, body {"output": <its answer>}, or by printing it on stdout.`
68416
68427
  };
68417
68428
  }
68418
68429
  const text29 = comparableText(answer.text, sensitive);
@@ -68429,7 +68440,8 @@ function evaluateAnswer(check4, trace) {
68429
68440
  const explanation = [
68430
68441
  ...missing8.length ? [`The final answer does not contain ${quoted2(missing8)}.`] : [],
68431
68442
  ...unstated.length ? [`It states no number within ${unstated.map((n2) => `${plainNumber(n2.tolerance)} of ${n2.written}`).join(", nor within ")}: ${said}.`] : [],
68432
- ...present3.length ? [`It contains ${quoted2(present3)}, which it must not.`] : []
68443
+ ...present3.length ? [`It contains ${quoted2(present3)}, which it must not.`] : [],
68444
+ ...answer.source === "stdout" ? ["Its answer is everything it printed on stdout."] : answer.source === "reply" ? ["Its answer is its HTTP reply."] : []
68433
68445
  ].join(" ");
68434
68446
  return { passed: false, expected, actual, explanation, evidence: [answer.seq] };
68435
68447
  }
@@ -120207,16 +120219,16 @@ var require_printer = __commonJS({
120207
120219
  },
120208
120220
  // Document
120209
120221
  Document: {
120210
- leave: (node5) => join70(node5.definitions, "\n\n")
120222
+ leave: (node5) => join71(node5.definitions, "\n\n")
120211
120223
  },
120212
120224
  OperationDefinition: {
120213
120225
  leave(node5) {
120214
- const varDefs = hasMultilineItems(node5.variableDefinitions) ? wrap("(\n", join70(node5.variableDefinitions, "\n"), "\n)") : wrap("(", join70(node5.variableDefinitions, ", "), ")");
120215
- const prefix2 = wrap("", node5.description, "\n") + join70(
120226
+ const varDefs = hasMultilineItems(node5.variableDefinitions) ? wrap("(\n", join71(node5.variableDefinitions, "\n"), "\n)") : wrap("(", join71(node5.variableDefinitions, ", "), ")");
120227
+ const prefix2 = wrap("", node5.description, "\n") + join71(
120216
120228
  [
120217
120229
  node5.operation,
120218
- join70([node5.name, varDefs]),
120219
- join70(node5.directives, " ")
120230
+ join71([node5.name, varDefs]),
120231
+ join71(node5.directives, " ")
120220
120232
  ],
120221
120233
  " "
120222
120234
  );
@@ -120224,7 +120236,7 @@ var require_printer = __commonJS({
120224
120236
  }
120225
120237
  },
120226
120238
  VariableDefinition: {
120227
- leave: ({ variable, type, defaultValue, directives, description: description2 }) => wrap("", description2, "\n") + variable + ": " + type + wrap(" = ", defaultValue) + wrap(" ", join70(directives, " "))
120239
+ leave: ({ variable, type, defaultValue, directives, description: description2 }) => wrap("", description2, "\n") + variable + ": " + type + wrap(" = ", defaultValue) + wrap(" ", join71(directives, " "))
120228
120240
  },
120229
120241
  SelectionSet: {
120230
120242
  leave: ({ selections: selections2 }) => block2(selections2)
@@ -120232,11 +120244,11 @@ var require_printer = __commonJS({
120232
120244
  Field: {
120233
120245
  leave({ alias, name: name5, arguments: args, directives, selectionSet }) {
120234
120246
  const prefix2 = wrap("", alias, ": ") + name5;
120235
- let argsLine = prefix2 + wrap("(", join70(args, ", "), ")");
120247
+ let argsLine = prefix2 + wrap("(", join71(args, ", "), ")");
120236
120248
  if (argsLine.length > MAX_LINE_LENGTH) {
120237
- argsLine = prefix2 + wrap("(\n", indent2(join70(args, "\n")), "\n)");
120249
+ argsLine = prefix2 + wrap("(\n", indent2(join71(args, "\n")), "\n)");
120238
120250
  }
120239
- return join70([argsLine, join70(directives, " "), selectionSet], " ");
120251
+ return join71([argsLine, join71(directives, " "), selectionSet], " ");
120240
120252
  }
120241
120253
  },
120242
120254
  Argument: {
@@ -120244,14 +120256,14 @@ var require_printer = __commonJS({
120244
120256
  },
120245
120257
  // Fragments
120246
120258
  FragmentSpread: {
120247
- leave: ({ name: name5, directives }) => "..." + name5 + wrap(" ", join70(directives, " "))
120259
+ leave: ({ name: name5, directives }) => "..." + name5 + wrap(" ", join71(directives, " "))
120248
120260
  },
120249
120261
  InlineFragment: {
120250
- leave: ({ typeCondition, directives, selectionSet }) => join70(
120262
+ leave: ({ typeCondition, directives, selectionSet }) => join71(
120251
120263
  [
120252
120264
  "...",
120253
120265
  wrap("on ", typeCondition),
120254
- join70(directives, " "),
120266
+ join71(directives, " "),
120255
120267
  selectionSet
120256
120268
  ],
120257
120269
  " "
@@ -120267,7 +120279,7 @@ var require_printer = __commonJS({
120267
120279
  description: description2
120268
120280
  }) => wrap("", description2, "\n") + // Note: fragment variable definitions are experimental and may be changed
120269
120281
  // or removed in the future.
120270
- `fragment ${name5}${wrap("(", join70(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join70(directives, " "), " ")}` + selectionSet
120282
+ `fragment ${name5}${wrap("(", join71(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join71(directives, " "), " ")}` + selectionSet
120271
120283
  },
120272
120284
  // Value
120273
120285
  IntValue: {
@@ -120289,17 +120301,17 @@ var require_printer = __commonJS({
120289
120301
  leave: ({ value: value5 }) => value5
120290
120302
  },
120291
120303
  ListValue: {
120292
- leave: ({ values: values2 }) => "[" + join70(values2, ", ") + "]"
120304
+ leave: ({ values: values2 }) => "[" + join71(values2, ", ") + "]"
120293
120305
  },
120294
120306
  ObjectValue: {
120295
- leave: ({ fields: fields11 }) => "{" + join70(fields11, ", ") + "}"
120307
+ leave: ({ fields: fields11 }) => "{" + join71(fields11, ", ") + "}"
120296
120308
  },
120297
120309
  ObjectField: {
120298
120310
  leave: ({ name: name5, value: value5 }) => name5 + ": " + value5
120299
120311
  },
120300
120312
  // Directive
120301
120313
  Directive: {
120302
- leave: ({ name: name5, arguments: args }) => "@" + name5 + wrap("(", join70(args, ", "), ")")
120314
+ leave: ({ name: name5, arguments: args }) => "@" + name5 + wrap("(", join71(args, ", "), ")")
120303
120315
  },
120304
120316
  // Type
120305
120317
  NamedType: {
@@ -120313,61 +120325,61 @@ var require_printer = __commonJS({
120313
120325
  },
120314
120326
  // Type System Definitions
120315
120327
  SchemaDefinition: {
120316
- leave: ({ description: description2, directives, operationTypes }) => wrap("", description2, "\n") + join70(["schema", join70(directives, " "), block2(operationTypes)], " ")
120328
+ leave: ({ description: description2, directives, operationTypes }) => wrap("", description2, "\n") + join71(["schema", join71(directives, " "), block2(operationTypes)], " ")
120317
120329
  },
120318
120330
  OperationTypeDefinition: {
120319
120331
  leave: ({ operation, type }) => operation + ": " + type
120320
120332
  },
120321
120333
  ScalarTypeDefinition: {
120322
- leave: ({ description: description2, name: name5, directives }) => wrap("", description2, "\n") + join70(["scalar", name5, join70(directives, " ")], " ")
120334
+ leave: ({ description: description2, name: name5, directives }) => wrap("", description2, "\n") + join71(["scalar", name5, join71(directives, " ")], " ")
120323
120335
  },
120324
120336
  ObjectTypeDefinition: {
120325
- leave: ({ description: description2, name: name5, interfaces, directives, fields: fields11 }) => wrap("", description2, "\n") + join70(
120337
+ leave: ({ description: description2, name: name5, interfaces, directives, fields: fields11 }) => wrap("", description2, "\n") + join71(
120326
120338
  [
120327
120339
  "type",
120328
120340
  name5,
120329
- wrap("implements ", join70(interfaces, " & ")),
120330
- join70(directives, " "),
120341
+ wrap("implements ", join71(interfaces, " & ")),
120342
+ join71(directives, " "),
120331
120343
  block2(fields11)
120332
120344
  ],
120333
120345
  " "
120334
120346
  )
120335
120347
  },
120336
120348
  FieldDefinition: {
120337
- leave: ({ description: description2, name: name5, arguments: args, type, directives }) => wrap("", description2, "\n") + name5 + (hasMultilineItems(args) ? wrap("(\n", indent2(join70(args, "\n")), "\n)") : wrap("(", join70(args, ", "), ")")) + ": " + type + wrap(" ", join70(directives, " "))
120349
+ leave: ({ description: description2, name: name5, arguments: args, type, directives }) => wrap("", description2, "\n") + name5 + (hasMultilineItems(args) ? wrap("(\n", indent2(join71(args, "\n")), "\n)") : wrap("(", join71(args, ", "), ")")) + ": " + type + wrap(" ", join71(directives, " "))
120338
120350
  },
120339
120351
  InputValueDefinition: {
120340
- leave: ({ description: description2, name: name5, type, defaultValue, directives }) => wrap("", description2, "\n") + join70(
120341
- [name5 + ": " + type, wrap("= ", defaultValue), join70(directives, " ")],
120352
+ leave: ({ description: description2, name: name5, type, defaultValue, directives }) => wrap("", description2, "\n") + join71(
120353
+ [name5 + ": " + type, wrap("= ", defaultValue), join71(directives, " ")],
120342
120354
  " "
120343
120355
  )
120344
120356
  },
120345
120357
  InterfaceTypeDefinition: {
120346
- leave: ({ description: description2, name: name5, interfaces, directives, fields: fields11 }) => wrap("", description2, "\n") + join70(
120358
+ leave: ({ description: description2, name: name5, interfaces, directives, fields: fields11 }) => wrap("", description2, "\n") + join71(
120347
120359
  [
120348
120360
  "interface",
120349
120361
  name5,
120350
- wrap("implements ", join70(interfaces, " & ")),
120351
- join70(directives, " "),
120362
+ wrap("implements ", join71(interfaces, " & ")),
120363
+ join71(directives, " "),
120352
120364
  block2(fields11)
120353
120365
  ],
120354
120366
  " "
120355
120367
  )
120356
120368
  },
120357
120369
  UnionTypeDefinition: {
120358
- leave: ({ description: description2, name: name5, directives, types }) => wrap("", description2, "\n") + join70(
120359
- ["union", name5, join70(directives, " "), wrap("= ", join70(types, " | "))],
120370
+ leave: ({ description: description2, name: name5, directives, types }) => wrap("", description2, "\n") + join71(
120371
+ ["union", name5, join71(directives, " "), wrap("= ", join71(types, " | "))],
120360
120372
  " "
120361
120373
  )
120362
120374
  },
120363
120375
  EnumTypeDefinition: {
120364
- leave: ({ description: description2, name: name5, directives, values: values2 }) => wrap("", description2, "\n") + join70(["enum", name5, join70(directives, " "), block2(values2)], " ")
120376
+ leave: ({ description: description2, name: name5, directives, values: values2 }) => wrap("", description2, "\n") + join71(["enum", name5, join71(directives, " "), block2(values2)], " ")
120365
120377
  },
120366
120378
  EnumValueDefinition: {
120367
- leave: ({ description: description2, name: name5, directives }) => wrap("", description2, "\n") + join70([name5, join70(directives, " ")], " ")
120379
+ leave: ({ description: description2, name: name5, directives }) => wrap("", description2, "\n") + join71([name5, join71(directives, " ")], " ")
120368
120380
  },
120369
120381
  InputObjectTypeDefinition: {
120370
- leave: ({ description: description2, name: name5, directives, fields: fields11 }) => wrap("", description2, "\n") + join70(["input", name5, join70(directives, " "), block2(fields11)], " ")
120382
+ leave: ({ description: description2, name: name5, directives, fields: fields11 }) => wrap("", description2, "\n") + join71(["input", name5, join71(directives, " "), block2(fields11)], " ")
120371
120383
  },
120372
120384
  DirectiveDefinition: {
120373
120385
  leave: ({
@@ -120377,84 +120389,84 @@ var require_printer = __commonJS({
120377
120389
  directives,
120378
120390
  repeatable,
120379
120391
  locations
120380
- }) => wrap("", description2, "\n") + "directive @" + name5 + (hasMultilineItems(args) ? wrap("(\n", indent2(join70(args, "\n")), "\n)") : wrap("(", join70(args, ", "), ")")) + wrap(" ", join70(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join70(locations, " | ")
120392
+ }) => wrap("", description2, "\n") + "directive @" + name5 + (hasMultilineItems(args) ? wrap("(\n", indent2(join71(args, "\n")), "\n)") : wrap("(", join71(args, ", "), ")")) + wrap(" ", join71(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join71(locations, " | ")
120381
120393
  },
120382
120394
  SchemaExtension: {
120383
- leave: ({ directives, operationTypes }) => join70(
120384
- ["extend schema", join70(directives, " "), block2(operationTypes)],
120395
+ leave: ({ directives, operationTypes }) => join71(
120396
+ ["extend schema", join71(directives, " "), block2(operationTypes)],
120385
120397
  " "
120386
120398
  )
120387
120399
  },
120388
120400
  ScalarTypeExtension: {
120389
- leave: ({ name: name5, directives }) => join70(["extend scalar", name5, join70(directives, " ")], " ")
120401
+ leave: ({ name: name5, directives }) => join71(["extend scalar", name5, join71(directives, " ")], " ")
120390
120402
  },
120391
120403
  ObjectTypeExtension: {
120392
- leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join70(
120404
+ leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join71(
120393
120405
  [
120394
120406
  "extend type",
120395
120407
  name5,
120396
- wrap("implements ", join70(interfaces, " & ")),
120397
- join70(directives, " "),
120408
+ wrap("implements ", join71(interfaces, " & ")),
120409
+ join71(directives, " "),
120398
120410
  block2(fields11)
120399
120411
  ],
120400
120412
  " "
120401
120413
  )
120402
120414
  },
120403
120415
  InterfaceTypeExtension: {
120404
- leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join70(
120416
+ leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join71(
120405
120417
  [
120406
120418
  "extend interface",
120407
120419
  name5,
120408
- wrap("implements ", join70(interfaces, " & ")),
120409
- join70(directives, " "),
120420
+ wrap("implements ", join71(interfaces, " & ")),
120421
+ join71(directives, " "),
120410
120422
  block2(fields11)
120411
120423
  ],
120412
120424
  " "
120413
120425
  )
120414
120426
  },
120415
120427
  UnionTypeExtension: {
120416
- leave: ({ name: name5, directives, types }) => join70(
120428
+ leave: ({ name: name5, directives, types }) => join71(
120417
120429
  [
120418
120430
  "extend union",
120419
120431
  name5,
120420
- join70(directives, " "),
120421
- wrap("= ", join70(types, " | "))
120432
+ join71(directives, " "),
120433
+ wrap("= ", join71(types, " | "))
120422
120434
  ],
120423
120435
  " "
120424
120436
  )
120425
120437
  },
120426
120438
  EnumTypeExtension: {
120427
- leave: ({ name: name5, directives, values: values2 }) => join70(["extend enum", name5, join70(directives, " "), block2(values2)], " ")
120439
+ leave: ({ name: name5, directives, values: values2 }) => join71(["extend enum", name5, join71(directives, " "), block2(values2)], " ")
120428
120440
  },
120429
120441
  InputObjectTypeExtension: {
120430
- leave: ({ name: name5, directives, fields: fields11 }) => join70(["extend input", name5, join70(directives, " "), block2(fields11)], " ")
120442
+ leave: ({ name: name5, directives, fields: fields11 }) => join71(["extend input", name5, join71(directives, " "), block2(fields11)], " ")
120431
120443
  },
120432
120444
  DirectiveExtension: {
120433
- leave: ({ name: name5, directives }) => join70(["extend directive @" + name5, join70(directives, " ")], " ")
120445
+ leave: ({ name: name5, directives }) => join71(["extend directive @" + name5, join71(directives, " ")], " ")
120434
120446
  },
120435
120447
  // Schema Coordinates
120436
120448
  TypeCoordinate: {
120437
120449
  leave: ({ name: name5 }) => name5
120438
120450
  },
120439
120451
  MemberCoordinate: {
120440
- leave: ({ name: name5, memberName }) => join70([name5, wrap(".", memberName)])
120452
+ leave: ({ name: name5, memberName }) => join71([name5, wrap(".", memberName)])
120441
120453
  },
120442
120454
  ArgumentCoordinate: {
120443
- leave: ({ name: name5, fieldName: fieldName2, argumentName }) => join70([name5, wrap(".", fieldName2), wrap("(", argumentName, ":)")])
120455
+ leave: ({ name: name5, fieldName: fieldName2, argumentName }) => join71([name5, wrap(".", fieldName2), wrap("(", argumentName, ":)")])
120444
120456
  },
120445
120457
  DirectiveCoordinate: {
120446
- leave: ({ name: name5 }) => join70(["@", name5])
120458
+ leave: ({ name: name5 }) => join71(["@", name5])
120447
120459
  },
120448
120460
  DirectiveArgumentCoordinate: {
120449
- leave: ({ name: name5, argumentName }) => join70(["@", name5, wrap("(", argumentName, ":)")])
120461
+ leave: ({ name: name5, argumentName }) => join71(["@", name5, wrap("(", argumentName, ":)")])
120450
120462
  }
120451
120463
  };
120452
- function join70(maybeArray, separator = "") {
120464
+ function join71(maybeArray, separator = "") {
120453
120465
  var _maybeArray$filter$jo;
120454
120466
  return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter((x) => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : "";
120455
120467
  }
120456
120468
  function block2(array3) {
120457
- return wrap("{\n", indent2(join70(array3, "\n")), "\n}");
120469
+ return wrap("{\n", indent2(join71(array3, "\n")), "\n}");
120458
120470
  }
120459
120471
  function wrap(start, maybeString, end = "") {
120460
120472
  return maybeString != null && maybeString !== "" ? start + maybeString + end : "";
@@ -172422,16 +172434,16 @@ var init_suiteql = __esm({
172422
172434
  block(q2, parent2, limit2 = -1, comparisonType) {
172423
172435
  const scope3 = { relations: [], parent: parent2, correlations: [] };
172424
172436
  let from = q2.from ? this.source(q2.from, scope3) : sql3("");
172425
- for (const join70 of q2.joins) {
172426
- const source = this.source(join70.source, scope3);
172427
- if (!join70.on) {
172428
- from = sql3(from, JOINS[join70.kind], source);
172437
+ for (const join71 of q2.joins) {
172438
+ const source = this.source(join71.source, scope3);
172439
+ if (!join71.on) {
172440
+ from = sql3(from, JOINS[join71.kind], source);
172429
172441
  continue;
172430
172442
  }
172431
- if (hasWindow(join70.on)) invalid26("Analytic functions are not allowed in JOIN conditions.");
172432
- const on = this.expr(join70.on, scope3);
172433
- if (on.aggregate || hasRownum(join70.on)) invalid26("JOIN conditions cannot contain aggregate functions or ROWNUM.");
172434
- from = sql3(from, JOINS[join70.kind], source, " ON ", on);
172443
+ if (hasWindow(join71.on)) invalid26("Analytic functions are not allowed in JOIN conditions.");
172444
+ const on = this.expr(join71.on, scope3);
172445
+ if (on.aggregate || hasRownum(join71.on)) invalid26("JOIN conditions cannot contain aggregate functions or ROWNUM.");
172446
+ from = sql3(from, JOINS[join71.kind], source, " ON ", on);
172435
172447
  }
172436
172448
  for (const e of [q2.where, ...q2.group, q2.having]) if (e && hasWindow(e)) invalid26("Analytic functions are only allowed in the select list and ORDER BY.");
172437
172449
  const split2 = this.rownumFilter(q2.where), usesRownum = expressions(q2).some(hasRownum);
@@ -174396,13 +174408,13 @@ var init_reports = __esm({
174396
174408
 
174397
174409
  // packages/server/src/twins/netsuite/searches.ts
174398
174410
  function joined(ctx, type, name5, error65, plan4) {
174399
- const [join70, column, ...rest2] = name5.split("."), spec = JOINS2[type]?.[join70];
174411
+ const [join71, column, ...rest2] = name5.split("."), spec = JOINS2[type]?.[join71];
174400
174412
  if (!spec || !column || rest2.length) throw error65(name5);
174401
- const target5 = FIELDS4[spec.type], alias = `j_${join70}`, original = target5.from.split(" ")[1];
174413
+ const target5 = FIELDS4[spec.type], alias = `j_${join71}`, original = target5.from.split(" ")[1];
174402
174414
  const replace = (s3) => s3.replace(new RegExp(`\\b${original}\\.`, "g"), `${alias}.`).replace(/\btl\./g, `${alias}_line.`);
174403
- if (!plan4.joins.has(join70)) {
174404
- const on = type === spec.type || type === "customer" && join70 === "contact" || type === "contact" && join70 === "customer" ? spec.on : spec.on.replace(new RegExp(`\\b${original}\\.`, "g"), `${alias}.`);
174405
- plan4.joins.set(join70, `${spec.via ? spec.via + " " : ""}LEFT JOIN ${spec.type} ${alias} ON ${on}${spec.type === "transaction" ? ` LEFT JOIN transactionline ${alias}_line ON ${alias}_line.transaction = ${alias}.id AND ${alias}_line.mainline = 'T'` : ""}`);
174415
+ if (!plan4.joins.has(join71)) {
174416
+ const on = type === spec.type || type === "customer" && join71 === "contact" || type === "contact" && join71 === "customer" ? spec.on : spec.on.replace(new RegExp(`\\b${original}\\.`, "g"), `${alias}.`);
174417
+ plan4.joins.set(join71, `${spec.via ? spec.via + " " : ""}LEFT JOIN ${spec.type} ${alias} ON ${on}${spec.type === "transaction" ? ` LEFT JOIN transactionline ${alias}_line ON ${alias}_line.transaction = ${alias}.id AND ${alias}_line.mainline = 'T'` : ""}`);
174406
174418
  }
174407
174419
  const found = field4(ctx, spec.type, column, error65, { joins: /* @__PURE__ */ new Map() });
174408
174420
  return { ...found, sql: replace(found.sql), ...found.text && { text: replace(found.text) } };
@@ -174582,9 +174594,9 @@ function expression2(ctx, type, filters, params10, plan4) {
174582
174594
  if (!filters.length) return "";
174583
174595
  if (filters.every((entry3) => entry3 && typeof entry3 === "object" && !Array.isArray(entry3))) {
174584
174596
  return filters.map((entry3) => {
174585
- const { name: name5, operator: operator2, values: values2, join: join70, formula, summary } = entry3;
174586
- if (join70 !== void 0 && typeof join70 !== "string") throw badExpression();
174587
- return term(ctx, type, [join70 ? `${join70}.${name5}` : name5, operator2, ...Array.isArray(values2) ? values2 : values2 === void 0 ? [] : [values2]], params10, plan4, summary, formula);
174597
+ const { name: name5, operator: operator2, values: values2, join: join71, formula, summary } = entry3;
174598
+ if (join71 !== void 0 && typeof join71 !== "string") throw badExpression();
174599
+ return term(ctx, type, [join71 ? `${join71}.${name5}` : name5, operator2, ...Array.isArray(values2) ? values2 : values2 === void 0 ? [] : [values2]], params10, plan4, summary, formula);
174588
174600
  }).join(" AND ");
174589
174601
  }
174590
174602
  if (typeof filters[0] === "string" && typeof filters[1] === "string" && !["AND", "OR", "NOT"].includes(String(filters[0]).toUpperCase())) return term(ctx, type, filters, params10, plan4);
@@ -176372,7 +176384,8 @@ function record21(ctx, args) {
176372
176384
  }
176373
176385
  function unchanged(ctx, args) {
176374
176386
  const changes = sql2(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype));
176375
- return checkOutcome(changes.length === 0, `no writes to ${args.types.join(", ")}`, changes.length ? JSON.stringify(changes) : "no committed writes");
176387
+ const types = args.types.length >= netsuiteRecordTypes.length && netsuiteRecordTypes.every((type) => args.types.includes(type)) ? "NetSuite records" : args.types.length > 4 ? `${args.types.slice(0, 3).join(", ")} and ${args.types.length - 3} more record types` : args.types.join(", ");
176388
+ return checkOutcome(changes.length === 0, `no writes to ${types}`, changes.length ? JSON.stringify(changes) : "no committed writes");
176376
176389
  }
176377
176390
  function count4(ctx, args) {
176378
176391
  const actual = recordIds(ctx, args.type).length;
@@ -176382,6 +176395,7 @@ var init_checks13 = __esm({
176382
176395
  "packages/server/src/twins/netsuite/checks.ts"() {
176383
176396
  "use strict";
176384
176397
  init_open_items();
176398
+ init_src();
176385
176399
  init_checks4();
176386
176400
  init_store5();
176387
176401
  }
@@ -181713,8 +181727,9 @@ var init_sessions = __esm({
181713
181727
  });
181714
181728
  }
181715
181729
  /**
181716
- * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or the
181717
- * final block of its stdout. The same `POST /done` entry, with that source; never a second answer.
181730
+ * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or its
181731
+ * stdout (SPEC-056 A), or how much it printed when that is too long to be an answer. The same `POST /done` entry, with
181732
+ * that source; never a second answer.
181718
181733
  */
181719
181734
  answer(env2, id14, answer) {
181720
181735
  return env2.serialize(() => {
@@ -181722,7 +181737,7 @@ var init_sessions = __esm({
181722
181737
  if (state3 === "prepared") throw new AnchaError("SESSION_CONFLICT", "session has not started");
181723
181738
  if (state3 === "finished") throw new AnchaError("SESSION_CONFLICT", "session has finished");
181724
181739
  if (env2.trace.list().some((entry3) => entry3.service === "agent" && entry3.path === "/done")) return { recorded: false };
181725
- env2.trace.record({ source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: answer.output, source: answer.source } });
181740
+ env2.trace.record({ source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: answer.output, source: answer.source, ...answer.printed !== void 0 && { printed: answer.printed } } });
181726
181741
  return { recorded: true };
181727
181742
  });
181728
181743
  }
@@ -182091,10 +182106,13 @@ function sessionRoutes(opts, sessions) {
182091
182106
  } catch {
182092
182107
  throw new AnchaError("USAGE", "request must be a JSON object");
182093
182108
  }
182094
- fields10(input4, ["output", "source"]);
182109
+ fields10(input4, ["output", "source", "printed"]);
182095
182110
  if (typeof input4.output !== "string" || input4.output.length > MAX_ANSWER_CHARS) throw new AnchaError("USAGE", `output must be a string of at most ${MAX_ANSWER_CHARS} characters`);
182096
182111
  if (input4.source !== "reply" && input4.source !== "stdout") throw new AnchaError("USAGE", "source must be reply or stdout");
182097
- return c.json(await sessions.answer(opts.manager.get(c.req.param("id")), c.req.param("sid"), { output: input4.output, source: input4.source }));
182112
+ if (input4.printed !== void 0 && (input4.source !== "stdout" || input4.output !== "" || typeof input4.printed !== "number" || !Number.isSafeInteger(input4.printed) || input4.printed <= 0)) {
182113
+ throw new AnchaError("USAGE", "printed is how many characters stdout held, with source stdout and an empty output");
182114
+ }
182115
+ return c.json(await sessions.answer(opts.manager.get(c.req.param("id")), c.req.param("sid"), { output: input4.output, source: input4.source, ...input4.printed !== void 0 && { printed: input4.printed } }));
182098
182116
  });
182099
182117
  app2.post("/envs/:id/trials/:sid/agent", async (c) => {
182100
182118
  let input4;
@@ -182141,7 +182159,7 @@ var init_session_routes = __esm({
182141
182159
  init_src();
182142
182160
  init_feed();
182143
182161
  init_env_info();
182144
- MAX_ANSWER_CHARS = 16e3;
182162
+ MAX_ANSWER_CHARS = 64 * 1024;
182145
182163
  }
182146
182164
  });
182147
182165
 
@@ -187322,6 +187340,26 @@ import { lookup as lookup5 } from "node:dns/promises";
187322
187340
  import { createServer, request } from "node:http";
187323
187341
  import { request as secureRequest } from "node:https";
187324
187342
  import { isIP as isIP3 } from "node:net";
187343
+ import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
187344
+ function refusalMessage(body7, encoding) {
187345
+ let text29;
187346
+ try {
187347
+ const raw3 = encoding === "gzip" || encoding === "x-gzip" ? gunzipSync(body7) : encoding === "deflate" ? inflateSync(body7) : encoding === "br" ? brotliDecompressSync(body7) : !encoding || encoding === "identity" ? body7 : void 0;
187348
+ if (raw3 === void 0) return void 0;
187349
+ text29 = raw3.toString("utf8");
187350
+ } catch {
187351
+ return void 0;
187352
+ }
187353
+ let message7 = text29;
187354
+ try {
187355
+ const json35 = JSON.parse(text29);
187356
+ const error65 = json35?.error;
187357
+ message7 = typeof error65 === "string" ? error65 : typeof error65?.message === "string" ? error65.message : typeof json35?.message === "string" ? json35.message : typeof json35?.detail === "string" ? json35.detail : typeof error65?.type === "string" ? error65.type : typeof error65?.code === "string" ? error65.code : text29;
187358
+ } catch {
187359
+ }
187360
+ const line2 = String(message7).replace(/\b(sk|rk|pk)-[\w*-]{4,}/g, "$1-\u2026").replace(/\s+/g, " ").trim();
187361
+ return line2 === "" ? void 0 : line2.length > 300 ? `${line2.slice(0, 299)}\u2026` : line2;
187362
+ }
187325
187363
  function loopbackOrigin(value5) {
187326
187364
  const url4 = new URL(value5);
187327
187365
  if (url4.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url4.hostname) || url4.username || url4.password) throw new Error("Isolation gateway requires a local HTTP tool server");
@@ -187462,11 +187500,30 @@ async function startIsolationGateway(options4) {
187462
187500
  agent: false,
187463
187501
  ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
187464
187502
  }, (reply5) => {
187465
- if (modelHost !== void 0 && reply5.statusCode !== void 0) {
187503
+ const observe2 = (host, status5, message7) => {
187466
187504
  try {
187467
- options4.onModelReply?.(modelHost, reply5.statusCode);
187505
+ options4.onModelReply?.(host, status5, message7);
187468
187506
  } catch {
187469
187507
  }
187508
+ };
187509
+ if (modelHost !== void 0 && reply5.statusCode !== void 0) {
187510
+ const host = modelHost, status5 = reply5.statusCode;
187511
+ if (!MODEL_REFUSALS.has(status5)) observe2(host, status5);
187512
+ else {
187513
+ const chunks2 = [];
187514
+ let size3 = 0, told = false;
187515
+ const tell = () => {
187516
+ if (told) return;
187517
+ told = true;
187518
+ observe2(host, status5, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply5.headers["content-encoding"]?.toLowerCase()) : void 0);
187519
+ };
187520
+ reply5.on("data", (chunk) => {
187521
+ size3 += chunk.length;
187522
+ if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
187523
+ });
187524
+ reply5.once("end", tell);
187525
+ reply5.once("close", tell);
187526
+ }
187470
187527
  }
187471
187528
  if (reply5.statusCode && reply5.statusCode >= 300 && reply5.statusCode < 400) {
187472
187529
  reply5.destroy();
@@ -187578,12 +187635,14 @@ async function startIsolationGateway(options4) {
187578
187635
  return mapped(exposedOrigin);
187579
187636
  }, close };
187580
187637
  }
187581
- var BODY_LIMIT, HOP_HEADERS;
187638
+ var BODY_LIMIT, HOP_HEADERS, MODEL_REFUSALS, REFUSAL_BYTES;
187582
187639
  var init_gateway = __esm({
187583
187640
  "backend/src/execution/gateway.ts"() {
187584
187641
  "use strict";
187585
187642
  BODY_LIMIT = 8 * 1024 * 1024;
187586
187643
  HOP_HEADERS = /* @__PURE__ */ new Set(["connection", "proxy-connection", "proxy-authenticate", "proxy-authorization", "keep-alive", "te", "trailer", "transfer-encoding", "upgrade"]);
187644
+ MODEL_REFUSALS = /* @__PURE__ */ new Set([401, 402, 403, 429]);
187645
+ REFUSAL_BYTES = 4096;
187587
187646
  }
187588
187647
  });
187589
187648
 
@@ -187910,38 +187969,38 @@ function withoutScriptBanners(lines2) {
187910
187969
  if (end > start && YARN_DONE.test(lines2[end - 1].trim())) end--;
187911
187970
  return lines2.slice(start, end);
187912
187971
  }
187913
- function finalBlock(stdout) {
187914
- const lines2 = withoutScriptBanners(stdout.replace(ANSI, "").replace(/\r\n?/g, "\n").trimEnd().split("\n"));
187915
- const blank = lines2.findLastIndex((line2) => line2.trim() === "");
187916
- let block2 = (blank >= 0 ? lines2.slice(blank + 1) : lines2.slice(-ANSWER_MAX_LINES)).join("\n");
187917
- if (Buffer.byteLength(block2) > ANSWER_MAX_BYTES) {
187918
- const bytes3 = Buffer.from(block2);
187919
- let end = bytes3.subarray(bytes3.length - ANSWER_MAX_BYTES).toString("utf8").replace(/^�+/, "");
187920
- const line2 = end.indexOf("\n");
187921
- if (line2 >= 0 && line2 < end.length - 1) end = end.slice(line2 + 1);
187922
- block2 = end;
187923
- }
187924
- return block2.replace(/^\s*\n/, "").trimEnd();
187972
+ function stdoutAnswer(stdout) {
187973
+ return withoutScriptBanners(stdout.replace(ANSI, "").replace(/\r\n?/g, "\n").trimEnd().split("\n")).join("\n").trimEnd();
187925
187974
  }
187926
- var TAIL_CHARS, ANSWER_MAX_BYTES, ANSWER_MAX_LINES, OutputTail, ModelReplies, ANSI, NPM_SCRIPT, NPM_COMMAND, YARN_RUN, YARN_COMMAND, YARN_DONE;
187975
+ var ANSWER_MAX_CHARS, STDOUT_MAX_CHARS, OutputTail, ModelReplies, ANSI, NPM_SCRIPT, NPM_COMMAND, YARN_RUN, YARN_COMMAND, YARN_DONE;
187927
187976
  var init_agent_output = __esm({
187928
187977
  "backend/src/runner/agent-output.ts"() {
187929
187978
  "use strict";
187930
- TAIL_CHARS = 64 * 1024;
187931
- ANSWER_MAX_BYTES = 8 * 1024;
187932
- ANSWER_MAX_LINES = 40;
187979
+ init_gateway();
187980
+ ANSWER_MAX_CHARS = 64 * 1024;
187981
+ STDOUT_MAX_CHARS = 2 * ANSWER_MAX_CHARS;
187933
187982
  OutputTail = class {
187983
+ max;
187934
187984
  #text = "";
187935
187985
  #cut = false;
187986
+ #length = 0;
187987
+ constructor(max = STDOUT_MAX_CHARS) {
187988
+ this.max = max;
187989
+ }
187936
187990
  push(text29) {
187937
187991
  this.#text += text29;
187938
- if (this.#text.length > TAIL_CHARS * 2) this.#trim();
187992
+ this.#length += text29.length;
187993
+ if (this.#text.length > this.max * 2) this.#trim();
187939
187994
  }
187940
187995
  #trim() {
187941
- if (this.#text.length <= TAIL_CHARS) return;
187942
- this.#text = this.#text.slice(-TAIL_CHARS);
187996
+ if (this.#text.length <= this.max) return;
187997
+ this.#text = this.#text.slice(-this.max);
187943
187998
  this.#cut = true;
187944
187999
  }
188000
+ /** How many characters were pushed in all. */
188001
+ length() {
188002
+ return this.#length;
188003
+ }
187945
188004
  /** What was kept; a first line cut in the middle is left out. */
187946
188005
  text() {
187947
188006
  this.#trim();
@@ -187950,15 +188009,23 @@ var init_agent_output = __esm({
187950
188009
  };
187951
188010
  ModelReplies = class {
187952
188011
  #counts = /* @__PURE__ */ new Map();
187953
- add(host, status5) {
188012
+ #last;
188013
+ add(host, status5, message7) {
187954
188014
  const key4 = `${host} ${status5}`;
187955
188015
  const reply5 = this.#counts.get(key4);
187956
- if (reply5) reply5.count++;
187957
- else if (this.#counts.size < 100) this.#counts.set(key4, { host, status: status5, count: 1 });
188016
+ if (reply5) {
188017
+ reply5.count++;
188018
+ if (message7 !== void 0) reply5.message ??= message7;
188019
+ } else if (this.#counts.size < 100) this.#counts.set(key4, { host, status: status5, count: 1, ...message7 !== void 0 && { message: message7 } });
188020
+ this.#last = { host, status: status5, ...message7 !== void 0 && { message: message7 } };
187958
188021
  }
187959
188022
  list() {
187960
188023
  return [...this.#counts.values()].map((reply5) => ({ ...reply5 }));
187961
188024
  }
188025
+ /** The last reply, when it refused the key: the provider stopped the agent there. */
188026
+ refusal() {
188027
+ return this.#last !== void 0 && MODEL_REFUSALS.has(this.#last.status) ? { ...this.#last } : void 0;
188028
+ }
187962
188029
  };
187963
188030
  ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
187964
188031
  NPM_SCRIPT = /^> (?:\S+@\S* )?[\w:.-]+(?: \/\S*)?$/;
@@ -188044,7 +188111,7 @@ function outputCopy(logFd) {
188044
188111
  closeSync2(stderr.fd);
188045
188112
  }
188046
188113
  },
188047
- tail: () => tail.text()
188114
+ output: () => ({ stdout: tail.text(), printed: tail.length() })
188048
188115
  };
188049
188116
  }
188050
188117
  function startAgentProcess(command, opts) {
@@ -188101,7 +188168,7 @@ function startAgentProcess(command, opts) {
188101
188168
  return { pid, exited, async stop() {
188102
188169
  terminate();
188103
188170
  await exited;
188104
- }, ...stdout && { output: () => ({ stdout: stdout.tail() }) } };
188171
+ }, ...stdout && { output: stdout.output } };
188105
188172
  }
188106
188173
  var KILL_GRACE_MS, GROUP_POLL_MS, COPY_MS;
188107
188174
  var init_process = __esm({
@@ -188741,7 +188808,7 @@ async function startContainedAgent(command, opts) {
188741
188808
  ]);
188742
188809
  await run6(["start", relayName]);
188743
188810
  const replies = new ModelReplies();
188744
- gateway = await startIsolationGateway({ env: opts.env, session: opts.session, modelHosts: policy.modelHosts, onModelReply: (host, status6) => replies.add(host, status6) });
188811
+ gateway = await startIsolationGateway({ env: opts.env, session: opts.session, modelHosts: policy.modelHosts, onModelReply: (host, status6, message7) => replies.add(host, status6, message7) });
188745
188812
  const script = isolationRelayScript({ port: RELAY_PORT, ...opts.runtime?.port && { agentPort: opts.runtime.port } });
188746
188813
  relayChild = spawn2("docker", ["--context", context3, "exec", "-i", relayName, "node", "-e", script], { env: dockerEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
188747
188814
  relayChild.stderr.on("data", () => {
@@ -188833,7 +188900,7 @@ async function startContainedAgent(command, opts) {
188833
188900
  return { pid: child2.pid, exited, async stop() {
188834
188901
  await cleanup();
188835
188902
  await exited;
188836
- }, output: () => ({ stdout: tail.text(), modelReplies: replies.list() }) };
188903
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
188837
188904
  } catch (error65) {
188838
188905
  opts.signal?.removeEventListener("abort", abort);
188839
188906
  await cleanup();
@@ -189029,7 +189096,7 @@ async function startVmAgent(command, opts, deps = {}) {
189029
189096
  ...opts.session && { session: opts.session },
189030
189097
  modelHosts,
189031
189098
  port: unsafe ? 0 : 18991,
189032
- onModelReply: (host, status5) => replies.add(host, status5)
189099
+ onModelReply: (host, status5, message7) => replies.add(host, status5, message7)
189033
189100
  });
189034
189101
  const mapped = gateway.rewrite(unsafe ? gateway.url : VM_GATEWAY_ORIGIN);
189035
189102
  const agentRuntime = { ...opts.runtime, ...taskFile !== void 0 && { taskFile }, ...opts.runtime?.attempt && { attempt: { ...opts.runtime.attempt, stateDir: paths2.state, records: records4 } } };
@@ -189151,7 +189218,7 @@ async function startVmAgent(command, opts, deps = {}) {
189151
189218
  return { pid: child2.pid, exited, async stop() {
189152
189219
  await cleanup();
189153
189220
  await exited;
189154
- }, output: () => ({ stdout: tail.text(), modelReplies: replies.list() }) };
189221
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
189155
189222
  } catch (error65) {
189156
189223
  await cleanup();
189157
189224
  throw error65;
@@ -215386,6 +215453,242 @@ var init_per_event = __esm({
215386
215453
  }
215387
215454
  });
215388
215455
 
215456
+ // backend/src/agent-fix.ts
215457
+ function givenByTwins(name5) {
215458
+ twinVariables ??= new Set(Object.keys(toolConnectionEnvironment(Object.fromEntries(SUPPORTED_TWINS.map((twin) => [twin, ANY_SERVICE])))));
215459
+ return twinVariables.has(name5);
215460
+ }
215461
+ function taskVariables(text29) {
215462
+ const found = [];
215463
+ for (const match3 of text29.matchAll(TASK_NAME)) {
215464
+ const name5 = match3[1], before = text29.slice(0, match3.index);
215465
+ if (name5.startsWith("ANCHA_") || /--?[A-Za-z][\w-]*[ =]$/.test(before)) continue;
215466
+ const bare = !name5.includes("_");
215467
+ const named5 = escape10(name5);
215468
+ if (bare && !new RegExp(`(?:\\$\\{?|process\\.env\\.|process\\.env\\[['"]|environ(?:\\.get)?\\(?\\[?['"]|getenv\\(['"]|\\bset\\s+|\\bexport\\s+)${named5}\\b|\\b${named5}\\s+(?:is\\s+)?(?:not\\s+set|unset|empty|missing|required|undefined)|\\b${named5}\\s+(?:env(?:ironment)?\\s+)?variable|variable\\s+${named5}\\b|KeyError:\\s*['"]${named5}['"]`).test(text29)) continue;
215469
+ if (!found.includes(name5)) found.push(name5);
215470
+ }
215471
+ return found;
215472
+ }
215473
+ function taskFlags(text29) {
215474
+ return [...new Set([...text29.matchAll(TASK_FLAG)].map((match3) => match3[1]))];
215475
+ }
215476
+ function taskFix(text29, command) {
215477
+ const names5 = taskVariables(text29);
215478
+ const plain6 = names5.find((name5) => !/_(?:FILE|PATH)$/.test(name5)), file3 = names5.find((name5) => /_(?:FILE|PATH)$/.test(name5));
215479
+ if (plain6 !== void 0) return `it looks for its task in ${plain6}; Ancha gives the task in ANCHA_TASK. Add under agent: in ancha.yaml: env: { ${plain6}: "{{task}}" }`;
215480
+ const flags = taskFlags(text29), flag5 = flags.find((f2) => !f2.endsWith("-file")), fileFlag = flags.find((f2) => f2.endsWith("-file"));
215481
+ const shellCommand = command !== void 0 && !/^https?:\/\//.test(command) ? command : void 0;
215482
+ if (flag5 !== void 0 && !shellCommand?.includes(flag5)) {
215483
+ return `it takes its task with ${flag5}; Ancha gives the task in ANCHA_TASK. In ancha.yaml, set agent.command to: ${shellCommand === void 0 ? "<its command>" : shellCommand} ${flag5} "$ANCHA_TASK"`;
215484
+ }
215485
+ if (file3 !== void 0) return `it looks for a file with its task in ${file3}; Ancha writes the task to a file at {{task_file}}. Add under agent: in ancha.yaml: env: { ${file3}: "{{task_file}}" }`;
215486
+ if (fileFlag !== void 0 && !shellCommand?.includes(fileFlag)) {
215487
+ return `it reads its task from the file given with ${fileFlag}; Ancha writes the task to a file at {{task_file}}. Add under agent: in ancha.yaml: env: { TASK_FILE: "{{task_file}}" }, and add ${fileFlag} "$TASK_FILE" to agent.command`;
215488
+ }
215489
+ return void 0;
215490
+ }
215491
+ function missingKey(lines2) {
215492
+ for (const line2 of [...lines2].reverse()) {
215493
+ if (!MISSING.test(line2)) continue;
215494
+ const name5 = [...line2.matchAll(CREDENTIAL)].map((match3) => match3[1]).find((found) => !found.startsWith("ANCHA_") && !givenByTwins(found));
215495
+ if (name5 !== void 0) return name5;
215496
+ }
215497
+ return void 0;
215498
+ }
215499
+ function keyFix(lines2, context3) {
215500
+ const name5 = missingKey(lines2);
215501
+ if (name5 === void 0) return void 0;
215502
+ return context3.target === "cloud" ? `it needs ${name5}: run ancha secrets set ${name5} in the project, which stores it in your workspace and lists it under agent.pass_env in ancha.yaml` : `it needs ${name5}: set it in this shell and list it under agent.pass_env in ancha.yaml (or pass --pass-env ${name5})`;
215503
+ }
215504
+ function missingFix(text29, context3) {
215505
+ const cloud = context3.target === "cloud";
215506
+ const notFoundCommand = /(?:^|\n|: )([\w./@+-]+): (?:command )?not found\b/.exec(text29) ?? /(?:^|\n)(?:sh|bash|zsh|\/bin\/sh)(?:: line \d+|: \d+)?: ([\w./@+-]+): not found/.exec(text29);
215507
+ const packageName = /Cannot find package '([^']+)'/.exec(text29)?.[1];
215508
+ const required4 = /Cannot find module '([^']+)'/.exec(text29)?.[1];
215509
+ const requiredFile = required4 !== void 0 && /^(?:\.{1,2}[/\\]|[/\\]|[A-Za-z]:\\)|\.(?:[cm]?[jt]s|py|sh)$/.test(required4);
215510
+ const missingFile = (requiredFile ? required4 : void 0) ?? /can't open file '([^']+)'/.exec(text29)?.[1] ?? /No such file or directory: '([^']+)'/.exec(text29)?.[1];
215511
+ const module = packageName ?? (requiredFile ? void 0 : required4);
215512
+ const pythonModule2 = /No module named '([^']+)'/.exec(text29)?.[1];
215513
+ const install = cloud ? "the cloud machine installs what the project's manifests list (agent.install in ancha.yaml sets the command)" : "install the project's dependencies";
215514
+ if (module === void 0 && missingFile !== void 0) {
215515
+ const file3 = missingFile.replace(/^.*[/\\](?=[^/\\]+$)/, "");
215516
+ return cloud ? `it could not find ${file3}: check the path in agent.command in ancha.yaml; the cloud machine has the project's files, so a built or gitignored file is built by agent.install or added with --bundle-file` : `it could not find ${file3}: check the path in agent.command in ancha.yaml (it runs in the project folder)`;
215517
+ }
215518
+ if (module !== void 0) return `its dependency ${module} is not installed: add it to package.json; ${install}`;
215519
+ if (pythonModule2 !== void 0) return `its dependency ${pythonModule2} is not installed: add it to requirements.txt or pyproject.toml; ${install}`;
215520
+ if (notFoundCommand !== null) return `its command ${notFoundCommand[1]} was not found: check agent.command in ancha.yaml, or make it a dependency of the project; ${install}`;
215521
+ return void 0;
215522
+ }
215523
+ function likelyFix(logTail3, context3 = {}) {
215524
+ const task2 = taskFix(logTail3.join("\n"), context3.command);
215525
+ if (task2 !== void 0 || context3.withheld !== void 0) return task2 ?? context3.withheld;
215526
+ const errors3 = logTail3.filter((line2) => /error|exception|fatal|panic|missing|required|usage|not set|not found|cannot|can't/i.test(line2));
215527
+ for (const lines2 of [errors3, logTail3]) {
215528
+ const fix = lines2.length === 0 ? void 0 : keyFix(lines2, context3) ?? missingFix(lines2.join("\n"), context3);
215529
+ if (fix !== void 0) return fix;
215530
+ }
215531
+ return void 0;
215532
+ }
215533
+ var TASK_WORD, TASK_NAME, TASK_FLAG, CREDENTIAL, MISSING, twinVariables, escape10;
215534
+ var init_agent_fix = __esm({
215535
+ "backend/src/agent-fix.ts"() {
215536
+ "use strict";
215537
+ init_src();
215538
+ init_agent_env();
215539
+ TASK_WORD = "(?:TASKS?|PROMPTS?|QUERY|QUERIES|INSTRUCTIONS?|MESSAGES?|REQUESTS?|INPUTS?)";
215540
+ TASK_NAME = new RegExp(`(?<![A-Za-z0-9_])((?:[A-Z][A-Z0-9]*_)*${TASK_WORD}(?:_[A-Z0-9]+)*)(?![A-Za-z0-9_])`, "g");
215541
+ TASK_FLAG = /(?<![\w-])(--(?:task|prompt|message|input|query|instructions?|request)(?:-file)?)(?![\w-])/g;
215542
+ CREDENTIAL = /(?<![A-Za-z0-9_])([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*_(?:KEY|TOKEN|SECRET|PASSWORD))(?![A-Za-z0-9_])/g;
215543
+ MISSING = /missing|not set|unset|undefined|required|must be set|no .*(?:key|token)|KeyError|not found|empty|expected/i;
215544
+ escape10 = (text29) => text29.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
215545
+ }
215546
+ });
215547
+
215548
+ // backend/src/agent-outcome.ts
215549
+ function printedOf(entry3) {
215550
+ const printed = entry3.request?.printed;
215551
+ return typeof printed === "number" ? printed : void 0;
215552
+ }
215553
+ function answerOf(entry3) {
215554
+ const request2 = entry3.request ?? {};
215555
+ const text29 = typeof request2.output === "string" ? request2.output : JSON.stringify(request2.output) ?? "";
215556
+ return { source: request2.source === "reply" || request2.source === "stdout" ? request2.source : "done", text: text29 };
215557
+ }
215558
+ function kindOf2(path7) {
215559
+ if (/^\/app\/site\/hosting\/restlet\.nl/i.test(path7)) return "restlet";
215560
+ if (/^\/services\/NetSuitePort/i.test(path7)) return "soap";
215561
+ if (path7.startsWith("/services/rest/query/v1/suiteql")) return "suiteql";
215562
+ if (path7.startsWith("/services/rest/record/") || path7.startsWith("/services/rest/async/")) return "record";
215563
+ if (path7.startsWith("/services/mcp/")) return "mcp";
215564
+ if (path7.startsWith("/services/rest/auth/")) return "auth";
215565
+ return "other";
215566
+ }
215567
+ function netsuiteStarterCustomers() {
215568
+ const seed43 = toolStarterSeed("netsuite");
215569
+ customers2 ??= (seed43.customers ?? []).map((c) => c.companyName ?? [c.firstName, c.lastName].filter(Boolean).join(" ")).filter((name5) => name5 !== "");
215570
+ return customers2;
215571
+ }
215572
+ function namesStarterCustomer(answer) {
215573
+ const said = words5(answer);
215574
+ return netsuiteStarterCustomers().some((name5) => {
215575
+ const whole2 = words5(name5), first = whole2.trim().split(" ")[0];
215576
+ return said.includes(whole2) || first.length >= 5 && said.includes(` ${first} `);
215577
+ });
215578
+ }
215579
+ function modelKeyName(host, given2) {
215580
+ const [pattern, usual2] = PROVIDER_KEYS[host] ?? [/(?!)/, "NAME"];
215581
+ return given2.find((name5) => pattern.test(name5) && /KEY|TOKEN/.test(name5)) ?? usual2;
215582
+ }
215583
+ function refusal(entry3) {
215584
+ const details = entry3.response?.["o:errorDetails"];
215585
+ const code5 = Array.isArray(details) ? details[0]?.["o:errorCode"] : void 0;
215586
+ return typeof code5 === "string" ? `${entry3.status} ${code5}` : String(entry3.status);
215587
+ }
215588
+ function unservedReason(unserved) {
215589
+ const first = unserved[0], kind2 = kindOf2(first.path), call4 = `${first.method} ${first.path}${unserved.length > 1 ? ` ${times(unserved.length)}` : ""}`;
215590
+ const what = kind2 === "restlet" ? "a RESTlet (your own SuiteScript)" : kind2 === "soap" ? "SuiteTalk SOAP web services" : "which Ancha's NetSuite does not serve";
215591
+ return { message: `It called ${call4}, ${what}.`, fix: SERVED };
215592
+ }
215593
+ function answeredNetsuite(calls2, answer) {
215594
+ const parts3 = [["suiteql", "SuiteQL"], ["record", "REST records"], ["mcp", "the MCP tools"]].map(([kind2, label5]) => [label5, calls2.filter((entry3) => kindOf2(entry3.path) === kind2).length]).filter(([, n2]) => n2 > 0).map(([label5, n2]) => `${label5} ${times(n2)}`);
215595
+ return `NetSuite: it ${parts3.length > 0 ? `called ${list17(parts3)} and ` : ""}answered ${quoted3(answer)}.`;
215596
+ }
215597
+ function endedSentence(view3) {
215598
+ if (view3.exit === "spawn_failed") return "The agent could not be started.";
215599
+ return view3.exitCode === null ? `The agent stopped on a signal after ${view3.realMs} ms.` : `The agent exited with code ${view3.exitCode} after ${view3.realMs} ms.`;
215600
+ }
215601
+ function attemptOutcome(view3, ctx) {
215602
+ const calls2 = view3.trace.filter((entry3) => entry3.source === "agent" && !isAgentAnswer(entry3));
215603
+ const netsuite = calls2.filter((entry3) => entry3.service === "netsuite");
215604
+ const unserved = netsuite.filter((entry3) => entry3.gap === true || kindOf2(entry3.path) === "restlet" || kindOf2(entry3.path) === "soap");
215605
+ const used = netsuite.filter((entry3) => !unserved.includes(entry3)), data5 = used.filter((entry3) => kindOf2(entry3.path) !== "auth");
215606
+ const served = used.filter((entry3) => entry3.status !== void 0 && entry3.status < 400);
215607
+ const hosts = netsuiteHosts(view3.log);
215608
+ const done = view3.trace.findLast(isAgentAnswer), printed = done === void 0 ? void 0 : printedOf(done), answer = done === void 0 || printed !== void 0 ? void 0 : answerOf(done);
215609
+ const byStatus = {};
215610
+ for (const entry3 of calls2) if (entry3.status !== void 0) byStatus[String(entry3.status)] = (byStatus[String(entry3.status)] ?? 0) + 1;
215611
+ const gaps2 = [...new Set(calls2.filter((entry3) => entry3.gap === true || unserved.includes(entry3)).map((entry3) => `${entry3.method} ${entry3.path}`))];
215612
+ const summary = { total: calls2.length, byStatus, gaps: gaps2.slice(0, 5), hosts: hosts.slice(0, 5) };
215613
+ const out = (reason2) => ({ reason: reason2, calls: summary, ...answer !== void 0 && { answer: { source: answer.source, text: answer.text.slice(0, 200) } } });
215614
+ if (answer !== void 0 && (ctx.check === "start" || ctx.check === "netsuite" && namesStarterCustomer(answer.text))) {
215615
+ if (unserved.length > 0) return out({ code: "unserved", level: "warning", ...unservedReason(unserved) });
215616
+ return out({ code: "answered", level: "pass", message: ctx.check === "netsuite" ? answeredNetsuite(netsuite, answer.text) : `It took the task and answered ${quoted3(answer.text)}.` });
215617
+ }
215618
+ const model2 = view3.modelReplies?.find((reply5) => MODEL_REFUSALS.has(reply5.status));
215619
+ if (model2 !== void 0) return out({ code: "model_key", level: "fail", message: `The model key was refused: ${model2.host} answered ${model2.status}${model2.message ? ` (${model2.message})` : ""}.`, fix: `ancha secrets set ${modelKeyName(model2.host, ctx.given ?? [])}` });
215620
+ const refused2 = (entry3) => entry3.status === 401 || entry3.status === 403;
215621
+ const turnedDown = used.length > 0 && used.every(refused2) ? used : data5.length > 0 && data5.every(refused2) ? data5 : [];
215622
+ if (turnedDown.length > 0) {
215623
+ const n2 = turnedDown.length;
215624
+ return out({ code: "refused", level: "fail", message: `NetSuite refused ${n2 === 1 ? "its one call" : `all ${n2} calls`} (${list17([...new Set(turnedDown.map(refusal))])}).`, fix: SIGN });
215625
+ }
215626
+ if (hosts.length > 0 && served.length === 0) return out({ code: "outside_host", level: "fail", message: `It tried to reach ${list17(hosts.slice(0, 3))}.`, fix: OUTSIDE });
215627
+ if (unserved.length > 0 && data5.length === 0) return out({ code: "unserved", level: "fail", ...unservedReason(unserved) });
215628
+ const crashed = view3.exit === "spawn_failed" || view3.exit === "exited" && view3.exitCode !== 0;
215629
+ const did = calls2.length > 0 || ctx.taskMark !== void 0 && view3.log.includes(ctx.taskMark);
215630
+ if (crashed && (ctx.check !== "start" || !did)) {
215631
+ const tail = view3.logTail?.length ? view3.logTail : view3.log.trimEnd().split("\n").slice(-10);
215632
+ const fix = ctx.taskFix ?? likelyFix(tail, { target: ctx.target ?? "cloud", ...ctx.command !== void 0 && { command: ctx.command } });
215633
+ const key4 = ctx.taskFix === void 0 ? missingKey(tail) : void 0;
215634
+ return out({ code: key4 !== void 0 && fix?.includes(key4) ? "missing_secret" : "crashed", level: "fail", message: endedSentence(view3), ...fix !== void 0 && { fix } });
215635
+ }
215636
+ if (view3.exit === "timeout" && view3.log.trim() === "" && calls2.length === 0 && !view3.modelReplies?.length && answer === void 0) {
215637
+ const fix = ctx.stdin ? `it reads its task from stdin (${ctx.stdin.source}:${ctx.stdin.line}): in ancha.yaml under agent:, set input: stdin` : "if it waits for input, hand it the task: it is in ANCHA_TASK and ANCHA_TASK_FILE, or on its stdin with agent.input: stdin in ancha.yaml";
215638
+ return out({ code: "idle", level: "fail", message: `It ran ${Math.round(view3.realMs / 1e3)} s without output, a model call, a tool call or an answer.`, fix });
215639
+ }
215640
+ const level3 = ctx.answerChecked ? "fail" : "warning";
215641
+ const called = netsuite.length > 0 ? `It called NetSuite ${times(netsuite.length)}` : ctx.check === "netsuite" ? "It made no NetSuite call" : "It";
215642
+ if (answer === void 0) return out({ code: "no_answer", level: level3, message: `${called}${called === "It" ? "" : netsuite.length > 0 ? " but" : " and"} ${printed === void 0 ? NO_ANSWER : `printed ${printed.toLocaleString("en-US")} characters on stdout, more than an answer can be.`}`, fix: POST_ANSWER });
215643
+ if (ctx.check === "netsuite") {
215644
+ const names5 = netsuiteStarterCustomers();
215645
+ return out({
215646
+ code: "wrong_answer",
215647
+ level: level3,
215648
+ message: `${called} and answered ${quoted3(answer.text)}, which names none of its NetSuite customers (${list17([...names5.slice(0, 2), ...names5.length > 2 ? [`${names5.length - 2} more`] : []])}).`,
215649
+ fix: "the check asks it to find one customer in NetSuite and reply with the name; its answer is what it posts to ANCHA_DONE_URL or prints on stdout"
215650
+ });
215651
+ }
215652
+ return out({ code: "answered", level: "pass", message: `It answered ${quoted3(answer.text)}.` });
215653
+ }
215654
+ var oneLine4, quoted3, times, list17, NETSUITE_HOST, netsuiteHosts, customers2, words5, PROVIDER_KEYS, SIGN, OUTSIDE, SERVED, NO_ANSWER, POST_ANSWER;
215655
+ var init_agent_outcome = __esm({
215656
+ "backend/src/agent-outcome.ts"() {
215657
+ "use strict";
215658
+ init_src();
215659
+ init_agent_fix();
215660
+ init_gateway();
215661
+ oneLine4 = (text29) => text29.replace(/\s+/g, " ").trim();
215662
+ quoted3 = (text29) => {
215663
+ const line2 = oneLine4(text29);
215664
+ return `"${line2.length > 80 ? `${line2.slice(0, 79)}\u2026` : line2}"`;
215665
+ };
215666
+ times = (n2) => n2 === 1 ? "once" : `${n2} times`;
215667
+ list17 = (items2) => items2.length <= 1 ? items2.join("") : `${items2.slice(0, -1).join(", ")} and ${items2.at(-1)}`;
215668
+ NETSUITE_HOST = /\b[a-z0-9-]+\.(?:suitetalk|restlets)\.api\.netsuite\.com\b|\b[a-z0-9-]+\.app\.netsuite\.com\b/gi;
215669
+ netsuiteHosts = (log3) => [...new Set([...log3.matchAll(NETSUITE_HOST)].map((match3) => match3[0].toLowerCase()))];
215670
+ words5 = (text29) => ` ${text29.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
215671
+ PROVIDER_KEYS = {
215672
+ "api.anthropic.com": [/ANTHROPIC|CLAUDE/, "ANTHROPIC_API_KEY"],
215673
+ "api.openai.com": [/OPENAI/, "OPENAI_API_KEY"],
215674
+ "openrouter.ai": [/OPENROUTER/, "OPENROUTER_API_KEY"],
215675
+ "generativelanguage.googleapis.com": [/GEMINI|GOOGLE/, "GEMINI_API_KEY"],
215676
+ "api.groq.com": [/GROQ/, "GROQ_API_KEY"],
215677
+ "api.mistral.ai": [/MISTRAL/, "MISTRAL_API_KEY"],
215678
+ "api.together.xyz": [/TOGETHER/, "TOGETHER_API_KEY"],
215679
+ "api.fireworks.ai": [/FIREWORKS/, "FIREWORKS_API_KEY"],
215680
+ "api.deepseek.com": [/DEEPSEEK/, "DEEPSEEK_API_KEY"],
215681
+ "api.x.ai": [/XAI|GROK/, "XAI_API_KEY"],
215682
+ "api.cohere.com": [/COHERE|CO_API/, "COHERE_API_KEY"]
215683
+ };
215684
+ SIGN = "The agent must sign with the variables Ancha gives: NETSUITE_ACCESS_TOKEN, or the four TBA values.";
215685
+ OUTSIDE = "In Ancha it reaches NetSuite at NETSUITE_API_URL: build its URLs from that variable.";
215686
+ SERVED = "Ancha's NetSuite serves REST records, SuiteQL, OAuth 2.0, OAuth 1.0 TBA and Oracle's MCP tools, not RESTlets or SOAP.";
215687
+ NO_ANSWER = "gave no answer: post it to ANCHA_DONE_URL or print it on stdout.";
215688
+ POST_ANSWER = 'POST {"output": "<the answer>"} to $ANCHA_DONE_URL with Authorization: Bearer $ANCHA_TRIAL_TOKEN, or print the answer on stdout and the logs on stderr';
215689
+ }
215690
+ });
215691
+
215389
215692
  // backend/src/runner/trial.ts
215390
215693
  import { setTimeout as sleep8 } from "node:timers/promises";
215391
215694
  import { closeSync as closeSync6, openSync as openSync6, writeSync as writeSync6 } from "node:fs";
@@ -215395,16 +215698,29 @@ function answersFrom(agent, source) {
215395
215698
  const mode = agent.answer ?? "auto";
215396
215699
  return mode === "auto" || mode === "stdout" && source === "stdout";
215397
215700
  }
215398
- async function recordAnswer(backend, envId, sessionId, output2, source) {
215399
- if (output2.trim() === "" || backend.recordAnswer === void 0) return void 0;
215701
+ async function recordAnswer(backend, envId, sessionId, output2, source, printed) {
215702
+ if (output2.trim() === "" && printed === void 0 || backend.recordAnswer === void 0) return void 0;
215400
215703
  try {
215401
- await backend.recordAnswer(envId, sessionId, { output: output2, source });
215704
+ await backend.recordAnswer(envId, sessionId, { output: output2, source, ...printed !== void 0 && { printed } });
215402
215705
  return void 0;
215403
215706
  } catch (error65) {
215404
215707
  if (unknownRoute18(error65)) return void 0;
215405
215708
  return { kind: "world", owner: "harness", service: "agent", message: `the agent's answer from its ${source === "reply" ? "reply" : "stdout"} could not be recorded: ${error65 instanceof Error ? error65.message : String(error65)}` };
215406
215709
  }
215407
215710
  }
215711
+ function modelKeyIssue(refusal4, given2) {
215712
+ return {
215713
+ kind: "model",
215714
+ owner: "harness",
215715
+ service: refusal4.host,
215716
+ code: "MODEL_KEY_REFUSED",
215717
+ message: `${refusal4.host} refused the agent's model key (${refusal4.status}${refusal4.message ? `: ${refusal4.message}` : ""}), so the attempt tested nothing. Give the agent a working ${modelKeyName(refusal4.host, given2)} and run again.`
215718
+ };
215719
+ }
215720
+ function recordStdout(backend, envId, sessionId, output2) {
215721
+ const answer = stdoutAnswer(output2?.stdout ?? ""), printed = output2?.printed ?? output2?.stdout.length ?? 0;
215722
+ return printed > STDOUT_MAX_CHARS || answer.length > ANSWER_MAX_CHARS ? recordAnswer(backend, envId, sessionId, "", "stdout", printed) : recordAnswer(backend, envId, sessionId, answer, "stdout");
215723
+ }
215408
215724
  async function runTrial(spec) {
215409
215725
  const { backend, env: env2, scene: scene2, trial, dir: dir2, signal, inheritedEnv = process.env } = spec;
215410
215726
  const agent = scene2.agent_input && spec.agent.mode !== "endpoint" ? { ...spec.agent, taskInput: sceneTaskInput(scene2, spec.agent.taskInput) } : spec.agent;
@@ -215499,7 +215815,7 @@ async function runTrial(spec) {
215499
215815
  const playOutIssues = [];
215500
215816
  const ended = exit === "timeout" || exit === "done" || exit === "exited" && exitCode === 0;
215501
215817
  if (ended && failure6 === void 0 && !signal?.aborted && answersFrom(agent, "stdout")) {
215502
- const issue6 = await recordAnswer(backend, env2.id, session2.id, finalBlock(output2?.stdout ?? ""), "stdout");
215818
+ const issue6 = await recordStdout(backend, env2.id, session2.id, output2);
215503
215819
  if (issue6 !== void 0) playOutIssues.push(issue6);
215504
215820
  }
215505
215821
  let playOut;
@@ -215512,6 +215828,7 @@ async function runTrial(spec) {
215512
215828
  }
215513
215829
  const capture4 = await captureTrialAfterFailure(failure6, backend, env2.id, session2.id, dir2, scene2, { ...spec.judge, ...signal !== void 0 && { signal } }, void 0, spec.onCaptured);
215514
215830
  const { checks: checks2, trace, simMs } = capture4, harnessIssues = [...capture4.harnessIssues, ...playOutIssues];
215831
+ if (output2?.modelRefusal !== void 0) harnessIssues.push(modelKeyIssue(output2.modelRefusal, Object.keys(agent.env ?? {})));
215515
215832
  if (failure6 !== void 0) throw failure6.error;
215516
215833
  signal?.throwIfAborted();
215517
215834
  return {
@@ -215551,6 +215868,7 @@ var init_trial = __esm({
215551
215868
  init_per_event();
215552
215869
  init_budget();
215553
215870
  init_agent_output();
215871
+ init_agent_outcome();
215554
215872
  init_agent_env();
215555
215873
  EXIT_COMMAND_NOT_FOUND2 = 127;
215556
215874
  unknownRoute18 = (error65) => error65 instanceof AnchaError && error65.code === "USAGE" && error65.message.startsWith("no such route");
@@ -216199,11 +216517,38 @@ var init_run = __esm({
216199
216517
  }
216200
216518
  });
216201
216519
 
216520
+ // backend/src/kit/connection-tools.ts
216521
+ import { readFile as readFile8 } from "node:fs/promises";
216522
+ import { join as join19 } from "node:path";
216523
+ async function connectionTools(root3) {
216524
+ const text29 = await readFile8(join19(root3, CONNECTION_TOOLS_PATH), "utf8").catch((error65) => {
216525
+ if (error65.code === "ENOENT") return void 0;
216526
+ throw error65;
216527
+ });
216528
+ if (text29 === void 0) return [];
216529
+ const value5 = JSON.parse(text29);
216530
+ if (!Array.isArray(value5) || value5.length > SUPPORTED_TWINS.length || value5.some((name5) => !SUPPORTED_TWINS.includes(name5))) {
216531
+ throw new AnchaError("CONFIG_INVALID", "The connection tools must name Ancha twins.");
216532
+ }
216533
+ return [...new Set(value5)];
216534
+ }
216535
+ function probeToolCalls(twins, trace) {
216536
+ return twins.map((name5) => ({ name: name5, calls: trace.filter((entry3) => entry3.source === "agent" && entry3.service === name5 && !isAgentAnswer(entry3)).length }));
216537
+ }
216538
+ var CONNECTION_TOOLS_PATH;
216539
+ var init_connection_tools = __esm({
216540
+ "backend/src/kit/connection-tools.ts"() {
216541
+ "use strict";
216542
+ init_src();
216543
+ CONNECTION_TOOLS_PATH = "ancha/connection-tools.json";
216544
+ }
216545
+ });
216546
+
216202
216547
  // backend/src/run-bundle.ts
216203
216548
  import { createHash as createHash59 } from "node:crypto";
216204
- import { readdir as readdir3, readFile as readFile8 } from "node:fs/promises";
216205
- import { join as join20 } from "node:path";
216206
- import { gunzipSync as gunzipSync2, gzipSync } from "node:zlib";
216549
+ import { readdir as readdir3, readFile as readFile9 } from "node:fs/promises";
216550
+ import { join as join21 } from "node:path";
216551
+ import { gunzipSync as gunzipSync3, gzipSync } from "node:zlib";
216207
216552
  function bundleSource(env2) {
216208
216553
  return env2.CI === "true" || env2.GITHUB_ACTIONS ? "ci" : "cli";
216209
216554
  }
@@ -216211,7 +216556,7 @@ async function bundleSecrets(options4) {
216211
216556
  const base3 = new Set(BASE_ENV);
216212
216557
  const names5 = options4.inheritEnv ? Object.keys(options4.env).filter((name5) => !base3.has(name5) && !name5.startsWith("LC_")) : [...options4.passEnv ?? []];
216213
216558
  const values2 = names5.map((name5) => options4.env[name5]);
216214
- const file3 = await readFile8(join20(options4.cwd, ".ancha/openrouter.env"), "utf8").catch(() => "");
216559
+ const file3 = await readFile9(join21(options4.cwd, ".ancha/openrouter.env"), "utf8").catch(() => "");
216215
216560
  for (const line2 of file3.split(/\r?\n/)) {
216216
216561
  const match3 = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.*?)\s*$/.exec(line2);
216217
216562
  if (match3) values2.push(match3[1].replace(/^(['"])(.*)\1$/, "$2"));
@@ -216251,7 +216596,7 @@ async function runFiles(runDir, source) {
216251
216596
  const root3 = await readdir3(runDir, { withFileTypes: true });
216252
216597
  const paths2 = ["summary.json", "inputs.json", "reproduction.json", "cloud.json"].filter((name5) => allowedFor(source, name5) && root3.some((entry3) => entry3.isFile() && entry3.name === name5));
216253
216598
  for (const dir2 of root3.filter((entry3) => entry3.isDirectory()).map((entry3) => entry3.name).sort()) {
216254
- for (const file3 of (await readdir3(join20(runDir, dir2), { withFileTypes: true })).filter((entry3) => entry3.isFile()).map((entry3) => entry3.name).sort()) {
216599
+ for (const file3 of (await readdir3(join21(runDir, dir2), { withFileTypes: true })).filter((entry3) => entry3.isFile()).map((entry3) => entry3.name).sort()) {
216255
216600
  if (allowedFor(source, `${dir2}/${file3}`)) paths2.push(`${dir2}/${file3}`);
216256
216601
  }
216257
216602
  }
@@ -216265,7 +216610,7 @@ async function packRun(options4) {
216265
216610
  if (paths2.length + 1 > most) throw tooBig2(`run ${options4.runId} has ${paths2.length} files to upload; a run bundle holds at most ${most - 1} besides its manifest`);
216266
216611
  const entries4 = [], omitted = [];
216267
216612
  for (const path7 of paths2) {
216268
- let data5 = redact(await readFile8(join20(options4.runDir, path7)), options4.secrets);
216613
+ let data5 = redact(await readFile9(join21(options4.runDir, path7)), options4.secrets);
216269
216614
  const cap = capFor(path7, options4.inputsBytes);
216270
216615
  if (data5.length > cap) {
216271
216616
  if (path7.endsWith("/agent.log")) data5 = logTail2(data5, cap);
@@ -216332,7 +216677,7 @@ function writeTar(entries4, mtimeMs) {
216332
216677
  return Buffer.concat(parts3);
216333
216678
  }
216334
216679
  function readBundle(archive) {
216335
- const tar = gunzipSync2(archive, { maxOutputLength: BUNDLE_LIMITS2.unpackedBytes + 1024 * 1024 });
216680
+ const tar = gunzipSync3(archive, { maxOutputLength: BUNDLE_LIMITS2.unpackedBytes + 1024 * 1024 });
216336
216681
  const entries4 = [];
216337
216682
  for (let offset18 = 0; offset18 + 512 <= tar.length; ) {
216338
216683
  const block2 = tar.subarray(offset18, offset18 + 512);
@@ -216449,101 +216794,9 @@ var init_reproduction_text = __esm({
216449
216794
  }
216450
216795
  });
216451
216796
 
216452
- // backend/src/agent-fix.ts
216453
- function givenByTwins(name5) {
216454
- twinVariables ??= new Set(Object.keys(toolConnectionEnvironment(Object.fromEntries(SUPPORTED_TWINS.map((twin) => [twin, ANY_SERVICE])))));
216455
- return twinVariables.has(name5);
216456
- }
216457
- function taskVariables(text29) {
216458
- const found = [];
216459
- for (const match3 of text29.matchAll(TASK_NAME)) {
216460
- const name5 = match3[1], before = text29.slice(0, match3.index);
216461
- if (name5.startsWith("ANCHA_") || /--?[A-Za-z][\w-]*[ =]$/.test(before)) continue;
216462
- const bare = !name5.includes("_");
216463
- const named5 = escape10(name5);
216464
- if (bare && !new RegExp(`(?:\\$\\{?|process\\.env\\.|process\\.env\\[['"]|environ(?:\\.get)?\\(?\\[?['"]|getenv\\(['"]|\\bset\\s+|\\bexport\\s+)${named5}\\b|\\b${named5}\\s+(?:is\\s+)?(?:not\\s+set|unset|empty|missing|required|undefined)|\\b${named5}\\s+(?:env(?:ironment)?\\s+)?variable|variable\\s+${named5}\\b|KeyError:\\s*['"]${named5}['"]`).test(text29)) continue;
216465
- if (!found.includes(name5)) found.push(name5);
216466
- }
216467
- return found;
216468
- }
216469
- function taskFlags(text29) {
216470
- return [...new Set([...text29.matchAll(TASK_FLAG)].map((match3) => match3[1]))];
216471
- }
216472
- function taskFix(text29, command) {
216473
- const names5 = taskVariables(text29);
216474
- const plain6 = names5.find((name5) => !/_(?:FILE|PATH)$/.test(name5)), file3 = names5.find((name5) => /_(?:FILE|PATH)$/.test(name5));
216475
- if (plain6 !== void 0) return `it looks for its task in ${plain6}; Ancha gives the task in ANCHA_TASK. Add under agent: in ancha.yaml: env: { ${plain6}: "{{task}}" }`;
216476
- const flags = taskFlags(text29), flag5 = flags.find((f2) => !f2.endsWith("-file")), fileFlag = flags.find((f2) => f2.endsWith("-file"));
216477
- const shellCommand = command !== void 0 && !/^https?:\/\//.test(command) ? command : void 0;
216478
- if (flag5 !== void 0 && !shellCommand?.includes(flag5)) {
216479
- return `it takes its task with ${flag5}; Ancha gives the task in ANCHA_TASK. In ancha.yaml, set agent.command to: ${shellCommand === void 0 ? "<its command>" : shellCommand} ${flag5} "$ANCHA_TASK"`;
216480
- }
216481
- if (file3 !== void 0) return `it looks for a file with its task in ${file3}; Ancha writes the task to a file at {{task_file}}. Add under agent: in ancha.yaml: env: { ${file3}: "{{task_file}}" }`;
216482
- if (fileFlag !== void 0 && !shellCommand?.includes(fileFlag)) {
216483
- return `it reads its task from the file given with ${fileFlag}; Ancha writes the task to a file at {{task_file}}. Add under agent: in ancha.yaml: env: { TASK_FILE: "{{task_file}}" }, and add ${fileFlag} "$TASK_FILE" to agent.command`;
216484
- }
216485
- return void 0;
216486
- }
216487
- function missingKey(lines2) {
216488
- for (const line2 of [...lines2].reverse()) {
216489
- if (!MISSING.test(line2)) continue;
216490
- const name5 = [...line2.matchAll(CREDENTIAL)].map((match3) => match3[1]).find((found) => !found.startsWith("ANCHA_") && !givenByTwins(found));
216491
- if (name5 !== void 0) return name5;
216492
- }
216493
- return void 0;
216494
- }
216495
- function keyFix(lines2, context3) {
216496
- const name5 = missingKey(lines2);
216497
- if (name5 === void 0) return void 0;
216498
- return context3.target === "cloud" ? `it needs ${name5}: run ancha secrets set ${name5} in the project, which stores it in your workspace and lists it under agent.pass_env in ancha.yaml` : `it needs ${name5}: set it in this shell and list it under agent.pass_env in ancha.yaml (or pass --pass-env ${name5})`;
216499
- }
216500
- function missingFix(text29, context3) {
216501
- const cloud = context3.target === "cloud";
216502
- const notFoundCommand = /(?:^|\n|: )([\w./@+-]+): (?:command )?not found\b/.exec(text29) ?? /(?:^|\n)(?:sh|bash|zsh|\/bin\/sh)(?:: line \d+|: \d+)?: ([\w./@+-]+): not found/.exec(text29);
216503
- const packageName = /Cannot find package '([^']+)'/.exec(text29)?.[1];
216504
- const required4 = /Cannot find module '([^']+)'/.exec(text29)?.[1];
216505
- const requiredFile = required4 !== void 0 && /^(?:\.{1,2}[/\\]|[/\\]|[A-Za-z]:\\)|\.(?:[cm]?[jt]s|py|sh)$/.test(required4);
216506
- const missingFile = (requiredFile ? required4 : void 0) ?? /can't open file '([^']+)'/.exec(text29)?.[1] ?? /No such file or directory: '([^']+)'/.exec(text29)?.[1];
216507
- const module = packageName ?? (requiredFile ? void 0 : required4);
216508
- const pythonModule2 = /No module named '([^']+)'/.exec(text29)?.[1];
216509
- const install = cloud ? "the cloud machine installs what the project's manifests list (agent.install in ancha.yaml sets the command)" : "install the project's dependencies";
216510
- if (module === void 0 && missingFile !== void 0) {
216511
- const file3 = missingFile.replace(/^.*[/\\](?=[^/\\]+$)/, "");
216512
- return cloud ? `it could not find ${file3}: check the path in agent.command in ancha.yaml; the cloud machine has the project's files, so a built or gitignored file is built by agent.install or added with --bundle-file` : `it could not find ${file3}: check the path in agent.command in ancha.yaml (it runs in the project folder)`;
216513
- }
216514
- if (module !== void 0) return `its dependency ${module} is not installed: add it to package.json; ${install}`;
216515
- if (pythonModule2 !== void 0) return `its dependency ${pythonModule2} is not installed: add it to requirements.txt or pyproject.toml; ${install}`;
216516
- if (notFoundCommand !== null) return `its command ${notFoundCommand[1]} was not found: check agent.command in ancha.yaml, or make it a dependency of the project; ${install}`;
216517
- return void 0;
216518
- }
216519
- function likelyFix(logTail3, context3 = {}) {
216520
- const task2 = taskFix(logTail3.join("\n"), context3.command);
216521
- if (task2 !== void 0 || context3.withheld !== void 0) return task2 ?? context3.withheld;
216522
- const errors3 = logTail3.filter((line2) => /error|exception|fatal|panic|missing|required|usage|not set|not found|cannot|can't/i.test(line2));
216523
- for (const lines2 of [errors3, logTail3]) {
216524
- const fix = lines2.length === 0 ? void 0 : keyFix(lines2, context3) ?? missingFix(lines2.join("\n"), context3);
216525
- if (fix !== void 0) return fix;
216526
- }
216527
- return void 0;
216528
- }
216529
- var TASK_WORD, TASK_NAME, TASK_FLAG, CREDENTIAL, MISSING, twinVariables, escape10;
216530
- var init_agent_fix = __esm({
216531
- "backend/src/agent-fix.ts"() {
216532
- "use strict";
216533
- init_src();
216534
- init_agent_env();
216535
- TASK_WORD = "(?:TASKS?|PROMPTS?|QUERY|QUERIES|INSTRUCTIONS?|MESSAGES?|REQUESTS?|INPUTS?)";
216536
- TASK_NAME = new RegExp(`(?<![A-Za-z0-9_])((?:[A-Z][A-Z0-9]*_)*${TASK_WORD}(?:_[A-Z0-9]+)*)(?![A-Za-z0-9_])`, "g");
216537
- TASK_FLAG = /(?<![\w-])(--(?:task|prompt|message|input|query|instructions?|request)(?:-file)?)(?![\w-])/g;
216538
- CREDENTIAL = /(?<![A-Za-z0-9_])([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*_(?:KEY|TOKEN|SECRET|PASSWORD))(?![A-Za-z0-9_])/g;
216539
- MISSING = /missing|not set|unset|undefined|required|must be set|no .*(?:key|token)|KeyError|not found|empty|expected/i;
216540
- escape10 = (text29) => text29.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
216541
- }
216542
- });
216543
-
216544
216797
  // backend/src/report.ts
216545
- import { readFile as readFile9, writeFile as writeFile9 } from "node:fs/promises";
216546
- import { basename as basename6, dirname as dirname9, join as join21, relative as relative8, resolve as resolve15 } from "node:path";
216798
+ import { readFile as readFile10, writeFile as writeFile9 } from "node:fs/promises";
216799
+ import { basename as basename6, dirname as dirname9, join as join22, relative as relative8, resolve as resolve15 } from "node:path";
216547
216800
  function okFalseError(response5) {
216548
216801
  if (typeof response5 !== "object" || response5 === null || response5.ok !== false) return void 0;
216549
216802
  const error65 = response5.error;
@@ -216592,7 +216845,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
216592
216845
  }
216593
216846
  const exit = t.exit === "invalid" && t.originalExit === "spawn_failed" ? "spawn_failed" : t.exit;
216594
216847
  if (!t.passed && exit !== "invalid" && !exitedCleanly({ exit, exitCode: t.exitCode }) && agentIssues.length < MAX_FAILURES_PER_SCENE) {
216595
- agentIssues.push({ sceneId, trial: t.trial, exit, exitCode: t.exitCode, realMs: t.realMs, log: join21(t.dir, "agent.log"), logTail: t.logTail, ...t.invocations !== void 0 && { invocations: t.invocations } });
216848
+ agentIssues.push({ sceneId, trial: t.trial, exit, exitCode: t.exitCode, realMs: t.realMs, log: join22(t.dir, "agent.log"), logTail: t.logTail, ...t.invocations !== void 0 && { invocations: t.invocations } });
216596
216849
  }
216597
216850
  const valid2 = trialValid(t);
216598
216851
  for (const c of t.checks) {
@@ -216799,9 +217052,9 @@ function neverRanNextLine(n2, retry) {
216799
217052
  return `next: ${n2.fix === void 0 ? "fix what its log says" : "make the fix above"}, then ${retry.join(", then ")}`;
216800
217053
  }
216801
217054
  async function writeSummary(run6, summary) {
216802
- await writeFile9(join21(run6.dir, "summary.json"), `${JSON.stringify(summary, null, 2)}
217055
+ await writeFile9(join22(run6.dir, "summary.json"), `${JSON.stringify(summary, null, 2)}
216803
217056
  `);
216804
- await writeFile9(join21(dirname9(run6.dir), "latest"), `${run6.runId}
217057
+ await writeFile9(join22(dirname9(run6.dir), "latest"), `${run6.runId}
216805
217058
  `);
216806
217059
  }
216807
217060
  function formatRateDelta(value5) {
@@ -216976,7 +217229,7 @@ function sinceStart2(ms2) {
216976
217229
  async function withWorldEvidence(s3, runDir, failures) {
216977
217230
  const starts = /* @__PURE__ */ new Map();
216978
217231
  try {
216979
- const inputs2 = JSON.parse(await readFile9(join21(runDir, "inputs.json"), "utf8"));
217232
+ const inputs2 = JSON.parse(await readFile10(join22(runDir, "inputs.json"), "utf8"));
216980
217233
  for (const item2 of inputs2.cases ?? []) {
216981
217234
  const start = Date.parse(item2.scene?.start_time ?? "");
216982
217235
  if (Number.isFinite(start)) starts.set(item2.id, start);
@@ -216989,7 +217242,7 @@ async function withWorldEvidence(s3, runDir, failures) {
216989
217242
  let file3 = files2.get(key4);
216990
217243
  if (file3 === void 0) {
216991
217244
  const dir2 = s3.scenes.find((scene2) => scene2.sceneId === f2.sceneId)?.trialsDetail.find((t) => t.trial === f2.trial)?.dir;
216992
- file3 = dir2 === void 0 ? Promise.resolve([]) : readFile9(join21(runDir, basename6(dir2), "explain.json"), "utf8").then((text29) => {
217245
+ file3 = dir2 === void 0 ? Promise.resolve([]) : readFile10(join22(runDir, basename6(dir2), "explain.json"), "utf8").then((text29) => {
216993
217246
  const value5 = JSON.parse(text29);
216994
217247
  return Array.isArray(value5) ? value5 : [];
216995
217248
  }).catch(() => []);
@@ -217138,19 +217391,19 @@ var init_report2 = __esm({
217138
217391
  });
217139
217392
 
217140
217393
  // backend/src/run-store.ts
217141
- import { readFile as readFile11, stat as stat5 } from "node:fs/promises";
217142
- import { join as join24, resolve as resolve18 } from "node:path";
217394
+ import { readFile as readFile12, stat as stat5 } from "node:fs/promises";
217395
+ import { join as join25, resolve as resolve18 } from "node:path";
217143
217396
  async function latestRunId(cwd, out) {
217144
217397
  if (out !== void 0) return resolveRunId(cwd, "latest", out);
217145
217398
  const dir2 = resolve18(cwd, DEFAULT_RUNS_DIR);
217146
217399
  let local2;
217147
217400
  try {
217148
- const path7 = join24(dir2, "latest");
217149
- local2 = { runId: (await readFile11(path7, "utf8")).trim(), time: (await stat5(path7)).mtimeMs };
217401
+ const path7 = join25(dir2, "latest");
217402
+ local2 = { runId: (await readFile12(path7, "utf8")).trim(), time: (await stat5(path7)).mtimeMs };
217150
217403
  } catch (error65) {
217151
217404
  if (!isEnoent(error65)) throw error65;
217152
217405
  }
217153
- const text29 = await readFile11(join24(dir2, "latest-cloud"), "utf8").catch((error65) => {
217406
+ const text29 = await readFile12(join25(dir2, "latest-cloud"), "utf8").catch((error65) => {
217154
217407
  if (!isEnoent(error65)) throw error65;
217155
217408
  return void 0;
217156
217409
  });
@@ -217169,7 +217422,7 @@ async function resolveRunId(cwd, ref22, out) {
217169
217422
  let runId2 = ref22;
217170
217423
  if (ref22 === "latest") {
217171
217424
  try {
217172
- runId2 = (await readFile11(join24(dir2, "latest"), "utf8")).trim();
217425
+ runId2 = (await readFile12(join25(dir2, "latest"), "utf8")).trim();
217173
217426
  } catch (e) {
217174
217427
  if (isEnoent(e)) throw new AnchaError("USAGE", `no runs found in ${dir2}`, { hint: "run `ancha run` first", cause: e });
217175
217428
  throw e;
@@ -217184,12 +217437,12 @@ async function loadRunSummary(cwd, ref22, out) {
217184
217437
  if (!RUN_ID.test(runId2)) throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint });
217185
217438
  let text29;
217186
217439
  try {
217187
- text29 = await readFile11(join24(dir2, runId2, "summary.json"), "utf8");
217440
+ text29 = await readFile12(join25(dir2, runId2, "summary.json"), "utf8");
217188
217441
  } catch (e) {
217189
217442
  if (!isEnoent(e)) throw e;
217190
- if (await stat5(join24(dir2, runId2)).then((s4) => s4.isDirectory(), () => false)) {
217443
+ if (await stat5(join25(dir2, runId2)).then((s4) => s4.isDirectory(), () => false)) {
217191
217444
  throw new AnchaError("USAGE", `run ${runId2} has no summary.json (it may have been interrupted)`, {
217192
- hint: `its trial directories (agent.log, trace.jsonl, \u2026) are in ${join24(out ?? DEFAULT_RUNS_DIR, runId2)}/; run \`ancha run\` again for a summary`,
217445
+ hint: `its trial directories (agent.log, trace.jsonl, \u2026) are in ${join25(out ?? DEFAULT_RUNS_DIR, runId2)}/; run \`ancha run\` again for a summary`,
217193
217446
  cause: e
217194
217447
  });
217195
217448
  }
@@ -217199,11 +217452,11 @@ async function loadRunSummary(cwd, ref22, out) {
217199
217452
  try {
217200
217453
  summary = JSON.parse(text29);
217201
217454
  } catch (e) {
217202
- throw new AnchaError("INTERNAL", `${join24(dir2, runId2, "summary.json")} is not valid JSON`, { cause: e });
217455
+ throw new AnchaError("INTERNAL", `${join25(dir2, runId2, "summary.json")} is not valid JSON`, { cause: e });
217203
217456
  }
217204
217457
  const s3 = summary;
217205
217458
  if (typeof s3 !== "object" || s3 === null || s3.runId !== runId2 || !Array.isArray(s3.scenes)) {
217206
- throw new AnchaError("INTERNAL", `${join24(dir2, runId2, "summary.json")} is not a run summary`);
217459
+ throw new AnchaError("INTERNAL", `${join25(dir2, runId2, "summary.json")} is not a run summary`);
217207
217460
  }
217208
217461
  return normalizeSummary(s3);
217209
217462
  }
@@ -217221,8 +217474,8 @@ var init_run_store = __esm({
217221
217474
 
217222
217475
  // backend/src/kit/assets.ts
217223
217476
  import { constants as constants8 } from "node:fs";
217224
- import { lstat as lstat4, mkdir as mkdir13, open as open6, readFile as readFile13, realpath as realpath5, rm as rm4 } from "node:fs/promises";
217225
- import { dirname as dirname11, isAbsolute as isAbsolute6, join as join26, relative as relative9, resolve as resolve19, sep as sep4 } from "node:path";
217477
+ import { lstat as lstat4, mkdir as mkdir13, open as open6, readFile as readFile14, realpath as realpath5, rm as rm4 } from "node:fs/promises";
217478
+ import { dirname as dirname11, isAbsolute as isAbsolute6, join as join27, relative as relative9, resolve as resolve19, sep as sep4 } from "node:path";
217226
217479
  import { fileURLToPath as fileURLToPath2 } from "node:url";
217227
217480
  function assetRoot() {
217228
217481
  return new URL("./assets/", import.meta.url);
@@ -217244,7 +217497,7 @@ async function preflightFiles(cwd, files2) {
217244
217497
  if (relative9(root3, target5).startsWith(`..${sep4}`)) throw invalid31(`path escapes project: ${file3.relativePath}`);
217245
217498
  const parts3 = file3.relativePath.split("/");
217246
217499
  for (let i = 1; i <= parts3.length; i++) {
217247
- const part = join26(root3, ...parts3.slice(0, i));
217500
+ const part = join27(root3, ...parts3.slice(0, i));
217248
217501
  try {
217249
217502
  const stat19 = await lstat4(part);
217250
217503
  if (stat19.isSymbolicLink() || (i < parts3.length ? !stat19.isDirectory() : !stat19.isFile())) throw invalid31(`unsafe scaffold target: ${relative9(root3, part)}`);
@@ -217259,7 +217512,7 @@ async function applyScaffold(cwd, files2) {
217259
217512
  const result = { created: [], skipped: [] };
217260
217513
  try {
217261
217514
  for (const file3 of files2) {
217262
- const target5 = join26(cwd, file3.relativePath);
217515
+ const target5 = join27(cwd, file3.relativePath);
217263
217516
  await mkdir13(dirname11(target5), { recursive: true });
217264
217517
  await preflightFiles(cwd, [file3]);
217265
217518
  let handle30;
@@ -217279,7 +217532,7 @@ async function applyScaffold(cwd, files2) {
217279
217532
  }
217280
217533
  return result;
217281
217534
  } catch (error65) {
217282
- await Promise.all(result.created.map((path7) => rm4(join26(cwd, path7), { force: true })));
217535
+ await Promise.all(result.created.map((path7) => rm4(join27(cwd, path7), { force: true })));
217283
217536
  throw error65;
217284
217537
  }
217285
217538
  }
@@ -217288,7 +217541,7 @@ async function templateFiles(template3, suppliedRoot) {
217288
217541
  let manifest2;
217289
217542
  try {
217290
217543
  await preflightFiles(fileURLToPath2(root3), [{ relativePath: "manifest.json", content: "" }]);
217291
- manifest2 = JSON.parse(await readFile13(new URL("manifest.json", root3), "utf8"));
217544
+ manifest2 = JSON.parse(await readFile14(new URL("manifest.json", root3), "utf8"));
217292
217545
  } catch (cause) {
217293
217546
  throw new AnchaError("CONFIG_INVALID", `the ${template3} template pack is unavailable or incomplete`, { hint: "install a distribution containing the pack, or use --template starter", docs: "ancha docs scenes", cause });
217294
217547
  }
@@ -217298,7 +217551,7 @@ async function templateFiles(template3, suppliedRoot) {
217298
217551
  safePath3(name5);
217299
217552
  await preflightFiles(fileURLToPath2(root3), [{ relativePath: name5, content: "" }]);
217300
217553
  try {
217301
- files2.push({ relativePath: name5, content: await readFile13(join26(fileURLToPath2(root3), name5), "utf8") });
217554
+ files2.push({ relativePath: name5, content: await readFile14(join27(fileURLToPath2(root3), name5), "utf8") });
217302
217555
  } catch (cause) {
217303
217556
  throw new AnchaError("CONFIG_INVALID", `template file is missing: ${name5}`, { hint: "install a complete template pack", cause });
217304
217557
  }
@@ -217310,7 +217563,7 @@ async function templateFiles(template3, suppliedRoot) {
217310
217563
  for (const scene2 of scenes) {
217311
217564
  parseScene((0, import_yaml5.parse)(scene2.content));
217312
217565
  for (const companion of ["oracle.ts", "null.ts"]) {
217313
- const sibling = join26(dirname11(scene2.relativePath), companion);
217566
+ const sibling = join27(dirname11(scene2.relativePath), companion);
217314
217567
  if (!paths2.has(sibling)) throw invalid31(`template pack is missing ${sibling}`);
217315
217568
  }
217316
217569
  }
@@ -217342,7 +217595,7 @@ var init_workspace = __esm({
217342
217595
 
217343
217596
  // backend/src/execution/world-image.ts
217344
217597
  import { createHash as createHash62 } from "node:crypto";
217345
- import { readFile as readFile17 } from "node:fs/promises";
217598
+ import { readFile as readFile18 } from "node:fs/promises";
217346
217599
  function worldImageTag(companion, worker = new Uint8Array()) {
217347
217600
  const hash7 = createHash62("sha256");
217348
217601
  for (const part of [WORLD_DOCKERFILE, WORLD_PACKAGE_JSON, companion, worker]) hash7.update(part).update("\0");
@@ -217350,14 +217603,14 @@ function worldImageTag(companion, worker = new Uint8Array()) {
217350
217603
  }
217351
217604
  async function packagedCompanion() {
217352
217605
  try {
217353
- return await readFile17(new URL("harbor/companion.mjs", assetRoot()));
217606
+ return await readFile18(new URL("harbor/companion.mjs", assetRoot()));
217354
217607
  } catch (cause) {
217355
217608
  throw new AnchaError("CONFIG_INVALID", "The packaged world runtime is missing. Rebuild or reinstall Ancha.", { cause });
217356
217609
  }
217357
217610
  }
217358
217611
  async function packagedSuiteqlWorker() {
217359
217612
  try {
217360
- return await readFile17(new URL("harbor/suiteql-worker.mjs", assetRoot()));
217613
+ return await readFile18(new URL("harbor/suiteql-worker.mjs", assetRoot()));
217361
217614
  } catch (cause) {
217362
217615
  throw new AnchaError("CONFIG_INVALID", "The packaged query runtime is missing. Rebuild or reinstall Ancha.", { cause });
217363
217616
  }
@@ -217598,9 +217851,9 @@ __export(harbor_exports, {
217598
217851
  validateHarborBatchSetup: () => validateHarborBatchSetup
217599
217852
  });
217600
217853
  import { execFile as execFile7, spawn as spawn4 } from "node:child_process";
217601
- import { access as access8, chmod as chmod6, mkdir as mkdir16, mkdtemp as mkdtemp5, readFile as readFile18, rm as rm7, writeFile as writeFile14, lstat as lstat7, realpath as realpath9 } from "node:fs/promises";
217854
+ import { access as access8, chmod as chmod6, mkdir as mkdir16, mkdtemp as mkdtemp5, readFile as readFile19, rm as rm7, writeFile as writeFile14, lstat as lstat7, realpath as realpath9 } from "node:fs/promises";
217602
217855
  import { tmpdir as tmpdir4, homedir } from "node:os";
217603
- import { dirname as dirname13, join as join31, basename as basename8 } from "node:path";
217856
+ import { dirname as dirname13, join as join32, basename as basename8 } from "node:path";
217604
217857
  import { fileURLToPath as fileURLToPath4 } from "node:url";
217605
217858
  import { promisify as promisify7 } from "node:util";
217606
217859
  async function exists3(path7) {
@@ -217612,9 +217865,9 @@ async function exists3(path7) {
217612
217865
  }
217613
217866
  }
217614
217867
  async function runtimePaths(workspaceDir = process.cwd()) {
217615
- const candidates = [join31(workspaceDir, ".ancha/harbor-runtime"), join31(workspaceDir, ".ancha/harbor-spike")];
217616
- const python = process.env.ANCHA_HARBOR_PYTHON ?? (await Promise.all(candidates.map(async (root3) => await exists3(join31(root3, ".venv/bin/python")) ? join31(root3, ".venv/bin/python") : void 0))).find(Boolean);
217617
- const dockerConfig = process.env.ANCHA_HARBOR_DOCKER_CONFIG ?? (await Promise.all(candidates.map(async (root3) => await exists3(join31(root3, "docker-config/cli-plugins/docker-compose")) ? join31(root3, "docker-config") : void 0))).find(Boolean) ?? process.env.DOCKER_CONFIG ?? join31(homedir(), ".docker");
217868
+ const candidates = [join32(workspaceDir, ".ancha/harbor-runtime"), join32(workspaceDir, ".ancha/harbor-spike")];
217869
+ const python = process.env.ANCHA_HARBOR_PYTHON ?? (await Promise.all(candidates.map(async (root3) => await exists3(join32(root3, ".venv/bin/python")) ? join32(root3, ".venv/bin/python") : void 0))).find(Boolean);
217870
+ const dockerConfig = process.env.ANCHA_HARBOR_DOCKER_CONFIG ?? (await Promise.all(candidates.map(async (root3) => await exists3(join32(root3, "docker-config/cli-plugins/docker-compose")) ? join32(root3, "docker-config") : void 0))).find(Boolean) ?? process.env.DOCKER_CONFIG ?? join32(homedir(), ".docker");
217618
217871
  return { python, dockerConfig };
217619
217872
  }
217620
217873
  async function checkHarborRuntime(workspaceDir = process.cwd()) {
@@ -217662,10 +217915,10 @@ function validateHarborBatchSetup(agent, resolvedAgent, configuration) {
217662
217915
  async function cleanupHarborBatch(workspaceDir, batchId) {
217663
217916
  if (!/^[A-Za-z0-9_-]{1,120}$/.test(batchId)) throw new AnchaError("CONFIG_INVALID", "Invalid batch identity for cleanup.");
217664
217917
  await preflightFiles(workspaceDir, [{ relativePath: `.ancha/harbor-runtime/controllers/${batchId}.json`, content: "" }]);
217665
- const controller = join31(workspaceDir, ".ancha/harbor-runtime/controllers", batchId + ".json");
217918
+ const controller = join32(workspaceDir, ".ancha/harbor-runtime/controllers", batchId + ".json");
217666
217919
  let marker;
217667
217920
  try {
217668
- marker = JSON.parse(await readFile18(controller, "utf8"));
217921
+ marker = JSON.parse(await readFile19(controller, "utf8"));
217669
217922
  } catch (error65) {
217670
217923
  if (error65.code !== "ENOENT") throw new AnchaError("INTERNAL", "The previous execution controller record could not be read.");
217671
217924
  }
@@ -217766,8 +218019,8 @@ async function executeHarborBatch(input4) {
217766
218019
  await mkdir16(input4.runDir, { recursive: true, mode: 448 });
217767
218020
  await chmod6(input4.runDir, 448);
217768
218021
  const usedResolved = resolvedEntries.filter((entry3) => usedEntries.includes(entry3.entryId));
217769
- await writeFile14(join31(input4.runDir, "execution.json"), JSON.stringify({ backend: "harbor", version: VERSION2, agentImage: usedResolved[0]?.image?.Id, worldImage, fingerprint: usedResolved[0]?.compiled.fingerprint, concurrency: input4.concurrency, entries: usedResolved.map((entry3) => ({ entryId: entry3.entryId, agentImage: entry3.image.Id, fingerprint: entry3.compiled.fingerprint })) }), { mode: 384 });
217770
- const privateDir = await mkdtemp5(join31(tmpdir4(), "ancha-harbor-"));
218022
+ await writeFile14(join32(input4.runDir, "execution.json"), JSON.stringify({ backend: "harbor", version: VERSION2, agentImage: usedResolved[0]?.image?.Id, worldImage, fingerprint: usedResolved[0]?.compiled.fingerprint, concurrency: input4.concurrency, entries: usedResolved.map((entry3) => ({ entryId: entry3.entryId, agentImage: entry3.image.Id, fingerprint: entry3.compiled.fingerprint })) }), { mode: 384 });
218023
+ const privateDir = await mkdtemp5(join32(tmpdir4(), "ancha-harbor-"));
217771
218024
  let peopleBridge, peopleController;
217772
218025
  let runtimeSignal = input4.signal;
217773
218026
  const final = /* @__PURE__ */ new Map();
@@ -217802,21 +218055,21 @@ async function executeHarborBatch(input4) {
217802
218055
  peopleController = peopleBridge ? new PeopleLeaseController(peopleBridge, input4.batchId) : void 0;
217803
218056
  runtimeSignal = peopleController ? AbortSignal.any([peopleController.signal, ...input4.signal ? [input4.signal] : []]) : input4.signal;
217804
218057
  for (const entry3 of resolvedEntries.filter((candidate) => usedEntries.includes(candidate.entryId))) {
217805
- entry3.source = join31(privateDir, "source-" + entry3.entryId);
218058
+ entry3.source = join32(privateDir, "source-" + entry3.entryId);
217806
218059
  const staged = await stageProject(entry3.resolvedAgent.cwd, entry3.policy.files, entry3.source);
217807
218060
  entry3.workspaceBytes = workspaceSizeBytes(staged.bytes, entry3.policy.memoryMb);
217808
218061
  }
217809
- const tasksRoot = join31(privateDir, "tasks");
218062
+ const tasksRoot = join32(privateDir, "tasks");
217810
218063
  await mkdir16(tasksRoot);
217811
218064
  const tasks = [];
217812
218065
  for (const attempt of input4.attempts) {
217813
218066
  const selected2 = attemptEntries.get(attempt.id);
217814
218067
  const entry3 = resolvedEntries.find((candidate) => candidate.entryId === (selected2?.entryId ?? "legacy"));
217815
218068
  const { taskInput, policy, image: image2, compiled: compiled2 } = entry3;
217816
- const path7 = join31(tasksRoot, attempt.id);
217817
- await mkdir16(join31(path7, "environment"), { recursive: true });
217818
- await writeFile14(join31(path7, "instruction.md"), attempt.prompt, { mode: 384 });
217819
- await writeFile14(join31(path7, "task.toml"), `schema_version = "1.3"
218069
+ const path7 = join32(tasksRoot, attempt.id);
218070
+ await mkdir16(join32(path7, "environment"), { recursive: true });
218071
+ await writeFile14(join32(path7, "instruction.md"), attempt.prompt, { mode: 384 });
218072
+ await writeFile14(join32(path7, "task.toml"), `schema_version = "1.3"
217820
218073
  [agent]
217821
218074
  timeout_sec = ${(attempt.timeoutMs + 45e3 + (taskInput.kind === "http" ? taskInput.startupTimeoutMs ?? DEFAULT_HTTP_STARTUP_TIMEOUT_MS : 0)) / 1e3}
217822
218075
  user = "65532"
@@ -217838,21 +218091,21 @@ network_mode = "public"
217838
218091
  if (peopleLease) secrets2.push(peopleLease.token);
217839
218092
  const peopleTools = peopleLease ? peopleLeaseTools(peopleLease) : void 0;
217840
218093
  const compose2 = { services: { main: { entrypoint: [], labels: labels2, networks: ["world"], read_only: true, tmpfs: ["/tmp:size=67108864,mode=1777", `/workspace:size=${workspaceBytes},mode=1777`, "/state:size=134217728,mode=1777", "/home/agent:size=33554432,mode=1777", "/logs:size=16777216,mode=1777", "/installed-agent:size=16777216,mode=1777", "/run:size=16777216,mode=1777"], cap_drop: ["ALL"], security_opt: ["no-new-privileges:true"], pids_limit: policy.pids, stop_grace_period: "1s", depends_on: { tools: { condition: "service_healthy" } } }, tools: { image: worldImage, pull_policy: "never", labels: labels2, command: ["node", "/opt/ancha/companion.mjs"], networks: ["world", ...policy.modelHosts.length ? ["models"] : []], read_only: true, tmpfs: ["/tmp:size=134217728,mode=1777"], ...peopleTools && { volumes: peopleTools.volumes }, environment: { ...worldEnvironment({ configuration: compiled2.configuration, checks: attempt.checks, people: entry3.people }), ANCHA_WORLD_SEED: selected2?.seed ?? input4.seed, ANCHA_MODEL_HOSTS: JSON.stringify(policy.modelHosts), ...peopleTools?.environment }, cap_drop: ["ALL"], security_opt: ["no-new-privileges:true"], pids_limit: 128, mem_limit: "512m", cpus: 0.5, stop_grace_period: "1s", healthcheck: { test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8000/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"], interval: "1s", timeout: "3s", retries: 30 } } }, networks: { world: { internal: true, labels: labels2 }, ...policy.modelHosts.length ? { models: { labels: labels2 } } : {} } };
217841
- await writeFile14(join31(path7, "environment/docker-compose.yaml"), (0, import_yaml7.stringify)(compose2), { mode: 384 });
218094
+ await writeFile14(join32(path7, "environment/docker-compose.yaml"), (0, import_yaml7.stringify)(compose2), { mode: 384 });
217842
218095
  tasks.push({ path: path7 });
217843
218096
  record28({ attemptId: attempt.id, status: "queued", at: (/* @__PURE__ */ new Date()).toISOString() });
217844
218097
  }
217845
218098
  const paths2 = await runtimePaths(input4.workspaceDir);
217846
- const job = { job_name: input4.batchId, jobs_dir: join31(privateDir, "jobs"), quiet: true, n_attempts: 1, n_concurrent_trials: input4.concurrency, environment: { type: "docker", kwargs: { auto_mounting: false } }, agents: [{ name: "ancha_harbor_driver:AnchaAgent" }], tasks, verifier: { disable: true } };
218099
+ const job = { job_name: input4.batchId, jobs_dir: join32(privateDir, "jobs"), quiet: true, n_attempts: 1, n_concurrent_trials: input4.concurrency, environment: { type: "docker", kwargs: { auto_mounting: false } }, agents: [{ name: "ancha_harbor_driver:AnchaAgent" }], tasks, verifier: { disable: true } };
217847
218100
  const data5 = { job, privateDir, ownerPid: process.pid, secrets: secrets2, attempts: Object.fromEntries(input4.attempts.map((a) => [a.id, { ...a, entryId: attemptEntries.get(a.id)?.entryId ?? "legacy" }])), entries: Object.fromEntries(resolvedEntries.filter((entry3) => usedEntries.includes(entry3.entryId)).map((entry3) => [entry3.entryId, { agent: { command: entry3.resolvedAgent.command, input: entry3.taskInput, env: entry3.inheritedValues, mapping: entry3.resolvedAgent.env, path: entry3.image.Config?.Env?.find((v) => v.startsWith("PATH="))?.slice(5) ?? "/usr/local/bin:/usr/bin:/bin" }, configuration: entry3.compiled.configuration, seed: entries4?.length ? entryInputs.find((source) => source.entryId === entry3.entryId).seed : input4.seed, source: entry3.source }])) };
217848
- const inputFile = join31(privateDir, "input.json");
218101
+ const inputFile = join32(privateDir, "input.json");
217849
218102
  await writeFile14(inputFile, JSON.stringify(data5), { mode: 384 });
217850
218103
  const driver = await driverPath();
217851
- await mkdir16(join31(privateDir, "home"));
218104
+ await mkdir16(join32(privateDir, "home"));
217852
218105
  input4.signal?.throwIfAborted();
217853
218106
  if (eventError) throw new AnchaError("INTERNAL", "Execution progress could not be persisted.");
217854
218107
  if (peopleController?.signal.aborted) return await peopleSetupFailed();
217855
- const child2 = spawn4(paths2.python, [driver, inputFile], { cwd: privateDir, env: { PATH: controlledEnv().PATH ?? "/usr/bin:/bin", HOME: join31(privateDir, "home"), PYTHONPATH: dirname13(driver), HARBOR_TELEMETRY: "0", DOCKER_CONFIG: paths2.dockerConfig, DOCKER_HOST: endpoint2 }, stdio: ["ignore", "pipe", "pipe", "pipe"] });
218108
+ const child2 = spawn4(paths2.python, [driver, inputFile], { cwd: privateDir, env: { PATH: controlledEnv().PATH ?? "/usr/bin:/bin", HOME: join32(privateDir, "home"), PYTHONPATH: dirname13(driver), HARBOR_TELEMETRY: "0", DOCKER_CONFIG: paths2.dockerConfig, DOCKER_HOST: endpoint2 }, stdio: ["ignore", "pipe", "pipe", "pipe"] });
217856
218109
  ownedChild = child2;
217857
218110
  const completion = new Promise((resolve55, reject4) => {
217858
218111
  child2.once("error", reject4);
@@ -217862,10 +218115,10 @@ network_mode = "public"
217862
218115
  void completion.catch(() => {
217863
218116
  });
217864
218117
  if (child2.pid) {
217865
- const controllers = join31(input4.workspaceDir, ".ancha/harbor-runtime/controllers");
218118
+ const controllers = join32(input4.workspaceDir, ".ancha/harbor-runtime/controllers");
217866
218119
  await mkdir16(controllers, { recursive: true, mode: 448 });
217867
218120
  await preflightFiles(input4.workspaceDir, [{ relativePath: controllerPath, content: "" }]);
217868
- await writeFile14(join31(input4.workspaceDir, controllerPath), JSON.stringify({ pid: child2.pid, inputFile }), { mode: 384 });
218121
+ await writeFile14(join32(input4.workspaceDir, controllerPath), JSON.stringify({ pid: child2.pid, inputFile }), { mode: 384 });
217869
218122
  }
217870
218123
  let diagnostic = "";
217871
218124
  const redactor2 = redactedLog([...secrets2, ...peopleBridge ? [peopleBridge.token] : []], (text29) => {
@@ -217915,7 +218168,7 @@ network_mode = "public"
217915
218168
  redactor2.end();
217916
218169
  }
217917
218170
  await queued;
217918
- await writeFile14(join31(input4.runDir, "harbor.log"), diagnostic, { mode: 384 });
218171
+ await writeFile14(join32(input4.runDir, "harbor.log"), diagnostic, { mode: 384 });
217919
218172
  if (eventError) throw new AnchaError("INTERNAL", "Execution progress could not be persisted.");
217920
218173
  for (const attempt of input4.attempts) if (!final.has(attempt.id)) record28({ attemptId: attempt.id, status: input4.signal?.aborted ? "stopped" : "error", at: (/* @__PURE__ */ new Date()).toISOString(), finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: input4.signal?.aborted ? "Stopped by user." : code5 === 0 ? "No final result was returned." : "Execution could not start or finish. See the runtime diagnostic." });
217921
218174
  await queued;
@@ -220194,8 +220447,8 @@ var init_production_state = __esm({
220194
220447
 
220195
220448
  // backend/src/production.ts
220196
220449
  import { createHash as createHash64 } from "node:crypto";
220197
- import { readFile as readFile20, writeFile as writeFile15 } from "node:fs/promises";
220198
- import { dirname as dirname14, join as join34 } from "node:path";
220450
+ import { readFile as readFile21, writeFile as writeFile15 } from "node:fs/promises";
220451
+ import { dirname as dirname14, join as join35 } from "node:path";
220199
220452
  function productionLines(made) {
220200
220453
  const records4 = [...(made.native ?? []).map((entry3) => ({ kind: "api", entry: entry3 })), ...made.calls.map((c) => ({ kind: "tool", ...c }))];
220201
220454
  const at4 = (line2) => line2.kind === "api" ? Date.parse(line2.entry.tSim) : Date.parse(made.startedAt ?? "") + parseDuration(line2.at ?? "0ms");
@@ -220228,16 +220481,16 @@ function productionTrace(lines2) {
220228
220481
  return entries4;
220229
220482
  }
220230
220483
  async function productionRecord(dir2) {
220231
- const text29 = await readFile20(join34(dir2, "production.jsonl"), "utf8").catch(() => void 0);
220484
+ const text29 = await readFile21(join35(dir2, "production.jsonl"), "utf8").catch(() => void 0);
220232
220485
  return text29 === void 0 ? void 0 : productionTrace(text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2)));
220233
220486
  }
220234
220487
  async function completeProduction(scenePath, scene2, judge, into) {
220235
220488
  const dir2 = dirname14(scenePath);
220236
- const text29 = await readFile20(join34(dir2, "production.jsonl"), "utf8").catch(() => void 0);
220489
+ const text29 = await readFile21(join35(dir2, "production.jsonl"), "utf8").catch(() => void 0);
220237
220490
  if (text29 === void 0) return [];
220238
220491
  const lines2 = text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
220239
- const file3 = into ?? join34(dir2, "production.json");
220240
- const known2 = await readFile20(file3, "utf8").then((t) => JSON.parse(t), () => ({}));
220492
+ const file3 = into ?? join35(dir2, "production.json");
220493
+ const known2 = await readFile21(file3, "utf8").then((t) => JSON.parse(t), () => ({}));
220241
220494
  const checks2 = { ...known2.checks }, signatures = { ...known2.signatures };
220242
220495
  const sign3 = productionSignature;
220243
220496
  const missing8 = scene2.checks.filter((check4) => checks2[check4.id] === void 0 || checks2[check4.id] === "unknown" || signatures[check4.id] !== void 0 && signatures[check4.id] !== sign3(check4));
@@ -220288,15 +220541,15 @@ var init_production = __esm({
220288
220541
  });
220289
220542
 
220290
220543
  // backend/src/production-comparison.ts
220291
- import { readFile as readFile21 } from "node:fs/promises";
220292
- import { dirname as dirname15, join as join35, resolve as resolve24 } from "node:path";
220544
+ import { readFile as readFile22 } from "node:fs/promises";
220545
+ import { dirname as dirname15, join as join36, resolve as resolve24 } from "node:path";
220293
220546
  async function reproductionOf(summary, scenePaths, cwd, runDir, scenes = [], productionFiles = {}) {
220294
220547
  const out = [];
220295
220548
  for (const scene2 of summary.scenes) {
220296
220549
  const path7 = scenePaths[scene2.sceneId];
220297
220550
  if (path7 === void 0) continue;
220298
- const file3 = Object.hasOwn(productionFiles, scene2.sceneId) ? productionFiles[scene2.sceneId] : join35(dirname15(resolve24(cwd, path7)), "production.json");
220299
- const production3 = await readFile21(file3, "utf8").then((text29) => JSON.parse(text29), () => void 0);
220551
+ const file3 = Object.hasOwn(productionFiles, scene2.sceneId) ? productionFiles[scene2.sceneId] : join36(dirname15(resolve24(cwd, path7)), "production.json");
220552
+ const production3 = await readFile22(file3, "utf8").then((text29) => JSON.parse(text29), () => void 0);
220300
220553
  if (production3?.checks === void 0) continue;
220301
220554
  const checks2 = Object.entries(production3.checks).flatMap(([check4, result]) => {
220302
220555
  const here = scene2.checks[check4];
@@ -220321,7 +220574,7 @@ async function reproductionOf(summary, scenePaths, cwd, runDir, scenes = [], pro
220321
220574
  async function answerSources(runDir, scene2) {
220322
220575
  const counts = {};
220323
220576
  for (const { trial } of scene2.trialsDetail) {
220324
- const text29 = await readFile21(join35(runDir, `trial-${scene2.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
220577
+ const text29 = await readFile22(join36(runDir, `trial-${scene2.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
220325
220578
  for (const entry3 of text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2))) {
220326
220579
  const source = entry3.service === "tools" && entry3.path?.startsWith("/tools/") ? entry3.response?.source : void 0;
220327
220580
  if (source) counts[source] = (counts[source] ?? 0) + 1;
@@ -220336,7 +220589,7 @@ async function writesOf(scene2, dir2, runDir, ran) {
220336
220589
  for (const action of actionsOf(scene2, record28)) made.set(action.tool, (made.get(action.tool) ?? 0) + 1);
220337
220590
  const trials = (ran.trialsDetail ?? []).filter((t) => t.valid !== false);
220338
220591
  for (const { trial } of trials) {
220339
- const text29 = await readFile21(join35(runDir, `trial-${ran.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
220592
+ const text29 = await readFile22(join36(runDir, `trial-${ran.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
220340
220593
  const trace = text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
220341
220594
  for (const tool of new Set(actionsOf(scene2, trace).map((action) => action.tool))) here.set(tool, (here.get(tool) ?? 0) + 1);
220342
220595
  }
@@ -220354,8 +220607,8 @@ var init_production_comparison = __esm({
220354
220607
 
220355
220608
  // backend/src/baselines.ts
220356
220609
  import { randomUUID as randomUUID13 } from "node:crypto";
220357
- import { link as link7, mkdir as mkdir17, readFile as readFile22, rename as rename6, unlink, writeFile as writeFile16 } from "node:fs/promises";
220358
- import { dirname as dirname16, join as join36, resolve as resolve25 } from "node:path";
220610
+ import { link as link7, mkdir as mkdir17, readFile as readFile23, rename as rename6, unlink, writeFile as writeFile16 } from "node:fs/promises";
220611
+ import { dirname as dirname16, join as join37, resolve as resolve25 } from "node:path";
220359
220612
  function validateTrialCounts(scene2) {
220360
220613
  if (!Number.isSafeInteger(scene2.passed) || !Number.isSafeInteger(scene2.trials) || scene2.trials <= 0 || scene2.passed < 0 || scene2.passed > scene2.trials) {
220361
220614
  throw new AnchaError("USAGE", `invalid passed/trial counts for test ${scene2.sceneId}`);
@@ -220438,9 +220691,9 @@ function validateName(name5) {
220438
220691
  async function saveBaseline(cwd, name5, opts = {}, load6) {
220439
220692
  validateName(name5);
220440
220693
  const summary = load6 ? await load6() : await loadRunSummary(cwd, opts.from ?? "latest", opts.out);
220441
- const dir2 = baselineDir(cwd, opts.out), path7 = join36(dir2, `${name5}.json`);
220694
+ const dir2 = baselineDir(cwd, opts.out), path7 = join37(dir2, `${name5}.json`);
220442
220695
  await mkdir17(dir2, { recursive: true });
220443
- const temporary = join36(dir2, `.${name5}-${randomUUID13()}.tmp`);
220696
+ const temporary = join37(dir2, `.${name5}-${randomUUID13()}.tmp`);
220444
220697
  try {
220445
220698
  await writeFile16(temporary, `${JSON.stringify(summary, null, 2)}
220446
220699
  `, { flag: "wx", mode: 384 });
@@ -220458,10 +220711,10 @@ async function saveBaseline(cwd, name5, opts = {}, load6) {
220458
220711
  }
220459
220712
  async function loadComparisonSummary(cwd, ref22, out) {
220460
220713
  if (BASELINE_NAME.test(ref22) && ref22 !== "latest" && !ref22.startsWith("run_")) {
220461
- const path7 = join36(baselineDir(cwd, out), `${ref22}.json`);
220714
+ const path7 = join37(baselineDir(cwd, out), `${ref22}.json`);
220462
220715
  let text29;
220463
220716
  try {
220464
- text29 = await readFile22(path7, "utf8");
220717
+ text29 = await readFile23(path7, "utf8");
220465
220718
  } catch (error65) {
220466
220719
  if (error65.code !== "ENOENT") throw error65;
220467
220720
  }
@@ -220488,7 +220741,7 @@ var init_baselines = __esm({
220488
220741
  init_actions7();
220489
220742
  init_scenes();
220490
220743
  BASELINE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
220491
- baselineDir = (cwd, out) => join36(dirname16(resolve25(cwd, out ?? DEFAULT_RUNS_DIR)), "baselines");
220744
+ baselineDir = (cwd, out) => join37(dirname16(resolve25(cwd, out ?? DEFAULT_RUNS_DIR)), "baselines");
220492
220745
  }
220493
220746
  });
220494
220747
 
@@ -220499,11 +220752,11 @@ __export(dependency_plan_exports, {
220499
220752
  });
220500
220753
  import { constants as constants9 } from "node:fs";
220501
220754
  import { open as open7 } from "node:fs/promises";
220502
- import { join as join38, resolve as resolve28 } from "node:path";
220755
+ import { join as join39, resolve as resolve28 } from "node:path";
220503
220756
  async function manifest(root3, name5) {
220504
220757
  let file3;
220505
220758
  try {
220506
- file3 = await open7(join38(root3, name5), constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
220759
+ file3 = await open7(join39(root3, name5), constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
220507
220760
  const stat19 = await file3.stat();
220508
220761
  if (!stat19.isFile() || stat19.size > 32 * 1024 * 1024) throw new Error();
220509
220762
  return await file3.readFile("utf8");
@@ -220515,7 +220768,7 @@ async function manifest(root3, name5) {
220515
220768
  }
220516
220769
  }
220517
220770
  async function dependencyPlan(root3, options4 = {}) {
220518
- const pathPrepend = [join38(resolve28(root3), ".venv/bin"), join38(resolve28(root3), "node_modules/.bin")];
220771
+ const pathPrepend = [join39(resolve28(root3), ".venv/bin"), join39(resolve28(root3), "node_modules/.bin")];
220519
220772
  if (options4.install !== void 0) {
220520
220773
  if (typeof options4.install !== "string" || !options4.install.trim() || options4.install.length > 2e3 || /[\0\r\n]/.test(options4.install)) {
220521
220774
  throw new AnchaError("CONFIG_INVALID", "agent.install must be a non-empty single-line command of at most 2000 characters.");
@@ -220564,8 +220817,8 @@ var init_dependency_plan = __esm({
220564
220817
  });
220565
220818
 
220566
220819
  // backend/src/kit/detect.ts
220567
- import { readFile as readFile23 } from "node:fs/promises";
220568
- import { join as join39 } from "node:path";
220820
+ import { readFile as readFile24 } from "node:fs/promises";
220821
+ import { join as join40 } from "node:path";
220569
220822
  function dockerfileCommand(body7) {
220570
220823
  const lines2 = body7.split(/\r?\n/).filter((line2) => /^\s*CMD\s/i.test(line2));
220571
220824
  const last = lines2.at(-1)?.replace(/^\s*CMD\s+/i, "").trim();
@@ -220607,7 +220860,7 @@ async function detectProject(cwd, agent) {
220607
220860
  for (const name5 of ["package.json", "pyproject.toml", "requirements.txt", "Pipfile"]) {
220608
220861
  let body7;
220609
220862
  try {
220610
- body7 = await readFile23(join39(cwd, name5), "utf8");
220863
+ body7 = await readFile24(join40(cwd, name5), "utf8");
220611
220864
  } catch (error65) {
220612
220865
  if (error65.code === "ENOENT") continue;
220613
220866
  throw error65;
@@ -220627,7 +220880,7 @@ async function detectProject(cwd, agent) {
220627
220880
  }
220628
220881
  }
220629
220882
  if (node5 && python) evidence2.push("mixed Node/Python manifests; choose connect --lang explicitly");
220630
- const read7 = (name5) => readFile23(join39(cwd, name5), "utf8").catch((error65) => {
220883
+ const read7 = (name5) => readFile24(join40(cwd, name5), "utf8").catch((error65) => {
220631
220884
  if (error65.code === "ENOENT" || error65.code === "EISDIR") return void 0;
220632
220885
  throw error65;
220633
220886
  });
@@ -220681,7 +220934,7 @@ var init_detect = __esm({
220681
220934
 
220682
220935
  // backend/src/kit/task-input.ts
220683
220936
  import { open as open8, stat as stat8 } from "node:fs/promises";
220684
- import { basename as basename11, dirname as dirname17, extname, isAbsolute as isAbsolute8, join as join40, relative as relative11, resolve as resolve29, sep as sep5 } from "node:path";
220937
+ import { basename as basename11, dirname as dirname17, extname, isAbsolute as isAbsolute8, join as join41, relative as relative11, resolve as resolve29, sep as sep5 } from "node:path";
220685
220938
  function taskVariable(name5) {
220686
220939
  if (!/^[A-Z][A-Z0-9_]*$/.test(name5) || name5.startsWith("ANCHA_")) return null;
220687
220940
  const parts3 = name5.split("_").filter(Boolean);
@@ -220778,7 +221031,7 @@ function taskInputsInText(text29) {
220778
221031
  }
220779
221032
  return rank(found);
220780
221033
  }
220781
- function words5(command) {
221034
+ function words6(command) {
220782
221035
  const commands = [[]];
220783
221036
  let word2 = "", quote6 = "", started = false;
220784
221037
  const end = () => {
@@ -220843,7 +221096,7 @@ function project12(root3) {
220843
221096
  }
220844
221097
  async function packageScript(p2, cwd, name5) {
220845
221098
  try {
220846
- const value5 = JSON.parse(await p2.read(join40(cwd, "package.json")) ?? "{}").scripts?.[name5];
221099
+ const value5 = JSON.parse(await p2.read(join41(cwd, "package.json")) ?? "{}").scripts?.[name5];
220847
221100
  return typeof value5 === "string" ? value5 : void 0;
220848
221101
  } catch {
220849
221102
  return void 0;
@@ -220851,16 +221104,16 @@ async function packageScript(p2, cwd, name5) {
220851
221104
  }
220852
221105
  async function packageBin(p2, cwd, name5) {
220853
221106
  try {
220854
- const manifest2 = JSON.parse(await p2.read(join40(cwd, "package.json")) ?? "{}");
220855
- if (typeof manifest2.bin === "string") return manifest2.name === name5 || String(manifest2.name).split("/").at(-1) === name5 ? join40(cwd, manifest2.bin) : void 0;
221107
+ const manifest2 = JSON.parse(await p2.read(join41(cwd, "package.json")) ?? "{}");
221108
+ if (typeof manifest2.bin === "string") return manifest2.name === name5 || String(manifest2.name).split("/").at(-1) === name5 ? join41(cwd, manifest2.bin) : void 0;
220856
221109
  const value5 = manifest2.bin?.[name5];
220857
- return typeof value5 === "string" ? join40(cwd, value5) : void 0;
221110
+ return typeof value5 === "string" ? join41(cwd, value5) : void 0;
220858
221111
  } catch {
220859
221112
  return void 0;
220860
221113
  }
220861
221114
  }
220862
221115
  async function pyprojectScript(p2, cwd, name5) {
220863
- const body7 = await p2.read(join40(cwd, "pyproject.toml"));
221116
+ const body7 = await p2.read(join41(cwd, "pyproject.toml"));
220864
221117
  const section2 = body7 === void 0 ? void 0 : /^\[(?:project\.scripts|tool\.poetry\.scripts)\]\s*\n((?:[^[\n].*\n?)*)/m.exec(body7)?.[1];
220865
221118
  const target5 = section2?.split("\n").map((line2) => /^\s*["']?([\w.-]+)["']?\s*=\s*["']([\w.]+)(?::\w+)?["']/.exec(line2)).find((match3) => match3?.[1] === name5)?.[2];
220866
221119
  return target5 === void 0 ? [] : pythonModule(cwd, target5);
@@ -220869,12 +221122,12 @@ async function entries3(p2, command, cwd = ".", depth = 0) {
220869
221122
  if (depth > 3) return [];
220870
221123
  const out = [];
220871
221124
  let dir2 = cwd;
220872
- for (let list18 of words5(command)) {
221125
+ for (let list18 of words6(command)) {
220873
221126
  while (list18.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(list18[0])) list18 = list18.slice(1);
220874
221127
  if (!list18.length) continue;
220875
221128
  const program2 = basename11(list18[0]), rest2 = list18.slice(1);
220876
221129
  if (program2 === "cd" && rest2[0] !== void 0) {
220877
- dir2 = join40(dir2, rest2[0]);
221130
+ dir2 = join41(dir2, rest2[0]);
220878
221131
  continue;
220879
221132
  }
220880
221133
  if (["uv", "poetry", "pipenv", "pdm", "rye", "hatch"].includes(program2) && rest2[0] === "run") {
@@ -220904,7 +221157,7 @@ async function entries3(p2, command, cwd = ".", depth = 0) {
220904
221157
  out.push(...await scriptEntry(p2, dir2, (program2 === "deno" || program2 === "bun") && rest2[0] === "run" ? rest2.slice(1) : rest2, false));
220905
221158
  continue;
220906
221159
  }
220907
- const path7 = join40(dir2, list18[0]);
221160
+ const path7 = join41(dir2, list18[0]);
220908
221161
  if (/[/.]/.test(list18[0]) && await p2.exists(path7)) {
220909
221162
  const text29 = await p2.read(path7) ?? "";
220910
221163
  const shebang = /^#!(.*)/.exec(text29)?.[1] ?? "";
@@ -220938,10 +221191,10 @@ async function scriptEntry(p2, dir2, args, python) {
220938
221191
  }
220939
221192
  const entry3 = args[i];
220940
221193
  if (entry3 === void 0 || /^[a-z][a-z\d+.-]*:/i.test(entry3)) return [];
220941
- const path7 = join40(dir2, entry3);
221194
+ const path7 = join41(dir2, entry3);
220942
221195
  if (await p2.exists(path7)) return [path7];
220943
221196
  const built3 = /^(?:\.\/)?(?:dist|build|out|lib)\/(.+)\.(?:c|m)?js$/.exec(entry3)?.[1];
220944
- return built3 === void 0 ? [path7] : [path7, ...[".ts", ".mts", ".tsx"].map((ext) => join40(dir2, "src", `${built3}${ext}`))];
221197
+ return built3 === void 0 ? [path7] : [path7, ...[".ts", ".mts", ".tsx"].map((ext) => join41(dir2, "src", `${built3}${ext}`))];
220945
221198
  }
220946
221199
  async function fallbackEntries(p2) {
220947
221200
  let main2;
@@ -220962,8 +221215,8 @@ async function imports(p2, file3, text29) {
220962
221215
  };
220963
221216
  if (extname(file3) === ".py") {
220964
221217
  const tryModule = async (base3, module) => {
220965
- const path7 = module ? join40(base3, ...module.split(".")) : base3;
220966
- for (const candidate of [`${path7}.py`, join40(path7, "__init__.py")]) if (keep2(candidate) && await p2.exists(candidate)) {
221218
+ const path7 = module ? join41(base3, ...module.split(".")) : base3;
221219
+ for (const candidate of [`${path7}.py`, join41(path7, "__init__.py")]) if (keep2(candidate) && await p2.exists(candidate)) {
220967
221220
  out.push(candidate);
220968
221221
  return true;
220969
221222
  }
@@ -220971,7 +221224,7 @@ async function imports(p2, file3, text29) {
220971
221224
  };
220972
221225
  for (const match3 of text29.matchAll(/^[ \t]*from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+(?:\(([^)]*)\)|([\w \t,*]+))/gm)) {
220973
221226
  const dots = match3[1].length, module = match3[2];
220974
- const bases2 = dots > 0 ? [join40(from, ...Array(dots - 1).fill(".."))] : [from, ".", "src"];
221227
+ const bases2 = dots > 0 ? [join41(from, ...Array(dots - 1).fill(".."))] : [from, ".", "src"];
220975
221228
  for (const base3 of bases2) {
220976
221229
  const found = await tryModule(base3, module);
220977
221230
  for (const name5 of (match3[3] ?? match3[4]).split(",").map((word2) => word2.trim().split(/\s+/)[0]).filter((word2) => /^\w+$/.test(word2))) await tryModule(base3, module ? `${module}.${name5}` : name5);
@@ -220984,8 +221237,8 @@ async function imports(p2, file3, text29) {
220984
221237
  return out;
220985
221238
  }
220986
221239
  for (const match3 of text29.matchAll(/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)(['"])(\.{1,2}\/[^'"\n]+)\1/g)) {
220987
- const base3 = join40(from, match3[2]);
220988
- const candidates = [base3, ...SOURCE_EXT.map((ext) => `${base3}${ext}`), ...SOURCE_EXT.map((ext) => join40(base3, `index${ext}`))];
221240
+ const base3 = join41(from, match3[2]);
221241
+ const candidates = [base3, ...SOURCE_EXT.map((ext) => `${base3}${ext}`), ...SOURCE_EXT.map((ext) => join41(base3, `index${ext}`))];
220989
221242
  const js = /\.(c|m)?js$/.exec(base3);
220990
221243
  if (js) candidates.push(...[".ts", ".tsx", ".mts", ".cts"].map((ext) => base3.slice(0, -js[0].length) + ext));
220991
221244
  for (const candidate of candidates) if (keep2(candidate) && await p2.exists(candidate)) {
@@ -221182,7 +221435,7 @@ var init_task_input = __esm({
221182
221435
  };
221183
221436
  pythonModule = (cwd, module) => {
221184
221437
  const path7 = module.split(".").join("/");
221185
- return [`${path7}.py`, `${path7}/__main__.py`, `${path7}/__init__.py`, `src/${path7}.py`, `src/${path7}/__main__.py`, `src/${path7}/__init__.py`].map((file3) => join40(cwd, file3));
221438
+ return [`${path7}.py`, `${path7}/__main__.py`, `${path7}/__init__.py`, `src/${path7}.py`, `src/${path7}/__main__.py`, `src/${path7}/__init__.py`].map((file3) => join41(cwd, file3));
221186
221439
  };
221187
221440
  NODE_VALUE_FLAGS = /* @__PURE__ */ new Set(["--require", "-r", "--import", "--loader", "--experimental-loader", "--tsconfig", "--config", "-c", "--env-file", "--conditions", "-C", "--title", "--inspect-port"]);
221188
221441
  PYTHON_VALUE_FLAGS = /* @__PURE__ */ new Set(["-W", "-X", "-Q"]);
@@ -221230,145 +221483,6 @@ var init_agent_tools3 = __esm({
221230
221483
  }
221231
221484
  });
221232
221485
 
221233
- // backend/src/agent-outcome.ts
221234
- function answerOf(entry3) {
221235
- const request2 = entry3.request ?? {};
221236
- const text29 = typeof request2.output === "string" ? request2.output : JSON.stringify(request2.output) ?? "";
221237
- return { source: request2.source === "reply" || request2.source === "stdout" ? request2.source : "done", text: text29 };
221238
- }
221239
- function kindOf2(path7) {
221240
- if (/^\/app\/site\/hosting\/restlet\.nl/i.test(path7)) return "restlet";
221241
- if (/^\/services\/NetSuitePort/i.test(path7)) return "soap";
221242
- if (path7.startsWith("/services/rest/query/v1/suiteql")) return "suiteql";
221243
- if (path7.startsWith("/services/rest/record/") || path7.startsWith("/services/rest/async/")) return "record";
221244
- if (path7.startsWith("/services/mcp/")) return "mcp";
221245
- if (path7.startsWith("/services/rest/auth/")) return "auth";
221246
- return "other";
221247
- }
221248
- function netsuiteStarterCustomers() {
221249
- const seed43 = toolStarterSeed("netsuite");
221250
- customers2 ??= (seed43.customers ?? []).map((c) => c.companyName ?? [c.firstName, c.lastName].filter(Boolean).join(" ")).filter((name5) => name5 !== "");
221251
- return customers2;
221252
- }
221253
- function namesStarterCustomer(answer) {
221254
- const said = words6(answer);
221255
- return netsuiteStarterCustomers().some((name5) => {
221256
- const whole2 = words6(name5), first = whole2.trim().split(" ")[0];
221257
- return said.includes(whole2) || first.length >= 5 && said.includes(` ${first} `);
221258
- });
221259
- }
221260
- function modelKeyName(host, given2) {
221261
- const [pattern, usual2] = PROVIDER_KEYS[host] ?? [/(?!)/, "NAME"];
221262
- return given2.find((name5) => pattern.test(name5) && /KEY|TOKEN/.test(name5)) ?? usual2;
221263
- }
221264
- function refusal3(entry3) {
221265
- const details = entry3.response?.["o:errorDetails"];
221266
- const code5 = Array.isArray(details) ? details[0]?.["o:errorCode"] : void 0;
221267
- return typeof code5 === "string" ? `${entry3.status} ${code5}` : String(entry3.status);
221268
- }
221269
- function unservedReason(unserved) {
221270
- const first = unserved[0], kind2 = kindOf2(first.path), call4 = `${first.method} ${first.path}${unserved.length > 1 ? ` ${times(unserved.length)}` : ""}`;
221271
- const what = kind2 === "restlet" ? "a RESTlet (your own SuiteScript)" : kind2 === "soap" ? "SuiteTalk SOAP web services" : "which Ancha's NetSuite does not serve";
221272
- return { message: `It called ${call4}, ${what}.`, fix: SERVED };
221273
- }
221274
- function answeredNetsuite(calls2, answer) {
221275
- const parts3 = [["suiteql", "SuiteQL"], ["record", "REST records"], ["mcp", "the MCP tools"]].map(([kind2, label5]) => [label5, calls2.filter((entry3) => kindOf2(entry3.path) === kind2).length]).filter(([, n2]) => n2 > 0).map(([label5, n2]) => `${label5} ${times(n2)}`);
221276
- return `NetSuite: it ${parts3.length > 0 ? `called ${list17(parts3)} and ` : ""}answered ${quoted3(answer)}.`;
221277
- }
221278
- function endedSentence(view3) {
221279
- if (view3.exit === "spawn_failed") return "The agent could not be started.";
221280
- return view3.exitCode === null ? `The agent stopped on a signal after ${view3.realMs} ms.` : `The agent exited with code ${view3.exitCode} after ${view3.realMs} ms.`;
221281
- }
221282
- function attemptOutcome(view3, ctx) {
221283
- const calls2 = view3.trace.filter((entry3) => entry3.source === "agent" && !isAgentAnswer(entry3));
221284
- const netsuite = calls2.filter((entry3) => entry3.service === "netsuite");
221285
- const unserved = netsuite.filter((entry3) => entry3.gap === true || kindOf2(entry3.path) === "restlet" || kindOf2(entry3.path) === "soap");
221286
- const used = netsuite.filter((entry3) => !unserved.includes(entry3)), data5 = used.filter((entry3) => kindOf2(entry3.path) !== "auth");
221287
- const served = used.filter((entry3) => entry3.status !== void 0 && entry3.status < 400);
221288
- const hosts = netsuiteHosts(view3.log);
221289
- const done = view3.trace.findLast(isAgentAnswer), answer = done === void 0 ? void 0 : answerOf(done);
221290
- const byStatus = {};
221291
- for (const entry3 of calls2) if (entry3.status !== void 0) byStatus[String(entry3.status)] = (byStatus[String(entry3.status)] ?? 0) + 1;
221292
- const gaps2 = [...new Set(calls2.filter((entry3) => entry3.gap === true || unserved.includes(entry3)).map((entry3) => `${entry3.method} ${entry3.path}`))];
221293
- const summary = { total: calls2.length, byStatus, gaps: gaps2.slice(0, 5), hosts: hosts.slice(0, 5) };
221294
- const out = (reason2) => ({ reason: reason2, calls: summary, ...answer !== void 0 && { answer: { source: answer.source, text: answer.text.slice(0, 200) } } });
221295
- if (answer !== void 0 && (ctx.check === "start" || ctx.check === "netsuite" && namesStarterCustomer(answer.text))) {
221296
- if (unserved.length > 0) return out({ code: "unserved", level: "warning", ...unservedReason(unserved) });
221297
- return out({ code: "answered", level: "pass", message: ctx.check === "netsuite" ? answeredNetsuite(netsuite, answer.text) : `It took the task and answered ${quoted3(answer.text)}.` });
221298
- }
221299
- const model2 = view3.modelReplies?.find((reply5) => reply5.status === 401 || reply5.status === 403);
221300
- if (model2 !== void 0) return out({ code: "model_key", level: "fail", message: `The model key was refused: ${model2.host} answered ${model2.status}.`, fix: `ancha secrets set ${modelKeyName(model2.host, ctx.given ?? [])}` });
221301
- const refused2 = (entry3) => entry3.status === 401 || entry3.status === 403;
221302
- const turnedDown = used.length > 0 && used.every(refused2) ? used : data5.length > 0 && data5.every(refused2) ? data5 : [];
221303
- if (turnedDown.length > 0) {
221304
- const n2 = turnedDown.length;
221305
- return out({ code: "refused", level: "fail", message: `NetSuite refused ${n2 === 1 ? "its one call" : `all ${n2} calls`} (${list17([...new Set(turnedDown.map(refusal3))])}).`, fix: SIGN });
221306
- }
221307
- if (hosts.length > 0 && served.length === 0) return out({ code: "outside_host", level: "fail", message: `It tried to reach ${list17(hosts.slice(0, 3))}.`, fix: OUTSIDE });
221308
- if (unserved.length > 0 && data5.length === 0) return out({ code: "unserved", level: "fail", ...unservedReason(unserved) });
221309
- const crashed = view3.exit === "spawn_failed" || view3.exit === "exited" && view3.exitCode !== 0;
221310
- const did = calls2.length > 0 || ctx.taskMark !== void 0 && view3.log.includes(ctx.taskMark);
221311
- if (crashed && (ctx.check !== "start" || !did)) {
221312
- const tail = view3.logTail?.length ? view3.logTail : view3.log.trimEnd().split("\n").slice(-10);
221313
- const fix = ctx.taskFix ?? likelyFix(tail, { target: ctx.target ?? "cloud", ...ctx.command !== void 0 && { command: ctx.command } });
221314
- const key4 = ctx.taskFix === void 0 ? missingKey(tail) : void 0;
221315
- return out({ code: key4 !== void 0 && fix?.includes(key4) ? "missing_secret" : "crashed", level: "fail", message: endedSentence(view3), ...fix !== void 0 && { fix } });
221316
- }
221317
- if (view3.exit === "timeout" && view3.log.trim() === "" && calls2.length === 0 && !view3.modelReplies?.length && answer === void 0) {
221318
- const fix = ctx.stdin ? `it reads its task from stdin (${ctx.stdin.source}:${ctx.stdin.line}): in ancha.yaml under agent:, set input: stdin` : "if it waits for input, hand it the task: it is in ANCHA_TASK and ANCHA_TASK_FILE, or on its stdin with agent.input: stdin in ancha.yaml";
221319
- return out({ code: "idle", level: "fail", message: `It ran ${Math.round(view3.realMs / 1e3)} s without output, a model call, a tool call or an answer.`, fix });
221320
- }
221321
- const level3 = ctx.answerChecked ? "fail" : "warning";
221322
- const called = netsuite.length > 0 ? `It called NetSuite ${times(netsuite.length)}` : ctx.check === "netsuite" ? "It made no NetSuite call" : "It";
221323
- if (answer === void 0) return out({ code: "no_answer", level: level3, message: `${called}${called === "It" ? "" : netsuite.length > 0 ? " but" : " and"} ${NO_ANSWER}`, fix: POST_ANSWER });
221324
- if (ctx.check === "netsuite") {
221325
- const names5 = netsuiteStarterCustomers();
221326
- return out({
221327
- code: "wrong_answer",
221328
- level: level3,
221329
- message: `${called} and answered ${quoted3(answer.text)}, which names none of its NetSuite customers (${list17([...names5.slice(0, 2), ...names5.length > 2 ? [`${names5.length - 2} more`] : []])}).`,
221330
- fix: "the check asks it to find one customer in NetSuite and reply with the name; its answer is what it posts to ANCHA_DONE_URL or prints last on stdout"
221331
- });
221332
- }
221333
- return out({ code: "answered", level: "pass", message: `It answered ${quoted3(answer.text)}.` });
221334
- }
221335
- var oneLine4, quoted3, times, list17, NETSUITE_HOST, netsuiteHosts, customers2, words6, PROVIDER_KEYS, SIGN, OUTSIDE, SERVED, NO_ANSWER, POST_ANSWER;
221336
- var init_agent_outcome = __esm({
221337
- "backend/src/agent-outcome.ts"() {
221338
- "use strict";
221339
- init_src();
221340
- init_agent_fix();
221341
- oneLine4 = (text29) => text29.replace(/\s+/g, " ").trim();
221342
- quoted3 = (text29) => {
221343
- const line2 = oneLine4(text29);
221344
- return `"${line2.length > 80 ? `${line2.slice(0, 79)}\u2026` : line2}"`;
221345
- };
221346
- times = (n2) => n2 === 1 ? "once" : `${n2} times`;
221347
- list17 = (items2) => items2.length <= 1 ? items2.join("") : `${items2.slice(0, -1).join(", ")} and ${items2.at(-1)}`;
221348
- NETSUITE_HOST = /\b[a-z0-9-]+\.(?:suitetalk|restlets)\.api\.netsuite\.com\b|\b[a-z0-9-]+\.app\.netsuite\.com\b/gi;
221349
- netsuiteHosts = (log3) => [...new Set([...log3.matchAll(NETSUITE_HOST)].map((match3) => match3[0].toLowerCase()))];
221350
- words6 = (text29) => ` ${text29.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
221351
- PROVIDER_KEYS = {
221352
- "api.anthropic.com": [/ANTHROPIC|CLAUDE/, "ANTHROPIC_API_KEY"],
221353
- "api.openai.com": [/OPENAI/, "OPENAI_API_KEY"],
221354
- "openrouter.ai": [/OPENROUTER/, "OPENROUTER_API_KEY"],
221355
- "generativelanguage.googleapis.com": [/GEMINI|GOOGLE/, "GEMINI_API_KEY"],
221356
- "api.groq.com": [/GROQ/, "GROQ_API_KEY"],
221357
- "api.mistral.ai": [/MISTRAL/, "MISTRAL_API_KEY"],
221358
- "api.together.xyz": [/TOGETHER/, "TOGETHER_API_KEY"],
221359
- "api.fireworks.ai": [/FIREWORKS/, "FIREWORKS_API_KEY"],
221360
- "api.deepseek.com": [/DEEPSEEK/, "DEEPSEEK_API_KEY"],
221361
- "api.x.ai": [/XAI|GROK/, "XAI_API_KEY"],
221362
- "api.cohere.com": [/COHERE|CO_API/, "COHERE_API_KEY"]
221363
- };
221364
- SIGN = "The agent must sign with the variables Ancha gives: NETSUITE_ACCESS_TOKEN, or the four TBA values.";
221365
- OUTSIDE = "In Ancha it reaches NetSuite at NETSUITE_API_URL: build its URLs from that variable.";
221366
- SERVED = "Ancha's NetSuite serves REST records, SuiteQL, OAuth 2.0, OAuth 1.0 TBA and Oracle's MCP tools, not RESTlets or SOAP.";
221367
- NO_ANSWER = "gave no answer: post it to ANCHA_DONE_URL or print it last on stdout.";
221368
- POST_ANSWER = 'POST {"output": "<the answer>"} to $ANCHA_DONE_URL with Authorization: Bearer $ANCHA_TRIAL_TOKEN, or print the answer last, after a blank line';
221369
- }
221370
- });
221371
-
221372
221486
  // backend/src/execution/vm-connection.ts
221373
221487
  var vm_connection_exports = {};
221374
221488
  __export(vm_connection_exports, {
@@ -221381,9 +221495,9 @@ __export(vm_connection_exports, {
221381
221495
  taskFixFromLog: () => taskFixFromLog
221382
221496
  });
221383
221497
  import { closeSync as closeSync7, openSync as openSync7, writeSync as writeSync7 } from "node:fs";
221384
- import { mkdir as mkdir19, readFile as readFile24 } from "node:fs/promises";
221498
+ import { mkdir as mkdir19, readFile as readFile25 } from "node:fs/promises";
221385
221499
  import { createServer as createServer5 } from "node:net";
221386
- import { join as join41 } from "node:path";
221500
+ import { join as join42 } from "node:path";
221387
221501
  import { setTimeout as sleep10 } from "node:timers/promises";
221388
221502
  function executable(command) {
221389
221503
  let text29 = command.trimStart();
@@ -221442,11 +221556,12 @@ async function probeVmConnection(descriptor3, deps = {}) {
221442
221556
  const agent = deps.agent ?? withLocalEnvironment(resolveRunAgent(config11, descriptor3.projectDir, { ...descriptor3.options.agentCommand !== null && { agent: descriptor3.options.agentCommand }, parallel: 1 }).agent, config11);
221443
221557
  const http = agent.mode === "endpoint" || agent.taskInput?.kind === "http";
221444
221558
  probe.kind = http ? "http" : agent.taskInput?.kind === "per_event" ? "per_event" : "command";
221445
- const asked2 = agent.mode !== "endpoint" && agent.taskInput?.kind === "http" && (await probeTwins(descriptor3.agentDir, agent)).includes("netsuite");
221559
+ const twins = agent.mode === "endpoint" ? [] : await probeTwins(descriptor3.agentDir, agent, await connectionTools(descriptor3.projectDir));
221560
+ const asked2 = agent.mode !== "endpoint" && agent.taskInput?.kind === "http" && twins.includes("netsuite");
221446
221561
  const scene2 = parseScene({ id: "connection", title: "Agent connection", twins: [], start_time: "2026-01-01T00:00:00Z", seed: {}, checks: [] });
221447
221562
  const env2 = { id: "connection", sceneId: scene2.id, services: {}, startTime: scene2.start_time, timeScale: 1 };
221448
221563
  await mkdir19(descriptor3.outDir, { recursive: true });
221449
- const logPath = join41(descriptor3.outDir, "agent.log");
221564
+ const logPath = join42(descriptor3.outDir, "agent.log");
221450
221565
  fd = openSync7(logPath, "w", 384);
221451
221566
  const timeout = AbortSignal.timeout(http ? agent.mode === "endpoint" ? agent.startupTimeoutMs : agent.taskInput?.kind === "http" ? agent.taskInput.startupTimeoutMs ?? 12e4 : 3e4 : 1e4);
221452
221567
  if (!http || asked2) {
@@ -221466,6 +221581,7 @@ async function probeVmConnection(descriptor3, deps = {}) {
221466
221581
  return await runWithTask(descriptor3, agent, {
221467
221582
  fd,
221468
221583
  probe,
221584
+ twins,
221469
221585
  ...deps.probeMs !== void 0 && { limit: deps.probeMs },
221470
221586
  open: deps.openBackend ?? (() => openBackend({ peopleRelay: cloudModelAccess(descriptor3.relay).peopleRelay }))
221471
221587
  });
@@ -221508,15 +221624,16 @@ async function probeVmConnection(descriptor3, deps = {}) {
221508
221624
  }
221509
221625
  }
221510
221626
  }
221511
- async function probeTwins(dir2, agent) {
221512
- return (await agentTools2(dir2, agent)).tools.slice(0, 6);
221627
+ async function probeTwins(dir2, agent, tests = []) {
221628
+ return [.../* @__PURE__ */ new Set([...(await agentTools2(dir2, agent)).tools, ...tests])].slice(0, 6);
221513
221629
  }
221514
221630
  function unfinished(trial) {
221515
221631
  return `The connection check could not finish: ${trial.harnessIssues.find((issue6) => issue6.owner === "harness")?.message ?? "the world failed"}.`;
221516
221632
  }
221517
221633
  async function runWithTask(descriptor3, agent, run6) {
221518
221634
  const { probe } = run6;
221519
- const twins = await probeTwins(descriptor3.agentDir, agent);
221635
+ const twins = run6.twins;
221636
+ probe.tools = probeToolCalls(twins, []);
221520
221637
  const netsuite = twins.includes("netsuite"), task2 = netsuite ? NETSUITE_PROBE_TASK : PROBE_TASK;
221521
221638
  const limit2 = run6.limit ?? (netsuite ? NETSUITE_PROBE_MS : PROBE_MS);
221522
221639
  const scene2 = parseScene({
@@ -221549,7 +221666,7 @@ async function runWithTask(descriptor3, agent, run6) {
221549
221666
  trials: 1,
221550
221667
  parallel: 1,
221551
221668
  seed: "connection",
221552
- outDir: join41(descriptor3.outDir, "connection"),
221669
+ outDir: join42(descriptor3.outDir, "connection"),
221553
221670
  root: descriptor3.projectDir,
221554
221671
  inheritedEnv: {},
221555
221672
  realTimeouts: { [scene2.id]: limit2 }
@@ -221560,13 +221677,15 @@ async function runWithTask(descriptor3, agent, run6) {
221560
221677
  await backend?.close().catch(() => {
221561
221678
  });
221562
221679
  }
221563
- const log3 = trial === void 0 ? void 0 : await readFile24(join41(trial.dir, "agent.log")).catch(() => void 0);
221680
+ const log3 = trial === void 0 ? void 0 : await readFile25(join42(trial.dir, "agent.log")).catch(() => void 0);
221564
221681
  if (log3 !== void 0) writeSync7(run6.fd, log3);
221565
221682
  probe.durationMs = trial?.realMs ?? 0;
221566
221683
  probe.exitCode = trial?.exitCode ?? null;
221567
221684
  if (trial === void 0) return { state: "failed", probe, message: "The connection check could not start." };
221685
+ probe.tools = probeToolCalls(twins, trial.trace);
221568
221686
  const tail = trial.logTail, fix = taskFixFromLog(tail, agent);
221569
- if (!trial.valid) {
221687
+ const harnessIssue = trial.harnessIssues.some((issue6) => issue6.owner === "harness" && issue6.code !== "MODEL_KEY_REFUSED");
221688
+ if (harnessIssue || !trial.valid && !trial.harnessIssues.some((issue6) => issue6.code === "MODEL_KEY_REFUSED")) {
221570
221689
  Object.assign(probe, { logTail: tail, ...fix !== void 0 && { fix } });
221571
221690
  return { state: "failed", probe, message: unfinished(trial) };
221572
221691
  }
@@ -221603,6 +221722,7 @@ var init_vm_connection = __esm({
221603
221722
  init_agent_env();
221604
221723
  init_run();
221605
221724
  init_relay3();
221725
+ init_connection_tools();
221606
221726
  init_agent_tools3();
221607
221727
  init_task_input();
221608
221728
  init_agent_outcome();
@@ -221623,9 +221743,9 @@ __export(assemble_exports, {
221623
221743
  finalizeInput: () => finalizeInput
221624
221744
  });
221625
221745
  import { createHash as createHash65 } from "node:crypto";
221626
- import { copyFile as copyFile4, lstat as lstat8, mkdir as mkdir20, mkdtemp as mkdtemp7, readdir as readdir6, readFile as readFile25, rm as rm9, writeFile as writeFile18 } from "node:fs/promises";
221746
+ import { copyFile as copyFile4, lstat as lstat8, mkdir as mkdir20, mkdtemp as mkdtemp7, readdir as readdir6, readFile as readFile26, rm as rm9, writeFile as writeFile18 } from "node:fs/promises";
221627
221747
  import { tmpdir as tmpdir6 } from "node:os";
221628
- import { dirname as dirname18, join as join42, resolve as resolve30, sep as sep6 } from "node:path";
221748
+ import { dirname as dirname18, join as join43, resolve as resolve30, sep as sep6 } from "node:path";
221629
221749
  function finalizeInput(value5) {
221630
221750
  const wrong = (what) => {
221631
221751
  throw new AnchaError("INTERNAL", `the finalize input ${what}`);
@@ -221719,7 +221839,7 @@ function inside2(root3, path7, what) {
221719
221839
  async function bundleManifest(bundleDir) {
221720
221840
  let manifest2;
221721
221841
  try {
221722
- manifest2 = JSON.parse(await readFile25(join42(bundleDir, "manifest.json"), "utf8"));
221842
+ manifest2 = JSON.parse(await readFile26(join43(bundleDir, "manifest.json"), "utf8"));
221723
221843
  } catch {
221724
221844
  throw new AnchaError("INTERNAL", "the bundle has no readable manifest.json");
221725
221845
  }
@@ -221744,7 +221864,7 @@ async function evidenceOf(folder2, input4, attempt) {
221744
221864
  };
221745
221865
  let manifest2;
221746
221866
  try {
221747
- manifest2 = JSON.parse(await readFile25(join42(folder2, "artifact.json"), "utf8"));
221867
+ manifest2 = JSON.parse(await readFile26(join43(folder2, "artifact.json"), "utf8"));
221748
221868
  } catch {
221749
221869
  broken("has no readable artifact.json");
221750
221870
  }
@@ -221756,9 +221876,9 @@ async function evidenceOf(folder2, input4, attempt) {
221756
221876
  const name5 = file3.path.slice(base3.length);
221757
221877
  if (!file3.path.startsWith(base3) || !FILE_NAME2.test(name5)) broken(`holds ${JSON.stringify(file3.path)}, which is not in its trial's directory`);
221758
221878
  if (files2.has(name5)) broken(`lists ${file3.path} twice`);
221759
- const path7 = join42(folder2, file3.path);
221879
+ const path7 = join43(folder2, file3.path);
221760
221880
  if (!await lstat8(path7).then((info) => info.isFile(), () => false)) broken(`has no ${file3.path}`);
221761
- const data5 = await readFile25(path7);
221881
+ const data5 = await readFile26(path7);
221762
221882
  if (data5.length !== file3.bytes || sha2565(data5) !== file3.sha256) broken(`has a ${file3.path} that differs from its artifact.json`);
221763
221883
  files2.set(name5, path7);
221764
221884
  }
@@ -221769,7 +221889,7 @@ async function rebuilt(files2, attempt, scene2, dir2) {
221769
221889
  if (resultFile === void 0) return { problem: "the attempt left no result.json" };
221770
221890
  let raw3;
221771
221891
  try {
221772
- raw3 = JSON.parse(await readFile25(resultFile, "utf8"));
221892
+ raw3 = JSON.parse(await readFile26(resultFile, "utf8"));
221773
221893
  } catch {
221774
221894
  return { problem: "the attempt's result.json is not JSON" };
221775
221895
  }
@@ -221790,7 +221910,7 @@ async function rebuilt(files2, attempt, scene2, dir2) {
221790
221910
  const traceFile = files2.get("trace.jsonl");
221791
221911
  if (traceFile !== void 0) {
221792
221912
  try {
221793
- trace = (await readFile25(traceFile, "utf8")).split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
221913
+ trace = (await readFile26(traceFile, "utf8")).split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
221794
221914
  } catch {
221795
221915
  return { problem: "the attempt's trace.jsonl is not JSON lines" };
221796
221916
  }
@@ -221807,41 +221927,41 @@ function asInvalid(result, attempt) {
221807
221927
  }
221808
221928
  async function trialOf(attempt, item2, input4, artifactsDir, runDir) {
221809
221929
  if (attempt.state === "skipped" || attempt.state === "cancelled") return void 0;
221810
- const { scene: scene2 } = item2, dir2 = join42(runDir, `trial-${attempt.caseId}-${attempt.trial}`);
221930
+ const { scene: scene2 } = item2, dir2 = join43(runDir, `trial-${attempt.caseId}-${attempt.trial}`);
221811
221931
  await mkdir20(dir2);
221812
221932
  const lost = (error65) => invalidTrial({ scene: scene2, trial: attempt.trial, dir: dir2, error: error65, service: "cloud" });
221813
221933
  let result;
221814
221934
  if (attempt.artifactHash === null) {
221815
221935
  result = await lost(attempt.error ?? { code: "INTERNAL", message: attempt.state === "invalid" ? "the attempt left no result" : "the attempt finished without its result" });
221816
221936
  } else {
221817
- const files2 = await evidenceOf(join42(artifactsDir, attempt.id), input4, attempt);
221937
+ const files2 = await evidenceOf(join43(artifactsDir, attempt.id), input4, attempt);
221818
221938
  const found = await rebuilt(files2, attempt, scene2, dir2);
221819
- for (const [name5, file3] of files2) if (TRIAL_FILES.has(name5) && name5 !== "result.json" && ("result" in found || name5 === "agent.log")) await copyFile4(file3, join42(dir2, name5));
221939
+ for (const [name5, file3] of files2) if (TRIAL_FILES.has(name5) && name5 !== "result.json" && ("result" in found || name5 === "agent.log")) await copyFile4(file3, join43(dir2, name5));
221820
221940
  result = "result" in found ? asInvalid(found.result, attempt) : await lost({ code: "INTERNAL", message: found.problem });
221821
221941
  }
221822
221942
  result.caseId = attempt.caseId;
221823
221943
  result.attemptId ??= `${input4.jobId}/${attempt.caseId}/${attempt.trial}`;
221824
221944
  if (writeTools(scene2).size) result.actions = actionsOf(scene2, result.trace);
221825
221945
  if (Object.keys(scene2.tools ?? {}).length) result.answers = answersOf(result.trace);
221826
- await writeFile18(join42(dir2, "result.json"), `${JSON.stringify({ ...result, trace: void 0 }, null, 2)}
221946
+ await writeFile18(join43(dir2, "result.json"), `${JSON.stringify({ ...result, trace: void 0 }, null, 2)}
221827
221947
  `, { flag: "wx", mode: 384 });
221828
221948
  return result;
221829
221949
  }
221830
221950
  async function pinnedBaseline2(projectDir, pin2) {
221831
- const data5 = await readFile25(inside2(projectDir, pin2.path, "the baseline"));
221951
+ const data5 = await readFile26(inside2(projectDir, pin2.path, "the baseline"));
221832
221952
  if (sha2565(data5) !== pin2.sha256) throw new AnchaError("INTERNAL", `the baseline ${pin2.path} is not the one the run was submitted with`);
221833
221953
  const parsed4 = JSON.parse(data5.toString("utf8"));
221834
221954
  if (!isRecord5(parsed4) || parsed4.runId !== pin2.runId || !Array.isArray(parsed4.scenes)) throw new AnchaError("INTERNAL", `the baseline ${pin2.path} is not run ${pin2.runId}`);
221835
221955
  return normalizeSummary(parsed4);
221836
221956
  }
221837
221957
  async function productionComparison(summary, cases, projectDir, runDir, judge) {
221838
- const copies = await mkdtemp7(join42(tmpdir6(), "ancha-production-"));
221958
+ const copies = await mkdtemp7(join43(tmpdir6(), "ancha-production-"));
221839
221959
  try {
221840
221960
  const files2 = {}, errors3 = /* @__PURE__ */ new Map();
221841
221961
  for (const [index, item2] of cases.entries()) {
221842
- const scenePath = resolve30(projectDir, item2.path), file3 = join42(copies, `${index}.json`);
221962
+ const scenePath = resolve30(projectDir, item2.path), file3 = join43(copies, `${index}.json`);
221843
221963
  files2[item2.caseId] = file3;
221844
- await copyFile4(join42(dirname18(scenePath), "production.json"), file3).catch((error65) => {
221964
+ await copyFile4(join43(dirname18(scenePath), "production.json"), file3).catch((error65) => {
221845
221965
  if (error65.code !== "ENOENT") throw error65;
221846
221966
  });
221847
221967
  try {
@@ -221861,8 +221981,8 @@ async function productionComparison(summary, cases, projectDir, runDir, judge) {
221861
221981
  }
221862
221982
  }
221863
221983
  async function assembleCloudRun(options4) {
221864
- const input4 = finalizeInput(typeof options4.input === "string" ? JSON.parse(await readFile25(options4.input, "utf8")) : options4.input);
221865
- const { jobId: runId2, options: resolved } = input4, projectDir = join42(options4.bundleDir, "project");
221984
+ const input4 = finalizeInput(typeof options4.input === "string" ? JSON.parse(await readFile26(options4.input, "utf8")) : options4.input);
221985
+ const { jobId: runId2, options: resolved } = input4, projectDir = join43(options4.bundleDir, "project");
221866
221986
  checkMatrix(input4);
221867
221987
  await checkFolders(options4.artifactsDir, input4);
221868
221988
  const manifest2 = await bundleManifest(options4.bundleDir);
@@ -221871,14 +221991,14 @@ async function assembleCloudRun(options4) {
221871
221991
  if (agent.mode === "endpoint") throw new AnchaError("INTERNAL", "a cloud run runs an agent started by a command");
221872
221992
  const cases = await loadCases(projectDir, input4);
221873
221993
  const baseline = resolved.baseline === null ? void 0 : await pinnedBaseline2(projectDir, resolved.baseline);
221874
- const runDir = join42(options4.outDir, runId2);
221994
+ const runDir = join43(options4.outDir, runId2);
221875
221995
  await mkdir20(options4.outDir, { recursive: true });
221876
221996
  await mkdir20(runDir);
221877
221997
  const frozen = cases.map((item2) => {
221878
221998
  const value5 = { id: item2.caseId, scenarioId: item2.scene.id, seed: item2.seed, compiledFingerprint: sceneFingerprint(item2.scene), identity: {} };
221879
221999
  return { ...value5, fingerprint: sceneFingerprint(value5), scene: item2.scene };
221880
222000
  });
221881
- await writeFile18(join42(runDir, "inputs.json"), `${JSON.stringify({ schemaVersion: 1, cases: sharedSeeds(frozen), isolation: { execution: "cloud", toolWorld: "fresh-per-attempt", agentProcess: "fresh-machine-per-attempt", agentState: "fresh-machine-per-attempt" } })}
222001
+ await writeFile18(join43(runDir, "inputs.json"), `${JSON.stringify({ schemaVersion: 1, cases: sharedSeeds(frozen), isolation: { execution: "cloud", toolWorld: "fresh-per-attempt", agentProcess: "fresh-machine-per-attempt", agentState: "fresh-machine-per-attempt" } })}
221882
222002
  `, { flag: "wx", mode: 384 });
221883
222003
  const results = new Map(cases.map((item2) => [item2.caseId, { scene: item2.scene, trials: [], requestedTrials: resolved.attempts, ...item2.records !== void 0 && { records: item2.records } }]));
221884
222004
  for (const item2 of cases) {
@@ -221922,9 +222042,9 @@ async function assembleCloudRun(options4) {
221922
222042
  summary.reproduction = await productionComparison(summary, cases, projectDir, runDir, options4.judge ?? {});
221923
222043
  const json35 = (value5) => `${JSON.stringify(value5, null, 2)}
221924
222044
  `;
221925
- await writeFile18(join42(runDir, "reproduction.json"), json35(summary.reproduction), { flag: "wx", mode: 384 });
221926
- await writeFile18(join42(runDir, "cloud.json"), json35({ version: 1, jobId: runId2, bundleHash: input4.bundleHash, startedAt: input4.startedAt, finishedAt: input4.finishedAt, terminalIntent: input4.terminalIntent, attempts: input4.attempts }), { flag: "wx", mode: 384 });
221927
- await writeFile18(join42(runDir, "summary.json"), json35(summary), { flag: "wx", mode: 384 });
222045
+ await writeFile18(join43(runDir, "reproduction.json"), json35(summary.reproduction), { flag: "wx", mode: 384 });
222046
+ await writeFile18(join43(runDir, "cloud.json"), json35({ version: 1, jobId: runId2, bundleHash: input4.bundleHash, startedAt: input4.startedAt, finishedAt: input4.finishedAt, terminalIntent: input4.terminalIntent, attempts: input4.attempts }), { flag: "wx", mode: 384 });
222047
+ await writeFile18(join43(runDir, "summary.json"), json35(summary), { flag: "wx", mode: 384 });
221928
222048
  const { archive } = await packRun({
221929
222049
  runDir,
221930
222050
  runId: runId2,
@@ -221935,7 +222055,7 @@ async function assembleCloudRun(options4) {
221935
222055
  secrets: [],
221936
222056
  inputsBytes: readsLargeInputs(input4.cliVersion) ? BUNDLE_LIMITS2.largeFileBytes : BUNDLE_LIMITS2.fileBytes
221937
222057
  });
221938
- const archivePath = join42(options4.outDir, `${runId2}.tar.gz`);
222058
+ const archivePath = join43(options4.outDir, `${runId2}.tar.gz`);
221939
222059
  await writeFile18(archivePath, archive, { flag: "wx", mode: 384 });
221940
222060
  return { archivePath, sha256: sha2565(archive), runId: runId2, exitCode: summary.exitCode, verdict: summary.verdict };
221941
222061
  }
@@ -222013,10 +222133,10 @@ __export(view_exports, {
222013
222133
  renderCloudView: () => renderCloudView
222014
222134
  });
222015
222135
  import { randomBytes as randomBytes6 } from "node:crypto";
222016
- import { readFile as readFile26 } from "node:fs/promises";
222136
+ import { readFile as readFile27 } from "node:fs/promises";
222017
222137
  import { dirname as dirname19 } from "node:path";
222018
222138
  async function renderCloudView(path7) {
222019
- const input4 = JSON.parse(await readFile26(path7, "utf8"));
222139
+ const input4 = JSON.parse(await readFile27(path7, "utf8"));
222020
222140
  if (!input4 || typeof input4 !== "object" || Array.isArray(input4) || Object.keys(input4).some((k) => !["scene", "configuration", "path", "seed"].includes(k)) || ["scene", "configuration", "path"].filter((k) => k in input4).length !== 1 || input4.seed !== null && (typeof input4.seed !== "string" || !input4.seed)) throw new AnchaError("CONFIG_INVALID", "Choose one world definition and its seed.");
222021
222141
  if ("path" in input4 && (typeof input4.path !== "string" || !input4.path.split("/").every((p2) => p2 && p2 !== "." && p2 !== "..") || /[\\:\x00-\x1f]/.test(input4.path))) throw new AnchaError("CONFIG_INVALID", "Choose a test path inside the view bundle.");
222022
222142
  const scene2 = "scene" in input4 ? parseScene(input4.scene) : "path" in input4 ? (await loadSceneOrTest(dirname19(path7), input4.path)).scene : null;
@@ -227358,9 +227478,9 @@ init_backend();
227358
227478
  init_src();
227359
227479
  init_credentials();
227360
227480
  import { execFile as execFile4 } from "node:child_process";
227361
- import { mkdtemp as mkdtemp4, readFile as readFile10, rm as rm3, stat as stat4, writeFile as writeFile11 } from "node:fs/promises";
227481
+ import { mkdtemp as mkdtemp4, readFile as readFile11, rm as rm3, stat as stat4, writeFile as writeFile11 } from "node:fs/promises";
227362
227482
  import { tmpdir as tmpdir3 } from "node:os";
227363
- import { basename as basename7, join as join23, resolve as resolve17 } from "node:path";
227483
+ import { basename as basename7, join as join24, resolve as resolve17 } from "node:path";
227364
227484
  import { promisify as promisify4 } from "node:util";
227365
227485
 
227366
227486
  // backend/src/cloud/dependencies.ts
@@ -228430,17 +228550,18 @@ ${conflicts.map(([path7, set2]) => `${path7} (${[...set2].sort().join(", ")})`).
228430
228550
  init_src();
228431
228551
  init_credentials();
228432
228552
  import { access as access7, mkdir as mkdir12, mkdtemp as mkdtemp3, rename as rename3, rm as rm2, writeFile as writeFile10 } from "node:fs/promises";
228433
- import { dirname as dirname10, join as join22 } from "node:path";
228553
+ import { dirname as dirname10, join as join23 } from "node:path";
228434
228554
  import { setTimeout as sleep9 } from "node:timers/promises";
228435
228555
 
228436
228556
  // backend/src/cloud/bundle.ts
228437
228557
  init_src();
228558
+ init_connection_tools();
228438
228559
  init_jobs_contract();
228439
228560
  import { createHash as createHash58 } from "node:crypto";
228440
228561
  import { constants as constants7 } from "node:fs";
228441
228562
  import { lstat as lstat3, open as open5, realpath as realpath4 } from "node:fs/promises";
228442
- import { join as join19 } from "node:path";
228443
- import { crc32 as crc323, deflateRawSync as deflateRawSync2, gunzipSync } from "node:zlib";
228563
+ import { join as join20 } from "node:path";
228564
+ import { crc32 as crc323, deflateRawSync as deflateRawSync2, gunzipSync as gunzipSync2 } from "node:zlib";
228444
228565
  var shared = jobs_contract_exports;
228445
228566
  var MIB2 = 1024 * 1024;
228446
228567
  var BUNDLE_PATH = /^(?!\/)(?!.*(?:^|\/)\.{0,2}(?:\/|$))[^\0-\x1f\x7f\\]+$/;
@@ -228448,7 +228569,7 @@ var sha2563 = (data5) => createHash58("sha256").update(data5).digest("hex");
228448
228569
  var mib2 = (bytes3) => `${(bytes3 / MIB2).toFixed(1)} MiB`;
228449
228570
  var tooBig = (message7, hint = "leave large files out with .anchaignore, or select the agent's files with agent.execution.files") => new AnchaError("CONFIG_INVALID", message7, { hint });
228450
228571
  async function readProjectFile(root3, path7) {
228451
- const file3 = join19(root3, ...path7.split("/"));
228572
+ const file3 = join20(root3, ...path7.split("/"));
228452
228573
  const stat19 = await lstat3(file3).catch(() => void 0);
228453
228574
  if (stat19 === void 0) throw new AnchaError("CONFIG_INVALID", `${path7} is missing`, { hint: "restore it, or change what names it" });
228454
228575
  if (stat19.isSymbolicLink()) throw new AnchaError("CONFIG_INVALID", `${path7} is a symbolic link; a cloud bundle carries regular files`, { hint: "copy what it points to into the project, or leave it out with .anchaignore" });
@@ -228469,6 +228590,11 @@ async function buildBundle(input4) {
228469
228590
  if (input4.kind === "connect" && input4.tests.length > 0) throw new AnchaError("USAGE", "a connection check carries the project without tests");
228470
228591
  if (input4.kind === "run" && input4.tests.length === 0) throw new AnchaError("USAGE", "no test to run", { hint: "pass a test file, or name tests in ancha.yaml" });
228471
228592
  const inventory = await bundleInventory({ root: input4.root, configPath: input4.configPath, config: input4.config, tests: input4.tests, bundleFiles: input4.bundleFiles ?? [], ...input4.baseline !== void 0 && { baseline: input4.baseline.path } });
228593
+ const connectionData = input4.kind === "connect" && input4.connectionTools !== void 0 ? Buffer.from(shared.canonicalJson([...new Set(input4.connectionTools)])) : void 0;
228594
+ if (connectionData !== void 0) {
228595
+ if (inventory.files.has(CONNECTION_TOOLS_PATH)) throw new AnchaError("CONFIG_INVALID", `${CONNECTION_TOOLS_PATH} is reserved for connection tools`);
228596
+ inventory.files.set(CONNECTION_TOOLS_PATH, ["config"]);
228597
+ }
228472
228598
  const paths2 = [...inventory.files.keys()];
228473
228599
  const invalid35 = paths2.filter((path7) => !BUNDLE_PATH.test(path7));
228474
228600
  if (invalid35.length) throw new AnchaError("CONFIG_INVALID", `a cloud bundle cannot name these files:
@@ -228485,7 +228611,7 @@ ${invalid35.map((path7) => JSON.stringify(path7)).join("\n")}`, { hint: "rename
228485
228611
  const contents = [];
228486
228612
  let bytes3 = 0;
228487
228613
  for (const [path7, roles2] of inventory.files) {
228488
- const read7 = input4.baseline !== void 0 && path7 === input4.baseline.path ? { data: input4.baseline.data, executable: false } : await readProjectFile(root3, path7);
228614
+ const read7 = connectionData !== void 0 && path7 === CONNECTION_TOOLS_PATH ? { data: connectionData, executable: false } : input4.baseline !== void 0 && path7 === input4.baseline.path ? { data: input4.baseline.data, executable: false } : await readProjectFile(root3, path7);
228489
228615
  if (path7.split("/").at(-1) === ".yarnrc.yml") {
228490
228616
  const release2 = yarnReleasePath(path7, read7.data.toString("utf8"));
228491
228617
  if (release2 !== void 0 && !inventory.files.has(release2)) throw new AnchaError("CONFIG_INVALID", `${path7}: yarnPath changed while the bundle was built`, { hint: "run the command again" });
@@ -228763,21 +228889,21 @@ function onThisComputer(ref22) {
228763
228889
  }
228764
228890
  var CLOUD_JOB_FILE = "cloud-job.json";
228765
228891
  async function cachedCloudRun(ctx, id14, runsDir) {
228766
- const dir2 = join22(runsDir, id14);
228767
- if (await access7(join22(dir2, CLOUD_JOB_FILE)).then(() => true, () => false)) return dir2;
228892
+ const dir2 = join23(runsDir, id14);
228893
+ if (await access7(join23(dir2, CLOUD_JOB_FILE)).then(() => true, () => false)) return dir2;
228768
228894
  if (!shared.RUN_CLOUD_ID.test(id14)) throw new AnchaError("USAGE", `${id14} is not a cloud run; a connection check has no run report`, { hint: `ancha runs show ${id14}` });
228769
228895
  const ws = await jobWorkspace(ctx, id14), detail3 = await getJob(ws, id14);
228770
228896
  if (!shared.TERMINAL_JOB_STATES.includes(detail3.job.state)) throw new AnchaError("SESSION_CONFLICT", `${id14} has not finished`, { hint: `ancha wait ${id14}, then ancha report ${id14} --html` });
228771
228897
  const archive = await getArchive(ws, id14), manifest2 = validateBundle(archive);
228772
228898
  if (manifest2.runId !== id14 || manifest2.source !== "cloud") throw new AnchaError("INTERNAL", `the workspace answered another run's archive for ${id14}`);
228773
228899
  await mkdir12(runsDir, { recursive: true });
228774
- const temp = await mkdtemp3(join22(runsDir, `.${id14}-`));
228900
+ const temp = await mkdtemp3(join23(runsDir, `.${id14}-`));
228775
228901
  try {
228776
228902
  for (const entry3 of readBundle(archive)) {
228777
- await mkdir12(dirname10(join22(temp, entry3.path)), { recursive: true });
228778
- await writeFile10(join22(temp, entry3.path), entry3.data, { mode: 384 });
228903
+ await mkdir12(dirname10(join23(temp, entry3.path)), { recursive: true });
228904
+ await writeFile10(join23(temp, entry3.path), entry3.data, { mode: 384 });
228779
228905
  }
228780
- await writeFile10(join22(temp, CLOUD_JOB_FILE), `${JSON.stringify(detail3, null, 2)}
228906
+ await writeFile10(join23(temp, CLOUD_JOB_FILE), `${JSON.stringify(detail3, null, 2)}
228781
228907
  `, { mode: 384 });
228782
228908
  await rm2(dir2, { recursive: true, force: true });
228783
228909
  await rename3(temp, dir2);
@@ -228810,7 +228936,7 @@ function retryHint(response5) {
228810
228936
  if (!Number.isInteger(seconds6) || seconds6 <= 0) return "wait a little, then retry";
228811
228937
  return `retry in ${seconds6 < 120 ? `${seconds6} seconds` : `${Math.ceil(seconds6 / 60)} minutes`}`;
228812
228938
  }
228813
- async function refusal(response5, server) {
228939
+ async function refusal2(response5, server) {
228814
228940
  if (response5.status === 401) return authError(server, { status: 401, keySent: true });
228815
228941
  const body7 = await response5.json().catch(() => void 0);
228816
228942
  const error65 = typeof body7?.error === "object" && body7.error !== null ? body7.error : { message: typeof body7?.error === "string" ? body7.error : void 0 };
@@ -228847,7 +228973,7 @@ async function call2(ws, method2, path7, options4 = {}) {
228847
228973
  continue;
228848
228974
  }
228849
228975
  if (response5 === void 0) throw new AnchaError("SERVER_UNREACHABLE", `${ws.server} did not answer`, { hint: "check the network, then retry", cause: failure6 });
228850
- throw await refusal(response5, ws.server);
228976
+ throw await refusal2(response5, ws.server);
228851
228977
  }
228852
228978
  }
228853
228979
  var path6 = (id14, rest2 = "") => `/_jobs/${encodeURIComponent(id14)}${rest2}`;
@@ -228894,7 +229020,7 @@ async function* readEvents(ws, id14, after, follow2, signal) {
228894
229020
  if (signal?.aborted) throw error65;
228895
229021
  throw new AnchaError("SERVER_UNREACHABLE", `${ws.server} did not answer`, { cause: error65 });
228896
229022
  }
228897
- if (!response5.ok || response5.body === null) throw await refusal(response5, ws.server);
229023
+ if (!response5.ok || response5.body === null) throw await refusal2(response5, ws.server);
228898
229024
  const decoder = new TextDecoder();
228899
229025
  let tail = "";
228900
229026
  try {
@@ -229177,7 +229303,7 @@ async function forward(ctx, serverUrl3, words8, raw3) {
229177
229303
  continue;
229178
229304
  }
229179
229305
  const path7 = resolve17(ctx.io.cwd, value5), name5 = basename7(path7).replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 100) || "file";
229180
- const content2 = await readFile10(path7).catch(() => void 0);
229306
+ const content2 = await readFile11(path7).catch(() => void 0);
229181
229307
  if (content2 === void 0) {
229182
229308
  if (flag5 === "--test") {
229183
229309
  argv.push(flag5, value5);
@@ -229211,7 +229337,7 @@ async function post4(server, key4, argv, files2) {
229211
229337
  throw new AnchaError("SERVER_UNREACHABLE", `${server} did not answer`, { hint: "check the network, then retry", cause: error65 });
229212
229338
  }
229213
229339
  if (response5.status === 401) throw authError(server, { status: 401, keySent: true });
229214
- if (!response5.ok || response5.body === null) throw await refusal2(response5, server);
229340
+ if (!response5.ok || response5.body === null) throw await refusal3(response5, server);
229215
229341
  return response5.body;
229216
229342
  }
229217
229343
  async function send2(ctx, server, key4, argv, files2 = {}) {
@@ -229251,7 +229377,7 @@ function optionValue(args, name5) {
229251
229377
  }
229252
229378
  return void 0;
229253
229379
  }
229254
- async function refusal2(response5, server) {
229380
+ async function refusal3(response5, server) {
229255
229381
  const body7 = await response5.json().catch(() => void 0);
229256
229382
  const error65 = typeof body7?.error === "object" ? body7.error : { message: typeof body7?.error === "string" ? body7.error : void 0 };
229257
229383
  if (response5.status === 429) return new AnchaError("USAGE", error65.message ?? "too many commands for this key", { hint: error65.hint ?? retryHint(response5) });
@@ -229310,13 +229436,13 @@ async function packProject(dir2) {
229310
229436
  const files2 = await projectFiles(root3);
229311
229437
  if (files2.length === 0) throw new AnchaError("USAGE", `${dir2} has no files to upload`, { hint: "check .gitignore and .anchaignore" });
229312
229438
  let bytes3 = 0;
229313
- for (const path7 of files2) bytes3 += (await stat4(join23(root3, path7))).size;
229439
+ for (const path7 of files2) bytes3 += (await stat4(join24(root3, path7))).size;
229314
229440
  if (bytes3 > MAX_PROJECT_BYTES) throw new AnchaError("USAGE", `${dir2} holds ${(bytes3 / 1024 / 1024).toFixed(1)} MB to upload; the limit is 200 MB`, { hint: "leave large files out with .anchaignore" });
229315
- const temporary = await mkdtemp4(join23(tmpdir3(), "ancha-pack-"));
229441
+ const temporary = await mkdtemp4(join24(tmpdir3(), "ancha-pack-"));
229316
229442
  try {
229317
- await writeFile11(join23(temporary, "files"), files2.join("\0"));
229318
- await run3("tar", ["-czf", join23(temporary, "project.tar.gz"), "-C", root3, "--null", "-T", join23(temporary, "files")], { maxBuffer: 16 * 1024 * 1024 });
229319
- return { archive: await readFile10(join23(temporary, "project.tar.gz")), files: files2.length, bytes: bytes3 };
229443
+ await writeFile11(join24(temporary, "files"), files2.join("\0"));
229444
+ await run3("tar", ["-czf", join24(temporary, "project.tar.gz"), "-C", root3, "--null", "-T", join24(temporary, "files")], { maxBuffer: 16 * 1024 * 1024 });
229445
+ return { archive: await readFile11(join24(temporary, "project.tar.gz")), files: files2.length, bytes: bytes3 };
229320
229446
  } finally {
229321
229447
  await rm3(temporary, { recursive: true, force: true });
229322
229448
  }
@@ -229419,8 +229545,8 @@ function registerEnv(program2, ctx) {
229419
229545
  // packages/cli/src/commands/explain.ts
229420
229546
  init_src();
229421
229547
  init_src();
229422
- import { access as access11, readFile as readFile31, writeFile as writeFile21 } from "node:fs/promises";
229423
- import { join as join45, relative as relative14, resolve as resolve34 } from "node:path";
229548
+ import { access as access11, readFile as readFile32, writeFile as writeFile21 } from "node:fs/promises";
229549
+ import { join as join46, relative as relative14, resolve as resolve34 } from "node:path";
229424
229550
 
229425
229551
  // packages/cli/src/numbers.ts
229426
229552
  init_src();
@@ -229443,8 +229569,8 @@ init_report2();
229443
229569
  init_src();
229444
229570
  init_report2();
229445
229571
  init_run_inputs();
229446
- import { readFile as readFile12 } from "node:fs/promises";
229447
- import { join as join25 } from "node:path";
229572
+ import { readFile as readFile13 } from "node:fs/promises";
229573
+ import { join as join26 } from "node:path";
229448
229574
  var CALLS_SHOWN = 200;
229449
229575
  var LOG_LINES = 40;
229450
229576
  var ANSWER_CHARS = 5e4;
@@ -229458,13 +229584,13 @@ var trialFolder = (sceneId, trial) => `trial-${sceneId}-${trial}`;
229458
229584
  async function readRunRecords(runDir, summary, options4) {
229459
229585
  const json35 = async (path7) => {
229460
229586
  try {
229461
- return JSON.parse(await readFile12(path7, "utf8"));
229587
+ return JSON.parse(await readFile13(path7, "utf8"));
229462
229588
  } catch {
229463
229589
  return null;
229464
229590
  }
229465
229591
  };
229466
- const text29 = async (path7) => readFile12(path7, "utf8").catch(() => null);
229467
- const events3 = await text29(join25(runDir, "events.ndjson"));
229592
+ const text29 = async (path7) => readFile13(path7, "utf8").catch(() => null);
229593
+ const events3 = await text29(join26(runDir, "events.ndjson"));
229468
229594
  let atOnce2 = null;
229469
229595
  try {
229470
229596
  const first = JSON.parse(events3?.split("\n", 1)[0] ?? "");
@@ -229473,9 +229599,9 @@ async function readRunRecords(runDir, summary, options4) {
229473
229599
  }
229474
229600
  const trials = /* @__PURE__ */ new Map();
229475
229601
  for (const scene2 of summary.scenes) for (const trial of scene2.trialsDetail) {
229476
- const dir2 = join25(runDir, trialFolder(scene2.sceneId, trial.trial));
229477
- const trace = await text29(join25(dir2, "trace.jsonl"));
229478
- const checks2 = await json35(join25(dir2, "checks.json")) ?? (await json35(join25(dir2, "result.json")))?.checks ?? null;
229602
+ const dir2 = join26(runDir, trialFolder(scene2.sceneId, trial.trial));
229603
+ const trace = await text29(join26(dir2, "trace.jsonl"));
229604
+ const checks2 = await json35(join26(dir2, "checks.json")) ?? (await json35(join26(dir2, "result.json")))?.checks ?? null;
229479
229605
  trials.set(trialKey(scene2.sceneId, trial.trial), {
229480
229606
  trace: trace === null ? null : trace.split("\n").flatMap((line2) => {
229481
229607
  if (!line2.trim()) return [];
@@ -229486,12 +229612,12 @@ async function readRunRecords(runDir, summary, options4) {
229486
229612
  }
229487
229613
  }),
229488
229614
  checks: Array.isArray(checks2) ? checks2 : null,
229489
- state: await json35(join25(dir2, "state.json")),
229490
- log: await text29(join25(dir2, "agent.log"))
229615
+ state: await json35(join26(dir2, "state.json")),
229616
+ log: await text29(join26(dir2, "agent.log"))
229491
229617
  });
229492
229618
  }
229493
- const inputs2 = await json35(join25(runDir, "inputs.json"));
229494
- return { folder: options4.folder, inputs: inputs2 && Array.isArray(inputs2.cases) ? { ...inputs2, cases: withSeeds(inputs2.cases) } : inputs2, bundle: await json35(join25(runDir, "bundle.json")), job: await json35(join25(runDir, "cloud-job.json")), atOnce: atOnce2, trials, secrets: options4.secrets ?? [] };
229619
+ const inputs2 = await json35(join26(runDir, "inputs.json"));
229620
+ return { folder: options4.folder, inputs: inputs2 && Array.isArray(inputs2.cases) ? { ...inputs2, cases: withSeeds(inputs2.cases) } : inputs2, bundle: await json35(join26(runDir, "bundle.json")), job: await json35(join26(runDir, "cloud-job.json")), atOnce: atOnce2, trials, secrets: options4.secrets ?? [] };
229495
229621
  }
229496
229622
  var noRecords = (folder2) => ({ folder: folder2, inputs: null, bundle: null, job: null, atOnce: null, trials: /* @__PURE__ */ new Map(), secrets: [] });
229497
229623
  var SECRET_SHAPES = [
@@ -229628,7 +229754,7 @@ function attemptOf2(scene2, detail3, n2, anchor2, records4, sceneRecord, cloud,
229628
229754
  const start = Date.parse(sceneRecord?.start_time ?? "");
229629
229755
  const agentCalls2 = trace.filter((entry3) => entry3.source === "agent" && entry3.service !== "agent");
229630
229756
  const done = [...trace].reverse().find((entry3) => entry3.source === "agent" && entry3.service === "agent" && entry3.path === "/done");
229631
- const output2 = isObject5(done?.request) ? done.request.output : void 0;
229757
+ const output2 = isObject5(done?.request) && done.request.printed === void 0 ? done.request.output : void 0;
229632
229758
  const answerText2 = output2 === void 0 ? null : typeof output2 === "string" ? output2 : JSON.stringify(output2, null, 2);
229633
229759
  const source = isObject5(done?.request) && typeof done.request.source === "string" ? done.request.source : "done";
229634
229760
  const seed43 = sceneRecord?.seed;
@@ -229817,7 +229943,7 @@ function verdictBlock(d) {
229817
229943
  const each = [...new Set(d.tests.map((test3) => test3.requested))].sort((a, b) => a - b);
229818
229944
  const stat19 = (term2, value5, more2 = "") => `<div><dt>${term2}</dt><dd><span class="big">${value5}</span>${more2}</dd></div>`;
229819
229945
  const stats2 = `<dl class="stats">${stat19("Attempt pass rate", t.attempts ? pct2(t.passed / t.attempts) : "\u2014", `<small><a class="n" href="#${attemptsOf(d, "passed")}">${num4(t.passed)}/${num4(t.attempts)}</a></small>`)}` + stat19("Tests", link6(tests, "tests")) + stat19("Attempts per test", each.length === 0 ? "\u2014" : each.length === 1 ? link6(each[0], "tests") : `${link6(each[0], "tests")}\u2013${link6(each.at(-1), "tests")}`) + `${stat19("Total attempts", link6(t.attempts, "machines"))}</dl>`;
229820
- const arithmetic2 = each.length !== 1 ? "" : each[0] === 1 ? '<p class="arith">1 attempt per test: repeatability not measured</p>' : `<p class="arith">${link6(tests, "tests")} ${s2(tests, "test", "tests")} \xD7 ${link6(each[0], "tests")} attempts = ${link6(t.attempts, "machines")} attempts</p>`;
229946
+ const arithmetic2 = each.length !== 1 ? "" : each[0] === 1 ? `<p class="arith">Each test ran once; ${code2("ancha run --attempts 3")} shows how often each one passes.</p>` : `<p class="arith">${link6(tests, "tests")} ${s2(tests, "test", "tests")} \xD7 ${link6(each[0], "tests")} attempts = ${link6(t.attempts, "machines")} attempts</p>`;
229821
229947
  const failed = d.tests.flatMap((test3) => test3.attempts).filter((a) => a.outcome === "failed");
229822
229948
  const fails = failed.slice(0, FAILED_SHOWN).map((a) => {
229823
229949
  const check4 = a.checks.find((c) => c.state === "failed");
@@ -230025,7 +230151,7 @@ h1 a{text-decoration:none}h1 a:hover{text-decoration:underline}
230025
230151
  .v-lines{margin:0;padding-left:20px;display:grid;gap:4px;color:var(--mid)}
230026
230152
  .v-lines a{color:var(--text)}
230027
230153
  .cmp{margin:0;color:var(--mid)}
230028
- .strip{position:relative;display:grid;grid-template-columns:repeat(24,1fr);gap:3px;max-width:720px}
230154
+ .strip{position:relative;display:grid;grid-template-columns:repeat(auto-fill,22px);gap:3px;max-width:720px}
230029
230155
  .cell{display:block;height:22px;border-radius:3px}
230030
230156
  .cell.ok{background:var(--pass)}.cell.no{background:var(--fail)}.cell.inv{background:var(--mute)}.cell.ung{background:var(--raised);box-shadow:inset 0 0 0 1.5px var(--rule-strong)}
230031
230157
  .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
@@ -230341,7 +230467,7 @@ async function consoleApi(base3) {
230341
230467
  // packages/cli/src/commands/playground.ts
230342
230468
  var import_yaml8 = __toESM(require_dist(), 1);
230343
230469
  init_src();
230344
- import { readFile as readFile29, stat as stat10 } from "node:fs/promises";
230470
+ import { readFile as readFile30, stat as stat10 } from "node:fs/promises";
230345
230471
  import { resolve as resolve33 } from "node:path";
230346
230472
 
230347
230473
  // backend/src/playgrounds/service.ts
@@ -230372,7 +230498,7 @@ init_docker();
230372
230498
  init_source();
230373
230499
  import { cp, mkdtemp as mkdtemp6, rm as rm8 } from "node:fs/promises";
230374
230500
  import { tmpdir as tmpdir5 } from "node:os";
230375
- import { join as join32 } from "node:path";
230501
+ import { join as join33 } from "node:path";
230376
230502
 
230377
230503
  // backend/src/execution/capacity.ts
230378
230504
  init_src();
@@ -230423,7 +230549,7 @@ init_assets();
230423
230549
  import { randomUUID as randomUUID7 } from "node:crypto";
230424
230550
  import { execFileSync } from "node:child_process";
230425
230551
  import { chmod as chmod4, mkdir as mkdir14 } from "node:fs/promises";
230426
- import { join as join27 } from "node:path";
230552
+ import { join as join28 } from "node:path";
230427
230553
  import Database3 from "better-sqlite3";
230428
230554
  var BASE3 = ".ancha/playgrounds";
230429
230555
  function runId(value5) {
@@ -230471,9 +230597,9 @@ var AdmissionStore = class {
230471
230597
  async withDb(fn) {
230472
230598
  const relative26 = `${BASE3}/ownership.sqlite`;
230473
230599
  await preflightFiles(this.workspace, [relative26, `${relative26}-journal`, `${relative26}-wal`, `${relative26}-shm`].map((relativePath) => ({ relativePath, content: "" })));
230474
- await mkdir14(join27(this.workspace, BASE3), { recursive: true, mode: 448 });
230475
- await chmod4(join27(this.workspace, BASE3), 448);
230476
- const db3 = new Database3(join27(this.workspace, relative26));
230600
+ await mkdir14(join28(this.workspace, BASE3), { recursive: true, mode: 448 });
230601
+ await chmod4(join28(this.workspace, BASE3), 448);
230602
+ const db3 = new Database3(join28(this.workspace, relative26));
230477
230603
  try {
230478
230604
  db3.pragma("busy_timeout = 5000");
230479
230605
  db3.exec(`CREATE TABLE IF NOT EXISTS lease (singleton INTEGER PRIMARY KEY CHECK(singleton = 1), token TEXT NOT NULL, runId TEXT NOT NULL, pid INTEGER NOT NULL, birth TEXT NOT NULL);
@@ -230481,7 +230607,7 @@ var AdmissionStore = class {
230481
230607
  CREATE TABLE IF NOT EXISTS submissions (key TEXT PRIMARY KEY, signature TEXT NOT NULL, runId TEXT NOT NULL);
230482
230608
  CREATE TABLE IF NOT EXISTS orphans (runId TEXT PRIMARY KEY);`);
230483
230609
  ensureAdmissionSchema(db3);
230484
- await chmod4(join27(this.workspace, relative26), 384);
230610
+ await chmod4(join28(this.workspace, relative26), 384);
230485
230611
  return fn(db3);
230486
230612
  } finally {
230487
230613
  db3.close();
@@ -230661,14 +230787,14 @@ init_src();
230661
230787
  import { createHash as createHash60, randomUUID as randomUUID8 } from "node:crypto";
230662
230788
  import { execFile as execFile6 } from "node:child_process";
230663
230789
  import { promisify as promisify6 } from "node:util";
230664
- import { readFile as readFile16, readdir as readdir4, realpath as realpath8, rename as rename4, rm as rm5, stat as stat7, lstat as lstat6, writeFile as writeFile12 } from "node:fs/promises";
230665
- import { join as join29, resolve as resolve22 } from "node:path";
230790
+ import { readFile as readFile17, readdir as readdir4, realpath as realpath8, rename as rename4, rm as rm5, stat as stat7, lstat as lstat6, writeFile as writeFile12 } from "node:fs/promises";
230791
+ import { join as join30, resolve as resolve22 } from "node:path";
230666
230792
  init_config();
230667
230793
  init_assets();
230668
230794
 
230669
230795
  // backend/src/console/catalog.ts
230670
- import { readFile as readFile14, realpath as realpath6, stat as stat6 } from "node:fs/promises";
230671
- import { join as join28, resolve as resolve20 } from "node:path";
230796
+ import { readFile as readFile15, realpath as realpath6, stat as stat6 } from "node:fs/promises";
230797
+ import { join as join29, resolve as resolve20 } from "node:path";
230672
230798
  import { fileURLToPath as fileURLToPath3 } from "node:url";
230673
230799
  var import_yaml6 = __toESM(require_dist(), 1);
230674
230800
  init_src();
@@ -230677,9 +230803,9 @@ init_scenes();
230677
230803
  init_config();
230678
230804
  async function safeRead(root3, path7, max = 2e6) {
230679
230805
  await preflightFiles(root3, [{ relativePath: path7, content: "" }]);
230680
- const file3 = join28(root3, path7);
230806
+ const file3 = join29(root3, path7);
230681
230807
  if ((await stat6(file3)).size > max) throw new AnchaError("USAGE", "file exceeds the console display limit");
230682
- return readFile14(file3, "utf8");
230808
+ return readFile15(file3, "utf8");
230683
230809
  }
230684
230810
  function parseDefinition(yaml) {
230685
230811
  const doc = (0, import_yaml6.parseDocument)(yaml);
@@ -230706,7 +230832,7 @@ var ScenarioCatalog = class {
230706
230832
  const add = async (root3, path7, origin) => {
230707
230833
  try {
230708
230834
  const yaml = await safeRead(root3, path7);
230709
- const absolute2 = await realpath6(join28(root3, path7));
230835
+ const absolute2 = await realpath6(join29(root3, path7));
230710
230836
  if (seen.has(absolute2)) return;
230711
230837
  seen.add(absolute2);
230712
230838
  const scene2 = parseDefinition(yaml);
@@ -230788,7 +230914,7 @@ init_policy();
230788
230914
 
230789
230915
  // backend/src/execution/provider.ts
230790
230916
  init_src();
230791
- import { lstat as lstat5, readFile as readFile15, realpath as realpath7 } from "node:fs/promises";
230917
+ import { lstat as lstat5, readFile as readFile16, realpath as realpath7 } from "node:fs/promises";
230792
230918
  import { isAbsolute as isAbsolute7, relative as relative10, resolve as resolve21 } from "node:path";
230793
230919
  var providerDetails = {
230794
230920
  openrouter: { key: "OPENROUTER_API_KEY", modelVariable: "OPENROUTER_MODEL", host: "openrouter.ai", baseVariable: "OPENROUTER_BASE_URL", baseUrl: "https://openrouter.ai/api/v1" },
@@ -230835,7 +230961,7 @@ async function readApprovedOpenRouterKey(workspace4) {
230835
230961
  const actual = await realpath7(path7);
230836
230962
  if (actual !== path7 || actual !== resolve21(root3, ".ancha/openrouter.env")) return void 0;
230837
230963
  if (fileStat.size > 16384) return void 0;
230838
- const contents = await readFile15(path7, "utf8");
230964
+ const contents = await readFile16(path7, "utf8");
230839
230965
  const keys5 = contents.split(/\r?\n/).flatMap((line2) => {
230840
230966
  const match3 = /^\s*OPENROUTER_API_KEY\s*=\s*(.*?)\s*$/.exec(line2);
230841
230967
  if (!match3) return [];
@@ -230932,9 +231058,9 @@ async function identifyCode(cwd) {
230932
231058
  const content2 = createHash60("sha256");
230933
231059
  let bytes3 = 0;
230934
231060
  for (const file3 of files2) {
230935
- const path7 = join29(cwd, file3), info = await lstat6(path7);
231061
+ const path7 = join30(cwd, file3), info = await lstat6(path7);
230936
231062
  if (!info.isFile() || (bytes3 += info.size) > 2e7) throw new Error("source scope incomplete");
230937
- content2.update(file3).update("\0").update(await readFile16(path7)).update("\0");
231063
+ content2.update(file3).update("\0").update(await readFile17(path7)).update("\0");
230938
231064
  }
230939
231065
  const sourceHash = content2.digest("hex");
230940
231066
  return { ...git, sourceFiles: files2.length, codeCoverage: git ? "tracked-and-source" : "source-files", mutable: true, fingerprint: hash5({ git, sourceHash }) };
@@ -230958,7 +231084,7 @@ var AgentRegistry = class {
230958
231084
  if (configured === void 0) parsed4.execution = parseExecutionPolicy(options4.defaultExecution);
230959
231085
  }
230960
231086
  const name5 = parsed4.name.trim().toLowerCase();
230961
- for (const file3 of (await readdir4(join29(this.workspace, ".ancha/agents")).catch((e) => {
231087
+ for (const file3 of (await readdir4(join30(this.workspace, ".ancha/agents")).catch((e) => {
230962
231088
  if (e.code === "ENOENT") return [];
230963
231089
  throw e;
230964
231090
  })).filter((f2) => /^agent_[a-f0-9-]{36}\.json$/.test(f2))) {
@@ -231011,11 +231137,11 @@ var AgentRegistry = class {
231011
231137
  const path7 = `.ancha/agents/${id14}.json`, temporary = `.ancha/agents/${id14}.${randomUUID8()}.tmp`;
231012
231138
  await preflightFiles(this.workspace, [{ relativePath: path7, content: "" }, { relativePath: temporary, content: "" }]);
231013
231139
  try {
231014
- await writeFile12(join29(this.workspace, temporary), JSON.stringify(saved, null, 2) + "\n", { flag: "wx", mode: 384 });
231140
+ await writeFile12(join30(this.workspace, temporary), JSON.stringify(saved, null, 2) + "\n", { flag: "wx", mode: 384 });
231015
231141
  await preflightFiles(this.workspace, [{ relativePath: path7, content: "" }]);
231016
- await rename4(join29(this.workspace, temporary), join29(this.workspace, path7));
231142
+ await rename4(join30(this.workspace, temporary), join30(this.workspace, path7));
231017
231143
  } finally {
231018
- await rm5(join29(this.workspace, temporary), { force: true });
231144
+ await rm5(join30(this.workspace, temporary), { force: true });
231019
231145
  }
231020
231146
  return this.get(id14);
231021
231147
  }
@@ -231051,7 +231177,7 @@ var AgentRegistry = class {
231051
231177
  async withVerification(profile) {
231052
231178
  const dir2 = `.ancha/agent-verifications/${profile.id}`;
231053
231179
  await preflightFiles(this.workspace, [{ relativePath: `${dir2}/probe.json`, content: "" }]);
231054
- const files2 = await readdir4(join29(this.workspace, dir2)).catch((e) => {
231180
+ const files2 = await readdir4(join30(this.workspace, dir2)).catch((e) => {
231055
231181
  if (e.code === "ENOENT") return [];
231056
231182
  throw e;
231057
231183
  });
@@ -231068,7 +231194,7 @@ var AgentRegistry = class {
231068
231194
  }
231069
231195
  async ids() {
231070
231196
  await preflightFiles(this.workspace, [{ relativePath: ".ancha/agents/probe.json", content: "" }]);
231071
- const files2 = await readdir4(join29(this.workspace, ".ancha/agents")).catch((e) => {
231197
+ const files2 = await readdir4(join30(this.workspace, ".ancha/agents")).catch((e) => {
231072
231198
  if (e.code === "ENOENT") return [];
231073
231199
  throw e;
231074
231200
  });
@@ -231118,7 +231244,7 @@ var AgentRegistry = class {
231118
231244
  agentId(id14);
231119
231245
  const path7 = `.ancha/agents/${id14}.json`;
231120
231246
  await preflightFiles(this.workspace, [{ relativePath: path7, content: "" }]);
231121
- await rm5(join29(this.workspace, path7), { force: true });
231247
+ await rm5(join30(this.workspace, path7), { force: true });
231122
231248
  return { removed: true };
231123
231249
  }
231124
231250
  };
@@ -231179,7 +231305,7 @@ init_src();
231179
231305
  import { createHash as createHash61, randomUUID as randomUUID10 } from "node:crypto";
231180
231306
  import { execFileSync as execFileSync2 } from "node:child_process";
231181
231307
  import { chmod as chmod5, mkdir as mkdir15, readdir as readdir5, rename as rename5, rm as rm6, writeFile as writeFile13 } from "node:fs/promises";
231182
- import { dirname as dirname12, join as join30 } from "node:path";
231308
+ import { dirname as dirname12, join as join31 } from "node:path";
231183
231309
  import Database4 from "better-sqlite3";
231184
231310
  init_assets();
231185
231311
  var BASE4 = ".ancha/playgrounds";
@@ -231215,9 +231341,9 @@ var PlaygroundStore = class {
231215
231341
  }
231216
231342
  async initialize() {
231217
231343
  await preflightFiles(this.workspace, ["ownership.sqlite", "ownership.sqlite-journal", "ownership.sqlite-wal", "ownership.sqlite-shm"].map((file3) => ({ relativePath: `${BASE4}/${file3}`, content: "" })));
231218
- await mkdir15(join30(this.workspace, BASE4), { recursive: true, mode: 448 });
231219
- await chmod5(join30(this.workspace, BASE4), 448);
231220
- this.#db = new Database4(join30(this.workspace, BASE4, "ownership.sqlite"));
231344
+ await mkdir15(join31(this.workspace, BASE4), { recursive: true, mode: 448 });
231345
+ await chmod5(join31(this.workspace, BASE4), 448);
231346
+ this.#db = new Database4(join31(this.workspace, BASE4, "ownership.sqlite"));
231221
231347
  this.#db.pragma("busy_timeout = 5000");
231222
231348
  this.#db.exec("CREATE TABLE IF NOT EXISTS lease (singleton INTEGER PRIMARY KEY CHECK(singleton = 1), token TEXT NOT NULL, runId TEXT NOT NULL, pid INTEGER NOT NULL, birth TEXT NOT NULL)");
231223
231349
  this.#db.exec("CREATE TABLE IF NOT EXISTS submissions (key TEXT PRIMARY KEY, signature TEXT NOT NULL, runId TEXT NOT NULL)");
@@ -231228,21 +231354,21 @@ var PlaygroundStore = class {
231228
231354
  this.#db.exec("CREATE TABLE IF NOT EXISTS catalog (kind TEXT NOT NULL, id TEXT NOT NULL, revision INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY(kind,id,revision))");
231229
231355
  this.#db.exec("CREATE TABLE IF NOT EXISTS archived_runs (runId TEXT PRIMARY KEY, archivedAt TEXT NOT NULL)");
231230
231356
  this.#db.exec("CREATE TABLE IF NOT EXISTS legacy_worlds (agentId TEXT PRIMARY KEY, worldId TEXT NOT NULL, sourceFingerprint TEXT NOT NULL)");
231231
- await chmod5(join30(this.workspace, BASE4, "ownership.sqlite"), 384);
231357
+ await chmod5(join31(this.workspace, BASE4, "ownership.sqlite"), 384);
231232
231358
  }
231233
231359
  async write(relative26, value5) {
231234
231360
  const content2 = JSON.stringify(value5) + "\n";
231235
231361
  if (Buffer.byteLength(content2) > 25e6) throw new AnchaError("CONFIG_INVALID", "playground artifact exceeds the 25 MB storage limit");
231236
231362
  const target5 = `${BASE4}/${relative26}`, temporary = `${target5}.${randomUUID10()}.tmp`;
231237
231363
  await preflightFiles(this.workspace, [{ relativePath: target5, content: "" }, { relativePath: temporary, content: "" }]);
231238
- await mkdir15(dirname12(join30(this.workspace, target5)), { recursive: true, mode: 448 });
231239
- await chmod5(dirname12(join30(this.workspace, target5)), 448);
231364
+ await mkdir15(dirname12(join31(this.workspace, target5)), { recursive: true, mode: 448 });
231365
+ await chmod5(dirname12(join31(this.workspace, target5)), 448);
231240
231366
  try {
231241
- await writeFile13(join30(this.workspace, temporary), content2, { flag: "wx", mode: 384 });
231367
+ await writeFile13(join31(this.workspace, temporary), content2, { flag: "wx", mode: 384 });
231242
231368
  await preflightFiles(this.workspace, [{ relativePath: target5, content: "" }]);
231243
- await rename5(join30(this.workspace, temporary), join30(this.workspace, target5));
231369
+ await rename5(join31(this.workspace, temporary), join31(this.workspace, target5));
231244
231370
  } finally {
231245
- await rm6(join30(this.workspace, temporary), { force: true });
231371
+ await rm6(join31(this.workspace, temporary), { force: true });
231246
231372
  }
231247
231373
  }
231248
231374
  async read(relative26) {
@@ -231254,7 +231380,7 @@ var PlaygroundStore = class {
231254
231380
  }
231255
231381
  }
231256
231382
  runDirectory(id14) {
231257
- return join30(this.workspace, BASE4, "runs", requireRunId(id14), "private");
231383
+ return join31(this.workspace, BASE4, "runs", requireRunId(id14), "private");
231258
231384
  }
231259
231385
  async configuration(agentId2) {
231260
231386
  const value5 = await this.read(`configurations/${requireAgentId(agentId2)}.json`);
@@ -231291,7 +231417,7 @@ var PlaygroundStore = class {
231291
231417
  const archived = new Set(this.#db.prepare("SELECT runId FROM archived_runs").all().map((row2) => row2.runId));
231292
231418
  if (agentId2) requireAgentId(agentId2);
231293
231419
  await preflightFiles(this.workspace, [{ relativePath: `${BASE4}/runs/probe.json`, content: "" }]);
231294
- const entries4 = await readdir5(join30(this.workspace, BASE4, "runs")).catch((error65) => {
231420
+ const entries4 = await readdir5(join31(this.workspace, BASE4, "runs")).catch((error65) => {
231295
231421
  if (missing6(error65)) return [];
231296
231422
  throw error65;
231297
231423
  });
@@ -231322,7 +231448,7 @@ var PlaygroundStore = class {
231322
231448
  }
231323
231449
  async stagedRuns() {
231324
231450
  await preflightFiles(this.workspace, [{ relativePath: `${BASE4}/runs/probe.json`, content: "" }]);
231325
- const ids2 = await readdir5(join30(this.workspace, BASE4, "runs")).catch((error65) => {
231451
+ const ids2 = await readdir5(join31(this.workspace, BASE4, "runs")).catch((error65) => {
231326
231452
  if (missing6(error65)) return [];
231327
231453
  throw error65;
231328
231454
  });
@@ -231386,7 +231512,7 @@ var PlaygroundStore = class {
231386
231512
  async migrateConfigurations() {
231387
231513
  await this.init();
231388
231514
  await preflightFiles(this.workspace, [{ relativePath: `${BASE4}/configurations/probe.json`, content: "" }]);
231389
- const names5 = await readdir5(join30(this.workspace, BASE4, "configurations")).catch((error65) => {
231515
+ const names5 = await readdir5(join31(this.workspace, BASE4, "configurations")).catch((error65) => {
231390
231516
  if (missing6(error65)) return [];
231391
231517
  throw error65;
231392
231518
  });
@@ -231958,11 +232084,11 @@ var PlaygroundService = class {
231958
232084
  for (const [index, entry3] of entries4.entries()) {
231959
232085
  for (const [key4, value5] of Object.entries(entry3.resolvedAgent.env)) if (keyName.test(key4) && value5 && !value5.includes("{{")) throw new AnchaError("CONFIG_INVALID", "Use credential references instead of literal keys in agent environment mappings.");
231960
232086
  if (this.#captureSources) {
231961
- const source = join32(this.store.runDirectory(run6.id), "source-" + index);
232087
+ const source = join33(this.store.runDirectory(run6.id), "source-" + index);
231962
232088
  if (entry3.resolvedAgent.execution?.mode !== "container") throw new AnchaError("CONFIG_INVALID", "Managed tasks require container execution.");
231963
- const temporary = await mkdtemp6(join32(tmpdir5(), "ancha-capture-"));
232089
+ const temporary = await mkdtemp6(join33(tmpdir5(), "ancha-capture-"));
231964
232090
  try {
231965
- const staged = join32(temporary, "source");
232091
+ const staged = join33(temporary, "source");
231966
232092
  const image2 = await pinExecutionImage(entry3.resolvedAgent.execution.image);
231967
232093
  entry3.resolvedAgent.execution = { ...entry3.resolvedAgent.execution, image: image2 };
231968
232094
  entry3.saved = { ...entry3.saved, execution: entry3.resolvedAgent.execution };
@@ -231978,11 +232104,11 @@ var PlaygroundService = class {
231978
232104
  await this.store.saveBatch(run6);
231979
232105
  const accepted = await this.#admission.submit({ runId: run6.id, signature: signature2, ...idempotencyKey && { idempotencyKey } });
231980
232106
  if (!accepted.created) {
231981
- await rm8(join32(this.workspace, ".ancha/playgrounds/runs", run6.id), { recursive: true, force: true });
232107
+ await rm8(join33(this.workspace, ".ancha/playgrounds/runs", run6.id), { recursive: true, force: true });
231982
232108
  return this.get(accepted.runId);
231983
232109
  }
231984
232110
  } catch (error65) {
231985
- await rm8(join32(this.workspace, ".ancha/playgrounds/runs", run6.id), { recursive: true, force: true });
232111
+ await rm8(join33(this.workspace, ".ancha/playgrounds/runs", run6.id), { recursive: true, force: true });
231986
232112
  throw error65;
231987
232113
  }
231988
232114
  this.wakeWaiters();
@@ -232084,7 +232210,7 @@ var PlaygroundService = class {
232084
232210
  if (entries4.length > 10 || entries4.length !== (run6.entries?.length ?? 1)) throw new AnchaError("CONFIG_INVALID", "Queued run entries do not match the accepted run.");
232085
232211
  for (const [index, entry3] of entries4.entries()) {
232086
232212
  if (entry3.saved?.id !== (run6.entries?.[index]?.agentId ?? run6.agentId) || entry3.entryId !== run6.entries?.[index]?.id) throw new AnchaError("CONFIG_INVALID", "Queued agent identity does not match the accepted run.");
232087
- if (this.#captureSources && entry3.resolvedAgent?.cwd !== join32(this.store.runDirectory(id14), "source-" + index)) throw new AnchaError("CONFIG_INVALID", "Queued source snapshot is invalid.");
232213
+ if (this.#captureSources && entry3.resolvedAgent?.cwd !== join33(this.store.runDirectory(id14), "source-" + index)) throw new AnchaError("CONFIG_INVALID", "Queued source snapshot is invalid.");
232088
232214
  const compiled2 = compileSandboxConfiguration(entry3.configuration, { ...entry3.people && { people: entry3.people } });
232089
232215
  if (compiled2.fingerprint !== (run6.entries?.[index]?.world.fingerprint ?? run6.fingerprint)) throw new AnchaError("CONFIG_INVALID", "Queued tool data does not match the accepted run.");
232090
232216
  if (JSON.stringify(entry3.people ?? null) !== JSON.stringify((run6.entries?.[index]?.world ?? run6.world)?.people ?? null)) throw new AnchaError("CONFIG_INVALID", "Queued people do not match the accepted run.");
@@ -232142,8 +232268,8 @@ var PlaygroundService = class {
232142
232268
  }
232143
232269
  async discardCapturedSources(id14) {
232144
232270
  await Promise.all([
232145
- ...Array.from({ length: 10 }, (_, index) => rm8(join32(this.store.runDirectory(id14), "source-" + index), { recursive: true, force: true })),
232146
- ...["launch.json", "staging.json"].map((name5) => rm8(join32(this.store.runDirectory(id14), name5), { force: true }))
232271
+ ...Array.from({ length: 10 }, (_, index) => rm8(join33(this.store.runDirectory(id14), "source-" + index), { recursive: true, force: true })),
232272
+ ...["launch.json", "staging.json"].map((name5) => rm8(join33(this.store.runDirectory(id14), name5), { force: true }))
232147
232273
  ]);
232148
232274
  }
232149
232275
  async finishQueued(run6, status5) {
@@ -232374,8 +232500,8 @@ var PlaygroundService = class {
232374
232500
  // packages/cli/src/commands/run.ts
232375
232501
  import { createHash as createHash66 } from "node:crypto";
232376
232502
  import { appendFileSync } from "node:fs";
232377
- import { access as access10, mkdir as mkdir21, readFile as readFile28, writeFile as writeFile20 } from "node:fs/promises";
232378
- import { dirname as dirname20, join as join44, relative as relative12, resolve as resolve32 } from "node:path";
232503
+ import { access as access10, mkdir as mkdir21, readFile as readFile29, writeFile as writeFile20 } from "node:fs/promises";
232504
+ import { dirname as dirname20, join as join45, relative as relative12, resolve as resolve32 } from "node:path";
232379
232505
  init_src();
232380
232506
  init_run_state();
232381
232507
 
@@ -232458,8 +232584,8 @@ init_backend();
232458
232584
  // packages/cli/src/run-upload.ts
232459
232585
  init_src();
232460
232586
  init_credentials();
232461
- import { readFile as readFile19 } from "node:fs/promises";
232462
- import { basename as basename9, join as join33 } from "node:path";
232587
+ import { readFile as readFile20 } from "node:fs/promises";
232588
+ import { basename as basename9, join as join34 } from "node:path";
232463
232589
 
232464
232590
  // packages/cli/src/git-state.ts
232465
232591
  import { execFile as execFile8 } from "node:child_process";
@@ -232488,7 +232614,7 @@ async function uploadWorkspace(ctx, missing8 = { message: "--upload needs a work
232488
232614
  }
232489
232615
  }
232490
232616
  async function uploadRun(ctx, workspace4, run6) {
232491
- const summary = JSON.parse(await readFile19(join33(run6.runDir, "summary.json"), "utf8").catch(() => "{}"));
232617
+ const summary = JSON.parse(await readFile20(join34(run6.runDir, "summary.json"), "utf8").catch(() => "{}"));
232492
232618
  if (summary.source === "pytest") throw new AnchaError("USAGE", "pytest run upload is not supported; records remain local");
232493
232619
  const key4 = await apiKeyFor(workspace4, ctx.io.env);
232494
232620
  if (key4 === void 0 && !isLoopbackUrl(workspace4)) throw authError(workspace4, { keySent: false });
@@ -232570,13 +232696,13 @@ init_src();
232570
232696
  init_report2();
232571
232697
  import { randomUUID as randomUUID14 } from "node:crypto";
232572
232698
  import { mkdir as mkdir18, writeFile as writeFile17 } from "node:fs/promises";
232573
- import { join as join37, resolve as resolve27 } from "node:path";
232699
+ import { join as join38, resolve as resolve27 } from "node:path";
232574
232700
 
232575
232701
  // packages/cli/src/cloud-bundle.ts
232576
232702
  init_src();
232577
- init_baselines();
232578
232703
  import { access as access9 } from "node:fs/promises";
232579
232704
  import { basename as basename10, resolve as resolve26 } from "node:path";
232705
+ init_baselines();
232580
232706
  init_run_store();
232581
232707
  init_config();
232582
232708
  init_report2();
@@ -232608,13 +232734,14 @@ async function cloudBundle(ctx, input4) {
232608
232734
  const configPath = projectPath(cwd, configFile, "the config file");
232609
232735
  const config11 = await ctx.loadConfig();
232610
232736
  const tests = input4.kind === "run" ? await loadTests(cwd, input4.tests) : [];
232737
+ const connectionTools2 = input4.kind === "connect" ? await glob3(config11.scenes, { cwd, absolute: true, onlyFiles: true }).then((paths2) => loadTests(cwd, paths2.sort())).then((found) => [...new Set(found.flatMap((test3) => test3.scene.twins))], () => void 0) : void 0;
232611
232738
  const agent = withLocalEnvironment(resolveRunAgent(config11, cwd, { ...input4.options.agentCommand !== null && { agent: input4.options.agentCommand }, parallel: 1 }).agent, config11);
232612
232739
  for (const test3 of tests) validateAgentEnv(test3.scene, agent);
232613
232740
  for (const name5 of input4.options.allowUnwrapped) {
232614
232741
  if (!tests.some((test3) => test3.scene.tools?.[name5] !== void 0)) throw new AnchaError("USAGE", `--allow-unwrapped ${name5}: no test has a tool named ${name5}`, { hint: "the names are the tools under tools: in the tests" });
232615
232742
  }
232616
232743
  const baseline = input4.compare === void 0 ? void 0 : await pinnedBaseline(ctx, input4.compare, tests, input4.options, input4.cloudSummary);
232617
- const bundle = await buildBundle({ root: cwd, kind: input4.kind, configPath, config: config11, agentName: agentName(cwd), tests, bundleFiles: input4.bundleFiles ?? [], options: input4.options, ...baseline !== void 0 && { baseline } });
232744
+ const bundle = await buildBundle({ root: cwd, kind: input4.kind, configPath, config: config11, agentName: agentName(cwd), tests, ...connectionTools2 !== void 0 && { connectionTools: connectionTools2 }, bundleFiles: input4.bundleFiles ?? [], options: input4.options, ...baseline !== void 0 && { baseline } });
232618
232745
  return { bundle, tests };
232619
232746
  }
232620
232747
 
@@ -232653,7 +232780,7 @@ async function runOnCloud(ctx, ws, run6, signal) {
232653
232780
  try {
232654
232781
  const dir2 = resolve27(ctx.io.cwd, DEFAULT_RUNS_DIR);
232655
232782
  await mkdir18(dir2, { recursive: true });
232656
- await writeFile17(join37(dir2, "latest-cloud"), `${JSON.stringify({ runId: job.id, server: ws.server, submittedAt: (/* @__PURE__ */ new Date()).toISOString() })}
232783
+ await writeFile17(join38(dir2, "latest-cloud"), `${JSON.stringify({ runId: job.id, server: ws.server, submittedAt: (/* @__PURE__ */ new Date()).toISOString() })}
232657
232784
  `);
232658
232785
  } catch {
232659
232786
  }
@@ -232693,8 +232820,8 @@ async function connectOnCloud(ctx, ws, check4, signal) {
232693
232820
  }
232694
232821
 
232695
232822
  // packages/cli/src/commands/internal-cloud.ts
232696
- import { readFile as readFile27, stat as stat9, writeFile as writeFile19 } from "node:fs/promises";
232697
- import { basename as basename12, join as join43, resolve as resolve31 } from "node:path";
232823
+ import { readFile as readFile28, stat as stat9, writeFile as writeFile19 } from "node:fs/promises";
232824
+ import { basename as basename12, join as join44, resolve as resolve31 } from "node:path";
232698
232825
  init_src();
232699
232826
  init_config();
232700
232827
  var cloudModules = {
@@ -232777,8 +232904,8 @@ async function missingCommandEntry(command, cwd) {
232777
232904
  if (!module || !/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/.test(module)) return void 0;
232778
232905
  const roots = [cwd, ...await glob3([".venv/lib*/python*/site-packages"], { cwd, absolute: true, dot: true, onlyDirectories: true })];
232779
232906
  paths2 = roots.flatMap((root3) => {
232780
- const entry3 = join43(root3, ...module.split("."));
232781
- return [`${entry3}.py`, join43(entry3, "__main__.py")];
232907
+ const entry3 = join44(root3, ...module.split("."));
232908
+ return [`${entry3}.py`, join44(entry3, "__main__.py")];
232782
232909
  });
232783
232910
  } else {
232784
232911
  const entry3 = words8[0];
@@ -232825,7 +232952,7 @@ function registerInternalCloud(program2, ctx) {
232825
232952
  program2.command("_cloud-assemble", { hidden: true }).description("assemble a cloud run from its attempts' artifacts in the finalize machine").requiredOption("--input <file>", "the finalize input (FinalizeInput JSON)").requiredOption("--bundle <dir>", "the unpacked input bundle").requiredOption("--artifacts <dir>", "one folder per source attempt id with its unpacked artifact").requiredOption("--out <dir>", "where the run and its archive go").option("--relay <file>", "the workspace relay for model-graded checks ({ baseUrl, token, bootId }, written root-only by the runner)").action(async (opts) => {
232826
232953
  let input4;
232827
232954
  try {
232828
- input4 = JSON.parse(await readFile27(resolve31(ctx.io.cwd, opts.input), "utf8"));
232955
+ input4 = JSON.parse(await readFile28(resolve31(ctx.io.cwd, opts.input), "utf8"));
232829
232956
  } catch (error65) {
232830
232957
  throw new AnchaError("USAGE", `cannot read the finalize input ${opts.input}`, { hint: "pass the FinalizeInput JSON the runner wrote", cause: error65 });
232831
232958
  }
@@ -232833,7 +232960,7 @@ function registerInternalCloud(program2, ctx) {
232833
232960
  if (opts.relay !== void 0) {
232834
232961
  let relay;
232835
232962
  try {
232836
- relay = JSON.parse(await readFile27(resolve31(ctx.io.cwd, opts.relay), "utf8"));
232963
+ relay = JSON.parse(await readFile28(resolve31(ctx.io.cwd, opts.relay), "utf8"));
232837
232964
  } catch (error65) {
232838
232965
  throw new AnchaError("USAGE", `cannot read the relay file ${opts.relay}`, { hint: "pass the relay JSON the runner wrote", cause: error65 });
232839
232966
  }
@@ -233003,7 +233130,7 @@ function registerRun(program2, ctx) {
233003
233130
  };
233004
233131
  for (const s3 of loaded) {
233005
233132
  const added = await completeProduction(resolve32(cwd, s3.path), s3.scene, input4.judge);
233006
- if (added.length) ctx.out.info(`computed production's result for ${added.join(", ")} from ${relative12(cwd, join44(dirname20(resolve32(cwd, s3.path)), "production.jsonl"))}`);
233133
+ if (added.length) ctx.out.info(`computed production's result for ${added.join(", ")} from ${relative12(cwd, join45(dirname20(resolve32(cwd, s3.path)), "production.jsonl"))}`);
233007
233134
  }
233008
233135
  const definition3 = createHash66("sha256").update(JSON.stringify({ scenes: scenes.map((scene2) => sceneFingerprint(scene2)).sort(), agent: agent.mode === "endpoint" ? agent.url : agent.command, trials, seed: opts.seed ?? null, minPassRate, strict: opts.strict ?? false, compare: opts.compare ?? null, detach: opts.detach ?? false, ...realTimeouts !== void 0 && { realTimeouts }, ...[...digests.values()].some((d) => d !== void 0) && { records: Object.fromEntries([...digests].filter(([, d]) => d !== void 0)) } })).digest("hex");
233009
233136
  if (opts.idempotencyKey !== void 0) {
@@ -233085,7 +233212,7 @@ async function runAttempt(ctx, descriptor3, config11, sceneArgs) {
233085
233212
  const access16 = (await cloudModules.relay()).cloudModelAccess(descriptor3.relay);
233086
233213
  const now11 = (/* @__PURE__ */ new Date()).toISOString();
233087
233214
  const state3 = { version: 1, runId: descriptor3.runId, state: "starting", pid: process.pid, startedAt: now11, updatedAt: now11, completedTrials: 0, totalTrials: 1 };
233088
- await mkdir21(join44(descriptor3.outDir, ".status"), { recursive: true });
233215
+ await mkdir21(join45(descriptor3.outDir, ".status"), { recursive: true });
233089
233216
  await saveRunState(descriptor3.outDir, state3);
233090
233217
  await executePreparedRun(ctx, {
233091
233218
  scenes,
@@ -233105,7 +233232,7 @@ async function runAttempt(ctx, descriptor3, config11, sceneArgs) {
233105
233232
  cloudAttempt: true
233106
233233
  }, state3);
233107
233234
  }
233108
- var idempotencyFile = (outDir, key4) => join44(dirname20(outDir), "idempotency", `${createHash66("sha256").update(key4).digest("hex")}.json`);
233235
+ var idempotencyFile = (outDir, key4) => join45(dirname20(outDir), "idempotency", `${createHash66("sha256").update(key4).digest("hex")}.json`);
233109
233236
  async function claimIdempotencyKey(outDir, key4, definition3) {
233110
233237
  if (!/^[\x21-\x7e]{1,200}$/.test(key4)) throw new AnchaError("USAGE", "--idempotency-key takes 1-200 visible ASCII characters", { hint: "e.g. --idempotency-key fix-csv-export-1" });
233111
233238
  const path7 = idempotencyFile(outDir, key4);
@@ -233117,7 +233244,7 @@ async function claimIdempotencyKey(outDir, key4, definition3) {
233117
233244
  } catch (error65) {
233118
233245
  if (error65.code !== "EEXIST") throw error65;
233119
233246
  }
233120
- const previous = JSON.parse(await readFile28(path7, "utf8"));
233247
+ const previous = JSON.parse(await readFile29(path7, "utf8"));
233121
233248
  if (previous.definition !== definition3) throw new AnchaError("USAGE", "this --idempotency-key was used for a different run", { hint: "use a new key for a new run; reuse a key only to retry the same command" });
233122
233249
  if (previous.runId === void 0) throw new AnchaError("SESSION_CONFLICT", "a run with this --idempotency-key is still starting", { hint: "retry in a moment, or use a new key" });
233123
233250
  return previous.runId;
@@ -233163,7 +233290,7 @@ ${uploadHintLine(summary.runId, uploadHint, { out: opts.out })}` : ""}`);
233163
233290
  async function uploadFinished(ctx, input4, runId2) {
233164
233291
  if (input4.upload === void 0) return void 0;
233165
233292
  try {
233166
- return await uploadRun(ctx, input4.upload.workspace, { runId: runId2, runDir: join44(input4.outDir, runId2), ...input4.agent.passEnv !== void 0 && { passEnv: input4.agent.passEnv }, ...input4.agent.inheritEnv && { inheritEnv: true } });
233293
+ return await uploadRun(ctx, input4.upload.workspace, { runId: runId2, runDir: join45(input4.outDir, runId2), ...input4.agent.passEnv !== void 0 && { passEnv: input4.agent.passEnv }, ...input4.agent.inheritEnv && { inheritEnv: true } });
233167
233294
  } catch (error65) {
233168
233295
  const json35 = toErrorJson(error65);
233169
233296
  if (input4.upload.required) {
@@ -233188,7 +233315,7 @@ async function executePreparedRun(ctx, input4, initial, ready3) {
233188
233315
  const backend = await openBackend({ ...input4.serverUrl !== void 0 && { serverUrl: input4.serverUrl }, ...input4.peopleRelay !== void 0 && { peopleRelay: input4.peopleRelay } });
233189
233316
  try {
233190
233317
  const where3 = { ...input4.workspace !== void 0 && { workspace: input4.workspace }, target: input4.agent.execution?.mode === "container" ? "docker" : "local", ...input4.peopleRelay !== void 0 && { modelCredit: "workspace" } };
233191
- const log3 = join44(input4.outDir, initial.runId, "events.ndjson");
233318
+ const log3 = join45(input4.outDir, initial.runId, "events.ndjson");
233192
233319
  const run6 = await executeRun({
233193
233320
  ...input4,
233194
233321
  root: ctx.io.cwd,
@@ -233243,7 +233370,7 @@ async function definition2(ctx, path7) {
233243
233370
  const info = await stat10(absolute2);
233244
233371
  if (!info.isFile()) throw new AnchaError("USAGE", "definition must be a file");
233245
233372
  if (info.size > 2e6) throw new AnchaError("USAGE", "definition file exceeds 2 MB");
233246
- body7 = await readFile29(absolute2, "utf8");
233373
+ body7 = await readFile30(absolute2, "utf8");
233247
233374
  } catch (error65) {
233248
233375
  if (["ENOENT", "EACCES"].includes(error65.code ?? "")) throw new AnchaError("USAGE", "definition file does not exist or cannot be read");
233249
233376
  throw error65;
@@ -233566,7 +233693,7 @@ ${worlds2 === "local" ? loginRunLine(ctx) : "This server override keeps the agen
233566
233693
 
233567
233694
  // packages/cli/src/kit/trace-connection.ts
233568
233695
  var import_yaml9 = __toESM(require_dist(), 1);
233569
- import { readFile as readFile30 } from "node:fs/promises";
233696
+ import { readFile as readFile31 } from "node:fs/promises";
233570
233697
  import { relative as relative13 } from "node:path";
233571
233698
 
233572
233699
  // packages/cli/src/kit/connect.ts
@@ -233850,7 +233977,7 @@ ${guide.snippet}`);
233850
233977
  // packages/cli/src/kit/trace-connection.ts
233851
233978
  init_detect();
233852
233979
  async function traceConnection(cwd, paths2, configured, target5, recordsAdapter, cloud = false) {
233853
- const scenes = await Promise.all(paths2.map(async (path7) => ({ path: relative13(cwd, path7), scene: (0, import_yaml9.parse)(await readFile30(path7, "utf8")) })));
233980
+ const scenes = await Promise.all(paths2.map(async (path7) => ({ path: relative13(cwd, path7), scene: (0, import_yaml9.parse)(await readFile31(path7, "utf8")) })));
233854
233981
  const tools2 = [...new Set(scenes.flatMap(({ scene: scene2 }) => (scene2.twins ?? []).filter((name5) => !(name5 === "slack" && scene2.agent_input === "per_event" && scene2.people?.length))))].map((name5) => ({
233855
233982
  name: name5,
233856
233983
  env: connectionGuide(name5, "ts").env,
@@ -233907,7 +234034,7 @@ async function toolAnswers(runDir, summary, filter4) {
233907
234034
  const out = [];
233908
234035
  for (const scene2 of summary.scenes) for (const { trial } of scene2.trialsDetail) {
233909
234036
  if (filter4.scene !== void 0 && filter4.scene !== scene2.sceneId || filter4.trial !== void 0 && filter4.trial !== trial) continue;
233910
- const text29 = await readFile31(join45(runDir, `trial-${scene2.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
234037
+ const text29 = await readFile32(join46(runDir, `trial-${scene2.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
233911
234038
  const calls2 = projectToolCalls(text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2))).filter((e) => e.service === "tools" && e.path.startsWith("/tools/") && e.response?.source).map((e) => ({ ...e, request: e.request, response: e.response }));
233912
234039
  if (!calls2.length) continue;
233913
234040
  const counts = {};
@@ -233942,7 +234069,7 @@ function renderToolAnswers(answers) {
233942
234069
  }
233943
234070
  var NAMED2 = /* @__PURE__ */ new Set(["model_key", "refused", "outside_host", "unserved", "idle", "no_answer"]);
233944
234071
  async function trialOutcomes(runDir, summary, filter4) {
233945
- const inputs2 = await readFile31(join45(runDir, "inputs.json"), "utf8").then((text29) => JSON.parse(text29), () => ({ cases: [] }));
234072
+ const inputs2 = await readFile32(join46(runDir, "inputs.json"), "utf8").then((text29) => JSON.parse(text29), () => ({ cases: [] }));
233946
234073
  const out = [];
233947
234074
  for (const scene2 of summary.scenes) {
233948
234075
  if (filter4.scene !== void 0 && filter4.scene !== scene2.sceneId) continue;
@@ -233950,16 +234077,16 @@ async function trialOutcomes(runDir, summary, filter4) {
233950
234077
  const answerChecked = checks2.some((check4) => check4 !== null && typeof check4 === "object" && ("answer" in check4 || "judge" in check4));
233951
234078
  for (const detail3 of scene2.trialsDetail) {
233952
234079
  if (detail3.passed || detail3.outcome === "skipped" || detail3.outcome === "xfailed" || filter4.trial !== void 0 && filter4.trial !== detail3.trial) continue;
233953
- const dir2 = join45(runDir, `trial-${scene2.sceneId}-${detail3.trial}`);
233954
- const trace = (await readFile31(join45(dir2, "trace.jsonl"), "utf8").catch(() => "")).split("\n").filter(Boolean).flatMap((line2) => {
234080
+ const dir2 = join46(runDir, `trial-${scene2.sceneId}-${detail3.trial}`);
234081
+ const trace = (await readFile32(join46(dir2, "trace.jsonl"), "utf8").catch(() => "")).split("\n").filter(Boolean).flatMap((line2) => {
233955
234082
  try {
233956
234083
  return [JSON.parse(line2)];
233957
234084
  } catch {
233958
234085
  return [];
233959
234086
  }
233960
234087
  });
233961
- const result = await readFile31(join45(dir2, "result.json"), "utf8").then((text29) => JSON.parse(text29), () => ({}));
233962
- const log3 = (await readFile31(join45(dir2, "agent.log"), "utf8").catch(() => "")).slice(-1e6);
234088
+ const result = await readFile32(join46(dir2, "result.json"), "utf8").then((text29) => JSON.parse(text29), () => ({}));
234089
+ const log3 = (await readFile32(join46(dir2, "agent.log"), "utf8").catch(() => "")).slice(-1e6);
233963
234090
  const { reason: reason2, calls: calls2 } = attemptOutcome(
233964
234091
  { exit: detail3.exit, exitCode: detail3.exitCode, realMs: detail3.realMs, trace, log: log3, ...result.logTail && { logTail: result.logTail }, modelReplies: result.modelReplies },
233965
234092
  { check: "test", answerChecked, target: "local" }
@@ -234087,11 +234214,11 @@ function registerExplain(program2, ctx) {
234087
234214
  const filter4 = { ...opts.scene !== void 0 && { scene: opts.scene }, ...trial !== void 0 && { trial } };
234088
234215
  const gradingWarnings = explainGradingWarnings(summary, filter4);
234089
234216
  const playOuts = explainPlayOuts(summary, filter4);
234090
- const failures = await withWorldEvidence(summary, join45(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), explainFailures(summary, filter4));
234091
- const tools2 = await toolAnswers(join45(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), summary, filter4);
234092
- const outcomes = await trialOutcomes(join45(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), summary, filter4);
234217
+ const failures = await withWorldEvidence(summary, join46(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), explainFailures(summary, filter4));
234218
+ const tools2 = await toolAnswers(join46(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), summary, filter4);
234219
+ const outcomes = await trialOutcomes(join46(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), summary, filter4);
234093
234220
  const out = opts.out === void 0 ? "" : ` --out ${opts.out}`;
234094
- const hasBaseline = await access11(join45(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), "..", "baselines", "before.json")).then(() => true, () => false);
234221
+ const hasBaseline = await access11(join46(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), "..", "baselines", "before.json")).then(() => true, () => false);
234095
234222
  const never2 = agentNeverRan(summary), folded = never2 !== void 0 && !opts.all && opts.scene === void 0 && trial === void 0;
234096
234223
  const next2 = never2 !== void 0 ? retryCommands(summary, { out: nonDefaultOut(ctx.io.cwd, opts.out) }) : summary.source === "pytest" ? [] : summary.verdict === "pass" || summary.verdict === "ungraded" ? [] : hasBaseline ? [`fix the agent`, `ancha run --compare before${out}`] : [`ancha baseline save before --from ${summary.runId}${out}`, "fix the agent", `ancha run --compare before${out}`];
234097
234224
  ctx.out.result(
@@ -234129,7 +234256,7 @@ next: ${next2.join(", then ")}` : ""}`
234129
234256
  if (isCloudId(ref22)) await cachedCloudRun(ctx, ref22, runsDir);
234130
234257
  const summary = await loadRunSummary(ctx.io.cwd, ref22, opts.out);
234131
234258
  if (opts.html || opts.open) {
234132
- const runDir = join45(runsDir, summary.runId), path7 = join45(runDir, "report.html");
234259
+ const runDir = join46(runsDir, summary.runId), path7 = join46(runDir, "report.html");
234133
234260
  const folder2 = relative14(ctx.io.cwd, runDir) || ".";
234134
234261
  const records4 = await readRunRecords(runDir, summary, { folder: folder2, secrets: await bundleSecrets({ cwd: ctx.io.cwd, env: ctx.io.env }) });
234135
234262
  await writeFile21(path7, renderHtmlReport(reportData(summary, records4)));
@@ -234144,7 +234271,7 @@ next: ${next2.join(", then ")}` : ""}`
234144
234271
  // packages/cli/src/commands/replay.ts
234145
234272
  init_src();
234146
234273
  import { appendFileSync as appendFileSync2 } from "node:fs";
234147
- import { join as join47, resolve as resolve36 } from "node:path";
234274
+ import { join as join48, resolve as resolve36 } from "node:path";
234148
234275
  init_backend();
234149
234276
  init_config();
234150
234277
 
@@ -234153,8 +234280,8 @@ init_src();
234153
234280
  init_report2();
234154
234281
  init_run();
234155
234282
  init_run_inputs();
234156
- import { readdir as readdir7, readFile as readFile32 } from "node:fs/promises";
234157
- import { join as join46, resolve as resolve35 } from "node:path";
234283
+ import { readdir as readdir7, readFile as readFile33 } from "node:fs/promises";
234284
+ import { join as join47, resolve as resolve35 } from "node:path";
234158
234285
  var RUN_ID2 = /^[A-Za-z0-9_][\w.-]*$/;
234159
234286
  var TRIAL_DIR = /^trial-[a-z0-9][a-z0-9_-]*-[1-9]\d*$/;
234160
234287
  var HINT = "name an attempt as <run id or latest>/<trial directory>, as it appears under the runs directory, e.g. latest/trial-relay-1";
@@ -234179,20 +234306,20 @@ async function loadReplayAttempt(cwd, ref22, out) {
234179
234306
  const trialDir = ref22.slice(slash + 1);
234180
234307
  if (runId2 === "latest") {
234181
234308
  try {
234182
- runId2 = (await readFile32(join46(runs, "latest"), "utf8")).trim();
234309
+ runId2 = (await readFile33(join47(runs, "latest"), "utf8")).trim();
234183
234310
  } catch (error65) {
234184
234311
  if (missing7(error65)) throw new AnchaError("USAGE", `no runs found in ${out ?? DEFAULT_RUNS_DIR}`, { hint: "run `ancha run` first", cause: error65 });
234185
234312
  throw error65;
234186
234313
  }
234187
234314
  }
234188
234315
  if (!RUN_ID2.test(runId2)) throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint: HINT });
234189
- const runDir = join46(runs, runId2);
234316
+ const runDir = join47(runs, runId2);
234190
234317
  let inputs2;
234191
234318
  try {
234192
- inputs2 = JSON.parse(await readFile32(join46(runDir, "inputs.json"), "utf8"));
234319
+ inputs2 = JSON.parse(await readFile33(join47(runDir, "inputs.json"), "utf8"));
234193
234320
  } catch (error65) {
234194
234321
  if (!missing7(error65)) throw error65;
234195
- const left = await readFile32(join46(runDir, "bundle.json"), "utf8").then((text29) => JSON.parse(text29).omitted?.find((item2) => item2.path === "inputs.json")).catch(() => void 0);
234322
+ const left = await readFile33(join47(runDir, "bundle.json"), "utf8").then((text29) => JSON.parse(text29).omitted?.find((item2) => item2.path === "inputs.json")).catch(() => void 0);
234196
234323
  const mb = (bytes3) => `${(bytes3 / (1024 * 1024)).toFixed(1)} MB`;
234197
234324
  if (left) throw new AnchaError("USAGE", `run ${runId2} came without its inputs.json (${mb(left.bytes)}, past the ${mb(left.cap)} its archive kept), so replay can't rebuild its worlds`, { hint: "a run started with ancha 0.4.14 or later keeps an inputs.json up to 12 MB: run the tests again, then replay the new run", cause: error65 });
234198
234325
  throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint: `see ${out ?? DEFAULT_RUNS_DIR}/`, cause: error65 });
@@ -234203,10 +234330,10 @@ async function loadReplayAttempt(cwd, ref22, out) {
234203
234330
  }
234204
234331
  const found = withSeeds(inputs2.cases ?? []).find((item2) => trialDir.startsWith(`trial-${item2.id}-`) && /^[1-9]\d*$/.test(trialDir.slice(`trial-${item2.id}-`.length)));
234205
234332
  if (!found) throw new AnchaError("USAGE", `run ${runId2} doesn't record the world of ${trialDir}`, { hint: "replay needs a run written by this version of ancha (its inputs.json lists every case)" });
234206
- const dir2 = join46(runDir, trialDir);
234333
+ const dir2 = join47(runDir, trialDir);
234207
234334
  const read7 = async (name5, optional2 = false) => {
234208
234335
  try {
234209
- return await readFile32(join46(dir2, name5), "utf8");
234336
+ return await readFile33(join47(dir2, name5), "utf8");
234210
234337
  } catch (error65) {
234211
234338
  if (missing7(error65) && optional2) return "";
234212
234339
  if (missing7(error65)) throw new AnchaError("USAGE", `attempt ${runId2}/${trialDir} has no ${name5}`, { hint: "it may have been interrupted before its world was captured; replay a finished attempt", cause: error65 });
@@ -234243,7 +234370,7 @@ async function replayAttempt(attempt, opts) {
234243
234370
  ...opts.onEvent !== void 0 && { onEvent: opts.onEvent }
234244
234371
  });
234245
234372
  const trial = run6.results.get(attempt.caseId).trials[0];
234246
- const people4 = JSON.parse(await readFile32(join46(trial.dir, "people-replay.json"), "utf8").catch(() => "null")) ?? { replayed: 0, live: 0, divergence: null };
234373
+ const people4 = JSON.parse(await readFile33(join47(trial.dir, "people-replay.json"), "utf8").catch(() => "null")) ?? { replayed: 0, live: 0, divergence: null };
234247
234374
  const recorded2 = new Map(attempt.checks.map((check4) => [check4.id, check4.passed]));
234248
234375
  return {
234249
234376
  replayOf: attempt.id,
@@ -234334,7 +234461,7 @@ function registerReplay(program2, ctx) {
234334
234461
  const backend = await openBackend({ ...choice5.url !== void 0 && { serverUrl: choice5.url }, ...relay !== void 0 && { peopleRelay: relay } });
234335
234462
  try {
234336
234463
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
234337
- const log3 = join47(outDir, state3.runId, "events.ndjson");
234464
+ const log3 = join48(outDir, state3.runId, "events.ndjson");
234338
234465
  const replay2 = await replayAttempt(attempt, {
234339
234466
  backend,
234340
234467
  agent,
@@ -234356,7 +234483,7 @@ function registerReplay(program2, ctx) {
234356
234483
  ctx.out.event(shown3);
234357
234484
  }
234358
234485
  });
234359
- const run6 = { runId: replay2.runId, dir: join47(outDir, replay2.runId), startedAt, finishedAt: (/* @__PURE__ */ new Date()).toISOString(), results: /* @__PURE__ */ new Map([[attempt.caseId, { scene: attempt.scene, trials: [replay2.trial] }]]) };
234486
+ const run6 = { runId: replay2.runId, dir: join48(outDir, replay2.runId), startedAt, finishedAt: (/* @__PURE__ */ new Date()).toISOString(), results: /* @__PURE__ */ new Map([[attempt.caseId, { scene: attempt.scene, trials: [replay2.trial] }]]) };
234360
234487
  const summary2 = { ...summarize(run6, agentName(ctx.io.cwd), 1, { agentCommand: agent.mode === "endpoint" ? agent.url : agent.command }), ...where3, source: "replay", replayOf: attempt.id };
234361
234488
  await writeSummary(run6, summary2);
234362
234489
  return { replay: replay2, summary: summary2 };
@@ -234390,8 +234517,8 @@ init_src();
234390
234517
  init_report2();
234391
234518
  init_run_store();
234392
234519
  init_run_state();
234393
- import { readFile as readFile33 } from "node:fs/promises";
234394
- import { join as join48, resolve as resolve37 } from "node:path";
234520
+ import { readFile as readFile34 } from "node:fs/promises";
234521
+ import { join as join49, resolve as resolve37 } from "node:path";
234395
234522
  import { setTimeout as sleep12 } from "node:timers/promises";
234396
234523
  function registerStatus(program2, ctx) {
234397
234524
  program2.command("status").description("show a run's lifecycle: a foreground, detached or cloud run; without an id, the workspace's first steps and the next command").argument("[id]", 'run id (run_\u2026, run_cloud_\u2026) or "latest"').option("--out <dir>", "run directory (default: .ancha/runs)").option("--on <target>", "cloud: the workspace's first steps (the same as no id)").action(async (ref22, opts) => {
@@ -234462,12 +234589,12 @@ hint: ${state3.upload.error.hint}` : ""}`);
234462
234589
  const outDir = resolve37(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR);
234463
234590
  const id14 = await resolveRunId(ctx.io.cwd, ref22, opts.out);
234464
234591
  await readRunState(outDir, id14);
234465
- const log3 = join48(outDir, id14, "events.ndjson");
234592
+ const log3 = join49(outDir, id14, "events.ndjson");
234466
234593
  await interruptible(ctx, async (signal) => {
234467
234594
  let printed = 0;
234468
234595
  for (; ; ) {
234469
234596
  const state3 = await readRunState(outDir, id14);
234470
- const lines2 = (await readFile33(log3, "utf8").catch(() => "")).split("\n");
234597
+ const lines2 = (await readFile34(log3, "utf8").catch(() => "")).split("\n");
234471
234598
  if (!terminal(state3)) lines2.pop();
234472
234599
  const complete = lines2.filter(Boolean);
234473
234600
  for (const line2 of complete.slice(printed)) ctx.out.event(JSON.parse(line2));
@@ -234491,8 +234618,8 @@ init_src();
234491
234618
  // packages/cli/src/commands/simulate.ts
234492
234619
  init_src();
234493
234620
  init_backend();
234494
- import { readFile as readFile34 } from "node:fs/promises";
234495
- import { dirname as dirname21, join as join50, resolve as resolve38 } from "node:path";
234621
+ import { readFile as readFile35 } from "node:fs/promises";
234622
+ import { dirname as dirname21, join as join51, resolve as resolve38 } from "node:path";
234496
234623
  init_config();
234497
234624
  init_report2();
234498
234625
  init_run();
@@ -234501,12 +234628,12 @@ init_scenes();
234501
234628
  // packages/cli/src/runner/companion.ts
234502
234629
  init_src();
234503
234630
  import { stat as stat11 } from "node:fs/promises";
234504
- import { join as join49 } from "node:path";
234631
+ import { join as join50 } from "node:path";
234505
234632
  import { createRequire as createRequire3 } from "node:module";
234506
234633
  var shellWord2 = (value5) => `'${value5.replaceAll("'", "'\\''")}'`;
234507
234634
  async function companionCommand(directory, mode) {
234508
234635
  for (const extension2 of ["mjs", "ts"]) {
234509
- const companion = join49(directory, `${mode}.${extension2}`);
234636
+ const companion = join50(directory, `${mode}.${extension2}`);
234510
234637
  try {
234511
234638
  if (!(await stat11(companion)).isFile()) continue;
234512
234639
  } catch (error65) {
@@ -234515,7 +234642,7 @@ async function companionCommand(directory, mode) {
234515
234642
  }
234516
234643
  return [process.execPath, ...extension2 === "ts" ? ["--import", createRequire3(import.meta.url).resolve("tsx")] : [], companion].map(shellWord2).join(" ");
234517
234644
  }
234518
- throw new AnchaError("USAGE", `missing readable companion ${join49(directory, `${mode}.ts`)}`, { hint: `add a sibling ${mode}.ts or ${mode}.mjs next to this test's scene.yaml` });
234645
+ throw new AnchaError("USAGE", `missing readable companion ${join50(directory, `${mode}.ts`)}`, { hint: `add a sibling ${mode}.ts or ${mode}.mjs next to this test's scene.yaml` });
234519
234646
  }
234520
234647
 
234521
234648
  // packages/cli/src/commands/simulate.ts
@@ -234612,7 +234739,7 @@ function registerSimulate(sceneCommand, ctx) {
234612
234739
  timeline: trial.trace,
234613
234740
  checks: trial.checks,
234614
234741
  harnessIssues: trial.harnessIssues,
234615
- state: JSON.parse(await readFile34(join50(trial.dir, "state.json"), "utf8")),
234742
+ state: JSON.parse(await readFile35(join51(trial.dir, "state.json"), "utf8")),
234616
234743
  runId: run6.runId,
234617
234744
  dir: trial.dir
234618
234745
  };
@@ -234631,8 +234758,8 @@ init_scenes();
234631
234758
 
234632
234759
  // packages/cli/src/kit/init.ts
234633
234760
  import { constants as constants10 } from "node:fs";
234634
- import { lstat as lstat9, mkdir as mkdir24, open as open9, readFile as readFile40, rm as rm12, writeFile as writeFile25 } from "node:fs/promises";
234635
- import { join as join55 } from "node:path";
234761
+ import { lstat as lstat9, mkdir as mkdir24, open as open9, readFile as readFile41, rm as rm12, writeFile as writeFile25 } from "node:fs/promises";
234762
+ import { join as join56 } from "node:path";
234636
234763
  import { Writable } from "node:stream";
234637
234764
  var import_yaml17 = __toESM(require_dist(), 1);
234638
234765
  init_src();
@@ -235714,9 +235841,9 @@ function readEvalItems(name5, raw3) {
235714
235841
  }
235715
235842
 
235716
235843
  // packages/cli/src/kit/doctor.ts
235717
- import { mkdtemp as mkdtemp9, readFile as readFile36, rm as rm11 } from "node:fs/promises";
235844
+ import { mkdtemp as mkdtemp9, readFile as readFile37, rm as rm11 } from "node:fs/promises";
235718
235845
  import { tmpdir as tmpdir8 } from "node:os";
235719
- import { join as join52, relative as relative16, resolve as resolve40 } from "node:path";
235846
+ import { join as join53, relative as relative16, resolve as resolve40 } from "node:path";
235720
235847
  var import_yaml13 = __toESM(require_dist(), 1);
235721
235848
  init_src();
235722
235849
  init_backend();
@@ -235729,9 +235856,9 @@ init_scenes();
235729
235856
  init_detect();
235730
235857
  init_run();
235731
235858
  import { randomUUID as randomUUID15 } from "node:crypto";
235732
- import { access as access12, mkdtemp as mkdtemp8, readFile as readFile35, rm as rm10, writeFile as writeFile22 } from "node:fs/promises";
235859
+ import { access as access12, mkdtemp as mkdtemp8, readFile as readFile36, rm as rm10, writeFile as writeFile22 } from "node:fs/promises";
235733
235860
  import { tmpdir as tmpdir7 } from "node:os";
235734
- import { join as join51, relative as relative15 } from "node:path";
235861
+ import { join as join52, relative as relative15 } from "node:path";
235735
235862
  var messages2 = {
235736
235863
  RECORDS_ADAPTER_UNBOUND: "Bind the store in ancha_records.py and call open_store() before creating tools.",
235737
235864
  RECORDS_ADAPTER_LEAK: "Attempt 2 observed attempt 1's diagnostic write.",
@@ -235777,13 +235904,13 @@ async function doctorRecords(opts) {
235777
235904
  const agent = opts.agent;
235778
235905
  const mode = agent.mode === "endpoint" ? "endpoint agent" : agent.taskInput?.kind === "per_event" ? "per_event agent" : agent.taskInput?.kind === "http" ? "HTTP task agent" : void 0;
235779
235906
  if (mode) return { name: "records-adapter", status: "warning", message: `This configuration uses a ${mode}. To verify the records adapter, run ancha doctor with an agent command that completes each attempt in one process.` };
235780
- const directory = await mkdtemp8(join51(tmpdir7(), "ancha-doctor-records-"));
235907
+ const directory = await mkdtemp8(join52(tmpdir7(), "ancha-doctor-records-"));
235781
235908
  const timeout = new AbortController(), timer = setTimeout(() => timeout.abort(), opts.budget);
235782
235909
  const evidence2 = { schemaVersion: 1, groups: [] };
235783
235910
  let result;
235784
235911
  try {
235785
235912
  const language = (await detectProject(agent.cwd)).language;
235786
- const adapter = await access12(join51(agent.cwd, "ancha_records.py")).then(() => true, () => false) || language === "py" ? "ancha_records.py" : "ancha_records.ts";
235913
+ const adapter = await access12(join52(agent.cwd, "ancha_records.py")).then(() => true, () => false) || language === "py" ? "ancha_records.py" : "ancha_records.ts";
235787
235914
  const groups = /* @__PURE__ */ new Map();
235788
235915
  for (const item2 of applicable) {
235789
235916
  const records4 = await recordsFor(item2.path, opts.cwd);
@@ -235791,8 +235918,8 @@ async function doctorRecords(opts) {
235791
235918
  if (!groups.has(key4)) groups.set(key4, { ...item2, ...records4 !== void 0 && { records: records4 } });
235792
235919
  }
235793
235920
  for (const item2 of groups.values()) {
235794
- const inputRecords = item2.records ? (await readFile35(item2.records, "utf8")).split(/\r?\n/).filter((line2) => line2.trim()).length : 0;
235795
- if (!item2.records) await writeFile22(join51(directory, "records.jsonl"), "");
235921
+ const inputRecords = item2.records ? (await readFile36(item2.records, "utf8")).split(/\r?\n/).filter((line2) => line2.trim()).length : 0;
235922
+ if (!item2.records) await writeFile22(join52(directory, "records.jsonl"), "");
235796
235923
  const scene2 = {
235797
235924
  id: item2.scene.id,
235798
235925
  title: item2.scene.title,
@@ -235815,7 +235942,7 @@ async function doctorRecords(opts) {
235815
235942
  recordsDiagnostic: { schemaVersion: 1, token: randomUUID15() },
235816
235943
  outDir: directory,
235817
235944
  root: opts.cwd,
235818
- scenePaths: { [scene2.id]: item2.records ? item2.path : join51(directory, "scene.yaml") },
235945
+ scenePaths: { [scene2.id]: item2.records ? item2.path : join52(directory, "scene.yaml") },
235819
235946
  inheritedEnv: opts.env,
235820
235947
  seed: "doctor-records",
235821
235948
  signal: opts.signal ? AbortSignal.any([timeout.signal, opts.signal]) : timeout.signal
@@ -235952,6 +236079,19 @@ async function uploadAgent(ctx, opts, command = "ancha agent upload") {
235952
236079
  });
235953
236080
  }
235954
236081
  }
236082
+ if (probe?.tools !== void 0) {
236083
+ for (const tool of probe.tools) checks2.push({
236084
+ name: tool.name,
236085
+ status: tool.calls > 0 ? "pass" : "warning",
236086
+ message: tool.calls > 0 ? `${tool.calls} tool call${tool.calls === 1 ? "" : "s"}` : "no call during the check"
236087
+ });
236088
+ if (probe.tools.length === 0) checks2.push({
236089
+ name: "tools",
236090
+ status: "warning",
236091
+ message: "the connection check gave the agent no tools",
236092
+ hint: "name them with ancha init --tools <tools> or the tests' twins"
236093
+ });
236094
+ }
235955
236095
  const onboarding = state3 === "failed" ? void 0 : await getOnboarding(ws).then((value5) => nextFromHere(ctx, value5)).then((next3) => human(next3.at(-1)), () => void 0);
235956
236096
  const next2 = state3 === "failed" ? ["ancha agent upload"] : [onboarding === void 0 || /doctor --on cloud|agent upload/.test(onboarding) ? "ancha run" : onboarding];
235957
236097
  return { report: { ok: state3 !== "failed", checks: checks2, next: next2, cloud: { jobId: detail3.job.id, url: url4, state: state3, ...agent !== void 0 && { agent }, connection: evidence2 } }, exitCode };
@@ -235962,7 +236102,7 @@ async function testsReadAnswer(cwd, scenes) {
235962
236102
  for (const path7 of paths2.slice(0, 1e3)) {
235963
236103
  let doc;
235964
236104
  try {
235965
- doc = (0, import_yaml13.parse)(await readFile36(path7, "utf8"));
236105
+ doc = (0, import_yaml13.parse)(await readFile37(path7, "utf8"));
235966
236106
  } catch {
235967
236107
  continue;
235968
236108
  }
@@ -236046,7 +236186,7 @@ async function doctor(ctx, opts) {
236046
236186
  add({ name: "agent", status: "warning", message: "Agent verification is incomplete (--no-agent); native twin access was not tested", hint: "configure agent.command, then run ancha doctor" });
236047
236187
  } else {
236048
236188
  phase = "agent";
236049
- directory = await mkdtemp9(join52(tmpdir8(), "ancha-doctor-"));
236189
+ directory = await mkdtemp9(join53(tmpdir8(), "ancha-doctor-"));
236050
236190
  const first = loaded[0];
236051
236191
  const scene2 = { ...first.scene, timeout: `${Math.max(1, Math.floor(Math.min(parseDuration(first.scene.timeout), budget2 * first.scene.time_scale)))}ms` };
236052
236192
  const boundedAgent = agent.mode === "endpoint" ? { ...agent, startupTimeoutMs: Math.min(agent.startupTimeoutMs, budget2), idleMs: Math.min(agent.idleMs, budget2) } : agent;
@@ -236152,8 +236292,8 @@ var import_yaml14 = __toESM(require_dist(), 1);
236152
236292
  init_src();
236153
236293
  import { createHash as createHash68 } from "node:crypto";
236154
236294
  import { existsSync as existsSync2 } from "node:fs";
236155
- import { mkdir as mkdir22, readFile as readFile37, writeFile as writeFile23 } from "node:fs/promises";
236156
- import { dirname as dirname22, join as join53, relative as relative17, resolve as resolve41 } from "node:path";
236295
+ import { mkdir as mkdir22, readFile as readFile38, writeFile as writeFile23 } from "node:fs/promises";
236296
+ import { dirname as dirname22, join as join54, relative as relative17, resolve as resolve41 } from "node:path";
236157
236297
  async function model(ctx) {
236158
236298
  const env2 = ctx.io.env;
236159
236299
  if (env2.ANCHA_PEOPLE_BASE_URL && env2.ANCHA_PEOPLE_API_KEY) return { client: gen_exports.openRouterClient({ apiKey: env2.ANCHA_PEOPLE_API_KEY, baseUrl: env2.ANCHA_PEOPLE_BASE_URL, relay: true }), credit: "own" };
@@ -236183,7 +236323,7 @@ async function worldGenDataset(ctx, options4, description2) {
236183
236323
  if (!["s", "m", "l"].includes(size2)) throw new AnchaError("USAGE", `--size must be s, m or l, got ${JSON.stringify(options4.size)}`, { hint: "e.g. --size s" });
236184
236324
  const id14 = options4.id ?? `netsuite-pe-${size2}`;
236185
236325
  if (!/^[a-z0-9-]+$/.test(id14)) throw new AnchaError("USAGE", "--id must match [a-z0-9-]+", { hint: "e.g. --id portfolio-books" });
236186
- const outDir = resolve41(ctx.io.cwd, options4.out ?? "ancha/worlds"), worldPath = join53(outDir, `${id14}.yaml`), evalsPath = join53(dirname22(outDir), "evals", `${id14}.jsonl`);
236326
+ const outDir = resolve41(ctx.io.cwd, options4.out ?? "ancha/worlds"), worldPath = join54(outDir, `${id14}.yaml`), evalsPath = join54(dirname22(outDir), "evals", `${id14}.jsonl`);
236187
236327
  const taken2 = [worldPath, evalsPath].find((path7) => existsSync2(path7));
236188
236328
  if (taken2 && !options4.force) throw exists4(taken2, ctx);
236189
236329
  const { world: world5, evals, counts } = generateNetsuitePe({ size: size2, id: id14, startTime: NETSUITE_PE_START_TIME });
@@ -236220,14 +236360,14 @@ async function worldGen(ctx, description2, options4) {
236220
236360
  if (options4.id !== void 0 && !/^[a-z0-9-]+$/.test(options4.id)) throw new AnchaError("USAGE", "--id must match [a-z0-9-]+", { hint: "e.g. --id acme-support" });
236221
236361
  const outDir = resolve41(ctx.io.cwd, options4.out ?? "ancha/worlds");
236222
236362
  const request2 = { description: description2, id: options4.id ?? null, tools: tools2 ?? null, size: size2, variants, from: options4.from ?? null };
236223
- const keyFile = options4.idempotencyKey === void 0 ? void 0 : join53(ctx.io.cwd, ".ancha", "world-gen", `${createHash68("sha256").update(options4.idempotencyKey).digest("hex").slice(0, 32)}.json`);
236363
+ const keyFile = options4.idempotencyKey === void 0 ? void 0 : join54(ctx.io.cwd, ".ancha", "world-gen", `${createHash68("sha256").update(options4.idempotencyKey).digest("hex").slice(0, 32)}.json`);
236224
236364
  if (keyFile && existsSync2(keyFile)) {
236225
- const saved = JSON.parse(await readFile37(keyFile, "utf8"));
236365
+ const saved = JSON.parse(await readFile38(keyFile, "utf8"));
236226
236366
  if (JSON.stringify(saved.request) !== JSON.stringify(request2)) throw new AnchaError("USAGE", "this --idempotency-key was used with different arguments", { hint: "use a new key for a new request" });
236227
236367
  if (saved.result.files.every((file3) => existsSync2(resolve41(ctx.io.cwd, file3)))) return report4(ctx, { ...saved.result, reused: true });
236228
236368
  }
236229
- const from = options4.from === void 0 ? void 0 : parseWorldFile((0, import_yaml14.parse)(await readFile37(resolve41(ctx.io.cwd, options4.from), "utf8")));
236230
- if (options4.id && !options4.force && existsSync2(join53(outDir, `${options4.id}.yaml`))) throw exists4(join53(outDir, `${options4.id}.yaml`), ctx);
236369
+ const from = options4.from === void 0 ? void 0 : parseWorldFile((0, import_yaml14.parse)(await readFile38(resolve41(ctx.io.cwd, options4.from), "utf8")));
236370
+ if (options4.id && !options4.force && existsSync2(join54(outDir, `${options4.id}.yaml`))) throw exists4(join54(outDir, `${options4.id}.yaml`), ctx);
236231
236371
  const { client: client2, credit } = await model(ctx);
236232
236372
  ctx.out.info(`generating a world from the description (size ${size2}${variants ? `, ${variants} variant${variants === 1 ? "" : "s"}` : ""})`);
236233
236373
  const generated = await gen_exports.generateWorld({
@@ -236240,20 +236380,20 @@ async function worldGen(ctx, description2, options4) {
236240
236380
  ...from && { from },
236241
236381
  onProgress: (line2) => ctx.out.info(` ${line2}`)
236242
236382
  });
236243
- const paths2 = Object.keys(generated.files).map((name5) => join53(outDir, name5));
236383
+ const paths2 = Object.keys(generated.files).map((name5) => join54(outDir, name5));
236244
236384
  const taken2 = paths2.find((path7) => existsSync2(path7));
236245
236385
  if (taken2 && !options4.force) throw exists4(taken2, ctx);
236246
236386
  await mkdir22(outDir, { recursive: true });
236247
- for (const [name5, text29] of Object.entries(generated.files)) await writeFile23(join53(outDir, name5), text29);
236387
+ for (const [name5, text29] of Object.entries(generated.files)) await writeFile23(join54(outDir, name5), text29);
236248
236388
  const rel = (path7) => relative17(ctx.io.cwd, path7) || ".";
236249
- const worldPath = rel(join53(outDir, `${generated.world.id}.yaml`));
236389
+ const worldPath = rel(join54(outDir, `${generated.world.id}.yaml`));
236250
236390
  const result = {
236251
236391
  workspace: `local:${ctx.io.cwd}`,
236252
236392
  id: generated.world.id,
236253
236393
  files: paths2.map(rel),
236254
236394
  world: worldPath,
236255
- record: rel(join53(outDir, `${generated.world.id}.gen.json`)),
236256
- variants: generated.variants.map((variant) => rel(join53(outDir, `${variant.id}.yaml`))),
236395
+ record: rel(join54(outDir, `${generated.world.id}.gen.json`)),
236396
+ variants: generated.variants.map((variant) => rel(join54(outDir, `${variant.id}.yaml`))),
236257
236397
  tools: generated.world.tools,
236258
236398
  people: (generated.world.people ?? []).map((person5) => person5.ref),
236259
236399
  calls: generated.record.calls.length,
@@ -236287,8 +236427,8 @@ var import_yaml16 = __toESM(require_dist(), 1);
236287
236427
  init_src();
236288
236428
  import { createHash as createHash70 } from "node:crypto";
236289
236429
  import { existsSync as existsSync3 } from "node:fs";
236290
- import { mkdir as mkdir23, readFile as readFile38, readdir as readdir8, writeFile as writeFile24 } from "node:fs/promises";
236291
- import { join as join54, relative as relative18, resolve as resolve42 } from "node:path";
236430
+ import { mkdir as mkdir23, readFile as readFile39, readdir as readdir8, writeFile as writeFile24 } from "node:fs/promises";
236431
+ import { join as join55, relative as relative18, resolve as resolve42 } from "node:path";
236292
236432
 
236293
236433
  // backend/src/kit/test-draft.ts
236294
236434
  init_src();
@@ -236691,10 +236831,10 @@ async function chooseWorld(ctx, id14, command = 'ancha test new "<sentence>"') {
236691
236831
  hint: ids2.length === 0 ? 'ancha world gen "<company and scenario>", or ancha init --intent "<\u2026>"' : `${command} --world ${ids2[0]}`
236692
236832
  });
236693
236833
  }
236694
- const path7 = join54(dir2, `${chosen}.yaml`);
236834
+ const path7 = join55(dir2, `${chosen}.yaml`);
236695
236835
  if (!existsSync3(path7)) throw new AnchaError("USAGE", `no world ${chosen} in ancha/worlds`, { hint: ids2.length ? `worlds: ${ids2.join(", ")}` : 'ancha world gen "<company and scenario>"' });
236696
236836
  try {
236697
- return parseWorldFile((0, import_yaml16.parse)(await readFile38(path7, "utf8")));
236837
+ return parseWorldFile((0, import_yaml16.parse)(await readFile39(path7, "utf8")));
236698
236838
  } catch (error65) {
236699
236839
  throw new AnchaError("SCENE_INVALID", `ancha/worlds/${chosen}.yaml: ${error65 instanceof Error ? error65.message : String(error65)}`, { hint: "run `ancha schema world` for the world file format" });
236700
236840
  }
@@ -236727,19 +236867,19 @@ async function testNew(ctx, intent, options4) {
236727
236867
  const world5 = await chooseWorld(ctx, options4.world);
236728
236868
  const outDir = resolve42(ctx.io.cwd, options4.out ?? "ancha/tests");
236729
236869
  const request2 = { intent, world: world5.id, id: options4.id ?? null, out: relative18(ctx.io.cwd, outDir) };
236730
- const keyFile = options4.idempotencyKey === void 0 ? void 0 : join54(ctx.io.cwd, ".ancha", "test-new", `${createHash70("sha256").update(options4.idempotencyKey).digest("hex").slice(0, 32)}.json`);
236870
+ const keyFile = options4.idempotencyKey === void 0 ? void 0 : join55(ctx.io.cwd, ".ancha", "test-new", `${createHash70("sha256").update(options4.idempotencyKey).digest("hex").slice(0, 32)}.json`);
236731
236871
  if (keyFile && existsSync3(keyFile)) {
236732
- const saved = JSON.parse(await readFile38(keyFile, "utf8"));
236872
+ const saved = JSON.parse(await readFile39(keyFile, "utf8"));
236733
236873
  if (JSON.stringify(saved.request) !== JSON.stringify(request2)) throw new AnchaError("USAGE", "this --idempotency-key was used with different arguments", { hint: "use a new key for a new request" });
236734
236874
  if ([saved.result.file, saved.result.record].every((file4) => existsSync3(resolve42(ctx.io.cwd, file4)))) return report5(ctx, { ...saved.result, reused: true });
236735
236875
  }
236736
- if (options4.id && !options4.force && existsSync3(join54(outDir, `${options4.id}.yaml`))) throw exists5(ctx, join54(outDir, `${options4.id}.yaml`));
236876
+ if (options4.id && !options4.force && existsSync3(join55(outDir, `${options4.id}.yaml`))) throw exists5(ctx, join55(outDir, `${options4.id}.yaml`));
236737
236877
  const { client: client2, credit } = await draftingModel(ctx);
236738
236878
  ctx.out.info(`drafting a test for world ${world5.id}`);
236739
236879
  const draft2 = await draftTest({ intent, world: world5, model: client2, ...options4.id && { id: options4.id }, onProgress: (line2) => ctx.out.info(` ${line2}`) });
236740
- const path7 = join54(outDir, `${draft2.test.id}.yaml`), recordPath = join54(outDir, `${draft2.test.id}.gen.json`);
236880
+ const path7 = join55(outDir, `${draft2.test.id}.yaml`), recordPath = join55(outDir, `${draft2.test.id}.gen.json`);
236741
236881
  if (existsSync3(path7) && !options4.force) throw exists5(ctx, path7);
236742
- const before = existsSync3(path7) ? await readFile38(path7, "utf8") : "";
236882
+ const before = existsSync3(path7) ? await readFile39(path7, "utf8") : "";
236743
236883
  const at4 = (/* @__PURE__ */ new Date()).toISOString();
236744
236884
  const yaml = testYaml2({ ...draft2.test, generated: { by: "ancha test new", at: at4, from: intent, record: `${draft2.test.id}.gen.json` } }, intent);
236745
236885
  const cost = Math.round(draft2.calls.reduce((sum6, call4) => sum6 + call4.costUsd, 0) * 1e6) / 1e6;
@@ -236764,7 +236904,7 @@ async function testNew(ctx, intent, options4) {
236764
236904
  ...credit === "workspace" && { modelCredit: "workspace" }
236765
236905
  };
236766
236906
  if (keyFile) {
236767
- await mkdir23(join54(ctx.io.cwd, ".ancha", "test-new"), { recursive: true });
236907
+ await mkdir23(join55(ctx.io.cwd, ".ancha", "test-new"), { recursive: true });
236768
236908
  await writeFile24(keyFile, `${JSON.stringify({ request: request2, result })}
236769
236909
  `);
236770
236910
  }
@@ -236792,11 +236932,11 @@ function registerTestNew(tests, ctx) {
236792
236932
  // packages/cli/src/kit/docs.ts
236793
236933
  init_src();
236794
236934
  init_assets();
236795
- import { readFile as readFile39 } from "node:fs/promises";
236935
+ import { readFile as readFile40 } from "node:fs/promises";
236796
236936
  var DOC_TOPICS = ["setup", "apps", "run", "traces", "explain", "compare", "scenes", "integrations", "cloud", "playgrounds", "cli-quickstart", "tools", "datasets"];
236797
236937
  async function loadDoc(topic = "setup") {
236798
236938
  if (!DOC_TOPICS.includes(topic)) throw new AnchaError("USAGE", `unknown docs topic: ${topic}`, { hint: `available topics: ${DOC_TOPICS.join(", ")}` });
236799
- return { topics: [...DOC_TOPICS], topic, markdown: await readFile39(new URL(`docs/${topic}.md`, assetRoot()), "utf8") };
236939
+ return { topics: [...DOC_TOPICS], topic, markdown: await readFile40(new URL(`docs/${topic}.md`, assetRoot()), "utf8") };
236800
236940
  }
236801
236941
  function registerDocs(program2, ctx) {
236802
236942
  program2.command("docs").description("read the bundled documentation: setup, the run loop, checks, SDK settings and the hosted workspace").argument("[topic]", `available: ${DOC_TOPICS.join(", ")}`).action(async (topic) => {
@@ -236817,13 +236957,13 @@ function step2(ctx) {
236817
236957
  }
236818
236958
  var BEGIN = "<!-- ancha:begin -->";
236819
236959
  var END = "<!-- ancha:end -->";
236820
- var managedSection = () => readFile40(new URL("agents-section.md", assetRoot()), "utf8");
236960
+ var managedSection = () => readFile41(new URL("agents-section.md", assetRoot()), "utf8");
236821
236961
  async function installAgents(cwd) {
236822
- const target5 = join55(cwd, "AGENTS.md");
236962
+ const target5 = join56(cwd, "AGENTS.md");
236823
236963
  const managed = await managedSection();
236824
236964
  let original;
236825
236965
  try {
236826
- original = await readFile40(target5, "utf8");
236966
+ original = await readFile41(target5, "utf8");
236827
236967
  } catch (error65) {
236828
236968
  if (error65.code !== "ENOENT") throw error65;
236829
236969
  const result = await applyScaffold(cwd, [{ relativePath: "AGENTS.md", content: managed }]);
@@ -236845,10 +236985,10 @@ function ignoresAncha(gitignore) {
236845
236985
  return gitignore.split(/\r?\n/).some((line2) => /^(?:\*\*\/|\/)?\.ancha(?:\/|\/\*{1,2})?$/.test(line2.trim()));
236846
236986
  }
236847
236987
  async function ignoreAnchaDirectory(cwd) {
236848
- const target5 = join55(cwd, ".gitignore");
236988
+ const target5 = join56(cwd, ".gitignore");
236849
236989
  let original;
236850
236990
  try {
236851
- original = await readFile40(target5, "utf8");
236991
+ original = await readFile41(target5, "utf8");
236852
236992
  } catch (error65) {
236853
236993
  if (error65.code !== "ENOENT") throw error65;
236854
236994
  const result = await applyScaffold(cwd, [{ relativePath: ".gitignore", content: ".ancha/\n" }]);
@@ -236929,7 +237069,7 @@ ${twins.map((twin) => tasks[twin] ?? `${toolName(twin)}: read its data through t
236929
237069
  }
236930
237070
  var STARTER_FILES = ["scene.yaml", "oracle.mjs", "null.mjs"];
236931
237071
  async function ownStarter(cwd) {
236932
- const read7 = (name5) => readFile40(join55(cwd, "scenes/starter", name5), "utf8").catch(() => void 0);
237072
+ const read7 = (name5) => readFile41(join56(cwd, "scenes/starter", name5), "utf8").catch(() => void 0);
236933
237073
  const scene2 = await read7("scene.yaml");
236934
237074
  if (scene2 === void 0) return void 0;
236935
237075
  let twins;
@@ -236970,7 +237110,7 @@ function netsuiteData(size2) {
236970
237110
  }
236971
237111
  async function rewrite(cwd, relativePath, content2) {
236972
237112
  await preflightFiles(cwd, [{ relativePath, content: "" }]);
236973
- const handle30 = await open9(join55(cwd, relativePath), constants10.O_WRONLY | constants10.O_TRUNC | constants10.O_NOFOLLOW);
237113
+ const handle30 = await open9(join56(cwd, relativePath), constants10.O_WRONLY | constants10.O_TRUNC | constants10.O_NOFOLLOW);
236974
237114
  try {
236975
237115
  await handle30.writeFile(content2);
236976
237116
  } finally {
@@ -236978,7 +237118,7 @@ async function rewrite(cwd, relativePath, content2) {
236978
237118
  }
236979
237119
  }
236980
237120
  async function listTests(cwd, tests) {
236981
- const text29 = await readFile40(join55(cwd, "ancha.yaml"), "utf8");
237121
+ const text29 = await readFile41(join56(cwd, "ancha.yaml"), "utf8");
236982
237122
  let scenes;
236983
237123
  try {
236984
237124
  scenes = parseConfigText(text29).scenes;
@@ -237005,7 +237145,7 @@ async function listTests(cwd, tests) {
237005
237145
  return true;
237006
237146
  }
237007
237147
  async function addExampleSeeds(file3, twins) {
237008
- const doc = (0, import_yaml17.parseDocument)(await readFile40(file3, "utf8"));
237148
+ const doc = (0, import_yaml17.parseDocument)(await readFile41(file3, "utf8"));
237009
237149
  const added = [], skipped = [];
237010
237150
  for (const twin of twins) {
237011
237151
  if (doc.hasIn(["seed", twin])) continue;
@@ -237044,7 +237184,7 @@ function answerLine(task2) {
237044
237184
  if (configured === "done") return "answer: ancha.yaml sets agent.answer: done; only what your agent posts to ANCHA_DONE_URL is its answer";
237045
237185
  if (from === "done" && done !== null) return done.name === "entry" ? `answer: entry() posts what your agent returns to ANCHA_DONE_URL (${where2(done)}); that is its answer` : `answer: your agent posts its answer to ANCHA_DONE_URL (${where2(done)})`;
237046
237186
  if (from === "reply" && configured !== "stdout") return "answer: your agent's HTTP reply is its answer";
237047
- return 'answer: the last block your agent prints on stdout (after its last blank line) is its answer; to give it exactly, POST {"output": ...} to ANCHA_DONE_URL';
237187
+ return 'answer: what your agent prints on stdout is its answer, and its logs go to stderr; to give it exactly, POST {"output": ...} to ANCHA_DONE_URL';
237048
237188
  }
237049
237189
  function netsuiteLine(task2, written) {
237050
237190
  if (task2.netsuite.length === 0) return void 0;
@@ -237077,10 +237217,10 @@ function parseTools(value5) {
237077
237217
  return SUPPORTED_TWINS.filter((twin) => names5.some((name5) => key4(twin) === key4(name5) || key4(toolName(twin)) === key4(name5)));
237078
237218
  }
237079
237219
  async function wireExistingConfig(cwd) {
237080
- const target5 = join55(cwd, "ancha.yaml");
237220
+ const target5 = join56(cwd, "ancha.yaml");
237081
237221
  let text29;
237082
237222
  try {
237083
- text29 = await readFile40(target5, "utf8");
237223
+ text29 = await readFile41(target5, "utf8");
237084
237224
  } catch {
237085
237225
  return void 0;
237086
237226
  }
@@ -237121,7 +237261,7 @@ function registerKit(program2, ctx) {
237121
237261
  throw new AnchaError("CONFIG_INVALID", "init --intent needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login; or run ancha init without --intent" });
237122
237262
  }
237123
237263
  const detection = await detectProject(ctx.io.cwd, opts.agent);
237124
- const configText = await readFile40(join55(ctx.io.cwd, "ancha.yaml"), "utf8").catch(() => void 0);
237264
+ const configText = await readFile41(join56(ctx.io.cwd, "ancha.yaml"), "utf8").catch(() => void 0);
237125
237265
  const configured = configText !== void 0;
237126
237266
  let task2 = configured || detection.agent === null ? void 0 : await taskSetup(ctx.io.cwd, detection.agent, { command: detection.agent });
237127
237267
  const existingConfig = (() => {
@@ -237144,10 +237284,10 @@ function registerKit(program2, ctx) {
237144
237284
  const noStarter = defaultTemplate && (existing2.length > 0 || cloud);
237145
237285
  const starter = opts.template === "starter" && (!noStarter || own2 !== void 0);
237146
237286
  const tests = (await glob3(["scenes/**/scene.yaml", "ancha/tests/**/*.yaml", ...existingConfig?.scenes ?? []], { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).filter((path7) => own2 === void 0 || path7 !== "scenes/starter/scene.yaml");
237147
- const traces = await lstat9(join55(ctx.io.cwd, "traces")).then((stat19) => stat19.isDirectory(), () => false);
237287
+ const traces = await lstat9(join56(ctx.io.cwd, "traces")).then((stat19) => stat19.isDirectory(), () => false);
237148
237288
  const dataSize = data5 === "none" ? void 0 : data5 !== void 0 ? data5.size : used.includes("netsuite") && opts.intent === void 0 && tests.length === 0 && !traces ? "m" : void 0;
237149
237289
  const pe = dataSize === void 0 ? void 0 : netsuiteData(dataSize);
237150
- const existingTwins = await Promise.all(existing2.map((path7) => loadSceneFile(join55(ctx.io.cwd, path7)).then((scene2) => scene2.twins, () => [])));
237290
+ const existingTwins = await Promise.all(existing2.map((path7) => loadSceneFile(join56(ctx.io.cwd, path7)).then((scene2) => scene2.twins, () => [])));
237151
237291
  const mapsNetsuite = task2 !== void 0 && task2.netsuite.length > 0 && opts.template === "starter" && existingTwins.every((list18) => list18.includes("netsuite")) && (!starter || twins.includes("netsuite"));
237152
237292
  const env2 = { ...task2?.wiring?.env, ...mapsNetsuite && Object.fromEntries(task2.netsuite.map((mapping) => [mapping.name, mapping.value])) };
237153
237293
  const agentConfig = detection.agent === null ? void 0 : { command: task2?.wiring?.command ?? detection.agent, ...Object.keys(env2).length > 0 && { env: env2 }, ...task2?.stdin && { input: "stdin" } };
@@ -237159,12 +237299,12 @@ parallel: 3
237159
237299
  min_pass_rate: 1
237160
237300
  ` },
237161
237301
  ...templates.map((file3) => ({ ...file3, relativePath: `scenes/${opts.template}/${file3.relativePath}` })),
237162
- { relativePath: ".claude/skills/ancha/SKILL.md", content: await readFile40(new URL("SKILL.md", assetRoot()), "utf8") },
237302
+ { relativePath: ".claude/skills/ancha/SKILL.md", content: await readFile41(new URL("SKILL.md", assetRoot()), "utf8") },
237163
237303
  ...pe?.files ?? []
237164
237304
  ];
237165
237305
  await preflightFiles(ctx.io.cwd, [...files2, { relativePath: "AGENTS.md", content: "" }, { relativePath: ".gitignore", content: "" }]);
237166
237306
  const updated = [];
237167
- const rewritten = own2 === void 0 ? [] : await Promise.all(files2.filter((file3) => file3.relativePath.startsWith("scenes/starter/")).map(async (file3) => await readFile40(join55(ctx.io.cwd, file3.relativePath), "utf8").catch(() => void 0) === file3.content ? void 0 : file3)).then((list18) => list18.filter((file3) => file3 !== void 0));
237307
+ const rewritten = own2 === void 0 ? [] : await Promise.all(files2.filter((file3) => file3.relativePath.startsWith("scenes/starter/")).map(async (file3) => await readFile41(join56(ctx.io.cwd, file3.relativePath), "utf8").catch(() => void 0) === file3.content ? void 0 : file3)).then((list18) => list18.filter((file3) => file3 !== void 0));
237168
237308
  for (const file3 of rewritten) {
237169
237309
  await rewrite(ctx.io.cwd, file3.relativePath, file3.content);
237170
237310
  updated.push(file3.relativePath);
@@ -237190,7 +237330,7 @@ min_pass_rate: 1
237190
237330
  const tools2 = twins.filter(isGenerated);
237191
237331
  const keyed2 = (suffix) => opts.idempotencyKey === void 0 ? {} : { idempotencyKey: `${opts.idempotencyKey}-${suffix}` };
237192
237332
  const world5 = await worldGen(step2(ctx), opts.intent, { ...used.length > 0 && tools2.length > 0 && { tools: tools2.join(",") }, ...keyed2("world") });
237193
- notGenerated = await addExampleSeeds(join55(ctx.io.cwd, world5.world), used.filter((twin) => !isGenerated(twin)));
237333
+ notGenerated = await addExampleSeeds(join56(ctx.io.cwd, world5.world), used.filter((twin) => !isGenerated(twin)));
237194
237334
  const test3 = await testNew(step2(ctx), opts.intent, { world: world5.id, ...keyed2("test") });
237195
237335
  generated = { world: { id: world5.id, file: world5.world, people: world5.people, ...notGenerated.added.length > 0 && { exampleData: notGenerated.added } }, test: { id: test3.id, file: test3.file, checks: test3.checks }, ...(world5.modelCredit ?? test3.modelCredit) && { modelCredit: "workspace" } };
237196
237336
  result.created.push(...world5.files, test3.file, test3.record);
@@ -237243,14 +237383,14 @@ function registerSceneNew(scene2, ctx) {
237243
237383
  const prefix2 = `scenes/${id14}`;
237244
237384
  const planned = files2.map((file3) => ({ ...file3, relativePath: `${prefix2}/${file3.relativePath}` }));
237245
237385
  await preflightFiles(ctx.io.cwd, planned);
237246
- const target5 = join55(ctx.io.cwd, prefix2);
237386
+ const target5 = join56(ctx.io.cwd, prefix2);
237247
237387
  try {
237248
237388
  await lstat9(target5);
237249
237389
  throw new AnchaError("USAGE", `scene destination already exists: ${prefix2}`, { hint: "choose another id; existing scene files are preserved" });
237250
237390
  } catch (error65) {
237251
237391
  if (error65.code !== "ENOENT") throw error65;
237252
237392
  }
237253
- await mkdir24(join55(ctx.io.cwd, "scenes"), { recursive: true });
237393
+ await mkdir24(join56(ctx.io.cwd, "scenes"), { recursive: true });
237254
237394
  try {
237255
237395
  await mkdir24(target5);
237256
237396
  } catch (cause) {
@@ -237457,16 +237597,16 @@ import { realpathSync as realpathSync2 } from "node:fs";
237457
237597
  init_src();
237458
237598
  import { randomUUID as randomUUID19 } from "node:crypto";
237459
237599
  import { mkdir as mkdir27, rm as rm16, writeFile as writeFile28 } from "node:fs/promises";
237460
- import { join as join59 } from "node:path";
237600
+ import { join as join60 } from "node:path";
237461
237601
  init_assets();
237462
237602
 
237463
237603
  // backend/src/execution/prepare-agent.ts
237464
237604
  init_src();
237465
237605
  import { execFile as execFile9 } from "node:child_process";
237466
237606
  import { createHash as createHash72, randomUUID as randomUUID17 } from "node:crypto";
237467
- import { mkdir as mkdir26, mkdtemp as mkdtemp10, readFile as readFile42, readdir as readdir10, rename as rename8, rm as rm14, writeFile as writeFile27 } from "node:fs/promises";
237607
+ import { mkdir as mkdir26, mkdtemp as mkdtemp10, readFile as readFile43, readdir as readdir10, rename as rename8, rm as rm14, writeFile as writeFile27 } from "node:fs/promises";
237468
237608
  import { tmpdir as tmpdir9 } from "node:os";
237469
- import { join as join57 } from "node:path";
237609
+ import { join as join58 } from "node:path";
237470
237610
  init_detect();
237471
237611
  init_source();
237472
237612
  init_docker();
@@ -237475,16 +237615,16 @@ init_policy();
237475
237615
 
237476
237616
  // backend/src/execution/runtime-cache.ts
237477
237617
  import { createHash as createHash71, randomUUID as randomUUID16 } from "node:crypto";
237478
- import { mkdir as mkdir25, readFile as readFile41, readdir as readdir9, realpath as realpath11, rename as rename7, rm as rm13, writeFile as writeFile26 } from "node:fs/promises";
237479
- import { join as join56 } from "node:path";
237618
+ import { mkdir as mkdir25, readFile as readFile42, readdir as readdir9, realpath as realpath11, rename as rename7, rm as rm13, writeFile as writeFile26 } from "node:fs/promises";
237619
+ import { join as join57 } from "node:path";
237480
237620
  init_assets();
237481
237621
  async function runtimeCacheKey(source, project13, command, context3) {
237482
237622
  const hash7 = createHash71("sha256").update(JSON.stringify(["verified-runtime-v1", await realpath11(project13), command, context3]));
237483
237623
  async function visit3(path7, prefix2 = "") {
237484
237624
  for (const entry3 of (await readdir9(path7, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
237485
237625
  const relative26 = prefix2 + entry3.name;
237486
- if (entry3.isDirectory()) await visit3(join56(path7, entry3.name), relative26 + "/");
237487
- else hash7.update(relative26).update("\0").update(await readFile41(join56(path7, entry3.name))).update("\0");
237626
+ if (entry3.isDirectory()) await visit3(join57(path7, entry3.name), relative26 + "/");
237627
+ else hash7.update(relative26).update("\0").update(await readFile42(join57(path7, entry3.name))).update("\0");
237488
237628
  }
237489
237629
  }
237490
237630
  await visit3(source);
@@ -237506,17 +237646,17 @@ async function rememberRuntime(workspace4, key4, image2) {
237506
237646
  if (!/^sha256:[a-f0-9]{64}$/.test(image2)) throw new Error("Runtime must be pinned before caching");
237507
237647
  const path7 = cachePath(key4), temporary = `${path7}.${randomUUID16()}.tmp`;
237508
237648
  await preflightFiles(workspace4, [{ relativePath: path7, content: "" }, { relativePath: temporary, content: "" }]);
237509
- await mkdir25(join56(workspace4, ".ancha/agent-runtime-cache"), { recursive: true, mode: 448 });
237649
+ await mkdir25(join57(workspace4, ".ancha/agent-runtime-cache"), { recursive: true, mode: 448 });
237510
237650
  try {
237511
- await writeFile26(join56(workspace4, temporary), JSON.stringify({ version: 1, image: image2 }), { flag: "wx", mode: 384 });
237512
- await rename7(join56(workspace4, temporary), join56(workspace4, path7));
237651
+ await writeFile26(join57(workspace4, temporary), JSON.stringify({ version: 1, image: image2 }), { flag: "wx", mode: 384 });
237652
+ await rename7(join57(workspace4, temporary), join57(workspace4, path7));
237513
237653
  } finally {
237514
- await rm13(join56(workspace4, temporary), { force: true });
237654
+ await rm13(join57(workspace4, temporary), { force: true });
237515
237655
  }
237516
237656
  }
237517
237657
 
237518
237658
  // backend/src/execution/prepare-agent.ts
237519
- var read6 = (directory, file3) => readFile42(join57(directory, file3), "utf8").catch((error65) => {
237659
+ var read6 = (directory, file3) => readFile43(join58(directory, file3), "utf8").catch((error65) => {
237520
237660
  if (error65.code === "ENOENT") return void 0;
237521
237661
  throw error65;
237522
237662
  });
@@ -237609,13 +237749,13 @@ async function prepareAgent(workspace4, agentId2, options4 = {}) {
237609
237749
  const runtime2 = await (options4.runtime ?? executionRuntimeStatus)();
237610
237750
  if (!runtime2.available || !runtime2.context) throw new AnchaError("AGENT_UNREACHABLE", runtime2.message);
237611
237751
  const runDocker = options4.docker ?? ((args, context3, signal) => docker2(args, context3, signal, options4.progress));
237612
- const temporary = await mkdtemp10(join57(tmpdir9(), "ancha-prepare-agent-"));
237752
+ const temporary = await mkdtemp10(join58(tmpdir9(), "ancha-prepare-agent-"));
237613
237753
  const tag3 = `ancha-agent-${agentId2.slice(6)}:${randomUUID17().slice(0, 8)}`;
237614
237754
  const baseTag = tag3 + "-base";
237615
237755
  const tags4 = /* @__PURE__ */ new Set();
237616
237756
  let success2 = false;
237617
237757
  try {
237618
- const source = join57(temporary, "source");
237758
+ const source = join58(temporary, "source");
237619
237759
  options4.progress?.("Copying agent source");
237620
237760
  await stageProject(saved.cwd, resolved.execution?.mode === "container" ? resolved.execution.files : ["."], source);
237621
237761
  const existing2 = resolved.execution?.mode === "container" ? resolved.execution : void 0;
@@ -237651,14 +237791,14 @@ async function prepareAgent(workspace4, agentId2, options4 = {}) {
237651
237791
  async function hashTree(path7, prefix2 = "") {
237652
237792
  for (const entry3 of (await readdir10(path7, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
237653
237793
  const relative26 = prefix2 + entry3.name;
237654
- if (entry3.isDirectory()) await hashTree(join57(path7, entry3.name), relative26 + "/");
237655
- else digest4.update(relative26).update("\0").update(await readFile42(join57(path7, entry3.name))).update("\0");
237794
+ if (entry3.isDirectory()) await hashTree(join58(path7, entry3.name), relative26 + "/");
237795
+ else digest4.update(relative26).update("\0").update(await readFile43(join58(path7, entry3.name))).update("\0");
237656
237796
  }
237657
237797
  }
237658
237798
  await hashTree(source);
237659
237799
  const fingerprint = digest4.digest("hex"), cacheRelative = `.ancha/agent-images/${fingerprint}.json`;
237660
237800
  await preflightFiles(workspace4, [{ relativePath: cacheRelative, content: "" }]);
237661
- const cached3 = await readFile42(join57(workspace4, cacheRelative), "utf8").then((text29) => JSON.parse(text29)).catch(() => void 0);
237801
+ const cached3 = await readFile43(join58(workspace4, cacheRelative), "utf8").then((text29) => JSON.parse(text29)).catch(() => void 0);
237662
237802
  let cachedImage;
237663
237803
  if (cached3?.image && /^sha256:[a-f0-9]{64}$/.test(cached3.image)) {
237664
237804
  try {
@@ -237674,7 +237814,7 @@ async function prepareAgent(workspace4, agentId2, options4 = {}) {
237674
237814
  const agent = await registry2.update(agentId2, { execution: parseExecutionPolicy({ memoryMb: 1024, ...previous2 ?? {}, mode: "container", preparation: "project", image: cachedImage.Id }) });
237675
237815
  return { prepared: true, agent, runtime: plan4.kind, image: cachedImage.Id, reused: true, runtimeKey };
237676
237816
  }
237677
- const dockerfile = join57(temporary, "Dockerfile");
237817
+ const dockerfile = join58(temporary, "Dockerfile");
237678
237818
  await writeFile27(dockerfile, plan4.dockerfile, { mode: 384 });
237679
237819
  options4.progress?.("Installing dependencies in an isolated runtime");
237680
237820
  tags4.add(plan4.custom ? baseTag : tag3);
@@ -237697,14 +237837,14 @@ RUN if [ -d ${quote3(nodeModules)} ] && [ ${quote3(nodeModules)} != '/opt/ancha/
237697
237837
  const previous = resolved.execution?.mode === "container" ? resolved.execution : void 0;
237698
237838
  const policy = parseExecutionPolicy({ memoryMb: 1024, ...previous ?? {}, mode: "container", preparation: "project", image: image2.Id });
237699
237839
  if (JSON.stringify(await registry2.saved(agentId2)) !== JSON.stringify(saved)) invalid33("Agent settings changed while connecting. Connect again with the new settings.");
237700
- await mkdir26(join57(workspace4, ".ancha/agent-images"), { recursive: true });
237840
+ await mkdir26(join58(workspace4, ".ancha/agent-images"), { recursive: true });
237701
237841
  const cacheTemp = cacheRelative + `.${randomUUID17()}.tmp`;
237702
237842
  await preflightFiles(workspace4, [{ relativePath: cacheRelative, content: "" }, { relativePath: cacheTemp, content: "" }]);
237703
237843
  try {
237704
- await writeFile27(join57(workspace4, cacheTemp), JSON.stringify({ image: image2.Id }), { flag: "wx", mode: 384 });
237705
- await rename8(join57(workspace4, cacheTemp), join57(workspace4, cacheRelative));
237844
+ await writeFile27(join58(workspace4, cacheTemp), JSON.stringify({ image: image2.Id }), { flag: "wx", mode: 384 });
237845
+ await rename8(join58(workspace4, cacheTemp), join58(workspace4, cacheRelative));
237706
237846
  } finally {
237707
- await rm14(join57(workspace4, cacheTemp), { force: true });
237847
+ await rm14(join58(workspace4, cacheTemp), { force: true });
237708
237848
  }
237709
237849
  checkSignal(options4.signal);
237710
237850
  if (JSON.stringify(await registry2.saved(agentId2)) !== JSON.stringify(saved)) invalid33("Agent settings changed while connecting. Connect again with the new settings.");
@@ -237728,7 +237868,7 @@ import { execFile as execFile10, spawn as spawn6 } from "node:child_process";
237728
237868
  import { randomUUID as randomUUID18 } from "node:crypto";
237729
237869
  import { mkdtemp as mkdtemp11, rm as rm15 } from "node:fs/promises";
237730
237870
  import { tmpdir as tmpdir10 } from "node:os";
237731
- import { join as join58 } from "node:path";
237871
+ import { join as join59 } from "node:path";
237732
237872
  import { promisify as promisify9 } from "node:util";
237733
237873
  var quote4 = (value5) => `'${value5.replaceAll("'", "'\\''")}'`;
237734
237874
  async function probeAgentConnection(agent, signal, progress2, inheritedEnv = process.env) {
@@ -237738,7 +237878,7 @@ async function probeAgentConnection(agent, signal, progress2, inheritedEnv = pro
237738
237878
  if (!runtime2.available || !runtime2.context) throw new AnchaError("AGENT_UNREACHABLE", runtime2.message);
237739
237879
  const env2 = Object.fromEntries(["PATH", "HOME", "TMPDIR"].flatMap((name5) => process.env[name5] ? [[name5, process.env[name5]]] : []));
237740
237880
  const id14 = `ancha-connect-${randomUUID18()}`, checker = `${id14}-check`;
237741
- const temporary = await mkdtemp11(join58(tmpdir10(), "ancha-connect-"));
237881
+ const temporary = await mkdtemp11(join59(tmpdir10(), "ancha-connect-"));
237742
237882
  const containers = [];
237743
237883
  const children3 = /* @__PURE__ */ new Set();
237744
237884
  function docker3(args, body7, cleanup = false, timeout = 3e4) {
@@ -237770,7 +237910,7 @@ async function probeAgentConnection(agent, signal, progress2, inheritedEnv = pro
237770
237910
  }
237771
237911
  try {
237772
237912
  progress2("starting");
237773
- const source = join58(temporary, "source");
237913
+ const source = join59(temporary, "source");
237774
237914
  const staged = await stageProject(agent.cwd, policy.files, source);
237775
237915
  const workspaceBytes = workspaceSizeBytes(staged.bytes, policy.memoryMb);
237776
237916
  signal.throwIfAborted();
@@ -237920,7 +238060,7 @@ var AgentConnectionService = class {
237920
238060
  return result;
237921
238061
  }
237922
238062
  async start(agentId2) {
237923
- const key4 = join59(this.workspace, this.path(agentId2));
238063
+ const key4 = join60(this.workspace, this.path(agentId2));
237924
238064
  const pending = starting.get(key4);
237925
238065
  if (pending) return pending;
237926
238066
  const promise3 = this.beginStart(agentId2, key4);
@@ -238034,26 +238174,26 @@ var AgentConnectionService = class {
238034
238174
  const finished = (/* @__PURE__ */ new Date()).toISOString();
238035
238175
  Object.assign(value5, { state: "cancelled", phase: "finished", message: "Connect cancelled while queued.", finishedAt: finished, updatedAt: finished });
238036
238176
  delete value5.blockedBy;
238037
- await rm16(join59(this.workspace, request2), { force: true });
238177
+ await rm16(join60(this.workspace, request2), { force: true });
238038
238178
  await this.store.queueConnection(value5.agentId, value5);
238039
238179
  }
238040
238180
  async cancel(agentId2, operationId) {
238041
238181
  const value5 = await this.read(agentId2);
238042
238182
  if (!value5 || value5.id !== operationId) throw new AnchaError("USAGE", "This connection operation is no longer current.");
238043
- const running2 = active2.get(join59(this.workspace, this.path(agentId2)));
238183
+ const running2 = active2.get(join60(this.workspace, this.path(agentId2)));
238044
238184
  if (running2?.id === operationId) {
238045
238185
  running2.controller.abort();
238046
238186
  await running2.done;
238047
238187
  } else if (value5.state === "connecting" || value5.state === "queued") {
238048
238188
  const request2 = `${this.path(agentId2)}.cancel`;
238049
238189
  await preflightFiles(this.workspace, [{ relativePath: request2, content: "" }]);
238050
- await mkdir27(join59(this.workspace, ".ancha/agent-connections"), { recursive: true, mode: 448 });
238051
- await writeFile28(join59(this.workspace, request2), operationId, { mode: 384 });
238190
+ await mkdir27(join60(this.workspace, ".ancha/agent-connections"), { recursive: true, mode: 448 });
238191
+ await writeFile28(join60(this.workspace, request2), operationId, { mode: 384 });
238052
238192
  }
238053
238193
  return this.status(agentId2);
238054
238194
  }
238055
238195
  async close() {
238056
- await Promise.allSettled([...starting.entries()].filter(([key4]) => key4.startsWith(join59(this.workspace, ".ancha/agent-connections/"))).map(([, promise3]) => promise3));
238196
+ await Promise.allSettled([...starting.entries()].filter(([key4]) => key4.startsWith(join60(this.workspace, ".ancha/agent-connections/"))).map(([, promise3]) => promise3));
238057
238197
  const owned2 = [...this.owned].flatMap((key4) => {
238058
238198
  const value5 = active2.get(key4);
238059
238199
  return value5 ? [value5] : [];
@@ -238063,7 +238203,7 @@ var AgentConnectionService = class {
238063
238203
  this.store.close();
238064
238204
  }
238065
238205
  async wait(agentId2) {
238066
- await active2.get(join59(this.workspace, this.path(agentId2)))?.done;
238206
+ await active2.get(join60(this.workspace, this.path(agentId2)))?.done;
238067
238207
  return this.status(agentId2);
238068
238208
  }
238069
238209
  async run(value5, controller, provider) {
@@ -238113,7 +238253,7 @@ var AgentConnectionService = class {
238113
238253
  value5.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
238114
238254
  value5.updatedAt = value5.finishedAt;
238115
238255
  clearInterval(cancellation);
238116
- await rm16(join59(this.workspace, request2), { force: true });
238256
+ await rm16(join60(this.workspace, request2), { force: true });
238117
238257
  await writes2;
238118
238258
  await this.write(value5);
238119
238259
  }
@@ -238127,7 +238267,7 @@ init_backend();
238127
238267
  init_assets();
238128
238268
  import { createServer as createServer6 } from "node:http";
238129
238269
  import { randomBytes as randomBytes8 } from "node:crypto";
238130
- import { readFile as readFile43, realpath as realpath12, stat as stat14 } from "node:fs/promises";
238270
+ import { readFile as readFile44, realpath as realpath12, stat as stat14 } from "node:fs/promises";
238131
238271
  import { isAbsolute as isAbsolute9 } from "node:path";
238132
238272
  import { fileURLToPath as fileURLToPath7 } from "node:url";
238133
238273
 
@@ -238141,7 +238281,7 @@ init_baselines();
238141
238281
  init_assets();
238142
238282
  import { readdir as readdir11, stat as stat13, writeFile as writeFile29, rename as rename9, rm as rm17 } from "node:fs/promises";
238143
238283
  import { createHash as createHash74, randomBytes as randomBytes7 } from "node:crypto";
238144
- import { join as join60 } from "node:path";
238284
+ import { join as join61 } from "node:path";
238145
238285
  import { fileURLToPath as fileURLToPath5 } from "node:url";
238146
238286
 
238147
238287
  // backend/src/connection-report.ts
@@ -238253,7 +238393,7 @@ var ConsoleJobs = class {
238253
238393
  this.catalog = catalog2;
238254
238394
  this.agents = new AgentRegistry(workspace4);
238255
238395
  this.inheritedEnv = inheritedEnv;
238256
- this.outDir = join60(workspace4, ".ancha/runs");
238396
+ this.outDir = join61(workspace4, ".ancha/runs");
238257
238397
  for (const [name5, value5] of Object.entries(inheritedEnv)) if (/key|token|secret|password/i.test(name5) && value5 && value5.length >= 8) this.secrets.push(value5);
238258
238398
  }
238259
238399
  async profiles() {
@@ -238266,7 +238406,7 @@ var ConsoleJobs = class {
238266
238406
  if (config11.agent) result.push({ id: "configured", name: "Workspace agent", detail: "Agent from your ancha.yaml / --config. May use paid services.", available: true, paid: true });
238267
238407
  } catch {
238268
238408
  }
238269
- if (await stat13(join60(this.workspace, "examples/incident-agent/ancha.yaml")).then((s3) => s3.isFile(), () => false)) result.push({ id: "haiku", name: "OpenRouter \xB7 Claude Haiku 5.5", detail: `${INCIDENT_MODEL} \xB7 uses your server-side key \xB7 provider charges apply`, available: true, paid: true });
238409
+ if (await stat13(join61(this.workspace, "examples/incident-agent/ancha.yaml")).then((s3) => s3.isFile(), () => false)) result.push({ id: "haiku", name: "OpenRouter \xB7 Claude Haiku 5.5", detail: `${INCIDENT_MODEL} \xB7 uses your server-side key \xB7 provider charges apply`, available: true, paid: true });
238270
238410
  return [...(await this.agents.listProfiles()).agents.map((a) => ({ id: `agent:${a.id}`, name: a.name, detail: "Your local agent \xB7 uses its configured model and services", available: true, paid: true })), ...result];
238271
238411
  }
238272
238412
  async key() {
@@ -238514,7 +238654,7 @@ var ConsoleJobs = class {
238514
238654
  if (e.code === "ENOENT") return [];
238515
238655
  throw e;
238516
238656
  });
238517
- const status5 = await readdir11(join60(this.outDir, ".status")).catch((e) => {
238657
+ const status5 = await readdir11(join61(this.outDir, ".status")).catch((e) => {
238518
238658
  if (e.code === "ENOENT") return [];
238519
238659
  throw e;
238520
238660
  });
@@ -238552,7 +238692,7 @@ var ConsoleJobs = class {
238552
238692
  const trace = (await safeRead(this.workspace, `${base3}/trace.jsonl`, 12e6)).trim().split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
238553
238693
  const { open: open13 } = await import("node:fs/promises");
238554
238694
  await preflightFiles(this.workspace, [{ relativePath: `${base3}/agent.log`, content: "" }]);
238555
- const handle30 = await open13(join60(this.workspace, `${base3}/agent.log`), "r");
238695
+ const handle30 = await open13(join61(this.workspace, `${base3}/agent.log`), "r");
238556
238696
  let log3 = "";
238557
238697
  try {
238558
238698
  const size2 = (await handle30.stat()).size;
@@ -238634,10 +238774,10 @@ var ConsoleJobs = class {
238634
238774
  const target5 = `.ancha/console-runs/${runId2}.events.json`, temporary = `${target5}.${randomBytes7(8).toString("hex")}.tmp`;
238635
238775
  await preflightFiles(this.workspace, [{ relativePath: target5, content: "" }, { relativePath: temporary, content: "" }]);
238636
238776
  try {
238637
- await writeFile29(join60(this.workspace, temporary), JSON.stringify(publicData(events3, this.secrets)), { flag: "wx", mode: 384 });
238638
- await rename9(join60(this.workspace, temporary), join60(this.workspace, target5));
238777
+ await writeFile29(join61(this.workspace, temporary), JSON.stringify(publicData(events3, this.secrets)), { flag: "wx", mode: 384 });
238778
+ await rename9(join61(this.workspace, temporary), join61(this.workspace, target5));
238639
238779
  } finally {
238640
- await rm17(join60(this.workspace, temporary), { force: true });
238780
+ await rm17(join61(this.workspace, temporary), { force: true });
238641
238781
  }
238642
238782
  }
238643
238783
  async savePublicAttempts(runId2, metadata7, events3, only4) {
@@ -238674,7 +238814,7 @@ var ConsoleJobs = class {
238674
238814
  entry3 = Object.fromEntries(["trial", "passed", "valid", "incomplete", "exit", "exitCode", "realMs", "simMs", "envId", "sessionId", "caseId", "attemptId", "taskDelivery"].filter((key4) => entry3[key4] !== void 0).map((key4) => [key4, entry3[key4]]));
238675
238815
  await preflightFiles(this.workspace, [{ relativePath: `${base3}/agent.log`, content: "" }]);
238676
238816
  const { open: open13 } = await import("node:fs/promises");
238677
- const handle30 = await open13(join60(this.workspace, base3, "agent.log"), "r");
238817
+ const handle30 = await open13(join61(this.workspace, base3, "agent.log"), "r");
238678
238818
  let log3;
238679
238819
  try {
238680
238820
  const size2 = (await handle30.stat()).size, buffer = Buffer.alloc(Math.min(size2, 65536));
@@ -238708,7 +238848,7 @@ init_report2();
238708
238848
  init_src();
238709
238849
  init_assets();
238710
238850
  import { open as open10, readdir as readdir12 } from "node:fs/promises";
238711
- import { join as join61 } from "node:path";
238851
+ import { join as join62 } from "node:path";
238712
238852
  var DISPLAY_LIMIT = "file exceeds the console display limit";
238713
238853
  var FsRunFiles = class {
238714
238854
  workspace;
@@ -238719,7 +238859,7 @@ var FsRunFiles = class {
238719
238859
  }
238720
238860
  async list() {
238721
238861
  await preflightFiles(this.workspace, [{ relativePath: ".ancha/runs/probe.json", content: "" }]);
238722
- const dirs = await readdir12(join61(this.workspace, ".ancha/runs"), { withFileTypes: true }).catch((error65) => {
238862
+ const dirs = await readdir12(join62(this.workspace, ".ancha/runs"), { withFileTypes: true }).catch((error65) => {
238723
238863
  if (error65.code === "ENOENT") return [];
238724
238864
  throw error65;
238725
238865
  });
@@ -238738,7 +238878,7 @@ var FsRunFiles = class {
238738
238878
  await preflightFiles(this.workspace, [{ relativePath: relative26, content: "" }]);
238739
238879
  let handle30;
238740
238880
  try {
238741
- handle30 = await open10(join61(this.workspace, relative26), "r");
238881
+ handle30 = await open10(join62(this.workspace, relative26), "r");
238742
238882
  } catch (error65) {
238743
238883
  if (error65.code === "ENOENT") return void 0;
238744
238884
  throw error65;
@@ -239327,7 +239467,7 @@ init_src();
239327
239467
  init_assets();
239328
239468
  import { randomUUID as randomUUID20 } from "node:crypto";
239329
239469
  import { readdir as readdir13, rm as rm18 } from "node:fs/promises";
239330
- import { join as join62 } from "node:path";
239470
+ import { join as join63 } from "node:path";
239331
239471
  var setupPattern = /^setup_[a-f0-9-]{36}$/;
239332
239472
  var runPattern = /^run_[A-Za-z0-9_-]{1,124}$/;
239333
239473
  function shape4(input4, fields11) {
@@ -239402,7 +239542,7 @@ var SavedTestSetups = class {
239402
239542
  }
239403
239543
  async list() {
239404
239544
  await preflightFiles(this.workspace, [{ relativePath: ".ancha/test-setups/probe.json", content: "" }]);
239405
- const files2 = await readdir13(join62(this.workspace, ".ancha/test-setups")).catch((e) => {
239545
+ const files2 = await readdir13(join63(this.workspace, ".ancha/test-setups")).catch((e) => {
239406
239546
  if (e.code === "ENOENT") return [];
239407
239547
  throw e;
239408
239548
  });
@@ -239424,7 +239564,7 @@ var SavedTestSetups = class {
239424
239564
  async remove(id14) {
239425
239565
  const relativePath = this.path(id14);
239426
239566
  await preflightFiles(this.workspace, [{ relativePath, content: "" }]);
239427
- await rm18(join62(this.workspace, relativePath));
239567
+ await rm18(join63(this.workspace, relativePath));
239428
239568
  return { removed: true };
239429
239569
  }
239430
239570
  };
@@ -239479,12 +239619,12 @@ async function startConsole(opts) {
239479
239619
  const files2 = /* @__PURE__ */ new Map();
239480
239620
  if (opts.assets !== false) {
239481
239621
  const assets = opts.assets ?? fileURLToPath7(new URL("ui/", assetRoot()));
239482
- const html2 = await readFile43(`${assets}/index.html`).catch(() => {
239622
+ const html2 = await readFile44(`${assets}/index.html`).catch(() => {
239483
239623
  throw new AnchaError("USAGE", "console assets are missing; reinstall Ancha with `npm install -g @ancha-labs/cli`");
239484
239624
  });
239485
239625
  files2.set("/", { body: html2, mime: "text/html; charset=utf-8" });
239486
- files2.set("/app.js", { body: await readFile43(`${assets}/app.js`), mime: "text/javascript; charset=utf-8" });
239487
- files2.set("/style.css", { body: await readFile43(`${assets}/style.css`), mime: "text/css; charset=utf-8" });
239626
+ files2.set("/app.js", { body: await readFile44(`${assets}/app.js`), mime: "text/javascript; charset=utf-8" });
239627
+ files2.set("/style.css", { body: await readFile44(`${assets}/style.css`), mime: "text/css; charset=utf-8" });
239488
239628
  }
239489
239629
  const backend = opts.backend ?? await openBackend();
239490
239630
  const catalog2 = new ScenarioCatalog(workspace4, opts.configPath);
@@ -240044,7 +240184,7 @@ init_backend();
240044
240184
 
240045
240185
  // packages/cli/src/commands/test-import.ts
240046
240186
  import { existsSync as existsSync4 } from "node:fs";
240047
- import { access as access13, mkdir as mkdir28, readFile as readFile44, writeFile as writeFile30 } from "node:fs/promises";
240187
+ import { access as access13, mkdir as mkdir28, readFile as readFile45, writeFile as writeFile30 } from "node:fs/promises";
240048
240188
  import { basename as basename13, dirname as dirname23, extname as extname2, isAbsolute as isAbsolute10, relative as relative19, resolve as resolve44 } from "node:path";
240049
240189
  init_src();
240050
240190
  var EXAMPLE = `
@@ -240075,7 +240215,7 @@ async function testImport(ctx, file3, options4) {
240075
240215
  }
240076
240216
  let text29, encoding;
240077
240217
  try {
240078
- ({ text: text29, encoding } = decodeEvalText(await readFile44(path7)));
240218
+ ({ text: text29, encoding } = decodeEvalText(await readFile45(path7)));
240079
240219
  } catch (error65) {
240080
240220
  throw new AnchaError("USAGE", `cannot read ${file3}: ${error65.code === "ENOENT" ? "no such file" : error65 instanceof Error ? error65.message : String(error65)}`, { hint: "ancha test import <evals file> --world <id>" });
240081
240221
  }
@@ -240098,7 +240238,7 @@ ${skipped.slice(0, 10).map((s3) => `item ${s3.item}: ${s3.reason}`).join("\n")}`
240098
240238
  const tests = [];
240099
240239
  for (const test3 of imported2.tests) {
240100
240240
  const target5 = resolve44(ctx.io.cwd, test3.path);
240101
- const before = existsSync4(target5) ? await readFile44(target5, "utf8") : void 0;
240241
+ const before = existsSync4(target5) ? await readFile45(target5, "utf8") : void 0;
240102
240242
  const status5 = before === void 0 ? "written" : before === test3.yaml ? "unchanged" : !editedSinceImport(before) ? "updated" : options4.force ? "written" : "kept";
240103
240243
  if (status5 === "written" || status5 === "updated") {
240104
240244
  await mkdir28(dirname23(target5), { recursive: true });
@@ -240392,7 +240532,7 @@ Run again with ancha test run ${saved.id}`);
240392
240532
  // packages/cli/src/commands/sandbox.ts
240393
240533
  var import_yaml18 = __toESM(require_dist(), 1);
240394
240534
  init_src();
240395
- import { readFile as readFile45 } from "node:fs/promises";
240535
+ import { readFile as readFile46 } from "node:fs/promises";
240396
240536
  import { resolve as resolve46 } from "node:path";
240397
240537
  init_backend();
240398
240538
  function tools(value5) {
@@ -240439,7 +240579,7 @@ Use --json to export this configuration.`);
240439
240579
  if ([opts.tools, opts.preset, opts.definition].filter(Boolean).length > 1) throw new AnchaError("USAGE", "choose --tools, --preset or --definition");
240440
240580
  let input4;
240441
240581
  if (opts.definition) {
240442
- const doc = (0, import_yaml18.parseDocument)(await readFile45(resolve46(ctx.io.cwd, opts.definition), "utf8"));
240582
+ const doc = (0, import_yaml18.parseDocument)(await readFile46(resolve46(ctx.io.cwd, opts.definition), "utf8"));
240443
240583
  if (doc.errors.length) throw new AnchaError("CONFIG_INVALID", doc.errors.map((error65) => error65.message).join("; "));
240444
240584
  input4 = doc.toJS({ maxAliasCount: 100 });
240445
240585
  if (opts.name && input4 && typeof input4 === "object" && !Array.isArray(input4)) input4 = { ...input4, name: opts.name };
@@ -257042,14 +257182,14 @@ init_src();
257042
257182
  init_backend();
257043
257183
  import { fork as fork2 } from "node:child_process";
257044
257184
  import { randomBytes as randomBytes9 } from "node:crypto";
257045
- import { mkdir as mkdir29, open as open11, readFile as readFile46, rename as rename10, rm as rm19, stat as stat15, writeFile as writeFile31 } from "node:fs/promises";
257185
+ import { mkdir as mkdir29, open as open11, readFile as readFile47, rename as rename10, rm as rm19, stat as stat15, writeFile as writeFile31 } from "node:fs/promises";
257046
257186
  import { createRequire as createRequire5 } from "node:module";
257047
- import { join as join63 } from "node:path";
257187
+ import { join as join64 } from "node:path";
257048
257188
  var WORLD_SERVER_IDLE_MS = 10 * 6e4;
257049
257189
  var SERVER_FILE = "world-server.json";
257050
257190
  var ENVS_FILE = "world-envs.json";
257051
257191
  var LOCK_FILE = "world-server.lock";
257052
- var dir = (cwd) => join63(cwd, ".ancha");
257192
+ var dir = (cwd) => join64(cwd, ".ancha");
257053
257193
  async function writePrivate(path7, value5) {
257054
257194
  const temporary = `${path7}.${process.pid}.tmp`;
257055
257195
  await writeFile31(temporary, `${JSON.stringify(value5, null, 2)}
@@ -257058,7 +257198,7 @@ async function writePrivate(path7, value5) {
257058
257198
  }
257059
257199
  async function readJson2(path7) {
257060
257200
  try {
257061
- return JSON.parse(await readFile46(path7, "utf8"));
257201
+ return JSON.parse(await readFile47(path7, "utf8"));
257062
257202
  } catch {
257063
257203
  return void 0;
257064
257204
  }
@@ -257077,7 +257217,7 @@ async function alive3(server) {
257077
257217
  }
257078
257218
  }
257079
257219
  async function withLock(cwd, work) {
257080
- const path7 = join63(dir(cwd), LOCK_FILE);
257220
+ const path7 = join64(dir(cwd), LOCK_FILE);
257081
257221
  for (let attempt = 0; ; attempt++) {
257082
257222
  try {
257083
257223
  await (await open11(path7, "wx", 384)).close();
@@ -257101,7 +257241,7 @@ async function withLock(cwd, work) {
257101
257241
  }
257102
257242
  async function localWorldServer(cwd) {
257103
257243
  await mkdir29(dir(cwd), { recursive: true });
257104
- const path7 = join63(dir(cwd), SERVER_FILE);
257244
+ const path7 = join64(dir(cwd), SERVER_FILE);
257105
257245
  const current = await readJson2(path7);
257106
257246
  if (current?.version === CLI_VERSION && await alive3(current)) return current;
257107
257247
  return withLock(cwd, async () => {
@@ -257115,7 +257255,7 @@ async function localWorldServer(cwd) {
257115
257255
  });
257116
257256
  }
257117
257257
  async function runningWorldServer(cwd) {
257118
- const server = await readJson2(join63(dir(cwd), SERVER_FILE));
257258
+ const server = await readJson2(join64(dir(cwd), SERVER_FILE));
257119
257259
  return server !== void 0 && await alive3(server) ? server : void 0;
257120
257260
  }
257121
257261
  function startWorldServer(cwd, controlToken) {
@@ -257159,17 +257299,17 @@ function startWorldServer(cwd, controlToken) {
257159
257299
  }
257160
257300
  async function recordWorld(cwd, envId, record28) {
257161
257301
  await mkdir29(dir(cwd), { recursive: true });
257162
- const path7 = join63(dir(cwd), ENVS_FILE);
257302
+ const path7 = join64(dir(cwd), ENVS_FILE);
257163
257303
  const all9 = await readJson2(path7) ?? {};
257164
257304
  for (const [id14, entry3] of Object.entries(all9)) if (Date.now() - Date.parse(entry3.createdAt) > 864e5) delete all9[id14];
257165
257305
  all9[envId] = record28;
257166
257306
  await writePrivate(path7, all9);
257167
257307
  }
257168
257308
  async function worldRecord(cwd, envId) {
257169
- return (await readJson2(join63(dir(cwd), ENVS_FILE)))?.[envId];
257309
+ return (await readJson2(join64(dir(cwd), ENVS_FILE)))?.[envId];
257170
257310
  }
257171
257311
  async function forgetWorld(cwd, envId) {
257172
- const path7 = join63(dir(cwd), ENVS_FILE);
257312
+ const path7 = join64(dir(cwd), ENVS_FILE);
257173
257313
  const all9 = await readJson2(path7);
257174
257314
  if (all9?.[envId] === void 0) return;
257175
257315
  delete all9[envId];
@@ -257428,7 +257568,7 @@ init_world_image();
257428
257568
  import { execFile as execFile12, spawn as spawn7 } from "node:child_process";
257429
257569
  import { promisify as promisify11 } from "node:util";
257430
257570
  import { access as access14, chmod as chmod7, copyFile as copyFile5, mkdir as mkdir30, writeFile as writeFile32 } from "node:fs/promises";
257431
- import { join as join64 } from "node:path";
257571
+ import { join as join65 } from "node:path";
257432
257572
  var exec7 = promisify11(execFile12);
257433
257573
  var VERSION3 = "0.25.0";
257434
257574
  var exists6 = (path7) => access14(path7).then(() => true, () => false);
@@ -257470,9 +257610,9 @@ async function preparePlaygroundRuntime(workspace4, progress2 = () => {
257470
257610
  "image/package.json",
257471
257611
  "image/Dockerfile"
257472
257612
  ].map((path7) => ({ relativePath: `.ancha/harbor-runtime/${path7}`, content: "" })));
257473
- const runtime2 = join64(workspace4, ".ancha/harbor-runtime");
257613
+ const runtime2 = join65(workspace4, ".ancha/harbor-runtime");
257474
257614
  await mkdir30(runtime2, { recursive: true, mode: 448 });
257475
- const python = join64(runtime2, ".venv/bin/python");
257615
+ const python = join65(runtime2, ".venv/bin/python");
257476
257616
  if (!await exists6(python)) {
257477
257617
  progress2("Preparing the local execution runtime");
257478
257618
  let source;
@@ -257485,7 +257625,7 @@ async function preparePlaygroundRuntime(workspace4, progress2 = () => {
257485
257625
  }
257486
257626
  }
257487
257627
  if (!source) throw new AnchaError("AGENT_UNREACHABLE", "Python 3.12 or newer is needed for local execution.", { hint: "Install Python 3.12, then run ancha execution prepare again." });
257488
- await run5(source, ["-m", "venv", join64(runtime2, ".venv")]);
257628
+ await run5(source, ["-m", "venv", join65(runtime2, ".venv")]);
257489
257629
  }
257490
257630
  let installed2 = "";
257491
257631
  try {
@@ -257503,26 +257643,26 @@ async function preparePlaygroundRuntime(workspace4, progress2 = () => {
257503
257643
  } catch {
257504
257644
  }
257505
257645
  if (!compose2) {
257506
- const plugin = join64(runtime2, "docker-config/cli-plugins/docker-compose");
257646
+ const plugin = join65(runtime2, "docker-config/cli-plugins/docker-compose");
257507
257647
  if (!await exists6(plugin)) {
257508
- const qualified = join64(workspace4, ".ancha/harbor-spike/docker-config/cli-plugins/docker-compose");
257648
+ const qualified = join65(workspace4, ".ancha/harbor-spike/docker-config/cli-plugins/docker-compose");
257509
257649
  if (!await exists6(qualified)) throw new AnchaError("AGENT_UNREACHABLE", "Docker Compose is needed for local execution.", { hint: "Install the Docker Compose plugin, then run ancha execution prepare again." });
257510
- await mkdir30(join64(runtime2, "docker-config/cli-plugins"), { recursive: true, mode: 448 });
257650
+ await mkdir30(join65(runtime2, "docker-config/cli-plugins"), { recursive: true, mode: 448 });
257511
257651
  await copyFile5(qualified, plugin);
257512
257652
  await chmod7(plugin, 448);
257513
257653
  }
257514
257654
  }
257515
257655
  progress2("Preparing the seeded tools");
257516
- const imageDir = join64(runtime2, "image");
257656
+ const imageDir = join65(runtime2, "image");
257517
257657
  await mkdir30(imageDir, { recursive: true, mode: 448 });
257518
257658
  const companion = await packagedCompanion(), worker = await packagedSuiteqlWorker();
257519
257659
  const image2 = worldImageTag(companion, worker);
257520
- await writeFile32(join64(imageDir, "companion.mjs"), companion);
257521
- await writeFile32(join64(imageDir, "suiteql-worker.mjs"), worker);
257522
- await writeFile32(join64(imageDir, "package.json"), WORLD_PACKAGE_JSON);
257523
- await writeFile32(join64(imageDir, "Dockerfile"), WORLD_DOCKERFILE);
257660
+ await writeFile32(join65(imageDir, "companion.mjs"), companion);
257661
+ await writeFile32(join65(imageDir, "suiteql-worker.mjs"), worker);
257662
+ await writeFile32(join65(imageDir, "package.json"), WORLD_PACKAGE_JSON);
257663
+ await writeFile32(join65(imageDir, "Dockerfile"), WORLD_DOCKERFILE);
257524
257664
  await run5("docker", ["--context", docker3.context, "build", "--tag", image2, imageDir]);
257525
- await writeFile32(join64(runtime2, "setup.json"), JSON.stringify({ harbor: VERSION3, image: image2, preparedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", { mode: 384 });
257665
+ await writeFile32(join65(runtime2, "setup.json"), JSON.stringify({ harbor: VERSION3, image: image2, preparedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", { mode: 384 });
257526
257666
  return { available: true, message: "Local playgrounds are ready.", worldImage: image2 };
257527
257667
  }
257528
257668
 
@@ -257560,8 +257700,8 @@ init_src();
257560
257700
  // packages/cli/src/commands/world-import.ts
257561
257701
  init_src();
257562
257702
  import { existsSync as existsSync5 } from "node:fs";
257563
- import { mkdir as mkdir31, readdir as readdir14, readFile as readFile48, stat as stat16, writeFile as writeFile33 } from "node:fs/promises";
257564
- import { extname as extname3, join as join65, relative as relative21, resolve as resolve48 } from "node:path";
257703
+ import { mkdir as mkdir31, readdir as readdir14, readFile as readFile49, stat as stat16, writeFile as writeFile33 } from "node:fs/promises";
257704
+ import { extname as extname3, join as join66, relative as relative21, resolve as resolve48 } from "node:path";
257565
257705
 
257566
257706
  // backend/src/kit/netsuite-import.ts
257567
257707
  init_src();
@@ -258029,7 +258169,7 @@ function realmOf(href2) {
258029
258169
  const m = href2 === void 0 ? null : /^https?:\/\/(\d{4,10})(?:[-_]sb(\d{1,2}))?\.suitetalk\.api\.netsuite\.com/i.exec(href2);
258030
258170
  return m ? `${m[1]}${m[2] ? `_SB${m[2]}` : ""}` : void 0;
258031
258171
  }
258032
- function readFile47(file3, type, notes6) {
258172
+ function readFile48(file3, type, notes6) {
258033
258173
  const text29 = file3.text.replace(/^/, ""), start = text29.trimStart();
258034
258174
  if (!/^[[{]/.test(start)) return readCsv2(file3.path, text29, type, notes6);
258035
258175
  let values2;
@@ -259210,7 +259350,7 @@ function importNetsuite(files2, options4) {
259210
259350
  const notes6 = [], problems = [], read7 = [], type = options4.type === void 0 ? void 0 : canonical6(options4.type);
259211
259351
  let raws = [];
259212
259352
  for (const file3 of files2) {
259213
- let rows33 = readFile47(file3, type, notes6).map((raw3) => ({ ...raw3, type: rowType(raw3) }));
259353
+ let rows33 = readFile48(file3, type, notes6).map((raw3) => ({ ...raw3, type: rowType(raw3) }));
259214
259354
  const untyped = rows33.filter((raw3) => raw3.type === "record" || raw3.type === TRANSACTION || raw3.type === ENTITY2);
259215
259355
  if (untyped.length) problems.push(`${file3.path}: ${untyped.length === 1 ? "a record" : `${untyped.length} records`} with no record type: name the file after its type (customers.csv, invoice.json) or pass --type`);
259216
259356
  rows33 = rows33.filter((raw3) => !untyped.includes(raw3));
@@ -259365,8 +259505,8 @@ async function exportFiles(cwd, path7) {
259365
259505
  const found = [];
259366
259506
  for (const entry3 of (await readdir14(full2, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
259367
259507
  if (entry3.name.startsWith(".")) continue;
259368
- if (entry3.isDirectory()) found.push(...await exportFiles(cwd, join65(full2, entry3.name)));
259369
- else if (FILES.has(extname3(entry3.name).toLowerCase())) found.push(join65(full2, entry3.name));
259508
+ if (entry3.isDirectory()) found.push(...await exportFiles(cwd, join66(full2, entry3.name)));
259509
+ else if (FILES.has(extname3(entry3.name).toLowerCase())) found.push(join66(full2, entry3.name));
259370
259510
  }
259371
259511
  return found;
259372
259512
  }
@@ -259377,11 +259517,11 @@ async function worldImportNetsuite(ctx, paths2, options4) {
259377
259517
  if (options4.start !== void 0 && !(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/.test(options4.start) && !Number.isNaN(Date.parse(options4.start)))) {
259378
259518
  throw new AnchaError("USAGE", `--start must be an ISO 8601 time with a timezone, got ${JSON.stringify(options4.start)}`, { hint: "e.g. --start 2026-11-02T14:00:00Z" });
259379
259519
  }
259380
- const outDir = resolve48(ctx.io.cwd, options4.out), worldPath = join65(outDir, `${options4.id}.yaml`), rel = (path7) => relative21(ctx.io.cwd, path7) || ".";
259520
+ const outDir = resolve48(ctx.io.cwd, options4.out), worldPath = join66(outDir, `${options4.id}.yaml`), rel = (path7) => relative21(ctx.io.cwd, path7) || ".";
259381
259521
  if (existsSync5(worldPath) && !options4.force) throw new AnchaError("USAGE", `${rel(worldPath)} already exists`, { hint: "pass --force to overwrite it, or choose another --id" });
259382
259522
  const names5 = [...new Set((await Promise.all(paths2.map((path7) => exportFiles(ctx.io.cwd, path7)))).flat())];
259383
259523
  if (!names5.length) throw new AnchaError("USAGE", `no export files in ${paths2.join(", ")}`, { hint: "NetSuite exports are .json (REST records, SuiteQL results) and .csv (saved searches)" });
259384
- const files2 = await Promise.all(names5.map(async (name5) => ({ path: rel(name5), text: decodeEvalText(await readFile48(name5)).text })));
259524
+ const files2 = await Promise.all(names5.map(async (name5) => ({ path: rel(name5), text: decodeEvalText(await readFile49(name5)).text })));
259385
259525
  const imported2 = importNetsuite(files2, {
259386
259526
  id: options4.id,
259387
259527
  now: (/* @__PURE__ */ new Date()).toISOString(),
@@ -259472,8 +259612,8 @@ init_privacy();
259472
259612
  init_assets();
259473
259613
  init_report2();
259474
259614
  import { createHash as createHash76, randomBytes as randomBytes10 } from "node:crypto";
259475
- import { lstat as lstat10, mkdir as mkdir32, mkdtemp as mkdtemp12, readFile as readFile49, rename as rename11, rm as rm20, writeFile as writeFile34 } from "node:fs/promises";
259476
- import { dirname as dirname24, join as join66, resolve as resolve49 } from "node:path";
259615
+ import { lstat as lstat10, mkdir as mkdir32, mkdtemp as mkdtemp12, readFile as readFile50, rename as rename11, rm as rm20, writeFile as writeFile34 } from "node:fs/promises";
259616
+ import { dirname as dirname24, join as join67, resolve as resolve49 } from "node:path";
259477
259617
  var object18 = external_exports.record(external_exports.string(), external_exports.unknown());
259478
259618
  var instant = external_exports.string().max(80).refine((value5) => /^\d{4}-\d\d-\d\dT.+(?:Z|[+-]\d\d:\d\d)$/.test(value5) && Number.isFinite(Date.parse(value5)));
259479
259619
  var code3 = external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/);
@@ -259583,7 +259723,7 @@ function artifacts(record28, runDir) {
259583
259723
  evidence: []
259584
259724
  }] : [];
259585
259725
  const realMs = Date.parse(attempt.finishedAt) - Date.parse(attempt.startedAt);
259586
- const trial = { trial: attempt.number, passed: passing(attempt.outcome), valid: attempt.outcome !== "invalid", outcome: attempt.outcome, exit: attempt.outcome === "invalid" ? "invalid" : "exited", exitCode: attempt.outcome === "invalid" ? null : 0, realMs, dir: join66(runDir, base3) };
259726
+ const trial = { trial: attempt.number, passed: passing(attempt.outcome), valid: attempt.outcome !== "invalid", outcome: attempt.outcome, exit: attempt.outcome === "invalid" ? "invalid" : "exited", exitCode: attempt.outcome === "invalid" ? null : 0, realMs, dir: join67(runDir, base3) };
259587
259727
  if (typeof primary3?.simMs === "number") trial.simMs = primary3.simMs;
259588
259728
  scene2.trialsDetail.push(trial);
259589
259729
  for (const check4 of checks2.filter((check5) => !check5.passed)) if (scene2.failures.length < 20) scene2.failures.push({ sceneId, trial: attempt.number, check: check4.id, expected: check4.expected, actual: check4.actual, explanation: check4.explanation, traceExcerpt: [] });
@@ -259635,12 +259775,12 @@ async function recordPytestRun(cwd, input4, env2 = {}) {
259635
259775
  attempts: record28.attempts.map((attempt) => ({ ...attempt, errors: cleanErrors(attempt.errors), worlds: attempt.worlds.map((world5) => redact3(world5, env2)) }))
259636
259776
  };
259637
259777
  const fingerprint = hash6(JSON.stringify(cleaned));
259638
- const outDir = resolve49(cwd, DEFAULT_RUNS_DIR), runDir = join66(outDir, record28.runId), relative26 = `${DEFAULT_RUNS_DIR}/${record28.runId}`;
259778
+ const outDir = resolve49(cwd, DEFAULT_RUNS_DIR), runDir = join67(outDir, record28.runId), relative26 = `${DEFAULT_RUNS_DIR}/${record28.runId}`;
259639
259779
  const result = { runId: record28.runId, runDir, source: "pytest", target: "local", next: [`ancha --local runs show ${record28.runId}`, `ancha --local explain ${record28.runId}`] };
259640
259780
  const exists7 = async () => {
259641
259781
  await preflightFiles(cwd, [{ relativePath: `${relative26}/record.json`, content: "" }]);
259642
259782
  const completed = async () => {
259643
- const text29 = await readFile49(join66(runDir, "record.json"), "utf8");
259783
+ const text29 = await readFile50(join67(runDir, "record.json"), "utf8");
259644
259784
  let previous;
259645
259785
  try {
259646
259786
  previous = JSON.parse(text29);
@@ -259674,11 +259814,11 @@ async function recordPytestRun(cwd, input4, env2 = {}) {
259674
259814
  files2.set("record.json", json34({ version: 1, fingerprint }));
259675
259815
  await mkdir32(outDir, { recursive: true, mode: 448 });
259676
259816
  await preflightFiles(cwd, [{ relativePath: `${relative26}/summary.json`, content: "" }]);
259677
- const staging = await mkdtemp12(join66(outDir, ".pytest-"));
259817
+ const staging = await mkdtemp12(join67(outDir, ".pytest-"));
259678
259818
  try {
259679
259819
  for (const [path7, content2] of files2) {
259680
- await mkdir32(dirname24(join66(staging, path7)), { recursive: true, mode: 448 });
259681
- await writeFile34(join66(staging, path7), content2, { flag: "wx", mode: 384 });
259820
+ await mkdir32(dirname24(join67(staging, path7)), { recursive: true, mode: 448 });
259821
+ await writeFile34(join67(staging, path7), content2, { flag: "wx", mode: 384 });
259682
259822
  }
259683
259823
  await preflightFiles(cwd, [{ relativePath: `${relative26}/summary.json`, content: "" }]);
259684
259824
  try {
@@ -259687,12 +259827,12 @@ async function recordPytestRun(cwd, input4, env2 = {}) {
259687
259827
  if (["EEXIST", "ENOTEMPTY"].includes(error65.code ?? "") && await exists7()) return result;
259688
259828
  throw error65;
259689
259829
  }
259690
- const latest2 = join66(outDir, `.latest-pytest-${randomBytes10(8).toString("hex")}`);
259830
+ const latest2 = join67(outDir, `.latest-pytest-${randomBytes10(8).toString("hex")}`);
259691
259831
  try {
259692
259832
  await writeFile34(latest2, `${record28.runId}
259693
259833
  `, { flag: "wx", mode: 384 });
259694
259834
  await preflightFiles(cwd, [{ relativePath: `${DEFAULT_RUNS_DIR}/latest`, content: "" }]);
259695
- await rename11(latest2, join66(outDir, "latest"));
259835
+ await rename11(latest2, join67(outDir, "latest"));
259696
259836
  } finally {
259697
259837
  await rm20(latest2, { force: true });
259698
259838
  }
@@ -259770,14 +259910,14 @@ ${formatTable(value5.configuration.preset.datasets.map((data5) => [data5.tool, d
259770
259910
  // packages/cli/src/commands/secrets.ts
259771
259911
  var import_yaml19 = __toESM(require_dist(), 1);
259772
259912
  init_src();
259773
- import { readFile as readFile50, writeFile as writeFile35 } from "node:fs/promises";
259913
+ import { readFile as readFile51, writeFile as writeFile35 } from "node:fs/promises";
259774
259914
  import { resolve as resolve51 } from "node:path";
259775
259915
  init_credentials();
259776
259916
  var NAME_RE2 = /^[A-Z][A-Z0-9_]{0,63}$/;
259777
259917
  async function nameInConfig(ctx, names5) {
259778
259918
  const label5 = ctx.globals().config ?? "ancha.yaml", file3 = resolve51(ctx.io.cwd, label5);
259779
259919
  const them = names5.length === 1 ? "it" : "them", list18 = names5.join(", ");
259780
- const text29 = await readFile50(file3, "utf8").catch(() => void 0);
259920
+ const text29 = await readFile51(file3, "utf8").catch(() => void 0);
259781
259921
  if (text29 === void 0) return { passEnvHint: `no ${label5} here: list ${list18} under agent.pass_env in the agent's ${label5} so its cloud runs get ${them}` };
259782
259922
  const doc = (0, import_yaml19.parseDocument)(text29);
259783
259923
  const listed2 = (path7) => {
@@ -259925,7 +260065,7 @@ function anchaConfigSchema() {
259925
260065
  pass_env: { ...strings4, description: "names a local agent inherits from this shell besides the base set; values are never saved" },
259926
260066
  install: { ...string8, minLength: 1, maxLength: 2e3, pattern: "^(?![\\s]*$)[^\\u0000\\r\\n]+$", description: "dependency installation command for a cloud attempt" },
259927
260067
  input: { enum: ["command", "per_event", "stdin"], description: "command: once per attempt; per_event: once per event addressed to the agent; stdin: once per attempt, with the task on its stdin" },
259928
- answer: { enum: ["auto", "done", "stdout", "none"], description: "where the agent's final answer comes from: auto (default) takes what it posts to ANCHA_DONE_URL, else an HTTP reply, else the last block of its stdout; done: only what it posts; stdout: what it posts, else its stdout; none: no answer" },
260068
+ answer: { enum: ["auto", "done", "stdout", "none"], description: "where the agent's final answer comes from: auto (default) takes what it posts to ANCHA_DONE_URL, else an HTTP reply, else what it prints on stdout; done: only what it posts; stdout: what it posts, else its stdout; none: no answer" },
259929
260069
  slack_transport: { enum: ["feed", "http", "socket"] },
259930
260070
  execution: {
259931
260071
  type: "object",
@@ -260183,15 +260323,15 @@ function registerSchema(program2, ctx) {
260183
260323
  // packages/cli/src/commands/runs.ts
260184
260324
  var import_yaml20 = __toESM(require_dist(), 1);
260185
260325
  init_src();
260186
- import { mkdir as mkdir33, readFile as readFile52, writeFile as writeFile36 } from "node:fs/promises";
260187
- import { basename as basename14, join as join68, relative as relative22, resolve as resolve52 } from "node:path";
260326
+ import { mkdir as mkdir33, readFile as readFile53, writeFile as writeFile36 } from "node:fs/promises";
260327
+ import { basename as basename14, join as join69, relative as relative22, resolve as resolve52 } from "node:path";
260188
260328
  init_report2();
260189
260329
  init_run_store();
260190
260330
 
260191
260331
  // backend/src/trace-ir.ts
260192
260332
  init_src();
260193
- import { readFile as readFile51 } from "node:fs/promises";
260194
- import { join as join67 } from "node:path";
260333
+ import { readFile as readFile52 } from "node:fs/promises";
260334
+ import { join as join68 } from "node:path";
260195
260335
  var VENDOR_API_BASES = {
260196
260336
  slack: "https://slack.com",
260197
260337
  github: "https://api.github.com",
@@ -260258,7 +260398,7 @@ function attemptToIr(entries4, traceId, agent, saved) {
260258
260398
  return [{ ir: "ancha.trace/v1", trace_id: traceId, ...agent !== void 0 && { agent }, source: "ancha-run", started_at: entries4[0]?.tSim ?? saved?.scene?.start_time, ...saved?.scene && { test: saved.scene, input: saved.scene.trigger?.input ?? { messages: [{ role: "user", content: saved.scene.task ?? saved.scene.trigger?.task ?? "" }] } }, ...output2?.output !== void 0 && { output: output2.output } }, ...records4];
260259
260399
  }
260260
260400
  async function readAttemptTrace(dir2) {
260261
- const text29 = (await readFile51(join67(dir2, "trace.jsonl"), "utf8")).trim();
260401
+ const text29 = (await readFile52(join68(dir2, "trace.jsonl"), "utf8")).trim();
260262
260402
  return text29 ? text29.split("\n").map((line2) => JSON.parse(line2)) : [];
260263
260403
  }
260264
260404
 
@@ -260289,7 +260429,7 @@ async function testTask(ctx, file3, worldOverride) {
260289
260429
  const path7 = resolve52(ctx.io.cwd, file3);
260290
260430
  let doc;
260291
260431
  try {
260292
- doc = (0, import_yaml20.parse)(await readFile52(path7, "utf8"));
260432
+ doc = (0, import_yaml20.parse)(await readFile53(path7, "utf8"));
260293
260433
  } catch (error65) {
260294
260434
  throw new AnchaError("CONFIG_INVALID", `cannot read ${file3}: ${error65 instanceof Error ? error65.message.split("\n")[0] : String(error65)}`, { hint: "pass a task file (version 2) or a test file (scene.yaml)" });
260295
260435
  }
@@ -260392,8 +260532,8 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
260392
260532
  if (isCloudId(ref22)) throw new AnchaError("USAGE", `${ref22} ran in the cloud and is in the workspace already`, { hint: `ancha runs show ${ref22}` });
260393
260533
  const workspace4 = await uploadWorkspace(ctx);
260394
260534
  const summary = await loadRunSummary(ctx.io.cwd, ref22, options4.out);
260395
- const runDir = join68(resolve52(ctx.io.cwd, options4.out ?? DEFAULT_RUNS_DIR), summary.runId);
260396
- const inputs2 = JSON.parse(await readFile52(join68(runDir, "inputs.json"), "utf8").catch(() => "{}"));
260535
+ const runDir = join69(resolve52(ctx.io.cwd, options4.out ?? DEFAULT_RUNS_DIR), summary.runId);
260536
+ const inputs2 = JSON.parse(await readFile53(join69(runDir, "inputs.json"), "utf8").catch(() => "{}"));
260397
260537
  const passEnv = inputs2.agentEnvironment?.passEnv ?? (await ctx.loadConfig().catch(() => void 0))?.agent?.passEnv ?? [];
260398
260538
  const inheritEnv = inputs2.agentEnvironment?.inheritEnv ?? summary.agentEnvironment?.inheritAll === true;
260399
260539
  const upload4 = await uploadRun(ctx, workspace4, { runId: summary.runId, runDir, passEnv, inheritEnv });
@@ -260403,15 +260543,15 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
260403
260543
  if (ref22 === "latest") ref22 = await latestRunId(ctx.io.cwd, options4.out);
260404
260544
  onThisComputer(ref22);
260405
260545
  const summary = await loadRunSummary(ctx.io.cwd, ref22, options4.out);
260406
- const dest = resolve52(ctx.io.cwd, options4.dest ?? join68(".ancha", "exports", summary.runId));
260546
+ const dest = resolve52(ctx.io.cwd, options4.dest ?? join69(".ancha", "exports", summary.runId));
260407
260547
  await mkdir33(dest, { recursive: true });
260408
- const inputs2 = await readFile52(join68(resolve52(ctx.io.cwd, options4.out ?? DEFAULT_RUNS_DIR), summary.runId, "inputs.json"), "utf8").then((text29) => JSON.parse(text29), () => ({}));
260548
+ const inputs2 = await readFile53(join69(resolve52(ctx.io.cwd, options4.out ?? DEFAULT_RUNS_DIR), summary.runId, "inputs.json"), "utf8").then((text29) => JSON.parse(text29), () => ({}));
260409
260549
  const files2 = [], cases = withSeeds(inputs2.cases ?? []);
260410
260550
  for (const scene2 of summary.scenes) for (const trial of scene2.trialsDetail) {
260411
- const dir2 = resolve52(ctx.io.cwd, trial.dir), name5 = basename14(dir2), file3 = join68(dest, `${name5}.ir.jsonl`);
260551
+ const dir2 = resolve52(ctx.io.cwd, trial.dir), name5 = basename14(dir2), file3 = join69(dest, `${name5}.ir.jsonl`);
260412
260552
  await writeFile36(file3, attemptToIr(await readAttemptTrace(dir2), `${summary.runId}/${name5}`, summary.agent, {
260413
260553
  scene: cases.find((c) => c.id === scene2.sceneId)?.scene,
260414
- checks: await readFile52(join68(dir2, "checks.json"), "utf8").then((text29) => JSON.parse(text29), () => void 0),
260554
+ checks: await readFile53(join69(dir2, "checks.json"), "utf8").then((text29) => JSON.parse(text29), () => void 0),
260415
260555
  outcome: trial.outcome ?? (trial.valid === false ? "invalid" : trial.passed ? "passed" : "failed"),
260416
260556
  exit: trial.exit,
260417
260557
  exitCode: trial.exitCode
@@ -260481,8 +260621,8 @@ next: ancha wait ${id14}`);
260481
260621
 
260482
260622
  // packages/cli/src/commands/traces.ts
260483
260623
  import { createHash as createHash77 } from "node:crypto";
260484
- import { access as access15, readFile as readFile54, mkdir as mkdir34, stat as stat18, writeFile as writeFile37 } from "node:fs/promises";
260485
- import { basename as basename16, dirname as dirname25, join as join69, relative as relative25, resolve as resolve54 } from "node:path";
260624
+ import { access as access15, readFile as readFile55, mkdir as mkdir34, stat as stat18, writeFile as writeFile37 } from "node:fs/promises";
260625
+ import { basename as basename16, dirname as dirname25, join as join70, relative as relative25, resolve as resolve54 } from "node:path";
260486
260626
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
260487
260627
  var import_yaml21 = __toESM(require_dist(), 1);
260488
260628
  init_src();
@@ -260608,7 +260748,7 @@ async function listTraces(source, { limit: limit2, since, name: name5 }, env2, f
260608
260748
  }
260609
260749
 
260610
260750
  // packages/cli/src/trace-files.ts
260611
- import { readFile as readFile53, stat as stat17 } from "node:fs/promises";
260751
+ import { readFile as readFile54, stat as stat17 } from "node:fs/promises";
260612
260752
  import { basename as basename15, relative as relative23, resolve as resolve53 } from "node:path";
260613
260753
  init_src();
260614
260754
  var MB3 = 1024 * 1024;
@@ -260637,7 +260777,7 @@ async function findTraceFiles(cwd, args) {
260637
260777
  return [...found].sort();
260638
260778
  }
260639
260779
  async function readTraceTexts(cwd, paths2) {
260640
- return Promise.all(paths2.map(async (path7) => ({ file: relative23(cwd, path7) || basename15(path7), name: basename15(path7), text: await readFile53(path7, "utf8").catch(() => void 0) })));
260780
+ return Promise.all(paths2.map(async (path7) => ({ file: relative23(cwd, path7) || basename15(path7), name: basename15(path7), text: await readFile54(path7, "utf8").catch(() => void 0) })));
260641
260781
  }
260642
260782
  function readTraceUnits(texts4, { fileToIr: fileToIr2, sourceOf: sourceOf2 }) {
260643
260783
  const drafts = /* @__PURE__ */ new Map(), skipped = [], read7 = [];
@@ -261078,7 +261218,7 @@ var importedCheckLines = (scene2, production3) => [
261078
261218
  ...importedChecks(scene2, production3).map((c) => ` ${c.id}: ${c.required ? "required" : "optional"}, ${c.production} in production`)
261079
261219
  ];
261080
261220
  async function localChanges(dir2) {
261081
- const text29 = await readFile54(join69(dir2, "scene.yaml"), "utf8").catch(() => void 0);
261221
+ const text29 = await readFile55(join70(dir2, "scene.yaml"), "utf8").catch(() => void 0);
261082
261222
  if (text29 === void 0) return void 0;
261083
261223
  const local2 = (() => {
261084
261224
  try {
@@ -261089,7 +261229,7 @@ async function localChanges(dir2) {
261089
261229
  })(), mark = MARK.exec(text29)?.[1];
261090
261230
  if (local2 === void 0 || mark === void 0) return { added: [], other: true };
261091
261231
  if (digest3(local2) === mark) return { added: [], other: false };
261092
- const production3 = await readFile54(join69(dir2, "production.json"), "utf8").then((t) => JSON.parse(t).checks, () => void 0);
261232
+ const production3 = await readFile55(join70(dir2, "production.json"), "utf8").then((t) => JSON.parse(t).checks, () => void 0);
261093
261233
  const added = production3 ? checksOf2(local2).filter((c) => !Object.hasOwn(production3, c.id)) : [];
261094
261234
  const addedIds = new Set(added.map((c) => c.id));
261095
261235
  const required4 = (Array.isArray(local2.pass) ? local2.pass : checksOf2(local2).map((c) => c.id)).filter((id14) => addedIds.has(id14));
@@ -261103,7 +261243,7 @@ async function guard(ctx, dir2, force) {
261103
261243
  if (changes?.other) {
261104
261244
  throw new AnchaError(
261105
261245
  "USAGE",
261106
- `${relative25(ctx.io.cwd, join69(dir2, "scene.yaml"))} has changes besides checks you added; pulling would overwrite them`,
261246
+ `${relative25(ctx.io.cwd, join70(dir2, "scene.yaml"))} has changes besides checks you added; pulling would overwrite them`,
261107
261247
  { hint: "move those changes into checks of your own, or pass --force to overwrite the file" }
261108
261248
  );
261109
261249
  }
@@ -261130,19 +261270,19 @@ async function writeWorld(ctx, world5, dest, changes) {
261130
261270
  const dir2 = resolve54(ctx.io.cwd, dest, world5.name);
261131
261271
  await mkdir34(dir2, { recursive: true });
261132
261272
  const { scene: content2, kept } = sceneToWrite(world5.scene, changes);
261133
- const scene2 = join69(dir2, "scene.yaml");
261273
+ const scene2 = join70(dir2, "scene.yaml");
261134
261274
  const { sceneFiles: sceneFiles2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
261135
261275
  const files2 = sceneFiles2(content2);
261136
261276
  await writeFile37(scene2, `# Rebuilt by Ancha from a production trace (world ${world5.id}). Where each part came from: provenance.json.
261137
261277
  # ancha pull: ${world5.id} ${digest3(sceneFiles2(world5.scene).scene)}
261138
261278
  ${(0, import_yaml21.stringify)(files2.scene)}`);
261139
- if (files2.observations !== void 0) await writeFile37(join69(dir2, "observations.jsonl"), files2.observations);
261140
- if (world5.record) await writeFile37(join69(dir2, "production.jsonl"), productionLines(world5.record));
261141
- await writeFile37(join69(dir2, "provenance.json"), JSON.stringify(world5.provenance, null, 2) + "\n");
261142
- await writeFile37(join69(dir2, "questions.json"), JSON.stringify(world5.questions ?? [], null, 2) + "\n");
261279
+ if (files2.observations !== void 0) await writeFile37(join70(dir2, "observations.jsonl"), files2.observations);
261280
+ if (world5.record) await writeFile37(join70(dir2, "production.jsonl"), productionLines(world5.record));
261281
+ await writeFile37(join70(dir2, "provenance.json"), JSON.stringify(world5.provenance, null, 2) + "\n");
261282
+ await writeFile37(join70(dir2, "questions.json"), JSON.stringify(world5.questions ?? [], null, 2) + "\n");
261143
261283
  if (world5.summary?.production !== void 0) {
261144
261284
  const checks2 = { ...Object.fromEntries(checksOf2(world5.scene).map((c) => [c.id, "unknown"])), ...world5.summary.production };
261145
- await writeFile37(join69(dir2, "production.json"), JSON.stringify({ trace: world5.summary.trace, checks: checks2, signatures: Object.fromEntries(checksOf2(world5.scene).map((c) => [c.id, productionSignature(c)])) }, null, 2) + "\n");
261285
+ await writeFile37(join70(dir2, "production.json"), JSON.stringify({ trace: world5.summary.trace, checks: checks2, signatures: Object.fromEntries(checksOf2(world5.scene).map((c) => [c.id, productionSignature(c)])) }, null, 2) + "\n");
261146
261286
  }
261147
261287
  await loadSceneFile(scene2);
261148
261288
  return { dir: dir2, scene: scene2, kept };
@@ -261646,7 +261786,7 @@ function registerTraces(program2, ctx) {
261646
261786
  });
261647
261787
  }
261648
261788
  async function traceSource(ctx, trace, from) {
261649
- if (!from) return { text: await readFile54(resolve54(ctx.io.cwd, trace), "utf8").catch(() => {
261789
+ if (!from) return { text: await readFile55(resolve54(ctx.io.cwd, trace), "utf8").catch(() => {
261650
261790
  throw new AnchaError("USAGE", `cannot read ${trace}`, { hint: "pass the path of a trace file: ancha import --offline <trace.jsonl>" });
261651
261791
  }), name: basename16(trace), label: basename16(trace) };
261652
261792
  const doc = await fetchTrace(from, trace, ctx.io.env);
@@ -261654,7 +261794,7 @@ async function traceSource(ctx, trace, from) {
261654
261794
  return { text: JSON.stringify(doc), name: `${from}-${id14}`.slice(0, 80), label: `${from === "langfuse" ? "Langfuse" : "LangSmith"} trace ${id14}` };
261655
261795
  }
261656
261796
  async function traceFileLines(ctx, file3) {
261657
- const text29 = await readFile54(resolve54(ctx.io.cwd, file3), "utf8").catch(() => {
261797
+ const text29 = await readFile55(resolve54(ctx.io.cwd, file3), "utf8").catch(() => {
261658
261798
  throw new AnchaError("USAGE", `cannot read ${file3}`, { hint: "pass the path of a trace file: ancha traces diff <trace.jsonl> latest" });
261659
261799
  });
261660
261800
  return { text: text29, lines: await traceTextLines(text29, basename16(file3)) };
@@ -261732,7 +261872,7 @@ async function writeRecords(ctx, conversations, dest) {
261732
261872
  const seen = conversations.flatMap((c) => recordsOf2(toolCallsOf(c.lines), { conversation: c.id }));
261733
261873
  if (!seen.length) return void 0;
261734
261874
  const path7 = resolve54(ctx.io.cwd, dest, "records.jsonl");
261735
- const merged = mergeRecords2(readRecordLines2(await readFile54(path7, "utf8").catch(() => "")), seen);
261875
+ const merged = mergeRecords2(readRecordLines2(await readFile55(path7, "utf8").catch(() => "")), seen);
261736
261876
  await mkdir34(dirname25(path7), { recursive: true });
261737
261877
  await writeFile37(path7, recordLines2(merged));
261738
261878
  const types = merged.reduce((all9, r2) => all9.set(r2.type, (all9.get(r2.type) ?? 0) + 1), /* @__PURE__ */ new Map());
@@ -261761,7 +261901,7 @@ async function importLocally(ctx, source, options4) {
261761
261901
  const made = [], skipped = [];
261762
261902
  for (const [i, conversation3] of picked.entries()) {
261763
261903
  const examples2 = [...all9.filter((c) => c !== conversation3).map((c) => c.lines), ...files2], customer3 = customers3.people[i];
261764
- const earlier2 = options4.resetAnswers ? {} : await readFile54(resolve54(ctx.io.cwd, options4.dest, named5.get(conversation3), "answers.json"), "utf8").then((text30) => JSON.parse(text30), () => ({}));
261904
+ const earlier2 = options4.resetAnswers ? {} : await readFile55(resolve54(ctx.io.cwd, options4.dest, named5.get(conversation3), "answers.json"), "utf8").then((text30) => JSON.parse(text30), () => ({}));
261765
261905
  try {
261766
261906
  const preview = rebuild2(conversation3.lines, { id: named5.get(conversation3), withRecords: true, examples: examples2 });
261767
261907
  const answers = { ...answersFor(preview.questions, earlier2, options4.answer), ...options4.expect && { "checks.expect": options4.expect } };
@@ -261772,23 +261912,23 @@ async function importLocally(ctx, source, options4) {
261772
261912
  skipped.push(conversation3.id);
261773
261913
  }
261774
261914
  }
261775
- const paths2 = made.map((m) => join69(resolve54(ctx.io.cwd, options4.dest, m.id), "scene.yaml"));
261915
+ const paths2 = made.map((m) => join70(resolve54(ctx.io.cwd, options4.dest, m.id), "scene.yaml"));
261776
261916
  if (!options4.force) {
261777
- for (const path7 of paths2) if (await readFile54(path7, "utf8").then(() => true, () => false)) throw new AnchaError("USAGE", `${relative25(ctx.io.cwd, path7)} exists; --force replaces it`);
261917
+ for (const path7 of paths2) if (await readFile55(path7, "utf8").then(() => true, () => false)) throw new AnchaError("USAGE", `${relative25(ctx.io.cwd, path7)} exists; --force replaces it`);
261778
261918
  }
261779
261919
  for (const [i, m] of made.entries()) {
261780
261920
  const path7 = paths2[i], dir2 = dirname25(path7);
261781
261921
  await mkdir34(dir2, { recursive: true });
261782
261922
  const files3 = sceneFiles2(m.made.scene);
261783
261923
  await writeFile37(path7, (0, import_yaml21.stringify)(files3.scene, { lineWidth: 0 }));
261784
- await writeFile37(join69(dir2, "answers.json"), JSON.stringify(m.answers, null, 2) + "\n");
261785
- if (files3.observations !== void 0) await writeFile37(join69(dir2, "observations.jsonl"), files3.observations);
261786
- if (m.made.record) await writeFile37(join69(dir2, "production.jsonl"), productionLines(m.made.record));
261787
- if (m.made.production !== void 0) await writeFile37(join69(dir2, "production.json"), `${JSON.stringify({ trace: m.made.summary.trace, checks: { ...Object.fromEntries(checksOf2(m.made.scene).map((c) => [c.id, "unknown"])), ...m.made.production }, signatures: Object.fromEntries(checksOf2(m.made.scene).map((c) => [c.id, productionSignature(c)])) }, null, 2)}
261924
+ await writeFile37(join70(dir2, "answers.json"), JSON.stringify(m.answers, null, 2) + "\n");
261925
+ if (files3.observations !== void 0) await writeFile37(join70(dir2, "observations.jsonl"), files3.observations);
261926
+ if (m.made.record) await writeFile37(join70(dir2, "production.jsonl"), productionLines(m.made.record));
261927
+ if (m.made.production !== void 0) await writeFile37(join70(dir2, "production.json"), `${JSON.stringify({ trace: m.made.summary.trace, checks: { ...Object.fromEntries(checksOf2(m.made.scene).map((c) => [c.id, "unknown"])), ...m.made.production }, signatures: Object.fromEntries(checksOf2(m.made.scene).map((c) => [c.id, productionSignature(c)])) }, null, 2)}
261788
261928
  `);
261789
- await writeFile37(join69(dir2, "provenance.json"), `${JSON.stringify({ summary: m.made.summary, provenance: m.made.provenance, questions: m.made.questions, ...all9.length > 1 && { conversation: { id: m.conversation.id, traces: m.conversation.traces } } }, null, 2)}
261929
+ await writeFile37(join70(dir2, "provenance.json"), `${JSON.stringify({ summary: m.made.summary, provenance: m.made.provenance, questions: m.made.questions, ...all9.length > 1 && { conversation: { id: m.conversation.id, traces: m.conversation.traces } } }, null, 2)}
261790
261930
  `);
261791
- await writeFile37(join69(dir2, "questions.json"), `${JSON.stringify(m.made.questions, null, 2)}
261931
+ await writeFile37(join70(dir2, "questions.json"), `${JSON.stringify(m.made.questions, null, 2)}
261792
261932
  `);
261793
261933
  await loadSceneFile(path7);
261794
261934
  }