@ancha-labs/cli 0.2.1 → 0.4.0

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.
@@ -56907,9 +56907,9 @@ function stringifyPrimitive(value4) {
56907
56907
  return `"${value4}"`;
56908
56908
  return `${value4}`;
56909
56909
  }
56910
- function optionalKeys(shape3) {
56911
- return Object.keys(shape3).filter((k) => {
56912
- return shape3[k]._zod.optin !== void 0 && shape3[k]._zod.optout === "optional";
56910
+ function optionalKeys(shape4) {
56911
+ return Object.keys(shape4).filter((k) => {
56912
+ return shape4[k]._zod.optin !== void 0 && shape4[k]._zod.optout === "optional";
56913
56913
  });
56914
56914
  }
56915
56915
  var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({
@@ -56958,33 +56958,33 @@ function omit(schema, mask2) {
56958
56958
  mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key3) => !omitted.has(key3)));
56959
56959
  return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
56960
56960
  }
56961
- function extend(schema, shape3) {
56962
- if (!isPlainObject(shape3)) {
56961
+ function extend(schema, shape4) {
56962
+ if (!isPlainObject(shape4)) {
56963
56963
  throw new Error("Invalid input to extend: expected a plain object");
56964
56964
  }
56965
56965
  const checks = schema._zod.def.checks;
56966
56966
  const hasChecks = checks && checks.length > 0;
56967
56967
  if (hasChecks) {
56968
56968
  const existingShape = sourceShape(schema);
56969
- for (const key3 of Reflect.ownKeys(shape3)) {
56969
+ for (const key3 of Reflect.ownKeys(shape4)) {
56970
56970
  if (Object.getOwnPropertyDescriptor(existingShape, key3) !== void 0) {
56971
56971
  throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
56972
56972
  }
56973
56973
  }
56974
56974
  }
56975
- return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape3) }));
56975
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape4) }));
56976
56976
  }
56977
- function extended(schema, shape3) {
56977
+ function extended(schema, shape4) {
56978
56978
  const newShape = {};
56979
56979
  mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));
56980
- mirrorProps(newShape, shape3);
56980
+ mirrorProps(newShape, shape4);
56981
56981
  return newShape;
56982
56982
  }
56983
- function safeExtend(schema, shape3) {
56984
- if (!isPlainObject(shape3)) {
56983
+ function safeExtend(schema, shape4) {
56984
+ if (!isPlainObject(shape4)) {
56985
56985
  throw new Error("Invalid input to safeExtend: expected a plain object");
56986
56986
  }
56987
- return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape3) }));
56987
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape4) }));
56988
56988
  }
56989
56989
  function merge(a, b) {
56990
56990
  if (!b?._zod?.def) {
@@ -59432,10 +59432,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
59432
59432
  }
59433
59433
  const _normalized = cached(() => normalizeDef(def));
59434
59434
  defineLazyInternal(inst, "propValues", (zod) => {
59435
- const shape3 = zod.def.shape;
59435
+ const shape4 = zod.def.shape;
59436
59436
  const propValues = {};
59437
- for (const key3 in shape3) {
59438
- const field3 = shape3[key3]._zod;
59437
+ for (const key3 in shape4) {
59438
+ const field3 = shape4[key3]._zod;
59439
59439
  if (field3.values) {
59440
59440
  if (!Object.prototype.hasOwnProperty.call(propValues, key3)) {
59441
59441
  assignProp(propValues, key3, /* @__PURE__ */ new Set());
@@ -59467,7 +59467,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
59467
59467
  }
59468
59468
  payload2.value = memo3 ? memo3.alloc(inst, payload2, {}, ctx) : {};
59469
59469
  const proms = [];
59470
- const shape3 = value4.shape;
59470
+ const shape4 = value4.shape;
59471
59471
  const abortEarly = ctx?.abortEarly;
59472
59472
  let seen = payload2.issues.length;
59473
59473
  for (const key3 of value4.allKeys) {
@@ -59478,7 +59478,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
59478
59478
  }
59479
59479
  if (key3 === "__proto__")
59480
59480
  continue;
59481
- const el2 = shape3[key3];
59481
+ const el2 = shape4[key3];
59482
59482
  const optin = el2._zod.optin;
59483
59483
  const optout = el2._zod.optout;
59484
59484
  const r = el2._zod.run({ value: input2[key3], issues: [] }, ctx);
@@ -59499,10 +59499,10 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
59499
59499
  const superParse = inst._zod.parse;
59500
59500
  const _normalized = cached(() => normalizeDef(def));
59501
59501
  const memo3 = globalConfig.memoizer;
59502
- const generateFastpass = (shape3) => {
59502
+ const generateFastpass = (shape4) => {
59503
59503
  const normalized = _normalized.value;
59504
59504
  const syms = normalized.symbolKeys;
59505
- const doc = new Doc(["payload", "ctx"], { shape: shape3, inst, memo: memo3, syms });
59505
+ const doc = new Doc(["payload", "ctx"], { shape: shape4, inst, memo: memo3, syms });
59506
59506
  const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
59507
59507
  const prefixStr = (id12, k) => `
59508
59508
  let ${id12}_ab = false;
@@ -59529,7 +59529,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
59529
59529
  const id12 = ids2[key3];
59530
59530
  const k = typeof key3 === "symbol" ? `syms[${syms.indexOf(key3)}]` : esc(key3);
59531
59531
  const isPresent = `${k} in input`;
59532
- const schema = shape3[key3];
59532
+ const schema = shape4[key3];
59533
59533
  const optin = schema?._zod?.optin;
59534
59534
  const isOptionalIn = optin !== void 0;
59535
59535
  const isOptionalOut = schema?._zod?.optout === "optional";
@@ -60968,7 +60968,7 @@ function isRecursive(inst, stack, resolve5) {
60968
60968
  result = answer;
60969
60969
  }
60970
60970
  };
60971
- const shape3 = (sh, spread) => {
60971
+ const shape4 = (sh, spread) => {
60972
60972
  let answer = NONE;
60973
60973
  for (const key3 of Reflect.ownKeys(sh)) {
60974
60974
  const desc = Object.getOwnPropertyDescriptor(sh, key3);
@@ -60989,7 +60989,7 @@ function isRecursive(inst, stack, resolve5) {
60989
60989
  switch (kind) {
60990
60990
  case "object": {
60991
60991
  const raw3 = rawShape(def);
60992
- merge3(raw3 ? shape3(raw3, true) : ASSUMED);
60992
+ merge3(raw3 ? shape4(raw3, true) : ASSUMED);
60993
60993
  check3(def.catchall);
60994
60994
  break;
60995
60995
  }
@@ -69200,12 +69200,12 @@ function generatePropertiesChecks(doc, ctx, def, accessor) {
69200
69200
  throw new ZodCompileUnsupportedError(`check with a custom "when" condition`);
69201
69201
  }
69202
69202
  doc.write(`if (${accessor} == null) return INVALID;`);
69203
- const shape3 = def.shape;
69204
- for (const key3 of Reflect.ownKeys(shape3)) {
69203
+ const shape4 = def.shape;
69204
+ for (const key3 of Reflect.ownKeys(shape4)) {
69205
69205
  const keyExpr = typeof key3 === "symbol" ? addConstant(ctx, key3) : esc(key3);
69206
69206
  const inputVar = newVar(ctx);
69207
69207
  doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`);
69208
- compileChild(doc, ctx, shape3[key3], inputVar, false);
69208
+ compileChild(doc, ctx, shape4[key3], inputVar, false);
69209
69209
  }
69210
69210
  }
69211
69211
  function generatePropertyCheck(doc, ctx, def, accessor) {
@@ -69587,13 +69587,13 @@ function generateDateCheck(doc, accessor) {
69587
69587
  function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) {
69588
69588
  const def = schema._zod.def;
69589
69589
  doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);
69590
- const shape3 = def.shape;
69591
- const keys5 = Object.keys(shape3);
69592
- const symbolKeys = Object.getOwnPropertySymbols(shape3);
69590
+ const shape4 = def.shape;
69591
+ const keys5 = Object.keys(shape4);
69592
+ const symbolKeys = Object.getOwnPropertySymbols(shape4);
69593
69593
  const allKeys = symbolKeys.length ? [...keys5, ...symbolKeys] : keys5;
69594
69594
  const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k);
69595
69595
  const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k);
69596
- const propShape = shape3;
69596
+ const propShape = shape4;
69597
69597
  if (keys5.includes("__proto__")) {
69598
69598
  throw new ZodCompileUnsupportedError('object shape key "__proto__"');
69599
69599
  }
@@ -71100,10 +71100,10 @@ function _property(property3, schema, params9) {
71100
71100
  });
71101
71101
  }
71102
71102
  // @__NO_SIDE_EFFECTS__
71103
- function _properties(shape3, params9) {
71103
+ function _properties(shape4, params9) {
71104
71104
  return new $ZodCheckProperties({
71105
71105
  check: "properties",
71106
- shape: shape3,
71106
+ shape: shape4,
71107
71107
  ...normalizeParams(params9)
71108
71108
  });
71109
71109
  }
@@ -72365,21 +72365,21 @@ function inputOptin(schema) {
72365
72365
  var objectProcessor = (schema, ctx, _json, params9) => {
72366
72366
  const json30 = _json;
72367
72367
  const def = schema._zod.def;
72368
- const shape3 = def.shape;
72369
- const symbolKeys = Object.getOwnPropertySymbols(shape3);
72368
+ const shape4 = def.shape;
72369
+ const symbolKeys = Object.getOwnPropertySymbols(shape4);
72370
72370
  if (symbolKeys.length && handleUnrepresentable(schema, ctx, json30, params9, "Symbol keys cannot be represented in JSON Schema")) {
72371
72371
  return;
72372
72372
  }
72373
72373
  json30.type = "object";
72374
72374
  json30.properties = {};
72375
- for (const key3 in shape3) {
72376
- assignProp(json30.properties, key3, processSchema(shape3[key3], ctx, {
72375
+ for (const key3 in shape4) {
72376
+ assignProp(json30.properties, key3, processSchema(shape4[key3], ctx, {
72377
72377
  ...params9,
72378
72378
  path: [...params9.path, "properties", key3]
72379
72379
  }));
72380
72380
  }
72381
72381
  const requiredKeys = [];
72382
- for (const key3 of Object.keys(shape3)) {
72382
+ for (const key3 of Object.keys(shape4)) {
72383
72383
  const field3 = def.shape[key3];
72384
72384
  if (ctx.io === "input" ? inputOptin(field3) === void 0 : field3._zod.optout === void 0) {
72385
72385
  requiredKeys.push(key3);
@@ -73941,8 +73941,8 @@ function array(element, params9) {
73941
73941
  return _array(ZodArray, element, params9);
73942
73942
  }
73943
73943
  function keyof(schema) {
73944
- const shape3 = schema._zod.def.shape;
73945
- return _enum2(Object.keys(shape3));
73944
+ const shape4 = schema._zod.def.shape;
73945
+ return _enum2(Object.keys(shape4));
73946
73946
  }
73947
73947
  var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
73948
73948
  _ensureDefaultMemoizer();
@@ -73994,26 +73994,26 @@ var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
73994
73994
  return util_exports.required(ZodNonOptional, this, args[0]);
73995
73995
  }
73996
73996
  });
73997
- function object(shape3, params9) {
73997
+ function object(shape4, params9) {
73998
73998
  const def = {
73999
73999
  type: "object",
74000
- shape: shape3 ?? {},
74000
+ shape: shape4 ?? {},
74001
74001
  ...util_exports.normalizeParams(params9)
74002
74002
  };
74003
74003
  return new ZodObject(def);
74004
74004
  }
74005
- function strictObject(shape3, params9) {
74005
+ function strictObject(shape4, params9) {
74006
74006
  return new ZodObject({
74007
74007
  type: "object",
74008
- shape: shape3,
74008
+ shape: shape4,
74009
74009
  catchall: never(),
74010
74010
  ...util_exports.normalizeParams(params9)
74011
74011
  });
74012
74012
  }
74013
- function looseObject(shape3, params9) {
74013
+ function looseObject(shape4, params9) {
74014
74014
  return new ZodObject({
74015
74015
  type: "object",
74016
- shape: shape3,
74016
+ shape: shape4,
74017
74017
  catchall: unknown(),
74018
74018
  ...util_exports.normalizeParams(params9)
74019
74019
  });
@@ -74552,8 +74552,8 @@ var meta2 = meta;
74552
74552
  var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => {
74553
74553
  ZodCustom.init(inst, def);
74554
74554
  }, {
74555
- properties(shape3, params9) {
74556
- return this.check(_properties(shape3, params9));
74555
+ properties(shape4, params9) {
74556
+ return this.check(_properties(shape4, params9));
74557
74557
  }
74558
74558
  });
74559
74559
  function _instanceof(cls, params9 = {}) {
@@ -75139,13 +75139,13 @@ function convertBaseSchema(schema, ctx) {
75139
75139
  break;
75140
75140
  }
75141
75141
  case "object": {
75142
- const shape3 = {};
75142
+ const shape4 = {};
75143
75143
  const properties2 = schema.properties || {};
75144
75144
  const requiredSet = new Set(schema.required || []);
75145
75145
  const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0;
75146
75146
  for (const [key3, propSchema] of Object.entries(properties2)) {
75147
75147
  const propZodSchema = convertSchema(propSchema, ctx);
75148
- assignProp(shape3, key3, requiredSet.has(key3) ? propZodSchema : propZodSchema.optional());
75148
+ assignProp(shape4, key3, requiredSet.has(key3) ? propZodSchema : propZodSchema.optional());
75149
75149
  }
75150
75150
  if (schema.patternProperties) {
75151
75151
  const patternProps = schema.patternProperties;
@@ -75157,8 +75157,8 @@ function convertBaseSchema(schema, ctx) {
75157
75157
  looseRecords.push(z.looseRecord(keySchema, patternValue));
75158
75158
  }
75159
75159
  const schemasToIntersect = [];
75160
- if (Object.keys(shape3).length > 0) {
75161
- schemasToIntersect.push(z.object(shape3).passthrough());
75160
+ if (Object.keys(shape4).length > 0) {
75161
+ schemasToIntersect.push(z.object(shape4).passthrough());
75162
75162
  }
75163
75163
  schemasToIntersect.push(...looseRecords);
75164
75164
  if (schemasToIntersect.length === 0) {
@@ -75173,7 +75173,7 @@ function convertBaseSchema(schema, ctx) {
75173
75173
  zodSchema = result;
75174
75174
  }
75175
75175
  if (schema.additionalProperties === false) {
75176
- const propertyKeys = Object.keys(shape3);
75176
+ const propertyKeys = Object.keys(shape4);
75177
75177
  const patterns = patternKeys.map((p2) => new RegExp(p2));
75178
75178
  const basePatternSchema = zodSchema;
75179
75179
  zodSchema = zodSchema.check((payload2) => {
@@ -75198,7 +75198,7 @@ function convertBaseSchema(schema, ctx) {
75198
75198
  });
75199
75199
  }
75200
75200
  } else {
75201
- const objectSchema = z.object(shape3);
75201
+ const objectSchema = z.object(shape4);
75202
75202
  if (schema.additionalProperties === false) {
75203
75203
  zodSchema = objectSchema.strict();
75204
75204
  } else if (additionalSchema) {
@@ -78375,11 +78375,11 @@ function build() {
78375
78375
  const ResultTypeSchema = string2();
78376
78376
  const ResultMetaSchema = looseObject({ [SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) });
78377
78377
  const wireMeta = ResultMetaSchema.optional();
78378
- function wireResult(shape3) {
78378
+ function wireResult(shape4) {
78379
78379
  return looseObject({
78380
78380
  _meta: wireMeta,
78381
78381
  resultType: ResultTypeSchema.default("complete"),
78382
- ...shape3
78382
+ ...shape4
78383
78383
  });
78384
78384
  }
78385
78385
  const ResultSchema$1 = wireResult({});
@@ -78592,10 +78592,10 @@ function build() {
78592
78592
  "server/discover": dispatchRequest("server/discover", {}),
78593
78593
  "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape)
78594
78594
  };
78595
- function liftedResult(shape3) {
78595
+ function liftedResult(shape4) {
78596
78596
  return looseObject({
78597
78597
  _meta: wireMeta,
78598
- ...shape3
78598
+ ...shape4
78599
78599
  });
78600
78600
  }
78601
78601
  const dispatchResultSchemas = {
@@ -88535,7 +88535,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
88535
88535
  function isLeapYear(year) {
88536
88536
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
88537
88537
  }
88538
- const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
88538
+ const DATE2 = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
88539
88539
  const DAYS2 = [
88540
88540
  0,
88541
88541
  31,
@@ -88552,7 +88552,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
88552
88552
  31
88553
88553
  ];
88554
88554
  function date10(str3) {
88555
- const matches7 = DATE.exec(str3);
88555
+ const matches7 = DATE2.exec(str3);
88556
88556
  if (!matches7) return false;
88557
88557
  const year = +matches7[1];
88558
88558
  const month = +matches7[2];
@@ -90383,9 +90383,9 @@ var McpServer = class {
90383
90383
  };
90384
90384
  this._registeredPrompts[name5] = registeredPrompt;
90385
90385
  if (argsSchema) {
90386
- const shape3 = getSchemaShape(argsSchema);
90387
- if (shape3) {
90388
- if (Object.values(shape3).some((field3) => {
90386
+ const shape4 = getSchemaShape(argsSchema);
90387
+ if (shape4) {
90388
+ if (Object.values(shape4).some((field3) => {
90389
90389
  return isCompletable(unwrapOptionalSchema(field3));
90390
90390
  })) this.setCompletionRequestHandler();
90391
90391
  }
@@ -91921,6 +91921,8 @@ var EXECUTION_SUPPORT = {
91921
91921
  "world_rules": sceneOnly,
91922
91922
  "people": sceneOnly,
91923
91923
  "until": sceneOnly,
91924
+ "trigger": sceneOnly,
91925
+ "tools": sceneOnly,
91924
91926
  "deadline": sceneOnly,
91925
91927
  "start.message": sceneOnly,
91926
91928
  "pass": sceneOnly,
@@ -91959,7 +91961,8 @@ var EXECUTION_SUPPORT = {
91959
91961
  "--pass-env": sceneOnly,
91960
91962
  "--inherit-env": sceneOnly,
91961
91963
  "--upload": sceneOnly,
91962
- "--upload-required": sceneOnly
91964
+ "--upload-required": sceneOnly,
91965
+ "--allow-unwrapped": sceneOnly
91963
91966
  };
91964
91967
 
91965
91968
  // packages/core/src/relay.ts
@@ -100635,6 +100638,53 @@ var TraceCheckSchema = external_exports.strictObject({
100635
100638
  message: "status applies to called; not_called always counts every attempt",
100636
100639
  path: ["status"]
100637
100640
  });
100641
+ var TOOL_NAME_PATTERN = /^[A-Za-z_][\w.-]{0,127}$/;
100642
+ var ToolObservationSchema = external_exports.strictObject({
100643
+ tool: external_exports.string().regex(TOOL_NAME_PATTERN),
100644
+ at: duration6("Offset from the start of the production trace, e.g. 3s200ms"),
100645
+ /** When the call returned, as an offset like `at`: a test that reaches this answer has reached that time. */
100646
+ end: duration6("Offset from the start of the production trace when the call returned").optional(),
100647
+ args: external_exports.unknown().optional(),
100648
+ /** What the tool function returned. A recorded failure has `error` instead. */
100649
+ result: external_exports.unknown().optional(),
100650
+ error: external_exports.string().optional(),
100651
+ /** The framework's envelope as the trace held it (an MCP CallToolResult, a LangChain ToolMessage), for replay over MCP. */
100652
+ wrap: external_exports.enum(["mcp", "langchain", "output"]).optional(),
100653
+ raw: external_exports.unknown().optional(),
100654
+ call_id: external_exports.string().optional()
100655
+ }).refine((o) => o.error === void 0 || o.result === void 0, { message: "a recorded call has a result or an error, not both" });
100656
+ var ToolExampleSchema = external_exports.strictObject({
100657
+ trace: external_exports.string().optional(),
100658
+ at: duration6("Offset from the start of that trace"),
100659
+ args: external_exports.unknown().optional(),
100660
+ result: external_exports.unknown().optional(),
100661
+ error: external_exports.string().optional()
100662
+ });
100663
+ var SceneToolSchema = external_exports.strictObject({
100664
+ /** A JSON lines file next to the scene, one recorded call per line (`ancha run` reads it into `recorded`). */
100665
+ observations: external_exports.string().regex(/^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/, "a path relative to the scene file, without ..").optional(),
100666
+ recorded: external_exports.array(ToolObservationSchema).optional(),
100667
+ /** Calls from other traces of this agent, so a simulated answer can follow how the tool behaved there. */
100668
+ examples: external_exports.array(ToolExampleSchema).optional(),
100669
+ /** A call production never made: simulated (the default for a read), a tool error (the default for a write), or the twin. */
100670
+ unrecorded: external_exports.enum(["simulate", "fail", "twin"]).optional(),
100671
+ /** The twin that answers what production never recorded (TRACE_PLAN_V2 §5.3). */
100672
+ twin: external_exports.string().optional(),
100673
+ /** The agent reaches this tool over MCP: in a test its client points at {{tools.mcp_url}}, so there is nothing to wrap. */
100674
+ mcp: external_exports.literal(true).optional(),
100675
+ /** `ancha run --allow-unwrapped`: the agent may call this tool for real (it does not wrap it), so the test does not stop. */
100676
+ allow_unwrapped: external_exports.literal(true).optional(),
100677
+ /** Changes something (a refund, an email): an unrecorded call is never answered by invention unless set to simulate. */
100678
+ write: external_exports.boolean().optional(),
100679
+ /** Only computes from its arguments (a calculator): a call production never made runs the tool itself, for real. */
100680
+ pure: external_exports.literal(true).optional(),
100681
+ description: external_exports.string().optional(),
100682
+ schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
100683
+ });
100684
+ var TriggerSchema = external_exports.strictObject({
100685
+ task: external_exports.string().optional(),
100686
+ input: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
100687
+ });
100638
100688
  var CheckSchema = external_exports.union([
100639
100689
  external_exports.strictObject({ id: external_exports.string(), state: StateCheckSchema }),
100640
100690
  external_exports.strictObject({ id: external_exports.string(), trace: TraceCheckSchema }),
@@ -100656,6 +100706,8 @@ var SceneSchema = external_exports.strictObject({
100656
100706
  skip_idle: external_exports.boolean().optional(),
100657
100707
  timeout: duration6("Per-trial time budget, e.g. 5m").default("5m"),
100658
100708
  task: external_exports.string().optional(),
100709
+ trigger: TriggerSchema.optional(),
100710
+ tools: external_exports.record(external_exports.string().regex(TOOL_NAME_PATTERN, "a tool name as the model saw it"), SceneToolSchema).optional(),
100659
100711
  seed: external_exports.strictObject({ slack: SlackSeedSchema.optional(), github: GitHubSeedSchema.optional(), datadog: DatadogSeedSchema.optional(), pagerduty: PagerDutySeedSchema.optional(), "linkedin-ads": LinkedInAdsSeedSchema.optional(), salesforce: SalesforceSeedSchema.optional(), gong: GongSeedSchema.optional(), hubspot: HubSpotSeedSchema.optional(), ga4: GA4SeedSchema.optional(), "google-ads": GoogleAdsSeedSchema.optional(), "chatgpt-ads": ChatGPTAdsSeedSchema.optional(), "open-meteo": OpenMeteoSeedSchema.optional(), "google-drive": GoogleDriveSeedSchema.optional(), gmail: GmailSeedSchema.optional(), "amazon-s3": AmazonS3SeedSchema.optional(), linear: LinearSeedSchema.optional(), "okta": OktaSeedSchema.optional(), stripe: StripeSeedSchema.optional(), "clerk": ClerkSeedSchema.optional(), "better-stack": BetterStackSeedSchema.optional(), notion: NotionSeedSchema.optional(), attio: AttioSeedSchema.optional(), "dropbox": DropboxSeedSchema.optional(), resend: ResendSeedSchema.optional(), "microsoft-word": MicrosoftWordSeedSchema.optional(), shopify: ShopifySeedSchema.optional(), "lob": LobSeedSchema.optional(), paypal: PayPalSeedSchema.optional(), jira: JiraSeedSchema.optional(), "kalshi": KalshiSeedSchema.optional(), intercom: IntercomSeedSchema.optional(), "zendesk": ZendeskSeedSchema.optional(), "google-calendar": GoogleCalendarSeedSchema.optional(), "twilio": TwilioSeedSchema.optional(), "asana": AsanaSeedSchema.optional(), "discord": DiscordSeedSchema.optional(), sentry: SentrySeedSchema.optional(), "airtable": AirtableSeedSchema.optional() }),
100660
100712
  world_rules: external_exports.strictObject({ actors: external_exports.array(ActorSchema).optional(), app_calls: external_exports.array(AppCallSchema).optional(), pipelines: external_exports.array(PipelineRuleSchema).optional(), faults: external_exports.array(FaultRuleSchema).optional(), metrics: external_exports.array(MetricRuleSchema).optional(), logs: external_exports.array(LogRuleSchema).optional(), monitors: external_exports.array(MonitorRuleSchema).optional(), integrations: external_exports.array(IntegrationSchema).optional() }).optional(),
100661
100713
  people: PeopleSchema.optional(),
@@ -101788,6 +101840,37 @@ function twinIssues(scene2) {
101788
101840
  });
101789
101841
  return issues;
101790
101842
  }
101843
+ function toolIssues(scene2) {
101844
+ const issues = [];
101845
+ for (const [name5, tool] of Object.entries(scene2.tools ?? {})) {
101846
+ const path4 = `tools.${name5}`;
101847
+ if (tool.twin !== void 0) {
101848
+ if (!isTwinName(tool.twin)) issues.push({ path: `${path4}.twin`, message: `unsupported twin ${tool.twin}`, hint: `supported twins: ${SUPPORTED_TWINS.join(", ")}` });
101849
+ else if (!scene2.twins.includes(tool.twin)) issues.push({ path: `${path4}.twin`, message: `twin ${tool.twin} is not listed in twins`, hint: `add ${tool.twin} to twins, e.g. twins: [${tool.twin}]` });
101850
+ }
101851
+ if (tool.unrecorded === "twin" && tool.twin === void 0) issues.push({ path: `${path4}.unrecorded`, message: "unrecorded: twin needs the twin that answers", hint: `set ${path4}.twin, e.g. twin: slack` });
101852
+ if (tool.pure && tool.write) issues.push({ path: `${path4}.pure`, message: "a tool that changes something is not pure", hint: `remove ${path4}.pure, or ${path4}.write if it only computes from its arguments` });
101853
+ if (tool.observations !== void 0 && tool.recorded === void 0) {
101854
+ issues.push({ path: `${path4}.observations`, message: `${tool.observations} was not read`, hint: "load the scene from its file (ancha run, ancha scene validate), which reads the recorded calls next to it" });
101855
+ }
101856
+ tool.recorded?.forEach((o, i) => {
101857
+ if (o.tool !== name5) issues.push({ path: `${path4}.recorded[${i}].tool`, message: `a call to ${o.tool} recorded under ${name5}` });
101858
+ });
101859
+ }
101860
+ if (scene2.tools && Object.keys(scene2.tools).length) {
101861
+ scene2.checks.forEach((check3, i) => {
101862
+ if (!("trace" in check3)) return;
101863
+ for (const key3 of ["called", "not_called"]) {
101864
+ const patterns = check3.trace[key3] === void 0 ? [] : [].concat(check3.trace[key3]);
101865
+ patterns.forEach((pattern) => {
101866
+ const bare = /^([A-Za-z_][\w.-]{0,127})(?:\s+\{.*\})?$/s.exec(pattern.trim());
101867
+ if (bare && !scene2.tools[bare[1]]) issues.push({ path: `checks[${i}].trace.${key3}`, message: `${bare[1]} is not one of this scene's tools`, hint: `the tools are ${Object.keys(scene2.tools).join(", ")}; an API call is "<METHOD> <PATH>"` });
101868
+ });
101869
+ }
101870
+ });
101871
+ }
101872
+ return issues;
101873
+ }
101791
101874
  function refName5(ref20) {
101792
101875
  try {
101793
101876
  return parseRef(ref20).name;
@@ -102169,7 +102252,7 @@ function parseScene(input2) {
102169
102252
  throw shapeError(parsed3.error.issues.flatMap((issue5) => fromZodIssue(issue5, [], input2)));
102170
102253
  }
102171
102254
  const scene2 = parsed3.data;
102172
- const issues = [...twinIssues(scene2), ...validateRefs(scene2), ...ruleIssues(scene2), ...worldIssues(scene2), ...peopleIssues(scene2)];
102255
+ const issues = [...twinIssues(scene2), ...toolIssues(scene2), ...validateRefs(scene2), ...ruleIssues(scene2), ...worldIssues(scene2), ...peopleIssues(scene2)];
102173
102256
  if (issues.length > 0) throw sceneError(issues);
102174
102257
  const pd = scene2.seed.pagerduty;
102175
102258
  if (pd && pd.default_service === void 0 && pd.services.length === 1) pd.default_service = `$${pd.services[0].ref}`;
@@ -102179,6 +102262,7 @@ function parseScene(input2) {
102179
102262
  if (link5.from === "datadog" && link5.handle === void 0 && service) link5.handle = `pagerduty-${service.name}`;
102180
102263
  if (link5.from === "pagerduty" && link5.channel === void 0 && service?.slack_channel !== void 0) link5.channel = service.slack_channel;
102181
102264
  });
102265
+ if (scene2.task === void 0 && scene2.trigger?.task !== void 0) scene2.task = scene2.trigger.task;
102182
102266
  return { ...scene2, twins: scene2.twins.filter(isTwinName), pass: scene2.pass ?? scene2.checks.map((c) => c.id) };
102183
102267
  }
102184
102268
  var ChecksSchema = external_exports.array(CheckSchema);
@@ -102198,6 +102282,54 @@ function parseChecks(input2) {
102198
102282
  { hint: "run `ancha scene schema` for the check format" }
102199
102283
  );
102200
102284
  }
102285
+ var PROSE_KEYS = /* @__PURE__ */ new Set(["judge", "task", "text", "value", "about", "message"]);
102286
+ var FIX_SHOWN = 120;
102287
+ function cutProseIssues(doc, text21, lineCounter) {
102288
+ const issues = [];
102289
+ (0, import_yaml.visit)(doc, {
102290
+ Pair(_, pair, ancestors2) {
102291
+ const value4 = pair.value;
102292
+ if (!(0, import_yaml.isScalar)(pair.key) || !PROSE_KEYS.has(String(pair.key.value)) || !(0, import_yaml.isScalar)(value4)) return;
102293
+ if (value4.type !== "PLAIN" || typeof value4.value !== "string" || !value4.range) return;
102294
+ const comment8 = /^[ \t]+#([^\r\n]*)/.exec(text21.slice(value4.range[1]));
102295
+ if (comment8 === null) return;
102296
+ const key3 = String(pair.key.value);
102297
+ const { line: line2 } = lineCounter.linePos(value4.range[0]);
102298
+ const meant = `${value4.value} #${comment8[1].trimEnd()}`;
102299
+ const fix = `${key3}: ${JSON.stringify(meant)}`;
102300
+ issues.push({
102301
+ path: `${pathOf(ancestors2, pair)} (line ${line2})`,
102302
+ message: `the text stops at " #": YAML reads ${JSON.stringify(`#${comment8[1].trimEnd()}`)} as a comment and keeps only ${JSON.stringify(value4.value)}`,
102303
+ hint: fix.length <= FIX_SHOWN ? `quote the text: ${fix}` : `quote the text, e.g. ${key3}: "\u2026", or write it as a block under ${key3}: |`
102304
+ });
102305
+ }
102306
+ });
102307
+ return issues;
102308
+ }
102309
+ function pathOf(ancestors2, pair) {
102310
+ const segments2 = [];
102311
+ ancestors2.forEach((node5, i) => {
102312
+ if ((0, import_yaml.isPair)(node5) && (0, import_yaml.isScalar)(node5.key)) segments2.push(String(node5.key.value));
102313
+ else if ((0, import_yaml.isSeq)(node5)) segments2.push(node5.items.indexOf(ancestors2[i + 1] ?? pair));
102314
+ });
102315
+ return formatPath([...segments2, String(pair.key.value)]);
102316
+ }
102317
+ function parseSceneYaml(text21) {
102318
+ const lineCounter = new import_yaml.LineCounter();
102319
+ const doc = (0, import_yaml.parseDocument)(text21, { lineCounter, prettyErrors: false });
102320
+ if (doc.errors.length > 0) {
102321
+ const issues = doc.errors.map((e) => {
102322
+ const { line: line2, col } = lineCounter.linePos(e.pos[0]);
102323
+ return { path: `line ${line2}, column ${col}`, message: e.message };
102324
+ });
102325
+ const atError = doc.errors.findIndex((e) => text21[e.pos[0]] === "@");
102326
+ if (atError >= 0) issues[atError].hint = "scene refs use $, e.g. $alice \u2014 YAML reserves @";
102327
+ throw sceneError(issues, doc.errors[0]);
102328
+ }
102329
+ const cut = cutProseIssues(doc, text21, lineCounter);
102330
+ if (cut.length > 0) throw sceneError(cut);
102331
+ return doc.toJS();
102332
+ }
102201
102333
 
102202
102334
  // packages/core/src/harness-issues.ts
102203
102335
  function collectHarnessIssues(trace, checks) {
@@ -102988,8 +103120,8 @@ function slackMcpServer(info, request) {
102988
103120
  if (!service) throw new AnchaError("USAGE", "this sandbox does not include Slack");
102989
103121
  const client = createVendorClient(info, "slack", "/api/", request);
102990
103122
  const server = new McpServer({ name: SLACK_MCP_PROFILE, version: "1.0.0" }, { instructions: "Tools access one local mock Slack workspace. Reads and writes use the same native API as the browser. Follow pagination cursors. There is no user-token search, DM, file upload, or management/reset tool. Reset is controlled by the developer and does not reset your conversation memory." });
102991
- for (const [method2, description2, shape3] of definitions) {
102992
- server.registerTool("slack_" + method2.replaceAll(".", "_"), { description: description2, inputSchema: external_exports.strictObject(shape3), annotations: { readOnlyHint: !writes.has(method2), destructiveHint: method2 === "chat.delete", openWorldHint: false } }, async (args, context2) => {
103123
+ for (const [method2, description2, shape4] of definitions) {
103124
+ server.registerTool("slack_" + method2.replaceAll(".", "_"), { description: description2, inputSchema: external_exports.strictObject(shape4), annotations: { readOnlyHint: !writes.has(method2), destructiveHint: method2 === "chat.delete", openWorldHint: false } }, async (args, context2) => {
102993
103125
  return client.result("POST", method2, args, context2.mcpReq.signal);
102994
103126
  });
102995
103127
  }
@@ -103112,9 +103244,9 @@ function safePath(path4, allowRoot = false) {
103112
103244
  return allowRoot && path4 === "" || path4.length > 0 && !path4.includes("\\") && !path4.includes("\0") && path4.split("/").every((part) => part !== "" && part !== "." && part !== "..");
103113
103245
  }
103114
103246
  function registerGithubRepositoryTools(server, api3) {
103115
- const invoke2 = async (method2, path4, body6, signal, shape3) => {
103247
+ const invoke2 = async (method2, path4, body6, signal, shape4) => {
103116
103248
  const response5 = await api3.call(method2, path4, body6, signal);
103117
- return mcpJsonResult(response5.isError ? response5.value : shape3(response5.value), response5.isError);
103249
+ return mcpJsonResult(response5.isError ? response5.value : shape4(response5.value), response5.isError);
103118
103250
  };
103119
103251
  server.registerTool("list_commits", {
103120
103252
  description: "List commits in a branch with native pagination.",
@@ -103613,8 +103745,34 @@ function datadogMcpServer(info, request) {
103613
103745
  return server;
103614
103746
  }
103615
103747
 
103748
+ // backend/src/mcp/agent-tools.ts
103749
+ function traced(schema) {
103750
+ return { "~standard": { version: 1, vendor: "ancha", validate: (value4) => ({ value: value4 }), jsonSchema: { input: () => schema, output: () => schema } } };
103751
+ }
103752
+ function callToolResult(answer) {
103753
+ if (answer.wrap === "mcp" && answer.raw && typeof answer.raw === "object") return answer.raw;
103754
+ if (answer.error !== void 0) return mcpTextResult(answer.error, true);
103755
+ return typeof answer.result === "string" ? mcpTextResult(answer.result) : mcpJsonResult(answer.result ?? null);
103756
+ }
103757
+ function agentToolsMcpServer(info, request) {
103758
+ if (!info.services.tools) throw new AnchaError("USAGE", "this world has no tools from a trace");
103759
+ const client = createVendorClient(info, "tools", "", request);
103760
+ const server = new McpServer({ name: "ancha-tools", version: "1.0.0" }, { instructions: "The agent's own tools, answered as production answered them." });
103761
+ for (const tool of info.tools ?? []) {
103762
+ server.registerTool(
103763
+ tool.name,
103764
+ { ...tool.description && { description: tool.description }, inputSchema: traced(tool.schema ?? { type: "object" }) },
103765
+ async (args, context2) => {
103766
+ const { value: value4, isError } = await client.call("POST", `/tools/${encodeURIComponent(tool.name)}`, { args }, context2.mcpReq.signal);
103767
+ return isError && value4?.error && !("source" in value4) ? mcpJsonResult(value4, true) : callToolResult(value4);
103768
+ }
103769
+ );
103770
+ }
103771
+ return server;
103772
+ }
103773
+
103616
103774
  // backend/src/mcp/http.ts
103617
- var factories = { slack: slackMcpServer, github: githubMcpServer, pagerduty: pagerdutyMcpServer, datadog: datadogMcpServer };
103775
+ var factories = { slack: slackMcpServer, github: githubMcpServer, pagerduty: pagerdutyMcpServer, datadog: datadogMcpServer, tools: agentToolsMcpServer };
103618
103776
  var names = { slack: SLACK_MCP_TOOL_NAMES, github: GITHUB_MCP_TOOL_NAMES, pagerduty: PAGERDUTY_MCP_TOOL_NAMES, datadog: DATADOG_MCP_TOOL_NAMES };
103619
103777
  var mcpTwins = Object.fromEntries(Object.entries(factories).map(([tool, factory]) => [
103620
103778
  tool,
@@ -103633,7 +103791,7 @@ var mcpTwins = Object.fromEntries(Object.entries(factories).map(([tool, factory]
103633
103791
  onerror: () => {
103634
103792
  }
103635
103793
  });
103636
- const known2 = new Set(names[tool]);
103794
+ const known2 = new Set(tool === "tools" ? (info.tools ?? []).map((t) => t.name) : names[tool]);
103637
103795
  return {
103638
103796
  close: () => handler.close(),
103639
103797
  async fetch(input2) {
@@ -103968,6 +104126,7 @@ var TraceRecorder = class {
103968
104126
 
103969
104127
  // packages/server/src/twin.ts
103970
104128
  var GAP_HEADER = "x-ancha-gap";
104129
+ var SETUP_ISSUE_HEADER = "x-ancha-setup-issue";
103971
104130
  var INTERNAL_ERROR_HEADER = "x-ancha-internal-error";
103972
104131
  function gapMessage(c) {
103973
104132
  return `ancha: not implemented: ${c.req.method} ${new URL(c.req.url).pathname}`;
@@ -104830,8 +104989,8 @@ function markHandled(env, ids2) {
104830
104989
  var TABLE = "world_milestones";
104831
104990
  var isPredicateMilestone2 = (milestone) => !("called" in milestone) && !("message" in milestone);
104832
104991
  function milestoneKey(predicate) {
104833
- const canonical4 = (value4) => Array.isArray(value4) ? value4.map(canonical4) : value4 !== null && typeof value4 === "object" ? Object.fromEntries(Object.keys(value4).sort().map((key3) => [key3, canonical4(value4[key3])])) : value4;
104834
- return JSON.stringify(canonical4(predicate));
104992
+ const canonical5 = (value4) => Array.isArray(value4) ? value4.map(canonical5) : value4 !== null && typeof value4 === "object" ? Object.fromEntries(Object.keys(value4).sort().map((key3) => [key3, canonical5(value4[key3])])) : value4;
104993
+ return JSON.stringify(canonical5(predicate));
104835
104994
  }
104836
104995
  function tracked(env) {
104837
104996
  const out = /* @__PURE__ */ new Map();
@@ -105328,7 +105487,28 @@ function evaluateWithin(env, within, calls2) {
105328
105487
 
105329
105488
  // packages/server/src/checks.ts
105330
105489
  var LIST_LIMIT = 10;
105331
- var PATTERN_HINT = 'write "<METHOD> <PATH>" using the service-relative path, e.g. "POST /api/chat.postMessage"; * matches any run of characters, and a bare "*" matches every call';
105490
+ var PATTERN_HINT = `write "<METHOD> <PATH>" using the service-relative path, e.g. "POST /api/chat.postMessage"; * matches any run of characters, and a bare "*" matches every call; one of the agent's own tools is its name, with the arguments it must have if any, e.g. "refund_order {order_id: A-1001}"`;
105491
+ function contains(have, want) {
105492
+ if (want === null || typeof want !== "object") return String(have) === String(want);
105493
+ if (Array.isArray(want)) return Array.isArray(have) && want.every((w, i) => contains(have[i], w));
105494
+ if (have === null || typeof have !== "object" || Array.isArray(have)) return false;
105495
+ return Object.entries(want).every(([k, w]) => contains(have[k], w));
105496
+ }
105497
+ function toolPattern(pattern, tools) {
105498
+ const m = /^([A-Za-z_][\w.-]{0,127})(?:\s+(\{.*\}))?$/s.exec(pattern);
105499
+ if (!m || !tools?.has(m[1])) return void 0;
105500
+ let args;
105501
+ if (m[2] !== void 0) {
105502
+ try {
105503
+ args = parseSceneYaml(m[2]);
105504
+ } catch {
105505
+ args = void 0;
105506
+ }
105507
+ if (args === null || typeof args !== "object" || Array.isArray(args)) throw new AnchaError("USAGE", `invalid trace pattern "${pattern}": the arguments must be a YAML or JSON object, e.g. {order_id: A-1001}`, { hint: PATTERN_HINT });
105508
+ }
105509
+ const path4 = `/tools/${m[1]}`;
105510
+ return (e) => e.source === "agent" && e.service === "tools" && e.method === "POST" && e.path === path4 && (args === void 0 || contains(e.request?.args, args));
105511
+ }
105332
105512
  function glob(pattern, caseInsensitive) {
105333
105513
  const fold2 = (s) => caseInsensitive ? s.toLowerCase() : s;
105334
105514
  const pieces = fold2(pattern).split("*");
@@ -105349,9 +105529,11 @@ function glob(pattern, caseInsensitive) {
105349
105529
  return true;
105350
105530
  };
105351
105531
  }
105352
- function compileTracePattern(p2) {
105532
+ function compileTracePattern(p2, tools) {
105353
105533
  const pattern = p2.trim();
105354
105534
  if (pattern === "*") return (e) => e.source === "agent";
105535
+ const tool = toolPattern(pattern, tools);
105536
+ if (tool) return tool;
105355
105537
  const parts3 = /^(\S+)\s+(\S+)$/.exec(pattern);
105356
105538
  if (!parts3) {
105357
105539
  throw new AnchaError("USAGE", `invalid trace pattern "${p2}": expected "<METHOD> <PATH>" or "*"`, { hint: PATTERN_HINT });
@@ -105379,12 +105561,13 @@ function failure2(e) {
105379
105561
  if (typeof body6 !== "object" || body6 === null) return void 0;
105380
105562
  const r = body6;
105381
105563
  if (e.service === "slack" && r.ok === false) return `ok: false${typeof r.error === "string" ? `, ${r.error}` : ""}`;
105564
+ if (e.service === "tools" && typeof r.error === "string") return `the tool's error: ${r.error}`;
105382
105565
  if (/\/graphql$/.test(e.path) && Array.isArray(r.errors) && r.errors.length > 0 && (r.data === void 0 || r.data === null)) return "GraphQL errors";
105383
105566
  return void 0;
105384
105567
  }
105385
- function calledPart(patterns, calls2, anyStatus) {
105568
+ function calledPart(patterns, calls2, anyStatus, tools) {
105386
105569
  const hits = patterns.map((p2) => {
105387
- const attempts = calls2.filter(compileTracePattern(p2));
105570
+ const attempts = calls2.filter(compileTracePattern(p2, tools));
105388
105571
  return { p: p2, attempts, worked: anyStatus ? attempts : attempts.filter((e) => failure2(e) === void 0) };
105389
105572
  });
105390
105573
  const missing4 = hits.filter((h) => h.worked.length === 0);
@@ -105410,8 +105593,8 @@ function calledPart(patterns, calls2, anyStatus) {
105410
105593
  ].join(" ");
105411
105594
  return { passed: false, expected, actual, explanation, evidence: unique2([...matched, ...failed.flatMap((h) => h.attempts)]) };
105412
105595
  }
105413
- function notCalledPart(patterns, calls2) {
105414
- const matchers = patterns.map(compileTracePattern);
105596
+ function notCalledPart(patterns, calls2, tools) {
105597
+ const matchers = patterns.map((p2) => compileTracePattern(p2, tools));
105415
105598
  const offenders = calls2.filter((c) => matchers.some((m) => m(c)));
105416
105599
  const expected = `agent never calls ${patterns.join(" or ")}`;
105417
105600
  if (offenders.length === 0) {
@@ -105432,13 +105615,13 @@ function notCalledPart(patterns, calls2) {
105432
105615
  evidence: offenders
105433
105616
  };
105434
105617
  }
105435
- function evaluateTrace(trace, calls2) {
105618
+ function evaluateTrace(trace, calls2, tools) {
105436
105619
  const called = asList(trace.called);
105437
105620
  const notCalled = asList(trace.not_called);
105438
105621
  if (called.length === 0 && notCalled.length === 0) {
105439
105622
  throw new AnchaError("USAGE", "a trace check needs at least one pattern in called or not_called", { hint: 'e.g. { called: "POST /api/chat.postMessage" }' });
105440
105623
  }
105441
- const parts3 = [...called.length > 0 ? [calledPart(called, calls2, trace.status === "any")] : [], ...notCalled.length > 0 ? [notCalledPart(notCalled, calls2)] : []];
105624
+ const parts3 = [...called.length > 0 ? [calledPart(called, calls2, trace.status === "any", tools)] : [], ...notCalled.length > 0 ? [notCalledPart(notCalled, calls2, tools)] : []];
105442
105625
  return {
105443
105626
  passed: parts3.every((p2) => p2.passed),
105444
105627
  expected: parts3.map((p2) => p2.expected).join("; "),
@@ -105508,10 +105691,11 @@ function evaluateProcess(env, check3, calls2) {
105508
105691
  if ("decided" in check3) return inspectPeoplePredicate(env, { decided: check3.decided }, atMs);
105509
105692
  if ("message" in check3) return evaluateMessageCheck(env, check3.message);
105510
105693
  if ("never" in check3) return evaluateNever(env, check3.never);
105511
- const agent = { first: (pattern) => calls2().find(compileTracePattern(pattern)) };
105694
+ const agent = { first: (pattern) => calls2().find(compileTracePattern(pattern, sceneTools(env))) };
105512
105695
  if ("before" in check3) return evaluateBefore(env, check3.before, agent);
105513
105696
  return evaluateWithin(env, check3.within, agent);
105514
105697
  }
105698
+ var sceneTools = (env) => new Set(Object.keys(env.scene.tools ?? {}));
105515
105699
  function errored(label5, e) {
105516
105700
  const message5 = e instanceof Error ? e.message : String(e);
105517
105701
  const hint = e instanceof AnchaError ? e.hint : void 0;
@@ -105541,7 +105725,7 @@ function evaluateChecks(env, checks = env.scene.checks) {
105541
105725
  let outcome3;
105542
105726
  let error63;
105543
105727
  try {
105544
- outcome3 = "state" in check3 ? evaluateState(env, check3.state) : "trace" in check3 ? evaluateTrace(check3.trace, agentCalls2()) : evaluateProcess(env, check3, agentCalls2);
105728
+ outcome3 = "state" in check3 ? evaluateState(env, check3.state) : "trace" in check3 ? evaluateTrace(check3.trace, agentCalls2(), sceneTools(env)) : evaluateProcess(env, check3, agentCalls2);
105545
105729
  } catch (e) {
105546
105730
  error63 = e instanceof Error ? e.message : String(e);
105547
105731
  outcome3 = errored("state" in check3 ? Object.keys(check3.state).join(", ") || "state" : checkKind(check3), e);
@@ -108355,12 +108539,12 @@ function persistMessageLinks(ctx, row, links2 = []) {
108355
108539
  ctx.store.db.prepare("INSERT INTO slack_message_links VALUES (?, ?, ?, ?, ?)").run(row.channel_id, row.ts, link5.pointer, link5.service, link5.path);
108356
108540
  }
108357
108541
  }
108358
- function materializeMessageLinks(ctx, row, shape3) {
108542
+ function materializeMessageLinks(ctx, row, shape4) {
108359
108543
  if (!ctx.serviceUrls) return;
108360
108544
  for (const link5 of messageLinks(ctx, row)) {
108361
108545
  const root2 = ctx.serviceUrls[link5.service];
108362
108546
  if (!root2) throw new AnchaError("INTERNAL", `Missing local ${link5.service} service for Slack message link`);
108363
- replaceLink(shape3, link5, root2.replace(/\/$/, "") + link5.path);
108547
+ replaceLink(shape4, link5, root2.replace(/\/$/, "") + link5.path);
108364
108548
  }
108365
108549
  }
108366
108550
 
@@ -111171,13 +111355,13 @@ function batch(ctx, type, operation, raw3, url3) {
111171
111355
  return { status: 204 };
111172
111356
  });
111173
111357
  }
111174
- const traceIds = items.map((item2) => item2.objectWriteTraceId), traced2 = operation === "create" && traceIds.some((value4) => value4 !== void 0);
111175
- if (traced2 && (traceIds.some((value4) => typeof value4 !== "string" || !value4 || value4.length > 255) || new Set(traceIds).size !== items.length)) throw new HubError(400, "VALIDATION_ERROR", "Every batch create input requires a unique objectWriteTraceId when enabled.");
111358
+ const traceIds = items.map((item2) => item2.objectWriteTraceId), traced3 = operation === "create" && traceIds.some((value4) => value4 !== void 0);
111359
+ if (traced3 && (traceIds.some((value4) => typeof value4 !== "string" || !value4 || value4.length > 255) || new Set(traceIds).size !== items.length)) throw new HubError(400, "VALIDATION_ERROR", "Every batch create input requires a unique objectWriteTraceId when enabled.");
111176
111360
  const execute3 = (item2) => {
111177
111361
  bodyObject2(item2, operation === "create" ? ["properties", "associations", "objectWriteTraceId"] : ["id", "properties"]);
111178
111362
  return project3(ctx, type, operation === "create" ? createRecord(ctx, type, item2) : updateRecord(ctx, type, identifier(item2.id), { properties: item2.properties }));
111179
111363
  };
111180
- if (traced2) return withMutation(ctx, () => {
111364
+ if (traced3) return withMutation(ctx, () => {
111181
111365
  const results = [], errors2 = [];
111182
111366
  let gap5 = false;
111183
111367
  for (const item2 of items) {
@@ -114432,7 +114616,7 @@ function explainFailedChecks(env, results, checks = env.scene.checks) {
114432
114616
  if (!failed.length) return [];
114433
114617
  const messages = attemptMessages(env);
114434
114618
  const agentCalls2 = env.trace.list().filter((entry2) => entry2.source === "agent");
114435
- const calls2 = { first: (pattern) => agentCalls2.find(compileTracePattern(pattern)) };
114619
+ const calls2 = { first: (pattern) => agentCalls2.find(compileTracePattern(pattern, sceneTools(env))) };
114436
114620
  const start = env.clock.startTime.getTime();
114437
114621
  return failed.flatMap((result) => {
114438
114622
  const check3 = checks.find((candidate) => candidate.id === result.id);
@@ -114570,7 +114754,271 @@ function readWorldSnapshot(bytes2) {
114570
114754
  }
114571
114755
  }
114572
114756
 
114757
+ // packages/server/src/agent-tools/simulate.ts
114758
+ var SYSTEM = `You stand in for one tool of an AI agent's application, in a test made from a production trace. Production recorded some calls to this tool. Answer the new call exactly as the real tool would at this point: consistent with what production recorded, with the calls the agent already made in this test and their answers (calls_in_this_test, writes included), and with the records that mention this call's values (records_that_mention_these_values: what other tools answered about the same thing), in the same shape as production's results (the same top-level fields, with values of the same types). The call happens at time.now: a time the tool reports for this call (when a reading was taken, when something was posted) is time.now. When time has passed since production's last answer, answer as the tool would by then: what changes over time (a status, a measurement) moves on the way the recorded answers, the writes and the tool's calls in other production runs imply; those runs' times are already on this run's timeline. Invent nothing the tool would not know. If the real tool would fail on this call (an unknown id, invalid arguments), answer with its error instead. Reply with JSON: {"result_json": "<the result as a JSON string>"} or {"error": "<the error message>"}.`;
114759
+ var SCHEMA5 = { name: "tool_answer", schema: { type: "object", additionalProperties: false, properties: { result_json: { type: "string" }, error: { type: "string" } } } };
114760
+ function shape(value4) {
114761
+ if (Array.isArray(value4)) return `[${value4.length ? shape(value4[0]) : ""}]`;
114762
+ if (value4 === null || typeof value4 !== "object") return value4 === null ? "null" : typeof value4;
114763
+ return `{${Object.keys(value4).sort().map((k) => `${k}:${value4[k] === null ? "null" : Array.isArray(value4[k]) ? "list" : typeof value4[k]}`).join(",")}}`;
114764
+ }
114765
+ function sameShape(result, recorded2) {
114766
+ if (!recorded2.length) return true;
114767
+ const top = (v) => Array.isArray(v) ? "list" : v === null ? "null" : typeof v;
114768
+ if (!recorded2.some((r) => top(r) === top(result) || top(r) === "null")) return false;
114769
+ const objects = recorded2.filter((r) => r !== null && typeof r === "object" && !Array.isArray(r));
114770
+ if (!objects.length || result === null || typeof result !== "object" || Array.isArray(result)) return true;
114771
+ const got = result;
114772
+ const always = Object.keys(objects[0]).filter((k) => objects.every((o) => k in o));
114773
+ const types = /* @__PURE__ */ new Map();
114774
+ for (const o of objects) for (const [k, v] of Object.entries(o)) types.set(k, (types.get(k) ?? /* @__PURE__ */ new Set()).add(top(v)));
114775
+ return always.every((k) => k in got) && Object.entries(got).every(([k, v]) => types.has(k) && (v === null || types.get(k).has("null") || types.get(k).has(top(v))));
114776
+ }
114777
+ async function simulate(model, request, signal) {
114778
+ const recorded2 = (request.tool?.recorded ?? []).map((o) => ({ args: o.args, at: o.at, ...o.error !== void 0 ? { error: o.error } : { result: o.result } }));
114779
+ const results = recorded2.filter((o) => "result" in o).map((o) => o.result);
114780
+ const known2 = results.length ? results : (request.tool?.examples ?? []).filter((o) => o.error === void 0 && o.result !== void 0).map((o) => o.result);
114781
+ const text21 = known2.length > 0 && known2.every((r) => typeof r === "string");
114782
+ const user8 = JSON.stringify({
114783
+ tool: { name: request.name, ...request.tool?.description && { description: request.tool.description }, ...request.tool?.schema && { arguments: request.tool.schema }, ...request.tool?.write && { changes_something: true } },
114784
+ production_recorded: recorded2.slice(-20),
114785
+ ...request.tool?.examples?.length && { other_production_runs_of_this_agent: request.tool.examples.slice(-30) },
114786
+ ...known2.length && { result_shape: shape(known2[0]) },
114787
+ calls_in_this_test: request.calls.slice(-30),
114788
+ ...request.records?.length && { records_that_mention_these_values: request.records },
114789
+ call: { arguments: request.args, ...request.repeat && { production_made_this_exact_call: request.repeat.recorded, this_is_call_number: request.repeat.call } },
114790
+ // Time moves on as the agent waits: a status read later may say what a real one would say by then.
114791
+ ...request.time && { time: {
114792
+ ...request.time.start && { now: new Date(Date.parse(request.time.start) + request.time.now_ms).toISOString() },
114793
+ ...request.time.now_ms > request.time.last_recorded_ms && { seconds_since_productions_last_answer: Math.round((request.time.now_ms - request.time.last_recorded_ms) / 1e3) }
114794
+ } }
114795
+ });
114796
+ let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "", last = "";
114797
+ for (let attempt = 0; attempt < 2; attempt++) {
114798
+ const answer = await model.complete({ kind: "simulate", person: request.name, system: SYSTEM, user: feedback ? `${user8}
114799
+
114800
+ ${feedback}` : user8, schema: SCHEMA5, temperature: 0, maxTokens: 1200 }, signal);
114801
+ inputTokens += answer.inputTokens;
114802
+ outputTokens += answer.outputTokens;
114803
+ costUsd += answer.costUsd;
114804
+ model_ = answer.model;
114805
+ const out = answer.output;
114806
+ last = JSON.stringify(out ?? null).slice(0, 200);
114807
+ if (typeof out?.error === "string" && out.error && out.result_json === void 0) return { error: out.error, inputTokens, outputTokens, costUsd, model: model_ };
114808
+ let result;
114809
+ try {
114810
+ result = JSON.parse(String(out?.result_json));
114811
+ } catch {
114812
+ if (!text21 || typeof out?.result_json !== "string") {
114813
+ feedback = "Your result_json was not valid JSON. Answer again.";
114814
+ continue;
114815
+ }
114816
+ result = out.result_json;
114817
+ }
114818
+ if (text21 && typeof result !== "string" && typeof out?.result_json === "string") result = out.result_json;
114819
+ if (sameShape(result, known2)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
114820
+ feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(known2[0])}. Answer again in that shape.`;
114821
+ }
114822
+ throw new PeopleModelError(`the simulated answer to ${request.name} did not have the shape of production's results (the model's last answer: ${last})`);
114823
+ }
114824
+
114825
+ // packages/server/src/agent-tools/index.ts
114826
+ var AGENT_TOOLS = "tools";
114827
+ function canonical2(value4) {
114828
+ return JSON.stringify(value4 ?? {}, (_key, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : v);
114829
+ }
114830
+ var recordedOf = /* @__PURE__ */ new WeakMap();
114831
+ function recorded(ctx, tool) {
114832
+ const tools = ctx.scene.tools ?? {};
114833
+ let byTool = recordedOf.get(tools);
114834
+ if (!byTool) {
114835
+ byTool = new Map(Object.entries(tools).map(([name5, t]) => [name5, (t.recorded ?? []).map((o) => {
114836
+ const atMs = parseDuration(o.at);
114837
+ return { ...o, atMs, endMs: o.end ? parseDuration(o.end) : atMs, key: canonical2(o.args) };
114838
+ }).sort((a, b) => a.atMs - b.atMs)]));
114839
+ recordedOf.set(tools, byTool);
114840
+ }
114841
+ return byTool.get(tool) ?? [];
114842
+ }
114843
+ function migrate6(db2) {
114844
+ db2.exec(`CREATE TABLE agent_tool_calls (key TEXT PRIMARY KEY, n INTEGER NOT NULL);
114845
+ CREATE TABLE agent_tool_state (k TEXT PRIMARY KEY, v TEXT NOT NULL);`);
114846
+ }
114847
+ var getState = (ctx, k) => ctx.store.db.prepare("SELECT v FROM agent_tool_state WHERE k=?").get(k)?.v;
114848
+ var setState = (ctx, k, v) => ctx.store.db.prepare("INSERT INTO agent_tool_state (k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v=excluded.v").run(k, v);
114849
+ var SIMULATION_LIMIT = () => Number(process.env.ANCHA_SIMULATE_MAX ?? 30);
114850
+ var simulationOn = (ctx) => process.env.ANCHA_SIMULATE !== "0" && ctx.model !== void 0;
114851
+ var ID_LIKE = /^(?=.*[\d@])[A-Za-z0-9][\w.:@#/+-]{3,63}$/;
114852
+ var DATE = /^\d{4}-\d{2}-\d{2}/;
114853
+ function idValues(value4, out = /* @__PURE__ */ new Set()) {
114854
+ if (Array.isArray(value4)) for (const v of value4) idValues(v, out);
114855
+ else if (value4 && typeof value4 === "object") for (const v of Object.values(value4)) idValues(v, out);
114856
+ else if ((typeof value4 === "string" || typeof value4 === "number" && Number.isInteger(value4)) && ID_LIKE.test(String(value4)) && !DATE.test(String(value4))) out.add(String(value4));
114857
+ return out;
114858
+ }
114859
+ var RECORDS_SHOWN = 20;
114860
+ function recordsMentioning(ctx, name5, args) {
114861
+ const ids2 = [...idValues(args)].map((id12) => new RegExp(`(^|[^A-Za-z0-9])${id12.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}([^A-Za-z0-9]|$)`));
114862
+ if (!ids2.length) return [];
114863
+ const records2 = [];
114864
+ const add = (tool, o, here) => {
114865
+ const answer = o.error !== void 0 ? { error: o.error } : { result: o.result };
114866
+ const text21 = JSON.stringify([o.args, answer]);
114867
+ if (ids2.some((id12) => id12.test(text21))) records2.push({ tool, args: o.args ?? {}, ...answer, conversation: here ? "this one" : o.trace ?? "another" });
114868
+ };
114869
+ const others = Object.entries(ctx.scene.tools ?? {}).filter(([tool]) => tool !== name5);
114870
+ for (const [tool] of others) for (const o of recorded(ctx, tool)) add(tool, o, true);
114871
+ for (const [tool, t] of others) for (const o of [...t.examples ?? []].reverse()) add(tool, o, false);
114872
+ return records2.slice(0, RECORDS_SHOWN);
114873
+ }
114874
+ function keepUp(ctx) {
114875
+ const behind = withRead(ctx, () => Number(getState(ctx, "reached") ?? 0)) - ctx.clock.elapsedMs();
114876
+ if (behind > 0) ctx.clock.advance(behind);
114877
+ }
114878
+ function decide(ctx, name5, args) {
114879
+ const tool = ctx.scene.tools?.[name5];
114880
+ const key3 = canonical2(args), callKey = `${name5} ${key3}`;
114881
+ const same2 = recorded(ctx, name5).filter((o) => o.key === key3);
114882
+ const n = ctx.store.db.prepare("SELECT n FROM agent_tool_calls WHERE key=?").get(callKey)?.n ?? 0;
114883
+ ctx.store.db.prepare("INSERT INTO agent_tool_calls (key, n) VALUES (?, 1) ON CONFLICT(key) DO UPDATE SET n=n+1").run(callKey);
114884
+ const policy = tool?.unrecorded ?? (tool?.write ? "fail" : "simulate");
114885
+ const reached = Number(getState(ctx, "reached") ?? 0);
114886
+ const cached2 = getState(ctx, `sim:${callKey}`);
114887
+ if (cached2 !== void 0) {
114888
+ const hit = JSON.parse(cached2);
114889
+ if (tool?.write || hit.reached >= reached) return hit.answer;
114890
+ }
114891
+ if (n < same2.length) {
114892
+ let index = n;
114893
+ for (let i = same2.length - 1; i > index; i--) if (same2[i].atMs <= reached) {
114894
+ index = i;
114895
+ break;
114896
+ }
114897
+ const o = same2[index];
114898
+ setState(ctx, "reached", String(Math.max(reached, o.endMs)));
114899
+ return o.error !== void 0 ? { source: "replayed", error: o.error, ...o.raw !== void 0 && { raw: o.raw, wrap: o.wrap } } : { source: "replayed", result: o.result, ...o.raw !== void 0 && { raw: o.raw, wrap: o.wrap } };
114900
+ }
114901
+ if (!same2.length && !tool?.write) {
114902
+ const elsewhere = [...tool?.examples ?? []].reverse().find((o) => o.error === void 0 && o.result !== void 0 && canonical2(o.args) === key3);
114903
+ if (elsewhere) return { source: "replayed-elsewhere", result: elsewhere.result };
114904
+ }
114905
+ if (tool?.twin !== void 0 || policy === "twin") return { source: "twin", passthrough: true };
114906
+ if (tool?.pure) return { source: "ran", passthrough: true };
114907
+ const repeat = same2.length ? { recorded: same2.length, call: n + 1 } : void 0;
114908
+ const last = same2.at(-1) ?? recorded(ctx, name5).at(-1), took = last ? last.endMs - last.atMs : 0;
114909
+ if (policy === "simulate" && simulationOn(ctx)) {
114910
+ if (Number(getState(ctx, "simulated") ?? 0) >= SIMULATION_LIMIT()) return { source: "failed", error: `Ancha has no recorded answer for this call, and this test reached its limit of ${SIMULATION_LIMIT()} simulated answers` };
114911
+ const lastRecordedMs = Math.max(0, ...recorded(ctx, name5).map((o) => o.endMs));
114912
+ const records2 = recordsMentioning(ctx, name5, args);
114913
+ return { simulate: { name: name5, tool, args, ...repeat && { repeat }, ...records2.length && { records: records2 }, time: { now_ms: Math.max(reached, ctx.clock.elapsedMs()), last_recorded_ms: lastRecordedMs, start: ctx.scene.start_time } }, cacheKey: callKey, reached, took };
114914
+ }
114915
+ if (repeat && !tool?.write) {
114916
+ const o = same2.at(-1);
114917
+ return o.error !== void 0 ? { source: "replayed", error: o.error } : { source: "replayed", result: o.result, ...o.raw !== void 0 && { raw: o.raw, wrap: o.wrap } };
114918
+ }
114919
+ const why = repeat ? `production made this call ${repeat.recorded} ${repeat.recorded === 1 ? "time" : "times"}, and this is call ${repeat.call}` : tool === void 0 || !recorded(ctx, name5).length ? `production never called ${name5}` : `production called ${name5}, but never with these arguments`;
114920
+ const unsimulated = policy === "simulate" && !simulationOn(ctx) ? process.env.ANCHA_SIMULATE === "0" ? "; simulation is off (ANCHA_SIMULATE=0)" : "; there is no model to simulate one with (set OPENROUTER_API_KEY)" : "";
114921
+ return { source: "failed", error: `Ancha has no recorded answer for this call: ${why}${unsimulated}` };
114922
+ }
114923
+ function noteCall(ctx, name5, args, a) {
114924
+ if (a.passthrough) return;
114925
+ const calls2 = JSON.parse(getState(ctx, "calls") ?? "[]");
114926
+ calls2.push({ tool: name5, args, ...ctx.scene.tools?.[name5]?.write && { changes_something: true }, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
114927
+ setState(ctx, "calls", JSON.stringify(calls2.slice(-50)));
114928
+ }
114929
+ function toolsToWrap(ctx) {
114930
+ return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.pure && !t.allow_unwrapped).map(([name5]) => name5).sort();
114931
+ }
114932
+ function registration(ctx, names3) {
114933
+ const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
114934
+ const wrapped = [.../* @__PURE__ */ new Set([...before, ...names3])].sort();
114935
+ setState(ctx, "wrapped", JSON.stringify(wrapped));
114936
+ return { wrapped, missing: toolsToWrap(ctx).filter((name5) => !wrapped.includes(name5)) };
114937
+ }
114938
+ function unwrappedMessage(missing4, noneWrapped = false) {
114939
+ const [first] = missing4, it = missing4.length === 1 ? "it" : "them";
114940
+ return `${missing4.join(", ")} ${missing4.length === 1 ? "is" : "are"} in the trace but your agent does not wrap ${it}, so a test would call ${it} for real. Wrap ${it}, or set tools.${first}.unrecorded: fail and allow ${it} with --allow-unwrapped ${missing4.join(",")}.` + (noneWrapped ? " If the agent wraps its tools when it runs, wrap them where they are defined instead, so the test can check them before the agent starts." : "");
114941
+ }
114942
+ function authorized(c) {
114943
+ const token2 = JSON.parse(c.env.ctx.store.meta.get(`credentials:${AGENT_TOOLS}`) ?? "{}").token;
114944
+ return token2 !== void 0 && c.req.header("authorization") === `Bearer ${token2}`;
114945
+ }
114946
+ function agentToolsService() {
114947
+ const app2 = new Hono3();
114948
+ app2.use("*", async (c, next2) => authorized(c) ? next2() : c.json({ error: "send Authorization: Bearer $ANCHA_TOOLS_TOKEN" }, 401));
114949
+ app2.get("/tools", (c) => withRead(c.env.ctx, () => c.json({ tools: Object.entries(c.env.ctx.scene.tools ?? {}).map(([name5, t]) => ({
114950
+ name: name5,
114951
+ ...t.description && { description: t.description },
114952
+ ...t.schema && { schema: t.schema },
114953
+ recorded: t.recorded?.length ?? 0,
114954
+ ...t.twin && { twin: t.twin },
114955
+ ...t.write && { write: true }
114956
+ })), wrap: toolsToWrap(c.env.ctx) })));
114957
+ app2.post("/register", async (c) => {
114958
+ const body6 = await c.req.json().catch(() => ({}));
114959
+ const names3 = (Array.isArray(body6.tools) ? body6.tools : []).map((t) => typeof t === "string" ? t : t?.name).filter((n) => typeof n === "string");
114960
+ const { wrapped, missing: missing4 } = withMutation(c.env.ctx, () => registration(c.env.ctx, names3));
114961
+ if (body6.complete) withMutation(c.env.ctx, () => setState(c.env.ctx, "checked", "1"));
114962
+ if (body6.complete && missing4.length) return c.json({ error: unwrappedMessage(missing4, wrapped.length === 0), wrapped, missing: missing4, stop: true }, 409, { [SETUP_ISSUE_HEADER]: "1" });
114963
+ return c.json({ wrapped, missing: missing4 });
114964
+ });
114965
+ app2.post("/tools/:name", async (c) => {
114966
+ const name5 = c.req.param("name");
114967
+ const body6 = await c.req.json().catch(() => ({}));
114968
+ const stop = withMutation(c.env.ctx, () => {
114969
+ if (getState(c.env.ctx, "checked")) return void 0;
114970
+ setState(c.env.ctx, "checked", "1");
114971
+ const { wrapped, missing: missing4 } = registration(c.env.ctx, []);
114972
+ return missing4.length ? { error: unwrappedMessage(missing4, wrapped.length === 0), wrapped, missing: missing4, stop: true } : void 0;
114973
+ });
114974
+ if (stop) return c.json(stop, 409, { [SETUP_ISSUE_HEADER]: "1" });
114975
+ const ctx = c.env.ctx, args = body6.args ?? {};
114976
+ const decision2 = withMutation(ctx, () => decide(ctx, name5, args));
114977
+ if (!("simulate" in decision2)) {
114978
+ withMutation(ctx, () => noteCall(ctx, name5, args, decision2));
114979
+ keepUp(ctx);
114980
+ return c.json(decision2);
114981
+ }
114982
+ let answered;
114983
+ try {
114984
+ const calls2 = withRead(ctx, () => JSON.parse(getState(ctx, "calls") ?? "[]"));
114985
+ const sim = await simulate(ctx.model, { ...decision2.simulate, calls: calls2 }, c.req.raw.signal);
114986
+ answered = { source: "simulated", ...sim.error !== void 0 ? { error: sim.error } : { result: sim.result }, cost_usd: Math.round(sim.costUsd * 1e6) / 1e6 };
114987
+ } catch (error63) {
114988
+ answered = { source: "failed", error: `Ancha has no recorded answer for this call and could not simulate one: ${error63 instanceof Error ? error63.message : String(error63)}` };
114989
+ }
114990
+ const answer = withMutation(ctx, () => {
114991
+ if (answered.source === "simulated") {
114992
+ const now10 = Math.max(Number(getState(ctx, "reached") ?? 0), decision2.reached + decision2.took);
114993
+ setState(ctx, "reached", String(now10));
114994
+ setState(ctx, `sim:${decision2.cacheKey}`, JSON.stringify({ answer: { ...answered, cost_usd: void 0 }, reached: now10 }));
114995
+ setState(ctx, "simulated", String(Number(getState(ctx, "simulated") ?? 0) + 1));
114996
+ }
114997
+ noteCall(ctx, name5, args, answered);
114998
+ return answered;
114999
+ });
115000
+ keepUp(ctx);
115001
+ return answer.source === "failed" ? c.json(answer, 200, { [SETUP_ISSUE_HEADER]: "1" }) : c.json(answer);
115002
+ });
115003
+ app2.all("*", (c) => c.json({ error: `not a route of Ancha's tool service: ${c.req.method} ${new URL(c.req.url).pathname}` }, 404));
115004
+ return {
115005
+ // A built-in service, not a catalog twin: a scene gets it by having tools.
115006
+ name: AGENT_TOOLS,
115007
+ basePath: "",
115008
+ app: app2,
115009
+ migrate: migrate6,
115010
+ seed() {
115011
+ },
115012
+ credentials: (ctx) => ({ token: `ancha-tools-${ctx.secrets.hex(32)}` }),
115013
+ actions: {},
115014
+ checks: {},
115015
+ dumpState: (ctx) => ({ calls: ctx.store.db.prepare("SELECT key, n FROM agent_tool_calls ORDER BY key").all(), wrapped: JSON.parse(getState(ctx, "wrapped") ?? "[]") }),
115016
+ coverage: []
115017
+ };
115018
+ }
115019
+
114573
115020
  // packages/server/src/env.ts
115021
+ var agentTools = agentToolsService();
114574
115022
  var ENV_ID_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";
114575
115023
  function newEnvId() {
114576
115024
  let id12 = "";
@@ -114664,7 +115112,8 @@ var Environment = class _Environment {
114664
115112
  }
114665
115113
  return twin;
114666
115114
  });
114667
- this.mcpTokens = Object.freeze(Object.fromEntries((opts.mcpTools ?? []).filter((tool) => scene2.twins.some((name5) => name5 === tool)).map((tool) => [tool, randomBytes(32).toString("hex")])));
115115
+ if (Object.keys(scene2.tools ?? {}).length) this.twins.push(agentTools);
115116
+ this.mcpTokens = Object.freeze(Object.fromEntries((opts.mcpTools ?? []).filter((tool) => scene2.twins.some((name5) => name5 === tool) || tool === "tools" && Object.keys(scene2.tools ?? {}).length > 0).map((tool) => [tool, randomBytes(32).toString("hex")])));
114668
115117
  const realNow = opts.realNow ?? (() => Date.now());
114669
115118
  this.#realNow = realNow;
114670
115119
  let frozenRealNow = realNow();
@@ -114721,7 +115170,8 @@ var Environment = class _Environment {
114721
115170
  trace: this.trace,
114722
115171
  events: this.events,
114723
115172
  enqueueJob: (job) => this.scheduler.enqueue(job),
114724
- world: this.world
115173
+ world: this.world,
115174
+ ...this.peopleModel && { model: this.peopleModel }
114725
115175
  };
114726
115176
  this.#contexts.set(twin, ctx);
114727
115177
  }
@@ -115252,7 +115702,7 @@ var FILE_KEYS2 = ["version", "id", "owner", "sceneId", "createdAt", "expiresAt",
115252
115702
 
115253
115703
  // packages/server/src/twins/google-ads/db.ts
115254
115704
  var collections = { budgets: "campaignBudgets", campaigns: "campaigns", adGroups: "adGroups", ads: "adGroupAds", criteria: "adGroupCriteria" };
115255
- function migrate6(db2) {
115705
+ function migrate7(db2) {
115256
115706
  db2.exec("CREATE TABLE google_ads_records (kind TEXT NOT NULL, name TEXT NOT NULL, customer_id TEXT NOT NULL, json TEXT NOT NULL, PRIMARY KEY(kind,name)); CREATE INDEX google_ads_customer ON google_ads_records(kind,customer_id)");
115257
115707
  }
115258
115708
  function config3(ctx) {
@@ -116219,11 +116669,11 @@ function googleAdsTwin() {
116219
116669
  throw e;
116220
116670
  }
116221
116671
  });
116222
- return { name: "google-ads", basePath: "", unprefixedPaths: /^\/v\d+\/customers[/:]/, app: app2, migrate: migrate6, seed: seed4, credentials: credentials3, actions: {}, checks: {}, dumpState: dumpState2, coverage: googleAdsCoverage };
116672
+ return { name: "google-ads", basePath: "", unprefixedPaths: /^\/v\d+\/customers[/:]/, app: app2, migrate: migrate7, seed: seed4, credentials: credentials3, actions: {}, checks: {}, dumpState: dumpState2, coverage: googleAdsCoverage };
116223
116673
  }
116224
116674
 
116225
116675
  // packages/server/src/twins/chatgpt-ads/db.ts
116226
- function migrate7(db2) {
116676
+ function migrate8(db2) {
116227
116677
  db2.exec(`CREATE TABLE chatgpt_ads_data(id INTEGER PRIMARY KEY CHECK(id=1),json TEXT NOT NULL);
116228
116678
  CREATE TABLE chatgpt_ads_credentials(principal_id TEXT PRIMARY KEY,token TEXT NOT NULL UNIQUE);
116229
116679
  CREATE TABLE chatgpt_ads_idempotency(account_id TEXT NOT NULL,kind TEXT NOT NULL,key TEXT NOT NULL,fingerprint TEXT NOT NULL,resource_id TEXT NOT NULL,PRIMARY KEY(account_id,kind,key));
@@ -116438,9 +116888,9 @@ function pagination(rows7, query10, defaultLimit = 20, max = 500) {
116438
116888
  const selected2 = rows7.slice(start, Math.min(start + limit, end));
116439
116889
  return { object: "list", data: selected2, first_id: selected2[0]?.id ?? null, last_id: selected2.at(-1)?.id ?? null, has_more: before !== void 0 ? start > 0 : start + selected2.length < rows7.length };
116440
116890
  }
116441
- function canonical2(value4) {
116442
- if (Array.isArray(value4)) return `[${value4.map(canonical2).join(",")}]`;
116443
- if (value4 && typeof value4 === "object") return `{${Object.entries(value4).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical2(v)}`).join(",")}}`;
116891
+ function canonical3(value4) {
116892
+ if (Array.isArray(value4)) return `[${value4.map(canonical3).join(",")}]`;
116893
+ if (value4 && typeof value4 === "object") return `{${Object.entries(value4).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical3(v)}`).join(",")}}`;
116444
116894
  return JSON.stringify(value4);
116445
116895
  }
116446
116896
  function idempotency(c, access2, kind, body6) {
@@ -116448,7 +116898,7 @@ function idempotency(c, access2, kind, body6) {
116448
116898
  if (key3 === void 0) return { existing: void 0, remember: (_id) => {
116449
116899
  } };
116450
116900
  if (key3.length > 255 || !key3.trim()) invalid6("Idempotency-Key requires 1\u2013255 characters and non-whitespace");
116451
- const fingerprint = createHash13("sha256").update(canonical2(body6)).digest("hex");
116901
+ const fingerprint = createHash13("sha256").update(canonical3(body6)).digest("hex");
116452
116902
  const prior = c.env.ctx.store.db.prepare("SELECT fingerprint,resource_id FROM chatgpt_ads_idempotency WHERE account_id=? AND kind=? AND key=?").get(access2.account.id, kind, key3);
116453
116903
  if (prior && prior.fingerprint !== fingerprint) throw new AdsError2(409, "Idempotency-Key was used with different input", "idempotency_conflict");
116454
116904
  return { existing: prior ? find(access2, kind, prior.resource_id) : void 0, remember: (id12) => c.env.ctx.store.db.prepare("INSERT INTO chatgpt_ads_idempotency VALUES (?,?,?,?,?)").run(access2.account.id, kind, key3, fingerprint, id12) };
@@ -116732,11 +117182,11 @@ function chatGPTAdsTwin() {
116732
117182
  const app2 = new Hono3();
116733
117183
  for (const route11 of chatGPTAdsRoutes) app2.on(route11.method, route11.path, handle2(route11));
116734
117184
  app2.all("*", handle2({ method: "GET", path: "*", notes: "", run: (c) => unsupported5(`${c.req.method} ${new URL(c.req.url).pathname}`) }));
116735
- return { name: "chatgpt-ads", basePath: "", app: app2, migrate: migrate7, seed: seed5, credentials: credentials4, dumpState: dumpState3, actions: {}, checks: {}, coverage: chatGPTAdsCoverage };
117185
+ return { name: "chatgpt-ads", basePath: "", app: app2, migrate: migrate8, seed: seed5, credentials: credentials4, dumpState: dumpState3, actions: {}, checks: {}, coverage: chatGPTAdsCoverage };
116736
117186
  }
116737
117187
 
116738
117188
  // packages/server/src/twins/ga4/db.ts
116739
- function migrate8(db2) {
117189
+ function migrate9(db2) {
116740
117190
  db2.exec(`CREATE TABLE ga4_data (id INTEGER PRIMARY KEY CHECK(id=1),json TEXT NOT NULL);
116741
117191
  CREATE TABLE ga4_credentials (principal_id TEXT PRIMARY KEY,token TEXT NOT NULL UNIQUE);
116742
117192
  CREATE TABLE ga4_quota (property_id TEXT NOT NULL,kind TEXT NOT NULL,bucket INTEGER NOT NULL,count INTEGER NOT NULL,PRIMARY KEY(property_id,kind));`);
@@ -117207,7 +117657,7 @@ function ga4Twin() {
117207
117657
  property2(c, "0", true);
117208
117658
  return unsupported6(`${c.req.method} ${new URL(c.req.url).pathname}`);
117209
117659
  } }));
117210
- return { name: "ga4", basePath: "", unprefixedPaths: /^\/v1(?:alpha|beta)\/properties\//, app: app2, migrate: migrate8, seed: seed6, credentials: credentials5, dumpState: dumpState4, actions: {}, checks: {}, coverage: ga4Coverage };
117660
+ return { name: "ga4", basePath: "", unprefixedPaths: /^\/v1(?:alpha|beta)\/properties\//, app: app2, migrate: migrate9, seed: seed6, credentials: credentials5, dumpState: dumpState4, actions: {}, checks: {}, coverage: ga4Coverage };
117211
117661
  }
117212
117662
 
117213
117663
  // packages/server/src/twins/github/actions.ts
@@ -117356,7 +117806,7 @@ var actionRoutes = [
117356
117806
  ];
117357
117807
 
117358
117808
  // packages/server/src/twins/github/methods/checks.ts
117359
- function shape(ctx, repo4, row) {
117809
+ function shape2(ctx, repo4, row) {
117360
117810
  return { ...JSON.parse(row.json), id: row.id, node_id: Buffer.from(`CheckRun:${row.id}`).toString("base64"), head_sha: row.head_sha, name: row.name, status: row.status, conclusion: row.conclusion, started_at: row.status === "queued" ? null : row.created_at, completed_at: row.status === "completed" ? row.created_at : null, url: apiUrl(ctx, `${repoPath(repo4)}/check-runs/${row.id}`), html_url: `https://github.com/${repo4.full_name}/runs/${row.id}`, details_url: null, external_id: "", output: { title: null, summary: null, text: null, annotations_count: 0, annotations_url: apiUrl(ctx, `${repoPath(repo4)}/check-runs/${row.id}/annotations`) }, app: null, check_suite: null, pull_requests: [] };
117361
117811
  }
117362
117812
  var notes4 = "Read-only seeded check runs, repository-scoped exact SHA/branch/full refs and name/status filters. No check execution, writes, suites or annotations: app and check_suite are null, and the annotations link answers 501 as a recorded gap; partial native resource.";
@@ -117377,13 +117827,13 @@ var checkRoutes = [
117377
117827
  });
117378
117828
  }
117379
117829
  const { page: page15, perPage } = pageInfo(c);
117380
- return json2({ total_count: rows7.length, check_runs: pageSlice(rows7, page15, perPage).map((row) => shape(ctx, repo4, row)) }, 200, pageHeaders(c, rows7.length, page15, perPage));
117830
+ return json2({ total_count: rows7.length, check_runs: pageSlice(rows7, page15, perPage).map((row) => shape2(ctx, repo4, row)) }, 200, pageHeaders(c, rows7.length, page15, perPage));
117381
117831
  } },
117382
117832
  { method: "GET", path: "/repos/:owner/:repo/check-runs/:id", coverage: { status: "partial", notes: notes4 }, handler: (c) => {
117383
117833
  query2(c, []);
117384
117834
  const ctx = c.env.ctx, repo4 = repository(c), row = ctx.store.db.prepare("SELECT * FROM github_check_runs WHERE repo_id = ? AND id = ?").get(repo4.id, resourceParam(c, "id"));
117385
117835
  if (!row) throw new GitHubError(404, "Not Found");
117386
- return shape(ctx, repo4, row);
117836
+ return shape2(ctx, repo4, row);
117387
117837
  } }
117388
117838
  ];
117389
117839
 
@@ -118608,7 +119058,7 @@ function downtime(ctx, args) {
118608
119058
  }
118609
119059
 
118610
119060
  // packages/server/src/twins/datadog/db.ts
118611
- function migrate9(db2) {
119061
+ function migrate10(db2) {
118612
119062
  db2.exec(`
118613
119063
  CREATE TABLE datadog_monitors (
118614
119064
  id INTEGER PRIMARY KEY, ref TEXT NOT NULL UNIQUE, name TEXT NOT NULL, query TEXT NOT NULL,
@@ -118991,7 +119441,7 @@ function datadogTwin() {
118991
119441
  name: "datadog",
118992
119442
  basePath: "",
118993
119443
  app: app2,
118994
- migrate: migrate9,
119444
+ migrate: migrate10,
118995
119445
  seed: seed7,
118996
119446
  credentials: credentials6,
118997
119447
  dumpState: dumpState6,
@@ -120047,7 +120497,7 @@ function unsupported8(message5, code2 = "INVALID_FIELD") {
120047
120497
  }
120048
120498
  var versionRoot = "/services/data/v67.0";
120049
120499
  var prefixes = { Account: "001", Contact: "003", Lead: "00Q", Opportunity: "006", Campaign: "701", CampaignMember: "00v" };
120050
- function migrate10(db2) {
120500
+ function migrate11(db2) {
120051
120501
  db2.exec(`
120052
120502
  CREATE TABLE salesforce_records (type TEXT NOT NULL,id TEXT NOT NULL PRIMARY KEY,data TEXT NOT NULL);
120053
120503
  CREATE TABLE salesforce_history (ordinal INTEGER PRIMARY KEY AUTOINCREMENT,type TEXT NOT NULL,id TEXT NOT NULL,operation TEXT NOT NULL,at TEXT NOT NULL,before_json TEXT,after_json TEXT);
@@ -120570,11 +121020,11 @@ function salesforceTwin() {
120570
121020
  };
120571
121021
  for (const [method2, path4] of routePairs2) app2.on(method2, path4, handler);
120572
121022
  app2.all("*", handler);
120573
- return { name: "salesforce", basePath: "", app: app2, migrate: migrate10, seed: seed10, credentials: credentials9, actions: {}, checks: {}, dumpState: dumpState9, coverage: salesforceCoverage };
121023
+ return { name: "salesforce", basePath: "", app: app2, migrate: migrate11, seed: seed10, credentials: credentials9, actions: {}, checks: {}, dumpState: dumpState9, coverage: salesforceCoverage };
120574
121024
  }
120575
121025
 
120576
121026
  // packages/server/src/twins/linkedin-ads/db.ts
120577
- function migrate11(db2) {
121027
+ function migrate12(db2) {
120578
121028
  db2.exec("CREATE TABLE linkedin_ads_records (kind TEXT NOT NULL, id TEXT NOT NULL, account_id TEXT NOT NULL, json TEXT NOT NULL, created_at INTEGER NOT NULL, modified_at INTEGER NOT NULL, PRIMARY KEY(kind,id)); CREATE INDEX linkedin_ads_account ON linkedin_ads_records(kind,account_id)");
120579
121029
  }
120580
121030
  function get2(ctx, kind, id12) {
@@ -121086,11 +121536,11 @@ function linkedinAdsTwin() {
121086
121536
  const app2 = new Hono3();
121087
121537
  for (const route11 of linkedinAdsRoutes) app2.on(route11.method, route11.path, handle4(route11));
121088
121538
  app2.all("*", unknown2);
121089
- return { name: "linkedin-ads", basePath: "", app: app2, migrate: migrate11, seed: seed11, credentials: credentials10, actions: {}, checks: {}, dumpState: dumpState10, coverage: linkedinAdsCoverage };
121539
+ return { name: "linkedin-ads", basePath: "", app: app2, migrate: migrate12, seed: seed11, credentials: credentials10, actions: {}, checks: {}, dumpState: dumpState10, coverage: linkedinAdsCoverage };
121090
121540
  }
121091
121541
 
121092
121542
  // packages/server/src/twins/gong/db.ts
121093
- function migrate12(db2) {
121543
+ function migrate13(db2) {
121094
121544
  db2.exec(`CREATE TABLE gong_data (id INTEGER PRIMARY KEY CHECK(id=1), json TEXT NOT NULL);
121095
121545
  CREATE TABLE gong_credentials (principal_id TEXT PRIMARY KEY, access_key TEXT NOT NULL UNIQUE, access_secret TEXT NOT NULL);
121096
121546
  CREATE TABLE gong_quota (account_id TEXT NOT NULL, window TEXT NOT NULL, bucket INTEGER NOT NULL, count INTEGER NOT NULL, PRIMARY KEY(account_id,window));`);
@@ -121229,13 +121679,13 @@ function handle5(route11) {
121229
121679
  };
121230
121680
  }
121231
121681
  var unknown3 = handle5({ method: "GET", path: "*", scope: "", notes: "", run: (c) => unsupported9(`${c.req.method} ${new URL(c.req.url).pathname}`) });
121232
- function canonical3(value4) {
121233
- if (Array.isArray(value4)) return `[${value4.map(canonical3).join(",")}]`;
121234
- if (value4 && typeof value4 === "object") return `{${Object.entries(value4).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical3(v)}`).join(",")}}`;
121682
+ function canonical4(value4) {
121683
+ if (Array.isArray(value4)) return `[${value4.map(canonical4).join(",")}]`;
121684
+ if (value4 && typeof value4 === "object") return `{${Object.entries(value4).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical4(v)}`).join(",")}}`;
121235
121685
  return JSON.stringify(value4);
121236
121686
  }
121237
121687
  function pageRequest(ctx, principal, op, criteria, raw3) {
121238
- const hash4 = createHash15("sha256").update(canonical3(criteria)).digest("hex");
121688
+ const hash4 = createHash15("sha256").update(canonical4(criteria)).digest("hex");
121239
121689
  const base3 = { v: 1, env: ctx.envId, principal: principal.id, op, hash: hash4, page: 0, asOf: ctx.clock.elapsedMs() };
121240
121690
  const sign2 = (payload2) => createHmac2("sha256", ctx.store.meta.get("gong.cursor-secret")).update(payload2).digest("base64url");
121241
121691
  let cursor4 = base3;
@@ -121369,11 +121819,11 @@ function gongTwin() {
121369
121819
  const app2 = new Hono3();
121370
121820
  for (const route11 of gongRoutes) app2.on(route11.method, route11.path, handle5(route11));
121371
121821
  app2.all("*", unknown3);
121372
- return { name: "gong", basePath: "", app: app2, migrate: migrate12, seed: seed12, credentials: credentials11, dumpState: dumpState11, actions: {}, checks: {}, coverage: gongCoverage };
121822
+ return { name: "gong", basePath: "", app: app2, migrate: migrate13, seed: seed12, credentials: credentials11, dumpState: dumpState11, actions: {}, checks: {}, coverage: gongCoverage };
121373
121823
  }
121374
121824
 
121375
121825
  // packages/server/src/twins/open-meteo/db.ts
121376
- function migrate13(db2) {
121826
+ function migrate14(db2) {
121377
121827
  db2.exec("CREATE TABLE open_meteo_data (id INTEGER PRIMARY KEY CHECK(id=1), json TEXT NOT NULL);");
121378
121828
  }
121379
121829
  function seed13(ctx) {
@@ -121621,12 +122071,12 @@ function openMeteoTwin() {
121621
122071
  app2.get("/v1/forecast", handle6(forecast));
121622
122072
  app2.get("/v1/search", handle6(search4));
121623
122073
  app2.all("*", handle6(unknownRoute5));
121624
- return { name: "open-meteo", basePath: "", app: app2, migrate: migrate13, seed: seed13, credentials: credentials12, dumpState: dumpState12, actions: {}, checks: {}, coverage: openMeteoCoverage };
122074
+ return { name: "open-meteo", basePath: "", app: app2, migrate: migrate14, seed: seed13, credentials: credentials12, dumpState: dumpState12, actions: {}, checks: {}, coverage: openMeteoCoverage };
121625
122075
  }
121626
122076
 
121627
122077
  // packages/server/src/twins/google-drive/db.ts
121628
122078
  import { createHash as createHash16 } from "node:crypto";
121629
- var SCHEMA5 = `
122079
+ var SCHEMA6 = `
121630
122080
  CREATE TABLE gdrive_users (email TEXT PRIMARY KEY, name TEXT, permission_id TEXT NOT NULL UNIQUE, root_id TEXT NOT NULL UNIQUE);
121631
122081
  CREATE TABLE gdrive_files (
121632
122082
  id TEXT PRIMARY KEY, name TEXT NOT NULL, mime_type TEXT NOT NULL, owner TEXT NOT NULL, parent TEXT, description TEXT,
@@ -121652,8 +122102,8 @@ CREATE TABLE gdrive_revisions (file_id TEXT NOT NULL, id TEXT NOT NULL, mime_typ
121652
122102
  CREATE TABLE gdrive_changes (seq INTEGER PRIMARY KEY, file_id TEXT NOT NULL, owner TEXT NOT NULL, removed INTEGER NOT NULL, time_ms INTEGER NOT NULL);
121653
122103
  CREATE TABLE gdrive_notifications (seq INTEGER PRIMARY KEY, file_id TEXT NOT NULL, recipient TEXT NOT NULL, sender TEXT NOT NULL, role TEXT NOT NULL, message TEXT, time_ms INTEGER NOT NULL);
121654
122104
  `;
121655
- function migrate14(db2) {
121656
- db2.exec(SCHEMA5);
122105
+ function migrate15(db2) {
122106
+ db2.exec(SCHEMA6);
121657
122107
  }
121658
122108
  var RANK2 = { reader: 1, commenter: 2, writer: 3, owner: 4 };
121659
122109
  var isFolder = (file3) => file3.mime_type === GOOGLE_DRIVE_FOLDER;
@@ -122279,12 +122729,12 @@ function parseQuery(source, aliases) {
122279
122729
  return (file3) => file3.sharedWithMe;
122280
122730
  }
122281
122731
  const operator2 = expect();
122282
- const contains2 = operator2.kind === "word" && operator2.value.toLowerCase() === "contains";
122283
- if (!contains2 && operator2.kind !== "op") {
122732
+ const contains3 = operator2.kind === "word" && operator2.value.toLowerCase() === "contains";
122733
+ if (!contains3 && operator2.kind !== "op") {
122284
122734
  if (operator2.kind === "word" && operator2.value.toLowerCase() === "has") unsupported11(`${field3} has search`);
122285
122735
  throw invalid10("q");
122286
122736
  }
122287
- const op = contains2 ? "contains" : operator2.value;
122737
+ const op = contains3 ? "contains" : operator2.value;
122288
122738
  switch (field3) {
122289
122739
  case "name": {
122290
122740
  const value4 = literal2();
@@ -123503,7 +123953,7 @@ async function handle7(c) {
123503
123953
  function googleDriveTwin() {
123504
123954
  const app2 = new Hono3();
123505
123955
  app2.all("*", handle7);
123506
- return { name: "google-drive", basePath: "", unprefixedPaths: /^\/(?:upload\/)?drive\/v3\//, app: app2, migrate: migrate14, seed: seed14, credentials: credentials13, dumpState: dumpState13, actions: {}, checks: {}, coverage: googleDriveCoverage };
123956
+ return { name: "google-drive", basePath: "", unprefixedPaths: /^\/(?:upload\/)?drive\/v3\//, app: app2, migrate: migrate15, seed: seed14, credentials: credentials13, dumpState: dumpState13, actions: {}, checks: {}, coverage: googleDriveCoverage };
123507
123957
  }
123508
123958
 
123509
123959
  // packages/server/src/twins/gmail/checks.ts
@@ -123536,7 +123986,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
123536
123986
  import { STATUS_CODES } from "node:http";
123537
123987
  var MAX_PARTS2 = 100;
123538
123988
  var BODYLESS = /* @__PURE__ */ new Set(["GET", "HEAD", "DELETE"]);
123539
- function traced(text21) {
123989
+ function traced2(text21) {
123540
123990
  if (text21 === "") return void 0;
123541
123991
  try {
123542
123992
  return JSON.parse(text21);
@@ -123576,8 +124026,8 @@ function batchHandler(app2) {
123576
124026
  path: url3.pathname,
123577
124027
  ...url3.search.length > 1 && { query: url3.search.slice(1) },
123578
124028
  status: response5.status,
123579
- ...content2 !== "" && { request: traced(content2) },
123580
- ...text21 !== "" && { response: traced(text21) },
124029
+ ...content2 !== "" && { request: traced2(content2) },
124030
+ ...text21 !== "" && { response: traced2(text21) },
123581
124031
  gap: response5.status === 501,
123582
124032
  note: "batch part"
123583
124033
  });
@@ -124821,9 +125271,9 @@ function stringToSign(method2, path4, query10, headers, signature) {
124821
125271
  const canonicalQuery = query10.filter(([key3]) => !(signature.presigned && key3 === "X-Amz-Signature")).map(([key3, value4]) => [awsEncode(key3), awsEncode(value4)]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0).map(([key3, value4]) => `${key3}=${value4}`).join("&");
124822
125272
  const canonicalHeaders = signature.signedHeaders.map((name5) => `${name5}:${(headers.get(name5) ?? "").trim().replace(/\s+/g, " ")}
124823
125273
  `).join("");
124824
- const canonical4 = [method2, path4, canonicalQuery, canonicalHeaders, signature.signedHeaders.join(";"), signature.payloadHash].join("\n");
124825
- const toSign = ["AWS4-HMAC-SHA256", signature.amzDate, `${signature.date}/${signature.region}/s3/aws4_request`, sha256Hex(canonical4)].join("\n");
124826
- return { canonical: canonical4, toSign };
125274
+ const canonical5 = [method2, path4, canonicalQuery, canonicalHeaders, signature.signedHeaders.join(";"), signature.payloadHash].join("\n");
125275
+ const toSign = ["AWS4-HMAC-SHA256", signature.amzDate, `${signature.date}/${signature.region}/s3/aws4_request`, sha256Hex(canonical5)].join("\n");
125276
+ return { canonical: canonical5, toSign };
124827
125277
  }
124828
125278
  function verifySignature(secret, signature, toSign) {
124829
125279
  const key3 = hmac(hmac(hmac(hmac(`AWS4${secret}`, signature.date), signature.region), "s3"), "aws4_request");
@@ -124889,7 +125339,7 @@ var md5Hex = (data5) => createHash19("md5").update(data5).digest("hex");
124889
125339
  var sha2562 = sha256Hex;
124890
125340
 
124891
125341
  // packages/server/src/twins/amazon-s3/db.ts
124892
- var SCHEMA6 = `
125342
+ var SCHEMA7 = `
124893
125343
  CREATE TABLE s3_buckets (name TEXT PRIMARY KEY, region TEXT NOT NULL, created_ms INTEGER NOT NULL, access TEXT NOT NULL, tags TEXT);
124894
125344
  CREATE TABLE s3_objects (
124895
125345
  bucket TEXT NOT NULL, key TEXT NOT NULL, content BLOB NOT NULL, content_type TEXT NOT NULL, etag TEXT NOT NULL,
@@ -124904,8 +125354,8 @@ CREATE TABLE s3_uploads (
124904
125354
  CREATE TABLE s3_parts (upload_id TEXT NOT NULL, part_number INTEGER NOT NULL, content BLOB NOT NULL, etag TEXT NOT NULL, modified_ms INTEGER NOT NULL, PRIMARY KEY (upload_id, part_number));
124905
125355
  CREATE TABLE s3_taken_names (name TEXT PRIMARY KEY);
124906
125356
  `;
124907
- function migrate15(db2) {
124908
- db2.exec(SCHEMA6);
125357
+ function migrate16(db2) {
125358
+ db2.exec(SCHEMA7);
124909
125359
  }
124910
125360
  function account3(ctx) {
124911
125361
  return JSON.parse(ctx.store.meta.get("amazon-s3.account"));
@@ -125762,11 +126212,11 @@ async function handle8(c) {
125762
126212
  function amazonS3Twin() {
125763
126213
  const app2 = new Hono3();
125764
126214
  app2.all("*", handle8);
125765
- return { name: "amazon-s3", basePath: "", app: app2, migrate: migrate15, seed: seed16, credentials: credentials15, dumpState: dumpState15, actions: {}, checks: {}, coverage: amazonS3Coverage };
126215
+ return { name: "amazon-s3", basePath: "", app: app2, migrate: migrate16, seed: seed16, credentials: credentials15, dumpState: dumpState15, actions: {}, checks: {}, coverage: amazonS3Coverage };
125766
126216
  }
125767
126217
 
125768
126218
  // packages/server/src/twins/linear/db.ts
125769
- var SCHEMA7 = `
126219
+ var SCHEMA8 = `
125770
126220
  CREATE TABLE linear_org (id TEXT PRIMARY KEY, name TEXT NOT NULL, url_key TEXT NOT NULL, created_at TEXT NOT NULL);
125771
126221
  CREATE TABLE linear_users (id TEXT PRIMARY KEY, ref TEXT UNIQUE, name TEXT NOT NULL, display_name TEXT NOT NULL, email TEXT NOT NULL COLLATE NOCASE UNIQUE,
125772
126222
  admin INTEGER NOT NULL, guest INTEGER NOT NULL, active INTEGER NOT NULL, title TEXT, timezone TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
@@ -125790,8 +126240,8 @@ CREATE TABLE linear_issue_labels (issue_id TEXT NOT NULL, label_id TEXT NOT NULL
125790
126240
  CREATE TABLE linear_comments (id TEXT PRIMARY KEY, issue_id TEXT NOT NULL, user_id TEXT NOT NULL, body TEXT NOT NULL, parent_id TEXT,
125791
126241
  created_at TEXT NOT NULL, updated_at TEXT NOT NULL, edited_at TEXT, archived_at TEXT);
125792
126242
  `;
125793
- function migrate16(db2) {
125794
- db2.exec(SCHEMA7);
126243
+ function migrate17(db2) {
126244
+ db2.exec(SCHEMA8);
125795
126245
  }
125796
126246
  var one = (ctx, sql, ...args) => ctx.store.db.prepare(sql).get(...args);
125797
126247
  var all2 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).all(...args);
@@ -126953,7 +127403,7 @@ function linearTwin() {
126953
127403
  const app2 = new Hono3();
126954
127404
  app2.post("/graphql", handleGraphql);
126955
127405
  app2.all("*", unknownRoute7);
126956
- return { name: "linear", basePath: "/graphql", app: app2, migrate: migrate16, seed: seed17, credentials: credentials16, actions: {}, checks: {}, dumpState: dumpState16, coverage: linearCoverage };
127406
+ return { name: "linear", basePath: "/graphql", app: app2, migrate: migrate17, seed: seed17, credentials: credentials16, actions: {}, checks: {}, dumpState: dumpState16, coverage: linearCoverage };
126957
127407
  }
126958
127408
 
126959
127409
  // packages/server/src/twins/okta/index.ts
@@ -126961,7 +127411,7 @@ import { createHash as createHash25 } from "node:crypto";
126961
127411
 
126962
127412
  // packages/server/src/twins/okta/db.ts
126963
127413
  import { createHash as createHash23 } from "node:crypto";
126964
- var SCHEMA8 = `
127414
+ var SCHEMA9 = `
126965
127415
  CREATE TABLE okta_users (
126966
127416
  id TEXT PRIMARY KEY, login TEXT NOT NULL UNIQUE COLLATE NOCASE, status TEXT NOT NULL, created_ms INTEGER NOT NULL, activated_ms INTEGER,
126967
127417
  status_changed_ms INTEGER, last_login_ms INTEGER, last_updated_ms INTEGER NOT NULL, password_changed_ms INTEGER, has_password INTEGER NOT NULL DEFAULT 0,
@@ -126977,8 +127427,8 @@ CREATE TABLE okta_logs (
126977
127427
  outcome TEXT NOT NULL, reason TEXT, actor_id TEXT NOT NULL, targets TEXT NOT NULL
126978
127428
  );
126979
127429
  `;
126980
- function migrate17(db2) {
126981
- db2.exec(SCHEMA8);
127430
+ function migrate18(db2) {
127431
+ db2.exec(SCHEMA9);
126982
127432
  }
126983
127433
  var BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
126984
127434
  var hashed = (value4, length) => [...createHash23("sha256").update(value4).digest()].slice(0, length).map((byte) => BASE62[byte % 62]).join("");
@@ -128037,18 +128487,18 @@ async function handle9(c) {
128037
128487
  function oktaTwin() {
128038
128488
  const app2 = new Hono3();
128039
128489
  app2.all("*", handle9);
128040
- return { name: "okta", basePath: "", app: app2, migrate: migrate17, seed: seed18, credentials: credentials17, dumpState: dumpState17, actions: {}, checks: { user: user6 }, coverage: oktaCoverage };
128490
+ return { name: "okta", basePath: "", app: app2, migrate: migrate18, seed: seed18, credentials: credentials17, dumpState: dumpState17, actions: {}, checks: { user: user6 }, coverage: oktaCoverage };
128041
128491
  }
128042
128492
 
128043
128493
  // packages/server/src/twins/stripe/db.ts
128044
- var SCHEMA9 = `
128494
+ var SCHEMA10 = `
128045
128495
  CREATE TABLE stripe_objects (id TEXT PRIMARY KEY, type TEXT NOT NULL, seq INTEGER NOT NULL, created INTEGER NOT NULL, customer TEXT, json TEXT NOT NULL);
128046
128496
  CREATE INDEX stripe_objects_type ON stripe_objects (type, created, seq);
128047
128497
  CREATE TABLE stripe_keys (key TEXT PRIMARY KEY);
128048
128498
  CREATE TABLE stripe_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, status INTEGER NOT NULL, body TEXT NOT NULL);
128049
128499
  `;
128050
- function migrate18(db2) {
128051
- db2.exec(SCHEMA9);
128500
+ function migrate19(db2) {
128501
+ db2.exec(SCHEMA10);
128052
128502
  }
128053
128503
  function load(ctx, id12) {
128054
128504
  const row = ctx.store.db.prepare("SELECT json FROM stripe_objects WHERE id = ?").get(id12);
@@ -130113,7 +130563,7 @@ function stripeTwin() {
130113
130563
  const app2 = new Hono3();
130114
130564
  for (const route11 of [...stripeRoutes].sort((a, b) => Number(a.path.includes(":")) - Number(b.path.includes(":")))) app2.on(route11.method, route11.path, handle10(route11));
130115
130565
  app2.all("*", unknownRoute8);
130116
- return { name: "stripe", basePath: "", app: app2, migrate: migrate18, seed: seed19, credentials: credentials18, actions: {}, checks: {}, dumpState: dumpState18, coverage: stripeCoverage };
130566
+ return { name: "stripe", basePath: "", app: app2, migrate: migrate19, seed: seed19, credentials: credentials18, actions: {}, checks: {}, dumpState: dumpState18, coverage: stripeCoverage };
130117
130567
  }
130118
130568
 
130119
130569
  // packages/server/src/twins/clerk/index.ts
@@ -130121,7 +130571,7 @@ import { createHash as createHash29 } from "node:crypto";
130121
130571
 
130122
130572
  // packages/server/src/twins/clerk/db.ts
130123
130573
  import { createHash as createHash27 } from "node:crypto";
130124
- var SCHEMA10 = `
130574
+ var SCHEMA11 = `
130125
130575
  CREATE TABLE clerk_users (
130126
130576
  id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE COLLATE NOCASE, email_id TEXT NOT NULL, email_strategy TEXT NOT NULL DEFAULT 'email_code', first_name TEXT, last_name TEXT, username TEXT UNIQUE,
130127
130577
  external_id TEXT, password_enabled INTEGER NOT NULL, banned INTEGER NOT NULL DEFAULT 0, locked INTEGER NOT NULL DEFAULT 0,
@@ -130139,8 +130589,8 @@ CREATE TABLE clerk_invitations (
130139
130589
  );
130140
130590
  CREATE TABLE clerk_sessions (id TEXT PRIMARY KEY, client_id TEXT NOT NULL, user_id TEXT NOT NULL, status TEXT NOT NULL, last_active_ms INTEGER NOT NULL, org_id TEXT, expire_ms INTEGER NOT NULL, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL);
130141
130591
  `;
130142
- function migrate19(db2) {
130143
- db2.exec(SCHEMA10);
130592
+ function migrate20(db2) {
130593
+ db2.exec(SCHEMA11);
130144
130594
  }
130145
130595
  var BASE623 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
130146
130596
  var seededId2 = (prefix2, key3) => `${prefix2}_2${[...createHash27("sha256").update(`clerk:${prefix2}:${key3}`).digest()].slice(0, 26).map((byte) => BASE623[byte % 62]).join("")}`;
@@ -130543,10 +130993,10 @@ function filterUsers(call2, query10) {
130543
130993
  const found = getOrg(ctx, org5);
130544
130994
  return found ? membershipsOf(ctx, found.id).map((member4) => member4.user_id) : [];
130545
130995
  })) : void 0;
130546
- const contains2 = (value4, needle) => needle === null || (value4 ?? "").toLowerCase().includes(needle.toLowerCase());
130996
+ const contains3 = (value4, needle) => needle === null || (value4 ?? "").toLowerCase().includes(needle.toLowerCase());
130547
130997
  const q = query10.get("query"), banned = bool4(query10.get("banned") ?? void 0, "banned");
130548
130998
  const before = time7("last_active_at_before"), after = time7("last_active_at_after") ?? time7("last_active_at_since"), createdBefore = time7("created_at_before"), createdAfter = time7("created_at_after");
130549
- return ctx.store.db.prepare("SELECT * FROM clerk_users").all().filter((user8) => (!emails.length || emails.includes(user8.email.toLowerCase())) && (!ids2.length || ids2.includes(user8.id)) && (!usernames.length || usernames.includes(user8.username ?? "")) && (!externals.length || externals.includes(user8.external_id ?? "")) && (!members4 || members4.has(user8.id)) && (q === null || [user8.email, user8.first_name, user8.last_name, user8.username, user8.id, user8.external_id, `${user8.first_name ?? ""} ${user8.last_name ?? ""}`].some((value4) => contains2(value4, q))) && contains2(user8.email, query10.get("email_address_query")) && contains2(user8.username, query10.get("username_query")) && contains2(`${user8.first_name ?? ""} ${user8.last_name ?? ""}`, query10.get("name_query")) && (banned === void 0 || user8.banned === 1 === banned) && (before === void 0 || user8.last_active_ms !== null && user8.last_active_ms < before) && (after === void 0 || user8.last_active_ms !== null && user8.last_active_ms > after) && (createdBefore === void 0 || user8.created_ms < createdBefore) && (createdAfter === void 0 || user8.created_ms > createdAfter));
130999
+ return ctx.store.db.prepare("SELECT * FROM clerk_users").all().filter((user8) => (!emails.length || emails.includes(user8.email.toLowerCase())) && (!ids2.length || ids2.includes(user8.id)) && (!usernames.length || usernames.includes(user8.username ?? "")) && (!externals.length || externals.includes(user8.external_id ?? "")) && (!members4 || members4.has(user8.id)) && (q === null || [user8.email, user8.first_name, user8.last_name, user8.username, user8.id, user8.external_id, `${user8.first_name ?? ""} ${user8.last_name ?? ""}`].some((value4) => contains3(value4, q))) && contains3(user8.email, query10.get("email_address_query")) && contains3(user8.username, query10.get("username_query")) && contains3(`${user8.first_name ?? ""} ${user8.last_name ?? ""}`, query10.get("name_query")) && (banned === void 0 || user8.banned === 1 === banned) && (before === void 0 || user8.last_active_ms !== null && user8.last_active_ms < before) && (after === void 0 || user8.last_active_ms !== null && user8.last_active_ms > after) && (createdBefore === void 0 || user8.created_ms < createdBefore) && (createdAfter === void 0 || user8.created_ms > createdAfter));
130550
131000
  }
130551
131001
  var USER_ORDER = {
130552
131002
  created_at: (user8) => user8.created_ms,
@@ -131076,12 +131526,12 @@ async function handle11(c) {
131076
131526
  function clerkTwin() {
131077
131527
  const app2 = new Hono3();
131078
131528
  app2.all("*", handle11);
131079
- return { name: "clerk", basePath: "", app: app2, migrate: migrate19, seed: seed20, credentials: credentials19, dumpState: dumpState19, actions: {}, checks: {}, coverage: clerkCoverage };
131529
+ return { name: "clerk", basePath: "", app: app2, migrate: migrate20, seed: seed20, credentials: credentials19, dumpState: dumpState19, actions: {}, checks: {}, coverage: clerkCoverage };
131080
131530
  }
131081
131531
 
131082
131532
  // packages/server/src/twins/better-stack/db.ts
131083
131533
  import { createHash as createHash30 } from "node:crypto";
131084
- var SCHEMA11 = `
131534
+ var SCHEMA12 = `
131085
131535
  CREATE TABLE bs_users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, first_name TEXT NOT NULL, last_name TEXT NOT NULL, phone TEXT);
131086
131536
  CREATE TABLE bs_sources (
131087
131537
  id TEXT PRIMARY KEY, kind TEXT NOT NULL, name TEXT NOT NULL, url TEXT, monitor_type TEXT, check_frequency INTEGER, required_keyword TEXT, monitor_group TEXT,
@@ -131097,8 +131547,8 @@ CREATE TABLE bs_resources (id TEXT PRIMARY KEY, page_id TEXT NOT NULL, public_na
131097
131547
  CREATE TABLE bs_reports (id TEXT PRIMARY KEY, page_id TEXT NOT NULL, title TEXT NOT NULL, report_type TEXT NOT NULL, starts_ms INTEGER NOT NULL, ends_ms INTEGER, created_ms INTEGER NOT NULL);
131098
131548
  CREATE TABLE bs_updates (id TEXT PRIMARY KEY, report_id TEXT NOT NULL, message TEXT NOT NULL, published_ms INTEGER NOT NULL, affected TEXT NOT NULL);
131099
131549
  `;
131100
- function migrate20(db2) {
131101
- db2.exec(SCHEMA11);
131550
+ function migrate21(db2) {
131551
+ db2.exec(SCHEMA12);
131102
131552
  }
131103
131553
  var BASES = { user: 145001, monitor: 2245001, heartbeat: 441501, incident: 600001, calendar: 9001, page: 160001, resource: 8800001, report: 3300001, update: 7700001 };
131104
131554
  function nextId3(ctx, kind) {
@@ -131867,18 +132317,18 @@ async function handle12(c) {
131867
132317
  function betterStackTwin() {
131868
132318
  const app2 = new Hono3();
131869
132319
  app2.all("*", handle12);
131870
- return { name: "better-stack", basePath: "", app: app2, migrate: migrate20, seed: seed21, credentials: credentials20, dumpState: dumpState20, actions: {}, checks: {}, coverage: betterStackCoverage };
132320
+ return { name: "better-stack", basePath: "", app: app2, migrate: migrate21, seed: seed21, credentials: credentials20, dumpState: dumpState20, actions: {}, checks: {}, coverage: betterStackCoverage };
131871
132321
  }
131872
132322
 
131873
132323
  // packages/server/src/twins/notion/db.ts
131874
- var SCHEMA12 = `
132324
+ var SCHEMA13 = `
131875
132325
  CREATE TABLE notion_nodes (id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('user','page','block','database','data_source','comment')),
131876
132326
  parent_id TEXT, position REAL NOT NULL DEFAULT 0, json TEXT NOT NULL);
131877
132327
  CREATE INDEX notion_nodes_parent ON notion_nodes (parent_id, position);
131878
132328
  CREATE TABLE notion_tokens (token TEXT PRIMARY KEY, bot_id TEXT NOT NULL);
131879
132329
  `;
131880
- function migrate21(db2) {
131881
- db2.exec(SCHEMA12);
132330
+ function migrate22(db2) {
132331
+ db2.exec(SCHEMA13);
131882
132332
  }
131883
132333
  var node4 = (row) => row && { id: row.id, kind: row.kind, parent_id: row.parent_id, position: row.position, doc: JSON.parse(row.json) };
131884
132334
  function get3(ctx, id12) {
@@ -133085,11 +133535,11 @@ function notionTwin() {
133085
133535
  const app2 = new Hono3();
133086
133536
  for (const route11 of [...notionRoutes].sort((a, b) => Number(a.path.includes(":")) - Number(b.path.includes(":")))) app2.on(route11.method, route11.path, handle13(route11));
133087
133537
  app2.all("*", unknownRoute9);
133088
- return { name: "notion", basePath: "", app: app2, migrate: migrate21, seed: seed22, credentials: credentials21, actions: {}, checks: {}, dumpState: dumpState21, coverage: notionCoverage };
133538
+ return { name: "notion", basePath: "", app: app2, migrate: migrate22, seed: seed22, credentials: credentials21, actions: {}, checks: {}, dumpState: dumpState21, coverage: notionCoverage };
133089
133539
  }
133090
133540
 
133091
133541
  // packages/server/src/twins/attio/db.ts
133092
- var SCHEMA13 = `
133542
+ var SCHEMA14 = `
133093
133543
  CREATE TABLE attio_members (id TEXT PRIMARY KEY, ref TEXT, first_name TEXT NOT NULL, last_name TEXT NOT NULL, email TEXT NOT NULL, access_level TEXT NOT NULL, created_at TEXT NOT NULL);
133094
133544
  CREATE TABLE attio_tokens (token TEXT PRIMARY KEY, member_id TEXT NOT NULL);
133095
133545
  CREATE TABLE attio_objects (id TEXT PRIMARY KEY, api_slug TEXT NOT NULL UNIQUE, singular_noun TEXT NOT NULL, plural_noun TEXT NOT NULL, created_at TEXT NOT NULL);
@@ -133106,8 +133556,8 @@ CREATE INDEX attio_values_parent ON attio_values (parent_id, attribute_id, activ
133106
133556
  CREATE TABLE attio_notes (id TEXT PRIMARY KEY, parent_object TEXT NOT NULL, parent_record_id TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL, created_by TEXT NOT NULL, created_at TEXT NOT NULL);
133107
133557
  CREATE TABLE attio_tasks (id TEXT PRIMARY KEY, content TEXT NOT NULL, deadline_at TEXT, is_completed INTEGER NOT NULL, linked TEXT NOT NULL, assignees TEXT NOT NULL, created_by TEXT NOT NULL, created_at TEXT NOT NULL);
133108
133558
  `;
133109
- function migrate22(db2) {
133110
- db2.exec(SCHEMA13);
133559
+ function migrate23(db2) {
133560
+ db2.exec(SCHEMA14);
133111
133561
  }
133112
133562
  var one2 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).get(...args);
133113
133563
  var all5 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).all(...args);
@@ -133911,7 +134361,7 @@ var attioRoutes = [
133911
134361
  ];
133912
134362
 
133913
134363
  // packages/server/src/twins/attio/seed.ts
133914
- var SYSTEM = [
134364
+ var SYSTEM2 = [
133915
134365
  { api_slug: "record_id", title: "Record ID", type: "text", system: true, writable: false }
133916
134366
  ];
133917
134367
  var TAIL = [
@@ -133921,7 +134371,7 @@ var TAIL = [
133921
134371
  function standard(dealStages, categories) {
133922
134372
  return {
133923
134373
  people: { singular: "Person", plural: "People", attributes: [
133924
- ...SYSTEM,
134374
+ ...SYSTEM2,
133925
134375
  { api_slug: "name", title: "Name", type: "personal-name", system: true },
133926
134376
  { api_slug: "email_addresses", title: "Email addresses", type: "email-address", is_multiselect: true, is_unique: true, system: true },
133927
134377
  { api_slug: "phone_numbers", title: "Phone numbers", type: "phone-number", is_multiselect: true, system: true },
@@ -133931,7 +134381,7 @@ function standard(dealStages, categories) {
133931
134381
  ...TAIL
133932
134382
  ] },
133933
134383
  companies: { singular: "Company", plural: "Companies", attributes: [
133934
- ...SYSTEM,
134384
+ ...SYSTEM2,
133935
134385
  { api_slug: "name", title: "Name", type: "text", system: true },
133936
134386
  { api_slug: "domains", title: "Domains", type: "domain", is_multiselect: true, is_unique: true, system: true },
133937
134387
  { api_slug: "description", title: "Description", type: "text", system: true },
@@ -133940,7 +134390,7 @@ function standard(dealStages, categories) {
133940
134390
  ...TAIL
133941
134391
  ] },
133942
134392
  deals: { singular: "Deal", plural: "Deals", attributes: [
133943
- ...SYSTEM,
134393
+ ...SYSTEM2,
133944
134394
  { api_slug: "name", title: "Deal name", type: "text", is_required: true, system: true },
133945
134395
  { api_slug: "stage", title: "Deal stage", type: "status", is_required: true, options: dealStages, system: true },
133946
134396
  { api_slug: "owner", title: "Deal owner", type: "actor-reference", is_required: true, system: true },
@@ -134113,12 +134563,12 @@ function attioTwin() {
134113
134563
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
134114
134564
  for (const route11 of [...attioRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle14(route11));
134115
134565
  app2.all("*", unknownRoute10);
134116
- return { name: "attio", basePath: "", app: app2, migrate: migrate22, seed: seed23, credentials: credentials22, actions: {}, checks: {}, dumpState: dumpState22, coverage: attioCoverage };
134566
+ return { name: "attio", basePath: "", app: app2, migrate: migrate23, seed: seed23, credentials: credentials22, actions: {}, checks: {}, dumpState: dumpState22, coverage: attioCoverage };
134117
134567
  }
134118
134568
 
134119
134569
  // packages/server/src/twins/dropbox/db.ts
134120
134570
  import { createHash as createHash33 } from "node:crypto";
134121
- var SCHEMA14 = `
134571
+ var SCHEMA15 = `
134122
134572
  CREATE TABLE dbx_entries (
134123
134573
  path_lower TEXT PRIMARY KEY, path_display TEXT NOT NULL, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, rev TEXT, content BLOB,
134124
134574
  client_modified_ms INTEGER, server_modified_ms INTEGER, uploaded_by TEXT, shared_folder_id TEXT
@@ -134132,8 +134582,8 @@ CREATE TABLE dbx_changes (seq INTEGER PRIMARY KEY, path_lower TEXT NOT NULL);
134132
134582
  CREATE TABLE dbx_temp_links (token TEXT PRIMARY KEY, path_lower TEXT NOT NULL, rev TEXT NOT NULL, expires_ms INTEGER NOT NULL);
134133
134583
  CREATE TABLE dbx_people (email TEXT PRIMARY KEY, name TEXT NOT NULL, same_team INTEGER NOT NULL);
134134
134584
  `;
134135
- function migrate23(db2) {
134136
- db2.exec(SCHEMA14);
134585
+ function migrate24(db2) {
134586
+ db2.exec(SCHEMA15);
134137
134587
  }
134138
134588
  var account5 = (ctx) => JSON.parse(ctx.store.meta.get("dropbox.account"));
134139
134589
  var getEntry = (ctx, pathLower) => ctx.store.db.prepare("SELECT * FROM dbx_entries WHERE path_lower = ?").get(pathLower);
@@ -134913,7 +135363,7 @@ async function handle15(c) {
134913
135363
  function dropboxTwin() {
134914
135364
  const app2 = new Hono3();
134915
135365
  app2.all("*", handle15);
134916
- return { name: "dropbox", basePath: "", app: app2, migrate: migrate23, seed: seed24, credentials: credentials23, dumpState: dumpState23, actions: {}, checks: {}, coverage: dropboxCoverage };
135366
+ return { name: "dropbox", basePath: "", app: app2, migrate: migrate24, seed: seed24, credentials: credentials23, dumpState: dumpState23, actions: {}, checks: {}, coverage: dropboxCoverage };
134917
135367
  }
134918
135368
 
134919
135369
  // packages/server/src/twins/resend/request.ts
@@ -135010,7 +135460,7 @@ function unknownRoute11(c) {
135010
135460
  }
135011
135461
 
135012
135462
  // packages/server/src/twins/resend/routes.ts
135013
- function migrate24(db2) {
135463
+ function migrate25(db2) {
135014
135464
  db2.exec(`
135015
135465
  CREATE TABLE resend_objects (id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('email','domain','contact','segment','broadcast')), created_ms INTEGER NOT NULL, json TEXT NOT NULL);
135016
135466
  CREATE INDEX resend_objects_kind ON resend_objects (kind, created_ms);
@@ -135649,7 +136099,7 @@ function resendTwin() {
135649
136099
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
135650
136100
  for (const route11 of [...resendRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle16(route11));
135651
136101
  app2.all("*", unknownRoute11);
135652
- return { name: "resend", basePath: "", app: app2, migrate: migrate24, seed: seed25, credentials: credentials24, actions: {}, checks: {}, dumpState: dumpState24, coverage: resendCoverage };
136102
+ return { name: "resend", basePath: "", app: app2, migrate: migrate25, seed: seed25, credentials: credentials24, actions: {}, checks: {}, dumpState: dumpState24, coverage: resendCoverage };
135653
136103
  }
135654
136104
 
135655
136105
  // packages/server/src/twins/microsoft-word/db.ts
@@ -135814,7 +136264,7 @@ function quickXorHash(data5) {
135814
136264
  }
135815
136265
 
135816
136266
  // packages/server/src/twins/microsoft-word/db.ts
135817
- var SCHEMA15 = `
136267
+ var SCHEMA16 = `
135818
136268
  CREATE TABLE ms_users (email TEXT PRIMARY KEY, id TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, job_title TEXT);
135819
136269
  CREATE TABLE ms_items (
135820
136270
  id TEXT PRIMARY KEY, parent_id TEXT, name TEXT NOT NULL, name_lower TEXT NOT NULL, kind TEXT NOT NULL, mime_type TEXT, content BLOB, description TEXT,
@@ -135827,8 +136277,8 @@ CREATE TABLE ms_permissions (
135827
136277
  );
135828
136278
  CREATE TABLE ms_invitations (seq INTEGER PRIMARY KEY, item_id TEXT NOT NULL, email TEXT NOT NULL, roles TEXT NOT NULL, message TEXT, time_ms INTEGER NOT NULL);
135829
136279
  `;
135830
- function migrate25(db2) {
135831
- db2.exec(SCHEMA15);
136280
+ function migrate26(db2) {
136281
+ db2.exec(SCHEMA16);
135832
136282
  }
135833
136283
  var hex3 = (value4) => createHash36("sha256").update(value4).digest("hex");
135834
136284
  var guid3 = (key3) => {
@@ -135850,7 +136300,7 @@ var childrenOf2 = (ctx, id12) => ctx.store.db.prepare("SELECT * FROM ms_items WH
135850
136300
  var userOf = (ctx, email10) => ctx.store.db.prepare("SELECT * FROM ms_users WHERE email = ?").get(email10);
135851
136301
  var MIME = { docx: DOCX_TYPE, pdf: "application/pdf", txt: "text/plain", csv: "text/csv", xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation", md: "text/markdown", json: "application/json", png: "image/png" };
135852
136302
  var mimeFor = (name5) => MIME[/\.([A-Za-z0-9]+)$/.exec(name5)?.[1]?.toLowerCase() ?? ""] ?? "application/octet-stream";
135853
- function pathOf(ctx, item2) {
136303
+ function pathOf2(ctx, item2) {
135854
136304
  const parts3 = [];
135855
136305
  for (let node5 = item2; node5 && node5.kind !== "root"; node5 = node5.parent_id ? getItem(ctx, node5.parent_id) : void 0) parts3.unshift(node5.name);
135856
136306
  return parts3.length ? `/${parts3.join("/")}` : "";
@@ -135924,7 +136374,7 @@ function credentials25(ctx) {
135924
136374
  }
135925
136375
  function dumpState25(ctx) {
135926
136376
  const db2 = ctx.store.db, iso19 = (ms) => new Date(ms).toISOString();
135927
- const items = db2.prepare("SELECT * FROM ms_items WHERE kind != 'root'").all().map((item2) => ({ item: item2, path: pathOf(ctx, item2) })).sort((a, b) => a.path.toLowerCase() < b.path.toLowerCase() ? -1 : 1);
136377
+ const items = db2.prepare("SELECT * FROM ms_items WHERE kind != 'root'").all().map((item2) => ({ item: item2, path: pathOf2(ctx, item2) })).sort((a, b) => a.path.toLowerCase() < b.path.toLowerCase() ? -1 : 1);
135928
136378
  const paths2 = new Map(items.map((entry2) => [entry2.item.id, entry2.path]));
135929
136379
  return {
135930
136380
  ...config8(ctx),
@@ -136002,7 +136452,7 @@ function identity3(ctx, email10) {
136002
136452
  return { user: { email: email10, id: user8?.id ?? guid3(`user:${email10}`), displayName: user8?.display_name ?? email10 } };
136003
136453
  }
136004
136454
  function itemJson(ctx, item2) {
136005
- const { driveId, me: me4, tenant } = config8(ctx), path4 = pathOf(ctx, item2), web = `https://${tenant.domain.split(".")[0]}-my.sharepoint.com/personal/${slug7(me4)}/Documents`;
136455
+ const { driveId, me: me4, tenant } = config8(ctx), path4 = pathOf2(ctx, item2), web = `https://${tenant.domain.split(".")[0]}-my.sharepoint.com/personal/${slug7(me4)}/Documents`;
136006
136456
  const tag3 = guid3(`etag:${item2.id}`).toUpperCase(), parent2 = item2.parent_id ? getItem(ctx, item2.parent_id) : void 0;
136007
136457
  const size = item2.kind === "file" ? item2.content?.length ?? 0 : childrenSize(ctx, item2);
136008
136458
  const shared = sharedScope(ctx, item2);
@@ -136018,7 +136468,7 @@ function itemJson(ctx, item2) {
136018
136468
  size,
136019
136469
  createdBy: identity3(ctx, item2.created_by),
136020
136470
  lastModifiedBy: identity3(ctx, item2.modified_by),
136021
- parentReference: { driveType: "business", driveId, ...parent2 && { id: parent2.id, name: parent2.kind === "root" ? "Documents" : parent2.name, path: `/drive/root:${pathOf(ctx, parent2)}` } },
136471
+ parentReference: { driveType: "business", driveId, ...parent2 && { id: parent2.id, name: parent2.kind === "root" ? "Documents" : parent2.name, path: `/drive/root:${pathOf2(ctx, parent2)}` } },
136022
136472
  fileSystemInfo: { createdDateTime: iso7(item2.created_ms), lastModifiedDateTime: iso7(item2.modified_ms) },
136023
136473
  ...item2.description !== null && { description: item2.description },
136024
136474
  ...item2.kind === "file" ? { file: { mimeType: item2.mime_type, hashes: { quickXorHash: quickXorHash(item2.content ?? Buffer.alloc(0)) } } } : { folder: { childCount: childrenOf2(ctx, item2.id).length } },
@@ -136047,7 +136497,7 @@ function permissionJson(ctx, row, inheritedFrom) {
136047
136497
  roles: roles2,
136048
136498
  ...row.kind === "link" ? { link: { type: row.link_type, scope: row.link_scope, webUrl: `https://${config8(ctx).tenant.domain.split(".")[0]}-my.sharepoint.com/:${kindCode}:/g/personal/${slug7(config8(ctx).me)}/${row.id.slice(-22)}?e=${row.id.slice(-6)}`, preventsDownload: false }, hasPassword: row.has_password === 1 } : { grantedTo: identity3(ctx, row.email), grantedToV2: identity3(ctx, row.email), invitation: { email: row.email, signInRequired: true } },
136049
136499
  ...row.expires_ms !== null && { expirationDateTime: iso7(row.expires_ms) },
136050
- ...inheritedFrom && { inheritedFrom: { driveId: config8(ctx).driveId, id: inheritedFrom.id, path: `/drive/root:${pathOf(ctx, inheritedFrom)}` } }
136500
+ ...inheritedFrom && { inheritedFrom: { driveId: config8(ctx).driveId, id: inheritedFrom.id, path: `/drive/root:${pathOf2(ctx, inheritedFrom)}` } }
136051
136501
  };
136052
136502
  }
136053
136503
  var ITEM_PROPERTIES = /* @__PURE__ */ new Set(["@microsoft.graph.downloadUrl", "createdDateTime", "eTag", "id", "lastModifiedDateTime", "name", "webUrl", "cTag", "size", "createdBy", "lastModifiedBy", "parentReference", "fileSystemInfo", "description", "file", "folder", "root", "shared", "children", "image", "photo", "video", "audio", "package", "remoteItem", "searchResult", "specialFolder", "deleted", "malware", "publication", "sharepointIds", "listItem", "permissions", "thumbnails", "versions", "content", "webDavUrl"]);
@@ -136624,11 +137074,11 @@ async function handle17(c) {
136624
137074
  function microsoftWordTwin() {
136625
137075
  const app2 = new Hono3();
136626
137076
  app2.all("*", handle17);
136627
- return { name: "microsoft-word", basePath: "", app: app2, migrate: migrate25, seed: seed26, credentials: credentials25, dumpState: dumpState25, actions: {}, checks: {}, coverage: microsoftWordCoverage };
137077
+ return { name: "microsoft-word", basePath: "", app: app2, migrate: migrate26, seed: seed26, credentials: credentials25, dumpState: dumpState25, actions: {}, checks: {}, coverage: microsoftWordCoverage };
136628
137078
  }
136629
137079
 
136630
137080
  // packages/server/src/twins/shopify/db.ts
136631
- function migrate26(db2) {
137081
+ function migrate27(db2) {
136632
137082
  db2.exec(`
136633
137083
  CREATE TABLE shopify_objects (gid TEXT PRIMARY KEY, kind TEXT NOT NULL, num INTEGER NOT NULL, parent TEXT, json TEXT NOT NULL);
136634
137084
  CREATE INDEX shopify_objects_kind ON shopify_objects (kind, num);
@@ -136933,7 +137383,7 @@ function compare7(op, a, b) {
136933
137383
  }
136934
137384
  }
136935
137385
  var wordsOf = (text21) => text21.toLowerCase().split(/[^\p{L}\p{N}*]+/u).filter(Boolean);
136936
- function textMatch(values2, wanted, contains2, words4 = false) {
137386
+ function textMatch(values2, wanted, contains3, words4 = false) {
136937
137387
  const options3 = wanted.split(",").map((v) => v.trim().toLowerCase()).filter(Boolean);
136938
137388
  return values2.some((raw3) => {
136939
137389
  if (raw3 === null) return false;
@@ -136942,7 +137392,7 @@ function textMatch(values2, wanted, contains2, words4 = false) {
136942
137392
  const have = wordsOf(v);
136943
137393
  return options3.some((o) => wordsOf(o).every((w) => have.some((h) => w.endsWith("*") ? h.startsWith(w.slice(0, -1)) : h === w)));
136944
137394
  }
136945
- return options3.some((o) => o.endsWith("*") ? contains2 ? v.split(/[\s,/#@.-]+/).some((w) => w.startsWith(o.slice(0, -1))) || v.startsWith(o.slice(0, -1)) : v.startsWith(o.slice(0, -1)) : contains2 ? v.includes(o) : v === o);
137395
+ return options3.some((o) => o.endsWith("*") ? contains3 ? v.split(/[\s,/#@.-]+/).some((w) => w.startsWith(o.slice(0, -1))) || v.startsWith(o.slice(0, -1)) : v.startsWith(o.slice(0, -1)) : contains3 ? v.includes(o) : v === o);
136946
137396
  });
136947
137397
  }
136948
137398
  function search7(items, query10, documented, fields11, nowMs) {
@@ -137004,7 +137454,7 @@ function decode3(cursor4) {
137004
137454
  return null;
137005
137455
  }
137006
137456
  }
137007
- function connection2(items, args, key3, shape3) {
137457
+ function connection2(items, args, key3, shape4) {
137008
137458
  const { first, last, after, before } = args;
137009
137459
  if ((first === void 0 || first === null) && (last === void 0 || last === null)) throw new import_graphql3.GraphQLError("you must provide one of first or last", { extensions: { code: "BAD_REQUEST" } });
137010
137460
  for (const [name5, n] of [["first", first], ["last", last]]) {
@@ -137028,16 +137478,16 @@ function connection2(items, args, key3, shape3) {
137028
137478
  };
137029
137479
  return {
137030
137480
  get edges() {
137031
- return page15.map((item2) => ({ cursor: cursor4(item2), node: shape3(item2) }));
137481
+ return page15.map((item2) => ({ cursor: cursor4(item2), node: shape4(item2) }));
137032
137482
  },
137033
137483
  get nodes() {
137034
- return page15.map(shape3);
137484
+ return page15.map(shape4);
137035
137485
  },
137036
137486
  pageInfo: { hasNextPage: end < ordered2.length, hasPreviousPage: start > 0, startCursor: page15.length ? cursor4(page15[0]) : null, endCursor: page15.length ? cursor4(page15[page15.length - 1]) : null }
137037
137487
  };
137038
137488
  }
137039
137489
  var byNum = (d) => ({ id: numOf(d.gid) });
137040
- var pathOf2 = (path4) => path4 ? [...pathOf2(path4.prev), path4.key] : [];
137490
+ var pathOf3 = (path4) => path4 ? [...pathOf3(path4.prev), path4.key] : [];
137041
137491
  var firstOf = (items, n) => typeof n === "number" ? items.slice(0, Math.max(0, n)) : items;
137042
137492
  var currencyOf = (ctx) => all6(ctx, "Shop")[0].currency;
137043
137493
  var bag = (ctx, c) => {
@@ -137376,7 +137826,7 @@ function customerShape(req, c) {
137376
137826
  },
137377
137827
  defaultAddress: addressShape(c.address),
137378
137828
  addresses: ({ first }) => firstOf(c.address ? [addressShape(c.address)] : [], first),
137379
- orders: (args, _req, info) => ordersConnection(req, orders(), args, pathOf2(info.path))
137829
+ orders: (args, _req, info) => ordersConnection(req, orders(), args, pathOf3(info.path))
137380
137830
  };
137381
137831
  }
137382
137832
  function orderShape(req, o) {
@@ -137894,21 +138344,21 @@ var now6 = (req) => req.ctx.clock.nowMs();
137894
138344
  var field2 = (...parts3) => parts3.map(String);
137895
138345
  function queryRoot(req) {
137896
138346
  const ctx = req.ctx;
137897
- const one7 = (kind, shape3) => ({ id: id12 }) => {
138347
+ const one7 = (kind, shape4) => ({ id: id12 }) => {
137898
138348
  const d = loadKind(ctx, kind, checkId(id12));
137899
- return d ? shape3(req, d) : null;
138349
+ return d ? shape4(req, d) : null;
137900
138350
  };
137901
138351
  return {
137902
138352
  shop: () => shopShape(req),
137903
- orders: (args, _r, info) => ordersConnection(req, all6(ctx, "Order"), args, pathOf2(info.path)),
138353
+ orders: (args, _r, info) => ordersConnection(req, all6(ctx, "Order"), args, pathOf3(info.path)),
137904
138354
  order: one7("Order", orderShape),
137905
- products: (args, _r, info) => productsConnection(req, args, pathOf2(info.path)),
138355
+ products: (args, _r, info) => productsConnection(req, args, pathOf3(info.path)),
137906
138356
  product: one7("Product", productShape),
137907
- productVariants: (args, _r, info) => variantsConnection(req, args, pathOf2(info.path)),
138357
+ productVariants: (args, _r, info) => variantsConnection(req, args, pathOf3(info.path)),
137908
138358
  productVariant: one7("ProductVariant", variantShape),
137909
- customers: (args, _r, info) => customersConnection(req, args, pathOf2(info.path)),
138359
+ customers: (args, _r, info) => customersConnection(req, args, pathOf3(info.path)),
137910
138360
  customer: one7("Customer", customerShape),
137911
- locations: (args, _r, info) => locationsConnection(req, args, pathOf2(info.path)),
138361
+ locations: (args, _r, info) => locationsConnection(req, args, pathOf3(info.path)),
137912
138362
  // Without an id, Shopify returns the primary location.
137913
138363
  location: ({ id: id12 }) => {
137914
138364
  const d = id12 === void 0 || id12 === null ? all6(ctx, "Location")[0] : loadKind(ctx, "Location", checkId(id12));
@@ -137938,12 +138388,12 @@ function idempotency2(req, info, args) {
137938
138388
  return { key: key3, fingerprint: `${name5}
137939
138389
  ${JSON.stringify(args)}` };
137940
138390
  }
137941
- function once(req, info, args, run3, shape3, mismatch) {
138391
+ function once(req, info, args, run3, shape4, mismatch) {
137942
138392
  const idem = idempotency2(req, info, args);
137943
138393
  if (!idem) return run3().payload;
137944
138394
  const db2 = req.ctx.store.db;
137945
138395
  const seen = db2.prepare("SELECT fingerprint, response FROM shopify_idempotency WHERE key = ?").get(idem.key);
137946
- if (seen) return seen.fingerprint === idem.fingerprint && seen.response ? shape3(seen.response) : mismatch();
138396
+ if (seen) return seen.fingerprint === idem.fingerprint && seen.response ? shape4(seen.response) : mismatch();
137947
138397
  const result = run3();
137948
138398
  if (result.made) db2.prepare("INSERT INTO shopify_idempotency (key, fingerprint, response) VALUES (?, ?, ?)").run(idem.key, idem.fingerprint, result.made);
137949
138399
  return result.payload;
@@ -138300,14 +138750,14 @@ function inventoryAdjust(req, input2) {
138300
138750
  changes.push({ item: item2.gid, location: location.gid, delta: c.delta, before: current, ledger: c.ledgerDocumentUri ?? null, on_hand: quantities(ctx, l).on_hand });
138301
138751
  });
138302
138752
  if (errors2.length) return fail6(errors2);
138303
- const at2 = now6(req), recorded = [];
138753
+ const at2 = now6(req), recorded2 = [];
138304
138754
  for (const c of changes) {
138305
138755
  const column = input2.name;
138306
138756
  ctx.store.db.prepare(`UPDATE shopify_inventory SET ${column} = ${column} + ?, updated_ms = ? WHERE item = ? AND location = ?`).run(c.delta, at2, c.item, c.location);
138307
- recorded.push({ name: input2.name, delta: c.delta, after: c.before + c.delta, item: c.item, location: c.location, ledger: c.ledger });
138308
- if (input2.name !== "incoming") recorded.push({ name: "on_hand", delta: c.delta, after: c.on_hand + c.delta, item: c.item, location: c.location, ledger: null });
138757
+ recorded2.push({ name: input2.name, delta: c.delta, after: c.before + c.delta, item: c.item, location: c.location, ledger: c.ledger });
138758
+ if (input2.name !== "incoming") recorded2.push({ name: "on_hand", delta: c.delta, after: c.on_hand + c.delta, item: c.item, location: c.location, ledger: null });
138309
138759
  }
138310
- const group5 = save8(ctx, "InventoryAdjustmentGroup", { gid: gid("InventoryAdjustmentGroup", nextNum(ctx, "InventoryAdjustmentGroup")), reason: input2.reason, reference: input2.referenceDocumentUri ?? null, created_ms: at2, changes: recorded });
138760
+ const group5 = save8(ctx, "InventoryAdjustmentGroup", { gid: gid("InventoryAdjustmentGroup", nextNum(ctx, "InventoryAdjustmentGroup")), reason: input2.reason, reference: input2.referenceDocumentUri ?? null, created_ms: at2, changes: recorded2 });
138311
138761
  return { made: group5.gid, payload: { inventoryAdjustmentGroup: adjustmentGroupShape(req, group5), userErrors: [] } };
138312
138762
  }
138313
138763
  function inventorySet(req, input2) {
@@ -138332,13 +138782,13 @@ function inventorySet(req, input2) {
138332
138782
  sets.push({ item: item2.gid, location: location.gid, delta: q.quantity - current, available: have.available, on_hand: have.on_hand });
138333
138783
  });
138334
138784
  if (errors2.length) return fail6(errors2);
138335
- const at2 = now6(req), recorded = [];
138785
+ const at2 = now6(req), recorded2 = [];
138336
138786
  for (const s of sets) {
138337
138787
  setAvailable(ctx, s.item, s.location, s.available + s.delta, at2);
138338
- recorded.push({ name: input2.name, delta: s.delta, after: (input2.name === "available" ? s.available : s.on_hand) + s.delta, item: s.item, location: s.location, ledger: null });
138339
- recorded.push({ name: input2.name === "available" ? "on_hand" : "available", delta: s.delta, after: (input2.name === "available" ? s.on_hand : s.available) + s.delta, item: s.item, location: s.location, ledger: null });
138788
+ recorded2.push({ name: input2.name, delta: s.delta, after: (input2.name === "available" ? s.available : s.on_hand) + s.delta, item: s.item, location: s.location, ledger: null });
138789
+ recorded2.push({ name: input2.name === "available" ? "on_hand" : "available", delta: s.delta, after: (input2.name === "available" ? s.on_hand : s.available) + s.delta, item: s.item, location: s.location, ledger: null });
138340
138790
  }
138341
- const group5 = save8(ctx, "InventoryAdjustmentGroup", { gid: gid("InventoryAdjustmentGroup", nextNum(ctx, "InventoryAdjustmentGroup")), reason: input2.reason, reference: input2.referenceDocumentUri ?? null, created_ms: at2, changes: recorded });
138791
+ const group5 = save8(ctx, "InventoryAdjustmentGroup", { gid: gid("InventoryAdjustmentGroup", nextNum(ctx, "InventoryAdjustmentGroup")), reason: input2.reason, reference: input2.referenceDocumentUri ?? null, created_ms: at2, changes: recorded2 });
138342
138792
  return { made: group5.gid, payload: { inventoryAdjustmentGroup: adjustmentGroupShape(req, group5), userErrors: [] } };
138343
138793
  }
138344
138794
  function customerWrite(req, input2, create2) {
@@ -138930,7 +139380,7 @@ function shopifyTwin() {
138930
139380
  const app2 = new Hono3();
138931
139381
  app2.post("/admin/api/:version/graphql.json", handleGraphql2);
138932
139382
  app2.all("*", unknownRoute12);
138933
- return { name: "shopify", basePath: "", app: app2, migrate: migrate26, seed: seed27, credentials: credentials26, actions: {}, checks: {}, dumpState: dumpState26, coverage: shopifyCoverage };
139383
+ return { name: "shopify", basePath: "", app: app2, migrate: migrate27, seed: seed27, credentials: credentials26, actions: {}, checks: {}, dumpState: dumpState26, coverage: shopifyCoverage };
138934
139384
  }
138935
139385
 
138936
139386
  // packages/server/src/twins/lob/db.ts
@@ -139236,7 +139686,7 @@ function assetUrl(ctx, kind, id12) {
139236
139686
  }
139237
139687
 
139238
139688
  // packages/server/src/twins/lob/db.ts
139239
- var SCHEMA16 = `
139689
+ var SCHEMA17 = `
139240
139690
  CREATE TABLE lob_directory (id INTEGER PRIMARY KEY, primary_line TEXT NOT NULL, unit TEXT NOT NULL, city TEXT NOT NULL, state TEXT NOT NULL, zip5 TEXT NOT NULL, zip4 TEXT NOT NULL, vacant INTEGER NOT NULL, type TEXT NOT NULL, county TEXT NOT NULL);
139241
139691
  CREATE INDEX lob_directory_street ON lob_directory (primary_line, zip5);
139242
139692
  CREATE TABLE lob_addresses (
@@ -139257,8 +139707,8 @@ CREATE TABLE lob_mail (
139257
139707
  CREATE TABLE lob_files (id TEXT PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, bytes BLOB NOT NULL);
139258
139708
  CREATE TABLE lob_idempotency (kind TEXT NOT NULL, key TEXT NOT NULL, id TEXT NOT NULL, created_ms INTEGER NOT NULL, PRIMARY KEY (kind, key));
139259
139709
  `;
139260
- function migrate27(db2) {
139261
- db2.exec(SCHEMA16);
139710
+ function migrate28(db2) {
139711
+ db2.exec(SCHEMA17);
139262
139712
  }
139263
139713
  var LENGTH = { adr: 16, ltr: 16, psc: 16, chk: 16, bank: 15, tmpl: 15, vrsn: 15, file: 16 };
139264
139714
  var seededId4 = (prefix2, key3) => `${prefix2}_${createHash40("sha256").update(`lob:${prefix2}:${key3}`).digest("hex").slice(0, LENGTH[prefix2])}`;
@@ -140347,11 +140797,11 @@ async function handle18(c) {
140347
140797
  function lobTwin() {
140348
140798
  const app2 = new Hono3();
140349
140799
  app2.all("*", handle18);
140350
- return { name: "lob", basePath: "/v1", app: app2, migrate: migrate27, seed: seed28, credentials: credentials27, dumpState: dumpState27, actions: {}, checks: {}, coverage: lobCoverage };
140800
+ return { name: "lob", basePath: "/v1", app: app2, migrate: migrate28, seed: seed28, credentials: credentials27, dumpState: dumpState27, actions: {}, checks: {}, coverage: lobCoverage };
140351
140801
  }
140352
140802
 
140353
140803
  // packages/server/src/twins/paypal/db.ts
140354
- function migrate28(db2) {
140804
+ function migrate29(db2) {
140355
140805
  db2.exec(`
140356
140806
  CREATE TABLE paypal_objects (id TEXT PRIMARY KEY, kind TEXT NOT NULL, created_ms INTEGER NOT NULL, json TEXT NOT NULL);
140357
140807
  CREATE INDEX paypal_objects_kind ON paypal_objects (kind, created_ms);
@@ -140896,8 +141346,8 @@ var orderRoutes = [
140896
141346
  description: u.description
140897
141347
  });
140898
141348
  save9(r.ctx, "authorization", touch3(r, a));
140899
- const shape3 = captureShape(r, c);
140900
- return [201, r.prefer === "representation" ? shape3 : { id: shape3.id, status: shape3.status, links: shape3.links }];
141349
+ const shape4 = captureShape(r, c);
141350
+ return [201, r.prefer === "representation" ? shape4 : { id: shape4.id, status: shape4.status, links: shape4.links }];
140901
141351
  }
140902
141352
  },
140903
141353
  {
@@ -140932,8 +141382,8 @@ var orderRoutes = [
140932
141382
  if (want > left) refused("REFUND_AMOUNT_EXCEEDED", "The refund amount must be less than or equal to the capture amount that has not yet been refunded.", "/amount/value");
140933
141383
  const x = refund2(r.ctx, c, { cents: want, atMs: r.ctx.clock.nowMs(), note: b.note_to_payer ?? null, invoice_id: b.invoice_id ?? null, custom_id: b.custom_id ?? null });
140934
141384
  save9(r.ctx, "capture", { ...c, update_ms: r.ctx.clock.nowMs() });
140935
- const shape3 = refundShape2(r, x);
140936
- return [201, r.prefer === "representation" ? shape3 : { id: shape3.id, status: shape3.status, links: shape3.links }];
141385
+ const shape4 = refundShape2(r, x);
141386
+ return [201, r.prefer === "representation" ? shape4 : { id: shape4.id, status: shape4.status, links: shape4.links }];
140937
141387
  }
140938
141388
  },
140939
141389
  { method: "GET", path: "/v2/payments/refunds/:id", coverage: { status: "supported" }, run: (r) => refundShape2(r, load4(r.ctx, "refund", r.param("id")) ?? notFound13(r.param("id"))) }
@@ -141673,11 +142123,11 @@ function paypalTwin() {
141673
142123
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
141674
142124
  for (const route11 of [...paypalRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle19(route11));
141675
142125
  app2.all("*", unknownRoute13);
141676
- return { name: "paypal", basePath: "", app: app2, migrate: migrate28, seed: seed29, credentials: credentials28, actions: {}, checks: {}, dumpState: dumpState28, coverage: paypalCoverage };
142126
+ return { name: "paypal", basePath: "", app: app2, migrate: migrate29, seed: seed29, credentials: credentials28, actions: {}, checks: {}, dumpState: dumpState28, coverage: paypalCoverage };
141677
142127
  }
141678
142128
 
141679
142129
  // packages/server/src/twins/jira/db.ts
141680
- function migrate29(db2) {
142130
+ function migrate30(db2) {
141681
142131
  db2.exec(`
141682
142132
  CREATE TABLE jira_site (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL);
141683
142133
  CREATE TABLE jira_users (account_id TEXT PRIMARY KEY, seq INTEGER NOT NULL, json TEXT NOT NULL);
@@ -143798,7 +144248,7 @@ function jiraTwin() {
143798
144248
  else for (const api3 of ["3", "2"]) app2.on(route11.method, `/rest/api/${api3}${route11.path}`, handle20(route11, api3));
143799
144249
  }
143800
144250
  app2.all("*", unknownRoute14);
143801
- return { name: "jira", basePath: "", app: app2, migrate: migrate29, seed: seed30, credentials: credentials29, actions: {}, checks: {}, dumpState: dumpState29, coverage: jiraCoverage };
144251
+ return { name: "jira", basePath: "", app: app2, migrate: migrate30, seed: seed30, credentials: credentials29, actions: {}, checks: {}, dumpState: dumpState29, coverage: jiraCoverage };
143802
144252
  }
143803
144253
 
143804
144254
  // packages/server/src/twins/kalshi/index.ts
@@ -143846,7 +144296,7 @@ function rsaPrivateKey(secrets) {
143846
144296
  }
143847
144297
 
143848
144298
  // packages/server/src/twins/kalshi/db.ts
143849
- var SCHEMA17 = `
144299
+ var SCHEMA18 = `
143850
144300
  CREATE TABLE kx_series (ticker TEXT PRIMARY KEY, title TEXT NOT NULL, category TEXT NOT NULL, frequency TEXT NOT NULL, tags TEXT NOT NULL, sources TEXT NOT NULL, fee_type TEXT NOT NULL, fee_multiplier REAL NOT NULL, position INTEGER NOT NULL);
143851
144301
  CREATE TABLE kx_events (ticker TEXT PRIMARY KEY, series TEXT NOT NULL, title TEXT NOT NULL, sub_title TEXT NOT NULL, mutually_exclusive INTEGER NOT NULL, strike_ms INTEGER, position INTEGER NOT NULL);
143852
144302
  CREATE TABLE kx_markets (
@@ -143868,8 +144318,8 @@ CREATE TABLE kx_fills (
143868
144318
  );
143869
144319
  CREATE TABLE kx_deposits (id INTEGER PRIMARY KEY, amount INTEGER NOT NULL, at_ms INTEGER NOT NULL);
143870
144320
  `;
143871
- function migrate30(db2) {
143872
- db2.exec(SCHEMA17);
144321
+ function migrate31(db2) {
144322
+ db2.exec(SCHEMA18);
143873
144323
  }
143874
144324
  var ONE = 1e4;
143875
144325
  var dollars2 = (price3) => (price3 / ONE).toFixed(4);
@@ -144896,12 +145346,12 @@ async function handle21(c) {
144896
145346
  function kalshiTwin() {
144897
145347
  const app2 = new Hono3();
144898
145348
  app2.all("*", handle21);
144899
- return { name: "kalshi", basePath: "/trade-api/v2", app: app2, migrate: migrate30, seed: seed31, credentials: credentials30, dumpState: dumpState30, actions: {}, checks: {}, coverage: kalshiCoverage };
145349
+ return { name: "kalshi", basePath: "/trade-api/v2", app: app2, migrate: migrate31, seed: seed31, credentials: credentials30, dumpState: dumpState30, actions: {}, checks: {}, coverage: kalshiCoverage };
144900
145350
  }
144901
145351
 
144902
145352
  // packages/server/src/twins/intercom/request.ts
144903
145353
  import { createHash as createHash43 } from "node:crypto";
144904
- function migrate31(db2) {
145354
+ function migrate32(db2) {
144905
145355
  db2.exec(`
144906
145356
  CREATE TABLE intercom_objects (kind TEXT NOT NULL, id TEXT NOT NULL, seq INTEGER NOT NULL, json TEXT NOT NULL, PRIMARY KEY (kind, id));
144907
145357
  CREATE INDEX intercom_objects_seq ON intercom_objects (kind, seq);
@@ -146116,11 +146566,11 @@ function intercomTwin() {
146116
146566
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
146117
146567
  for (const route11 of [...intercomRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle22(route11));
146118
146568
  app2.all("*", unknownRoute15);
146119
- return { name: "intercom", basePath: "", app: app2, migrate: migrate31, seed: seed32, credentials: credentials31, actions: {}, checks: {}, dumpState: dumpState31, coverage: intercomCoverage };
146569
+ return { name: "intercom", basePath: "", app: app2, migrate: migrate32, seed: seed32, credentials: credentials31, actions: {}, checks: {}, dumpState: dumpState31, coverage: intercomCoverage };
146120
146570
  }
146121
146571
 
146122
146572
  // packages/server/src/twins/zendesk/db.ts
146123
- var SCHEMA18 = `
146573
+ var SCHEMA19 = `
146124
146574
  CREATE TABLE zd_users (
146125
146575
  id INTEGER PRIMARY KEY, email TEXT UNIQUE, name TEXT NOT NULL, role TEXT NOT NULL, organization_id INTEGER, phone TEXT, time_zone TEXT NOT NULL, tags TEXT NOT NULL,
146126
146576
  suspended INTEGER NOT NULL, external_id TEXT, default_group_id INTEGER, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL
@@ -146137,8 +146587,8 @@ CREATE TABLE zd_audits (id INTEGER PRIMARY KEY, ticket_id INTEGER NOT NULL, auth
146137
146587
  CREATE TABLE zd_macros (id INTEGER PRIMARY KEY, title TEXT NOT NULL, description TEXT, active INTEGER NOT NULL, actions TEXT NOT NULL, position INTEGER NOT NULL, created_ms INTEGER NOT NULL);
146138
146588
  CREATE TABLE zd_views (id INTEGER PRIMARY KEY, title TEXT NOT NULL, statuses TEXT NOT NULL, assignee TEXT NOT NULL, group_id INTEGER, sort_by TEXT NOT NULL, sort_order TEXT NOT NULL, active INTEGER NOT NULL, position INTEGER NOT NULL, created_ms INTEGER NOT NULL);
146139
146589
  `;
146140
- function migrate32(db2) {
146141
- db2.exec(SCHEMA18);
146590
+ function migrate33(db2) {
146591
+ db2.exec(SCHEMA19);
146142
146592
  }
146143
146593
  var BASES2 = { user: 21457810001, organization: 360041201001, group: 360000118001, ticket: 4101, comment: 31870100001, audit: 31870200001, macro: 360101000001, view: 360102000001 };
146144
146594
  function nextId6(ctx, kind) {
@@ -146324,20 +146774,20 @@ var ordered = (order4, actual, term) => {
146324
146774
  if (b < 0 || a < 0) return term.op === ":" && term.value.toLowerCase() === "none" && actual === null;
146325
146775
  return term.op === ":" ? a === b : term.op === "<" ? a < b : term.op === ">" ? a > b : term.op === "<=" ? a <= b : a >= b;
146326
146776
  };
146327
- var contains = (haystack, needle) => haystack.toLowerCase().includes(needle.toLowerCase());
146777
+ var contains2 = (haystack, needle) => haystack.toLowerCase().includes(needle.toLowerCase());
146328
146778
  var person3 = (world4, id12, value4) => {
146329
146779
  if (value4 === "none") return id12 === null;
146330
146780
  if (id12 === null) return false;
146331
146781
  const user8 = world4.users.get(id12);
146332
- return value4 === "me" ? id12 === world4.me.id : !!user8 && (String(user8.id) === value4 || user8.email === value4.toLowerCase() || contains(user8.name, value4));
146782
+ return value4 === "me" ? id12 === world4.me.id : !!user8 && (String(user8.id) === value4 || user8.email === value4.toLowerCase() || contains2(user8.name, value4));
146333
146783
  };
146334
- var named2 = (map2, id12, value4) => value4 === "none" ? id12 === null : id12 !== null && (String(id12) === value4 || contains(map2.get(id12)?.name ?? "", value4));
146784
+ var named2 = (map2, id12, value4) => value4 === "none" ? id12 === null : id12 !== null && (String(id12) === value4 || contains2(map2.get(id12)?.name ?? "", value4));
146335
146785
  function ticketMatches(world4, ticket2, term) {
146336
146786
  const tags4 = tagsOf(ticket2.tags);
146337
146787
  switch (term.key) {
146338
146788
  case null: {
146339
146789
  const text21 = [ticket2.subject, ticket2.description, ...commentsOf2(world4.ctx, ticket2.id).map((comment8) => comment8.body), ...tags4].join("\n");
146340
- return contains(text21, term.value);
146790
+ return contains2(text21, term.value);
146341
146791
  }
146342
146792
  case "status":
146343
146793
  return ordered(STATUSES2, ticket2.status, term);
@@ -146359,11 +146809,11 @@ function ticketMatches(world4, ticket2, term) {
146359
146809
  case "tag":
146360
146810
  return tags4.includes(term.value.toLowerCase());
146361
146811
  case "subject":
146362
- return contains(ticket2.subject, term.value);
146812
+ return contains2(ticket2.subject, term.value);
146363
146813
  case "description":
146364
- return contains(ticket2.description, term.value);
146814
+ return contains2(ticket2.description, term.value);
146365
146815
  case "comment":
146366
- return commentsOf2(world4.ctx, ticket2.id).some((comment8) => contains(comment8.body, term.value));
146816
+ return commentsOf2(world4.ctx, ticket2.id).some((comment8) => contains2(comment8.body, term.value));
146367
146817
  case "via":
146368
146818
  return ticket2.via === term.value.toLowerCase();
146369
146819
  case "external_id":
@@ -146382,10 +146832,10 @@ function ticketMatches(world4, ticket2, term) {
146382
146832
  function userMatches2(world4, user8, term) {
146383
146833
  switch (term.key) {
146384
146834
  case null:
146385
- return contains(`${user8.name}
146835
+ return contains2(`${user8.name}
146386
146836
  ${user8.email ?? ""}`, term.value);
146387
146837
  case "name":
146388
- return contains(user8.name, term.value);
146838
+ return contains2(user8.name, term.value);
146389
146839
  case "email":
146390
146840
  return (user8.email ?? "") === term.value.toLowerCase() || term.value.startsWith("*") && (user8.email ?? "").endsWith(term.value.slice(1).toLowerCase());
146391
146841
  case "role":
@@ -146409,10 +146859,10 @@ ${user8.email ?? ""}`, term.value);
146409
146859
  function organizationMatches(world4, organization4, term) {
146410
146860
  switch (term.key) {
146411
146861
  case null:
146412
- return contains(`${organization4.name}
146862
+ return contains2(`${organization4.name}
146413
146863
  ${JSON.parse(organization4.domains).join(" ")}`, term.value);
146414
146864
  case "name":
146415
- return contains(organization4.name, term.value);
146865
+ return contains2(organization4.name, term.value);
146416
146866
  case "tags":
146417
146867
  case "tag":
146418
146868
  return tagsOf(organization4.tags).includes(term.value.toLowerCase());
@@ -146424,7 +146874,7 @@ ${JSON.parse(organization4.domains).join(" ")}`, term.value);
146424
146874
  }
146425
146875
  }
146426
146876
  function groupMatches(world4, group5, term) {
146427
- if (term.key === null || term.key === "name") return contains(group5.name, term.value);
146877
+ if (term.key === null || term.key === "name") return contains2(group5.name, term.value);
146428
146878
  return world4.unsupported(`the group search property ${term.key}`);
146429
146879
  }
146430
146880
 
@@ -147248,11 +147698,11 @@ async function handle23(c) {
147248
147698
  function zendeskTwin() {
147249
147699
  const app2 = new Hono3();
147250
147700
  app2.all("*", handle23);
147251
- return { name: "zendesk", basePath: "/api/v2", app: app2, migrate: migrate32, seed: seed33, credentials: credentials32, dumpState: dumpState32, actions: {}, checks: {}, coverage: zendeskCoverage };
147701
+ return { name: "zendesk", basePath: "/api/v2", app: app2, migrate: migrate33, seed: seed33, credentials: credentials32, dumpState: dumpState32, actions: {}, checks: {}, coverage: zendeskCoverage };
147252
147702
  }
147253
147703
 
147254
147704
  // packages/server/src/twins/google-calendar/request.ts
147255
- function migrate33(db2) {
147705
+ function migrate34(db2) {
147256
147706
  db2.exec(`
147257
147707
  CREATE TABLE gcal_owner (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL);
147258
147708
  CREATE TABLE gcal_calendars (id TEXT PRIMARY KEY, seq INTEGER NOT NULL, json TEXT NOT NULL);
@@ -147851,12 +148301,12 @@ function listEvents3(r, cal, only4) {
147851
148301
  defaultReminders: writable2(cal) ? [{ method: "popup", minutes: 10 }] : [],
147852
148302
  ...p2.next && { nextPageToken: p2.next },
147853
148303
  items: p2.slice.map(({ e, at: at2 }) => {
147854
- const shape3 = eventShape2(r, e, tz, at2, limited);
147855
- if (maxAttendees !== null && shape3.attendees?.length > maxAttendees) {
147856
- shape3.attendees = shape3.attendees.filter((a) => a.self).slice(0, 1);
147857
- shape3.attendeesOmitted = true;
148304
+ const shape4 = eventShape2(r, e, tz, at2, limited);
148305
+ if (maxAttendees !== null && shape4.attendees?.length > maxAttendees) {
148306
+ shape4.attendees = shape4.attendees.filter((a) => a.self).slice(0, 1);
148307
+ shape4.attendeesOmitted = true;
147858
148308
  }
147859
- return shape3;
148309
+ return shape4;
147860
148310
  })
147861
148311
  };
147862
148312
  }
@@ -148272,12 +148722,12 @@ function googleCalendarTwin() {
148272
148722
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
148273
148723
  for (const route11 of [...calendarRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle24(route11));
148274
148724
  app2.all("*", unknownRoute16);
148275
- return { name: "google-calendar", basePath: "", unprefixedPaths: /^\/calendar\/v3\//, app: app2, migrate: migrate33, seed: seed34, credentials: credentials33, actions: {}, checks: {}, dumpState: dumpState33, coverage: googleCalendarCoverage };
148725
+ return { name: "google-calendar", basePath: "", unprefixedPaths: /^\/calendar\/v3\//, app: app2, migrate: migrate34, seed: seed34, credentials: credentials33, actions: {}, checks: {}, dumpState: dumpState33, coverage: googleCalendarCoverage };
148276
148726
  }
148277
148727
 
148278
148728
  // packages/server/src/twins/twilio/db.ts
148279
148729
  import { createHash as createHash45 } from "node:crypto";
148280
- var SCHEMA19 = `
148730
+ var SCHEMA20 = `
148281
148731
  CREATE TABLE tw_numbers (sid TEXT PRIMARY KEY, phone_number TEXT NOT NULL UNIQUE, friendly_name TEXT NOT NULL, sms INTEGER NOT NULL, voice INTEGER NOT NULL, created_ms INTEGER NOT NULL);
148282
148732
  CREATE TABLE tw_directory (phone_number TEXT PRIMARY KEY, type TEXT NOT NULL, carrier TEXT NOT NULL, caller_name TEXT, reachable INTEGER NOT NULL, opted_out INTEGER NOT NULL);
148283
148733
  CREATE TABLE tw_messages (
@@ -148294,8 +148744,8 @@ CREATE TABLE tw_verifications (
148294
148744
  created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL
148295
148745
  );
148296
148746
  `;
148297
- function migrate34(db2) {
148298
- db2.exec(SCHEMA19);
148747
+ function migrate35(db2) {
148748
+ db2.exec(SCHEMA20);
148299
148749
  }
148300
148750
  var seededSid = (prefix2, key3) => `${prefix2}${createHash45("sha256").update(`twilio:${prefix2}:${key3}`).digest("hex").slice(0, 32)}`;
148301
148751
  var newSid = (ctx, prefix2) => `${prefix2}${ctx.ids.hex(32)}`;
@@ -148954,11 +149404,11 @@ async function handle25(c) {
148954
149404
  function twilioTwin() {
148955
149405
  const app2 = new Hono3();
148956
149406
  app2.all("*", handle25);
148957
- return { name: "twilio", basePath: "", app: app2, migrate: migrate34, seed: seed35, credentials: credentials34, dumpState: dumpState34, actions: {}, checks: {}, coverage: twilioCoverage };
149407
+ return { name: "twilio", basePath: "", app: app2, migrate: migrate35, seed: seed35, credentials: credentials34, dumpState: dumpState34, actions: {}, checks: {}, coverage: twilioCoverage };
148958
149408
  }
148959
149409
 
148960
149410
  // packages/server/src/twins/asana/db.ts
148961
- var SCHEMA20 = `
149411
+ var SCHEMA21 = `
148962
149412
  CREATE TABLE as_users (gid TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, name TEXT NOT NULL);
148963
149413
  CREATE TABLE as_projects (gid TEXT PRIMARY KEY, name TEXT NOT NULL, owner TEXT, notes TEXT NOT NULL, color TEXT, archived INTEGER NOT NULL, due_on TEXT, created_ms INTEGER NOT NULL, modified_ms INTEGER NOT NULL);
148964
149414
  CREATE TABLE as_project_members (project TEXT NOT NULL, user TEXT NOT NULL, PRIMARY KEY (project, user));
@@ -148971,8 +149421,8 @@ CREATE TABLE as_memberships (task TEXT NOT NULL, project TEXT NOT NULL, section
148971
149421
  CREATE TABLE as_followers (task TEXT NOT NULL, user TEXT NOT NULL, PRIMARY KEY (task, user));
148972
149422
  CREATE TABLE as_stories (gid TEXT PRIMARY KEY, task TEXT NOT NULL, created_by TEXT, created_ms INTEGER NOT NULL, type TEXT NOT NULL, subtype TEXT NOT NULL, text TEXT NOT NULL);
148973
149423
  `;
148974
- function migrate35(db2) {
148975
- db2.exec(SCHEMA20);
149424
+ function migrate36(db2) {
149425
+ db2.exec(SCHEMA21);
148976
149426
  }
148977
149427
  var BASES3 = { workspace: 1200000000000001, user: 1201000000000001, project: 1205000000000001, section: 1206000000000001, task: 1208000000000001, story: 1210000000000001 };
148978
149428
  function nextGid(ctx, kind) {
@@ -149270,22 +149720,22 @@ function treeOf(fields11) {
149270
149720
  }
149271
149721
  return root2;
149272
149722
  }
149273
- function shape2(ctx, value4, tree) {
149274
- if (Array.isArray(value4)) return value4.map((item2) => shape2(ctx, item2, tree));
149723
+ function shape3(ctx, value4, tree) {
149724
+ if (Array.isArray(value4)) return value4.map((item2) => shape3(ctx, item2, tree));
149275
149725
  if (value4 === null || typeof value4 !== "object") return value4;
149276
149726
  let record8 = value4;
149277
149727
  if (record8.resource_type && record8.gid && [...tree.keys()].some((field3) => !(field3 in record8))) record8 = expand2(ctx, record8);
149278
149728
  const out = "gid" in record8 ? { gid: record8.gid } : {};
149279
- for (const [field3, child2] of tree) if (field3 in record8) out[field3] = child2.size ? shape2(ctx, record8[field3], child2) : record8[field3];
149729
+ for (const [field3, child2] of tree) if (field3 in record8) out[field3] = child2.size ? shape3(ctx, record8[field3], child2) : record8[field3];
149280
149730
  return out;
149281
149731
  }
149282
149732
  function one5(call2, full2) {
149283
149733
  const tree = treeOf(call2.url.searchParams.get("opt_fields"));
149284
- return json26({ data: tree ? shape2(call2.ctx, full2, tree) : full2 });
149734
+ return json26({ data: tree ? shape3(call2.ctx, full2, tree) : full2 });
149285
149735
  }
149286
149736
  function list14(call2, items, full2, compact2) {
149287
149737
  const params9 = call2.url.searchParams, tree = treeOf(params9.get("opt_fields"));
149288
- const render = (item2) => tree ? shape2(call2.ctx, full2(item2), tree) : compact2(item2);
149738
+ const render = (item2) => tree ? shape3(call2.ctx, full2(item2), tree) : compact2(item2);
149289
149739
  if (params9.get("limit") === null) return json26({ data: items.map(render) });
149290
149740
  const limit = Number(params9.get("limit")), offset16 = params9.get("offset");
149291
149741
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw bad("limit: Value must be between 1 and 100");
@@ -149647,7 +150097,7 @@ function searchTasks(call2) {
149647
150097
  return (x < y ? -1 : x > y ? 1 : a.gid < b.gid ? -1 : 1) * (ascending ? 1 : -1);
149648
150098
  });
149649
150099
  const tree = treeOf(params9.get("opt_fields"));
149650
- return json26({ data: tasks.slice(0, limit).map((task2) => tree ? shape2(ctx, taskFull(ctx, task2), tree) : taskCompact(task2)) });
150100
+ return json26({ data: tasks.slice(0, limit).map((task2) => tree ? shape3(ctx, taskFull(ctx, task2), tree) : taskCompact(task2)) });
149651
150101
  }
149652
150102
  var route8 = (method2, path4, write4, handle30, notes6) => ({ method: method2, path: path4, write: write4, handle: handle30, ...notes6 && { notes: notes6 }, pattern: new RegExp(`^${path4.replace(/\{[^}]+\}/g, "([^/]+)")}$`) });
149653
150103
  var API = "/api/1.0";
@@ -149771,11 +150221,11 @@ async function handle26(c) {
149771
150221
  function asanaTwin() {
149772
150222
  const app2 = new Hono3();
149773
150223
  app2.all("*", handle26);
149774
- return { name: "asana", basePath: "/api/1.0", app: app2, migrate: migrate35, seed: seed36, credentials: credentials35, dumpState: dumpState35, actions: {}, checks: {}, coverage: asanaCoverage };
150224
+ return { name: "asana", basePath: "/api/1.0", app: app2, migrate: migrate36, seed: seed36, credentials: credentials35, dumpState: dumpState35, actions: {}, checks: {}, coverage: asanaCoverage };
149775
150225
  }
149776
150226
 
149777
150227
  // packages/server/src/twins/discord/db.ts
149778
- var SCHEMA21 = `
150228
+ var SCHEMA22 = `
149779
150229
  CREATE TABLE dc_users (id TEXT PRIMARY KEY, username TEXT NOT NULL UNIQUE, global_name TEXT, bot INTEGER NOT NULL);
149780
150230
  CREATE TABLE dc_roles (id TEXT PRIMARY KEY, name TEXT NOT NULL, permissions TEXT NOT NULL, color INTEGER NOT NULL, hoist INTEGER NOT NULL, mentionable INTEGER NOT NULL, managed INTEGER NOT NULL, position INTEGER NOT NULL);
149781
150231
  CREATE TABLE dc_members (user_id TEXT PRIMARY KEY, nick TEXT, roles TEXT NOT NULL, joined_ms INTEGER NOT NULL);
@@ -149789,8 +150239,8 @@ CREATE TABLE dc_messages (
149789
150239
  );
149790
150240
  CREATE TABLE dc_reactions (message_id TEXT NOT NULL, emoji TEXT NOT NULL, user_id TEXT NOT NULL, created_ms INTEGER NOT NULL, PRIMARY KEY (message_id, emoji, user_id));
149791
150241
  `;
149792
- function migrate36(db2) {
149793
- db2.exec(SCHEMA21);
150242
+ function migrate37(db2) {
150243
+ db2.exec(SCHEMA22);
149794
150244
  }
149795
150245
  var TEXT3 = 0;
149796
150246
  var DM = 1;
@@ -150431,11 +150881,11 @@ async function handle27(c) {
150431
150881
  function discordTwin() {
150432
150882
  const app2 = new Hono3();
150433
150883
  app2.all("*", handle27);
150434
- return { name: "discord", basePath: "/api/v10", app: app2, migrate: migrate36, seed: seed37, credentials: credentials36, dumpState: dumpState36, actions: {}, checks: {}, coverage: discordCoverage };
150884
+ return { name: "discord", basePath: "/api/v10", app: app2, migrate: migrate37, seed: seed37, credentials: credentials36, dumpState: dumpState36, actions: {}, checks: {}, coverage: discordCoverage };
150435
150885
  }
150436
150886
 
150437
150887
  // packages/server/src/twins/sentry/db.ts
150438
- function migrate37(db2) {
150888
+ function migrate38(db2) {
150439
150889
  db2.exec(`
150440
150890
  CREATE TABLE sentry_org (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL);
150441
150891
  CREATE TABLE sentry_members (id TEXT PRIMARY KEY, seq INTEGER NOT NULL, json TEXT NOT NULL);
@@ -151382,8 +151832,8 @@ function apply(ctx, i, by2, c, ms) {
151382
151832
  const same2 = c.assign?.type === i.assignee?.type && c.assign?.id === i.assignee?.id;
151383
151833
  if (!same2) {
151384
151834
  i.assignee = c.assign;
151385
- const shape3 = actorShape(ctx, c.assign);
151386
- if (shape3) activity(ctx, i, "assigned", by2, { assignee: shape3.id, assigneeEmail: shape3.type === "user" ? shape3.email : void 0, assigneeName: shape3.name, assigneeType: shape3.type }, ms);
151835
+ const shape4 = actorShape(ctx, c.assign);
151836
+ if (shape4) activity(ctx, i, "assigned", by2, { assignee: shape4.id, assigneeEmail: shape4.type === "user" ? shape4.email : void 0, assigneeName: shape4.name, assigneeType: shape4.type }, ms);
151387
151837
  else activity(ctx, i, "unassigned", by2, {}, ms);
151388
151838
  }
151389
151839
  delta.assignedTo = actorShape(ctx, i.assignee);
@@ -152495,11 +152945,11 @@ function sentryTwin() {
152495
152945
  if (route11.path.startsWith(ISSUE)) app2.on(route11.method, `/api/0/issues/:issue${route11.path.slice(ISSUE.length)}`, handle28(route11));
152496
152946
  }
152497
152947
  app2.all("*", unknownRoute17);
152498
- return { name: "sentry", basePath: "", app: app2, migrate: migrate37, seed: seed38, credentials: credentials37, actions: { capture: capture2 }, checks: {}, dumpState: dumpState37, coverage: sentryCoverage };
152948
+ return { name: "sentry", basePath: "", app: app2, migrate: migrate38, seed: seed38, credentials: credentials37, actions: { capture: capture2 }, checks: {}, dumpState: dumpState37, coverage: sentryCoverage };
152499
152949
  }
152500
152950
 
152501
152951
  // packages/server/src/twins/airtable/db.ts
152502
- var SCHEMA22 = `
152952
+ var SCHEMA23 = `
152503
152953
  CREATE TABLE at_users (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, position INTEGER NOT NULL);
152504
152954
  CREATE TABLE at_bases (id TEXT PRIMARY KEY, name TEXT NOT NULL, permission TEXT NOT NULL, position INTEGER NOT NULL);
152505
152955
  CREATE TABLE at_tables (id TEXT PRIMARY KEY, base_id TEXT NOT NULL, name TEXT NOT NULL, description TEXT, primary_field_id TEXT NOT NULL, position INTEGER NOT NULL, next_number INTEGER NOT NULL);
@@ -152515,8 +152965,8 @@ CREATE TABLE at_comments (
152515
152965
  created_ms INTEGER NOT NULL, updated_ms INTEGER, deleted_ms INTEGER
152516
152966
  );
152517
152967
  `;
152518
- function migrate38(db2) {
152519
- db2.exec(SCHEMA22);
152968
+ function migrate39(db2) {
152969
+ db2.exec(SCHEMA23);
152520
152970
  }
152521
152971
  var BASE625 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
152522
152972
  function newId7(ctx, kind) {
@@ -153849,7 +154299,7 @@ async function handle29(c) {
153849
154299
  function airtableTwin() {
153850
154300
  const app2 = new Hono3();
153851
154301
  app2.all("*", handle29);
153852
- return { name: "airtable", basePath: "/v0", app: app2, migrate: migrate38, seed: seed39, credentials: credentials38, dumpState: dumpState38, actions: {}, checks: {}, coverage: airtableCoverage };
154302
+ return { name: "airtable", basePath: "/v0", app: app2, migrate: migrate39, seed: seed39, credentials: credentials38, dumpState: dumpState38, actions: {}, checks: {}, coverage: airtableCoverage };
153853
154303
  }
153854
154304
 
153855
154305
  // packages/server/src/registry.ts
@@ -153878,6 +154328,7 @@ function envInfo(env, origin, port) {
153878
154328
  };
153879
154329
  }
153880
154330
  const mcp = Object.fromEntries(Object.entries(env.mcpTokens).map(([tool, token2]) => [tool, { url: `${origin}/e/${env.id}/mcp/${tool}`, token: token2 }]));
154331
+ const tools = Object.entries(env.scene.tools ?? {}).map(([name5, t]) => ({ name: name5, ...t.description && { description: t.description }, ...t.schema && { schema: t.schema }, ...t.twin && { twin: t.twin } }));
153881
154332
  return {
153882
154333
  id: env.id,
153883
154334
  sceneId: env.scene.id,
@@ -153885,6 +154336,7 @@ function envInfo(env, origin, port) {
153885
154336
  timeScale: env.scene.time_scale,
153886
154337
  services: services2,
153887
154338
  ...Object.keys(mcp).length ? { mcp } : {},
154339
+ ...tools.length ? { tools } : {},
153888
154340
  ...env.sandbox ? { sandbox: { ...structuredClone(env.sandbox), seed: env.seed } } : {}
153889
154341
  };
153890
154342
  }
@@ -154732,7 +155184,7 @@ function addressedEvent(env, event3) {
154732
155184
  // packages/server/src/sessions.ts
154733
155185
  function agentCalls(env) {
154734
155186
  let calls2;
154735
- return { first: (pattern) => (calls2 ??= env.trace.list().filter((entry2) => entry2.source === "agent")).find(compileTracePattern(pattern)) };
155187
+ return { first: (pattern) => (calls2 ??= env.trace.list().filter((entry2) => entry2.source === "agent")).find(compileTracePattern(pattern, sceneTools(env))) };
154736
155188
  }
154737
155189
  function lastTimedActorMs(env) {
154738
155190
  return env.store.db.prepare("SELECT max(due_ms) AS due FROM _ancha_jobs WHERE state = 'pending' AND kind IN ('actor', 'world.conditional_actor') AND due_ms <= ?").get(parseDuration(env.scene.timeout)).due;
@@ -154927,12 +155379,13 @@ var TrialSessions = class {
154927
155379
  env.touchLease();
154928
155380
  return { env, session: { ...record8.session } };
154929
155381
  }
154930
- done(token2) {
155382
+ done(token2, answer) {
154931
155383
  const { env, session } = this.authenticate(token2, true);
154932
155384
  return env.serialize(() => {
154933
155385
  this.authenticate(token2, true);
154934
155386
  const record8 = this.#record(env, session.id);
154935
155387
  if (record8.session.state === "prepared") throw new AnchaError("SESSION_CONFLICT", "session has not started");
155388
+ if (answer !== void 0 && record8.session.state === "running") env.trace.record({ source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: answer.output } });
154936
155389
  if (record8.session.state === "running") record8.session.state = "done";
154937
155390
  });
154938
155391
  }
@@ -155290,7 +155743,8 @@ function sessionRoutes(opts, sessions) {
155290
155743
  signal: c.req.raw.signal
155291
155744
  })));
155292
155745
  app2.post("/done", async (c) => {
155293
- await sessions.done(token2(c.req.header("authorization")));
155746
+ const body6 = await c.req.json().catch(() => void 0);
155747
+ await sessions.done(token2(c.req.header("authorization")), body6 && typeof body6 === "object" && "output" in body6 ? { output: body6.output } : void 0);
155294
155748
  return c.json({ ok: true });
155295
155749
  });
155296
155750
  app2.get("/events", async (c) => {
@@ -155583,6 +156037,12 @@ function createApp(opts) {
155583
156037
  ...response5 !== void 0 && { response: response5 },
155584
156038
  gap: res.status === 501 || res.headers.has(GAP_HEADER),
155585
156039
  // Extract before TraceRecorder caps response bodies; never infer a harness fault from status.
156040
+ ...res.headers.has(SETUP_ISSUE_HEADER) && { issue: {
156041
+ kind: "tools",
156042
+ owner: "harness",
156043
+ service,
156044
+ message: typeof response5 === "object" && response5 !== null && typeof response5.error === "string" ? response5.error : "the test stopped before the agent ran"
156045
+ } },
155586
156046
  ...res.headers.has(INTERNAL_ERROR_HEADER) && { issue: {
155587
156047
  kind: "twin",
155588
156048
  owner: "harness",