@ancha-labs/cli 0.4.14 → 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
 
@@ -44474,9 +44474,11 @@ function projectToolCalls(trace) {
44474
44474
  };
44475
44475
  });
44476
44476
  }
44477
+ var isAgentAnswer;
44477
44478
  var init_tool_call_trace = __esm({
44478
44479
  "packages/core/src/tool-call-trace.ts"() {
44479
44480
  "use strict";
44481
+ isAgentAnswer = (entry3) => entry3.source === "agent" && entry3.service === "agent" && entry3.path === "/done";
44480
44482
  }
44481
44483
  });
44482
44484
 
@@ -44566,6 +44568,9 @@ function worldToSceneInput(world5, test3 = {}) {
44566
44568
  pass: test3.pass
44567
44569
  }).filter(([, value5]) => value5 !== void 0));
44568
44570
  }
44571
+ function worldToScene(world5, test3 = {}) {
44572
+ return parseScene(worldToSceneInput(world5, test3));
44573
+ }
44569
44574
  function worldError(issues) {
44570
44575
  return new AnchaError("SCENE_INVALID", issues.map((issue6) => `${issue6.path}: ${issue6.message}`).join("\n"), {
44571
44576
  ...issues.some((issue6) => issue6.hint) && { hint: issues.filter((issue6) => issue6.hint).map((issue6) => issues.length === 1 ? issue6.hint : `${issue6.path}: ${issue6.hint}`).join("\n") }
@@ -48903,7 +48908,7 @@ function validate3(raw3, issues) {
48903
48908
  }
48904
48909
  if (raw3.agent.answer !== void 0) {
48905
48910
  if (ANSWER_MODES.includes(raw3.agent.answer)) agent.answer = raw3.agent.answer;
48906
- 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" });
48907
48912
  }
48908
48913
  if (raw3.agent.pass_env !== void 0) {
48909
48914
  const names5 = raw3.agent.pass_env;
@@ -68388,8 +68393,10 @@ function evaluateTrace(trace, calls2, tools2) {
68388
68393
  function finalAnswer(trace) {
68389
68394
  const entry3 = trace.findLast((e) => e.source === "agent" && e.service === "agent" && e.path === "/done");
68390
68395
  if (!entry3) return void 0;
68391
- const output2 = typeof entry3.request === "string" ? entry3.request : entry3.request?.output;
68392
- 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 } };
68393
68400
  }
68394
68401
  function evaluateAnswer(check4, trace) {
68395
68402
  const contains3 = asList(check4.contains), absent = asList(check4.not_contains), sensitive = check4.case === "sensitive";
@@ -68401,13 +68408,22 @@ function evaluateAnswer(check4, trace) {
68401
68408
  ];
68402
68409
  const expected = parts3.length ? `the final answer ${parts3.join("; ")}` : "a final answer";
68403
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
+ }
68404
68420
  if (!answer || answer.text.trim() === "") {
68405
68421
  return {
68406
68422
  passed: false,
68407
68423
  expected,
68408
68424
  actual: answer ? "an empty final answer" : "no final answer",
68409
68425
  evidence: answer ? [answer.seq] : [],
68410
- 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.`
68411
68427
  };
68412
68428
  }
68413
68429
  const text29 = comparableText(answer.text, sensitive);
@@ -68424,7 +68440,8 @@ function evaluateAnswer(check4, trace) {
68424
68440
  const explanation = [
68425
68441
  ...missing8.length ? [`The final answer does not contain ${quoted2(missing8)}.`] : [],
68426
68442
  ...unstated.length ? [`It states no number within ${unstated.map((n2) => `${plainNumber(n2.tolerance)} of ${n2.written}`).join(", nor within ")}: ${said}.`] : [],
68427
- ...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."] : []
68428
68445
  ].join(" ");
68429
68446
  return { passed: false, expected, actual, explanation, evidence: [answer.seq] };
68430
68447
  }
@@ -120202,16 +120219,16 @@ var require_printer = __commonJS({
120202
120219
  },
120203
120220
  // Document
120204
120221
  Document: {
120205
- leave: (node5) => join70(node5.definitions, "\n\n")
120222
+ leave: (node5) => join71(node5.definitions, "\n\n")
120206
120223
  },
120207
120224
  OperationDefinition: {
120208
120225
  leave(node5) {
120209
- const varDefs = hasMultilineItems(node5.variableDefinitions) ? wrap("(\n", join70(node5.variableDefinitions, "\n"), "\n)") : wrap("(", join70(node5.variableDefinitions, ", "), ")");
120210
- 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(
120211
120228
  [
120212
120229
  node5.operation,
120213
- join70([node5.name, varDefs]),
120214
- join70(node5.directives, " ")
120230
+ join71([node5.name, varDefs]),
120231
+ join71(node5.directives, " ")
120215
120232
  ],
120216
120233
  " "
120217
120234
  );
@@ -120219,7 +120236,7 @@ var require_printer = __commonJS({
120219
120236
  }
120220
120237
  },
120221
120238
  VariableDefinition: {
120222
- 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, " "))
120223
120240
  },
120224
120241
  SelectionSet: {
120225
120242
  leave: ({ selections: selections2 }) => block2(selections2)
@@ -120227,11 +120244,11 @@ var require_printer = __commonJS({
120227
120244
  Field: {
120228
120245
  leave({ alias, name: name5, arguments: args, directives, selectionSet }) {
120229
120246
  const prefix2 = wrap("", alias, ": ") + name5;
120230
- let argsLine = prefix2 + wrap("(", join70(args, ", "), ")");
120247
+ let argsLine = prefix2 + wrap("(", join71(args, ", "), ")");
120231
120248
  if (argsLine.length > MAX_LINE_LENGTH) {
120232
- argsLine = prefix2 + wrap("(\n", indent2(join70(args, "\n")), "\n)");
120249
+ argsLine = prefix2 + wrap("(\n", indent2(join71(args, "\n")), "\n)");
120233
120250
  }
120234
- return join70([argsLine, join70(directives, " "), selectionSet], " ");
120251
+ return join71([argsLine, join71(directives, " "), selectionSet], " ");
120235
120252
  }
120236
120253
  },
120237
120254
  Argument: {
@@ -120239,14 +120256,14 @@ var require_printer = __commonJS({
120239
120256
  },
120240
120257
  // Fragments
120241
120258
  FragmentSpread: {
120242
- leave: ({ name: name5, directives }) => "..." + name5 + wrap(" ", join70(directives, " "))
120259
+ leave: ({ name: name5, directives }) => "..." + name5 + wrap(" ", join71(directives, " "))
120243
120260
  },
120244
120261
  InlineFragment: {
120245
- leave: ({ typeCondition, directives, selectionSet }) => join70(
120262
+ leave: ({ typeCondition, directives, selectionSet }) => join71(
120246
120263
  [
120247
120264
  "...",
120248
120265
  wrap("on ", typeCondition),
120249
- join70(directives, " "),
120266
+ join71(directives, " "),
120250
120267
  selectionSet
120251
120268
  ],
120252
120269
  " "
@@ -120262,7 +120279,7 @@ var require_printer = __commonJS({
120262
120279
  description: description2
120263
120280
  }) => wrap("", description2, "\n") + // Note: fragment variable definitions are experimental and may be changed
120264
120281
  // or removed in the future.
120265
- `fragment ${name5}${wrap("(", join70(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join70(directives, " "), " ")}` + selectionSet
120282
+ `fragment ${name5}${wrap("(", join71(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join71(directives, " "), " ")}` + selectionSet
120266
120283
  },
120267
120284
  // Value
120268
120285
  IntValue: {
@@ -120284,17 +120301,17 @@ var require_printer = __commonJS({
120284
120301
  leave: ({ value: value5 }) => value5
120285
120302
  },
120286
120303
  ListValue: {
120287
- leave: ({ values: values2 }) => "[" + join70(values2, ", ") + "]"
120304
+ leave: ({ values: values2 }) => "[" + join71(values2, ", ") + "]"
120288
120305
  },
120289
120306
  ObjectValue: {
120290
- leave: ({ fields: fields11 }) => "{" + join70(fields11, ", ") + "}"
120307
+ leave: ({ fields: fields11 }) => "{" + join71(fields11, ", ") + "}"
120291
120308
  },
120292
120309
  ObjectField: {
120293
120310
  leave: ({ name: name5, value: value5 }) => name5 + ": " + value5
120294
120311
  },
120295
120312
  // Directive
120296
120313
  Directive: {
120297
- leave: ({ name: name5, arguments: args }) => "@" + name5 + wrap("(", join70(args, ", "), ")")
120314
+ leave: ({ name: name5, arguments: args }) => "@" + name5 + wrap("(", join71(args, ", "), ")")
120298
120315
  },
120299
120316
  // Type
120300
120317
  NamedType: {
@@ -120308,61 +120325,61 @@ var require_printer = __commonJS({
120308
120325
  },
120309
120326
  // Type System Definitions
120310
120327
  SchemaDefinition: {
120311
- 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)], " ")
120312
120329
  },
120313
120330
  OperationTypeDefinition: {
120314
120331
  leave: ({ operation, type }) => operation + ": " + type
120315
120332
  },
120316
120333
  ScalarTypeDefinition: {
120317
- 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, " ")], " ")
120318
120335
  },
120319
120336
  ObjectTypeDefinition: {
120320
- 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(
120321
120338
  [
120322
120339
  "type",
120323
120340
  name5,
120324
- wrap("implements ", join70(interfaces, " & ")),
120325
- join70(directives, " "),
120341
+ wrap("implements ", join71(interfaces, " & ")),
120342
+ join71(directives, " "),
120326
120343
  block2(fields11)
120327
120344
  ],
120328
120345
  " "
120329
120346
  )
120330
120347
  },
120331
120348
  FieldDefinition: {
120332
- 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, " "))
120333
120350
  },
120334
120351
  InputValueDefinition: {
120335
- leave: ({ description: description2, name: name5, type, defaultValue, directives }) => wrap("", description2, "\n") + join70(
120336
- [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, " ")],
120337
120354
  " "
120338
120355
  )
120339
120356
  },
120340
120357
  InterfaceTypeDefinition: {
120341
- 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(
120342
120359
  [
120343
120360
  "interface",
120344
120361
  name5,
120345
- wrap("implements ", join70(interfaces, " & ")),
120346
- join70(directives, " "),
120362
+ wrap("implements ", join71(interfaces, " & ")),
120363
+ join71(directives, " "),
120347
120364
  block2(fields11)
120348
120365
  ],
120349
120366
  " "
120350
120367
  )
120351
120368
  },
120352
120369
  UnionTypeDefinition: {
120353
- leave: ({ description: description2, name: name5, directives, types }) => wrap("", description2, "\n") + join70(
120354
- ["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, " | "))],
120355
120372
  " "
120356
120373
  )
120357
120374
  },
120358
120375
  EnumTypeDefinition: {
120359
- 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)], " ")
120360
120377
  },
120361
120378
  EnumValueDefinition: {
120362
- 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, " ")], " ")
120363
120380
  },
120364
120381
  InputObjectTypeDefinition: {
120365
- 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)], " ")
120366
120383
  },
120367
120384
  DirectiveDefinition: {
120368
120385
  leave: ({
@@ -120372,84 +120389,84 @@ var require_printer = __commonJS({
120372
120389
  directives,
120373
120390
  repeatable,
120374
120391
  locations
120375
- }) => 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, " | ")
120376
120393
  },
120377
120394
  SchemaExtension: {
120378
- leave: ({ directives, operationTypes }) => join70(
120379
- ["extend schema", join70(directives, " "), block2(operationTypes)],
120395
+ leave: ({ directives, operationTypes }) => join71(
120396
+ ["extend schema", join71(directives, " "), block2(operationTypes)],
120380
120397
  " "
120381
120398
  )
120382
120399
  },
120383
120400
  ScalarTypeExtension: {
120384
- leave: ({ name: name5, directives }) => join70(["extend scalar", name5, join70(directives, " ")], " ")
120401
+ leave: ({ name: name5, directives }) => join71(["extend scalar", name5, join71(directives, " ")], " ")
120385
120402
  },
120386
120403
  ObjectTypeExtension: {
120387
- leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join70(
120404
+ leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join71(
120388
120405
  [
120389
120406
  "extend type",
120390
120407
  name5,
120391
- wrap("implements ", join70(interfaces, " & ")),
120392
- join70(directives, " "),
120408
+ wrap("implements ", join71(interfaces, " & ")),
120409
+ join71(directives, " "),
120393
120410
  block2(fields11)
120394
120411
  ],
120395
120412
  " "
120396
120413
  )
120397
120414
  },
120398
120415
  InterfaceTypeExtension: {
120399
- leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join70(
120416
+ leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join71(
120400
120417
  [
120401
120418
  "extend interface",
120402
120419
  name5,
120403
- wrap("implements ", join70(interfaces, " & ")),
120404
- join70(directives, " "),
120420
+ wrap("implements ", join71(interfaces, " & ")),
120421
+ join71(directives, " "),
120405
120422
  block2(fields11)
120406
120423
  ],
120407
120424
  " "
120408
120425
  )
120409
120426
  },
120410
120427
  UnionTypeExtension: {
120411
- leave: ({ name: name5, directives, types }) => join70(
120428
+ leave: ({ name: name5, directives, types }) => join71(
120412
120429
  [
120413
120430
  "extend union",
120414
120431
  name5,
120415
- join70(directives, " "),
120416
- wrap("= ", join70(types, " | "))
120432
+ join71(directives, " "),
120433
+ wrap("= ", join71(types, " | "))
120417
120434
  ],
120418
120435
  " "
120419
120436
  )
120420
120437
  },
120421
120438
  EnumTypeExtension: {
120422
- 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)], " ")
120423
120440
  },
120424
120441
  InputObjectTypeExtension: {
120425
- 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)], " ")
120426
120443
  },
120427
120444
  DirectiveExtension: {
120428
- leave: ({ name: name5, directives }) => join70(["extend directive @" + name5, join70(directives, " ")], " ")
120445
+ leave: ({ name: name5, directives }) => join71(["extend directive @" + name5, join71(directives, " ")], " ")
120429
120446
  },
120430
120447
  // Schema Coordinates
120431
120448
  TypeCoordinate: {
120432
120449
  leave: ({ name: name5 }) => name5
120433
120450
  },
120434
120451
  MemberCoordinate: {
120435
- leave: ({ name: name5, memberName }) => join70([name5, wrap(".", memberName)])
120452
+ leave: ({ name: name5, memberName }) => join71([name5, wrap(".", memberName)])
120436
120453
  },
120437
120454
  ArgumentCoordinate: {
120438
- 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, ":)")])
120439
120456
  },
120440
120457
  DirectiveCoordinate: {
120441
- leave: ({ name: name5 }) => join70(["@", name5])
120458
+ leave: ({ name: name5 }) => join71(["@", name5])
120442
120459
  },
120443
120460
  DirectiveArgumentCoordinate: {
120444
- leave: ({ name: name5, argumentName }) => join70(["@", name5, wrap("(", argumentName, ":)")])
120461
+ leave: ({ name: name5, argumentName }) => join71(["@", name5, wrap("(", argumentName, ":)")])
120445
120462
  }
120446
120463
  };
120447
- function join70(maybeArray, separator = "") {
120464
+ function join71(maybeArray, separator = "") {
120448
120465
  var _maybeArray$filter$jo;
120449
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 : "";
120450
120467
  }
120451
120468
  function block2(array3) {
120452
- return wrap("{\n", indent2(join70(array3, "\n")), "\n}");
120469
+ return wrap("{\n", indent2(join71(array3, "\n")), "\n}");
120453
120470
  }
120454
120471
  function wrap(start, maybeString, end = "") {
120455
120472
  return maybeString != null && maybeString !== "" ? start + maybeString + end : "";
@@ -172417,16 +172434,16 @@ var init_suiteql = __esm({
172417
172434
  block(q2, parent2, limit2 = -1, comparisonType) {
172418
172435
  const scope3 = { relations: [], parent: parent2, correlations: [] };
172419
172436
  let from = q2.from ? this.source(q2.from, scope3) : sql3("");
172420
- for (const join70 of q2.joins) {
172421
- const source = this.source(join70.source, scope3);
172422
- if (!join70.on) {
172423
- 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);
172424
172441
  continue;
172425
172442
  }
172426
- if (hasWindow(join70.on)) invalid26("Analytic functions are not allowed in JOIN conditions.");
172427
- const on = this.expr(join70.on, scope3);
172428
- if (on.aggregate || hasRownum(join70.on)) invalid26("JOIN conditions cannot contain aggregate functions or ROWNUM.");
172429
- 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);
172430
172447
  }
172431
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.");
172432
172449
  const split2 = this.rownumFilter(q2.where), usesRownum = expressions(q2).some(hasRownum);
@@ -174391,13 +174408,13 @@ var init_reports = __esm({
174391
174408
 
174392
174409
  // packages/server/src/twins/netsuite/searches.ts
174393
174410
  function joined(ctx, type, name5, error65, plan4) {
174394
- const [join70, column, ...rest2] = name5.split("."), spec = JOINS2[type]?.[join70];
174411
+ const [join71, column, ...rest2] = name5.split("."), spec = JOINS2[type]?.[join71];
174395
174412
  if (!spec || !column || rest2.length) throw error65(name5);
174396
- 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];
174397
174414
  const replace = (s3) => s3.replace(new RegExp(`\\b${original}\\.`, "g"), `${alias}.`).replace(/\btl\./g, `${alias}_line.`);
174398
- if (!plan4.joins.has(join70)) {
174399
- const on = type === spec.type || type === "customer" && join70 === "contact" || type === "contact" && join70 === "customer" ? spec.on : spec.on.replace(new RegExp(`\\b${original}\\.`, "g"), `${alias}.`);
174400
- 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'` : ""}`);
174401
174418
  }
174402
174419
  const found = field4(ctx, spec.type, column, error65, { joins: /* @__PURE__ */ new Map() });
174403
174420
  return { ...found, sql: replace(found.sql), ...found.text && { text: replace(found.text) } };
@@ -174577,9 +174594,9 @@ function expression2(ctx, type, filters, params10, plan4) {
174577
174594
  if (!filters.length) return "";
174578
174595
  if (filters.every((entry3) => entry3 && typeof entry3 === "object" && !Array.isArray(entry3))) {
174579
174596
  return filters.map((entry3) => {
174580
- const { name: name5, operator: operator2, values: values2, join: join70, formula, summary } = entry3;
174581
- if (join70 !== void 0 && typeof join70 !== "string") throw badExpression();
174582
- 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);
174583
174600
  }).join(" AND ");
174584
174601
  }
174585
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);
@@ -176367,7 +176384,8 @@ function record21(ctx, args) {
176367
176384
  }
176368
176385
  function unchanged(ctx, args) {
176369
176386
  const changes = sql2(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype));
176370
- 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");
176371
176389
  }
176372
176390
  function count4(ctx, args) {
176373
176391
  const actual = recordIds(ctx, args.type).length;
@@ -176377,6 +176395,7 @@ var init_checks13 = __esm({
176377
176395
  "packages/server/src/twins/netsuite/checks.ts"() {
176378
176396
  "use strict";
176379
176397
  init_open_items();
176398
+ init_src();
176380
176399
  init_checks4();
176381
176400
  init_store5();
176382
176401
  }
@@ -181708,8 +181727,9 @@ var init_sessions = __esm({
181708
181727
  });
181709
181728
  }
181710
181729
  /**
181711
- * The runner records the agent's answer for it when the agent posted none (SPEC-053 F2): an HTTP agent's reply, or the
181712
- * 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.
181713
181733
  */
181714
181734
  answer(env2, id14, answer) {
181715
181735
  return env2.serialize(() => {
@@ -181717,7 +181737,7 @@ var init_sessions = __esm({
181717
181737
  if (state3 === "prepared") throw new AnchaError("SESSION_CONFLICT", "session has not started");
181718
181738
  if (state3 === "finished") throw new AnchaError("SESSION_CONFLICT", "session has finished");
181719
181739
  if (env2.trace.list().some((entry3) => entry3.service === "agent" && entry3.path === "/done")) return { recorded: false };
181720
- 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 } } });
181721
181741
  return { recorded: true };
181722
181742
  });
181723
181743
  }
@@ -182086,10 +182106,13 @@ function sessionRoutes(opts, sessions) {
182086
182106
  } catch {
182087
182107
  throw new AnchaError("USAGE", "request must be a JSON object");
182088
182108
  }
182089
- fields10(input4, ["output", "source"]);
182109
+ fields10(input4, ["output", "source", "printed"]);
182090
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`);
182091
182111
  if (input4.source !== "reply" && input4.source !== "stdout") throw new AnchaError("USAGE", "source must be reply or stdout");
182092
- 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 } }));
182093
182116
  });
182094
182117
  app2.post("/envs/:id/trials/:sid/agent", async (c) => {
182095
182118
  let input4;
@@ -182136,7 +182159,7 @@ var init_session_routes = __esm({
182136
182159
  init_src();
182137
182160
  init_feed();
182138
182161
  init_env_info();
182139
- MAX_ANSWER_CHARS = 16e3;
182162
+ MAX_ANSWER_CHARS = 64 * 1024;
182140
182163
  }
182141
182164
  });
182142
182165
 
@@ -187317,6 +187340,26 @@ import { lookup as lookup5 } from "node:dns/promises";
187317
187340
  import { createServer, request } from "node:http";
187318
187341
  import { request as secureRequest } from "node:https";
187319
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
+ }
187320
187363
  function loopbackOrigin(value5) {
187321
187364
  const url4 = new URL(value5);
187322
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");
@@ -187457,11 +187500,30 @@ async function startIsolationGateway(options4) {
187457
187500
  agent: false,
187458
187501
  ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
187459
187502
  }, (reply5) => {
187460
- if (modelHost !== void 0 && reply5.statusCode !== void 0) {
187503
+ const observe2 = (host, status5, message7) => {
187461
187504
  try {
187462
- options4.onModelReply?.(modelHost, reply5.statusCode);
187505
+ options4.onModelReply?.(host, status5, message7);
187463
187506
  } catch {
187464
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
+ }
187465
187527
  }
187466
187528
  if (reply5.statusCode && reply5.statusCode >= 300 && reply5.statusCode < 400) {
187467
187529
  reply5.destroy();
@@ -187573,12 +187635,14 @@ async function startIsolationGateway(options4) {
187573
187635
  return mapped(exposedOrigin);
187574
187636
  }, close };
187575
187637
  }
187576
- var BODY_LIMIT, HOP_HEADERS;
187638
+ var BODY_LIMIT, HOP_HEADERS, MODEL_REFUSALS, REFUSAL_BYTES;
187577
187639
  var init_gateway = __esm({
187578
187640
  "backend/src/execution/gateway.ts"() {
187579
187641
  "use strict";
187580
187642
  BODY_LIMIT = 8 * 1024 * 1024;
187581
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;
187582
187646
  }
187583
187647
  });
187584
187648
 
@@ -187905,38 +187969,38 @@ function withoutScriptBanners(lines2) {
187905
187969
  if (end > start && YARN_DONE.test(lines2[end - 1].trim())) end--;
187906
187970
  return lines2.slice(start, end);
187907
187971
  }
187908
- function finalBlock(stdout) {
187909
- const lines2 = withoutScriptBanners(stdout.replace(ANSI, "").replace(/\r\n?/g, "\n").trimEnd().split("\n"));
187910
- const blank = lines2.findLastIndex((line2) => line2.trim() === "");
187911
- let block2 = (blank >= 0 ? lines2.slice(blank + 1) : lines2.slice(-ANSWER_MAX_LINES)).join("\n");
187912
- if (Buffer.byteLength(block2) > ANSWER_MAX_BYTES) {
187913
- const bytes3 = Buffer.from(block2);
187914
- let end = bytes3.subarray(bytes3.length - ANSWER_MAX_BYTES).toString("utf8").replace(/^�+/, "");
187915
- const line2 = end.indexOf("\n");
187916
- if (line2 >= 0 && line2 < end.length - 1) end = end.slice(line2 + 1);
187917
- block2 = end;
187918
- }
187919
- 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();
187920
187974
  }
187921
- 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;
187922
187976
  var init_agent_output = __esm({
187923
187977
  "backend/src/runner/agent-output.ts"() {
187924
187978
  "use strict";
187925
- TAIL_CHARS = 64 * 1024;
187926
- ANSWER_MAX_BYTES = 8 * 1024;
187927
- ANSWER_MAX_LINES = 40;
187979
+ init_gateway();
187980
+ ANSWER_MAX_CHARS = 64 * 1024;
187981
+ STDOUT_MAX_CHARS = 2 * ANSWER_MAX_CHARS;
187928
187982
  OutputTail = class {
187983
+ max;
187929
187984
  #text = "";
187930
187985
  #cut = false;
187986
+ #length = 0;
187987
+ constructor(max = STDOUT_MAX_CHARS) {
187988
+ this.max = max;
187989
+ }
187931
187990
  push(text29) {
187932
187991
  this.#text += text29;
187933
- if (this.#text.length > TAIL_CHARS * 2) this.#trim();
187992
+ this.#length += text29.length;
187993
+ if (this.#text.length > this.max * 2) this.#trim();
187934
187994
  }
187935
187995
  #trim() {
187936
- if (this.#text.length <= TAIL_CHARS) return;
187937
- this.#text = this.#text.slice(-TAIL_CHARS);
187996
+ if (this.#text.length <= this.max) return;
187997
+ this.#text = this.#text.slice(-this.max);
187938
187998
  this.#cut = true;
187939
187999
  }
188000
+ /** How many characters were pushed in all. */
188001
+ length() {
188002
+ return this.#length;
188003
+ }
187940
188004
  /** What was kept; a first line cut in the middle is left out. */
187941
188005
  text() {
187942
188006
  this.#trim();
@@ -187945,15 +188009,23 @@ var init_agent_output = __esm({
187945
188009
  };
187946
188010
  ModelReplies = class {
187947
188011
  #counts = /* @__PURE__ */ new Map();
187948
- add(host, status5) {
188012
+ #last;
188013
+ add(host, status5, message7) {
187949
188014
  const key4 = `${host} ${status5}`;
187950
188015
  const reply5 = this.#counts.get(key4);
187951
- if (reply5) reply5.count++;
187952
- 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 } };
187953
188021
  }
187954
188022
  list() {
187955
188023
  return [...this.#counts.values()].map((reply5) => ({ ...reply5 }));
187956
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
+ }
187957
188029
  };
187958
188030
  ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
187959
188031
  NPM_SCRIPT = /^> (?:\S+@\S* )?[\w:.-]+(?: \/\S*)?$/;
@@ -188039,7 +188111,7 @@ function outputCopy(logFd) {
188039
188111
  closeSync2(stderr.fd);
188040
188112
  }
188041
188113
  },
188042
- tail: () => tail.text()
188114
+ output: () => ({ stdout: tail.text(), printed: tail.length() })
188043
188115
  };
188044
188116
  }
188045
188117
  function startAgentProcess(command, opts) {
@@ -188096,7 +188168,7 @@ function startAgentProcess(command, opts) {
188096
188168
  return { pid, exited, async stop() {
188097
188169
  terminate();
188098
188170
  await exited;
188099
- }, ...stdout && { output: () => ({ stdout: stdout.tail() }) } };
188171
+ }, ...stdout && { output: stdout.output } };
188100
188172
  }
188101
188173
  var KILL_GRACE_MS, GROUP_POLL_MS, COPY_MS;
188102
188174
  var init_process = __esm({
@@ -188736,7 +188808,7 @@ async function startContainedAgent(command, opts) {
188736
188808
  ]);
188737
188809
  await run6(["start", relayName]);
188738
188810
  const replies = new ModelReplies();
188739
- 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) });
188740
188812
  const script = isolationRelayScript({ port: RELAY_PORT, ...opts.runtime?.port && { agentPort: opts.runtime.port } });
188741
188813
  relayChild = spawn2("docker", ["--context", context3, "exec", "-i", relayName, "node", "-e", script], { env: dockerEnvironment(), stdio: ["pipe", "pipe", "pipe"] });
188742
188814
  relayChild.stderr.on("data", () => {
@@ -188828,7 +188900,7 @@ async function startContainedAgent(command, opts) {
188828
188900
  return { pid: child2.pid, exited, async stop() {
188829
188901
  await cleanup();
188830
188902
  await exited;
188831
- }, output: () => ({ stdout: tail.text(), modelReplies: replies.list() }) };
188903
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
188832
188904
  } catch (error65) {
188833
188905
  opts.signal?.removeEventListener("abort", abort);
188834
188906
  await cleanup();
@@ -189024,7 +189096,7 @@ async function startVmAgent(command, opts, deps = {}) {
189024
189096
  ...opts.session && { session: opts.session },
189025
189097
  modelHosts,
189026
189098
  port: unsafe ? 0 : 18991,
189027
- onModelReply: (host, status5) => replies.add(host, status5)
189099
+ onModelReply: (host, status5, message7) => replies.add(host, status5, message7)
189028
189100
  });
189029
189101
  const mapped = gateway.rewrite(unsafe ? gateway.url : VM_GATEWAY_ORIGIN);
189030
189102
  const agentRuntime = { ...opts.runtime, ...taskFile !== void 0 && { taskFile }, ...opts.runtime?.attempt && { attempt: { ...opts.runtime.attempt, stateDir: paths2.state, records: records4 } } };
@@ -189146,7 +189218,7 @@ async function startVmAgent(command, opts, deps = {}) {
189146
189218
  return { pid: child2.pid, exited, async stop() {
189147
189219
  await cleanup();
189148
189220
  await exited;
189149
- }, output: () => ({ stdout: tail.text(), modelReplies: replies.list() }) };
189221
+ }, output: () => ({ stdout: tail.text(), printed: tail.length(), modelReplies: replies.list(), modelRefusal: replies.refusal() }) };
189150
189222
  } catch (error65) {
189151
189223
  await cleanup();
189152
189224
  throw error65;
@@ -215381,6 +215453,242 @@ var init_per_event = __esm({
215381
215453
  }
215382
215454
  });
215383
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
+
215384
215692
  // backend/src/runner/trial.ts
215385
215693
  import { setTimeout as sleep8 } from "node:timers/promises";
215386
215694
  import { closeSync as closeSync6, openSync as openSync6, writeSync as writeSync6 } from "node:fs";
@@ -215390,16 +215698,29 @@ function answersFrom(agent, source) {
215390
215698
  const mode = agent.answer ?? "auto";
215391
215699
  return mode === "auto" || mode === "stdout" && source === "stdout";
215392
215700
  }
215393
- async function recordAnswer(backend, envId, sessionId, output2, source) {
215394
- 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;
215395
215703
  try {
215396
- await backend.recordAnswer(envId, sessionId, { output: output2, source });
215704
+ await backend.recordAnswer(envId, sessionId, { output: output2, source, ...printed !== void 0 && { printed } });
215397
215705
  return void 0;
215398
215706
  } catch (error65) {
215399
215707
  if (unknownRoute18(error65)) return void 0;
215400
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)}` };
215401
215709
  }
215402
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
+ }
215403
215724
  async function runTrial(spec) {
215404
215725
  const { backend, env: env2, scene: scene2, trial, dir: dir2, signal, inheritedEnv = process.env } = spec;
215405
215726
  const agent = scene2.agent_input && spec.agent.mode !== "endpoint" ? { ...spec.agent, taskInput: sceneTaskInput(scene2, spec.agent.taskInput) } : spec.agent;
@@ -215494,7 +215815,7 @@ async function runTrial(spec) {
215494
215815
  const playOutIssues = [];
215495
215816
  const ended = exit === "timeout" || exit === "done" || exit === "exited" && exitCode === 0;
215496
215817
  if (ended && failure6 === void 0 && !signal?.aborted && answersFrom(agent, "stdout")) {
215497
- const issue6 = await recordAnswer(backend, env2.id, session2.id, finalBlock(output2?.stdout ?? ""), "stdout");
215818
+ const issue6 = await recordStdout(backend, env2.id, session2.id, output2);
215498
215819
  if (issue6 !== void 0) playOutIssues.push(issue6);
215499
215820
  }
215500
215821
  let playOut;
@@ -215507,6 +215828,7 @@ async function runTrial(spec) {
215507
215828
  }
215508
215829
  const capture4 = await captureTrialAfterFailure(failure6, backend, env2.id, session2.id, dir2, scene2, { ...spec.judge, ...signal !== void 0 && { signal } }, void 0, spec.onCaptured);
215509
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 ?? {})));
215510
215832
  if (failure6 !== void 0) throw failure6.error;
215511
215833
  signal?.throwIfAborted();
215512
215834
  return {
@@ -215546,6 +215868,7 @@ var init_trial = __esm({
215546
215868
  init_per_event();
215547
215869
  init_budget();
215548
215870
  init_agent_output();
215871
+ init_agent_outcome();
215549
215872
  init_agent_env();
215550
215873
  EXIT_COMMAND_NOT_FOUND2 = 127;
215551
215874
  unknownRoute18 = (error65) => error65 instanceof AnchaError && error65.code === "USAGE" && error65.message.startsWith("no such route");
@@ -215680,6 +216003,11 @@ async function worldFile(cwd, test3, id14) {
215680
216003
  hint: `put the world at ancha/worlds/${id14}.yaml, or generate one: ancha world gen "<the company and the scenario>" --id ${id14}`
215681
216004
  });
215682
216005
  }
216006
+ async function loadWorldFile(cwd, ref22) {
216007
+ const exists7 = (path8) => access3(path8).then(() => true, () => false);
216008
+ const path7 = /\.ya?ml$/.test(ref22) && await exists7(resolve12(cwd, ref22)) ? resolve12(cwd, ref22) : join15(cwd, "ancha", "worlds", `${ref22}.yaml`);
216009
+ return await exists7(path7) ? { path: path7, world: await readWorldFile(cwd, path7) } : void 0;
216010
+ }
215683
216011
  async function readWorldFile(cwd, path7) {
215684
216012
  try {
215685
216013
  const text29 = await readFile5(path7, "utf8"), kept = parsedWorlds.get(path7);
@@ -216189,11 +216517,38 @@ var init_run = __esm({
216189
216517
  }
216190
216518
  });
216191
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
+
216192
216547
  // backend/src/run-bundle.ts
216193
216548
  import { createHash as createHash59 } from "node:crypto";
216194
- import { readdir as readdir3, readFile as readFile8 } from "node:fs/promises";
216195
- import { join as join20 } from "node:path";
216196
- 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";
216197
216552
  function bundleSource(env2) {
216198
216553
  return env2.CI === "true" || env2.GITHUB_ACTIONS ? "ci" : "cli";
216199
216554
  }
@@ -216201,7 +216556,7 @@ async function bundleSecrets(options4) {
216201
216556
  const base3 = new Set(BASE_ENV);
216202
216557
  const names5 = options4.inheritEnv ? Object.keys(options4.env).filter((name5) => !base3.has(name5) && !name5.startsWith("LC_")) : [...options4.passEnv ?? []];
216203
216558
  const values2 = names5.map((name5) => options4.env[name5]);
216204
- 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(() => "");
216205
216560
  for (const line2 of file3.split(/\r?\n/)) {
216206
216561
  const match3 = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.*?)\s*$/.exec(line2);
216207
216562
  if (match3) values2.push(match3[1].replace(/^(['"])(.*)\1$/, "$2"));
@@ -216241,7 +216596,7 @@ async function runFiles(runDir, source) {
216241
216596
  const root3 = await readdir3(runDir, { withFileTypes: true });
216242
216597
  const paths2 = ["summary.json", "inputs.json", "reproduction.json", "cloud.json"].filter((name5) => allowedFor(source, name5) && root3.some((entry3) => entry3.isFile() && entry3.name === name5));
216243
216598
  for (const dir2 of root3.filter((entry3) => entry3.isDirectory()).map((entry3) => entry3.name).sort()) {
216244
- 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()) {
216245
216600
  if (allowedFor(source, `${dir2}/${file3}`)) paths2.push(`${dir2}/${file3}`);
216246
216601
  }
216247
216602
  }
@@ -216255,7 +216610,7 @@ async function packRun(options4) {
216255
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`);
216256
216611
  const entries4 = [], omitted = [];
216257
216612
  for (const path7 of paths2) {
216258
- let data5 = redact(await readFile8(join20(options4.runDir, path7)), options4.secrets);
216613
+ let data5 = redact(await readFile9(join21(options4.runDir, path7)), options4.secrets);
216259
216614
  const cap = capFor(path7, options4.inputsBytes);
216260
216615
  if (data5.length > cap) {
216261
216616
  if (path7.endsWith("/agent.log")) data5 = logTail2(data5, cap);
@@ -216322,7 +216677,7 @@ function writeTar(entries4, mtimeMs) {
216322
216677
  return Buffer.concat(parts3);
216323
216678
  }
216324
216679
  function readBundle(archive) {
216325
- const tar = gunzipSync2(archive, { maxOutputLength: BUNDLE_LIMITS2.unpackedBytes + 1024 * 1024 });
216680
+ const tar = gunzipSync3(archive, { maxOutputLength: BUNDLE_LIMITS2.unpackedBytes + 1024 * 1024 });
216326
216681
  const entries4 = [];
216327
216682
  for (let offset18 = 0; offset18 + 512 <= tar.length; ) {
216328
216683
  const block2 = tar.subarray(offset18, offset18 + 512);
@@ -216439,101 +216794,9 @@ var init_reproduction_text = __esm({
216439
216794
  }
216440
216795
  });
216441
216796
 
216442
- // backend/src/agent-fix.ts
216443
- function givenByTwins(name5) {
216444
- twinVariables ??= new Set(Object.keys(toolConnectionEnvironment(Object.fromEntries(SUPPORTED_TWINS.map((twin) => [twin, ANY_SERVICE])))));
216445
- return twinVariables.has(name5);
216446
- }
216447
- function taskVariables(text29) {
216448
- const found = [];
216449
- for (const match3 of text29.matchAll(TASK_NAME)) {
216450
- const name5 = match3[1], before = text29.slice(0, match3.index);
216451
- if (name5.startsWith("ANCHA_") || /--?[A-Za-z][\w-]*[ =]$/.test(before)) continue;
216452
- const bare = !name5.includes("_");
216453
- const named5 = escape10(name5);
216454
- 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;
216455
- if (!found.includes(name5)) found.push(name5);
216456
- }
216457
- return found;
216458
- }
216459
- function taskFlags(text29) {
216460
- return [...new Set([...text29.matchAll(TASK_FLAG)].map((match3) => match3[1]))];
216461
- }
216462
- function taskFix(text29, command) {
216463
- const names5 = taskVariables(text29);
216464
- const plain6 = names5.find((name5) => !/_(?:FILE|PATH)$/.test(name5)), file3 = names5.find((name5) => /_(?:FILE|PATH)$/.test(name5));
216465
- 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}}" }`;
216466
- const flags = taskFlags(text29), flag5 = flags.find((f2) => !f2.endsWith("-file")), fileFlag = flags.find((f2) => f2.endsWith("-file"));
216467
- const shellCommand = command !== void 0 && !/^https?:\/\//.test(command) ? command : void 0;
216468
- if (flag5 !== void 0 && !shellCommand?.includes(flag5)) {
216469
- 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"`;
216470
- }
216471
- 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}}" }`;
216472
- if (fileFlag !== void 0 && !shellCommand?.includes(fileFlag)) {
216473
- 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`;
216474
- }
216475
- return void 0;
216476
- }
216477
- function missingKey(lines2) {
216478
- for (const line2 of [...lines2].reverse()) {
216479
- if (!MISSING.test(line2)) continue;
216480
- const name5 = [...line2.matchAll(CREDENTIAL)].map((match3) => match3[1]).find((found) => !found.startsWith("ANCHA_") && !givenByTwins(found));
216481
- if (name5 !== void 0) return name5;
216482
- }
216483
- return void 0;
216484
- }
216485
- function keyFix(lines2, context3) {
216486
- const name5 = missingKey(lines2);
216487
- if (name5 === void 0) return void 0;
216488
- 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})`;
216489
- }
216490
- function missingFix(text29, context3) {
216491
- const cloud = context3.target === "cloud";
216492
- const notFoundCommand = /(?:^|\n|: )([\w./@+-]+): (?:command )?not found\b/.exec(text29) ?? /(?:^|\n)(?:sh|bash|zsh|\/bin\/sh)(?:: line \d+|: \d+)?: ([\w./@+-]+): not found/.exec(text29);
216493
- const packageName = /Cannot find package '([^']+)'/.exec(text29)?.[1];
216494
- const required4 = /Cannot find module '([^']+)'/.exec(text29)?.[1];
216495
- const requiredFile = required4 !== void 0 && /^(?:\.{1,2}[/\\]|[/\\]|[A-Za-z]:\\)|\.(?:[cm]?[jt]s|py|sh)$/.test(required4);
216496
- const missingFile = (requiredFile ? required4 : void 0) ?? /can't open file '([^']+)'/.exec(text29)?.[1] ?? /No such file or directory: '([^']+)'/.exec(text29)?.[1];
216497
- const module = packageName ?? (requiredFile ? void 0 : required4);
216498
- const pythonModule2 = /No module named '([^']+)'/.exec(text29)?.[1];
216499
- 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";
216500
- if (module === void 0 && missingFile !== void 0) {
216501
- const file3 = missingFile.replace(/^.*[/\\](?=[^/\\]+$)/, "");
216502
- 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)`;
216503
- }
216504
- if (module !== void 0) return `its dependency ${module} is not installed: add it to package.json; ${install}`;
216505
- if (pythonModule2 !== void 0) return `its dependency ${pythonModule2} is not installed: add it to requirements.txt or pyproject.toml; ${install}`;
216506
- 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}`;
216507
- return void 0;
216508
- }
216509
- function likelyFix(logTail3, context3 = {}) {
216510
- const task2 = taskFix(logTail3.join("\n"), context3.command);
216511
- if (task2 !== void 0 || context3.withheld !== void 0) return task2 ?? context3.withheld;
216512
- const errors3 = logTail3.filter((line2) => /error|exception|fatal|panic|missing|required|usage|not set|not found|cannot|can't/i.test(line2));
216513
- for (const lines2 of [errors3, logTail3]) {
216514
- const fix = lines2.length === 0 ? void 0 : keyFix(lines2, context3) ?? missingFix(lines2.join("\n"), context3);
216515
- if (fix !== void 0) return fix;
216516
- }
216517
- return void 0;
216518
- }
216519
- var TASK_WORD, TASK_NAME, TASK_FLAG, CREDENTIAL, MISSING, twinVariables, escape10;
216520
- var init_agent_fix = __esm({
216521
- "backend/src/agent-fix.ts"() {
216522
- "use strict";
216523
- init_src();
216524
- init_agent_env();
216525
- TASK_WORD = "(?:TASKS?|PROMPTS?|QUERY|QUERIES|INSTRUCTIONS?|MESSAGES?|REQUESTS?|INPUTS?)";
216526
- TASK_NAME = new RegExp(`(?<![A-Za-z0-9_])((?:[A-Z][A-Z0-9]*_)*${TASK_WORD}(?:_[A-Z0-9]+)*)(?![A-Za-z0-9_])`, "g");
216527
- TASK_FLAG = /(?<![\w-])(--(?:task|prompt|message|input|query|instructions?|request)(?:-file)?)(?![\w-])/g;
216528
- CREDENTIAL = /(?<![A-Za-z0-9_])([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*_(?:KEY|TOKEN|SECRET|PASSWORD))(?![A-Za-z0-9_])/g;
216529
- MISSING = /missing|not set|unset|undefined|required|must be set|no .*(?:key|token)|KeyError|not found|empty|expected/i;
216530
- escape10 = (text29) => text29.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
216531
- }
216532
- });
216533
-
216534
216797
  // backend/src/report.ts
216535
- import { readFile as readFile9, writeFile as writeFile9 } from "node:fs/promises";
216536
- 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";
216537
216800
  function okFalseError(response5) {
216538
216801
  if (typeof response5 !== "object" || response5 === null || response5.ok !== false) return void 0;
216539
216802
  const error65 = response5.error;
@@ -216582,7 +216845,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
216582
216845
  }
216583
216846
  const exit = t.exit === "invalid" && t.originalExit === "spawn_failed" ? "spawn_failed" : t.exit;
216584
216847
  if (!t.passed && exit !== "invalid" && !exitedCleanly({ exit, exitCode: t.exitCode }) && agentIssues.length < MAX_FAILURES_PER_SCENE) {
216585
- 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 } });
216586
216849
  }
216587
216850
  const valid2 = trialValid(t);
216588
216851
  for (const c of t.checks) {
@@ -216609,7 +216872,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
216609
216872
  }
216610
216873
  }
216611
216874
  for (const e of projectToolCalls(t.trace)) {
216612
- if (e.source === "agent") agentCalls2++;
216875
+ if (e.source === "agent" && !isAgentAnswer(e)) agentCalls2++;
216613
216876
  if (e.gap === true) {
216614
216877
  const key4 = JSON.stringify([e.service, e.method, e.path]);
216615
216878
  const gap6 = gaps2.get(key4);
@@ -216789,9 +217052,9 @@ function neverRanNextLine(n2, retry) {
216789
217052
  return `next: ${n2.fix === void 0 ? "fix what its log says" : "make the fix above"}, then ${retry.join(", then ")}`;
216790
217053
  }
216791
217054
  async function writeSummary(run6, summary) {
216792
- 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)}
216793
217056
  `);
216794
- await writeFile9(join21(dirname9(run6.dir), "latest"), `${run6.runId}
217057
+ await writeFile9(join22(dirname9(run6.dir), "latest"), `${run6.runId}
216795
217058
  `);
216796
217059
  }
216797
217060
  function formatRateDelta(value5) {
@@ -216966,7 +217229,7 @@ function sinceStart2(ms2) {
216966
217229
  async function withWorldEvidence(s3, runDir, failures) {
216967
217230
  const starts = /* @__PURE__ */ new Map();
216968
217231
  try {
216969
- const inputs2 = JSON.parse(await readFile9(join21(runDir, "inputs.json"), "utf8"));
217232
+ const inputs2 = JSON.parse(await readFile10(join22(runDir, "inputs.json"), "utf8"));
216970
217233
  for (const item2 of inputs2.cases ?? []) {
216971
217234
  const start = Date.parse(item2.scene?.start_time ?? "");
216972
217235
  if (Number.isFinite(start)) starts.set(item2.id, start);
@@ -216979,7 +217242,7 @@ async function withWorldEvidence(s3, runDir, failures) {
216979
217242
  let file3 = files2.get(key4);
216980
217243
  if (file3 === void 0) {
216981
217244
  const dir2 = s3.scenes.find((scene2) => scene2.sceneId === f2.sceneId)?.trialsDetail.find((t) => t.trial === f2.trial)?.dir;
216982
- 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) => {
216983
217246
  const value5 = JSON.parse(text29);
216984
217247
  return Array.isArray(value5) ? value5 : [];
216985
217248
  }).catch(() => []);
@@ -217128,19 +217391,19 @@ var init_report2 = __esm({
217128
217391
  });
217129
217392
 
217130
217393
  // backend/src/run-store.ts
217131
- import { readFile as readFile11, stat as stat5 } from "node:fs/promises";
217132
- 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";
217133
217396
  async function latestRunId(cwd, out) {
217134
217397
  if (out !== void 0) return resolveRunId(cwd, "latest", out);
217135
217398
  const dir2 = resolve18(cwd, DEFAULT_RUNS_DIR);
217136
217399
  let local2;
217137
217400
  try {
217138
- const path7 = join24(dir2, "latest");
217139
- 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 };
217140
217403
  } catch (error65) {
217141
217404
  if (!isEnoent(error65)) throw error65;
217142
217405
  }
217143
- const text29 = await readFile11(join24(dir2, "latest-cloud"), "utf8").catch((error65) => {
217406
+ const text29 = await readFile12(join25(dir2, "latest-cloud"), "utf8").catch((error65) => {
217144
217407
  if (!isEnoent(error65)) throw error65;
217145
217408
  return void 0;
217146
217409
  });
@@ -217159,7 +217422,7 @@ async function resolveRunId(cwd, ref22, out) {
217159
217422
  let runId2 = ref22;
217160
217423
  if (ref22 === "latest") {
217161
217424
  try {
217162
- runId2 = (await readFile11(join24(dir2, "latest"), "utf8")).trim();
217425
+ runId2 = (await readFile12(join25(dir2, "latest"), "utf8")).trim();
217163
217426
  } catch (e) {
217164
217427
  if (isEnoent(e)) throw new AnchaError("USAGE", `no runs found in ${dir2}`, { hint: "run `ancha run` first", cause: e });
217165
217428
  throw e;
@@ -217174,12 +217437,12 @@ async function loadRunSummary(cwd, ref22, out) {
217174
217437
  if (!RUN_ID.test(runId2)) throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint });
217175
217438
  let text29;
217176
217439
  try {
217177
- text29 = await readFile11(join24(dir2, runId2, "summary.json"), "utf8");
217440
+ text29 = await readFile12(join25(dir2, runId2, "summary.json"), "utf8");
217178
217441
  } catch (e) {
217179
217442
  if (!isEnoent(e)) throw e;
217180
- if (await stat5(join24(dir2, runId2)).then((s4) => s4.isDirectory(), () => false)) {
217443
+ if (await stat5(join25(dir2, runId2)).then((s4) => s4.isDirectory(), () => false)) {
217181
217444
  throw new AnchaError("USAGE", `run ${runId2} has no summary.json (it may have been interrupted)`, {
217182
- 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`,
217183
217446
  cause: e
217184
217447
  });
217185
217448
  }
@@ -217189,11 +217452,11 @@ async function loadRunSummary(cwd, ref22, out) {
217189
217452
  try {
217190
217453
  summary = JSON.parse(text29);
217191
217454
  } catch (e) {
217192
- 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 });
217193
217456
  }
217194
217457
  const s3 = summary;
217195
217458
  if (typeof s3 !== "object" || s3 === null || s3.runId !== runId2 || !Array.isArray(s3.scenes)) {
217196
- 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`);
217197
217460
  }
217198
217461
  return normalizeSummary(s3);
217199
217462
  }
@@ -217211,8 +217474,8 @@ var init_run_store = __esm({
217211
217474
 
217212
217475
  // backend/src/kit/assets.ts
217213
217476
  import { constants as constants8 } from "node:fs";
217214
- import { lstat as lstat4, mkdir as mkdir13, open as open6, readFile as readFile13, realpath as realpath5, rm as rm4 } from "node:fs/promises";
217215
- 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";
217216
217479
  import { fileURLToPath as fileURLToPath2 } from "node:url";
217217
217480
  function assetRoot() {
217218
217481
  return new URL("./assets/", import.meta.url);
@@ -217234,7 +217497,7 @@ async function preflightFiles(cwd, files2) {
217234
217497
  if (relative9(root3, target5).startsWith(`..${sep4}`)) throw invalid31(`path escapes project: ${file3.relativePath}`);
217235
217498
  const parts3 = file3.relativePath.split("/");
217236
217499
  for (let i = 1; i <= parts3.length; i++) {
217237
- const part = join26(root3, ...parts3.slice(0, i));
217500
+ const part = join27(root3, ...parts3.slice(0, i));
217238
217501
  try {
217239
217502
  const stat19 = await lstat4(part);
217240
217503
  if (stat19.isSymbolicLink() || (i < parts3.length ? !stat19.isDirectory() : !stat19.isFile())) throw invalid31(`unsafe scaffold target: ${relative9(root3, part)}`);
@@ -217249,7 +217512,7 @@ async function applyScaffold(cwd, files2) {
217249
217512
  const result = { created: [], skipped: [] };
217250
217513
  try {
217251
217514
  for (const file3 of files2) {
217252
- const target5 = join26(cwd, file3.relativePath);
217515
+ const target5 = join27(cwd, file3.relativePath);
217253
217516
  await mkdir13(dirname11(target5), { recursive: true });
217254
217517
  await preflightFiles(cwd, [file3]);
217255
217518
  let handle30;
@@ -217269,7 +217532,7 @@ async function applyScaffold(cwd, files2) {
217269
217532
  }
217270
217533
  return result;
217271
217534
  } catch (error65) {
217272
- 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 })));
217273
217536
  throw error65;
217274
217537
  }
217275
217538
  }
@@ -217278,7 +217541,7 @@ async function templateFiles(template3, suppliedRoot) {
217278
217541
  let manifest2;
217279
217542
  try {
217280
217543
  await preflightFiles(fileURLToPath2(root3), [{ relativePath: "manifest.json", content: "" }]);
217281
- manifest2 = JSON.parse(await readFile13(new URL("manifest.json", root3), "utf8"));
217544
+ manifest2 = JSON.parse(await readFile14(new URL("manifest.json", root3), "utf8"));
217282
217545
  } catch (cause) {
217283
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 });
217284
217547
  }
@@ -217288,7 +217551,7 @@ async function templateFiles(template3, suppliedRoot) {
217288
217551
  safePath3(name5);
217289
217552
  await preflightFiles(fileURLToPath2(root3), [{ relativePath: name5, content: "" }]);
217290
217553
  try {
217291
- 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") });
217292
217555
  } catch (cause) {
217293
217556
  throw new AnchaError("CONFIG_INVALID", `template file is missing: ${name5}`, { hint: "install a complete template pack", cause });
217294
217557
  }
@@ -217300,7 +217563,7 @@ async function templateFiles(template3, suppliedRoot) {
217300
217563
  for (const scene2 of scenes) {
217301
217564
  parseScene((0, import_yaml5.parse)(scene2.content));
217302
217565
  for (const companion of ["oracle.ts", "null.ts"]) {
217303
- const sibling = join26(dirname11(scene2.relativePath), companion);
217566
+ const sibling = join27(dirname11(scene2.relativePath), companion);
217304
217567
  if (!paths2.has(sibling)) throw invalid31(`template pack is missing ${sibling}`);
217305
217568
  }
217306
217569
  }
@@ -217332,7 +217595,7 @@ var init_workspace = __esm({
217332
217595
 
217333
217596
  // backend/src/execution/world-image.ts
217334
217597
  import { createHash as createHash62 } from "node:crypto";
217335
- import { readFile as readFile17 } from "node:fs/promises";
217598
+ import { readFile as readFile18 } from "node:fs/promises";
217336
217599
  function worldImageTag(companion, worker = new Uint8Array()) {
217337
217600
  const hash7 = createHash62("sha256");
217338
217601
  for (const part of [WORLD_DOCKERFILE, WORLD_PACKAGE_JSON, companion, worker]) hash7.update(part).update("\0");
@@ -217340,14 +217603,14 @@ function worldImageTag(companion, worker = new Uint8Array()) {
217340
217603
  }
217341
217604
  async function packagedCompanion() {
217342
217605
  try {
217343
- return await readFile17(new URL("harbor/companion.mjs", assetRoot()));
217606
+ return await readFile18(new URL("harbor/companion.mjs", assetRoot()));
217344
217607
  } catch (cause) {
217345
217608
  throw new AnchaError("CONFIG_INVALID", "The packaged world runtime is missing. Rebuild or reinstall Ancha.", { cause });
217346
217609
  }
217347
217610
  }
217348
217611
  async function packagedSuiteqlWorker() {
217349
217612
  try {
217350
- return await readFile17(new URL("harbor/suiteql-worker.mjs", assetRoot()));
217613
+ return await readFile18(new URL("harbor/suiteql-worker.mjs", assetRoot()));
217351
217614
  } catch (cause) {
217352
217615
  throw new AnchaError("CONFIG_INVALID", "The packaged query runtime is missing. Rebuild or reinstall Ancha.", { cause });
217353
217616
  }
@@ -217588,9 +217851,9 @@ __export(harbor_exports, {
217588
217851
  validateHarborBatchSetup: () => validateHarborBatchSetup
217589
217852
  });
217590
217853
  import { execFile as execFile7, spawn as spawn4 } from "node:child_process";
217591
- 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";
217592
217855
  import { tmpdir as tmpdir4, homedir } from "node:os";
217593
- 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";
217594
217857
  import { fileURLToPath as fileURLToPath4 } from "node:url";
217595
217858
  import { promisify as promisify7 } from "node:util";
217596
217859
  async function exists3(path7) {
@@ -217602,9 +217865,9 @@ async function exists3(path7) {
217602
217865
  }
217603
217866
  }
217604
217867
  async function runtimePaths(workspaceDir = process.cwd()) {
217605
- const candidates = [join31(workspaceDir, ".ancha/harbor-runtime"), join31(workspaceDir, ".ancha/harbor-spike")];
217606
- 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);
217607
- 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");
217608
217871
  return { python, dockerConfig };
217609
217872
  }
217610
217873
  async function checkHarborRuntime(workspaceDir = process.cwd()) {
@@ -217652,10 +217915,10 @@ function validateHarborBatchSetup(agent, resolvedAgent, configuration) {
217652
217915
  async function cleanupHarborBatch(workspaceDir, batchId) {
217653
217916
  if (!/^[A-Za-z0-9_-]{1,120}$/.test(batchId)) throw new AnchaError("CONFIG_INVALID", "Invalid batch identity for cleanup.");
217654
217917
  await preflightFiles(workspaceDir, [{ relativePath: `.ancha/harbor-runtime/controllers/${batchId}.json`, content: "" }]);
217655
- const controller = join31(workspaceDir, ".ancha/harbor-runtime/controllers", batchId + ".json");
217918
+ const controller = join32(workspaceDir, ".ancha/harbor-runtime/controllers", batchId + ".json");
217656
217919
  let marker;
217657
217920
  try {
217658
- marker = JSON.parse(await readFile18(controller, "utf8"));
217921
+ marker = JSON.parse(await readFile19(controller, "utf8"));
217659
217922
  } catch (error65) {
217660
217923
  if (error65.code !== "ENOENT") throw new AnchaError("INTERNAL", "The previous execution controller record could not be read.");
217661
217924
  }
@@ -217756,8 +218019,8 @@ async function executeHarborBatch(input4) {
217756
218019
  await mkdir16(input4.runDir, { recursive: true, mode: 448 });
217757
218020
  await chmod6(input4.runDir, 448);
217758
218021
  const usedResolved = resolvedEntries.filter((entry3) => usedEntries.includes(entry3.entryId));
217759
- 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 });
217760
- 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-"));
217761
218024
  let peopleBridge, peopleController;
217762
218025
  let runtimeSignal = input4.signal;
217763
218026
  const final = /* @__PURE__ */ new Map();
@@ -217792,21 +218055,21 @@ async function executeHarborBatch(input4) {
217792
218055
  peopleController = peopleBridge ? new PeopleLeaseController(peopleBridge, input4.batchId) : void 0;
217793
218056
  runtimeSignal = peopleController ? AbortSignal.any([peopleController.signal, ...input4.signal ? [input4.signal] : []]) : input4.signal;
217794
218057
  for (const entry3 of resolvedEntries.filter((candidate) => usedEntries.includes(candidate.entryId))) {
217795
- entry3.source = join31(privateDir, "source-" + entry3.entryId);
218058
+ entry3.source = join32(privateDir, "source-" + entry3.entryId);
217796
218059
  const staged = await stageProject(entry3.resolvedAgent.cwd, entry3.policy.files, entry3.source);
217797
218060
  entry3.workspaceBytes = workspaceSizeBytes(staged.bytes, entry3.policy.memoryMb);
217798
218061
  }
217799
- const tasksRoot = join31(privateDir, "tasks");
218062
+ const tasksRoot = join32(privateDir, "tasks");
217800
218063
  await mkdir16(tasksRoot);
217801
218064
  const tasks = [];
217802
218065
  for (const attempt of input4.attempts) {
217803
218066
  const selected2 = attemptEntries.get(attempt.id);
217804
218067
  const entry3 = resolvedEntries.find((candidate) => candidate.entryId === (selected2?.entryId ?? "legacy"));
217805
218068
  const { taskInput, policy, image: image2, compiled: compiled2 } = entry3;
217806
- const path7 = join31(tasksRoot, attempt.id);
217807
- await mkdir16(join31(path7, "environment"), { recursive: true });
217808
- await writeFile14(join31(path7, "instruction.md"), attempt.prompt, { mode: 384 });
217809
- 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"
217810
218073
  [agent]
217811
218074
  timeout_sec = ${(attempt.timeoutMs + 45e3 + (taskInput.kind === "http" ? taskInput.startupTimeoutMs ?? DEFAULT_HTTP_STARTUP_TIMEOUT_MS : 0)) / 1e3}
217812
218075
  user = "65532"
@@ -217828,21 +218091,21 @@ network_mode = "public"
217828
218091
  if (peopleLease) secrets2.push(peopleLease.token);
217829
218092
  const peopleTools = peopleLease ? peopleLeaseTools(peopleLease) : void 0;
217830
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 } } : {} } };
217831
- 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 });
217832
218095
  tasks.push({ path: path7 });
217833
218096
  record28({ attemptId: attempt.id, status: "queued", at: (/* @__PURE__ */ new Date()).toISOString() });
217834
218097
  }
217835
218098
  const paths2 = await runtimePaths(input4.workspaceDir);
217836
- 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 } };
217837
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 }])) };
217838
- const inputFile = join31(privateDir, "input.json");
218101
+ const inputFile = join32(privateDir, "input.json");
217839
218102
  await writeFile14(inputFile, JSON.stringify(data5), { mode: 384 });
217840
218103
  const driver = await driverPath();
217841
- await mkdir16(join31(privateDir, "home"));
218104
+ await mkdir16(join32(privateDir, "home"));
217842
218105
  input4.signal?.throwIfAborted();
217843
218106
  if (eventError) throw new AnchaError("INTERNAL", "Execution progress could not be persisted.");
217844
218107
  if (peopleController?.signal.aborted) return await peopleSetupFailed();
217845
- 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"] });
217846
218109
  ownedChild = child2;
217847
218110
  const completion = new Promise((resolve55, reject4) => {
217848
218111
  child2.once("error", reject4);
@@ -217852,10 +218115,10 @@ network_mode = "public"
217852
218115
  void completion.catch(() => {
217853
218116
  });
217854
218117
  if (child2.pid) {
217855
- const controllers = join31(input4.workspaceDir, ".ancha/harbor-runtime/controllers");
218118
+ const controllers = join32(input4.workspaceDir, ".ancha/harbor-runtime/controllers");
217856
218119
  await mkdir16(controllers, { recursive: true, mode: 448 });
217857
218120
  await preflightFiles(input4.workspaceDir, [{ relativePath: controllerPath, content: "" }]);
217858
- 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 });
217859
218122
  }
217860
218123
  let diagnostic = "";
217861
218124
  const redactor2 = redactedLog([...secrets2, ...peopleBridge ? [peopleBridge.token] : []], (text29) => {
@@ -217905,7 +218168,7 @@ network_mode = "public"
217905
218168
  redactor2.end();
217906
218169
  }
217907
218170
  await queued;
217908
- await writeFile14(join31(input4.runDir, "harbor.log"), diagnostic, { mode: 384 });
218171
+ await writeFile14(join32(input4.runDir, "harbor.log"), diagnostic, { mode: 384 });
217909
218172
  if (eventError) throw new AnchaError("INTERNAL", "Execution progress could not be persisted.");
217910
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." });
217911
218174
  await queued;
@@ -220184,8 +220447,8 @@ var init_production_state = __esm({
220184
220447
 
220185
220448
  // backend/src/production.ts
220186
220449
  import { createHash as createHash64 } from "node:crypto";
220187
- import { readFile as readFile20, writeFile as writeFile15 } from "node:fs/promises";
220188
- 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";
220189
220452
  function productionLines(made) {
220190
220453
  const records4 = [...(made.native ?? []).map((entry3) => ({ kind: "api", entry: entry3 })), ...made.calls.map((c) => ({ kind: "tool", ...c }))];
220191
220454
  const at4 = (line2) => line2.kind === "api" ? Date.parse(line2.entry.tSim) : Date.parse(made.startedAt ?? "") + parseDuration(line2.at ?? "0ms");
@@ -220218,16 +220481,16 @@ function productionTrace(lines2) {
220218
220481
  return entries4;
220219
220482
  }
220220
220483
  async function productionRecord(dir2) {
220221
- 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);
220222
220485
  return text29 === void 0 ? void 0 : productionTrace(text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2)));
220223
220486
  }
220224
220487
  async function completeProduction(scenePath, scene2, judge, into) {
220225
220488
  const dir2 = dirname14(scenePath);
220226
- 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);
220227
220490
  if (text29 === void 0) return [];
220228
220491
  const lines2 = text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
220229
- const file3 = into ?? join34(dir2, "production.json");
220230
- 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), () => ({}));
220231
220494
  const checks2 = { ...known2.checks }, signatures = { ...known2.signatures };
220232
220495
  const sign3 = productionSignature;
220233
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));
@@ -220278,15 +220541,15 @@ var init_production = __esm({
220278
220541
  });
220279
220542
 
220280
220543
  // backend/src/production-comparison.ts
220281
- import { readFile as readFile21 } from "node:fs/promises";
220282
- 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";
220283
220546
  async function reproductionOf(summary, scenePaths, cwd, runDir, scenes = [], productionFiles = {}) {
220284
220547
  const out = [];
220285
220548
  for (const scene2 of summary.scenes) {
220286
220549
  const path7 = scenePaths[scene2.sceneId];
220287
220550
  if (path7 === void 0) continue;
220288
- const file3 = Object.hasOwn(productionFiles, scene2.sceneId) ? productionFiles[scene2.sceneId] : join35(dirname15(resolve24(cwd, path7)), "production.json");
220289
- 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);
220290
220553
  if (production3?.checks === void 0) continue;
220291
220554
  const checks2 = Object.entries(production3.checks).flatMap(([check4, result]) => {
220292
220555
  const here = scene2.checks[check4];
@@ -220311,7 +220574,7 @@ async function reproductionOf(summary, scenePaths, cwd, runDir, scenes = [], pro
220311
220574
  async function answerSources(runDir, scene2) {
220312
220575
  const counts = {};
220313
220576
  for (const { trial } of scene2.trialsDetail) {
220314
- 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(() => "");
220315
220578
  for (const entry3 of text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2))) {
220316
220579
  const source = entry3.service === "tools" && entry3.path?.startsWith("/tools/") ? entry3.response?.source : void 0;
220317
220580
  if (source) counts[source] = (counts[source] ?? 0) + 1;
@@ -220326,7 +220589,7 @@ async function writesOf(scene2, dir2, runDir, ran) {
220326
220589
  for (const action of actionsOf(scene2, record28)) made.set(action.tool, (made.get(action.tool) ?? 0) + 1);
220327
220590
  const trials = (ran.trialsDetail ?? []).filter((t) => t.valid !== false);
220328
220591
  for (const { trial } of trials) {
220329
- 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(() => "");
220330
220593
  const trace = text29.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
220331
220594
  for (const tool of new Set(actionsOf(scene2, trace).map((action) => action.tool))) here.set(tool, (here.get(tool) ?? 0) + 1);
220332
220595
  }
@@ -220344,8 +220607,8 @@ var init_production_comparison = __esm({
220344
220607
 
220345
220608
  // backend/src/baselines.ts
220346
220609
  import { randomUUID as randomUUID13 } from "node:crypto";
220347
- import { link as link7, mkdir as mkdir17, readFile as readFile22, rename as rename6, unlink, writeFile as writeFile16 } from "node:fs/promises";
220348
- 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";
220349
220612
  function validateTrialCounts(scene2) {
220350
220613
  if (!Number.isSafeInteger(scene2.passed) || !Number.isSafeInteger(scene2.trials) || scene2.trials <= 0 || scene2.passed < 0 || scene2.passed > scene2.trials) {
220351
220614
  throw new AnchaError("USAGE", `invalid passed/trial counts for test ${scene2.sceneId}`);
@@ -220428,9 +220691,9 @@ function validateName(name5) {
220428
220691
  async function saveBaseline(cwd, name5, opts = {}, load6) {
220429
220692
  validateName(name5);
220430
220693
  const summary = load6 ? await load6() : await loadRunSummary(cwd, opts.from ?? "latest", opts.out);
220431
- const dir2 = baselineDir(cwd, opts.out), path7 = join36(dir2, `${name5}.json`);
220694
+ const dir2 = baselineDir(cwd, opts.out), path7 = join37(dir2, `${name5}.json`);
220432
220695
  await mkdir17(dir2, { recursive: true });
220433
- const temporary = join36(dir2, `.${name5}-${randomUUID13()}.tmp`);
220696
+ const temporary = join37(dir2, `.${name5}-${randomUUID13()}.tmp`);
220434
220697
  try {
220435
220698
  await writeFile16(temporary, `${JSON.stringify(summary, null, 2)}
220436
220699
  `, { flag: "wx", mode: 384 });
@@ -220448,10 +220711,10 @@ async function saveBaseline(cwd, name5, opts = {}, load6) {
220448
220711
  }
220449
220712
  async function loadComparisonSummary(cwd, ref22, out) {
220450
220713
  if (BASELINE_NAME.test(ref22) && ref22 !== "latest" && !ref22.startsWith("run_")) {
220451
- const path7 = join36(baselineDir(cwd, out), `${ref22}.json`);
220714
+ const path7 = join37(baselineDir(cwd, out), `${ref22}.json`);
220452
220715
  let text29;
220453
220716
  try {
220454
- text29 = await readFile22(path7, "utf8");
220717
+ text29 = await readFile23(path7, "utf8");
220455
220718
  } catch (error65) {
220456
220719
  if (error65.code !== "ENOENT") throw error65;
220457
220720
  }
@@ -220478,7 +220741,7 @@ var init_baselines = __esm({
220478
220741
  init_actions7();
220479
220742
  init_scenes();
220480
220743
  BASELINE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
220481
- 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");
220482
220745
  }
220483
220746
  });
220484
220747
 
@@ -220489,11 +220752,11 @@ __export(dependency_plan_exports, {
220489
220752
  });
220490
220753
  import { constants as constants9 } from "node:fs";
220491
220754
  import { open as open7 } from "node:fs/promises";
220492
- import { join as join38, resolve as resolve28 } from "node:path";
220755
+ import { join as join39, resolve as resolve28 } from "node:path";
220493
220756
  async function manifest(root3, name5) {
220494
220757
  let file3;
220495
220758
  try {
220496
- 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);
220497
220760
  const stat19 = await file3.stat();
220498
220761
  if (!stat19.isFile() || stat19.size > 32 * 1024 * 1024) throw new Error();
220499
220762
  return await file3.readFile("utf8");
@@ -220505,7 +220768,7 @@ async function manifest(root3, name5) {
220505
220768
  }
220506
220769
  }
220507
220770
  async function dependencyPlan(root3, options4 = {}) {
220508
- 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")];
220509
220772
  if (options4.install !== void 0) {
220510
220773
  if (typeof options4.install !== "string" || !options4.install.trim() || options4.install.length > 2e3 || /[\0\r\n]/.test(options4.install)) {
220511
220774
  throw new AnchaError("CONFIG_INVALID", "agent.install must be a non-empty single-line command of at most 2000 characters.");
@@ -220554,8 +220817,8 @@ var init_dependency_plan = __esm({
220554
220817
  });
220555
220818
 
220556
220819
  // backend/src/kit/detect.ts
220557
- import { readFile as readFile23 } from "node:fs/promises";
220558
- import { join as join39 } from "node:path";
220820
+ import { readFile as readFile24 } from "node:fs/promises";
220821
+ import { join as join40 } from "node:path";
220559
220822
  function dockerfileCommand(body7) {
220560
220823
  const lines2 = body7.split(/\r?\n/).filter((line2) => /^\s*CMD\s/i.test(line2));
220561
220824
  const last = lines2.at(-1)?.replace(/^\s*CMD\s+/i, "").trim();
@@ -220597,7 +220860,7 @@ async function detectProject(cwd, agent) {
220597
220860
  for (const name5 of ["package.json", "pyproject.toml", "requirements.txt", "Pipfile"]) {
220598
220861
  let body7;
220599
220862
  try {
220600
- body7 = await readFile23(join39(cwd, name5), "utf8");
220863
+ body7 = await readFile24(join40(cwd, name5), "utf8");
220601
220864
  } catch (error65) {
220602
220865
  if (error65.code === "ENOENT") continue;
220603
220866
  throw error65;
@@ -220617,7 +220880,7 @@ async function detectProject(cwd, agent) {
220617
220880
  }
220618
220881
  }
220619
220882
  if (node5 && python) evidence2.push("mixed Node/Python manifests; choose connect --lang explicitly");
220620
- const read7 = (name5) => readFile23(join39(cwd, name5), "utf8").catch((error65) => {
220883
+ const read7 = (name5) => readFile24(join40(cwd, name5), "utf8").catch((error65) => {
220621
220884
  if (error65.code === "ENOENT" || error65.code === "EISDIR") return void 0;
220622
220885
  throw error65;
220623
220886
  });
@@ -220671,7 +220934,7 @@ var init_detect = __esm({
220671
220934
 
220672
220935
  // backend/src/kit/task-input.ts
220673
220936
  import { open as open8, stat as stat8 } from "node:fs/promises";
220674
- 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";
220675
220938
  function taskVariable(name5) {
220676
220939
  if (!/^[A-Z][A-Z0-9_]*$/.test(name5) || name5.startsWith("ANCHA_")) return null;
220677
220940
  const parts3 = name5.split("_").filter(Boolean);
@@ -220768,7 +221031,7 @@ function taskInputsInText(text29) {
220768
221031
  }
220769
221032
  return rank(found);
220770
221033
  }
220771
- function words5(command) {
221034
+ function words6(command) {
220772
221035
  const commands = [[]];
220773
221036
  let word2 = "", quote6 = "", started = false;
220774
221037
  const end = () => {
@@ -220833,7 +221096,7 @@ function project12(root3) {
220833
221096
  }
220834
221097
  async function packageScript(p2, cwd, name5) {
220835
221098
  try {
220836
- 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];
220837
221100
  return typeof value5 === "string" ? value5 : void 0;
220838
221101
  } catch {
220839
221102
  return void 0;
@@ -220841,16 +221104,16 @@ async function packageScript(p2, cwd, name5) {
220841
221104
  }
220842
221105
  async function packageBin(p2, cwd, name5) {
220843
221106
  try {
220844
- const manifest2 = JSON.parse(await p2.read(join40(cwd, "package.json")) ?? "{}");
220845
- 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;
220846
221109
  const value5 = manifest2.bin?.[name5];
220847
- return typeof value5 === "string" ? join40(cwd, value5) : void 0;
221110
+ return typeof value5 === "string" ? join41(cwd, value5) : void 0;
220848
221111
  } catch {
220849
221112
  return void 0;
220850
221113
  }
220851
221114
  }
220852
221115
  async function pyprojectScript(p2, cwd, name5) {
220853
- const body7 = await p2.read(join40(cwd, "pyproject.toml"));
221116
+ const body7 = await p2.read(join41(cwd, "pyproject.toml"));
220854
221117
  const section2 = body7 === void 0 ? void 0 : /^\[(?:project\.scripts|tool\.poetry\.scripts)\]\s*\n((?:[^[\n].*\n?)*)/m.exec(body7)?.[1];
220855
221118
  const target5 = section2?.split("\n").map((line2) => /^\s*["']?([\w.-]+)["']?\s*=\s*["']([\w.]+)(?::\w+)?["']/.exec(line2)).find((match3) => match3?.[1] === name5)?.[2];
220856
221119
  return target5 === void 0 ? [] : pythonModule(cwd, target5);
@@ -220859,12 +221122,12 @@ async function entries3(p2, command, cwd = ".", depth = 0) {
220859
221122
  if (depth > 3) return [];
220860
221123
  const out = [];
220861
221124
  let dir2 = cwd;
220862
- for (let list18 of words5(command)) {
221125
+ for (let list18 of words6(command)) {
220863
221126
  while (list18.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(list18[0])) list18 = list18.slice(1);
220864
221127
  if (!list18.length) continue;
220865
221128
  const program2 = basename11(list18[0]), rest2 = list18.slice(1);
220866
221129
  if (program2 === "cd" && rest2[0] !== void 0) {
220867
- dir2 = join40(dir2, rest2[0]);
221130
+ dir2 = join41(dir2, rest2[0]);
220868
221131
  continue;
220869
221132
  }
220870
221133
  if (["uv", "poetry", "pipenv", "pdm", "rye", "hatch"].includes(program2) && rest2[0] === "run") {
@@ -220894,7 +221157,7 @@ async function entries3(p2, command, cwd = ".", depth = 0) {
220894
221157
  out.push(...await scriptEntry(p2, dir2, (program2 === "deno" || program2 === "bun") && rest2[0] === "run" ? rest2.slice(1) : rest2, false));
220895
221158
  continue;
220896
221159
  }
220897
- const path7 = join40(dir2, list18[0]);
221160
+ const path7 = join41(dir2, list18[0]);
220898
221161
  if (/[/.]/.test(list18[0]) && await p2.exists(path7)) {
220899
221162
  const text29 = await p2.read(path7) ?? "";
220900
221163
  const shebang = /^#!(.*)/.exec(text29)?.[1] ?? "";
@@ -220928,10 +221191,10 @@ async function scriptEntry(p2, dir2, args, python) {
220928
221191
  }
220929
221192
  const entry3 = args[i];
220930
221193
  if (entry3 === void 0 || /^[a-z][a-z\d+.-]*:/i.test(entry3)) return [];
220931
- const path7 = join40(dir2, entry3);
221194
+ const path7 = join41(dir2, entry3);
220932
221195
  if (await p2.exists(path7)) return [path7];
220933
221196
  const built3 = /^(?:\.\/)?(?:dist|build|out|lib)\/(.+)\.(?:c|m)?js$/.exec(entry3)?.[1];
220934
- 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}`))];
220935
221198
  }
220936
221199
  async function fallbackEntries(p2) {
220937
221200
  let main2;
@@ -220952,8 +221215,8 @@ async function imports(p2, file3, text29) {
220952
221215
  };
220953
221216
  if (extname(file3) === ".py") {
220954
221217
  const tryModule = async (base3, module) => {
220955
- const path7 = module ? join40(base3, ...module.split(".")) : base3;
220956
- 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)) {
220957
221220
  out.push(candidate);
220958
221221
  return true;
220959
221222
  }
@@ -220961,7 +221224,7 @@ async function imports(p2, file3, text29) {
220961
221224
  };
220962
221225
  for (const match3 of text29.matchAll(/^[ \t]*from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+(?:\(([^)]*)\)|([\w \t,*]+))/gm)) {
220963
221226
  const dots = match3[1].length, module = match3[2];
220964
- 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"];
220965
221228
  for (const base3 of bases2) {
220966
221229
  const found = await tryModule(base3, module);
220967
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);
@@ -220974,8 +221237,8 @@ async function imports(p2, file3, text29) {
220974
221237
  return out;
220975
221238
  }
220976
221239
  for (const match3 of text29.matchAll(/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)(['"])(\.{1,2}\/[^'"\n]+)\1/g)) {
220977
- const base3 = join40(from, match3[2]);
220978
- 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}`))];
220979
221242
  const js = /\.(c|m)?js$/.exec(base3);
220980
221243
  if (js) candidates.push(...[".ts", ".tsx", ".mts", ".cts"].map((ext) => base3.slice(0, -js[0].length) + ext));
220981
221244
  for (const candidate of candidates) if (keep2(candidate) && await p2.exists(candidate)) {
@@ -221172,7 +221435,7 @@ var init_task_input = __esm({
221172
221435
  };
221173
221436
  pythonModule = (cwd, module) => {
221174
221437
  const path7 = module.split(".").join("/");
221175
- 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));
221176
221439
  };
221177
221440
  NODE_VALUE_FLAGS = /* @__PURE__ */ new Set(["--require", "-r", "--import", "--loader", "--experimental-loader", "--tsconfig", "--config", "-c", "--env-file", "--conditions", "-C", "--title", "--inspect-port"]);
221178
221441
  PYTHON_VALUE_FLAGS = /* @__PURE__ */ new Set(["-W", "-X", "-Q"]);
@@ -221220,146 +221483,6 @@ var init_agent_tools3 = __esm({
221220
221483
  }
221221
221484
  });
221222
221485
 
221223
- // backend/src/agent-outcome.ts
221224
- function answerOf(entry3) {
221225
- const request2 = entry3.request ?? {};
221226
- const text29 = typeof request2.output === "string" ? request2.output : JSON.stringify(request2.output) ?? "";
221227
- return { source: request2.source === "reply" || request2.source === "stdout" ? request2.source : "done", text: text29 };
221228
- }
221229
- function kindOf2(path7) {
221230
- if (/^\/app\/site\/hosting\/restlet\.nl/i.test(path7)) return "restlet";
221231
- if (/^\/services\/NetSuitePort/i.test(path7)) return "soap";
221232
- if (path7.startsWith("/services/rest/query/v1/suiteql")) return "suiteql";
221233
- if (path7.startsWith("/services/rest/record/") || path7.startsWith("/services/rest/async/")) return "record";
221234
- if (path7.startsWith("/services/mcp/")) return "mcp";
221235
- if (path7.startsWith("/services/rest/auth/")) return "auth";
221236
- return "other";
221237
- }
221238
- function netsuiteStarterCustomers() {
221239
- const seed43 = toolStarterSeed("netsuite");
221240
- customers2 ??= (seed43.customers ?? []).map((c) => c.companyName ?? [c.firstName, c.lastName].filter(Boolean).join(" ")).filter((name5) => name5 !== "");
221241
- return customers2;
221242
- }
221243
- function namesStarterCustomer(answer) {
221244
- const said = words6(answer);
221245
- return netsuiteStarterCustomers().some((name5) => {
221246
- const whole2 = words6(name5), first = whole2.trim().split(" ")[0];
221247
- return said.includes(whole2) || first.length >= 5 && said.includes(` ${first} `);
221248
- });
221249
- }
221250
- function modelKeyName(host, given2) {
221251
- const [pattern, usual2] = PROVIDER_KEYS[host] ?? [/(?!)/, "NAME"];
221252
- return given2.find((name5) => pattern.test(name5) && /KEY|TOKEN/.test(name5)) ?? usual2;
221253
- }
221254
- function refusal3(entry3) {
221255
- const details = entry3.response?.["o:errorDetails"];
221256
- const code5 = Array.isArray(details) ? details[0]?.["o:errorCode"] : void 0;
221257
- return typeof code5 === "string" ? `${entry3.status} ${code5}` : String(entry3.status);
221258
- }
221259
- function unservedReason(unserved) {
221260
- const first = unserved[0], kind2 = kindOf2(first.path), call4 = `${first.method} ${first.path}${unserved.length > 1 ? ` ${times(unserved.length)}` : ""}`;
221261
- const what = kind2 === "restlet" ? "a RESTlet (your own SuiteScript)" : kind2 === "soap" ? "SuiteTalk SOAP web services" : "which Ancha's NetSuite does not serve";
221262
- return { message: `It called ${call4}, ${what}.`, fix: SERVED };
221263
- }
221264
- function answeredNetsuite(calls2, answer) {
221265
- 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)}`);
221266
- return `NetSuite: it ${parts3.length > 0 ? `called ${list17(parts3)} and ` : ""}answered ${quoted3(answer)}.`;
221267
- }
221268
- function endedSentence(view3) {
221269
- if (view3.exit === "spawn_failed") return "The agent could not be started.";
221270
- 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.`;
221271
- }
221272
- function attemptOutcome(view3, ctx) {
221273
- const calls2 = view3.trace.filter((entry3) => entry3.source === "agent" && !isAnswer(entry3));
221274
- const netsuite = calls2.filter((entry3) => entry3.service === "netsuite");
221275
- const unserved = netsuite.filter((entry3) => entry3.gap === true || kindOf2(entry3.path) === "restlet" || kindOf2(entry3.path) === "soap");
221276
- const used = netsuite.filter((entry3) => !unserved.includes(entry3)), data5 = used.filter((entry3) => kindOf2(entry3.path) !== "auth");
221277
- const served = used.filter((entry3) => entry3.status !== void 0 && entry3.status < 400);
221278
- const hosts = netsuiteHosts(view3.log);
221279
- const done = view3.trace.findLast(isAnswer), answer = done === void 0 ? void 0 : answerOf(done);
221280
- const byStatus = {};
221281
- for (const entry3 of calls2) if (entry3.status !== void 0) byStatus[String(entry3.status)] = (byStatus[String(entry3.status)] ?? 0) + 1;
221282
- const gaps2 = [...new Set(calls2.filter((entry3) => entry3.gap === true || unserved.includes(entry3)).map((entry3) => `${entry3.method} ${entry3.path}`))];
221283
- const summary = { total: calls2.length, byStatus, gaps: gaps2.slice(0, 5), hosts: hosts.slice(0, 5) };
221284
- const out = (reason2) => ({ reason: reason2, calls: summary, ...answer !== void 0 && { answer: { source: answer.source, text: answer.text.slice(0, 200) } } });
221285
- if (answer !== void 0 && (ctx.check === "start" || ctx.check === "netsuite" && namesStarterCustomer(answer.text))) {
221286
- if (unserved.length > 0) return out({ code: "unserved", level: "warning", ...unservedReason(unserved) });
221287
- return out({ code: "answered", level: "pass", message: ctx.check === "netsuite" ? answeredNetsuite(netsuite, answer.text) : `It took the task and answered ${quoted3(answer.text)}.` });
221288
- }
221289
- const model2 = view3.modelReplies?.find((reply5) => reply5.status === 401 || reply5.status === 403);
221290
- 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 ?? [])}` });
221291
- const refused2 = (entry3) => entry3.status === 401 || entry3.status === 403;
221292
- const turnedDown = used.length > 0 && used.every(refused2) ? used : data5.length > 0 && data5.every(refused2) ? data5 : [];
221293
- if (turnedDown.length > 0) {
221294
- const n2 = turnedDown.length;
221295
- 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 });
221296
- }
221297
- 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 });
221298
- if (unserved.length > 0 && data5.length === 0) return out({ code: "unserved", level: "fail", ...unservedReason(unserved) });
221299
- const crashed = view3.exit === "spawn_failed" || view3.exit === "exited" && view3.exitCode !== 0;
221300
- const did = calls2.length > 0 || ctx.taskMark !== void 0 && view3.log.includes(ctx.taskMark);
221301
- if (crashed && (ctx.check !== "start" || !did)) {
221302
- const tail = view3.logTail?.length ? view3.logTail : view3.log.trimEnd().split("\n").slice(-10);
221303
- const fix = ctx.taskFix ?? likelyFix(tail, { target: ctx.target ?? "cloud", ...ctx.command !== void 0 && { command: ctx.command } });
221304
- const key4 = ctx.taskFix === void 0 ? missingKey(tail) : void 0;
221305
- return out({ code: key4 !== void 0 && fix?.includes(key4) ? "missing_secret" : "crashed", level: "fail", message: endedSentence(view3), ...fix !== void 0 && { fix } });
221306
- }
221307
- if (view3.exit === "timeout" && view3.log.trim() === "" && calls2.length === 0 && !view3.modelReplies?.length && answer === void 0) {
221308
- 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";
221309
- 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 });
221310
- }
221311
- const level3 = ctx.answerChecked ? "fail" : "warning";
221312
- const called = netsuite.length > 0 ? `It called NetSuite ${times(netsuite.length)}` : ctx.check === "netsuite" ? "It made no NetSuite call" : "It";
221313
- 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 });
221314
- if (ctx.check === "netsuite") {
221315
- const names5 = netsuiteStarterCustomers();
221316
- return out({
221317
- code: "wrong_answer",
221318
- level: level3,
221319
- 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`] : []])}).`,
221320
- 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"
221321
- });
221322
- }
221323
- return out({ code: "answered", level: "pass", message: `It answered ${quoted3(answer.text)}.` });
221324
- }
221325
- var isAnswer, oneLine4, quoted3, times, list17, NETSUITE_HOST, netsuiteHosts, customers2, words6, PROVIDER_KEYS, SIGN, OUTSIDE, SERVED, NO_ANSWER, POST_ANSWER;
221326
- var init_agent_outcome = __esm({
221327
- "backend/src/agent-outcome.ts"() {
221328
- "use strict";
221329
- init_src();
221330
- init_agent_fix();
221331
- isAnswer = (entry3) => entry3.source === "agent" && entry3.service === "agent" && entry3.path === "/done";
221332
- oneLine4 = (text29) => text29.replace(/\s+/g, " ").trim();
221333
- quoted3 = (text29) => {
221334
- const line2 = oneLine4(text29);
221335
- return `"${line2.length > 80 ? `${line2.slice(0, 79)}\u2026` : line2}"`;
221336
- };
221337
- times = (n2) => n2 === 1 ? "once" : `${n2} times`;
221338
- list17 = (items2) => items2.length <= 1 ? items2.join("") : `${items2.slice(0, -1).join(", ")} and ${items2.at(-1)}`;
221339
- NETSUITE_HOST = /\b[a-z0-9-]+\.(?:suitetalk|restlets)\.api\.netsuite\.com\b|\b[a-z0-9-]+\.app\.netsuite\.com\b/gi;
221340
- netsuiteHosts = (log3) => [...new Set([...log3.matchAll(NETSUITE_HOST)].map((match3) => match3[0].toLowerCase()))];
221341
- words6 = (text29) => ` ${text29.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
221342
- PROVIDER_KEYS = {
221343
- "api.anthropic.com": [/ANTHROPIC|CLAUDE/, "ANTHROPIC_API_KEY"],
221344
- "api.openai.com": [/OPENAI/, "OPENAI_API_KEY"],
221345
- "openrouter.ai": [/OPENROUTER/, "OPENROUTER_API_KEY"],
221346
- "generativelanguage.googleapis.com": [/GEMINI|GOOGLE/, "GEMINI_API_KEY"],
221347
- "api.groq.com": [/GROQ/, "GROQ_API_KEY"],
221348
- "api.mistral.ai": [/MISTRAL/, "MISTRAL_API_KEY"],
221349
- "api.together.xyz": [/TOGETHER/, "TOGETHER_API_KEY"],
221350
- "api.fireworks.ai": [/FIREWORKS/, "FIREWORKS_API_KEY"],
221351
- "api.deepseek.com": [/DEEPSEEK/, "DEEPSEEK_API_KEY"],
221352
- "api.x.ai": [/XAI|GROK/, "XAI_API_KEY"],
221353
- "api.cohere.com": [/COHERE|CO_API/, "COHERE_API_KEY"]
221354
- };
221355
- SIGN = "The agent must sign with the variables Ancha gives: NETSUITE_ACCESS_TOKEN, or the four TBA values.";
221356
- OUTSIDE = "In Ancha it reaches NetSuite at NETSUITE_API_URL: build its URLs from that variable.";
221357
- SERVED = "Ancha's NetSuite serves REST records, SuiteQL, OAuth 2.0, OAuth 1.0 TBA and Oracle's MCP tools, not RESTlets or SOAP.";
221358
- NO_ANSWER = "gave no answer: post it to ANCHA_DONE_URL or print it last on stdout.";
221359
- 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';
221360
- }
221361
- });
221362
-
221363
221486
  // backend/src/execution/vm-connection.ts
221364
221487
  var vm_connection_exports = {};
221365
221488
  __export(vm_connection_exports, {
@@ -221372,9 +221495,9 @@ __export(vm_connection_exports, {
221372
221495
  taskFixFromLog: () => taskFixFromLog
221373
221496
  });
221374
221497
  import { closeSync as closeSync7, openSync as openSync7, writeSync as writeSync7 } from "node:fs";
221375
- import { mkdir as mkdir19, readFile as readFile24 } from "node:fs/promises";
221498
+ import { mkdir as mkdir19, readFile as readFile25 } from "node:fs/promises";
221376
221499
  import { createServer as createServer5 } from "node:net";
221377
- import { join as join41 } from "node:path";
221500
+ import { join as join42 } from "node:path";
221378
221501
  import { setTimeout as sleep10 } from "node:timers/promises";
221379
221502
  function executable(command) {
221380
221503
  let text29 = command.trimStart();
@@ -221433,11 +221556,12 @@ async function probeVmConnection(descriptor3, deps = {}) {
221433
221556
  const agent = deps.agent ?? withLocalEnvironment(resolveRunAgent(config11, descriptor3.projectDir, { ...descriptor3.options.agentCommand !== null && { agent: descriptor3.options.agentCommand }, parallel: 1 }).agent, config11);
221434
221557
  const http = agent.mode === "endpoint" || agent.taskInput?.kind === "http";
221435
221558
  probe.kind = http ? "http" : agent.taskInput?.kind === "per_event" ? "per_event" : "command";
221436
- 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");
221437
221561
  const scene2 = parseScene({ id: "connection", title: "Agent connection", twins: [], start_time: "2026-01-01T00:00:00Z", seed: {}, checks: [] });
221438
221562
  const env2 = { id: "connection", sceneId: scene2.id, services: {}, startTime: scene2.start_time, timeScale: 1 };
221439
221563
  await mkdir19(descriptor3.outDir, { recursive: true });
221440
- const logPath = join41(descriptor3.outDir, "agent.log");
221564
+ const logPath = join42(descriptor3.outDir, "agent.log");
221441
221565
  fd = openSync7(logPath, "w", 384);
221442
221566
  const timeout = AbortSignal.timeout(http ? agent.mode === "endpoint" ? agent.startupTimeoutMs : agent.taskInput?.kind === "http" ? agent.taskInput.startupTimeoutMs ?? 12e4 : 3e4 : 1e4);
221443
221567
  if (!http || asked2) {
@@ -221457,6 +221581,7 @@ async function probeVmConnection(descriptor3, deps = {}) {
221457
221581
  return await runWithTask(descriptor3, agent, {
221458
221582
  fd,
221459
221583
  probe,
221584
+ twins,
221460
221585
  ...deps.probeMs !== void 0 && { limit: deps.probeMs },
221461
221586
  open: deps.openBackend ?? (() => openBackend({ peopleRelay: cloudModelAccess(descriptor3.relay).peopleRelay }))
221462
221587
  });
@@ -221499,15 +221624,16 @@ async function probeVmConnection(descriptor3, deps = {}) {
221499
221624
  }
221500
221625
  }
221501
221626
  }
221502
- async function probeTwins(dir2, agent) {
221503
- 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);
221504
221629
  }
221505
221630
  function unfinished(trial) {
221506
221631
  return `The connection check could not finish: ${trial.harnessIssues.find((issue6) => issue6.owner === "harness")?.message ?? "the world failed"}.`;
221507
221632
  }
221508
221633
  async function runWithTask(descriptor3, agent, run6) {
221509
221634
  const { probe } = run6;
221510
- const twins = await probeTwins(descriptor3.agentDir, agent);
221635
+ const twins = run6.twins;
221636
+ probe.tools = probeToolCalls(twins, []);
221511
221637
  const netsuite = twins.includes("netsuite"), task2 = netsuite ? NETSUITE_PROBE_TASK : PROBE_TASK;
221512
221638
  const limit2 = run6.limit ?? (netsuite ? NETSUITE_PROBE_MS : PROBE_MS);
221513
221639
  const scene2 = parseScene({
@@ -221540,7 +221666,7 @@ async function runWithTask(descriptor3, agent, run6) {
221540
221666
  trials: 1,
221541
221667
  parallel: 1,
221542
221668
  seed: "connection",
221543
- outDir: join41(descriptor3.outDir, "connection"),
221669
+ outDir: join42(descriptor3.outDir, "connection"),
221544
221670
  root: descriptor3.projectDir,
221545
221671
  inheritedEnv: {},
221546
221672
  realTimeouts: { [scene2.id]: limit2 }
@@ -221551,13 +221677,15 @@ async function runWithTask(descriptor3, agent, run6) {
221551
221677
  await backend?.close().catch(() => {
221552
221678
  });
221553
221679
  }
221554
- 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);
221555
221681
  if (log3 !== void 0) writeSync7(run6.fd, log3);
221556
221682
  probe.durationMs = trial?.realMs ?? 0;
221557
221683
  probe.exitCode = trial?.exitCode ?? null;
221558
221684
  if (trial === void 0) return { state: "failed", probe, message: "The connection check could not start." };
221685
+ probe.tools = probeToolCalls(twins, trial.trace);
221559
221686
  const tail = trial.logTail, fix = taskFixFromLog(tail, agent);
221560
- 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")) {
221561
221689
  Object.assign(probe, { logTail: tail, ...fix !== void 0 && { fix } });
221562
221690
  return { state: "failed", probe, message: unfinished(trial) };
221563
221691
  }
@@ -221594,6 +221722,7 @@ var init_vm_connection = __esm({
221594
221722
  init_agent_env();
221595
221723
  init_run();
221596
221724
  init_relay3();
221725
+ init_connection_tools();
221597
221726
  init_agent_tools3();
221598
221727
  init_task_input();
221599
221728
  init_agent_outcome();
@@ -221614,9 +221743,9 @@ __export(assemble_exports, {
221614
221743
  finalizeInput: () => finalizeInput
221615
221744
  });
221616
221745
  import { createHash as createHash65 } from "node:crypto";
221617
- 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";
221618
221747
  import { tmpdir as tmpdir6 } from "node:os";
221619
- 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";
221620
221749
  function finalizeInput(value5) {
221621
221750
  const wrong = (what) => {
221622
221751
  throw new AnchaError("INTERNAL", `the finalize input ${what}`);
@@ -221710,7 +221839,7 @@ function inside2(root3, path7, what) {
221710
221839
  async function bundleManifest(bundleDir) {
221711
221840
  let manifest2;
221712
221841
  try {
221713
- manifest2 = JSON.parse(await readFile25(join42(bundleDir, "manifest.json"), "utf8"));
221842
+ manifest2 = JSON.parse(await readFile26(join43(bundleDir, "manifest.json"), "utf8"));
221714
221843
  } catch {
221715
221844
  throw new AnchaError("INTERNAL", "the bundle has no readable manifest.json");
221716
221845
  }
@@ -221735,7 +221864,7 @@ async function evidenceOf(folder2, input4, attempt) {
221735
221864
  };
221736
221865
  let manifest2;
221737
221866
  try {
221738
- manifest2 = JSON.parse(await readFile25(join42(folder2, "artifact.json"), "utf8"));
221867
+ manifest2 = JSON.parse(await readFile26(join43(folder2, "artifact.json"), "utf8"));
221739
221868
  } catch {
221740
221869
  broken("has no readable artifact.json");
221741
221870
  }
@@ -221747,9 +221876,9 @@ async function evidenceOf(folder2, input4, attempt) {
221747
221876
  const name5 = file3.path.slice(base3.length);
221748
221877
  if (!file3.path.startsWith(base3) || !FILE_NAME2.test(name5)) broken(`holds ${JSON.stringify(file3.path)}, which is not in its trial's directory`);
221749
221878
  if (files2.has(name5)) broken(`lists ${file3.path} twice`);
221750
- const path7 = join42(folder2, file3.path);
221879
+ const path7 = join43(folder2, file3.path);
221751
221880
  if (!await lstat8(path7).then((info) => info.isFile(), () => false)) broken(`has no ${file3.path}`);
221752
- const data5 = await readFile25(path7);
221881
+ const data5 = await readFile26(path7);
221753
221882
  if (data5.length !== file3.bytes || sha2565(data5) !== file3.sha256) broken(`has a ${file3.path} that differs from its artifact.json`);
221754
221883
  files2.set(name5, path7);
221755
221884
  }
@@ -221760,7 +221889,7 @@ async function rebuilt(files2, attempt, scene2, dir2) {
221760
221889
  if (resultFile === void 0) return { problem: "the attempt left no result.json" };
221761
221890
  let raw3;
221762
221891
  try {
221763
- raw3 = JSON.parse(await readFile25(resultFile, "utf8"));
221892
+ raw3 = JSON.parse(await readFile26(resultFile, "utf8"));
221764
221893
  } catch {
221765
221894
  return { problem: "the attempt's result.json is not JSON" };
221766
221895
  }
@@ -221781,7 +221910,7 @@ async function rebuilt(files2, attempt, scene2, dir2) {
221781
221910
  const traceFile = files2.get("trace.jsonl");
221782
221911
  if (traceFile !== void 0) {
221783
221912
  try {
221784
- 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));
221785
221914
  } catch {
221786
221915
  return { problem: "the attempt's trace.jsonl is not JSON lines" };
221787
221916
  }
@@ -221798,41 +221927,41 @@ function asInvalid(result, attempt) {
221798
221927
  }
221799
221928
  async function trialOf(attempt, item2, input4, artifactsDir, runDir) {
221800
221929
  if (attempt.state === "skipped" || attempt.state === "cancelled") return void 0;
221801
- 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}`);
221802
221931
  await mkdir20(dir2);
221803
221932
  const lost = (error65) => invalidTrial({ scene: scene2, trial: attempt.trial, dir: dir2, error: error65, service: "cloud" });
221804
221933
  let result;
221805
221934
  if (attempt.artifactHash === null) {
221806
221935
  result = await lost(attempt.error ?? { code: "INTERNAL", message: attempt.state === "invalid" ? "the attempt left no result" : "the attempt finished without its result" });
221807
221936
  } else {
221808
- const files2 = await evidenceOf(join42(artifactsDir, attempt.id), input4, attempt);
221937
+ const files2 = await evidenceOf(join43(artifactsDir, attempt.id), input4, attempt);
221809
221938
  const found = await rebuilt(files2, attempt, scene2, dir2);
221810
- 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));
221811
221940
  result = "result" in found ? asInvalid(found.result, attempt) : await lost({ code: "INTERNAL", message: found.problem });
221812
221941
  }
221813
221942
  result.caseId = attempt.caseId;
221814
221943
  result.attemptId ??= `${input4.jobId}/${attempt.caseId}/${attempt.trial}`;
221815
221944
  if (writeTools(scene2).size) result.actions = actionsOf(scene2, result.trace);
221816
221945
  if (Object.keys(scene2.tools ?? {}).length) result.answers = answersOf(result.trace);
221817
- 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)}
221818
221947
  `, { flag: "wx", mode: 384 });
221819
221948
  return result;
221820
221949
  }
221821
221950
  async function pinnedBaseline2(projectDir, pin2) {
221822
- const data5 = await readFile25(inside2(projectDir, pin2.path, "the baseline"));
221951
+ const data5 = await readFile26(inside2(projectDir, pin2.path, "the baseline"));
221823
221952
  if (sha2565(data5) !== pin2.sha256) throw new AnchaError("INTERNAL", `the baseline ${pin2.path} is not the one the run was submitted with`);
221824
221953
  const parsed4 = JSON.parse(data5.toString("utf8"));
221825
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}`);
221826
221955
  return normalizeSummary(parsed4);
221827
221956
  }
221828
221957
  async function productionComparison(summary, cases, projectDir, runDir, judge) {
221829
- const copies = await mkdtemp7(join42(tmpdir6(), "ancha-production-"));
221958
+ const copies = await mkdtemp7(join43(tmpdir6(), "ancha-production-"));
221830
221959
  try {
221831
221960
  const files2 = {}, errors3 = /* @__PURE__ */ new Map();
221832
221961
  for (const [index, item2] of cases.entries()) {
221833
- const scenePath = resolve30(projectDir, item2.path), file3 = join42(copies, `${index}.json`);
221962
+ const scenePath = resolve30(projectDir, item2.path), file3 = join43(copies, `${index}.json`);
221834
221963
  files2[item2.caseId] = file3;
221835
- await copyFile4(join42(dirname18(scenePath), "production.json"), file3).catch((error65) => {
221964
+ await copyFile4(join43(dirname18(scenePath), "production.json"), file3).catch((error65) => {
221836
221965
  if (error65.code !== "ENOENT") throw error65;
221837
221966
  });
221838
221967
  try {
@@ -221852,8 +221981,8 @@ async function productionComparison(summary, cases, projectDir, runDir, judge) {
221852
221981
  }
221853
221982
  }
221854
221983
  async function assembleCloudRun(options4) {
221855
- const input4 = finalizeInput(typeof options4.input === "string" ? JSON.parse(await readFile25(options4.input, "utf8")) : options4.input);
221856
- 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");
221857
221986
  checkMatrix(input4);
221858
221987
  await checkFolders(options4.artifactsDir, input4);
221859
221988
  const manifest2 = await bundleManifest(options4.bundleDir);
@@ -221862,14 +221991,14 @@ async function assembleCloudRun(options4) {
221862
221991
  if (agent.mode === "endpoint") throw new AnchaError("INTERNAL", "a cloud run runs an agent started by a command");
221863
221992
  const cases = await loadCases(projectDir, input4);
221864
221993
  const baseline = resolved.baseline === null ? void 0 : await pinnedBaseline2(projectDir, resolved.baseline);
221865
- const runDir = join42(options4.outDir, runId2);
221994
+ const runDir = join43(options4.outDir, runId2);
221866
221995
  await mkdir20(options4.outDir, { recursive: true });
221867
221996
  await mkdir20(runDir);
221868
221997
  const frozen = cases.map((item2) => {
221869
221998
  const value5 = { id: item2.caseId, scenarioId: item2.scene.id, seed: item2.seed, compiledFingerprint: sceneFingerprint(item2.scene), identity: {} };
221870
221999
  return { ...value5, fingerprint: sceneFingerprint(value5), scene: item2.scene };
221871
222000
  });
221872
- 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" } })}
221873
222002
  `, { flag: "wx", mode: 384 });
221874
222003
  const results = new Map(cases.map((item2) => [item2.caseId, { scene: item2.scene, trials: [], requestedTrials: resolved.attempts, ...item2.records !== void 0 && { records: item2.records } }]));
221875
222004
  for (const item2 of cases) {
@@ -221913,9 +222042,9 @@ async function assembleCloudRun(options4) {
221913
222042
  summary.reproduction = await productionComparison(summary, cases, projectDir, runDir, options4.judge ?? {});
221914
222043
  const json35 = (value5) => `${JSON.stringify(value5, null, 2)}
221915
222044
  `;
221916
- await writeFile18(join42(runDir, "reproduction.json"), json35(summary.reproduction), { flag: "wx", mode: 384 });
221917
- 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 });
221918
- 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 });
221919
222048
  const { archive } = await packRun({
221920
222049
  runDir,
221921
222050
  runId: runId2,
@@ -221926,7 +222055,7 @@ async function assembleCloudRun(options4) {
221926
222055
  secrets: [],
221927
222056
  inputsBytes: readsLargeInputs(input4.cliVersion) ? BUNDLE_LIMITS2.largeFileBytes : BUNDLE_LIMITS2.fileBytes
221928
222057
  });
221929
- const archivePath = join42(options4.outDir, `${runId2}.tar.gz`);
222058
+ const archivePath = join43(options4.outDir, `${runId2}.tar.gz`);
221930
222059
  await writeFile18(archivePath, archive, { flag: "wx", mode: 384 });
221931
222060
  return { archivePath, sha256: sha2565(archive), runId: runId2, exitCode: summary.exitCode, verdict: summary.verdict };
221932
222061
  }
@@ -222004,10 +222133,10 @@ __export(view_exports, {
222004
222133
  renderCloudView: () => renderCloudView
222005
222134
  });
222006
222135
  import { randomBytes as randomBytes6 } from "node:crypto";
222007
- import { readFile as readFile26 } from "node:fs/promises";
222136
+ import { readFile as readFile27 } from "node:fs/promises";
222008
222137
  import { dirname as dirname19 } from "node:path";
222009
222138
  async function renderCloudView(path7) {
222010
- const input4 = JSON.parse(await readFile26(path7, "utf8"));
222139
+ const input4 = JSON.parse(await readFile27(path7, "utf8"));
222011
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.");
222012
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.");
222013
222142
  const scene2 = "scene" in input4 ? parseScene(input4.scene) : "path" in input4 ? (await loadSceneOrTest(dirname19(path7), input4.path)).scene : null;
@@ -227349,9 +227478,9 @@ init_backend();
227349
227478
  init_src();
227350
227479
  init_credentials();
227351
227480
  import { execFile as execFile4 } from "node:child_process";
227352
- 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";
227353
227482
  import { tmpdir as tmpdir3 } from "node:os";
227354
- 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";
227355
227484
  import { promisify as promisify4 } from "node:util";
227356
227485
 
227357
227486
  // backend/src/cloud/dependencies.ts
@@ -228421,17 +228550,18 @@ ${conflicts.map(([path7, set2]) => `${path7} (${[...set2].sort().join(", ")})`).
228421
228550
  init_src();
228422
228551
  init_credentials();
228423
228552
  import { access as access7, mkdir as mkdir12, mkdtemp as mkdtemp3, rename as rename3, rm as rm2, writeFile as writeFile10 } from "node:fs/promises";
228424
- import { dirname as dirname10, join as join22 } from "node:path";
228553
+ import { dirname as dirname10, join as join23 } from "node:path";
228425
228554
  import { setTimeout as sleep9 } from "node:timers/promises";
228426
228555
 
228427
228556
  // backend/src/cloud/bundle.ts
228428
228557
  init_src();
228558
+ init_connection_tools();
228429
228559
  init_jobs_contract();
228430
228560
  import { createHash as createHash58 } from "node:crypto";
228431
228561
  import { constants as constants7 } from "node:fs";
228432
228562
  import { lstat as lstat3, open as open5, realpath as realpath4 } from "node:fs/promises";
228433
- import { join as join19 } from "node:path";
228434
- 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";
228435
228565
  var shared = jobs_contract_exports;
228436
228566
  var MIB2 = 1024 * 1024;
228437
228567
  var BUNDLE_PATH = /^(?!\/)(?!.*(?:^|\/)\.{0,2}(?:\/|$))[^\0-\x1f\x7f\\]+$/;
@@ -228439,7 +228569,7 @@ var sha2563 = (data5) => createHash58("sha256").update(data5).digest("hex");
228439
228569
  var mib2 = (bytes3) => `${(bytes3 / MIB2).toFixed(1)} MiB`;
228440
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 });
228441
228571
  async function readProjectFile(root3, path7) {
228442
- const file3 = join19(root3, ...path7.split("/"));
228572
+ const file3 = join20(root3, ...path7.split("/"));
228443
228573
  const stat19 = await lstat3(file3).catch(() => void 0);
228444
228574
  if (stat19 === void 0) throw new AnchaError("CONFIG_INVALID", `${path7} is missing`, { hint: "restore it, or change what names it" });
228445
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" });
@@ -228460,6 +228590,11 @@ async function buildBundle(input4) {
228460
228590
  if (input4.kind === "connect" && input4.tests.length > 0) throw new AnchaError("USAGE", "a connection check carries the project without tests");
228461
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" });
228462
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
+ }
228463
228598
  const paths2 = [...inventory.files.keys()];
228464
228599
  const invalid35 = paths2.filter((path7) => !BUNDLE_PATH.test(path7));
228465
228600
  if (invalid35.length) throw new AnchaError("CONFIG_INVALID", `a cloud bundle cannot name these files:
@@ -228476,7 +228611,7 @@ ${invalid35.map((path7) => JSON.stringify(path7)).join("\n")}`, { hint: "rename
228476
228611
  const contents = [];
228477
228612
  let bytes3 = 0;
228478
228613
  for (const [path7, roles2] of inventory.files) {
228479
- 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);
228480
228615
  if (path7.split("/").at(-1) === ".yarnrc.yml") {
228481
228616
  const release2 = yarnReleasePath(path7, read7.data.toString("utf8"));
228482
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" });
@@ -228754,21 +228889,21 @@ function onThisComputer(ref22) {
228754
228889
  }
228755
228890
  var CLOUD_JOB_FILE = "cloud-job.json";
228756
228891
  async function cachedCloudRun(ctx, id14, runsDir) {
228757
- const dir2 = join22(runsDir, id14);
228758
- 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;
228759
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}` });
228760
228895
  const ws = await jobWorkspace(ctx, id14), detail3 = await getJob(ws, id14);
228761
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` });
228762
228897
  const archive = await getArchive(ws, id14), manifest2 = validateBundle(archive);
228763
228898
  if (manifest2.runId !== id14 || manifest2.source !== "cloud") throw new AnchaError("INTERNAL", `the workspace answered another run's archive for ${id14}`);
228764
228899
  await mkdir12(runsDir, { recursive: true });
228765
- const temp = await mkdtemp3(join22(runsDir, `.${id14}-`));
228900
+ const temp = await mkdtemp3(join23(runsDir, `.${id14}-`));
228766
228901
  try {
228767
228902
  for (const entry3 of readBundle(archive)) {
228768
- await mkdir12(dirname10(join22(temp, entry3.path)), { recursive: true });
228769
- 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 });
228770
228905
  }
228771
- 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)}
228772
228907
  `, { mode: 384 });
228773
228908
  await rm2(dir2, { recursive: true, force: true });
228774
228909
  await rename3(temp, dir2);
@@ -228801,7 +228936,7 @@ function retryHint(response5) {
228801
228936
  if (!Number.isInteger(seconds6) || seconds6 <= 0) return "wait a little, then retry";
228802
228937
  return `retry in ${seconds6 < 120 ? `${seconds6} seconds` : `${Math.ceil(seconds6 / 60)} minutes`}`;
228803
228938
  }
228804
- async function refusal(response5, server) {
228939
+ async function refusal2(response5, server) {
228805
228940
  if (response5.status === 401) return authError(server, { status: 401, keySent: true });
228806
228941
  const body7 = await response5.json().catch(() => void 0);
228807
228942
  const error65 = typeof body7?.error === "object" && body7.error !== null ? body7.error : { message: typeof body7?.error === "string" ? body7.error : void 0 };
@@ -228838,7 +228973,7 @@ async function call2(ws, method2, path7, options4 = {}) {
228838
228973
  continue;
228839
228974
  }
228840
228975
  if (response5 === void 0) throw new AnchaError("SERVER_UNREACHABLE", `${ws.server} did not answer`, { hint: "check the network, then retry", cause: failure6 });
228841
- throw await refusal(response5, ws.server);
228976
+ throw await refusal2(response5, ws.server);
228842
228977
  }
228843
228978
  }
228844
228979
  var path6 = (id14, rest2 = "") => `/_jobs/${encodeURIComponent(id14)}${rest2}`;
@@ -228885,7 +229020,7 @@ async function* readEvents(ws, id14, after, follow2, signal) {
228885
229020
  if (signal?.aborted) throw error65;
228886
229021
  throw new AnchaError("SERVER_UNREACHABLE", `${ws.server} did not answer`, { cause: error65 });
228887
229022
  }
228888
- 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);
228889
229024
  const decoder = new TextDecoder();
228890
229025
  let tail = "";
228891
229026
  try {
@@ -229168,7 +229303,7 @@ async function forward(ctx, serverUrl3, words8, raw3) {
229168
229303
  continue;
229169
229304
  }
229170
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";
229171
- const content2 = await readFile10(path7).catch(() => void 0);
229306
+ const content2 = await readFile11(path7).catch(() => void 0);
229172
229307
  if (content2 === void 0) {
229173
229308
  if (flag5 === "--test") {
229174
229309
  argv.push(flag5, value5);
@@ -229202,7 +229337,7 @@ async function post4(server, key4, argv, files2) {
229202
229337
  throw new AnchaError("SERVER_UNREACHABLE", `${server} did not answer`, { hint: "check the network, then retry", cause: error65 });
229203
229338
  }
229204
229339
  if (response5.status === 401) throw authError(server, { status: 401, keySent: true });
229205
- if (!response5.ok || response5.body === null) throw await refusal2(response5, server);
229340
+ if (!response5.ok || response5.body === null) throw await refusal3(response5, server);
229206
229341
  return response5.body;
229207
229342
  }
229208
229343
  async function send2(ctx, server, key4, argv, files2 = {}) {
@@ -229242,7 +229377,7 @@ function optionValue(args, name5) {
229242
229377
  }
229243
229378
  return void 0;
229244
229379
  }
229245
- async function refusal2(response5, server) {
229380
+ async function refusal3(response5, server) {
229246
229381
  const body7 = await response5.json().catch(() => void 0);
229247
229382
  const error65 = typeof body7?.error === "object" ? body7.error : { message: typeof body7?.error === "string" ? body7.error : void 0 };
229248
229383
  if (response5.status === 429) return new AnchaError("USAGE", error65.message ?? "too many commands for this key", { hint: error65.hint ?? retryHint(response5) });
@@ -229301,13 +229436,13 @@ async function packProject(dir2) {
229301
229436
  const files2 = await projectFiles(root3);
229302
229437
  if (files2.length === 0) throw new AnchaError("USAGE", `${dir2} has no files to upload`, { hint: "check .gitignore and .anchaignore" });
229303
229438
  let bytes3 = 0;
229304
- 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;
229305
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" });
229306
- const temporary = await mkdtemp4(join23(tmpdir3(), "ancha-pack-"));
229441
+ const temporary = await mkdtemp4(join24(tmpdir3(), "ancha-pack-"));
229307
229442
  try {
229308
- await writeFile11(join23(temporary, "files"), files2.join("\0"));
229309
- await run3("tar", ["-czf", join23(temporary, "project.tar.gz"), "-C", root3, "--null", "-T", join23(temporary, "files")], { maxBuffer: 16 * 1024 * 1024 });
229310
- 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 };
229311
229446
  } finally {
229312
229447
  await rm3(temporary, { recursive: true, force: true });
229313
229448
  }
@@ -229410,8 +229545,8 @@ function registerEnv(program2, ctx) {
229410
229545
  // packages/cli/src/commands/explain.ts
229411
229546
  init_src();
229412
229547
  init_src();
229413
- import { access as access11, readFile as readFile31, writeFile as writeFile21 } from "node:fs/promises";
229414
- 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";
229415
229550
 
229416
229551
  // packages/cli/src/numbers.ts
229417
229552
  init_src();
@@ -229434,8 +229569,8 @@ init_report2();
229434
229569
  init_src();
229435
229570
  init_report2();
229436
229571
  init_run_inputs();
229437
- import { readFile as readFile12 } from "node:fs/promises";
229438
- import { join as join25 } from "node:path";
229572
+ import { readFile as readFile13 } from "node:fs/promises";
229573
+ import { join as join26 } from "node:path";
229439
229574
  var CALLS_SHOWN = 200;
229440
229575
  var LOG_LINES = 40;
229441
229576
  var ANSWER_CHARS = 5e4;
@@ -229449,13 +229584,13 @@ var trialFolder = (sceneId, trial) => `trial-${sceneId}-${trial}`;
229449
229584
  async function readRunRecords(runDir, summary, options4) {
229450
229585
  const json35 = async (path7) => {
229451
229586
  try {
229452
- return JSON.parse(await readFile12(path7, "utf8"));
229587
+ return JSON.parse(await readFile13(path7, "utf8"));
229453
229588
  } catch {
229454
229589
  return null;
229455
229590
  }
229456
229591
  };
229457
- const text29 = async (path7) => readFile12(path7, "utf8").catch(() => null);
229458
- 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"));
229459
229594
  let atOnce2 = null;
229460
229595
  try {
229461
229596
  const first = JSON.parse(events3?.split("\n", 1)[0] ?? "");
@@ -229464,9 +229599,9 @@ async function readRunRecords(runDir, summary, options4) {
229464
229599
  }
229465
229600
  const trials = /* @__PURE__ */ new Map();
229466
229601
  for (const scene2 of summary.scenes) for (const trial of scene2.trialsDetail) {
229467
- const dir2 = join25(runDir, trialFolder(scene2.sceneId, trial.trial));
229468
- const trace = await text29(join25(dir2, "trace.jsonl"));
229469
- 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;
229470
229605
  trials.set(trialKey(scene2.sceneId, trial.trial), {
229471
229606
  trace: trace === null ? null : trace.split("\n").flatMap((line2) => {
229472
229607
  if (!line2.trim()) return [];
@@ -229477,12 +229612,12 @@ async function readRunRecords(runDir, summary, options4) {
229477
229612
  }
229478
229613
  }),
229479
229614
  checks: Array.isArray(checks2) ? checks2 : null,
229480
- state: await json35(join25(dir2, "state.json")),
229481
- log: await text29(join25(dir2, "agent.log"))
229615
+ state: await json35(join26(dir2, "state.json")),
229616
+ log: await text29(join26(dir2, "agent.log"))
229482
229617
  });
229483
229618
  }
229484
- const inputs2 = await json35(join25(runDir, "inputs.json"));
229485
- 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 ?? [] };
229486
229621
  }
229487
229622
  var noRecords = (folder2) => ({ folder: folder2, inputs: null, bundle: null, job: null, atOnce: null, trials: /* @__PURE__ */ new Map(), secrets: [] });
229488
229623
  var SECRET_SHAPES = [
@@ -229619,7 +229754,7 @@ function attemptOf2(scene2, detail3, n2, anchor2, records4, sceneRecord, cloud,
229619
229754
  const start = Date.parse(sceneRecord?.start_time ?? "");
229620
229755
  const agentCalls2 = trace.filter((entry3) => entry3.source === "agent" && entry3.service !== "agent");
229621
229756
  const done = [...trace].reverse().find((entry3) => entry3.source === "agent" && entry3.service === "agent" && entry3.path === "/done");
229622
- 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;
229623
229758
  const answerText2 = output2 === void 0 ? null : typeof output2 === "string" ? output2 : JSON.stringify(output2, null, 2);
229624
229759
  const source = isObject5(done?.request) && typeof done.request.source === "string" ? done.request.source : "done";
229625
229760
  const seed43 = sceneRecord?.seed;
@@ -229808,7 +229943,7 @@ function verdictBlock(d) {
229808
229943
  const each = [...new Set(d.tests.map((test3) => test3.requested))].sort((a, b) => a - b);
229809
229944
  const stat19 = (term2, value5, more2 = "") => `<div><dt>${term2}</dt><dd><span class="big">${value5}</span>${more2}</dd></div>`;
229810
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>`;
229811
- 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>`;
229812
229947
  const failed = d.tests.flatMap((test3) => test3.attempts).filter((a) => a.outcome === "failed");
229813
229948
  const fails = failed.slice(0, FAILED_SHOWN).map((a) => {
229814
229949
  const check4 = a.checks.find((c) => c.state === "failed");
@@ -230016,7 +230151,7 @@ h1 a{text-decoration:none}h1 a:hover{text-decoration:underline}
230016
230151
  .v-lines{margin:0;padding-left:20px;display:grid;gap:4px;color:var(--mid)}
230017
230152
  .v-lines a{color:var(--text)}
230018
230153
  .cmp{margin:0;color:var(--mid)}
230019
- .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}
230020
230155
  .cell{display:block;height:22px;border-radius:3px}
230021
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)}
230022
230157
  .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
@@ -230332,7 +230467,7 @@ async function consoleApi(base3) {
230332
230467
  // packages/cli/src/commands/playground.ts
230333
230468
  var import_yaml8 = __toESM(require_dist(), 1);
230334
230469
  init_src();
230335
- import { readFile as readFile29, stat as stat10 } from "node:fs/promises";
230470
+ import { readFile as readFile30, stat as stat10 } from "node:fs/promises";
230336
230471
  import { resolve as resolve33 } from "node:path";
230337
230472
 
230338
230473
  // backend/src/playgrounds/service.ts
@@ -230363,7 +230498,7 @@ init_docker();
230363
230498
  init_source();
230364
230499
  import { cp, mkdtemp as mkdtemp6, rm as rm8 } from "node:fs/promises";
230365
230500
  import { tmpdir as tmpdir5 } from "node:os";
230366
- import { join as join32 } from "node:path";
230501
+ import { join as join33 } from "node:path";
230367
230502
 
230368
230503
  // backend/src/execution/capacity.ts
230369
230504
  init_src();
@@ -230414,7 +230549,7 @@ init_assets();
230414
230549
  import { randomUUID as randomUUID7 } from "node:crypto";
230415
230550
  import { execFileSync } from "node:child_process";
230416
230551
  import { chmod as chmod4, mkdir as mkdir14 } from "node:fs/promises";
230417
- import { join as join27 } from "node:path";
230552
+ import { join as join28 } from "node:path";
230418
230553
  import Database3 from "better-sqlite3";
230419
230554
  var BASE3 = ".ancha/playgrounds";
230420
230555
  function runId(value5) {
@@ -230462,9 +230597,9 @@ var AdmissionStore = class {
230462
230597
  async withDb(fn) {
230463
230598
  const relative26 = `${BASE3}/ownership.sqlite`;
230464
230599
  await preflightFiles(this.workspace, [relative26, `${relative26}-journal`, `${relative26}-wal`, `${relative26}-shm`].map((relativePath) => ({ relativePath, content: "" })));
230465
- await mkdir14(join27(this.workspace, BASE3), { recursive: true, mode: 448 });
230466
- await chmod4(join27(this.workspace, BASE3), 448);
230467
- 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));
230468
230603
  try {
230469
230604
  db3.pragma("busy_timeout = 5000");
230470
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);
@@ -230472,7 +230607,7 @@ var AdmissionStore = class {
230472
230607
  CREATE TABLE IF NOT EXISTS submissions (key TEXT PRIMARY KEY, signature TEXT NOT NULL, runId TEXT NOT NULL);
230473
230608
  CREATE TABLE IF NOT EXISTS orphans (runId TEXT PRIMARY KEY);`);
230474
230609
  ensureAdmissionSchema(db3);
230475
- await chmod4(join27(this.workspace, relative26), 384);
230610
+ await chmod4(join28(this.workspace, relative26), 384);
230476
230611
  return fn(db3);
230477
230612
  } finally {
230478
230613
  db3.close();
@@ -230652,14 +230787,14 @@ init_src();
230652
230787
  import { createHash as createHash60, randomUUID as randomUUID8 } from "node:crypto";
230653
230788
  import { execFile as execFile6 } from "node:child_process";
230654
230789
  import { promisify as promisify6 } from "node:util";
230655
- 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";
230656
- 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";
230657
230792
  init_config();
230658
230793
  init_assets();
230659
230794
 
230660
230795
  // backend/src/console/catalog.ts
230661
- import { readFile as readFile14, realpath as realpath6, stat as stat6 } from "node:fs/promises";
230662
- 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";
230663
230798
  import { fileURLToPath as fileURLToPath3 } from "node:url";
230664
230799
  var import_yaml6 = __toESM(require_dist(), 1);
230665
230800
  init_src();
@@ -230668,9 +230803,9 @@ init_scenes();
230668
230803
  init_config();
230669
230804
  async function safeRead(root3, path7, max = 2e6) {
230670
230805
  await preflightFiles(root3, [{ relativePath: path7, content: "" }]);
230671
- const file3 = join28(root3, path7);
230806
+ const file3 = join29(root3, path7);
230672
230807
  if ((await stat6(file3)).size > max) throw new AnchaError("USAGE", "file exceeds the console display limit");
230673
- return readFile14(file3, "utf8");
230808
+ return readFile15(file3, "utf8");
230674
230809
  }
230675
230810
  function parseDefinition(yaml) {
230676
230811
  const doc = (0, import_yaml6.parseDocument)(yaml);
@@ -230697,7 +230832,7 @@ var ScenarioCatalog = class {
230697
230832
  const add = async (root3, path7, origin) => {
230698
230833
  try {
230699
230834
  const yaml = await safeRead(root3, path7);
230700
- const absolute2 = await realpath6(join28(root3, path7));
230835
+ const absolute2 = await realpath6(join29(root3, path7));
230701
230836
  if (seen.has(absolute2)) return;
230702
230837
  seen.add(absolute2);
230703
230838
  const scene2 = parseDefinition(yaml);
@@ -230779,7 +230914,7 @@ init_policy();
230779
230914
 
230780
230915
  // backend/src/execution/provider.ts
230781
230916
  init_src();
230782
- 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";
230783
230918
  import { isAbsolute as isAbsolute7, relative as relative10, resolve as resolve21 } from "node:path";
230784
230919
  var providerDetails = {
230785
230920
  openrouter: { key: "OPENROUTER_API_KEY", modelVariable: "OPENROUTER_MODEL", host: "openrouter.ai", baseVariable: "OPENROUTER_BASE_URL", baseUrl: "https://openrouter.ai/api/v1" },
@@ -230826,7 +230961,7 @@ async function readApprovedOpenRouterKey(workspace4) {
230826
230961
  const actual = await realpath7(path7);
230827
230962
  if (actual !== path7 || actual !== resolve21(root3, ".ancha/openrouter.env")) return void 0;
230828
230963
  if (fileStat.size > 16384) return void 0;
230829
- const contents = await readFile15(path7, "utf8");
230964
+ const contents = await readFile16(path7, "utf8");
230830
230965
  const keys5 = contents.split(/\r?\n/).flatMap((line2) => {
230831
230966
  const match3 = /^\s*OPENROUTER_API_KEY\s*=\s*(.*?)\s*$/.exec(line2);
230832
230967
  if (!match3) return [];
@@ -230923,9 +231058,9 @@ async function identifyCode(cwd) {
230923
231058
  const content2 = createHash60("sha256");
230924
231059
  let bytes3 = 0;
230925
231060
  for (const file3 of files2) {
230926
- const path7 = join29(cwd, file3), info = await lstat6(path7);
231061
+ const path7 = join30(cwd, file3), info = await lstat6(path7);
230927
231062
  if (!info.isFile() || (bytes3 += info.size) > 2e7) throw new Error("source scope incomplete");
230928
- content2.update(file3).update("\0").update(await readFile16(path7)).update("\0");
231063
+ content2.update(file3).update("\0").update(await readFile17(path7)).update("\0");
230929
231064
  }
230930
231065
  const sourceHash = content2.digest("hex");
230931
231066
  return { ...git, sourceFiles: files2.length, codeCoverage: git ? "tracked-and-source" : "source-files", mutable: true, fingerprint: hash5({ git, sourceHash }) };
@@ -230949,7 +231084,7 @@ var AgentRegistry = class {
230949
231084
  if (configured === void 0) parsed4.execution = parseExecutionPolicy(options4.defaultExecution);
230950
231085
  }
230951
231086
  const name5 = parsed4.name.trim().toLowerCase();
230952
- 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) => {
230953
231088
  if (e.code === "ENOENT") return [];
230954
231089
  throw e;
230955
231090
  })).filter((f2) => /^agent_[a-f0-9-]{36}\.json$/.test(f2))) {
@@ -231002,11 +231137,11 @@ var AgentRegistry = class {
231002
231137
  const path7 = `.ancha/agents/${id14}.json`, temporary = `.ancha/agents/${id14}.${randomUUID8()}.tmp`;
231003
231138
  await preflightFiles(this.workspace, [{ relativePath: path7, content: "" }, { relativePath: temporary, content: "" }]);
231004
231139
  try {
231005
- 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 });
231006
231141
  await preflightFiles(this.workspace, [{ relativePath: path7, content: "" }]);
231007
- await rename4(join29(this.workspace, temporary), join29(this.workspace, path7));
231142
+ await rename4(join30(this.workspace, temporary), join30(this.workspace, path7));
231008
231143
  } finally {
231009
- await rm5(join29(this.workspace, temporary), { force: true });
231144
+ await rm5(join30(this.workspace, temporary), { force: true });
231010
231145
  }
231011
231146
  return this.get(id14);
231012
231147
  }
@@ -231042,7 +231177,7 @@ var AgentRegistry = class {
231042
231177
  async withVerification(profile) {
231043
231178
  const dir2 = `.ancha/agent-verifications/${profile.id}`;
231044
231179
  await preflightFiles(this.workspace, [{ relativePath: `${dir2}/probe.json`, content: "" }]);
231045
- const files2 = await readdir4(join29(this.workspace, dir2)).catch((e) => {
231180
+ const files2 = await readdir4(join30(this.workspace, dir2)).catch((e) => {
231046
231181
  if (e.code === "ENOENT") return [];
231047
231182
  throw e;
231048
231183
  });
@@ -231059,7 +231194,7 @@ var AgentRegistry = class {
231059
231194
  }
231060
231195
  async ids() {
231061
231196
  await preflightFiles(this.workspace, [{ relativePath: ".ancha/agents/probe.json", content: "" }]);
231062
- const files2 = await readdir4(join29(this.workspace, ".ancha/agents")).catch((e) => {
231197
+ const files2 = await readdir4(join30(this.workspace, ".ancha/agents")).catch((e) => {
231063
231198
  if (e.code === "ENOENT") return [];
231064
231199
  throw e;
231065
231200
  });
@@ -231109,7 +231244,7 @@ var AgentRegistry = class {
231109
231244
  agentId(id14);
231110
231245
  const path7 = `.ancha/agents/${id14}.json`;
231111
231246
  await preflightFiles(this.workspace, [{ relativePath: path7, content: "" }]);
231112
- await rm5(join29(this.workspace, path7), { force: true });
231247
+ await rm5(join30(this.workspace, path7), { force: true });
231113
231248
  return { removed: true };
231114
231249
  }
231115
231250
  };
@@ -231170,7 +231305,7 @@ init_src();
231170
231305
  import { createHash as createHash61, randomUUID as randomUUID10 } from "node:crypto";
231171
231306
  import { execFileSync as execFileSync2 } from "node:child_process";
231172
231307
  import { chmod as chmod5, mkdir as mkdir15, readdir as readdir5, rename as rename5, rm as rm6, writeFile as writeFile13 } from "node:fs/promises";
231173
- import { dirname as dirname12, join as join30 } from "node:path";
231308
+ import { dirname as dirname12, join as join31 } from "node:path";
231174
231309
  import Database4 from "better-sqlite3";
231175
231310
  init_assets();
231176
231311
  var BASE4 = ".ancha/playgrounds";
@@ -231206,9 +231341,9 @@ var PlaygroundStore = class {
231206
231341
  }
231207
231342
  async initialize() {
231208
231343
  await preflightFiles(this.workspace, ["ownership.sqlite", "ownership.sqlite-journal", "ownership.sqlite-wal", "ownership.sqlite-shm"].map((file3) => ({ relativePath: `${BASE4}/${file3}`, content: "" })));
231209
- await mkdir15(join30(this.workspace, BASE4), { recursive: true, mode: 448 });
231210
- await chmod5(join30(this.workspace, BASE4), 448);
231211
- 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"));
231212
231347
  this.#db.pragma("busy_timeout = 5000");
231213
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)");
231214
231349
  this.#db.exec("CREATE TABLE IF NOT EXISTS submissions (key TEXT PRIMARY KEY, signature TEXT NOT NULL, runId TEXT NOT NULL)");
@@ -231219,21 +231354,21 @@ var PlaygroundStore = class {
231219
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))");
231220
231355
  this.#db.exec("CREATE TABLE IF NOT EXISTS archived_runs (runId TEXT PRIMARY KEY, archivedAt TEXT NOT NULL)");
231221
231356
  this.#db.exec("CREATE TABLE IF NOT EXISTS legacy_worlds (agentId TEXT PRIMARY KEY, worldId TEXT NOT NULL, sourceFingerprint TEXT NOT NULL)");
231222
- await chmod5(join30(this.workspace, BASE4, "ownership.sqlite"), 384);
231357
+ await chmod5(join31(this.workspace, BASE4, "ownership.sqlite"), 384);
231223
231358
  }
231224
231359
  async write(relative26, value5) {
231225
231360
  const content2 = JSON.stringify(value5) + "\n";
231226
231361
  if (Buffer.byteLength(content2) > 25e6) throw new AnchaError("CONFIG_INVALID", "playground artifact exceeds the 25 MB storage limit");
231227
231362
  const target5 = `${BASE4}/${relative26}`, temporary = `${target5}.${randomUUID10()}.tmp`;
231228
231363
  await preflightFiles(this.workspace, [{ relativePath: target5, content: "" }, { relativePath: temporary, content: "" }]);
231229
- await mkdir15(dirname12(join30(this.workspace, target5)), { recursive: true, mode: 448 });
231230
- 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);
231231
231366
  try {
231232
- await writeFile13(join30(this.workspace, temporary), content2, { flag: "wx", mode: 384 });
231367
+ await writeFile13(join31(this.workspace, temporary), content2, { flag: "wx", mode: 384 });
231233
231368
  await preflightFiles(this.workspace, [{ relativePath: target5, content: "" }]);
231234
- await rename5(join30(this.workspace, temporary), join30(this.workspace, target5));
231369
+ await rename5(join31(this.workspace, temporary), join31(this.workspace, target5));
231235
231370
  } finally {
231236
- await rm6(join30(this.workspace, temporary), { force: true });
231371
+ await rm6(join31(this.workspace, temporary), { force: true });
231237
231372
  }
231238
231373
  }
231239
231374
  async read(relative26) {
@@ -231245,7 +231380,7 @@ var PlaygroundStore = class {
231245
231380
  }
231246
231381
  }
231247
231382
  runDirectory(id14) {
231248
- return join30(this.workspace, BASE4, "runs", requireRunId(id14), "private");
231383
+ return join31(this.workspace, BASE4, "runs", requireRunId(id14), "private");
231249
231384
  }
231250
231385
  async configuration(agentId2) {
231251
231386
  const value5 = await this.read(`configurations/${requireAgentId(agentId2)}.json`);
@@ -231282,7 +231417,7 @@ var PlaygroundStore = class {
231282
231417
  const archived = new Set(this.#db.prepare("SELECT runId FROM archived_runs").all().map((row2) => row2.runId));
231283
231418
  if (agentId2) requireAgentId(agentId2);
231284
231419
  await preflightFiles(this.workspace, [{ relativePath: `${BASE4}/runs/probe.json`, content: "" }]);
231285
- const entries4 = await readdir5(join30(this.workspace, BASE4, "runs")).catch((error65) => {
231420
+ const entries4 = await readdir5(join31(this.workspace, BASE4, "runs")).catch((error65) => {
231286
231421
  if (missing6(error65)) return [];
231287
231422
  throw error65;
231288
231423
  });
@@ -231313,7 +231448,7 @@ var PlaygroundStore = class {
231313
231448
  }
231314
231449
  async stagedRuns() {
231315
231450
  await preflightFiles(this.workspace, [{ relativePath: `${BASE4}/runs/probe.json`, content: "" }]);
231316
- const ids2 = await readdir5(join30(this.workspace, BASE4, "runs")).catch((error65) => {
231451
+ const ids2 = await readdir5(join31(this.workspace, BASE4, "runs")).catch((error65) => {
231317
231452
  if (missing6(error65)) return [];
231318
231453
  throw error65;
231319
231454
  });
@@ -231377,7 +231512,7 @@ var PlaygroundStore = class {
231377
231512
  async migrateConfigurations() {
231378
231513
  await this.init();
231379
231514
  await preflightFiles(this.workspace, [{ relativePath: `${BASE4}/configurations/probe.json`, content: "" }]);
231380
- const names5 = await readdir5(join30(this.workspace, BASE4, "configurations")).catch((error65) => {
231515
+ const names5 = await readdir5(join31(this.workspace, BASE4, "configurations")).catch((error65) => {
231381
231516
  if (missing6(error65)) return [];
231382
231517
  throw error65;
231383
231518
  });
@@ -231949,11 +232084,11 @@ var PlaygroundService = class {
231949
232084
  for (const [index, entry3] of entries4.entries()) {
231950
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.");
231951
232086
  if (this.#captureSources) {
231952
- const source = join32(this.store.runDirectory(run6.id), "source-" + index);
232087
+ const source = join33(this.store.runDirectory(run6.id), "source-" + index);
231953
232088
  if (entry3.resolvedAgent.execution?.mode !== "container") throw new AnchaError("CONFIG_INVALID", "Managed tasks require container execution.");
231954
- const temporary = await mkdtemp6(join32(tmpdir5(), "ancha-capture-"));
232089
+ const temporary = await mkdtemp6(join33(tmpdir5(), "ancha-capture-"));
231955
232090
  try {
231956
- const staged = join32(temporary, "source");
232091
+ const staged = join33(temporary, "source");
231957
232092
  const image2 = await pinExecutionImage(entry3.resolvedAgent.execution.image);
231958
232093
  entry3.resolvedAgent.execution = { ...entry3.resolvedAgent.execution, image: image2 };
231959
232094
  entry3.saved = { ...entry3.saved, execution: entry3.resolvedAgent.execution };
@@ -231969,11 +232104,11 @@ var PlaygroundService = class {
231969
232104
  await this.store.saveBatch(run6);
231970
232105
  const accepted = await this.#admission.submit({ runId: run6.id, signature: signature2, ...idempotencyKey && { idempotencyKey } });
231971
232106
  if (!accepted.created) {
231972
- 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 });
231973
232108
  return this.get(accepted.runId);
231974
232109
  }
231975
232110
  } catch (error65) {
231976
- 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 });
231977
232112
  throw error65;
231978
232113
  }
231979
232114
  this.wakeWaiters();
@@ -232075,7 +232210,7 @@ var PlaygroundService = class {
232075
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.");
232076
232211
  for (const [index, entry3] of entries4.entries()) {
232077
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.");
232078
- 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.");
232079
232214
  const compiled2 = compileSandboxConfiguration(entry3.configuration, { ...entry3.people && { people: entry3.people } });
232080
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.");
232081
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.");
@@ -232133,8 +232268,8 @@ var PlaygroundService = class {
232133
232268
  }
232134
232269
  async discardCapturedSources(id14) {
232135
232270
  await Promise.all([
232136
- ...Array.from({ length: 10 }, (_, index) => rm8(join32(this.store.runDirectory(id14), "source-" + index), { recursive: true, force: true })),
232137
- ...["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 }))
232138
232273
  ]);
232139
232274
  }
232140
232275
  async finishQueued(run6, status5) {
@@ -232168,7 +232303,7 @@ var PlaygroundService = class {
232168
232303
  if (event3.error !== void 0) attempt.error = event3.error.slice(0, 4e3);
232169
232304
  const previous = await this.store.evidence(run6.id, attempt.id);
232170
232305
  const trace = event3.trace ?? previous?.trace ?? [];
232171
- attempt.toolCalls = trace.length;
232306
+ attempt.toolCalls = trace.filter((entry3) => !isAgentAnswer(entry3)).length;
232172
232307
  const snapshot = event3.snapshot;
232173
232308
  const state3 = snapshot ? snapshot.state ?? snapshot : previous?.state;
232174
232309
  const harnessIssues = snapshot?.harnessIssues ?? event3.harnessIssues ?? previous?.harnessIssues;
@@ -232365,8 +232500,8 @@ var PlaygroundService = class {
232365
232500
  // packages/cli/src/commands/run.ts
232366
232501
  import { createHash as createHash66 } from "node:crypto";
232367
232502
  import { appendFileSync } from "node:fs";
232368
- import { access as access10, mkdir as mkdir21, readFile as readFile28, writeFile as writeFile20 } from "node:fs/promises";
232369
- 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";
232370
232505
  init_src();
232371
232506
  init_run_state();
232372
232507
 
@@ -232449,8 +232584,8 @@ init_backend();
232449
232584
  // packages/cli/src/run-upload.ts
232450
232585
  init_src();
232451
232586
  init_credentials();
232452
- import { readFile as readFile19 } from "node:fs/promises";
232453
- 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";
232454
232589
 
232455
232590
  // packages/cli/src/git-state.ts
232456
232591
  import { execFile as execFile8 } from "node:child_process";
@@ -232479,7 +232614,7 @@ async function uploadWorkspace(ctx, missing8 = { message: "--upload needs a work
232479
232614
  }
232480
232615
  }
232481
232616
  async function uploadRun(ctx, workspace4, run6) {
232482
- 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(() => "{}"));
232483
232618
  if (summary.source === "pytest") throw new AnchaError("USAGE", "pytest run upload is not supported; records remain local");
232484
232619
  const key4 = await apiKeyFor(workspace4, ctx.io.env);
232485
232620
  if (key4 === void 0 && !isLoopbackUrl(workspace4)) throw authError(workspace4, { keySent: false });
@@ -232561,13 +232696,13 @@ init_src();
232561
232696
  init_report2();
232562
232697
  import { randomUUID as randomUUID14 } from "node:crypto";
232563
232698
  import { mkdir as mkdir18, writeFile as writeFile17 } from "node:fs/promises";
232564
- import { join as join37, resolve as resolve27 } from "node:path";
232699
+ import { join as join38, resolve as resolve27 } from "node:path";
232565
232700
 
232566
232701
  // packages/cli/src/cloud-bundle.ts
232567
232702
  init_src();
232568
- init_baselines();
232569
232703
  import { access as access9 } from "node:fs/promises";
232570
232704
  import { basename as basename10, resolve as resolve26 } from "node:path";
232705
+ init_baselines();
232571
232706
  init_run_store();
232572
232707
  init_config();
232573
232708
  init_report2();
@@ -232599,13 +232734,14 @@ async function cloudBundle(ctx, input4) {
232599
232734
  const configPath = projectPath(cwd, configFile, "the config file");
232600
232735
  const config11 = await ctx.loadConfig();
232601
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;
232602
232738
  const agent = withLocalEnvironment(resolveRunAgent(config11, cwd, { ...input4.options.agentCommand !== null && { agent: input4.options.agentCommand }, parallel: 1 }).agent, config11);
232603
232739
  for (const test3 of tests) validateAgentEnv(test3.scene, agent);
232604
232740
  for (const name5 of input4.options.allowUnwrapped) {
232605
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" });
232606
232742
  }
232607
232743
  const baseline = input4.compare === void 0 ? void 0 : await pinnedBaseline(ctx, input4.compare, tests, input4.options, input4.cloudSummary);
232608
- 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 } });
232609
232745
  return { bundle, tests };
232610
232746
  }
232611
232747
 
@@ -232644,7 +232780,7 @@ async function runOnCloud(ctx, ws, run6, signal) {
232644
232780
  try {
232645
232781
  const dir2 = resolve27(ctx.io.cwd, DEFAULT_RUNS_DIR);
232646
232782
  await mkdir18(dir2, { recursive: true });
232647
- 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() })}
232648
232784
  `);
232649
232785
  } catch {
232650
232786
  }
@@ -232684,8 +232820,8 @@ async function connectOnCloud(ctx, ws, check4, signal) {
232684
232820
  }
232685
232821
 
232686
232822
  // packages/cli/src/commands/internal-cloud.ts
232687
- import { readFile as readFile27, stat as stat9, writeFile as writeFile19 } from "node:fs/promises";
232688
- 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";
232689
232825
  init_src();
232690
232826
  init_config();
232691
232827
  var cloudModules = {
@@ -232768,8 +232904,8 @@ async function missingCommandEntry(command, cwd) {
232768
232904
  if (!module || !/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/.test(module)) return void 0;
232769
232905
  const roots = [cwd, ...await glob3([".venv/lib*/python*/site-packages"], { cwd, absolute: true, dot: true, onlyDirectories: true })];
232770
232906
  paths2 = roots.flatMap((root3) => {
232771
- const entry3 = join43(root3, ...module.split("."));
232772
- return [`${entry3}.py`, join43(entry3, "__main__.py")];
232907
+ const entry3 = join44(root3, ...module.split("."));
232908
+ return [`${entry3}.py`, join44(entry3, "__main__.py")];
232773
232909
  });
232774
232910
  } else {
232775
232911
  const entry3 = words8[0];
@@ -232816,7 +232952,7 @@ function registerInternalCloud(program2, ctx) {
232816
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) => {
232817
232953
  let input4;
232818
232954
  try {
232819
- 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"));
232820
232956
  } catch (error65) {
232821
232957
  throw new AnchaError("USAGE", `cannot read the finalize input ${opts.input}`, { hint: "pass the FinalizeInput JSON the runner wrote", cause: error65 });
232822
232958
  }
@@ -232824,7 +232960,7 @@ function registerInternalCloud(program2, ctx) {
232824
232960
  if (opts.relay !== void 0) {
232825
232961
  let relay;
232826
232962
  try {
232827
- 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"));
232828
232964
  } catch (error65) {
232829
232965
  throw new AnchaError("USAGE", `cannot read the relay file ${opts.relay}`, { hint: "pass the relay JSON the runner wrote", cause: error65 });
232830
232966
  }
@@ -232994,7 +233130,7 @@ function registerRun(program2, ctx) {
232994
233130
  };
232995
233131
  for (const s3 of loaded) {
232996
233132
  const added = await completeProduction(resolve32(cwd, s3.path), s3.scene, input4.judge);
232997
- 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"))}`);
232998
233134
  }
232999
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");
233000
233136
  if (opts.idempotencyKey !== void 0) {
@@ -233076,7 +233212,7 @@ async function runAttempt(ctx, descriptor3, config11, sceneArgs) {
233076
233212
  const access16 = (await cloudModules.relay()).cloudModelAccess(descriptor3.relay);
233077
233213
  const now11 = (/* @__PURE__ */ new Date()).toISOString();
233078
233214
  const state3 = { version: 1, runId: descriptor3.runId, state: "starting", pid: process.pid, startedAt: now11, updatedAt: now11, completedTrials: 0, totalTrials: 1 };
233079
- await mkdir21(join44(descriptor3.outDir, ".status"), { recursive: true });
233215
+ await mkdir21(join45(descriptor3.outDir, ".status"), { recursive: true });
233080
233216
  await saveRunState(descriptor3.outDir, state3);
233081
233217
  await executePreparedRun(ctx, {
233082
233218
  scenes,
@@ -233096,7 +233232,7 @@ async function runAttempt(ctx, descriptor3, config11, sceneArgs) {
233096
233232
  cloudAttempt: true
233097
233233
  }, state3);
233098
233234
  }
233099
- 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`);
233100
233236
  async function claimIdempotencyKey(outDir, key4, definition3) {
233101
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" });
233102
233238
  const path7 = idempotencyFile(outDir, key4);
@@ -233108,7 +233244,7 @@ async function claimIdempotencyKey(outDir, key4, definition3) {
233108
233244
  } catch (error65) {
233109
233245
  if (error65.code !== "EEXIST") throw error65;
233110
233246
  }
233111
- const previous = JSON.parse(await readFile28(path7, "utf8"));
233247
+ const previous = JSON.parse(await readFile29(path7, "utf8"));
233112
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" });
233113
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" });
233114
233250
  return previous.runId;
@@ -233154,7 +233290,7 @@ ${uploadHintLine(summary.runId, uploadHint, { out: opts.out })}` : ""}`);
233154
233290
  async function uploadFinished(ctx, input4, runId2) {
233155
233291
  if (input4.upload === void 0) return void 0;
233156
233292
  try {
233157
- 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 } });
233158
233294
  } catch (error65) {
233159
233295
  const json35 = toErrorJson(error65);
233160
233296
  if (input4.upload.required) {
@@ -233179,7 +233315,7 @@ async function executePreparedRun(ctx, input4, initial, ready3) {
233179
233315
  const backend = await openBackend({ ...input4.serverUrl !== void 0 && { serverUrl: input4.serverUrl }, ...input4.peopleRelay !== void 0 && { peopleRelay: input4.peopleRelay } });
233180
233316
  try {
233181
233317
  const where3 = { ...input4.workspace !== void 0 && { workspace: input4.workspace }, target: input4.agent.execution?.mode === "container" ? "docker" : "local", ...input4.peopleRelay !== void 0 && { modelCredit: "workspace" } };
233182
- const log3 = join44(input4.outDir, initial.runId, "events.ndjson");
233318
+ const log3 = join45(input4.outDir, initial.runId, "events.ndjson");
233183
233319
  const run6 = await executeRun({
233184
233320
  ...input4,
233185
233321
  root: ctx.io.cwd,
@@ -233234,7 +233370,7 @@ async function definition2(ctx, path7) {
233234
233370
  const info = await stat10(absolute2);
233235
233371
  if (!info.isFile()) throw new AnchaError("USAGE", "definition must be a file");
233236
233372
  if (info.size > 2e6) throw new AnchaError("USAGE", "definition file exceeds 2 MB");
233237
- body7 = await readFile29(absolute2, "utf8");
233373
+ body7 = await readFile30(absolute2, "utf8");
233238
233374
  } catch (error65) {
233239
233375
  if (["ENOENT", "EACCES"].includes(error65.code ?? "")) throw new AnchaError("USAGE", "definition file does not exist or cannot be read");
233240
233376
  throw error65;
@@ -233557,7 +233693,7 @@ ${worlds2 === "local" ? loginRunLine(ctx) : "This server override keeps the agen
233557
233693
 
233558
233694
  // packages/cli/src/kit/trace-connection.ts
233559
233695
  var import_yaml9 = __toESM(require_dist(), 1);
233560
- import { readFile as readFile30 } from "node:fs/promises";
233696
+ import { readFile as readFile31 } from "node:fs/promises";
233561
233697
  import { relative as relative13 } from "node:path";
233562
233698
 
233563
233699
  // packages/cli/src/kit/connect.ts
@@ -233841,7 +233977,7 @@ ${guide.snippet}`);
233841
233977
  // packages/cli/src/kit/trace-connection.ts
233842
233978
  init_detect();
233843
233979
  async function traceConnection(cwd, paths2, configured, target5, recordsAdapter, cloud = false) {
233844
- 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")) })));
233845
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) => ({
233846
233982
  name: name5,
233847
233983
  env: connectionGuide(name5, "ts").env,
@@ -233898,7 +234034,7 @@ async function toolAnswers(runDir, summary, filter4) {
233898
234034
  const out = [];
233899
234035
  for (const scene2 of summary.scenes) for (const { trial } of scene2.trialsDetail) {
233900
234036
  if (filter4.scene !== void 0 && filter4.scene !== scene2.sceneId || filter4.trial !== void 0 && filter4.trial !== trial) continue;
233901
- 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(() => "");
233902
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 }));
233903
234039
  if (!calls2.length) continue;
233904
234040
  const counts = {};
@@ -233933,7 +234069,7 @@ function renderToolAnswers(answers) {
233933
234069
  }
233934
234070
  var NAMED2 = /* @__PURE__ */ new Set(["model_key", "refused", "outside_host", "unserved", "idle", "no_answer"]);
233935
234071
  async function trialOutcomes(runDir, summary, filter4) {
233936
- 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: [] }));
233937
234073
  const out = [];
233938
234074
  for (const scene2 of summary.scenes) {
233939
234075
  if (filter4.scene !== void 0 && filter4.scene !== scene2.sceneId) continue;
@@ -233941,16 +234077,16 @@ async function trialOutcomes(runDir, summary, filter4) {
233941
234077
  const answerChecked = checks2.some((check4) => check4 !== null && typeof check4 === "object" && ("answer" in check4 || "judge" in check4));
233942
234078
  for (const detail3 of scene2.trialsDetail) {
233943
234079
  if (detail3.passed || detail3.outcome === "skipped" || detail3.outcome === "xfailed" || filter4.trial !== void 0 && filter4.trial !== detail3.trial) continue;
233944
- const dir2 = join45(runDir, `trial-${scene2.sceneId}-${detail3.trial}`);
233945
- 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) => {
233946
234082
  try {
233947
234083
  return [JSON.parse(line2)];
233948
234084
  } catch {
233949
234085
  return [];
233950
234086
  }
233951
234087
  });
233952
- const result = await readFile31(join45(dir2, "result.json"), "utf8").then((text29) => JSON.parse(text29), () => ({}));
233953
- 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);
233954
234090
  const { reason: reason2, calls: calls2 } = attemptOutcome(
233955
234091
  { exit: detail3.exit, exitCode: detail3.exitCode, realMs: detail3.realMs, trace, log: log3, ...result.logTail && { logTail: result.logTail }, modelReplies: result.modelReplies },
233956
234092
  { check: "test", answerChecked, target: "local" }
@@ -234078,11 +234214,11 @@ function registerExplain(program2, ctx) {
234078
234214
  const filter4 = { ...opts.scene !== void 0 && { scene: opts.scene }, ...trial !== void 0 && { trial } };
234079
234215
  const gradingWarnings = explainGradingWarnings(summary, filter4);
234080
234216
  const playOuts = explainPlayOuts(summary, filter4);
234081
- const failures = await withWorldEvidence(summary, join45(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), explainFailures(summary, filter4));
234082
- const tools2 = await toolAnswers(join45(resolve34(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), summary, filter4);
234083
- 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);
234084
234220
  const out = opts.out === void 0 ? "" : ` --out ${opts.out}`;
234085
- 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);
234086
234222
  const never2 = agentNeverRan(summary), folded = never2 !== void 0 && !opts.all && opts.scene === void 0 && trial === void 0;
234087
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}`];
234088
234224
  ctx.out.result(
@@ -234120,7 +234256,7 @@ next: ${next2.join(", then ")}` : ""}`
234120
234256
  if (isCloudId(ref22)) await cachedCloudRun(ctx, ref22, runsDir);
234121
234257
  const summary = await loadRunSummary(ctx.io.cwd, ref22, opts.out);
234122
234258
  if (opts.html || opts.open) {
234123
- const runDir = join45(runsDir, summary.runId), path7 = join45(runDir, "report.html");
234259
+ const runDir = join46(runsDir, summary.runId), path7 = join46(runDir, "report.html");
234124
234260
  const folder2 = relative14(ctx.io.cwd, runDir) || ".";
234125
234261
  const records4 = await readRunRecords(runDir, summary, { folder: folder2, secrets: await bundleSecrets({ cwd: ctx.io.cwd, env: ctx.io.env }) });
234126
234262
  await writeFile21(path7, renderHtmlReport(reportData(summary, records4)));
@@ -234135,7 +234271,7 @@ next: ${next2.join(", then ")}` : ""}`
234135
234271
  // packages/cli/src/commands/replay.ts
234136
234272
  init_src();
234137
234273
  import { appendFileSync as appendFileSync2 } from "node:fs";
234138
- import { join as join47, resolve as resolve36 } from "node:path";
234274
+ import { join as join48, resolve as resolve36 } from "node:path";
234139
234275
  init_backend();
234140
234276
  init_config();
234141
234277
 
@@ -234144,8 +234280,8 @@ init_src();
234144
234280
  init_report2();
234145
234281
  init_run();
234146
234282
  init_run_inputs();
234147
- import { readdir as readdir7, readFile as readFile32 } from "node:fs/promises";
234148
- 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";
234149
234285
  var RUN_ID2 = /^[A-Za-z0-9_][\w.-]*$/;
234150
234286
  var TRIAL_DIR = /^trial-[a-z0-9][a-z0-9_-]*-[1-9]\d*$/;
234151
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";
@@ -234170,20 +234306,20 @@ async function loadReplayAttempt(cwd, ref22, out) {
234170
234306
  const trialDir = ref22.slice(slash + 1);
234171
234307
  if (runId2 === "latest") {
234172
234308
  try {
234173
- runId2 = (await readFile32(join46(runs, "latest"), "utf8")).trim();
234309
+ runId2 = (await readFile33(join47(runs, "latest"), "utf8")).trim();
234174
234310
  } catch (error65) {
234175
234311
  if (missing7(error65)) throw new AnchaError("USAGE", `no runs found in ${out ?? DEFAULT_RUNS_DIR}`, { hint: "run `ancha run` first", cause: error65 });
234176
234312
  throw error65;
234177
234313
  }
234178
234314
  }
234179
234315
  if (!RUN_ID2.test(runId2)) throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint: HINT });
234180
- const runDir = join46(runs, runId2);
234316
+ const runDir = join47(runs, runId2);
234181
234317
  let inputs2;
234182
234318
  try {
234183
- inputs2 = JSON.parse(await readFile32(join46(runDir, "inputs.json"), "utf8"));
234319
+ inputs2 = JSON.parse(await readFile33(join47(runDir, "inputs.json"), "utf8"));
234184
234320
  } catch (error65) {
234185
234321
  if (!missing7(error65)) throw error65;
234186
- 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);
234187
234323
  const mb = (bytes3) => `${(bytes3 / (1024 * 1024)).toFixed(1)} MB`;
234188
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 });
234189
234325
  throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint: `see ${out ?? DEFAULT_RUNS_DIR}/`, cause: error65 });
@@ -234194,10 +234330,10 @@ async function loadReplayAttempt(cwd, ref22, out) {
234194
234330
  }
234195
234331
  const found = withSeeds(inputs2.cases ?? []).find((item2) => trialDir.startsWith(`trial-${item2.id}-`) && /^[1-9]\d*$/.test(trialDir.slice(`trial-${item2.id}-`.length)));
234196
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)" });
234197
- const dir2 = join46(runDir, trialDir);
234333
+ const dir2 = join47(runDir, trialDir);
234198
234334
  const read7 = async (name5, optional2 = false) => {
234199
234335
  try {
234200
- return await readFile32(join46(dir2, name5), "utf8");
234336
+ return await readFile33(join47(dir2, name5), "utf8");
234201
234337
  } catch (error65) {
234202
234338
  if (missing7(error65) && optional2) return "";
234203
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 });
@@ -234234,7 +234370,7 @@ async function replayAttempt(attempt, opts) {
234234
234370
  ...opts.onEvent !== void 0 && { onEvent: opts.onEvent }
234235
234371
  });
234236
234372
  const trial = run6.results.get(attempt.caseId).trials[0];
234237
- 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 };
234238
234374
  const recorded2 = new Map(attempt.checks.map((check4) => [check4.id, check4.passed]));
234239
234375
  return {
234240
234376
  replayOf: attempt.id,
@@ -234325,7 +234461,7 @@ function registerReplay(program2, ctx) {
234325
234461
  const backend = await openBackend({ ...choice5.url !== void 0 && { serverUrl: choice5.url }, ...relay !== void 0 && { peopleRelay: relay } });
234326
234462
  try {
234327
234463
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
234328
- const log3 = join47(outDir, state3.runId, "events.ndjson");
234464
+ const log3 = join48(outDir, state3.runId, "events.ndjson");
234329
234465
  const replay2 = await replayAttempt(attempt, {
234330
234466
  backend,
234331
234467
  agent,
@@ -234347,7 +234483,7 @@ function registerReplay(program2, ctx) {
234347
234483
  ctx.out.event(shown3);
234348
234484
  }
234349
234485
  });
234350
- 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] }]]) };
234351
234487
  const summary2 = { ...summarize(run6, agentName(ctx.io.cwd), 1, { agentCommand: agent.mode === "endpoint" ? agent.url : agent.command }), ...where3, source: "replay", replayOf: attempt.id };
234352
234488
  await writeSummary(run6, summary2);
234353
234489
  return { replay: replay2, summary: summary2 };
@@ -234381,8 +234517,8 @@ init_src();
234381
234517
  init_report2();
234382
234518
  init_run_store();
234383
234519
  init_run_state();
234384
- import { readFile as readFile33 } from "node:fs/promises";
234385
- 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";
234386
234522
  import { setTimeout as sleep12 } from "node:timers/promises";
234387
234523
  function registerStatus(program2, ctx) {
234388
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) => {
@@ -234453,12 +234589,12 @@ hint: ${state3.upload.error.hint}` : ""}`);
234453
234589
  const outDir = resolve37(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR);
234454
234590
  const id14 = await resolveRunId(ctx.io.cwd, ref22, opts.out);
234455
234591
  await readRunState(outDir, id14);
234456
- const log3 = join48(outDir, id14, "events.ndjson");
234592
+ const log3 = join49(outDir, id14, "events.ndjson");
234457
234593
  await interruptible(ctx, async (signal) => {
234458
234594
  let printed = 0;
234459
234595
  for (; ; ) {
234460
234596
  const state3 = await readRunState(outDir, id14);
234461
- const lines2 = (await readFile33(log3, "utf8").catch(() => "")).split("\n");
234597
+ const lines2 = (await readFile34(log3, "utf8").catch(() => "")).split("\n");
234462
234598
  if (!terminal(state3)) lines2.pop();
234463
234599
  const complete = lines2.filter(Boolean);
234464
234600
  for (const line2 of complete.slice(printed)) ctx.out.event(JSON.parse(line2));
@@ -234482,8 +234618,8 @@ init_src();
234482
234618
  // packages/cli/src/commands/simulate.ts
234483
234619
  init_src();
234484
234620
  init_backend();
234485
- import { readFile as readFile34 } from "node:fs/promises";
234486
- 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";
234487
234623
  init_config();
234488
234624
  init_report2();
234489
234625
  init_run();
@@ -234492,12 +234628,12 @@ init_scenes();
234492
234628
  // packages/cli/src/runner/companion.ts
234493
234629
  init_src();
234494
234630
  import { stat as stat11 } from "node:fs/promises";
234495
- import { join as join49 } from "node:path";
234631
+ import { join as join50 } from "node:path";
234496
234632
  import { createRequire as createRequire3 } from "node:module";
234497
234633
  var shellWord2 = (value5) => `'${value5.replaceAll("'", "'\\''")}'`;
234498
234634
  async function companionCommand(directory, mode) {
234499
234635
  for (const extension2 of ["mjs", "ts"]) {
234500
- const companion = join49(directory, `${mode}.${extension2}`);
234636
+ const companion = join50(directory, `${mode}.${extension2}`);
234501
234637
  try {
234502
234638
  if (!(await stat11(companion)).isFile()) continue;
234503
234639
  } catch (error65) {
@@ -234506,7 +234642,7 @@ async function companionCommand(directory, mode) {
234506
234642
  }
234507
234643
  return [process.execPath, ...extension2 === "ts" ? ["--import", createRequire3(import.meta.url).resolve("tsx")] : [], companion].map(shellWord2).join(" ");
234508
234644
  }
234509
- 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` });
234510
234646
  }
234511
234647
 
234512
234648
  // packages/cli/src/commands/simulate.ts
@@ -234603,7 +234739,7 @@ function registerSimulate(sceneCommand, ctx) {
234603
234739
  timeline: trial.trace,
234604
234740
  checks: trial.checks,
234605
234741
  harnessIssues: trial.harnessIssues,
234606
- state: JSON.parse(await readFile34(join50(trial.dir, "state.json"), "utf8")),
234742
+ state: JSON.parse(await readFile35(join51(trial.dir, "state.json"), "utf8")),
234607
234743
  runId: run6.runId,
234608
234744
  dir: trial.dir
234609
234745
  };
@@ -234622,8 +234758,8 @@ init_scenes();
234622
234758
 
234623
234759
  // packages/cli/src/kit/init.ts
234624
234760
  import { constants as constants10 } from "node:fs";
234625
- import { lstat as lstat9, mkdir as mkdir24, open as open9, readFile as readFile40, rm as rm12, writeFile as writeFile25 } from "node:fs/promises";
234626
- 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";
234627
234763
  import { Writable } from "node:stream";
234628
234764
  var import_yaml17 = __toESM(require_dist(), 1);
234629
234765
  init_src();
@@ -235705,9 +235841,9 @@ function readEvalItems(name5, raw3) {
235705
235841
  }
235706
235842
 
235707
235843
  // packages/cli/src/kit/doctor.ts
235708
- 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";
235709
235845
  import { tmpdir as tmpdir8 } from "node:os";
235710
- 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";
235711
235847
  var import_yaml13 = __toESM(require_dist(), 1);
235712
235848
  init_src();
235713
235849
  init_backend();
@@ -235720,9 +235856,9 @@ init_scenes();
235720
235856
  init_detect();
235721
235857
  init_run();
235722
235858
  import { randomUUID as randomUUID15 } from "node:crypto";
235723
- 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";
235724
235860
  import { tmpdir as tmpdir7 } from "node:os";
235725
- import { join as join51, relative as relative15 } from "node:path";
235861
+ import { join as join52, relative as relative15 } from "node:path";
235726
235862
  var messages2 = {
235727
235863
  RECORDS_ADAPTER_UNBOUND: "Bind the store in ancha_records.py and call open_store() before creating tools.",
235728
235864
  RECORDS_ADAPTER_LEAK: "Attempt 2 observed attempt 1's diagnostic write.",
@@ -235768,13 +235904,13 @@ async function doctorRecords(opts) {
235768
235904
  const agent = opts.agent;
235769
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;
235770
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.` };
235771
- const directory = await mkdtemp8(join51(tmpdir7(), "ancha-doctor-records-"));
235907
+ const directory = await mkdtemp8(join52(tmpdir7(), "ancha-doctor-records-"));
235772
235908
  const timeout = new AbortController(), timer = setTimeout(() => timeout.abort(), opts.budget);
235773
235909
  const evidence2 = { schemaVersion: 1, groups: [] };
235774
235910
  let result;
235775
235911
  try {
235776
235912
  const language = (await detectProject(agent.cwd)).language;
235777
- 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";
235778
235914
  const groups = /* @__PURE__ */ new Map();
235779
235915
  for (const item2 of applicable) {
235780
235916
  const records4 = await recordsFor(item2.path, opts.cwd);
@@ -235782,8 +235918,8 @@ async function doctorRecords(opts) {
235782
235918
  if (!groups.has(key4)) groups.set(key4, { ...item2, ...records4 !== void 0 && { records: records4 } });
235783
235919
  }
235784
235920
  for (const item2 of groups.values()) {
235785
- const inputRecords = item2.records ? (await readFile35(item2.records, "utf8")).split(/\r?\n/).filter((line2) => line2.trim()).length : 0;
235786
- 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"), "");
235787
235923
  const scene2 = {
235788
235924
  id: item2.scene.id,
235789
235925
  title: item2.scene.title,
@@ -235806,7 +235942,7 @@ async function doctorRecords(opts) {
235806
235942
  recordsDiagnostic: { schemaVersion: 1, token: randomUUID15() },
235807
235943
  outDir: directory,
235808
235944
  root: opts.cwd,
235809
- scenePaths: { [scene2.id]: item2.records ? item2.path : join51(directory, "scene.yaml") },
235945
+ scenePaths: { [scene2.id]: item2.records ? item2.path : join52(directory, "scene.yaml") },
235810
235946
  inheritedEnv: opts.env,
235811
235947
  seed: "doctor-records",
235812
235948
  signal: opts.signal ? AbortSignal.any([timeout.signal, opts.signal]) : timeout.signal
@@ -235943,6 +236079,19 @@ async function uploadAgent(ctx, opts, command = "ancha agent upload") {
235943
236079
  });
235944
236080
  }
235945
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
+ }
235946
236095
  const onboarding = state3 === "failed" ? void 0 : await getOnboarding(ws).then((value5) => nextFromHere(ctx, value5)).then((next3) => human(next3.at(-1)), () => void 0);
235947
236096
  const next2 = state3 === "failed" ? ["ancha agent upload"] : [onboarding === void 0 || /doctor --on cloud|agent upload/.test(onboarding) ? "ancha run" : onboarding];
235948
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 };
@@ -235953,7 +236102,7 @@ async function testsReadAnswer(cwd, scenes) {
235953
236102
  for (const path7 of paths2.slice(0, 1e3)) {
235954
236103
  let doc;
235955
236104
  try {
235956
- doc = (0, import_yaml13.parse)(await readFile36(path7, "utf8"));
236105
+ doc = (0, import_yaml13.parse)(await readFile37(path7, "utf8"));
235957
236106
  } catch {
235958
236107
  continue;
235959
236108
  }
@@ -236037,7 +236186,7 @@ async function doctor(ctx, opts) {
236037
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" });
236038
236187
  } else {
236039
236188
  phase = "agent";
236040
- directory = await mkdtemp9(join52(tmpdir8(), "ancha-doctor-"));
236189
+ directory = await mkdtemp9(join53(tmpdir8(), "ancha-doctor-"));
236041
236190
  const first = loaded[0];
236042
236191
  const scene2 = { ...first.scene, timeout: `${Math.max(1, Math.floor(Math.min(parseDuration(first.scene.timeout), budget2 * first.scene.time_scale)))}ms` };
236043
236192
  const boundedAgent = agent.mode === "endpoint" ? { ...agent, startupTimeoutMs: Math.min(agent.startupTimeoutMs, budget2), idleMs: Math.min(agent.idleMs, budget2) } : agent;
@@ -236143,8 +236292,8 @@ var import_yaml14 = __toESM(require_dist(), 1);
236143
236292
  init_src();
236144
236293
  import { createHash as createHash68 } from "node:crypto";
236145
236294
  import { existsSync as existsSync2 } from "node:fs";
236146
- import { mkdir as mkdir22, readFile as readFile37, writeFile as writeFile23 } from "node:fs/promises";
236147
- 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";
236148
236297
  async function model(ctx) {
236149
236298
  const env2 = ctx.io.env;
236150
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" };
@@ -236174,7 +236323,7 @@ async function worldGenDataset(ctx, options4, description2) {
236174
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" });
236175
236324
  const id14 = options4.id ?? `netsuite-pe-${size2}`;
236176
236325
  if (!/^[a-z0-9-]+$/.test(id14)) throw new AnchaError("USAGE", "--id must match [a-z0-9-]+", { hint: "e.g. --id portfolio-books" });
236177
- 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`);
236178
236327
  const taken2 = [worldPath, evalsPath].find((path7) => existsSync2(path7));
236179
236328
  if (taken2 && !options4.force) throw exists4(taken2, ctx);
236180
236329
  const { world: world5, evals, counts } = generateNetsuitePe({ size: size2, id: id14, startTime: NETSUITE_PE_START_TIME });
@@ -236211,14 +236360,14 @@ async function worldGen(ctx, description2, options4) {
236211
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" });
236212
236361
  const outDir = resolve41(ctx.io.cwd, options4.out ?? "ancha/worlds");
236213
236362
  const request2 = { description: description2, id: options4.id ?? null, tools: tools2 ?? null, size: size2, variants, from: options4.from ?? null };
236214
- 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`);
236215
236364
  if (keyFile && existsSync2(keyFile)) {
236216
- const saved = JSON.parse(await readFile37(keyFile, "utf8"));
236365
+ const saved = JSON.parse(await readFile38(keyFile, "utf8"));
236217
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" });
236218
236367
  if (saved.result.files.every((file3) => existsSync2(resolve41(ctx.io.cwd, file3)))) return report4(ctx, { ...saved.result, reused: true });
236219
236368
  }
236220
- const from = options4.from === void 0 ? void 0 : parseWorldFile((0, import_yaml14.parse)(await readFile37(resolve41(ctx.io.cwd, options4.from), "utf8")));
236221
- 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);
236222
236371
  const { client: client2, credit } = await model(ctx);
236223
236372
  ctx.out.info(`generating a world from the description (size ${size2}${variants ? `, ${variants} variant${variants === 1 ? "" : "s"}` : ""})`);
236224
236373
  const generated = await gen_exports.generateWorld({
@@ -236231,20 +236380,20 @@ async function worldGen(ctx, description2, options4) {
236231
236380
  ...from && { from },
236232
236381
  onProgress: (line2) => ctx.out.info(` ${line2}`)
236233
236382
  });
236234
- const paths2 = Object.keys(generated.files).map((name5) => join53(outDir, name5));
236383
+ const paths2 = Object.keys(generated.files).map((name5) => join54(outDir, name5));
236235
236384
  const taken2 = paths2.find((path7) => existsSync2(path7));
236236
236385
  if (taken2 && !options4.force) throw exists4(taken2, ctx);
236237
236386
  await mkdir22(outDir, { recursive: true });
236238
- 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);
236239
236388
  const rel = (path7) => relative17(ctx.io.cwd, path7) || ".";
236240
- const worldPath = rel(join53(outDir, `${generated.world.id}.yaml`));
236389
+ const worldPath = rel(join54(outDir, `${generated.world.id}.yaml`));
236241
236390
  const result = {
236242
236391
  workspace: `local:${ctx.io.cwd}`,
236243
236392
  id: generated.world.id,
236244
236393
  files: paths2.map(rel),
236245
236394
  world: worldPath,
236246
- record: rel(join53(outDir, `${generated.world.id}.gen.json`)),
236247
- 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`))),
236248
236397
  tools: generated.world.tools,
236249
236398
  people: (generated.world.people ?? []).map((person5) => person5.ref),
236250
236399
  calls: generated.record.calls.length,
@@ -236278,8 +236427,8 @@ var import_yaml16 = __toESM(require_dist(), 1);
236278
236427
  init_src();
236279
236428
  import { createHash as createHash70 } from "node:crypto";
236280
236429
  import { existsSync as existsSync3 } from "node:fs";
236281
- import { mkdir as mkdir23, readFile as readFile38, readdir as readdir8, writeFile as writeFile24 } from "node:fs/promises";
236282
- 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";
236283
236432
 
236284
236433
  // backend/src/kit/test-draft.ts
236285
236434
  init_src();
@@ -236682,10 +236831,10 @@ async function chooseWorld(ctx, id14, command = 'ancha test new "<sentence>"') {
236682
236831
  hint: ids2.length === 0 ? 'ancha world gen "<company and scenario>", or ancha init --intent "<\u2026>"' : `${command} --world ${ids2[0]}`
236683
236832
  });
236684
236833
  }
236685
- const path7 = join54(dir2, `${chosen}.yaml`);
236834
+ const path7 = join55(dir2, `${chosen}.yaml`);
236686
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>"' });
236687
236836
  try {
236688
- return parseWorldFile((0, import_yaml16.parse)(await readFile38(path7, "utf8")));
236837
+ return parseWorldFile((0, import_yaml16.parse)(await readFile39(path7, "utf8")));
236689
236838
  } catch (error65) {
236690
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" });
236691
236840
  }
@@ -236718,19 +236867,19 @@ async function testNew(ctx, intent, options4) {
236718
236867
  const world5 = await chooseWorld(ctx, options4.world);
236719
236868
  const outDir = resolve42(ctx.io.cwd, options4.out ?? "ancha/tests");
236720
236869
  const request2 = { intent, world: world5.id, id: options4.id ?? null, out: relative18(ctx.io.cwd, outDir) };
236721
- 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`);
236722
236871
  if (keyFile && existsSync3(keyFile)) {
236723
- const saved = JSON.parse(await readFile38(keyFile, "utf8"));
236872
+ const saved = JSON.parse(await readFile39(keyFile, "utf8"));
236724
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" });
236725
236874
  if ([saved.result.file, saved.result.record].every((file4) => existsSync3(resolve42(ctx.io.cwd, file4)))) return report5(ctx, { ...saved.result, reused: true });
236726
236875
  }
236727
- 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`));
236728
236877
  const { client: client2, credit } = await draftingModel(ctx);
236729
236878
  ctx.out.info(`drafting a test for world ${world5.id}`);
236730
236879
  const draft2 = await draftTest({ intent, world: world5, model: client2, ...options4.id && { id: options4.id }, onProgress: (line2) => ctx.out.info(` ${line2}`) });
236731
- 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`);
236732
236881
  if (existsSync3(path7) && !options4.force) throw exists5(ctx, path7);
236733
- const before = existsSync3(path7) ? await readFile38(path7, "utf8") : "";
236882
+ const before = existsSync3(path7) ? await readFile39(path7, "utf8") : "";
236734
236883
  const at4 = (/* @__PURE__ */ new Date()).toISOString();
236735
236884
  const yaml = testYaml2({ ...draft2.test, generated: { by: "ancha test new", at: at4, from: intent, record: `${draft2.test.id}.gen.json` } }, intent);
236736
236885
  const cost = Math.round(draft2.calls.reduce((sum6, call4) => sum6 + call4.costUsd, 0) * 1e6) / 1e6;
@@ -236755,7 +236904,7 @@ async function testNew(ctx, intent, options4) {
236755
236904
  ...credit === "workspace" && { modelCredit: "workspace" }
236756
236905
  };
236757
236906
  if (keyFile) {
236758
- await mkdir23(join54(ctx.io.cwd, ".ancha", "test-new"), { recursive: true });
236907
+ await mkdir23(join55(ctx.io.cwd, ".ancha", "test-new"), { recursive: true });
236759
236908
  await writeFile24(keyFile, `${JSON.stringify({ request: request2, result })}
236760
236909
  `);
236761
236910
  }
@@ -236783,11 +236932,11 @@ function registerTestNew(tests, ctx) {
236783
236932
  // packages/cli/src/kit/docs.ts
236784
236933
  init_src();
236785
236934
  init_assets();
236786
- import { readFile as readFile39 } from "node:fs/promises";
236935
+ import { readFile as readFile40 } from "node:fs/promises";
236787
236936
  var DOC_TOPICS = ["setup", "apps", "run", "traces", "explain", "compare", "scenes", "integrations", "cloud", "playgrounds", "cli-quickstart", "tools", "datasets"];
236788
236937
  async function loadDoc(topic = "setup") {
236789
236938
  if (!DOC_TOPICS.includes(topic)) throw new AnchaError("USAGE", `unknown docs topic: ${topic}`, { hint: `available topics: ${DOC_TOPICS.join(", ")}` });
236790
- 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") };
236791
236940
  }
236792
236941
  function registerDocs(program2, ctx) {
236793
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) => {
@@ -236808,13 +236957,13 @@ function step2(ctx) {
236808
236957
  }
236809
236958
  var BEGIN = "<!-- ancha:begin -->";
236810
236959
  var END = "<!-- ancha:end -->";
236811
- var managedSection = () => readFile40(new URL("agents-section.md", assetRoot()), "utf8");
236960
+ var managedSection = () => readFile41(new URL("agents-section.md", assetRoot()), "utf8");
236812
236961
  async function installAgents(cwd) {
236813
- const target5 = join55(cwd, "AGENTS.md");
236962
+ const target5 = join56(cwd, "AGENTS.md");
236814
236963
  const managed = await managedSection();
236815
236964
  let original;
236816
236965
  try {
236817
- original = await readFile40(target5, "utf8");
236966
+ original = await readFile41(target5, "utf8");
236818
236967
  } catch (error65) {
236819
236968
  if (error65.code !== "ENOENT") throw error65;
236820
236969
  const result = await applyScaffold(cwd, [{ relativePath: "AGENTS.md", content: managed }]);
@@ -236836,10 +236985,10 @@ function ignoresAncha(gitignore) {
236836
236985
  return gitignore.split(/\r?\n/).some((line2) => /^(?:\*\*\/|\/)?\.ancha(?:\/|\/\*{1,2})?$/.test(line2.trim()));
236837
236986
  }
236838
236987
  async function ignoreAnchaDirectory(cwd) {
236839
- const target5 = join55(cwd, ".gitignore");
236988
+ const target5 = join56(cwd, ".gitignore");
236840
236989
  let original;
236841
236990
  try {
236842
- original = await readFile40(target5, "utf8");
236991
+ original = await readFile41(target5, "utf8");
236843
236992
  } catch (error65) {
236844
236993
  if (error65.code !== "ENOENT") throw error65;
236845
236994
  const result = await applyScaffold(cwd, [{ relativePath: ".gitignore", content: ".ancha/\n" }]);
@@ -236920,7 +237069,7 @@ ${twins.map((twin) => tasks[twin] ?? `${toolName(twin)}: read its data through t
236920
237069
  }
236921
237070
  var STARTER_FILES = ["scene.yaml", "oracle.mjs", "null.mjs"];
236922
237071
  async function ownStarter(cwd) {
236923
- 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);
236924
237073
  const scene2 = await read7("scene.yaml");
236925
237074
  if (scene2 === void 0) return void 0;
236926
237075
  let twins;
@@ -236961,7 +237110,7 @@ function netsuiteData(size2) {
236961
237110
  }
236962
237111
  async function rewrite(cwd, relativePath, content2) {
236963
237112
  await preflightFiles(cwd, [{ relativePath, content: "" }]);
236964
- 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);
236965
237114
  try {
236966
237115
  await handle30.writeFile(content2);
236967
237116
  } finally {
@@ -236969,7 +237118,7 @@ async function rewrite(cwd, relativePath, content2) {
236969
237118
  }
236970
237119
  }
236971
237120
  async function listTests(cwd, tests) {
236972
- const text29 = await readFile40(join55(cwd, "ancha.yaml"), "utf8");
237121
+ const text29 = await readFile41(join56(cwd, "ancha.yaml"), "utf8");
236973
237122
  let scenes;
236974
237123
  try {
236975
237124
  scenes = parseConfigText(text29).scenes;
@@ -236996,7 +237145,7 @@ async function listTests(cwd, tests) {
236996
237145
  return true;
236997
237146
  }
236998
237147
  async function addExampleSeeds(file3, twins) {
236999
- const doc = (0, import_yaml17.parseDocument)(await readFile40(file3, "utf8"));
237148
+ const doc = (0, import_yaml17.parseDocument)(await readFile41(file3, "utf8"));
237000
237149
  const added = [], skipped = [];
237001
237150
  for (const twin of twins) {
237002
237151
  if (doc.hasIn(["seed", twin])) continue;
@@ -237035,7 +237184,7 @@ function answerLine(task2) {
237035
237184
  if (configured === "done") return "answer: ancha.yaml sets agent.answer: done; only what your agent posts to ANCHA_DONE_URL is its answer";
237036
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)})`;
237037
237186
  if (from === "reply" && configured !== "stdout") return "answer: your agent's HTTP reply is its answer";
237038
- 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';
237039
237188
  }
237040
237189
  function netsuiteLine(task2, written) {
237041
237190
  if (task2.netsuite.length === 0) return void 0;
@@ -237068,10 +237217,10 @@ function parseTools(value5) {
237068
237217
  return SUPPORTED_TWINS.filter((twin) => names5.some((name5) => key4(twin) === key4(name5) || key4(toolName(twin)) === key4(name5)));
237069
237218
  }
237070
237219
  async function wireExistingConfig(cwd) {
237071
- const target5 = join55(cwd, "ancha.yaml");
237220
+ const target5 = join56(cwd, "ancha.yaml");
237072
237221
  let text29;
237073
237222
  try {
237074
- text29 = await readFile40(target5, "utf8");
237223
+ text29 = await readFile41(target5, "utf8");
237075
237224
  } catch {
237076
237225
  return void 0;
237077
237226
  }
@@ -237112,7 +237261,7 @@ function registerKit(program2, ctx) {
237112
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" });
237113
237262
  }
237114
237263
  const detection = await detectProject(ctx.io.cwd, opts.agent);
237115
- 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);
237116
237265
  const configured = configText !== void 0;
237117
237266
  let task2 = configured || detection.agent === null ? void 0 : await taskSetup(ctx.io.cwd, detection.agent, { command: detection.agent });
237118
237267
  const existingConfig = (() => {
@@ -237135,10 +237284,10 @@ function registerKit(program2, ctx) {
237135
237284
  const noStarter = defaultTemplate && (existing2.length > 0 || cloud);
237136
237285
  const starter = opts.template === "starter" && (!noStarter || own2 !== void 0);
237137
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");
237138
- 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);
237139
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;
237140
237289
  const pe = dataSize === void 0 ? void 0 : netsuiteData(dataSize);
237141
- 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, () => [])));
237142
237291
  const mapsNetsuite = task2 !== void 0 && task2.netsuite.length > 0 && opts.template === "starter" && existingTwins.every((list18) => list18.includes("netsuite")) && (!starter || twins.includes("netsuite"));
237143
237292
  const env2 = { ...task2?.wiring?.env, ...mapsNetsuite && Object.fromEntries(task2.netsuite.map((mapping) => [mapping.name, mapping.value])) };
237144
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" } };
@@ -237150,12 +237299,12 @@ parallel: 3
237150
237299
  min_pass_rate: 1
237151
237300
  ` },
237152
237301
  ...templates.map((file3) => ({ ...file3, relativePath: `scenes/${opts.template}/${file3.relativePath}` })),
237153
- { 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") },
237154
237303
  ...pe?.files ?? []
237155
237304
  ];
237156
237305
  await preflightFiles(ctx.io.cwd, [...files2, { relativePath: "AGENTS.md", content: "" }, { relativePath: ".gitignore", content: "" }]);
237157
237306
  const updated = [];
237158
- 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));
237159
237308
  for (const file3 of rewritten) {
237160
237309
  await rewrite(ctx.io.cwd, file3.relativePath, file3.content);
237161
237310
  updated.push(file3.relativePath);
@@ -237181,7 +237330,7 @@ min_pass_rate: 1
237181
237330
  const tools2 = twins.filter(isGenerated);
237182
237331
  const keyed2 = (suffix) => opts.idempotencyKey === void 0 ? {} : { idempotencyKey: `${opts.idempotencyKey}-${suffix}` };
237183
237332
  const world5 = await worldGen(step2(ctx), opts.intent, { ...used.length > 0 && tools2.length > 0 && { tools: tools2.join(",") }, ...keyed2("world") });
237184
- 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)));
237185
237334
  const test3 = await testNew(step2(ctx), opts.intent, { world: world5.id, ...keyed2("test") });
237186
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" } };
237187
237336
  result.created.push(...world5.files, test3.file, test3.record);
@@ -237234,14 +237383,14 @@ function registerSceneNew(scene2, ctx) {
237234
237383
  const prefix2 = `scenes/${id14}`;
237235
237384
  const planned = files2.map((file3) => ({ ...file3, relativePath: `${prefix2}/${file3.relativePath}` }));
237236
237385
  await preflightFiles(ctx.io.cwd, planned);
237237
- const target5 = join55(ctx.io.cwd, prefix2);
237386
+ const target5 = join56(ctx.io.cwd, prefix2);
237238
237387
  try {
237239
237388
  await lstat9(target5);
237240
237389
  throw new AnchaError("USAGE", `scene destination already exists: ${prefix2}`, { hint: "choose another id; existing scene files are preserved" });
237241
237390
  } catch (error65) {
237242
237391
  if (error65.code !== "ENOENT") throw error65;
237243
237392
  }
237244
- await mkdir24(join55(ctx.io.cwd, "scenes"), { recursive: true });
237393
+ await mkdir24(join56(ctx.io.cwd, "scenes"), { recursive: true });
237245
237394
  try {
237246
237395
  await mkdir24(target5);
237247
237396
  } catch (cause) {
@@ -237448,16 +237597,16 @@ import { realpathSync as realpathSync2 } from "node:fs";
237448
237597
  init_src();
237449
237598
  import { randomUUID as randomUUID19 } from "node:crypto";
237450
237599
  import { mkdir as mkdir27, rm as rm16, writeFile as writeFile28 } from "node:fs/promises";
237451
- import { join as join59 } from "node:path";
237600
+ import { join as join60 } from "node:path";
237452
237601
  init_assets();
237453
237602
 
237454
237603
  // backend/src/execution/prepare-agent.ts
237455
237604
  init_src();
237456
237605
  import { execFile as execFile9 } from "node:child_process";
237457
237606
  import { createHash as createHash72, randomUUID as randomUUID17 } from "node:crypto";
237458
- 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";
237459
237608
  import { tmpdir as tmpdir9 } from "node:os";
237460
- import { join as join57 } from "node:path";
237609
+ import { join as join58 } from "node:path";
237461
237610
  init_detect();
237462
237611
  init_source();
237463
237612
  init_docker();
@@ -237466,16 +237615,16 @@ init_policy();
237466
237615
 
237467
237616
  // backend/src/execution/runtime-cache.ts
237468
237617
  import { createHash as createHash71, randomUUID as randomUUID16 } from "node:crypto";
237469
- 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";
237470
- 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";
237471
237620
  init_assets();
237472
237621
  async function runtimeCacheKey(source, project13, command, context3) {
237473
237622
  const hash7 = createHash71("sha256").update(JSON.stringify(["verified-runtime-v1", await realpath11(project13), command, context3]));
237474
237623
  async function visit3(path7, prefix2 = "") {
237475
237624
  for (const entry3 of (await readdir9(path7, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
237476
237625
  const relative26 = prefix2 + entry3.name;
237477
- if (entry3.isDirectory()) await visit3(join56(path7, entry3.name), relative26 + "/");
237478
- 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");
237479
237628
  }
237480
237629
  }
237481
237630
  await visit3(source);
@@ -237497,17 +237646,17 @@ async function rememberRuntime(workspace4, key4, image2) {
237497
237646
  if (!/^sha256:[a-f0-9]{64}$/.test(image2)) throw new Error("Runtime must be pinned before caching");
237498
237647
  const path7 = cachePath(key4), temporary = `${path7}.${randomUUID16()}.tmp`;
237499
237648
  await preflightFiles(workspace4, [{ relativePath: path7, content: "" }, { relativePath: temporary, content: "" }]);
237500
- 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 });
237501
237650
  try {
237502
- await writeFile26(join56(workspace4, temporary), JSON.stringify({ version: 1, image: image2 }), { flag: "wx", mode: 384 });
237503
- 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));
237504
237653
  } finally {
237505
- await rm13(join56(workspace4, temporary), { force: true });
237654
+ await rm13(join57(workspace4, temporary), { force: true });
237506
237655
  }
237507
237656
  }
237508
237657
 
237509
237658
  // backend/src/execution/prepare-agent.ts
237510
- var read6 = (directory, file3) => readFile42(join57(directory, file3), "utf8").catch((error65) => {
237659
+ var read6 = (directory, file3) => readFile43(join58(directory, file3), "utf8").catch((error65) => {
237511
237660
  if (error65.code === "ENOENT") return void 0;
237512
237661
  throw error65;
237513
237662
  });
@@ -237600,13 +237749,13 @@ async function prepareAgent(workspace4, agentId2, options4 = {}) {
237600
237749
  const runtime2 = await (options4.runtime ?? executionRuntimeStatus)();
237601
237750
  if (!runtime2.available || !runtime2.context) throw new AnchaError("AGENT_UNREACHABLE", runtime2.message);
237602
237751
  const runDocker = options4.docker ?? ((args, context3, signal) => docker2(args, context3, signal, options4.progress));
237603
- const temporary = await mkdtemp10(join57(tmpdir9(), "ancha-prepare-agent-"));
237752
+ const temporary = await mkdtemp10(join58(tmpdir9(), "ancha-prepare-agent-"));
237604
237753
  const tag3 = `ancha-agent-${agentId2.slice(6)}:${randomUUID17().slice(0, 8)}`;
237605
237754
  const baseTag = tag3 + "-base";
237606
237755
  const tags4 = /* @__PURE__ */ new Set();
237607
237756
  let success2 = false;
237608
237757
  try {
237609
- const source = join57(temporary, "source");
237758
+ const source = join58(temporary, "source");
237610
237759
  options4.progress?.("Copying agent source");
237611
237760
  await stageProject(saved.cwd, resolved.execution?.mode === "container" ? resolved.execution.files : ["."], source);
237612
237761
  const existing2 = resolved.execution?.mode === "container" ? resolved.execution : void 0;
@@ -237642,14 +237791,14 @@ async function prepareAgent(workspace4, agentId2, options4 = {}) {
237642
237791
  async function hashTree(path7, prefix2 = "") {
237643
237792
  for (const entry3 of (await readdir10(path7, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
237644
237793
  const relative26 = prefix2 + entry3.name;
237645
- if (entry3.isDirectory()) await hashTree(join57(path7, entry3.name), relative26 + "/");
237646
- 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");
237647
237796
  }
237648
237797
  }
237649
237798
  await hashTree(source);
237650
237799
  const fingerprint = digest4.digest("hex"), cacheRelative = `.ancha/agent-images/${fingerprint}.json`;
237651
237800
  await preflightFiles(workspace4, [{ relativePath: cacheRelative, content: "" }]);
237652
- 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);
237653
237802
  let cachedImage;
237654
237803
  if (cached3?.image && /^sha256:[a-f0-9]{64}$/.test(cached3.image)) {
237655
237804
  try {
@@ -237665,7 +237814,7 @@ async function prepareAgent(workspace4, agentId2, options4 = {}) {
237665
237814
  const agent = await registry2.update(agentId2, { execution: parseExecutionPolicy({ memoryMb: 1024, ...previous2 ?? {}, mode: "container", preparation: "project", image: cachedImage.Id }) });
237666
237815
  return { prepared: true, agent, runtime: plan4.kind, image: cachedImage.Id, reused: true, runtimeKey };
237667
237816
  }
237668
- const dockerfile = join57(temporary, "Dockerfile");
237817
+ const dockerfile = join58(temporary, "Dockerfile");
237669
237818
  await writeFile27(dockerfile, plan4.dockerfile, { mode: 384 });
237670
237819
  options4.progress?.("Installing dependencies in an isolated runtime");
237671
237820
  tags4.add(plan4.custom ? baseTag : tag3);
@@ -237688,14 +237837,14 @@ RUN if [ -d ${quote3(nodeModules)} ] && [ ${quote3(nodeModules)} != '/opt/ancha/
237688
237837
  const previous = resolved.execution?.mode === "container" ? resolved.execution : void 0;
237689
237838
  const policy = parseExecutionPolicy({ memoryMb: 1024, ...previous ?? {}, mode: "container", preparation: "project", image: image2.Id });
237690
237839
  if (JSON.stringify(await registry2.saved(agentId2)) !== JSON.stringify(saved)) invalid33("Agent settings changed while connecting. Connect again with the new settings.");
237691
- await mkdir26(join57(workspace4, ".ancha/agent-images"), { recursive: true });
237840
+ await mkdir26(join58(workspace4, ".ancha/agent-images"), { recursive: true });
237692
237841
  const cacheTemp = cacheRelative + `.${randomUUID17()}.tmp`;
237693
237842
  await preflightFiles(workspace4, [{ relativePath: cacheRelative, content: "" }, { relativePath: cacheTemp, content: "" }]);
237694
237843
  try {
237695
- await writeFile27(join57(workspace4, cacheTemp), JSON.stringify({ image: image2.Id }), { flag: "wx", mode: 384 });
237696
- 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));
237697
237846
  } finally {
237698
- await rm14(join57(workspace4, cacheTemp), { force: true });
237847
+ await rm14(join58(workspace4, cacheTemp), { force: true });
237699
237848
  }
237700
237849
  checkSignal(options4.signal);
237701
237850
  if (JSON.stringify(await registry2.saved(agentId2)) !== JSON.stringify(saved)) invalid33("Agent settings changed while connecting. Connect again with the new settings.");
@@ -237719,7 +237868,7 @@ import { execFile as execFile10, spawn as spawn6 } from "node:child_process";
237719
237868
  import { randomUUID as randomUUID18 } from "node:crypto";
237720
237869
  import { mkdtemp as mkdtemp11, rm as rm15 } from "node:fs/promises";
237721
237870
  import { tmpdir as tmpdir10 } from "node:os";
237722
- import { join as join58 } from "node:path";
237871
+ import { join as join59 } from "node:path";
237723
237872
  import { promisify as promisify9 } from "node:util";
237724
237873
  var quote4 = (value5) => `'${value5.replaceAll("'", "'\\''")}'`;
237725
237874
  async function probeAgentConnection(agent, signal, progress2, inheritedEnv = process.env) {
@@ -237729,7 +237878,7 @@ async function probeAgentConnection(agent, signal, progress2, inheritedEnv = pro
237729
237878
  if (!runtime2.available || !runtime2.context) throw new AnchaError("AGENT_UNREACHABLE", runtime2.message);
237730
237879
  const env2 = Object.fromEntries(["PATH", "HOME", "TMPDIR"].flatMap((name5) => process.env[name5] ? [[name5, process.env[name5]]] : []));
237731
237880
  const id14 = `ancha-connect-${randomUUID18()}`, checker = `${id14}-check`;
237732
- const temporary = await mkdtemp11(join58(tmpdir10(), "ancha-connect-"));
237881
+ const temporary = await mkdtemp11(join59(tmpdir10(), "ancha-connect-"));
237733
237882
  const containers = [];
237734
237883
  const children3 = /* @__PURE__ */ new Set();
237735
237884
  function docker3(args, body7, cleanup = false, timeout = 3e4) {
@@ -237761,7 +237910,7 @@ async function probeAgentConnection(agent, signal, progress2, inheritedEnv = pro
237761
237910
  }
237762
237911
  try {
237763
237912
  progress2("starting");
237764
- const source = join58(temporary, "source");
237913
+ const source = join59(temporary, "source");
237765
237914
  const staged = await stageProject(agent.cwd, policy.files, source);
237766
237915
  const workspaceBytes = workspaceSizeBytes(staged.bytes, policy.memoryMb);
237767
237916
  signal.throwIfAborted();
@@ -237911,7 +238060,7 @@ var AgentConnectionService = class {
237911
238060
  return result;
237912
238061
  }
237913
238062
  async start(agentId2) {
237914
- const key4 = join59(this.workspace, this.path(agentId2));
238063
+ const key4 = join60(this.workspace, this.path(agentId2));
237915
238064
  const pending = starting.get(key4);
237916
238065
  if (pending) return pending;
237917
238066
  const promise3 = this.beginStart(agentId2, key4);
@@ -238025,26 +238174,26 @@ var AgentConnectionService = class {
238025
238174
  const finished = (/* @__PURE__ */ new Date()).toISOString();
238026
238175
  Object.assign(value5, { state: "cancelled", phase: "finished", message: "Connect cancelled while queued.", finishedAt: finished, updatedAt: finished });
238027
238176
  delete value5.blockedBy;
238028
- await rm16(join59(this.workspace, request2), { force: true });
238177
+ await rm16(join60(this.workspace, request2), { force: true });
238029
238178
  await this.store.queueConnection(value5.agentId, value5);
238030
238179
  }
238031
238180
  async cancel(agentId2, operationId) {
238032
238181
  const value5 = await this.read(agentId2);
238033
238182
  if (!value5 || value5.id !== operationId) throw new AnchaError("USAGE", "This connection operation is no longer current.");
238034
- const running2 = active2.get(join59(this.workspace, this.path(agentId2)));
238183
+ const running2 = active2.get(join60(this.workspace, this.path(agentId2)));
238035
238184
  if (running2?.id === operationId) {
238036
238185
  running2.controller.abort();
238037
238186
  await running2.done;
238038
238187
  } else if (value5.state === "connecting" || value5.state === "queued") {
238039
238188
  const request2 = `${this.path(agentId2)}.cancel`;
238040
238189
  await preflightFiles(this.workspace, [{ relativePath: request2, content: "" }]);
238041
- await mkdir27(join59(this.workspace, ".ancha/agent-connections"), { recursive: true, mode: 448 });
238042
- 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 });
238043
238192
  }
238044
238193
  return this.status(agentId2);
238045
238194
  }
238046
238195
  async close() {
238047
- 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));
238048
238197
  const owned2 = [...this.owned].flatMap((key4) => {
238049
238198
  const value5 = active2.get(key4);
238050
238199
  return value5 ? [value5] : [];
@@ -238054,7 +238203,7 @@ var AgentConnectionService = class {
238054
238203
  this.store.close();
238055
238204
  }
238056
238205
  async wait(agentId2) {
238057
- await active2.get(join59(this.workspace, this.path(agentId2)))?.done;
238206
+ await active2.get(join60(this.workspace, this.path(agentId2)))?.done;
238058
238207
  return this.status(agentId2);
238059
238208
  }
238060
238209
  async run(value5, controller, provider) {
@@ -238104,7 +238253,7 @@ var AgentConnectionService = class {
238104
238253
  value5.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
238105
238254
  value5.updatedAt = value5.finishedAt;
238106
238255
  clearInterval(cancellation);
238107
- await rm16(join59(this.workspace, request2), { force: true });
238256
+ await rm16(join60(this.workspace, request2), { force: true });
238108
238257
  await writes2;
238109
238258
  await this.write(value5);
238110
238259
  }
@@ -238118,7 +238267,7 @@ init_backend();
238118
238267
  init_assets();
238119
238268
  import { createServer as createServer6 } from "node:http";
238120
238269
  import { randomBytes as randomBytes8 } from "node:crypto";
238121
- 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";
238122
238271
  import { isAbsolute as isAbsolute9 } from "node:path";
238123
238272
  import { fileURLToPath as fileURLToPath7 } from "node:url";
238124
238273
 
@@ -238132,7 +238281,7 @@ init_baselines();
238132
238281
  init_assets();
238133
238282
  import { readdir as readdir11, stat as stat13, writeFile as writeFile29, rename as rename9, rm as rm17 } from "node:fs/promises";
238134
238283
  import { createHash as createHash74, randomBytes as randomBytes7 } from "node:crypto";
238135
- import { join as join60 } from "node:path";
238284
+ import { join as join61 } from "node:path";
238136
238285
  import { fileURLToPath as fileURLToPath5 } from "node:url";
238137
238286
 
238138
238287
  // backend/src/connection-report.ts
@@ -238244,7 +238393,7 @@ var ConsoleJobs = class {
238244
238393
  this.catalog = catalog2;
238245
238394
  this.agents = new AgentRegistry(workspace4);
238246
238395
  this.inheritedEnv = inheritedEnv;
238247
- this.outDir = join60(workspace4, ".ancha/runs");
238396
+ this.outDir = join61(workspace4, ".ancha/runs");
238248
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);
238249
238398
  }
238250
238399
  async profiles() {
@@ -238257,7 +238406,7 @@ var ConsoleJobs = class {
238257
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 });
238258
238407
  } catch {
238259
238408
  }
238260
- 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 });
238261
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];
238262
238411
  }
238263
238412
  async key() {
@@ -238505,7 +238654,7 @@ var ConsoleJobs = class {
238505
238654
  if (e.code === "ENOENT") return [];
238506
238655
  throw e;
238507
238656
  });
238508
- const status5 = await readdir11(join60(this.outDir, ".status")).catch((e) => {
238657
+ const status5 = await readdir11(join61(this.outDir, ".status")).catch((e) => {
238509
238658
  if (e.code === "ENOENT") return [];
238510
238659
  throw e;
238511
238660
  });
@@ -238543,7 +238692,7 @@ var ConsoleJobs = class {
238543
238692
  const trace = (await safeRead(this.workspace, `${base3}/trace.jsonl`, 12e6)).trim().split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
238544
238693
  const { open: open13 } = await import("node:fs/promises");
238545
238694
  await preflightFiles(this.workspace, [{ relativePath: `${base3}/agent.log`, content: "" }]);
238546
- const handle30 = await open13(join60(this.workspace, `${base3}/agent.log`), "r");
238695
+ const handle30 = await open13(join61(this.workspace, `${base3}/agent.log`), "r");
238547
238696
  let log3 = "";
238548
238697
  try {
238549
238698
  const size2 = (await handle30.stat()).size;
@@ -238625,10 +238774,10 @@ var ConsoleJobs = class {
238625
238774
  const target5 = `.ancha/console-runs/${runId2}.events.json`, temporary = `${target5}.${randomBytes7(8).toString("hex")}.tmp`;
238626
238775
  await preflightFiles(this.workspace, [{ relativePath: target5, content: "" }, { relativePath: temporary, content: "" }]);
238627
238776
  try {
238628
- await writeFile29(join60(this.workspace, temporary), JSON.stringify(publicData(events3, this.secrets)), { flag: "wx", mode: 384 });
238629
- 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));
238630
238779
  } finally {
238631
- await rm17(join60(this.workspace, temporary), { force: true });
238780
+ await rm17(join61(this.workspace, temporary), { force: true });
238632
238781
  }
238633
238782
  }
238634
238783
  async savePublicAttempts(runId2, metadata7, events3, only4) {
@@ -238665,7 +238814,7 @@ var ConsoleJobs = class {
238665
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]]));
238666
238815
  await preflightFiles(this.workspace, [{ relativePath: `${base3}/agent.log`, content: "" }]);
238667
238816
  const { open: open13 } = await import("node:fs/promises");
238668
- const handle30 = await open13(join60(this.workspace, base3, "agent.log"), "r");
238817
+ const handle30 = await open13(join61(this.workspace, base3, "agent.log"), "r");
238669
238818
  let log3;
238670
238819
  try {
238671
238820
  const size2 = (await handle30.stat()).size, buffer = Buffer.alloc(Math.min(size2, 65536));
@@ -238699,7 +238848,7 @@ init_report2();
238699
238848
  init_src();
238700
238849
  init_assets();
238701
238850
  import { open as open10, readdir as readdir12 } from "node:fs/promises";
238702
- import { join as join61 } from "node:path";
238851
+ import { join as join62 } from "node:path";
238703
238852
  var DISPLAY_LIMIT = "file exceeds the console display limit";
238704
238853
  var FsRunFiles = class {
238705
238854
  workspace;
@@ -238710,7 +238859,7 @@ var FsRunFiles = class {
238710
238859
  }
238711
238860
  async list() {
238712
238861
  await preflightFiles(this.workspace, [{ relativePath: ".ancha/runs/probe.json", content: "" }]);
238713
- 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) => {
238714
238863
  if (error65.code === "ENOENT") return [];
238715
238864
  throw error65;
238716
238865
  });
@@ -238729,7 +238878,7 @@ var FsRunFiles = class {
238729
238878
  await preflightFiles(this.workspace, [{ relativePath: relative26, content: "" }]);
238730
238879
  let handle30;
238731
238880
  try {
238732
- handle30 = await open10(join61(this.workspace, relative26), "r");
238881
+ handle30 = await open10(join62(this.workspace, relative26), "r");
238733
238882
  } catch (error65) {
238734
238883
  if (error65.code === "ENOENT") return void 0;
238735
238884
  throw error65;
@@ -238909,7 +239058,15 @@ var CliRuns = class {
238909
239058
  const raw3 = JSON.parse(rawChecks);
238910
239059
  checks2 = Array.isArray(raw3) ? raw3 : Array.isArray(raw3?.checks) ? raw3.checks : [];
238911
239060
  }
238912
- const toolCalls = (await optional2("trace.jsonl", 12e6) ?? "").split("\n").filter((line2) => line2.includes('"source":"agent"')).length;
239061
+ const toolCalls = (await optional2("trace.jsonl", 12e6) ?? "").split("\n").filter((line2) => {
239062
+ if (!line2.trim()) return false;
239063
+ try {
239064
+ const entry3 = JSON.parse(line2);
239065
+ return entry3?.source === "agent" && !isAgentAnswer(entry3);
239066
+ } catch {
239067
+ return false;
239068
+ }
239069
+ }).length;
238913
239070
  let response5;
238914
239071
  try {
238915
239072
  const text29 = await optional2("result.json", 4e6);
@@ -239310,7 +239467,7 @@ init_src();
239310
239467
  init_assets();
239311
239468
  import { randomUUID as randomUUID20 } from "node:crypto";
239312
239469
  import { readdir as readdir13, rm as rm18 } from "node:fs/promises";
239313
- import { join as join62 } from "node:path";
239470
+ import { join as join63 } from "node:path";
239314
239471
  var setupPattern = /^setup_[a-f0-9-]{36}$/;
239315
239472
  var runPattern = /^run_[A-Za-z0-9_-]{1,124}$/;
239316
239473
  function shape4(input4, fields11) {
@@ -239385,7 +239542,7 @@ var SavedTestSetups = class {
239385
239542
  }
239386
239543
  async list() {
239387
239544
  await preflightFiles(this.workspace, [{ relativePath: ".ancha/test-setups/probe.json", content: "" }]);
239388
- 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) => {
239389
239546
  if (e.code === "ENOENT") return [];
239390
239547
  throw e;
239391
239548
  });
@@ -239407,7 +239564,7 @@ var SavedTestSetups = class {
239407
239564
  async remove(id14) {
239408
239565
  const relativePath = this.path(id14);
239409
239566
  await preflightFiles(this.workspace, [{ relativePath, content: "" }]);
239410
- await rm18(join62(this.workspace, relativePath));
239567
+ await rm18(join63(this.workspace, relativePath));
239411
239568
  return { removed: true };
239412
239569
  }
239413
239570
  };
@@ -239462,12 +239619,12 @@ async function startConsole(opts) {
239462
239619
  const files2 = /* @__PURE__ */ new Map();
239463
239620
  if (opts.assets !== false) {
239464
239621
  const assets = opts.assets ?? fileURLToPath7(new URL("ui/", assetRoot()));
239465
- const html2 = await readFile43(`${assets}/index.html`).catch(() => {
239622
+ const html2 = await readFile44(`${assets}/index.html`).catch(() => {
239466
239623
  throw new AnchaError("USAGE", "console assets are missing; reinstall Ancha with `npm install -g @ancha-labs/cli`");
239467
239624
  });
239468
239625
  files2.set("/", { body: html2, mime: "text/html; charset=utf-8" });
239469
- files2.set("/app.js", { body: await readFile43(`${assets}/app.js`), mime: "text/javascript; charset=utf-8" });
239470
- 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" });
239471
239628
  }
239472
239629
  const backend = opts.backend ?? await openBackend();
239473
239630
  const catalog2 = new ScenarioCatalog(workspace4, opts.configPath);
@@ -240027,7 +240184,7 @@ init_backend();
240027
240184
 
240028
240185
  // packages/cli/src/commands/test-import.ts
240029
240186
  import { existsSync as existsSync4 } from "node:fs";
240030
- 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";
240031
240188
  import { basename as basename13, dirname as dirname23, extname as extname2, isAbsolute as isAbsolute10, relative as relative19, resolve as resolve44 } from "node:path";
240032
240189
  init_src();
240033
240190
  var EXAMPLE = `
@@ -240058,7 +240215,7 @@ async function testImport(ctx, file3, options4) {
240058
240215
  }
240059
240216
  let text29, encoding;
240060
240217
  try {
240061
- ({ text: text29, encoding } = decodeEvalText(await readFile44(path7)));
240218
+ ({ text: text29, encoding } = decodeEvalText(await readFile45(path7)));
240062
240219
  } catch (error65) {
240063
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>" });
240064
240221
  }
@@ -240081,7 +240238,7 @@ ${skipped.slice(0, 10).map((s3) => `item ${s3.item}: ${s3.reason}`).join("\n")}`
240081
240238
  const tests = [];
240082
240239
  for (const test3 of imported2.tests) {
240083
240240
  const target5 = resolve44(ctx.io.cwd, test3.path);
240084
- const before = existsSync4(target5) ? await readFile44(target5, "utf8") : void 0;
240241
+ const before = existsSync4(target5) ? await readFile45(target5, "utf8") : void 0;
240085
240242
  const status5 = before === void 0 ? "written" : before === test3.yaml ? "unchanged" : !editedSinceImport(before) ? "updated" : options4.force ? "written" : "kept";
240086
240243
  if (status5 === "written" || status5 === "updated") {
240087
240244
  await mkdir28(dirname23(target5), { recursive: true });
@@ -240375,7 +240532,7 @@ Run again with ancha test run ${saved.id}`);
240375
240532
  // packages/cli/src/commands/sandbox.ts
240376
240533
  var import_yaml18 = __toESM(require_dist(), 1);
240377
240534
  init_src();
240378
- import { readFile as readFile45 } from "node:fs/promises";
240535
+ import { readFile as readFile46 } from "node:fs/promises";
240379
240536
  import { resolve as resolve46 } from "node:path";
240380
240537
  init_backend();
240381
240538
  function tools(value5) {
@@ -240422,7 +240579,7 @@ Use --json to export this configuration.`);
240422
240579
  if ([opts.tools, opts.preset, opts.definition].filter(Boolean).length > 1) throw new AnchaError("USAGE", "choose --tools, --preset or --definition");
240423
240580
  let input4;
240424
240581
  if (opts.definition) {
240425
- 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"));
240426
240583
  if (doc.errors.length) throw new AnchaError("CONFIG_INVALID", doc.errors.map((error65) => error65.message).join("; "));
240427
240584
  input4 = doc.toJS({ maxAliasCount: 100 });
240428
240585
  if (opts.name && input4 && typeof input4 === "object" && !Array.isArray(input4)) input4 = { ...input4, name: opts.name };
@@ -257025,14 +257182,14 @@ init_src();
257025
257182
  init_backend();
257026
257183
  import { fork as fork2 } from "node:child_process";
257027
257184
  import { randomBytes as randomBytes9 } from "node:crypto";
257028
- 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";
257029
257186
  import { createRequire as createRequire5 } from "node:module";
257030
- import { join as join63 } from "node:path";
257187
+ import { join as join64 } from "node:path";
257031
257188
  var WORLD_SERVER_IDLE_MS = 10 * 6e4;
257032
257189
  var SERVER_FILE = "world-server.json";
257033
257190
  var ENVS_FILE = "world-envs.json";
257034
257191
  var LOCK_FILE = "world-server.lock";
257035
- var dir = (cwd) => join63(cwd, ".ancha");
257192
+ var dir = (cwd) => join64(cwd, ".ancha");
257036
257193
  async function writePrivate(path7, value5) {
257037
257194
  const temporary = `${path7}.${process.pid}.tmp`;
257038
257195
  await writeFile31(temporary, `${JSON.stringify(value5, null, 2)}
@@ -257041,7 +257198,7 @@ async function writePrivate(path7, value5) {
257041
257198
  }
257042
257199
  async function readJson2(path7) {
257043
257200
  try {
257044
- return JSON.parse(await readFile46(path7, "utf8"));
257201
+ return JSON.parse(await readFile47(path7, "utf8"));
257045
257202
  } catch {
257046
257203
  return void 0;
257047
257204
  }
@@ -257060,7 +257217,7 @@ async function alive3(server) {
257060
257217
  }
257061
257218
  }
257062
257219
  async function withLock(cwd, work) {
257063
- const path7 = join63(dir(cwd), LOCK_FILE);
257220
+ const path7 = join64(dir(cwd), LOCK_FILE);
257064
257221
  for (let attempt = 0; ; attempt++) {
257065
257222
  try {
257066
257223
  await (await open11(path7, "wx", 384)).close();
@@ -257084,7 +257241,7 @@ async function withLock(cwd, work) {
257084
257241
  }
257085
257242
  async function localWorldServer(cwd) {
257086
257243
  await mkdir29(dir(cwd), { recursive: true });
257087
- const path7 = join63(dir(cwd), SERVER_FILE);
257244
+ const path7 = join64(dir(cwd), SERVER_FILE);
257088
257245
  const current = await readJson2(path7);
257089
257246
  if (current?.version === CLI_VERSION && await alive3(current)) return current;
257090
257247
  return withLock(cwd, async () => {
@@ -257098,7 +257255,7 @@ async function localWorldServer(cwd) {
257098
257255
  });
257099
257256
  }
257100
257257
  async function runningWorldServer(cwd) {
257101
- const server = await readJson2(join63(dir(cwd), SERVER_FILE));
257258
+ const server = await readJson2(join64(dir(cwd), SERVER_FILE));
257102
257259
  return server !== void 0 && await alive3(server) ? server : void 0;
257103
257260
  }
257104
257261
  function startWorldServer(cwd, controlToken) {
@@ -257142,17 +257299,17 @@ function startWorldServer(cwd, controlToken) {
257142
257299
  }
257143
257300
  async function recordWorld(cwd, envId, record28) {
257144
257301
  await mkdir29(dir(cwd), { recursive: true });
257145
- const path7 = join63(dir(cwd), ENVS_FILE);
257302
+ const path7 = join64(dir(cwd), ENVS_FILE);
257146
257303
  const all9 = await readJson2(path7) ?? {};
257147
257304
  for (const [id14, entry3] of Object.entries(all9)) if (Date.now() - Date.parse(entry3.createdAt) > 864e5) delete all9[id14];
257148
257305
  all9[envId] = record28;
257149
257306
  await writePrivate(path7, all9);
257150
257307
  }
257151
257308
  async function worldRecord(cwd, envId) {
257152
- return (await readJson2(join63(dir(cwd), ENVS_FILE)))?.[envId];
257309
+ return (await readJson2(join64(dir(cwd), ENVS_FILE)))?.[envId];
257153
257310
  }
257154
257311
  async function forgetWorld(cwd, envId) {
257155
- const path7 = join63(dir(cwd), ENVS_FILE);
257312
+ const path7 = join64(dir(cwd), ENVS_FILE);
257156
257313
  const all9 = await readJson2(path7);
257157
257314
  if (all9?.[envId] === void 0) return;
257158
257315
  delete all9[envId];
@@ -257226,14 +257383,23 @@ function agentVariables(info, scene2) {
257226
257383
  return { ...toolConnectionEnvironment(info.services), ...mcpConnectionEnvironment(info.mcp), ANCHA_ENV_ID: info.id, ...scene2 !== void 0 && { ANCHA_SCENE_ID: scene2.id, ANCHA_TASK: scene2.task } };
257227
257384
  }
257228
257385
  function registerWorldLifecycle(world5, ctx) {
257229
- world5.command("up").description("start a fresh world for your own harness: prints its tools' URLs and fake credentials").option("--scene <file>", "test file (scene.yaml) to start (default: the one test ancha.yaml names)").option("--test <file>", "test file to start; same as --scene").option("--world <id>", "a saved world from ancha world list").option("--on <where>", "local (this computer) or cloud (your workspace); default: the server --server-url, server.url or ANCHA_SERVER_URL names, else this computer").option("--seed <seed>", 'seed for ids and data (default: "<test id>:1")').option("--ttl <duration>", "remove the world after this long with no call from the agent and no ancha world or ancha check command on it", DEFAULT_TTL).action(async (opts) => {
257386
+ world5.command("up").description("start a fresh world for your own harness: prints its tools' URLs and fake credentials").option("--scene <file>", "test file (scene.yaml) to start (default: the one test ancha.yaml names)").option("--test <file>", "test file to start; same as --scene").option("--world <id>", "a world file (ancha/worlds/<id>.yaml) by id or path, or a saved world from ancha world list").option("--on <where>", "local (this computer) or cloud (your workspace); default: the server --server-url, server.url or ANCHA_SERVER_URL names, else this computer").option("--seed <seed>", 'seed for ids and data (default: "<test id>:1")').option("--ttl <duration>", "remove the world after this long with no call from the agent and no ancha world or ancha check command on it", DEFAULT_TTL).action(async (opts) => {
257230
257387
  if ([opts.scene, opts.test, opts.world].filter((value5) => value5 !== void 0).length > 1) throw new AnchaError("USAGE", "choose one of --scene, --test or --world");
257231
257388
  const ttlMs = ttl(opts.ttl);
257389
+ const fileWorld = opts.world !== void 0 ? await loadWorldFile(ctx.io.cwd, opts.world) : void 0;
257232
257390
  const where3 = await target4(ctx, opts.on);
257233
257391
  let scene2, scenePath, configuration, definition3;
257234
- if (opts.world !== void 0) {
257392
+ if (fileWorld !== void 0) {
257393
+ scene2 = worldToScene(fileWorld.world);
257394
+ definition3 = { scene: scene2 };
257395
+ } else if (opts.world !== void 0) {
257235
257396
  let saved;
257236
257397
  if (where3.local || isLoopbackUrl(where3.serverUrl)) {
257398
+ if (!/^world_[a-f0-9-]{36}$/.test(opts.world)) {
257399
+ throw new AnchaError("USAGE", `no world ${opts.world}: no ancha/worlds/${opts.world}.yaml, and ${opts.world} is not a saved world id (world_\u2026)`, {
257400
+ hint: "ancha world list shows saved worlds; world files are in ancha/worlds/ (ancha world gen --dataset netsuite-pe writes one)"
257401
+ });
257402
+ }
257237
257403
  saved = await withService(ctx, (service) => service.world(opts.world));
257238
257404
  } else {
257239
257405
  const key4 = await apiKeyFor(where3.serverUrl, ctx.io.env);
@@ -257254,7 +257420,7 @@ function registerWorldLifecycle(world5, ctx) {
257254
257420
  ctx.out.notice(where3.line);
257255
257421
  const backend = await openBackend({ serverUrl: where3.serverUrl, ...where3.controlToken !== void 0 && { controlToken: where3.controlToken } });
257256
257422
  try {
257257
- const seed43 = opts.seed ?? (opts.world !== void 0 ? "world-1" : void 0);
257423
+ const seed43 = opts.seed ?? (opts.world !== void 0 && fileWorld === void 0 ? "world-1" : void 0);
257258
257424
  const info = scene2 !== void 0 ? await backend.createEnv(scene2, seed43, { ttlMs }) : await backend.createSandbox(configuration, seed43, { ttlMs });
257259
257425
  await recordWorld(ctx.io.cwd, info.id, { serverUrl: where3.serverUrl, workspace: where3.workspace, local: where3.local, ...scenePath !== void 0 && { scene: scenePath }, definition: definition3, createdAt: (/* @__PURE__ */ new Date()).toISOString() });
257260
257426
  const lease = await backend.renewEnv(info.id);
@@ -257402,7 +257568,7 @@ init_world_image();
257402
257568
  import { execFile as execFile12, spawn as spawn7 } from "node:child_process";
257403
257569
  import { promisify as promisify11 } from "node:util";
257404
257570
  import { access as access14, chmod as chmod7, copyFile as copyFile5, mkdir as mkdir30, writeFile as writeFile32 } from "node:fs/promises";
257405
- import { join as join64 } from "node:path";
257571
+ import { join as join65 } from "node:path";
257406
257572
  var exec7 = promisify11(execFile12);
257407
257573
  var VERSION3 = "0.25.0";
257408
257574
  var exists6 = (path7) => access14(path7).then(() => true, () => false);
@@ -257444,9 +257610,9 @@ async function preparePlaygroundRuntime(workspace4, progress2 = () => {
257444
257610
  "image/package.json",
257445
257611
  "image/Dockerfile"
257446
257612
  ].map((path7) => ({ relativePath: `.ancha/harbor-runtime/${path7}`, content: "" })));
257447
- const runtime2 = join64(workspace4, ".ancha/harbor-runtime");
257613
+ const runtime2 = join65(workspace4, ".ancha/harbor-runtime");
257448
257614
  await mkdir30(runtime2, { recursive: true, mode: 448 });
257449
- const python = join64(runtime2, ".venv/bin/python");
257615
+ const python = join65(runtime2, ".venv/bin/python");
257450
257616
  if (!await exists6(python)) {
257451
257617
  progress2("Preparing the local execution runtime");
257452
257618
  let source;
@@ -257459,7 +257625,7 @@ async function preparePlaygroundRuntime(workspace4, progress2 = () => {
257459
257625
  }
257460
257626
  }
257461
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." });
257462
- await run5(source, ["-m", "venv", join64(runtime2, ".venv")]);
257628
+ await run5(source, ["-m", "venv", join65(runtime2, ".venv")]);
257463
257629
  }
257464
257630
  let installed2 = "";
257465
257631
  try {
@@ -257477,26 +257643,26 @@ async function preparePlaygroundRuntime(workspace4, progress2 = () => {
257477
257643
  } catch {
257478
257644
  }
257479
257645
  if (!compose2) {
257480
- const plugin = join64(runtime2, "docker-config/cli-plugins/docker-compose");
257646
+ const plugin = join65(runtime2, "docker-config/cli-plugins/docker-compose");
257481
257647
  if (!await exists6(plugin)) {
257482
- 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");
257483
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." });
257484
- 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 });
257485
257651
  await copyFile5(qualified, plugin);
257486
257652
  await chmod7(plugin, 448);
257487
257653
  }
257488
257654
  }
257489
257655
  progress2("Preparing the seeded tools");
257490
- const imageDir = join64(runtime2, "image");
257656
+ const imageDir = join65(runtime2, "image");
257491
257657
  await mkdir30(imageDir, { recursive: true, mode: 448 });
257492
257658
  const companion = await packagedCompanion(), worker = await packagedSuiteqlWorker();
257493
257659
  const image2 = worldImageTag(companion, worker);
257494
- await writeFile32(join64(imageDir, "companion.mjs"), companion);
257495
- await writeFile32(join64(imageDir, "suiteql-worker.mjs"), worker);
257496
- await writeFile32(join64(imageDir, "package.json"), WORLD_PACKAGE_JSON);
257497
- 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);
257498
257664
  await run5("docker", ["--context", docker3.context, "build", "--tag", image2, imageDir]);
257499
- 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 });
257500
257666
  return { available: true, message: "Local playgrounds are ready.", worldImage: image2 };
257501
257667
  }
257502
257668
 
@@ -257534,8 +257700,8 @@ init_src();
257534
257700
  // packages/cli/src/commands/world-import.ts
257535
257701
  init_src();
257536
257702
  import { existsSync as existsSync5 } from "node:fs";
257537
- import { mkdir as mkdir31, readdir as readdir14, readFile as readFile48, stat as stat16, writeFile as writeFile33 } from "node:fs/promises";
257538
- 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";
257539
257705
 
257540
257706
  // backend/src/kit/netsuite-import.ts
257541
257707
  init_src();
@@ -258003,7 +258169,7 @@ function realmOf(href2) {
258003
258169
  const m = href2 === void 0 ? null : /^https?:\/\/(\d{4,10})(?:[-_]sb(\d{1,2}))?\.suitetalk\.api\.netsuite\.com/i.exec(href2);
258004
258170
  return m ? `${m[1]}${m[2] ? `_SB${m[2]}` : ""}` : void 0;
258005
258171
  }
258006
- function readFile47(file3, type, notes6) {
258172
+ function readFile48(file3, type, notes6) {
258007
258173
  const text29 = file3.text.replace(/^/, ""), start = text29.trimStart();
258008
258174
  if (!/^[[{]/.test(start)) return readCsv2(file3.path, text29, type, notes6);
258009
258175
  let values2;
@@ -259184,7 +259350,7 @@ function importNetsuite(files2, options4) {
259184
259350
  const notes6 = [], problems = [], read7 = [], type = options4.type === void 0 ? void 0 : canonical6(options4.type);
259185
259351
  let raws = [];
259186
259352
  for (const file3 of files2) {
259187
- 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) }));
259188
259354
  const untyped = rows33.filter((raw3) => raw3.type === "record" || raw3.type === TRANSACTION || raw3.type === ENTITY2);
259189
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`);
259190
259356
  rows33 = rows33.filter((raw3) => !untyped.includes(raw3));
@@ -259339,8 +259505,8 @@ async function exportFiles(cwd, path7) {
259339
259505
  const found = [];
259340
259506
  for (const entry3 of (await readdir14(full2, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
259341
259507
  if (entry3.name.startsWith(".")) continue;
259342
- if (entry3.isDirectory()) found.push(...await exportFiles(cwd, join65(full2, entry3.name)));
259343
- 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));
259344
259510
  }
259345
259511
  return found;
259346
259512
  }
@@ -259351,11 +259517,11 @@ async function worldImportNetsuite(ctx, paths2, options4) {
259351
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)))) {
259352
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" });
259353
259519
  }
259354
- 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) || ".";
259355
259521
  if (existsSync5(worldPath) && !options4.force) throw new AnchaError("USAGE", `${rel(worldPath)} already exists`, { hint: "pass --force to overwrite it, or choose another --id" });
259356
259522
  const names5 = [...new Set((await Promise.all(paths2.map((path7) => exportFiles(ctx.io.cwd, path7)))).flat())];
259357
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)" });
259358
- 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 })));
259359
259525
  const imported2 = importNetsuite(files2, {
259360
259526
  id: options4.id,
259361
259527
  now: (/* @__PURE__ */ new Date()).toISOString(),
@@ -259446,8 +259612,8 @@ init_privacy();
259446
259612
  init_assets();
259447
259613
  init_report2();
259448
259614
  import { createHash as createHash76, randomBytes as randomBytes10 } from "node:crypto";
259449
- 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";
259450
- 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";
259451
259617
  var object18 = external_exports.record(external_exports.string(), external_exports.unknown());
259452
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)));
259453
259619
  var code3 = external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/);
@@ -259557,7 +259723,7 @@ function artifacts(record28, runDir) {
259557
259723
  evidence: []
259558
259724
  }] : [];
259559
259725
  const realMs = Date.parse(attempt.finishedAt) - Date.parse(attempt.startedAt);
259560
- 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) };
259561
259727
  if (typeof primary3?.simMs === "number") trial.simMs = primary3.simMs;
259562
259728
  scene2.trialsDetail.push(trial);
259563
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: [] });
@@ -259569,7 +259735,7 @@ function artifacts(record28, runDir) {
259569
259735
  if (excluded2(attempt.outcome)) scene2.warnings.push({ trial: attempt.number, check: "pytest", message: `${attempt.outcome}: excluded from grading` });
259570
259736
  if (observed.length > 1) scene2.warnings.push({ trial: attempt.number, check: "pytest", message: "This attempt used multiple worlds; state.json and trace.jsonl show the first captured world. All captures are in world-observations.json." });
259571
259737
  const trace = Array.isArray(primary3?.trace) ? primary3.trace : [];
259572
- scene2.agentCalls += attempt.worlds.reduce((sum6, world5) => sum6 + (Array.isArray(world5.capture?.observation.trace) ? world5.capture.observation.trace.filter((entry3) => entry3?.source === "agent").length : 0), 0);
259738
+ scene2.agentCalls += attempt.worlds.reduce((sum6, world5) => sum6 + (Array.isArray(world5.capture?.observation.trace) ? world5.capture.observation.trace.filter((entry3) => entry3?.source === "agent" && !isAgentAnswer(entry3)).length : 0), 0);
259573
259739
  files2.set(`${base3}/checks.json`, json34(checks2));
259574
259740
  files2.set(`${base3}/result.json`, json34({ source: "pytest", outcome: attempt.outcome, reportedOutcome: record28.attempts.find((item2) => item2.number === attempt.number).outcome, startedAt: attempt.startedAt, finishedAt: attempt.finishedAt, errors: attemptErrors(attempt), capture: primary3 ? "observation" : "none" }));
259575
259741
  files2.set(`${base3}/world-observations.json`, json34(attempt.worlds));
@@ -259609,12 +259775,12 @@ async function recordPytestRun(cwd, input4, env2 = {}) {
259609
259775
  attempts: record28.attempts.map((attempt) => ({ ...attempt, errors: cleanErrors(attempt.errors), worlds: attempt.worlds.map((world5) => redact3(world5, env2)) }))
259610
259776
  };
259611
259777
  const fingerprint = hash6(JSON.stringify(cleaned));
259612
- 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}`;
259613
259779
  const result = { runId: record28.runId, runDir, source: "pytest", target: "local", next: [`ancha --local runs show ${record28.runId}`, `ancha --local explain ${record28.runId}`] };
259614
259780
  const exists7 = async () => {
259615
259781
  await preflightFiles(cwd, [{ relativePath: `${relative26}/record.json`, content: "" }]);
259616
259782
  const completed = async () => {
259617
- const text29 = await readFile49(join66(runDir, "record.json"), "utf8");
259783
+ const text29 = await readFile50(join67(runDir, "record.json"), "utf8");
259618
259784
  let previous;
259619
259785
  try {
259620
259786
  previous = JSON.parse(text29);
@@ -259648,11 +259814,11 @@ async function recordPytestRun(cwd, input4, env2 = {}) {
259648
259814
  files2.set("record.json", json34({ version: 1, fingerprint }));
259649
259815
  await mkdir32(outDir, { recursive: true, mode: 448 });
259650
259816
  await preflightFiles(cwd, [{ relativePath: `${relative26}/summary.json`, content: "" }]);
259651
- const staging = await mkdtemp12(join66(outDir, ".pytest-"));
259817
+ const staging = await mkdtemp12(join67(outDir, ".pytest-"));
259652
259818
  try {
259653
259819
  for (const [path7, content2] of files2) {
259654
- await mkdir32(dirname24(join66(staging, path7)), { recursive: true, mode: 448 });
259655
- 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 });
259656
259822
  }
259657
259823
  await preflightFiles(cwd, [{ relativePath: `${relative26}/summary.json`, content: "" }]);
259658
259824
  try {
@@ -259661,12 +259827,12 @@ async function recordPytestRun(cwd, input4, env2 = {}) {
259661
259827
  if (["EEXIST", "ENOTEMPTY"].includes(error65.code ?? "") && await exists7()) return result;
259662
259828
  throw error65;
259663
259829
  }
259664
- const latest2 = join66(outDir, `.latest-pytest-${randomBytes10(8).toString("hex")}`);
259830
+ const latest2 = join67(outDir, `.latest-pytest-${randomBytes10(8).toString("hex")}`);
259665
259831
  try {
259666
259832
  await writeFile34(latest2, `${record28.runId}
259667
259833
  `, { flag: "wx", mode: 384 });
259668
259834
  await preflightFiles(cwd, [{ relativePath: `${DEFAULT_RUNS_DIR}/latest`, content: "" }]);
259669
- await rename11(latest2, join66(outDir, "latest"));
259835
+ await rename11(latest2, join67(outDir, "latest"));
259670
259836
  } finally {
259671
259837
  await rm20(latest2, { force: true });
259672
259838
  }
@@ -259744,14 +259910,14 @@ ${formatTable(value5.configuration.preset.datasets.map((data5) => [data5.tool, d
259744
259910
  // packages/cli/src/commands/secrets.ts
259745
259911
  var import_yaml19 = __toESM(require_dist(), 1);
259746
259912
  init_src();
259747
- import { readFile as readFile50, writeFile as writeFile35 } from "node:fs/promises";
259913
+ import { readFile as readFile51, writeFile as writeFile35 } from "node:fs/promises";
259748
259914
  import { resolve as resolve51 } from "node:path";
259749
259915
  init_credentials();
259750
259916
  var NAME_RE2 = /^[A-Z][A-Z0-9_]{0,63}$/;
259751
259917
  async function nameInConfig(ctx, names5) {
259752
259918
  const label5 = ctx.globals().config ?? "ancha.yaml", file3 = resolve51(ctx.io.cwd, label5);
259753
259919
  const them = names5.length === 1 ? "it" : "them", list18 = names5.join(", ");
259754
- const text29 = await readFile50(file3, "utf8").catch(() => void 0);
259920
+ const text29 = await readFile51(file3, "utf8").catch(() => void 0);
259755
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}` };
259756
259922
  const doc = (0, import_yaml19.parseDocument)(text29);
259757
259923
  const listed2 = (path7) => {
@@ -259899,7 +260065,7 @@ function anchaConfigSchema() {
259899
260065
  pass_env: { ...strings4, description: "names a local agent inherits from this shell besides the base set; values are never saved" },
259900
260066
  install: { ...string8, minLength: 1, maxLength: 2e3, pattern: "^(?![\\s]*$)[^\\u0000\\r\\n]+$", description: "dependency installation command for a cloud attempt" },
259901
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" },
259902
- 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" },
259903
260069
  slack_transport: { enum: ["feed", "http", "socket"] },
259904
260070
  execution: {
259905
260071
  type: "object",
@@ -260157,15 +260323,15 @@ function registerSchema(program2, ctx) {
260157
260323
  // packages/cli/src/commands/runs.ts
260158
260324
  var import_yaml20 = __toESM(require_dist(), 1);
260159
260325
  init_src();
260160
- import { mkdir as mkdir33, readFile as readFile52, writeFile as writeFile36 } from "node:fs/promises";
260161
- 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";
260162
260328
  init_report2();
260163
260329
  init_run_store();
260164
260330
 
260165
260331
  // backend/src/trace-ir.ts
260166
260332
  init_src();
260167
- import { readFile as readFile51 } from "node:fs/promises";
260168
- import { join as join67 } from "node:path";
260333
+ import { readFile as readFile52 } from "node:fs/promises";
260334
+ import { join as join68 } from "node:path";
260169
260335
  var VENDOR_API_BASES = {
260170
260336
  slack: "https://slack.com",
260171
260337
  github: "https://api.github.com",
@@ -260188,7 +260354,7 @@ var vendorBase = (service) => VENDOR_API_BASES[service] ?? `https://${service}.i
260188
260354
  function attemptToIr(entries4, traceId, agent, saved) {
260189
260355
  const records4 = [];
260190
260356
  for (const e of projectToolCalls(entries4)) {
260191
- if (e.source === "agent" && e.service === "agent" && e.path === "/done") continue;
260357
+ if (isAgentAnswer(e)) continue;
260192
260358
  if (e.source === "agent" && e.service === "tools" && e.path.startsWith("/tools/")) {
260193
260359
  const response5 = e.response;
260194
260360
  records4.push({
@@ -260232,7 +260398,7 @@ function attemptToIr(entries4, traceId, agent, saved) {
260232
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];
260233
260399
  }
260234
260400
  async function readAttemptTrace(dir2) {
260235
- const text29 = (await readFile51(join67(dir2, "trace.jsonl"), "utf8")).trim();
260401
+ const text29 = (await readFile52(join68(dir2, "trace.jsonl"), "utf8")).trim();
260236
260402
  return text29 ? text29.split("\n").map((line2) => JSON.parse(line2)) : [];
260237
260403
  }
260238
260404
 
@@ -260263,7 +260429,7 @@ async function testTask(ctx, file3, worldOverride) {
260263
260429
  const path7 = resolve52(ctx.io.cwd, file3);
260264
260430
  let doc;
260265
260431
  try {
260266
- doc = (0, import_yaml20.parse)(await readFile52(path7, "utf8"));
260432
+ doc = (0, import_yaml20.parse)(await readFile53(path7, "utf8"));
260267
260433
  } catch (error65) {
260268
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)" });
260269
260435
  }
@@ -260366,8 +260532,8 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
260366
260532
  if (isCloudId(ref22)) throw new AnchaError("USAGE", `${ref22} ran in the cloud and is in the workspace already`, { hint: `ancha runs show ${ref22}` });
260367
260533
  const workspace4 = await uploadWorkspace(ctx);
260368
260534
  const summary = await loadRunSummary(ctx.io.cwd, ref22, options4.out);
260369
- const runDir = join68(resolve52(ctx.io.cwd, options4.out ?? DEFAULT_RUNS_DIR), summary.runId);
260370
- 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(() => "{}"));
260371
260537
  const passEnv = inputs2.agentEnvironment?.passEnv ?? (await ctx.loadConfig().catch(() => void 0))?.agent?.passEnv ?? [];
260372
260538
  const inheritEnv = inputs2.agentEnvironment?.inheritEnv ?? summary.agentEnvironment?.inheritAll === true;
260373
260539
  const upload4 = await uploadRun(ctx, workspace4, { runId: summary.runId, runDir, passEnv, inheritEnv });
@@ -260377,15 +260543,15 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
260377
260543
  if (ref22 === "latest") ref22 = await latestRunId(ctx.io.cwd, options4.out);
260378
260544
  onThisComputer(ref22);
260379
260545
  const summary = await loadRunSummary(ctx.io.cwd, ref22, options4.out);
260380
- 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));
260381
260547
  await mkdir33(dest, { recursive: true });
260382
- 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), () => ({}));
260383
260549
  const files2 = [], cases = withSeeds(inputs2.cases ?? []);
260384
260550
  for (const scene2 of summary.scenes) for (const trial of scene2.trialsDetail) {
260385
- 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`);
260386
260552
  await writeFile36(file3, attemptToIr(await readAttemptTrace(dir2), `${summary.runId}/${name5}`, summary.agent, {
260387
260553
  scene: cases.find((c) => c.id === scene2.sceneId)?.scene,
260388
- 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),
260389
260555
  outcome: trial.outcome ?? (trial.valid === false ? "invalid" : trial.passed ? "passed" : "failed"),
260390
260556
  exit: trial.exit,
260391
260557
  exitCode: trial.exitCode
@@ -260455,8 +260621,8 @@ next: ancha wait ${id14}`);
260455
260621
 
260456
260622
  // packages/cli/src/commands/traces.ts
260457
260623
  import { createHash as createHash77 } from "node:crypto";
260458
- import { access as access15, readFile as readFile54, mkdir as mkdir34, stat as stat18, writeFile as writeFile37 } from "node:fs/promises";
260459
- 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";
260460
260626
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
260461
260627
  var import_yaml21 = __toESM(require_dist(), 1);
260462
260628
  init_src();
@@ -260582,7 +260748,7 @@ async function listTraces(source, { limit: limit2, since, name: name5 }, env2, f
260582
260748
  }
260583
260749
 
260584
260750
  // packages/cli/src/trace-files.ts
260585
- import { readFile as readFile53, stat as stat17 } from "node:fs/promises";
260751
+ import { readFile as readFile54, stat as stat17 } from "node:fs/promises";
260586
260752
  import { basename as basename15, relative as relative23, resolve as resolve53 } from "node:path";
260587
260753
  init_src();
260588
260754
  var MB3 = 1024 * 1024;
@@ -260611,7 +260777,7 @@ async function findTraceFiles(cwd, args) {
260611
260777
  return [...found].sort();
260612
260778
  }
260613
260779
  async function readTraceTexts(cwd, paths2) {
260614
- 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) })));
260615
260781
  }
260616
260782
  function readTraceUnits(texts4, { fileToIr: fileToIr2, sourceOf: sourceOf2 }) {
260617
260783
  const drafts = /* @__PURE__ */ new Map(), skipped = [], read7 = [];
@@ -261052,7 +261218,7 @@ var importedCheckLines = (scene2, production3) => [
261052
261218
  ...importedChecks(scene2, production3).map((c) => ` ${c.id}: ${c.required ? "required" : "optional"}, ${c.production} in production`)
261053
261219
  ];
261054
261220
  async function localChanges(dir2) {
261055
- 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);
261056
261222
  if (text29 === void 0) return void 0;
261057
261223
  const local2 = (() => {
261058
261224
  try {
@@ -261063,7 +261229,7 @@ async function localChanges(dir2) {
261063
261229
  })(), mark = MARK.exec(text29)?.[1];
261064
261230
  if (local2 === void 0 || mark === void 0) return { added: [], other: true };
261065
261231
  if (digest3(local2) === mark) return { added: [], other: false };
261066
- 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);
261067
261233
  const added = production3 ? checksOf2(local2).filter((c) => !Object.hasOwn(production3, c.id)) : [];
261068
261234
  const addedIds = new Set(added.map((c) => c.id));
261069
261235
  const required4 = (Array.isArray(local2.pass) ? local2.pass : checksOf2(local2).map((c) => c.id)).filter((id14) => addedIds.has(id14));
@@ -261077,7 +261243,7 @@ async function guard(ctx, dir2, force) {
261077
261243
  if (changes?.other) {
261078
261244
  throw new AnchaError(
261079
261245
  "USAGE",
261080
- `${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`,
261081
261247
  { hint: "move those changes into checks of your own, or pass --force to overwrite the file" }
261082
261248
  );
261083
261249
  }
@@ -261104,19 +261270,19 @@ async function writeWorld(ctx, world5, dest, changes) {
261104
261270
  const dir2 = resolve54(ctx.io.cwd, dest, world5.name);
261105
261271
  await mkdir34(dir2, { recursive: true });
261106
261272
  const { scene: content2, kept } = sceneToWrite(world5.scene, changes);
261107
- const scene2 = join69(dir2, "scene.yaml");
261273
+ const scene2 = join70(dir2, "scene.yaml");
261108
261274
  const { sceneFiles: sceneFiles2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
261109
261275
  const files2 = sceneFiles2(content2);
261110
261276
  await writeFile37(scene2, `# Rebuilt by Ancha from a production trace (world ${world5.id}). Where each part came from: provenance.json.
261111
261277
  # ancha pull: ${world5.id} ${digest3(sceneFiles2(world5.scene).scene)}
261112
261278
  ${(0, import_yaml21.stringify)(files2.scene)}`);
261113
- if (files2.observations !== void 0) await writeFile37(join69(dir2, "observations.jsonl"), files2.observations);
261114
- if (world5.record) await writeFile37(join69(dir2, "production.jsonl"), productionLines(world5.record));
261115
- await writeFile37(join69(dir2, "provenance.json"), JSON.stringify(world5.provenance, null, 2) + "\n");
261116
- 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");
261117
261283
  if (world5.summary?.production !== void 0) {
261118
261284
  const checks2 = { ...Object.fromEntries(checksOf2(world5.scene).map((c) => [c.id, "unknown"])), ...world5.summary.production };
261119
- 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");
261120
261286
  }
261121
261287
  await loadSceneFile(scene2);
261122
261288
  return { dir: dir2, scene: scene2, kept };
@@ -261620,7 +261786,7 @@ function registerTraces(program2, ctx) {
261620
261786
  });
261621
261787
  }
261622
261788
  async function traceSource(ctx, trace, from) {
261623
- 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(() => {
261624
261790
  throw new AnchaError("USAGE", `cannot read ${trace}`, { hint: "pass the path of a trace file: ancha import --offline <trace.jsonl>" });
261625
261791
  }), name: basename16(trace), label: basename16(trace) };
261626
261792
  const doc = await fetchTrace(from, trace, ctx.io.env);
@@ -261628,7 +261794,7 @@ async function traceSource(ctx, trace, from) {
261628
261794
  return { text: JSON.stringify(doc), name: `${from}-${id14}`.slice(0, 80), label: `${from === "langfuse" ? "Langfuse" : "LangSmith"} trace ${id14}` };
261629
261795
  }
261630
261796
  async function traceFileLines(ctx, file3) {
261631
- const text29 = await readFile54(resolve54(ctx.io.cwd, file3), "utf8").catch(() => {
261797
+ const text29 = await readFile55(resolve54(ctx.io.cwd, file3), "utf8").catch(() => {
261632
261798
  throw new AnchaError("USAGE", `cannot read ${file3}`, { hint: "pass the path of a trace file: ancha traces diff <trace.jsonl> latest" });
261633
261799
  });
261634
261800
  return { text: text29, lines: await traceTextLines(text29, basename16(file3)) };
@@ -261706,7 +261872,7 @@ async function writeRecords(ctx, conversations, dest) {
261706
261872
  const seen = conversations.flatMap((c) => recordsOf2(toolCallsOf(c.lines), { conversation: c.id }));
261707
261873
  if (!seen.length) return void 0;
261708
261874
  const path7 = resolve54(ctx.io.cwd, dest, "records.jsonl");
261709
- const merged = mergeRecords2(readRecordLines2(await readFile54(path7, "utf8").catch(() => "")), seen);
261875
+ const merged = mergeRecords2(readRecordLines2(await readFile55(path7, "utf8").catch(() => "")), seen);
261710
261876
  await mkdir34(dirname25(path7), { recursive: true });
261711
261877
  await writeFile37(path7, recordLines2(merged));
261712
261878
  const types = merged.reduce((all9, r2) => all9.set(r2.type, (all9.get(r2.type) ?? 0) + 1), /* @__PURE__ */ new Map());
@@ -261735,7 +261901,7 @@ async function importLocally(ctx, source, options4) {
261735
261901
  const made = [], skipped = [];
261736
261902
  for (const [i, conversation3] of picked.entries()) {
261737
261903
  const examples2 = [...all9.filter((c) => c !== conversation3).map((c) => c.lines), ...files2], customer3 = customers3.people[i];
261738
- 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), () => ({}));
261739
261905
  try {
261740
261906
  const preview = rebuild2(conversation3.lines, { id: named5.get(conversation3), withRecords: true, examples: examples2 });
261741
261907
  const answers = { ...answersFor(preview.questions, earlier2, options4.answer), ...options4.expect && { "checks.expect": options4.expect } };
@@ -261746,23 +261912,23 @@ async function importLocally(ctx, source, options4) {
261746
261912
  skipped.push(conversation3.id);
261747
261913
  }
261748
261914
  }
261749
- 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"));
261750
261916
  if (!options4.force) {
261751
- 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`);
261752
261918
  }
261753
261919
  for (const [i, m] of made.entries()) {
261754
261920
  const path7 = paths2[i], dir2 = dirname25(path7);
261755
261921
  await mkdir34(dir2, { recursive: true });
261756
261922
  const files3 = sceneFiles2(m.made.scene);
261757
261923
  await writeFile37(path7, (0, import_yaml21.stringify)(files3.scene, { lineWidth: 0 }));
261758
- await writeFile37(join69(dir2, "answers.json"), JSON.stringify(m.answers, null, 2) + "\n");
261759
- if (files3.observations !== void 0) await writeFile37(join69(dir2, "observations.jsonl"), files3.observations);
261760
- if (m.made.record) await writeFile37(join69(dir2, "production.jsonl"), productionLines(m.made.record));
261761
- 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)}
261762
261928
  `);
261763
- 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)}
261764
261930
  `);
261765
- 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)}
261766
261932
  `);
261767
261933
  await loadSceneFile(path7);
261768
261934
  }