@ancha-labs/cli 0.2.1 → 0.3.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.
@@ -56519,6 +56519,8 @@ var EXECUTION_SUPPORT = {
56519
56519
  "world_rules": sceneOnly,
56520
56520
  "people": sceneOnly,
56521
56521
  "until": sceneOnly,
56522
+ "trigger": sceneOnly,
56523
+ "tools": sceneOnly,
56522
56524
  "deadline": sceneOnly,
56523
56525
  "start.message": sceneOnly,
56524
56526
  "pass": sceneOnly,
@@ -56557,7 +56559,8 @@ var EXECUTION_SUPPORT = {
56557
56559
  "--pass-env": sceneOnly,
56558
56560
  "--inherit-env": sceneOnly,
56559
56561
  "--upload": sceneOnly,
56560
- "--upload-required": sceneOnly
56562
+ "--upload-required": sceneOnly,
56563
+ "--allow-unwrapped": sceneOnly
56561
56564
  };
56562
56565
 
56563
56566
  // packages/core/src/relay.ts
@@ -57807,9 +57810,9 @@ function stringifyPrimitive(value4) {
57807
57810
  return `"${value4}"`;
57808
57811
  return `${value4}`;
57809
57812
  }
57810
- function optionalKeys(shape3) {
57811
- return Object.keys(shape3).filter((k) => {
57812
- return shape3[k]._zod.optin !== void 0 && shape3[k]._zod.optout === "optional";
57813
+ function optionalKeys(shape4) {
57814
+ return Object.keys(shape4).filter((k) => {
57815
+ return shape4[k]._zod.optin !== void 0 && shape4[k]._zod.optout === "optional";
57813
57816
  });
57814
57817
  }
57815
57818
  var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({
@@ -57858,33 +57861,33 @@ function omit(schema, mask2) {
57858
57861
  mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key3) => !omitted.has(key3)));
57859
57862
  return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));
57860
57863
  }
57861
- function extend(schema, shape3) {
57862
- if (!isPlainObject(shape3)) {
57864
+ function extend(schema, shape4) {
57865
+ if (!isPlainObject(shape4)) {
57863
57866
  throw new Error("Invalid input to extend: expected a plain object");
57864
57867
  }
57865
57868
  const checks = schema._zod.def.checks;
57866
57869
  const hasChecks = checks && checks.length > 0;
57867
57870
  if (hasChecks) {
57868
57871
  const existingShape = sourceShape(schema);
57869
- for (const key3 of Reflect.ownKeys(shape3)) {
57872
+ for (const key3 of Reflect.ownKeys(shape4)) {
57870
57873
  if (Object.getOwnPropertyDescriptor(existingShape, key3) !== void 0) {
57871
57874
  throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
57872
57875
  }
57873
57876
  }
57874
57877
  }
57875
- return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape3) }));
57878
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape4) }));
57876
57879
  }
57877
- function extended(schema, shape3) {
57880
+ function extended(schema, shape4) {
57878
57881
  const newShape = {};
57879
57882
  mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));
57880
- mirrorProps(newShape, shape3);
57883
+ mirrorProps(newShape, shape4);
57881
57884
  return newShape;
57882
57885
  }
57883
- function safeExtend(schema, shape3) {
57884
- if (!isPlainObject(shape3)) {
57886
+ function safeExtend(schema, shape4) {
57887
+ if (!isPlainObject(shape4)) {
57885
57888
  throw new Error("Invalid input to safeExtend: expected a plain object");
57886
57889
  }
57887
- return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape3) }));
57890
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape4) }));
57888
57891
  }
57889
57892
  function merge(a, b) {
57890
57893
  if (!b?._zod?.def) {
@@ -60332,10 +60335,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
60332
60335
  }
60333
60336
  const _normalized = cached(() => normalizeDef(def));
60334
60337
  defineLazyInternal(inst, "propValues", (zod) => {
60335
- const shape3 = zod.def.shape;
60338
+ const shape4 = zod.def.shape;
60336
60339
  const propValues = {};
60337
- for (const key3 in shape3) {
60338
- const field3 = shape3[key3]._zod;
60340
+ for (const key3 in shape4) {
60341
+ const field3 = shape4[key3]._zod;
60339
60342
  if (field3.values) {
60340
60343
  if (!Object.prototype.hasOwnProperty.call(propValues, key3)) {
60341
60344
  assignProp(propValues, key3, /* @__PURE__ */ new Set());
@@ -60367,7 +60370,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
60367
60370
  }
60368
60371
  payload2.value = memo3 ? memo3.alloc(inst, payload2, {}, ctx) : {};
60369
60372
  const proms = [];
60370
- const shape3 = value4.shape;
60373
+ const shape4 = value4.shape;
60371
60374
  const abortEarly = ctx?.abortEarly;
60372
60375
  let seen = payload2.issues.length;
60373
60376
  for (const key3 of value4.allKeys) {
@@ -60378,7 +60381,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
60378
60381
  }
60379
60382
  if (key3 === "__proto__")
60380
60383
  continue;
60381
- const el2 = shape3[key3];
60384
+ const el2 = shape4[key3];
60382
60385
  const optin = el2._zod.optin;
60383
60386
  const optout = el2._zod.optout;
60384
60387
  const r = el2._zod.run({ value: input2[key3], issues: [] }, ctx);
@@ -60399,10 +60402,10 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
60399
60402
  const superParse = inst._zod.parse;
60400
60403
  const _normalized = cached(() => normalizeDef(def));
60401
60404
  const memo3 = globalConfig.memoizer;
60402
- const generateFastpass = (shape3) => {
60405
+ const generateFastpass = (shape4) => {
60403
60406
  const normalized = _normalized.value;
60404
60407
  const syms = normalized.symbolKeys;
60405
- const doc = new Doc(["payload", "ctx"], { shape: shape3, inst, memo: memo3, syms });
60408
+ const doc = new Doc(["payload", "ctx"], { shape: shape4, inst, memo: memo3, syms });
60406
60409
  const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
60407
60410
  const prefixStr = (id12, k) => `
60408
60411
  let ${id12}_ab = false;
@@ -60429,7 +60432,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
60429
60432
  const id12 = ids2[key3];
60430
60433
  const k = typeof key3 === "symbol" ? `syms[${syms.indexOf(key3)}]` : esc(key3);
60431
60434
  const isPresent = `${k} in input`;
60432
- const schema = shape3[key3];
60435
+ const schema = shape4[key3];
60433
60436
  const optin = schema?._zod?.optin;
60434
60437
  const isOptionalIn = optin !== void 0;
60435
60438
  const isOptionalOut = schema?._zod?.optout === "optional";
@@ -61868,7 +61871,7 @@ function isRecursive(inst, stack, resolve5) {
61868
61871
  result = answer;
61869
61872
  }
61870
61873
  };
61871
- const shape3 = (sh, spread) => {
61874
+ const shape4 = (sh, spread) => {
61872
61875
  let answer = NONE;
61873
61876
  for (const key3 of Reflect.ownKeys(sh)) {
61874
61877
  const desc = Object.getOwnPropertyDescriptor(sh, key3);
@@ -61889,7 +61892,7 @@ function isRecursive(inst, stack, resolve5) {
61889
61892
  switch (kind) {
61890
61893
  case "object": {
61891
61894
  const raw3 = rawShape(def);
61892
- merge3(raw3 ? shape3(raw3, true) : ASSUMED);
61895
+ merge3(raw3 ? shape4(raw3, true) : ASSUMED);
61893
61896
  check3(def.catchall);
61894
61897
  break;
61895
61898
  }
@@ -70100,12 +70103,12 @@ function generatePropertiesChecks(doc, ctx, def, accessor) {
70100
70103
  throw new ZodCompileUnsupportedError(`check with a custom "when" condition`);
70101
70104
  }
70102
70105
  doc.write(`if (${accessor} == null) return INVALID;`);
70103
- const shape3 = def.shape;
70104
- for (const key3 of Reflect.ownKeys(shape3)) {
70106
+ const shape4 = def.shape;
70107
+ for (const key3 of Reflect.ownKeys(shape4)) {
70105
70108
  const keyExpr = typeof key3 === "symbol" ? addConstant(ctx, key3) : esc(key3);
70106
70109
  const inputVar = newVar(ctx);
70107
70110
  doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`);
70108
- compileChild(doc, ctx, shape3[key3], inputVar, false);
70111
+ compileChild(doc, ctx, shape4[key3], inputVar, false);
70109
70112
  }
70110
70113
  }
70111
70114
  function generatePropertyCheck(doc, ctx, def, accessor) {
@@ -70487,13 +70490,13 @@ function generateDateCheck(doc, accessor) {
70487
70490
  function generateObjectCheck(doc, ctx, schema, accessor, buildsValue = true) {
70488
70491
  const def = schema._zod.def;
70489
70492
  doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);
70490
- const shape3 = def.shape;
70491
- const keys5 = Object.keys(shape3);
70492
- const symbolKeys = Object.getOwnPropertySymbols(shape3);
70493
+ const shape4 = def.shape;
70494
+ const keys5 = Object.keys(shape4);
70495
+ const symbolKeys = Object.getOwnPropertySymbols(shape4);
70493
70496
  const allKeys = symbolKeys.length ? [...keys5, ...symbolKeys] : keys5;
70494
70497
  const keyExpr = (k) => typeof k === "symbol" ? addConstant(ctx, k) : esc(k);
70495
70498
  const propKey = (k) => typeof k === "symbol" ? `[${keyExpr(k)}]` : esc(k);
70496
- const propShape = shape3;
70499
+ const propShape = shape4;
70497
70500
  if (keys5.includes("__proto__")) {
70498
70501
  throw new ZodCompileUnsupportedError('object shape key "__proto__"');
70499
70502
  }
@@ -72000,10 +72003,10 @@ function _property(property3, schema, params9) {
72000
72003
  });
72001
72004
  }
72002
72005
  // @__NO_SIDE_EFFECTS__
72003
- function _properties(shape3, params9) {
72006
+ function _properties(shape4, params9) {
72004
72007
  return new $ZodCheckProperties({
72005
72008
  check: "properties",
72006
- shape: shape3,
72009
+ shape: shape4,
72007
72010
  ...normalizeParams(params9)
72008
72011
  });
72009
72012
  }
@@ -73265,21 +73268,21 @@ function inputOptin(schema) {
73265
73268
  var objectProcessor = (schema, ctx, _json, params9) => {
73266
73269
  const json30 = _json;
73267
73270
  const def = schema._zod.def;
73268
- const shape3 = def.shape;
73269
- const symbolKeys = Object.getOwnPropertySymbols(shape3);
73271
+ const shape4 = def.shape;
73272
+ const symbolKeys = Object.getOwnPropertySymbols(shape4);
73270
73273
  if (symbolKeys.length && handleUnrepresentable(schema, ctx, json30, params9, "Symbol keys cannot be represented in JSON Schema")) {
73271
73274
  return;
73272
73275
  }
73273
73276
  json30.type = "object";
73274
73277
  json30.properties = {};
73275
- for (const key3 in shape3) {
73276
- assignProp(json30.properties, key3, processSchema(shape3[key3], ctx, {
73278
+ for (const key3 in shape4) {
73279
+ assignProp(json30.properties, key3, processSchema(shape4[key3], ctx, {
73277
73280
  ...params9,
73278
73281
  path: [...params9.path, "properties", key3]
73279
73282
  }));
73280
73283
  }
73281
73284
  const requiredKeys = [];
73282
- for (const key3 of Object.keys(shape3)) {
73285
+ for (const key3 of Object.keys(shape4)) {
73283
73286
  const field3 = def.shape[key3];
73284
73287
  if (ctx.io === "input" ? inputOptin(field3) === void 0 : field3._zod.optout === void 0) {
73285
73288
  requiredKeys.push(key3);
@@ -74841,8 +74844,8 @@ function array(element, params9) {
74841
74844
  return _array(ZodArray, element, params9);
74842
74845
  }
74843
74846
  function keyof(schema) {
74844
- const shape3 = schema._zod.def.shape;
74845
- return _enum2(Object.keys(shape3));
74847
+ const shape4 = schema._zod.def.shape;
74848
+ return _enum2(Object.keys(shape4));
74846
74849
  }
74847
74850
  var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
74848
74851
  _ensureDefaultMemoizer();
@@ -74894,26 +74897,26 @@ var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
74894
74897
  return util_exports.required(ZodNonOptional, this, args[0]);
74895
74898
  }
74896
74899
  });
74897
- function object(shape3, params9) {
74900
+ function object(shape4, params9) {
74898
74901
  const def = {
74899
74902
  type: "object",
74900
- shape: shape3 ?? {},
74903
+ shape: shape4 ?? {},
74901
74904
  ...util_exports.normalizeParams(params9)
74902
74905
  };
74903
74906
  return new ZodObject(def);
74904
74907
  }
74905
- function strictObject(shape3, params9) {
74908
+ function strictObject(shape4, params9) {
74906
74909
  return new ZodObject({
74907
74910
  type: "object",
74908
- shape: shape3,
74911
+ shape: shape4,
74909
74912
  catchall: never(),
74910
74913
  ...util_exports.normalizeParams(params9)
74911
74914
  });
74912
74915
  }
74913
- function looseObject(shape3, params9) {
74916
+ function looseObject(shape4, params9) {
74914
74917
  return new ZodObject({
74915
74918
  type: "object",
74916
- shape: shape3,
74919
+ shape: shape4,
74917
74920
  catchall: unknown(),
74918
74921
  ...util_exports.normalizeParams(params9)
74919
74922
  });
@@ -75452,8 +75455,8 @@ var meta2 = meta;
75452
75455
  var ZodInstanceOf = /* @__PURE__ */ $constructor("ZodInstanceOf", (inst, def) => {
75453
75456
  ZodCustom.init(inst, def);
75454
75457
  }, {
75455
- properties(shape3, params9) {
75456
- return this.check(_properties(shape3, params9));
75458
+ properties(shape4, params9) {
75459
+ return this.check(_properties(shape4, params9));
75457
75460
  }
75458
75461
  });
75459
75462
  function _instanceof(cls, params9 = {}) {
@@ -76039,13 +76042,13 @@ function convertBaseSchema(schema, ctx) {
76039
76042
  break;
76040
76043
  }
76041
76044
  case "object": {
76042
- const shape3 = {};
76045
+ const shape4 = {};
76043
76046
  const properties2 = schema.properties || {};
76044
76047
  const requiredSet = new Set(schema.required || []);
76045
76048
  const additionalSchema = typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : void 0;
76046
76049
  for (const [key3, propSchema] of Object.entries(properties2)) {
76047
76050
  const propZodSchema = convertSchema(propSchema, ctx);
76048
- assignProp(shape3, key3, requiredSet.has(key3) ? propZodSchema : propZodSchema.optional());
76051
+ assignProp(shape4, key3, requiredSet.has(key3) ? propZodSchema : propZodSchema.optional());
76049
76052
  }
76050
76053
  if (schema.patternProperties) {
76051
76054
  const patternProps = schema.patternProperties;
@@ -76057,8 +76060,8 @@ function convertBaseSchema(schema, ctx) {
76057
76060
  looseRecords.push(z.looseRecord(keySchema, patternValue));
76058
76061
  }
76059
76062
  const schemasToIntersect = [];
76060
- if (Object.keys(shape3).length > 0) {
76061
- schemasToIntersect.push(z.object(shape3).passthrough());
76063
+ if (Object.keys(shape4).length > 0) {
76064
+ schemasToIntersect.push(z.object(shape4).passthrough());
76062
76065
  }
76063
76066
  schemasToIntersect.push(...looseRecords);
76064
76067
  if (schemasToIntersect.length === 0) {
@@ -76073,7 +76076,7 @@ function convertBaseSchema(schema, ctx) {
76073
76076
  zodSchema = result;
76074
76077
  }
76075
76078
  if (schema.additionalProperties === false) {
76076
- const propertyKeys = Object.keys(shape3);
76079
+ const propertyKeys = Object.keys(shape4);
76077
76080
  const patterns = patternKeys.map((p2) => new RegExp(p2));
76078
76081
  const basePatternSchema = zodSchema;
76079
76082
  zodSchema = zodSchema.check((payload2) => {
@@ -76098,7 +76101,7 @@ function convertBaseSchema(schema, ctx) {
76098
76101
  });
76099
76102
  }
76100
76103
  } else {
76101
- const objectSchema = z.object(shape3);
76104
+ const objectSchema = z.object(shape4);
76102
76105
  if (schema.additionalProperties === false) {
76103
76106
  zodSchema = objectSchema.strict();
76104
76107
  } else if (additionalSchema) {
@@ -84950,6 +84953,51 @@ var TraceCheckSchema = external_exports.strictObject({
84950
84953
  message: "status applies to called; not_called always counts every attempt",
84951
84954
  path: ["status"]
84952
84955
  });
84956
+ var TOOL_NAME_PATTERN = /^[A-Za-z_][\w.-]{0,127}$/;
84957
+ var ToolObservationSchema = external_exports.strictObject({
84958
+ tool: external_exports.string().regex(TOOL_NAME_PATTERN),
84959
+ at: duration6("Offset from the start of the production trace, e.g. 3s200ms"),
84960
+ /** When the call returned, as an offset like `at`: a test that reaches this answer has reached that time. */
84961
+ end: duration6("Offset from the start of the production trace when the call returned").optional(),
84962
+ args: external_exports.unknown().optional(),
84963
+ /** What the tool function returned. A recorded failure has `error` instead. */
84964
+ result: external_exports.unknown().optional(),
84965
+ error: external_exports.string().optional(),
84966
+ /** The framework's envelope as the trace held it (an MCP CallToolResult, a LangChain ToolMessage), for replay over MCP. */
84967
+ wrap: external_exports.enum(["mcp", "langchain", "output"]).optional(),
84968
+ raw: external_exports.unknown().optional(),
84969
+ call_id: external_exports.string().optional()
84970
+ }).refine((o) => o.error === void 0 || o.result === void 0, { message: "a recorded call has a result or an error, not both" });
84971
+ var ToolExampleSchema = external_exports.strictObject({
84972
+ trace: external_exports.string().optional(),
84973
+ at: duration6("Offset from the start of that trace"),
84974
+ args: external_exports.unknown().optional(),
84975
+ result: external_exports.unknown().optional(),
84976
+ error: external_exports.string().optional()
84977
+ });
84978
+ var SceneToolSchema = external_exports.strictObject({
84979
+ /** A JSON lines file next to the scene, one recorded call per line (`ancha run` reads it into `recorded`). */
84980
+ observations: external_exports.string().regex(/^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/, "a path relative to the scene file, without ..").optional(),
84981
+ recorded: external_exports.array(ToolObservationSchema).optional(),
84982
+ /** Calls from other traces of this agent, so a simulated answer can follow how the tool behaved there. */
84983
+ examples: external_exports.array(ToolExampleSchema).optional(),
84984
+ /** A call production never made: simulated (the default for a read), a tool error (the default for a write), or the twin. */
84985
+ unrecorded: external_exports.enum(["simulate", "fail", "twin"]).optional(),
84986
+ /** The twin that answers what production never recorded (TRACE_PLAN_V2 §5.3). */
84987
+ twin: external_exports.string().optional(),
84988
+ /** The agent reaches this tool over MCP: in a test its client points at {{tools.mcp_url}}, so there is nothing to wrap. */
84989
+ mcp: external_exports.literal(true).optional(),
84990
+ /** `ancha run --allow-unwrapped`: the agent may call this tool for real (it does not wrap it), so the test does not stop. */
84991
+ allow_unwrapped: external_exports.literal(true).optional(),
84992
+ /** Changes something (a refund, an email): an unrecorded call is never answered by invention unless set to simulate. */
84993
+ write: external_exports.boolean().optional(),
84994
+ description: external_exports.string().optional(),
84995
+ schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
84996
+ });
84997
+ var TriggerSchema = external_exports.strictObject({
84998
+ task: external_exports.string().optional(),
84999
+ input: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
85000
+ });
84953
85001
  var CheckSchema = external_exports.union([
84954
85002
  external_exports.strictObject({ id: external_exports.string(), state: StateCheckSchema }),
84955
85003
  external_exports.strictObject({ id: external_exports.string(), trace: TraceCheckSchema }),
@@ -84971,6 +85019,8 @@ var SceneSchema = external_exports.strictObject({
84971
85019
  skip_idle: external_exports.boolean().optional(),
84972
85020
  timeout: duration6("Per-trial time budget, e.g. 5m").default("5m"),
84973
85021
  task: external_exports.string().optional(),
85022
+ trigger: TriggerSchema.optional(),
85023
+ tools: external_exports.record(external_exports.string().regex(TOOL_NAME_PATTERN, "a tool name as the model saw it"), SceneToolSchema).optional(),
84974
85024
  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() }),
84975
85025
  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(),
84976
85026
  people: PeopleSchema.optional(),
@@ -86103,6 +86153,36 @@ function twinIssues(scene2) {
86103
86153
  });
86104
86154
  return issues;
86105
86155
  }
86156
+ function toolIssues(scene2) {
86157
+ const issues = [];
86158
+ for (const [name5, tool] of Object.entries(scene2.tools ?? {})) {
86159
+ const path4 = `tools.${name5}`;
86160
+ if (tool.twin !== void 0) {
86161
+ if (!isTwinName(tool.twin)) issues.push({ path: `${path4}.twin`, message: `unsupported twin ${tool.twin}`, hint: `supported twins: ${SUPPORTED_TWINS.join(", ")}` });
86162
+ 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}]` });
86163
+ }
86164
+ 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` });
86165
+ if (tool.observations !== void 0 && tool.recorded === void 0) {
86166
+ 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" });
86167
+ }
86168
+ tool.recorded?.forEach((o, i) => {
86169
+ if (o.tool !== name5) issues.push({ path: `${path4}.recorded[${i}].tool`, message: `a call to ${o.tool} recorded under ${name5}` });
86170
+ });
86171
+ }
86172
+ if (scene2.tools && Object.keys(scene2.tools).length) {
86173
+ scene2.checks.forEach((check3, i) => {
86174
+ if (!("trace" in check3)) return;
86175
+ for (const key3 of ["called", "not_called"]) {
86176
+ const patterns = check3.trace[key3] === void 0 ? [] : [].concat(check3.trace[key3]);
86177
+ patterns.forEach((pattern) => {
86178
+ const bare = /^([A-Za-z_][\w.-]{0,127})(?:\s+\{.*\})?$/s.exec(pattern.trim());
86179
+ 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>"` });
86180
+ });
86181
+ }
86182
+ });
86183
+ }
86184
+ return issues;
86185
+ }
86106
86186
  function refName5(ref20) {
86107
86187
  try {
86108
86188
  return parseRef(ref20).name;
@@ -86484,7 +86564,7 @@ function parseScene(input2) {
86484
86564
  throw shapeError(parsed3.error.issues.flatMap((issue5) => fromZodIssue(issue5, [], input2)));
86485
86565
  }
86486
86566
  const scene2 = parsed3.data;
86487
- const issues = [...twinIssues(scene2), ...validateRefs(scene2), ...ruleIssues(scene2), ...worldIssues(scene2), ...peopleIssues(scene2)];
86567
+ const issues = [...twinIssues(scene2), ...toolIssues(scene2), ...validateRefs(scene2), ...ruleIssues(scene2), ...worldIssues(scene2), ...peopleIssues(scene2)];
86488
86568
  if (issues.length > 0) throw sceneError(issues);
86489
86569
  const pd = scene2.seed.pagerduty;
86490
86570
  if (pd && pd.default_service === void 0 && pd.services.length === 1) pd.default_service = `$${pd.services[0].ref}`;
@@ -86494,6 +86574,7 @@ function parseScene(input2) {
86494
86574
  if (link5.from === "datadog" && link5.handle === void 0 && service) link5.handle = `pagerduty-${service.name}`;
86495
86575
  if (link5.from === "pagerduty" && link5.channel === void 0 && service?.slack_channel !== void 0) link5.channel = service.slack_channel;
86496
86576
  });
86577
+ if (scene2.task === void 0 && scene2.trigger?.task !== void 0) scene2.task = scene2.trigger.task;
86497
86578
  return { ...scene2, twins: scene2.twins.filter(isTwinName), pass: scene2.pass ?? scene2.checks.map((c) => c.id) };
86498
86579
  }
86499
86580
  var ChecksSchema = external_exports.array(CheckSchema);
@@ -86513,6 +86594,54 @@ function parseChecks(input2) {
86513
86594
  { hint: "run `ancha scene schema` for the check format" }
86514
86595
  );
86515
86596
  }
86597
+ var PROSE_KEYS = /* @__PURE__ */ new Set(["judge", "task", "text", "value", "about", "message"]);
86598
+ var FIX_SHOWN = 120;
86599
+ function cutProseIssues(doc, text21, lineCounter) {
86600
+ const issues = [];
86601
+ (0, import_yaml.visit)(doc, {
86602
+ Pair(_, pair, ancestors2) {
86603
+ const value4 = pair.value;
86604
+ if (!(0, import_yaml.isScalar)(pair.key) || !PROSE_KEYS.has(String(pair.key.value)) || !(0, import_yaml.isScalar)(value4)) return;
86605
+ if (value4.type !== "PLAIN" || typeof value4.value !== "string" || !value4.range) return;
86606
+ const comment8 = /^[ \t]+#([^\r\n]*)/.exec(text21.slice(value4.range[1]));
86607
+ if (comment8 === null) return;
86608
+ const key3 = String(pair.key.value);
86609
+ const { line: line2 } = lineCounter.linePos(value4.range[0]);
86610
+ const meant = `${value4.value} #${comment8[1].trimEnd()}`;
86611
+ const fix = `${key3}: ${JSON.stringify(meant)}`;
86612
+ issues.push({
86613
+ path: `${pathOf(ancestors2, pair)} (line ${line2})`,
86614
+ message: `the text stops at " #": YAML reads ${JSON.stringify(`#${comment8[1].trimEnd()}`)} as a comment and keeps only ${JSON.stringify(value4.value)}`,
86615
+ hint: fix.length <= FIX_SHOWN ? `quote the text: ${fix}` : `quote the text, e.g. ${key3}: "\u2026", or write it as a block under ${key3}: |`
86616
+ });
86617
+ }
86618
+ });
86619
+ return issues;
86620
+ }
86621
+ function pathOf(ancestors2, pair) {
86622
+ const segments2 = [];
86623
+ ancestors2.forEach((node5, i) => {
86624
+ if ((0, import_yaml.isPair)(node5) && (0, import_yaml.isScalar)(node5.key)) segments2.push(String(node5.key.value));
86625
+ else if ((0, import_yaml.isSeq)(node5)) segments2.push(node5.items.indexOf(ancestors2[i + 1] ?? pair));
86626
+ });
86627
+ return formatPath([...segments2, String(pair.key.value)]);
86628
+ }
86629
+ function parseSceneYaml(text21) {
86630
+ const lineCounter = new import_yaml.LineCounter();
86631
+ const doc = (0, import_yaml.parseDocument)(text21, { lineCounter, prettyErrors: false });
86632
+ if (doc.errors.length > 0) {
86633
+ const issues = doc.errors.map((e) => {
86634
+ const { line: line2, col } = lineCounter.linePos(e.pos[0]);
86635
+ return { path: `line ${line2}, column ${col}`, message: e.message };
86636
+ });
86637
+ const atError = doc.errors.findIndex((e) => text21[e.pos[0]] === "@");
86638
+ if (atError >= 0) issues[atError].hint = "scene refs use $, e.g. $alice \u2014 YAML reserves @";
86639
+ throw sceneError(issues, doc.errors[0]);
86640
+ }
86641
+ const cut = cutProseIssues(doc, text21, lineCounter);
86642
+ if (cut.length > 0) throw sceneError(cut);
86643
+ return doc.toJS();
86644
+ }
86516
86645
 
86517
86646
  // packages/core/src/harness-issues.ts
86518
86647
  function collectHarnessIssues(trace, checks) {
@@ -87160,6 +87289,10 @@ function toolConnectionEnvironment(services2) {
87160
87289
  for (const [key3, value4] of Object.entries(values2)) if (value4 !== void 0) result[key3] = value4;
87161
87290
  };
87162
87291
  switch (tool) {
87292
+ case "tools":
87293
+ add({ ANCHA_TOOLS_URL: s.url, ANCHA_TOOLS_TOKEN: s.token });
87294
+ break;
87295
+ // the agent's own tools in a test made from a trace (TRACE_PLAN_V2 §3)
87163
87296
  case "slack":
87164
87297
  add({ SLACK_API_URL: s.url, SLACK_BOT_TOKEN: s.token, SLACK_SIGNING_SECRET: s.signingSecret, SLACK_APP_TOKEN: s.appToken });
87165
87298
  break;
@@ -87606,6 +87739,7 @@ var TraceRecorder = class {
87606
87739
 
87607
87740
  // packages/server/src/twin.ts
87608
87741
  var GAP_HEADER = "x-ancha-gap";
87742
+ var SETUP_ISSUE_HEADER = "x-ancha-setup-issue";
87609
87743
  var INTERNAL_ERROR_HEADER = "x-ancha-internal-error";
87610
87744
  function gapMessage(c) {
87611
87745
  return `ancha: not implemented: ${c.req.method} ${new URL(c.req.url).pathname}`;
@@ -88468,8 +88602,8 @@ function markHandled(env, ids2) {
88468
88602
  var TABLE = "world_milestones";
88469
88603
  var isPredicateMilestone2 = (milestone) => !("called" in milestone) && !("message" in milestone);
88470
88604
  function milestoneKey(predicate) {
88471
- 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;
88472
- return JSON.stringify(canonical4(predicate));
88605
+ 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;
88606
+ return JSON.stringify(canonical5(predicate));
88473
88607
  }
88474
88608
  function tracked(env) {
88475
88609
  const out = /* @__PURE__ */ new Map();
@@ -88966,7 +89100,28 @@ function evaluateWithin(env, within, calls2) {
88966
89100
 
88967
89101
  // packages/server/src/checks.ts
88968
89102
  var LIST_LIMIT = 10;
88969
- 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';
89103
+ 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}"`;
89104
+ function contains(have, want) {
89105
+ if (want === null || typeof want !== "object") return String(have) === String(want);
89106
+ if (Array.isArray(want)) return Array.isArray(have) && want.every((w, i) => contains(have[i], w));
89107
+ if (have === null || typeof have !== "object" || Array.isArray(have)) return false;
89108
+ return Object.entries(want).every(([k, w]) => contains(have[k], w));
89109
+ }
89110
+ function toolPattern(pattern, tools) {
89111
+ const m = /^([A-Za-z_][\w.-]{0,127})(?:\s+(\{.*\}))?$/s.exec(pattern);
89112
+ if (!m || !tools?.has(m[1])) return void 0;
89113
+ let args;
89114
+ if (m[2] !== void 0) {
89115
+ try {
89116
+ args = parseSceneYaml(m[2]);
89117
+ } catch {
89118
+ args = void 0;
89119
+ }
89120
+ 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 });
89121
+ }
89122
+ const path4 = `/tools/${m[1]}`;
89123
+ return (e) => e.source === "agent" && e.service === "tools" && e.method === "POST" && e.path === path4 && (args === void 0 || contains(e.request?.args, args));
89124
+ }
88970
89125
  function glob(pattern, caseInsensitive) {
88971
89126
  const fold2 = (s) => caseInsensitive ? s.toLowerCase() : s;
88972
89127
  const pieces = fold2(pattern).split("*");
@@ -88987,9 +89142,11 @@ function glob(pattern, caseInsensitive) {
88987
89142
  return true;
88988
89143
  };
88989
89144
  }
88990
- function compileTracePattern(p2) {
89145
+ function compileTracePattern(p2, tools) {
88991
89146
  const pattern = p2.trim();
88992
89147
  if (pattern === "*") return (e) => e.source === "agent";
89148
+ const tool = toolPattern(pattern, tools);
89149
+ if (tool) return tool;
88993
89150
  const parts3 = /^(\S+)\s+(\S+)$/.exec(pattern);
88994
89151
  if (!parts3) {
88995
89152
  throw new AnchaError("USAGE", `invalid trace pattern "${p2}": expected "<METHOD> <PATH>" or "*"`, { hint: PATTERN_HINT });
@@ -89017,12 +89174,13 @@ function failure2(e) {
89017
89174
  if (typeof body6 !== "object" || body6 === null) return void 0;
89018
89175
  const r = body6;
89019
89176
  if (e.service === "slack" && r.ok === false) return `ok: false${typeof r.error === "string" ? `, ${r.error}` : ""}`;
89177
+ if (e.service === "tools" && typeof r.error === "string") return `the tool's error: ${r.error}`;
89020
89178
  if (/\/graphql$/.test(e.path) && Array.isArray(r.errors) && r.errors.length > 0 && (r.data === void 0 || r.data === null)) return "GraphQL errors";
89021
89179
  return void 0;
89022
89180
  }
89023
- function calledPart(patterns, calls2, anyStatus) {
89181
+ function calledPart(patterns, calls2, anyStatus, tools) {
89024
89182
  const hits = patterns.map((p2) => {
89025
- const attempts = calls2.filter(compileTracePattern(p2));
89183
+ const attempts = calls2.filter(compileTracePattern(p2, tools));
89026
89184
  return { p: p2, attempts, worked: anyStatus ? attempts : attempts.filter((e) => failure2(e) === void 0) };
89027
89185
  });
89028
89186
  const missing4 = hits.filter((h) => h.worked.length === 0);
@@ -89048,8 +89206,8 @@ function calledPart(patterns, calls2, anyStatus) {
89048
89206
  ].join(" ");
89049
89207
  return { passed: false, expected, actual, explanation, evidence: unique2([...matched, ...failed.flatMap((h) => h.attempts)]) };
89050
89208
  }
89051
- function notCalledPart(patterns, calls2) {
89052
- const matchers = patterns.map(compileTracePattern);
89209
+ function notCalledPart(patterns, calls2, tools) {
89210
+ const matchers = patterns.map((p2) => compileTracePattern(p2, tools));
89053
89211
  const offenders = calls2.filter((c) => matchers.some((m) => m(c)));
89054
89212
  const expected = `agent never calls ${patterns.join(" or ")}`;
89055
89213
  if (offenders.length === 0) {
@@ -89070,13 +89228,13 @@ function notCalledPart(patterns, calls2) {
89070
89228
  evidence: offenders
89071
89229
  };
89072
89230
  }
89073
- function evaluateTrace(trace, calls2) {
89231
+ function evaluateTrace(trace, calls2, tools) {
89074
89232
  const called = asList(trace.called);
89075
89233
  const notCalled = asList(trace.not_called);
89076
89234
  if (called.length === 0 && notCalled.length === 0) {
89077
89235
  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" }' });
89078
89236
  }
89079
- const parts3 = [...called.length > 0 ? [calledPart(called, calls2, trace.status === "any")] : [], ...notCalled.length > 0 ? [notCalledPart(notCalled, calls2)] : []];
89237
+ const parts3 = [...called.length > 0 ? [calledPart(called, calls2, trace.status === "any", tools)] : [], ...notCalled.length > 0 ? [notCalledPart(notCalled, calls2, tools)] : []];
89080
89238
  return {
89081
89239
  passed: parts3.every((p2) => p2.passed),
89082
89240
  expected: parts3.map((p2) => p2.expected).join("; "),
@@ -89146,10 +89304,11 @@ function evaluateProcess(env, check3, calls2) {
89146
89304
  if ("decided" in check3) return inspectPeoplePredicate(env, { decided: check3.decided }, atMs);
89147
89305
  if ("message" in check3) return evaluateMessageCheck(env, check3.message);
89148
89306
  if ("never" in check3) return evaluateNever(env, check3.never);
89149
- const agent = { first: (pattern) => calls2().find(compileTracePattern(pattern)) };
89307
+ const agent = { first: (pattern) => calls2().find(compileTracePattern(pattern, sceneTools(env))) };
89150
89308
  if ("before" in check3) return evaluateBefore(env, check3.before, agent);
89151
89309
  return evaluateWithin(env, check3.within, agent);
89152
89310
  }
89311
+ var sceneTools = (env) => new Set(Object.keys(env.scene.tools ?? {}));
89153
89312
  function errored(label5, e) {
89154
89313
  const message6 = e instanceof Error ? e.message : String(e);
89155
89314
  const hint = e instanceof AnchaError ? e.hint : void 0;
@@ -89179,7 +89338,7 @@ function evaluateChecks(env, checks = env.scene.checks) {
89179
89338
  let outcome3;
89180
89339
  let error63;
89181
89340
  try {
89182
- outcome3 = "state" in check3 ? evaluateState(env, check3.state) : "trace" in check3 ? evaluateTrace(check3.trace, agentCalls2()) : evaluateProcess(env, check3, agentCalls2);
89341
+ outcome3 = "state" in check3 ? evaluateState(env, check3.state) : "trace" in check3 ? evaluateTrace(check3.trace, agentCalls2(), sceneTools(env)) : evaluateProcess(env, check3, agentCalls2);
89183
89342
  } catch (e) {
89184
89343
  error63 = e instanceof Error ? e.message : String(e);
89185
89344
  outcome3 = errored("state" in check3 ? Object.keys(check3.state).join(", ") || "state" : checkKind(check3), e);
@@ -91993,12 +92152,12 @@ function persistMessageLinks(ctx, row, links2 = []) {
91993
92152
  ctx.store.db.prepare("INSERT INTO slack_message_links VALUES (?, ?, ?, ?, ?)").run(row.channel_id, row.ts, link5.pointer, link5.service, link5.path);
91994
92153
  }
91995
92154
  }
91996
- function materializeMessageLinks(ctx, row, shape3) {
92155
+ function materializeMessageLinks(ctx, row, shape4) {
91997
92156
  if (!ctx.serviceUrls) return;
91998
92157
  for (const link5 of messageLinks(ctx, row)) {
91999
92158
  const root2 = ctx.serviceUrls[link5.service];
92000
92159
  if (!root2) throw new AnchaError("INTERNAL", `Missing local ${link5.service} service for Slack message link`);
92001
- replaceLink(shape3, link5, root2.replace(/\/$/, "") + link5.path);
92160
+ replaceLink(shape4, link5, root2.replace(/\/$/, "") + link5.path);
92002
92161
  }
92003
92162
  }
92004
92163
 
@@ -94809,13 +94968,13 @@ function batch(ctx, type, operation2, raw3, url3) {
94809
94968
  return { status: 204 };
94810
94969
  });
94811
94970
  }
94812
- const traceIds = items.map((item2) => item2.objectWriteTraceId), traced2 = operation2 === "create" && traceIds.some((value4) => value4 !== void 0);
94813
- 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.");
94971
+ const traceIds = items.map((item2) => item2.objectWriteTraceId), traced3 = operation2 === "create" && traceIds.some((value4) => value4 !== void 0);
94972
+ 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.");
94814
94973
  const execute3 = (item2) => {
94815
94974
  bodyObject2(item2, operation2 === "create" ? ["properties", "associations", "objectWriteTraceId"] : ["id", "properties"]);
94816
94975
  return project2(ctx, type, operation2 === "create" ? createRecord(ctx, type, item2) : updateRecord(ctx, type, identifier(item2.id), { properties: item2.properties }));
94817
94976
  };
94818
- if (traced2) return withMutation(ctx, () => {
94977
+ if (traced3) return withMutation(ctx, () => {
94819
94978
  const results = [], errors2 = [];
94820
94979
  let gap5 = false;
94821
94980
  for (const item2 of items) {
@@ -98070,7 +98229,7 @@ function explainFailedChecks(env, results, checks = env.scene.checks) {
98070
98229
  if (!failed.length) return [];
98071
98230
  const messages = attemptMessages(env);
98072
98231
  const agentCalls2 = env.trace.list().filter((entry2) => entry2.source === "agent");
98073
- const calls2 = { first: (pattern) => agentCalls2.find(compileTracePattern(pattern)) };
98232
+ const calls2 = { first: (pattern) => agentCalls2.find(compileTracePattern(pattern, sceneTools(env))) };
98074
98233
  const start = env.clock.startTime.getTime();
98075
98234
  return failed.flatMap((result) => {
98076
98235
  const check3 = checks.find((candidate) => candidate.id === result.id);
@@ -98208,7 +98367,234 @@ function readWorldSnapshot(bytes2) {
98208
98367
  }
98209
98368
  }
98210
98369
 
98370
+ // packages/server/src/agent-tools/simulate.ts
98371
+ 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 and with the writes the agent already made in this test, 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>"}.`;
98372
+ var SCHEMA5 = { name: "tool_answer", schema: { type: "object", additionalProperties: false, properties: { result_json: { type: "string" }, error: { type: "string" } } } };
98373
+ function shape(value4) {
98374
+ if (Array.isArray(value4)) return `[${value4.length ? shape(value4[0]) : ""}]`;
98375
+ if (value4 === null || typeof value4 !== "object") return value4 === null ? "null" : typeof value4;
98376
+ return `{${Object.keys(value4).sort().map((k) => `${k}:${value4[k] === null ? "null" : Array.isArray(value4[k]) ? "list" : typeof value4[k]}`).join(",")}}`;
98377
+ }
98378
+ function sameShape(result, recorded2) {
98379
+ if (!recorded2.length) return true;
98380
+ const top = (v) => Array.isArray(v) ? "list" : v === null ? "null" : typeof v;
98381
+ if (!recorded2.some((r) => top(r) === top(result) || top(r) === "null")) return false;
98382
+ const objects = recorded2.filter((r) => r !== null && typeof r === "object" && !Array.isArray(r));
98383
+ if (!objects.length || result === null || typeof result !== "object" || Array.isArray(result)) return true;
98384
+ const got = result;
98385
+ const always = Object.keys(objects[0]).filter((k) => objects.every((o) => k in o));
98386
+ const types = /* @__PURE__ */ new Map();
98387
+ 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)));
98388
+ 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))));
98389
+ }
98390
+ async function simulate(model, request4, signal) {
98391
+ const recorded2 = (request4.tool?.recorded ?? []).map((o) => ({ args: o.args, at: o.at, ...o.error !== void 0 ? { error: o.error } : { result: o.result } }));
98392
+ const results = recorded2.filter((o) => "result" in o).map((o) => o.result);
98393
+ const user8 = JSON.stringify({
98394
+ tool: { name: request4.name, ...request4.tool?.description && { description: request4.tool.description }, ...request4.tool?.schema && { arguments: request4.tool.schema }, ...request4.tool?.write && { changes_something: true } },
98395
+ production_recorded: recorded2.slice(-20),
98396
+ ...request4.tool?.examples?.length && { other_production_runs_of_this_agent: request4.tool.examples.slice(-30) },
98397
+ ...results.length && { result_shape: shape(results[0]) },
98398
+ writes_in_this_test: request4.writes.slice(-20),
98399
+ call: { arguments: request4.args, ...request4.repeat && { production_made_this_exact_call: request4.repeat.recorded, this_is_call_number: request4.repeat.call } },
98400
+ // Time moves on as the agent waits: a status read later may say what a real one would say by then.
98401
+ ...request4.time && { time: {
98402
+ ...request4.time.start && { now: new Date(Date.parse(request4.time.start) + request4.time.now_ms).toISOString() },
98403
+ ...request4.time.now_ms > request4.time.last_recorded_ms && { seconds_since_productions_last_answer: Math.round((request4.time.now_ms - request4.time.last_recorded_ms) / 1e3) }
98404
+ } }
98405
+ });
98406
+ let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "";
98407
+ for (let attempt = 0; attempt < 2; attempt++) {
98408
+ const answer = await model.complete({ kind: "simulate", person: request4.name, system: SYSTEM, user: feedback ? `${user8}
98409
+
98410
+ ${feedback}` : user8, schema: SCHEMA5, temperature: 0, maxTokens: 1200 }, signal);
98411
+ inputTokens += answer.inputTokens;
98412
+ outputTokens += answer.outputTokens;
98413
+ costUsd += answer.costUsd;
98414
+ model_ = answer.model;
98415
+ const out = answer.output;
98416
+ if (typeof out?.error === "string" && out.error && out.result_json === void 0) return { error: out.error, inputTokens, outputTokens, costUsd, model: model_ };
98417
+ let result;
98418
+ try {
98419
+ result = JSON.parse(String(out?.result_json));
98420
+ } catch {
98421
+ feedback = "Your result_json was not valid JSON. Answer again.";
98422
+ continue;
98423
+ }
98424
+ if (sameShape(result, results)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
98425
+ feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(results[0])}. Answer again in that shape.`;
98426
+ }
98427
+ throw new PeopleModelError(`the simulated answer to ${request4.name} did not have the shape of production's results`);
98428
+ }
98429
+
98430
+ // packages/server/src/agent-tools/index.ts
98431
+ var AGENT_TOOLS = "tools";
98432
+ function canonical2(value4) {
98433
+ 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);
98434
+ }
98435
+ var recordedOf = /* @__PURE__ */ new WeakMap();
98436
+ function recorded(ctx, tool) {
98437
+ const tools = ctx.scene.tools ?? {};
98438
+ let byTool = recordedOf.get(tools);
98439
+ if (!byTool) {
98440
+ byTool = new Map(Object.entries(tools).map(([name5, t]) => [name5, (t.recorded ?? []).map((o) => {
98441
+ const atMs = parseDuration(o.at);
98442
+ return { ...o, atMs, endMs: o.end ? parseDuration(o.end) : atMs, key: canonical2(o.args) };
98443
+ }).sort((a, b) => a.atMs - b.atMs)]));
98444
+ recordedOf.set(tools, byTool);
98445
+ }
98446
+ return byTool.get(tool) ?? [];
98447
+ }
98448
+ function migrate6(db2) {
98449
+ db2.exec(`CREATE TABLE agent_tool_calls (key TEXT PRIMARY KEY, n INTEGER NOT NULL);
98450
+ CREATE TABLE agent_tool_state (k TEXT PRIMARY KEY, v TEXT NOT NULL);`);
98451
+ }
98452
+ var getState = (ctx, k) => ctx.store.db.prepare("SELECT v FROM agent_tool_state WHERE k=?").get(k)?.v;
98453
+ 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);
98454
+ var SIMULATION_LIMIT = () => Number(process.env.ANCHA_SIMULATE_MAX ?? 30);
98455
+ var simulationOn = (ctx) => process.env.ANCHA_SIMULATE !== "0" && ctx.model !== void 0;
98456
+ function keepUp(ctx) {
98457
+ const behind = withRead(ctx, () => Number(getState(ctx, "reached") ?? 0)) - ctx.clock.elapsedMs();
98458
+ if (behind > 0) ctx.clock.advance(behind);
98459
+ }
98460
+ function decide(ctx, name5, args) {
98461
+ const tool = ctx.scene.tools?.[name5];
98462
+ const key3 = canonical2(args), callKey = `${name5} ${key3}`;
98463
+ const same2 = recorded(ctx, name5).filter((o) => o.key === key3);
98464
+ const n = ctx.store.db.prepare("SELECT n FROM agent_tool_calls WHERE key=?").get(callKey)?.n ?? 0;
98465
+ ctx.store.db.prepare("INSERT INTO agent_tool_calls (key, n) VALUES (?, 1) ON CONFLICT(key) DO UPDATE SET n=n+1").run(callKey);
98466
+ const policy = tool?.unrecorded ?? (tool?.write ? "fail" : "simulate");
98467
+ const reached = Number(getState(ctx, "reached") ?? 0);
98468
+ const cached2 = getState(ctx, `sim:${callKey}`);
98469
+ if (cached2 !== void 0) {
98470
+ const hit = JSON.parse(cached2);
98471
+ if (tool?.write || hit.reached >= reached) return hit.answer;
98472
+ }
98473
+ if (n < same2.length) {
98474
+ let index = n;
98475
+ for (let i = same2.length - 1; i > index; i--) if (same2[i].atMs <= reached) {
98476
+ index = i;
98477
+ break;
98478
+ }
98479
+ const o = same2[index];
98480
+ setState(ctx, "reached", String(Math.max(reached, o.endMs)));
98481
+ 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 } };
98482
+ }
98483
+ if (tool?.twin !== void 0 || policy === "twin") return { source: "twin", passthrough: true };
98484
+ const repeat = same2.length ? { recorded: same2.length, call: n + 1 } : void 0;
98485
+ const last = same2.at(-1) ?? recorded(ctx, name5).at(-1), took = last ? last.endMs - last.atMs : 0;
98486
+ if (policy === "simulate" && simulationOn(ctx)) {
98487
+ 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` };
98488
+ const lastRecordedMs = Math.max(0, ...recorded(ctx, name5).map((o) => o.endMs));
98489
+ return { simulate: { name: name5, tool, args, ...repeat && { repeat }, time: { now_ms: Math.max(reached, ctx.clock.elapsedMs()), last_recorded_ms: lastRecordedMs, start: ctx.scene.start_time } }, cacheKey: callKey, reached, took };
98490
+ }
98491
+ if (repeat && !tool?.write) {
98492
+ const o = same2.at(-1);
98493
+ 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 } };
98494
+ }
98495
+ 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`;
98496
+ 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)" : "";
98497
+ return { source: "failed", error: `Ancha has no recorded answer for this call: ${why}${unsimulated}` };
98498
+ }
98499
+ function noteWrite(ctx, name5, args, a) {
98500
+ if (!ctx.scene.tools?.[name5]?.write || a.passthrough) return;
98501
+ const writes2 = JSON.parse(getState(ctx, "writes") ?? "[]");
98502
+ writes2.push({ tool: name5, args, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
98503
+ setState(ctx, "writes", JSON.stringify(writes2.slice(-50)));
98504
+ }
98505
+ function toolsToWrap(ctx) {
98506
+ return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.allow_unwrapped).map(([name5]) => name5).sort();
98507
+ }
98508
+ function registration(ctx, names3) {
98509
+ const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
98510
+ const wrapped = [.../* @__PURE__ */ new Set([...before, ...names3])].sort();
98511
+ setState(ctx, "wrapped", JSON.stringify(wrapped));
98512
+ return { wrapped, missing: toolsToWrap(ctx).filter((name5) => !wrapped.includes(name5)) };
98513
+ }
98514
+ function unwrappedMessage(missing4, noneWrapped = false) {
98515
+ const [first] = missing4, it = missing4.length === 1 ? "it" : "them";
98516
+ 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." : "");
98517
+ }
98518
+ function authorized(c) {
98519
+ const token2 = JSON.parse(c.env.ctx.store.meta.get(`credentials:${AGENT_TOOLS}`) ?? "{}").token;
98520
+ return token2 !== void 0 && c.req.header("authorization") === `Bearer ${token2}`;
98521
+ }
98522
+ function agentToolsService() {
98523
+ const app2 = new Hono3();
98524
+ app2.use("*", async (c, next2) => authorized(c) ? next2() : c.json({ error: "send Authorization: Bearer $ANCHA_TOOLS_TOKEN" }, 401));
98525
+ app2.get("/tools", (c) => withRead(c.env.ctx, () => c.json({ tools: Object.entries(c.env.ctx.scene.tools ?? {}).map(([name5, t]) => ({
98526
+ name: name5,
98527
+ ...t.description && { description: t.description },
98528
+ ...t.schema && { schema: t.schema },
98529
+ recorded: t.recorded?.length ?? 0,
98530
+ ...t.twin && { twin: t.twin },
98531
+ ...t.write && { write: true }
98532
+ })), wrap: toolsToWrap(c.env.ctx) })));
98533
+ app2.post("/register", async (c) => {
98534
+ const body6 = await c.req.json().catch(() => ({}));
98535
+ const names3 = (Array.isArray(body6.tools) ? body6.tools : []).map((t) => typeof t === "string" ? t : t?.name).filter((n) => typeof n === "string");
98536
+ const { wrapped, missing: missing4 } = withMutation(c.env.ctx, () => registration(c.env.ctx, names3));
98537
+ if (body6.complete) withMutation(c.env.ctx, () => setState(c.env.ctx, "checked", "1"));
98538
+ if (body6.complete && missing4.length) return c.json({ error: unwrappedMessage(missing4, wrapped.length === 0), wrapped, missing: missing4, stop: true }, 409, { [SETUP_ISSUE_HEADER]: "1" });
98539
+ return c.json({ wrapped, missing: missing4 });
98540
+ });
98541
+ app2.post("/tools/:name", async (c) => {
98542
+ const name5 = c.req.param("name");
98543
+ const body6 = await c.req.json().catch(() => ({}));
98544
+ const stop = withMutation(c.env.ctx, () => {
98545
+ if (getState(c.env.ctx, "checked")) return void 0;
98546
+ setState(c.env.ctx, "checked", "1");
98547
+ const { wrapped, missing: missing4 } = registration(c.env.ctx, []);
98548
+ return missing4.length ? { error: unwrappedMessage(missing4, wrapped.length === 0), wrapped, missing: missing4, stop: true } : void 0;
98549
+ });
98550
+ if (stop) return c.json(stop, 409, { [SETUP_ISSUE_HEADER]: "1" });
98551
+ const ctx = c.env.ctx, args = body6.args ?? {};
98552
+ const decision2 = withMutation(ctx, () => decide(ctx, name5, args));
98553
+ if (!("simulate" in decision2)) {
98554
+ withMutation(ctx, () => noteWrite(ctx, name5, args, decision2));
98555
+ keepUp(ctx);
98556
+ return c.json(decision2);
98557
+ }
98558
+ let answered;
98559
+ try {
98560
+ const writes2 = withRead(ctx, () => JSON.parse(getState(ctx, "writes") ?? "[]"));
98561
+ const sim = await simulate(ctx.model, { ...decision2.simulate, writes: writes2 }, c.req.raw.signal);
98562
+ answered = { source: "simulated", ...sim.error !== void 0 ? { error: sim.error } : { result: sim.result }, cost_usd: Math.round(sim.costUsd * 1e6) / 1e6 };
98563
+ } catch (error63) {
98564
+ answered = { source: "failed", error: `Ancha has no recorded answer for this call and could not simulate one: ${error63 instanceof Error ? error63.message : String(error63)}` };
98565
+ }
98566
+ const answer = withMutation(ctx, () => {
98567
+ if (answered.source === "simulated") {
98568
+ const now10 = Math.max(Number(getState(ctx, "reached") ?? 0), decision2.reached + decision2.took);
98569
+ setState(ctx, "reached", String(now10));
98570
+ setState(ctx, `sim:${decision2.cacheKey}`, JSON.stringify({ answer: { ...answered, cost_usd: void 0 }, reached: now10 }));
98571
+ setState(ctx, "simulated", String(Number(getState(ctx, "simulated") ?? 0) + 1));
98572
+ }
98573
+ noteWrite(ctx, name5, args, answered);
98574
+ return answered;
98575
+ });
98576
+ keepUp(ctx);
98577
+ return c.json(answer);
98578
+ });
98579
+ app2.all("*", (c) => c.json({ error: `not a route of Ancha's tool service: ${c.req.method} ${new URL(c.req.url).pathname}` }, 404));
98580
+ return {
98581
+ // A built-in service, not a catalog twin: a scene gets it by having tools.
98582
+ name: AGENT_TOOLS,
98583
+ basePath: "",
98584
+ app: app2,
98585
+ migrate: migrate6,
98586
+ seed() {
98587
+ },
98588
+ credentials: (ctx) => ({ token: `ancha-tools-${ctx.secrets.hex(32)}` }),
98589
+ actions: {},
98590
+ checks: {},
98591
+ dumpState: (ctx) => ({ calls: ctx.store.db.prepare("SELECT key, n FROM agent_tool_calls ORDER BY key").all(), wrapped: JSON.parse(getState(ctx, "wrapped") ?? "[]") }),
98592
+ coverage: []
98593
+ };
98594
+ }
98595
+
98211
98596
  // packages/server/src/env.ts
98597
+ var agentTools = agentToolsService();
98212
98598
  var ENV_ID_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";
98213
98599
  function newEnvId() {
98214
98600
  let id12 = "";
@@ -98302,7 +98688,8 @@ var Environment = class _Environment {
98302
98688
  }
98303
98689
  return twin;
98304
98690
  });
98305
- this.mcpTokens = Object.freeze(Object.fromEntries((opts.mcpTools ?? []).filter((tool) => scene2.twins.some((name5) => name5 === tool)).map((tool) => [tool, randomBytes(32).toString("hex")])));
98691
+ if (Object.keys(scene2.tools ?? {}).length) this.twins.push(agentTools);
98692
+ 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")])));
98306
98693
  const realNow = opts.realNow ?? (() => Date.now());
98307
98694
  this.#realNow = realNow;
98308
98695
  let frozenRealNow = realNow();
@@ -98359,7 +98746,8 @@ var Environment = class _Environment {
98359
98746
  trace: this.trace,
98360
98747
  events: this.events,
98361
98748
  enqueueJob: (job) => this.scheduler.enqueue(job),
98362
- world: this.world
98749
+ world: this.world,
98750
+ ...this.peopleModel && { model: this.peopleModel }
98363
98751
  };
98364
98752
  this.#contexts.set(twin, ctx);
98365
98753
  }
@@ -98890,7 +99278,7 @@ var FILE_KEYS2 = ["version", "id", "owner", "sceneId", "createdAt", "expiresAt",
98890
99278
 
98891
99279
  // packages/server/src/twins/google-ads/db.ts
98892
99280
  var collections = { budgets: "campaignBudgets", campaigns: "campaigns", adGroups: "adGroups", ads: "adGroupAds", criteria: "adGroupCriteria" };
98893
- function migrate6(db2) {
99281
+ function migrate7(db2) {
98894
99282
  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)");
98895
99283
  }
98896
99284
  function config3(ctx) {
@@ -99857,11 +100245,11 @@ function googleAdsTwin() {
99857
100245
  throw e;
99858
100246
  }
99859
100247
  });
99860
- return { name: "google-ads", basePath: "", unprefixedPaths: /^\/v\d+\/customers[/:]/, app: app2, migrate: migrate6, seed: seed4, credentials: credentials3, actions: {}, checks: {}, dumpState: dumpState2, coverage: googleAdsCoverage };
100248
+ return { name: "google-ads", basePath: "", unprefixedPaths: /^\/v\d+\/customers[/:]/, app: app2, migrate: migrate7, seed: seed4, credentials: credentials3, actions: {}, checks: {}, dumpState: dumpState2, coverage: googleAdsCoverage };
99861
100249
  }
99862
100250
 
99863
100251
  // packages/server/src/twins/chatgpt-ads/db.ts
99864
- function migrate7(db2) {
100252
+ function migrate8(db2) {
99865
100253
  db2.exec(`CREATE TABLE chatgpt_ads_data(id INTEGER PRIMARY KEY CHECK(id=1),json TEXT NOT NULL);
99866
100254
  CREATE TABLE chatgpt_ads_credentials(principal_id TEXT PRIMARY KEY,token TEXT NOT NULL UNIQUE);
99867
100255
  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));
@@ -100076,9 +100464,9 @@ function pagination(rows7, query10, defaultLimit = 20, max = 500) {
100076
100464
  const selected2 = rows7.slice(start, Math.min(start + limit, end));
100077
100465
  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 };
100078
100466
  }
100079
- function canonical2(value4) {
100080
- if (Array.isArray(value4)) return `[${value4.map(canonical2).join(",")}]`;
100081
- if (value4 && typeof value4 === "object") return `{${Object.entries(value4).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical2(v)}`).join(",")}}`;
100467
+ function canonical3(value4) {
100468
+ if (Array.isArray(value4)) return `[${value4.map(canonical3).join(",")}]`;
100469
+ if (value4 && typeof value4 === "object") return `{${Object.entries(value4).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical3(v)}`).join(",")}}`;
100082
100470
  return JSON.stringify(value4);
100083
100471
  }
100084
100472
  function idempotency(c, access2, kind, body6) {
@@ -100086,7 +100474,7 @@ function idempotency(c, access2, kind, body6) {
100086
100474
  if (key3 === void 0) return { existing: void 0, remember: (_id) => {
100087
100475
  } };
100088
100476
  if (key3.length > 255 || !key3.trim()) invalid6("Idempotency-Key requires 1\u2013255 characters and non-whitespace");
100089
- const fingerprint = createHash13("sha256").update(canonical2(body6)).digest("hex");
100477
+ const fingerprint = createHash13("sha256").update(canonical3(body6)).digest("hex");
100090
100478
  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);
100091
100479
  if (prior && prior.fingerprint !== fingerprint) throw new AdsError2(409, "Idempotency-Key was used with different input", "idempotency_conflict");
100092
100480
  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) };
@@ -100370,11 +100758,11 @@ function chatGPTAdsTwin() {
100370
100758
  const app2 = new Hono3();
100371
100759
  for (const route11 of chatGPTAdsRoutes) app2.on(route11.method, route11.path, handle2(route11));
100372
100760
  app2.all("*", handle2({ method: "GET", path: "*", notes: "", run: (c) => unsupported5(`${c.req.method} ${new URL(c.req.url).pathname}`) }));
100373
- return { name: "chatgpt-ads", basePath: "", app: app2, migrate: migrate7, seed: seed5, credentials: credentials4, dumpState: dumpState3, actions: {}, checks: {}, coverage: chatGPTAdsCoverage };
100761
+ return { name: "chatgpt-ads", basePath: "", app: app2, migrate: migrate8, seed: seed5, credentials: credentials4, dumpState: dumpState3, actions: {}, checks: {}, coverage: chatGPTAdsCoverage };
100374
100762
  }
100375
100763
 
100376
100764
  // packages/server/src/twins/ga4/db.ts
100377
- function migrate8(db2) {
100765
+ function migrate9(db2) {
100378
100766
  db2.exec(`CREATE TABLE ga4_data (id INTEGER PRIMARY KEY CHECK(id=1),json TEXT NOT NULL);
100379
100767
  CREATE TABLE ga4_credentials (principal_id TEXT PRIMARY KEY,token TEXT NOT NULL UNIQUE);
100380
100768
  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));`);
@@ -100845,7 +101233,7 @@ function ga4Twin() {
100845
101233
  property2(c, "0", true);
100846
101234
  return unsupported6(`${c.req.method} ${new URL(c.req.url).pathname}`);
100847
101235
  } }));
100848
- return { name: "ga4", basePath: "", unprefixedPaths: /^\/v1(?:alpha|beta)\/properties\//, app: app2, migrate: migrate8, seed: seed6, credentials: credentials5, dumpState: dumpState4, actions: {}, checks: {}, coverage: ga4Coverage };
101236
+ return { name: "ga4", basePath: "", unprefixedPaths: /^\/v1(?:alpha|beta)\/properties\//, app: app2, migrate: migrate9, seed: seed6, credentials: credentials5, dumpState: dumpState4, actions: {}, checks: {}, coverage: ga4Coverage };
100849
101237
  }
100850
101238
 
100851
101239
  // packages/server/src/twins/github/actions.ts
@@ -100994,7 +101382,7 @@ var actionRoutes = [
100994
101382
  ];
100995
101383
 
100996
101384
  // packages/server/src/twins/github/methods/checks.ts
100997
- function shape(ctx, repo4, row) {
101385
+ function shape2(ctx, repo4, row) {
100998
101386
  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: [] };
100999
101387
  }
101000
101388
  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.";
@@ -101015,13 +101403,13 @@ var checkRoutes = [
101015
101403
  });
101016
101404
  }
101017
101405
  const { page: page15, perPage } = pageInfo(c);
101018
- 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));
101406
+ 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));
101019
101407
  } },
101020
101408
  { method: "GET", path: "/repos/:owner/:repo/check-runs/:id", coverage: { status: "partial", notes: notes4 }, handler: (c) => {
101021
101409
  query(c, []);
101022
101410
  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"));
101023
101411
  if (!row) throw new GitHubError(404, "Not Found");
101024
- return shape(ctx, repo4, row);
101412
+ return shape2(ctx, repo4, row);
101025
101413
  } }
101026
101414
  ];
101027
101415
 
@@ -102246,7 +102634,7 @@ function downtime(ctx, args) {
102246
102634
  }
102247
102635
 
102248
102636
  // packages/server/src/twins/datadog/db.ts
102249
- function migrate9(db2) {
102637
+ function migrate10(db2) {
102250
102638
  db2.exec(`
102251
102639
  CREATE TABLE datadog_monitors (
102252
102640
  id INTEGER PRIMARY KEY, ref TEXT NOT NULL UNIQUE, name TEXT NOT NULL, query TEXT NOT NULL,
@@ -102629,7 +103017,7 @@ function datadogTwin() {
102629
103017
  name: "datadog",
102630
103018
  basePath: "",
102631
103019
  app: app2,
102632
- migrate: migrate9,
103020
+ migrate: migrate10,
102633
103021
  seed: seed7,
102634
103022
  credentials: credentials6,
102635
103023
  dumpState: dumpState6,
@@ -103685,7 +104073,7 @@ function unsupported8(message6, code2 = "INVALID_FIELD") {
103685
104073
  }
103686
104074
  var versionRoot = "/services/data/v67.0";
103687
104075
  var prefixes = { Account: "001", Contact: "003", Lead: "00Q", Opportunity: "006", Campaign: "701", CampaignMember: "00v" };
103688
- function migrate10(db2) {
104076
+ function migrate11(db2) {
103689
104077
  db2.exec(`
103690
104078
  CREATE TABLE salesforce_records (type TEXT NOT NULL,id TEXT NOT NULL PRIMARY KEY,data TEXT NOT NULL);
103691
104079
  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);
@@ -104208,11 +104596,11 @@ function salesforceTwin() {
104208
104596
  };
104209
104597
  for (const [method2, path4] of routePairs2) app2.on(method2, path4, handler);
104210
104598
  app2.all("*", handler);
104211
- return { name: "salesforce", basePath: "", app: app2, migrate: migrate10, seed: seed10, credentials: credentials9, actions: {}, checks: {}, dumpState: dumpState9, coverage: salesforceCoverage };
104599
+ return { name: "salesforce", basePath: "", app: app2, migrate: migrate11, seed: seed10, credentials: credentials9, actions: {}, checks: {}, dumpState: dumpState9, coverage: salesforceCoverage };
104212
104600
  }
104213
104601
 
104214
104602
  // packages/server/src/twins/linkedin-ads/db.ts
104215
- function migrate11(db2) {
104603
+ function migrate12(db2) {
104216
104604
  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)");
104217
104605
  }
104218
104606
  function get2(ctx, kind, id12) {
@@ -104724,11 +105112,11 @@ function linkedinAdsTwin() {
104724
105112
  const app2 = new Hono3();
104725
105113
  for (const route11 of linkedinAdsRoutes) app2.on(route11.method, route11.path, handle4(route11));
104726
105114
  app2.all("*", unknown2);
104727
- return { name: "linkedin-ads", basePath: "", app: app2, migrate: migrate11, seed: seed11, credentials: credentials10, actions: {}, checks: {}, dumpState: dumpState10, coverage: linkedinAdsCoverage };
105115
+ return { name: "linkedin-ads", basePath: "", app: app2, migrate: migrate12, seed: seed11, credentials: credentials10, actions: {}, checks: {}, dumpState: dumpState10, coverage: linkedinAdsCoverage };
104728
105116
  }
104729
105117
 
104730
105118
  // packages/server/src/twins/gong/db.ts
104731
- function migrate12(db2) {
105119
+ function migrate13(db2) {
104732
105120
  db2.exec(`CREATE TABLE gong_data (id INTEGER PRIMARY KEY CHECK(id=1), json TEXT NOT NULL);
104733
105121
  CREATE TABLE gong_credentials (principal_id TEXT PRIMARY KEY, access_key TEXT NOT NULL UNIQUE, access_secret TEXT NOT NULL);
104734
105122
  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));`);
@@ -104867,13 +105255,13 @@ function handle5(route11) {
104867
105255
  };
104868
105256
  }
104869
105257
  var unknown3 = handle5({ method: "GET", path: "*", scope: "", notes: "", run: (c) => unsupported9(`${c.req.method} ${new URL(c.req.url).pathname}`) });
104870
- function canonical3(value4) {
104871
- if (Array.isArray(value4)) return `[${value4.map(canonical3).join(",")}]`;
104872
- 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(",")}}`;
105258
+ function canonical4(value4) {
105259
+ if (Array.isArray(value4)) return `[${value4.map(canonical4).join(",")}]`;
105260
+ 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(",")}}`;
104873
105261
  return JSON.stringify(value4);
104874
105262
  }
104875
105263
  function pageRequest(ctx, principal, op, criteria, raw3) {
104876
- const hash4 = createHash15("sha256").update(canonical3(criteria)).digest("hex");
105264
+ const hash4 = createHash15("sha256").update(canonical4(criteria)).digest("hex");
104877
105265
  const base3 = { v: 1, env: ctx.envId, principal: principal.id, op, hash: hash4, page: 0, asOf: ctx.clock.elapsedMs() };
104878
105266
  const sign2 = (payload2) => createHmac2("sha256", ctx.store.meta.get("gong.cursor-secret")).update(payload2).digest("base64url");
104879
105267
  let cursor4 = base3;
@@ -105007,11 +105395,11 @@ function gongTwin() {
105007
105395
  const app2 = new Hono3();
105008
105396
  for (const route11 of gongRoutes) app2.on(route11.method, route11.path, handle5(route11));
105009
105397
  app2.all("*", unknown3);
105010
- return { name: "gong", basePath: "", app: app2, migrate: migrate12, seed: seed12, credentials: credentials11, dumpState: dumpState11, actions: {}, checks: {}, coverage: gongCoverage };
105398
+ return { name: "gong", basePath: "", app: app2, migrate: migrate13, seed: seed12, credentials: credentials11, dumpState: dumpState11, actions: {}, checks: {}, coverage: gongCoverage };
105011
105399
  }
105012
105400
 
105013
105401
  // packages/server/src/twins/open-meteo/db.ts
105014
- function migrate13(db2) {
105402
+ function migrate14(db2) {
105015
105403
  db2.exec("CREATE TABLE open_meteo_data (id INTEGER PRIMARY KEY CHECK(id=1), json TEXT NOT NULL);");
105016
105404
  }
105017
105405
  function seed13(ctx) {
@@ -105259,12 +105647,12 @@ function openMeteoTwin() {
105259
105647
  app2.get("/v1/forecast", handle6(forecast));
105260
105648
  app2.get("/v1/search", handle6(search4));
105261
105649
  app2.all("*", handle6(unknownRoute5));
105262
- return { name: "open-meteo", basePath: "", app: app2, migrate: migrate13, seed: seed13, credentials: credentials12, dumpState: dumpState12, actions: {}, checks: {}, coverage: openMeteoCoverage };
105650
+ return { name: "open-meteo", basePath: "", app: app2, migrate: migrate14, seed: seed13, credentials: credentials12, dumpState: dumpState12, actions: {}, checks: {}, coverage: openMeteoCoverage };
105263
105651
  }
105264
105652
 
105265
105653
  // packages/server/src/twins/google-drive/db.ts
105266
105654
  import { createHash as createHash16 } from "node:crypto";
105267
- var SCHEMA5 = `
105655
+ var SCHEMA6 = `
105268
105656
  CREATE TABLE gdrive_users (email TEXT PRIMARY KEY, name TEXT, permission_id TEXT NOT NULL UNIQUE, root_id TEXT NOT NULL UNIQUE);
105269
105657
  CREATE TABLE gdrive_files (
105270
105658
  id TEXT PRIMARY KEY, name TEXT NOT NULL, mime_type TEXT NOT NULL, owner TEXT NOT NULL, parent TEXT, description TEXT,
@@ -105290,8 +105678,8 @@ CREATE TABLE gdrive_revisions (file_id TEXT NOT NULL, id TEXT NOT NULL, mime_typ
105290
105678
  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);
105291
105679
  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);
105292
105680
  `;
105293
- function migrate14(db2) {
105294
- db2.exec(SCHEMA5);
105681
+ function migrate15(db2) {
105682
+ db2.exec(SCHEMA6);
105295
105683
  }
105296
105684
  var RANK2 = { reader: 1, commenter: 2, writer: 3, owner: 4 };
105297
105685
  var isFolder = (file3) => file3.mime_type === GOOGLE_DRIVE_FOLDER;
@@ -105917,12 +106305,12 @@ function parseQuery(source, aliases) {
105917
106305
  return (file3) => file3.sharedWithMe;
105918
106306
  }
105919
106307
  const operator2 = expect();
105920
- const contains2 = operator2.kind === "word" && operator2.value.toLowerCase() === "contains";
105921
- if (!contains2 && operator2.kind !== "op") {
106308
+ const contains3 = operator2.kind === "word" && operator2.value.toLowerCase() === "contains";
106309
+ if (!contains3 && operator2.kind !== "op") {
105922
106310
  if (operator2.kind === "word" && operator2.value.toLowerCase() === "has") unsupported11(`${field3} has search`);
105923
106311
  throw invalid10("q");
105924
106312
  }
105925
- const op = contains2 ? "contains" : operator2.value;
106313
+ const op = contains3 ? "contains" : operator2.value;
105926
106314
  switch (field3) {
105927
106315
  case "name": {
105928
106316
  const value4 = literal2();
@@ -107141,7 +107529,7 @@ async function handle7(c) {
107141
107529
  function googleDriveTwin() {
107142
107530
  const app2 = new Hono3();
107143
107531
  app2.all("*", handle7);
107144
- return { name: "google-drive", basePath: "", unprefixedPaths: /^\/(?:upload\/)?drive\/v3\//, app: app2, migrate: migrate14, seed: seed14, credentials: credentials13, dumpState: dumpState13, actions: {}, checks: {}, coverage: googleDriveCoverage };
107532
+ return { name: "google-drive", basePath: "", unprefixedPaths: /^\/(?:upload\/)?drive\/v3\//, app: app2, migrate: migrate15, seed: seed14, credentials: credentials13, dumpState: dumpState13, actions: {}, checks: {}, coverage: googleDriveCoverage };
107145
107533
  }
107146
107534
 
107147
107535
  // packages/server/src/twins/gmail/checks.ts
@@ -108459,9 +108847,9 @@ function stringToSign(method2, path4, query10, headers, signature) {
108459
108847
  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("&");
108460
108848
  const canonicalHeaders = signature.signedHeaders.map((name5) => `${name5}:${(headers.get(name5) ?? "").trim().replace(/\s+/g, " ")}
108461
108849
  `).join("");
108462
- const canonical4 = [method2, path4, canonicalQuery, canonicalHeaders, signature.signedHeaders.join(";"), signature.payloadHash].join("\n");
108463
- const toSign = ["AWS4-HMAC-SHA256", signature.amzDate, `${signature.date}/${signature.region}/s3/aws4_request`, sha256Hex(canonical4)].join("\n");
108464
- return { canonical: canonical4, toSign };
108850
+ const canonical5 = [method2, path4, canonicalQuery, canonicalHeaders, signature.signedHeaders.join(";"), signature.payloadHash].join("\n");
108851
+ const toSign = ["AWS4-HMAC-SHA256", signature.amzDate, `${signature.date}/${signature.region}/s3/aws4_request`, sha256Hex(canonical5)].join("\n");
108852
+ return { canonical: canonical5, toSign };
108465
108853
  }
108466
108854
  function verifySignature(secret, signature, toSign) {
108467
108855
  const key3 = hmac(hmac(hmac(hmac(`AWS4${secret}`, signature.date), signature.region), "s3"), "aws4_request");
@@ -108527,7 +108915,7 @@ var md5Hex = (data5) => createHash19("md5").update(data5).digest("hex");
108527
108915
  var sha2562 = sha256Hex;
108528
108916
 
108529
108917
  // packages/server/src/twins/amazon-s3/db.ts
108530
- var SCHEMA6 = `
108918
+ var SCHEMA7 = `
108531
108919
  CREATE TABLE s3_buckets (name TEXT PRIMARY KEY, region TEXT NOT NULL, created_ms INTEGER NOT NULL, access TEXT NOT NULL, tags TEXT);
108532
108920
  CREATE TABLE s3_objects (
108533
108921
  bucket TEXT NOT NULL, key TEXT NOT NULL, content BLOB NOT NULL, content_type TEXT NOT NULL, etag TEXT NOT NULL,
@@ -108542,8 +108930,8 @@ CREATE TABLE s3_uploads (
108542
108930
  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));
108543
108931
  CREATE TABLE s3_taken_names (name TEXT PRIMARY KEY);
108544
108932
  `;
108545
- function migrate15(db2) {
108546
- db2.exec(SCHEMA6);
108933
+ function migrate16(db2) {
108934
+ db2.exec(SCHEMA7);
108547
108935
  }
108548
108936
  function account3(ctx) {
108549
108937
  return JSON.parse(ctx.store.meta.get("amazon-s3.account"));
@@ -109400,11 +109788,11 @@ async function handle8(c) {
109400
109788
  function amazonS3Twin() {
109401
109789
  const app2 = new Hono3();
109402
109790
  app2.all("*", handle8);
109403
- return { name: "amazon-s3", basePath: "", app: app2, migrate: migrate15, seed: seed16, credentials: credentials15, dumpState: dumpState15, actions: {}, checks: {}, coverage: amazonS3Coverage };
109791
+ return { name: "amazon-s3", basePath: "", app: app2, migrate: migrate16, seed: seed16, credentials: credentials15, dumpState: dumpState15, actions: {}, checks: {}, coverage: amazonS3Coverage };
109404
109792
  }
109405
109793
 
109406
109794
  // packages/server/src/twins/linear/db.ts
109407
- var SCHEMA7 = `
109795
+ var SCHEMA8 = `
109408
109796
  CREATE TABLE linear_org (id TEXT PRIMARY KEY, name TEXT NOT NULL, url_key TEXT NOT NULL, created_at TEXT NOT NULL);
109409
109797
  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,
109410
109798
  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);
@@ -109428,8 +109816,8 @@ CREATE TABLE linear_issue_labels (issue_id TEXT NOT NULL, label_id TEXT NOT NULL
109428
109816
  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,
109429
109817
  created_at TEXT NOT NULL, updated_at TEXT NOT NULL, edited_at TEXT, archived_at TEXT);
109430
109818
  `;
109431
- function migrate16(db2) {
109432
- db2.exec(SCHEMA7);
109819
+ function migrate17(db2) {
109820
+ db2.exec(SCHEMA8);
109433
109821
  }
109434
109822
  var one = (ctx, sql, ...args) => ctx.store.db.prepare(sql).get(...args);
109435
109823
  var all2 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).all(...args);
@@ -110591,7 +110979,7 @@ function linearTwin() {
110591
110979
  const app2 = new Hono3();
110592
110980
  app2.post("/graphql", handleGraphql);
110593
110981
  app2.all("*", unknownRoute7);
110594
- return { name: "linear", basePath: "/graphql", app: app2, migrate: migrate16, seed: seed17, credentials: credentials16, actions: {}, checks: {}, dumpState: dumpState16, coverage: linearCoverage };
110982
+ return { name: "linear", basePath: "/graphql", app: app2, migrate: migrate17, seed: seed17, credentials: credentials16, actions: {}, checks: {}, dumpState: dumpState16, coverage: linearCoverage };
110595
110983
  }
110596
110984
 
110597
110985
  // packages/server/src/twins/okta/index.ts
@@ -110599,7 +110987,7 @@ import { createHash as createHash25 } from "node:crypto";
110599
110987
 
110600
110988
  // packages/server/src/twins/okta/db.ts
110601
110989
  import { createHash as createHash23 } from "node:crypto";
110602
- var SCHEMA8 = `
110990
+ var SCHEMA9 = `
110603
110991
  CREATE TABLE okta_users (
110604
110992
  id TEXT PRIMARY KEY, login TEXT NOT NULL UNIQUE COLLATE NOCASE, status TEXT NOT NULL, created_ms INTEGER NOT NULL, activated_ms INTEGER,
110605
110993
  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,
@@ -110615,8 +111003,8 @@ CREATE TABLE okta_logs (
110615
111003
  outcome TEXT NOT NULL, reason TEXT, actor_id TEXT NOT NULL, targets TEXT NOT NULL
110616
111004
  );
110617
111005
  `;
110618
- function migrate17(db2) {
110619
- db2.exec(SCHEMA8);
111006
+ function migrate18(db2) {
111007
+ db2.exec(SCHEMA9);
110620
111008
  }
110621
111009
  var BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
110622
111010
  var hashed = (value4, length) => [...createHash23("sha256").update(value4).digest()].slice(0, length).map((byte) => BASE62[byte % 62]).join("");
@@ -111675,18 +112063,18 @@ async function handle9(c) {
111675
112063
  function oktaTwin() {
111676
112064
  const app2 = new Hono3();
111677
112065
  app2.all("*", handle9);
111678
- return { name: "okta", basePath: "", app: app2, migrate: migrate17, seed: seed18, credentials: credentials17, dumpState: dumpState17, actions: {}, checks: { user: user5 }, coverage: oktaCoverage };
112066
+ return { name: "okta", basePath: "", app: app2, migrate: migrate18, seed: seed18, credentials: credentials17, dumpState: dumpState17, actions: {}, checks: { user: user5 }, coverage: oktaCoverage };
111679
112067
  }
111680
112068
 
111681
112069
  // packages/server/src/twins/stripe/db.ts
111682
- var SCHEMA9 = `
112070
+ var SCHEMA10 = `
111683
112071
  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);
111684
112072
  CREATE INDEX stripe_objects_type ON stripe_objects (type, created, seq);
111685
112073
  CREATE TABLE stripe_keys (key TEXT PRIMARY KEY);
111686
112074
  CREATE TABLE stripe_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, status INTEGER NOT NULL, body TEXT NOT NULL);
111687
112075
  `;
111688
- function migrate18(db2) {
111689
- db2.exec(SCHEMA9);
112076
+ function migrate19(db2) {
112077
+ db2.exec(SCHEMA10);
111690
112078
  }
111691
112079
  function load(ctx, id12) {
111692
112080
  const row = ctx.store.db.prepare("SELECT json FROM stripe_objects WHERE id = ?").get(id12);
@@ -113751,7 +114139,7 @@ function stripeTwin() {
113751
114139
  const app2 = new Hono3();
113752
114140
  for (const route11 of [...stripeRoutes].sort((a, b) => Number(a.path.includes(":")) - Number(b.path.includes(":")))) app2.on(route11.method, route11.path, handle10(route11));
113753
114141
  app2.all("*", unknownRoute8);
113754
- return { name: "stripe", basePath: "", app: app2, migrate: migrate18, seed: seed19, credentials: credentials18, actions: {}, checks: {}, dumpState: dumpState18, coverage: stripeCoverage };
114142
+ return { name: "stripe", basePath: "", app: app2, migrate: migrate19, seed: seed19, credentials: credentials18, actions: {}, checks: {}, dumpState: dumpState18, coverage: stripeCoverage };
113755
114143
  }
113756
114144
 
113757
114145
  // packages/server/src/twins/clerk/index.ts
@@ -113759,7 +114147,7 @@ import { createHash as createHash29 } from "node:crypto";
113759
114147
 
113760
114148
  // packages/server/src/twins/clerk/db.ts
113761
114149
  import { createHash as createHash27 } from "node:crypto";
113762
- var SCHEMA10 = `
114150
+ var SCHEMA11 = `
113763
114151
  CREATE TABLE clerk_users (
113764
114152
  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,
113765
114153
  external_id TEXT, password_enabled INTEGER NOT NULL, banned INTEGER NOT NULL DEFAULT 0, locked INTEGER NOT NULL DEFAULT 0,
@@ -113777,8 +114165,8 @@ CREATE TABLE clerk_invitations (
113777
114165
  );
113778
114166
  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);
113779
114167
  `;
113780
- function migrate19(db2) {
113781
- db2.exec(SCHEMA10);
114168
+ function migrate20(db2) {
114169
+ db2.exec(SCHEMA11);
113782
114170
  }
113783
114171
  var BASE623 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
113784
114172
  var seededId2 = (prefix2, key3) => `${prefix2}_2${[...createHash27("sha256").update(`clerk:${prefix2}:${key3}`).digest()].slice(0, 26).map((byte) => BASE623[byte % 62]).join("")}`;
@@ -114181,10 +114569,10 @@ function filterUsers(call2, query10) {
114181
114569
  const found = getOrg(ctx, org5);
114182
114570
  return found ? membershipsOf(ctx, found.id).map((member4) => member4.user_id) : [];
114183
114571
  })) : void 0;
114184
- const contains2 = (value4, needle) => needle === null || (value4 ?? "").toLowerCase().includes(needle.toLowerCase());
114572
+ const contains3 = (value4, needle) => needle === null || (value4 ?? "").toLowerCase().includes(needle.toLowerCase());
114185
114573
  const q = query10.get("query"), banned = bool4(query10.get("banned") ?? void 0, "banned");
114186
114574
  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");
114187
- 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));
114575
+ 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));
114188
114576
  }
114189
114577
  var USER_ORDER = {
114190
114578
  created_at: (user8) => user8.created_ms,
@@ -114714,12 +115102,12 @@ async function handle11(c) {
114714
115102
  function clerkTwin() {
114715
115103
  const app2 = new Hono3();
114716
115104
  app2.all("*", handle11);
114717
- return { name: "clerk", basePath: "", app: app2, migrate: migrate19, seed: seed20, credentials: credentials19, dumpState: dumpState19, actions: {}, checks: {}, coverage: clerkCoverage };
115105
+ return { name: "clerk", basePath: "", app: app2, migrate: migrate20, seed: seed20, credentials: credentials19, dumpState: dumpState19, actions: {}, checks: {}, coverage: clerkCoverage };
114718
115106
  }
114719
115107
 
114720
115108
  // packages/server/src/twins/better-stack/db.ts
114721
115109
  import { createHash as createHash30 } from "node:crypto";
114722
- var SCHEMA11 = `
115110
+ var SCHEMA12 = `
114723
115111
  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);
114724
115112
  CREATE TABLE bs_sources (
114725
115113
  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,
@@ -114735,8 +115123,8 @@ CREATE TABLE bs_resources (id TEXT PRIMARY KEY, page_id TEXT NOT NULL, public_na
114735
115123
  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);
114736
115124
  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);
114737
115125
  `;
114738
- function migrate20(db2) {
114739
- db2.exec(SCHEMA11);
115126
+ function migrate21(db2) {
115127
+ db2.exec(SCHEMA12);
114740
115128
  }
114741
115129
  var BASES = { user: 145001, monitor: 2245001, heartbeat: 441501, incident: 600001, calendar: 9001, page: 160001, resource: 8800001, report: 3300001, update: 7700001 };
114742
115130
  function nextId3(ctx, kind) {
@@ -115505,18 +115893,18 @@ async function handle12(c) {
115505
115893
  function betterStackTwin() {
115506
115894
  const app2 = new Hono3();
115507
115895
  app2.all("*", handle12);
115508
- return { name: "better-stack", basePath: "", app: app2, migrate: migrate20, seed: seed21, credentials: credentials20, dumpState: dumpState20, actions: {}, checks: {}, coverage: betterStackCoverage };
115896
+ return { name: "better-stack", basePath: "", app: app2, migrate: migrate21, seed: seed21, credentials: credentials20, dumpState: dumpState20, actions: {}, checks: {}, coverage: betterStackCoverage };
115509
115897
  }
115510
115898
 
115511
115899
  // packages/server/src/twins/notion/db.ts
115512
- var SCHEMA12 = `
115900
+ var SCHEMA13 = `
115513
115901
  CREATE TABLE notion_nodes (id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('user','page','block','database','data_source','comment')),
115514
115902
  parent_id TEXT, position REAL NOT NULL DEFAULT 0, json TEXT NOT NULL);
115515
115903
  CREATE INDEX notion_nodes_parent ON notion_nodes (parent_id, position);
115516
115904
  CREATE TABLE notion_tokens (token TEXT PRIMARY KEY, bot_id TEXT NOT NULL);
115517
115905
  `;
115518
- function migrate21(db2) {
115519
- db2.exec(SCHEMA12);
115906
+ function migrate22(db2) {
115907
+ db2.exec(SCHEMA13);
115520
115908
  }
115521
115909
  var node4 = (row) => row && { id: row.id, kind: row.kind, parent_id: row.parent_id, position: row.position, doc: JSON.parse(row.json) };
115522
115910
  function get3(ctx, id12) {
@@ -116723,11 +117111,11 @@ function notionTwin() {
116723
117111
  const app2 = new Hono3();
116724
117112
  for (const route11 of [...notionRoutes].sort((a, b) => Number(a.path.includes(":")) - Number(b.path.includes(":")))) app2.on(route11.method, route11.path, handle13(route11));
116725
117113
  app2.all("*", unknownRoute9);
116726
- return { name: "notion", basePath: "", app: app2, migrate: migrate21, seed: seed22, credentials: credentials21, actions: {}, checks: {}, dumpState: dumpState21, coverage: notionCoverage };
117114
+ return { name: "notion", basePath: "", app: app2, migrate: migrate22, seed: seed22, credentials: credentials21, actions: {}, checks: {}, dumpState: dumpState21, coverage: notionCoverage };
116727
117115
  }
116728
117116
 
116729
117117
  // packages/server/src/twins/attio/db.ts
116730
- var SCHEMA13 = `
117118
+ var SCHEMA14 = `
116731
117119
  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);
116732
117120
  CREATE TABLE attio_tokens (token TEXT PRIMARY KEY, member_id TEXT NOT NULL);
116733
117121
  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);
@@ -116744,8 +117132,8 @@ CREATE INDEX attio_values_parent ON attio_values (parent_id, attribute_id, activ
116744
117132
  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);
116745
117133
  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);
116746
117134
  `;
116747
- function migrate22(db2) {
116748
- db2.exec(SCHEMA13);
117135
+ function migrate23(db2) {
117136
+ db2.exec(SCHEMA14);
116749
117137
  }
116750
117138
  var one2 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).get(...args);
116751
117139
  var all5 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).all(...args);
@@ -117549,7 +117937,7 @@ var attioRoutes = [
117549
117937
  ];
117550
117938
 
117551
117939
  // packages/server/src/twins/attio/seed.ts
117552
- var SYSTEM = [
117940
+ var SYSTEM2 = [
117553
117941
  { api_slug: "record_id", title: "Record ID", type: "text", system: true, writable: false }
117554
117942
  ];
117555
117943
  var TAIL = [
@@ -117559,7 +117947,7 @@ var TAIL = [
117559
117947
  function standard(dealStages, categories) {
117560
117948
  return {
117561
117949
  people: { singular: "Person", plural: "People", attributes: [
117562
- ...SYSTEM,
117950
+ ...SYSTEM2,
117563
117951
  { api_slug: "name", title: "Name", type: "personal-name", system: true },
117564
117952
  { api_slug: "email_addresses", title: "Email addresses", type: "email-address", is_multiselect: true, is_unique: true, system: true },
117565
117953
  { api_slug: "phone_numbers", title: "Phone numbers", type: "phone-number", is_multiselect: true, system: true },
@@ -117569,7 +117957,7 @@ function standard(dealStages, categories) {
117569
117957
  ...TAIL
117570
117958
  ] },
117571
117959
  companies: { singular: "Company", plural: "Companies", attributes: [
117572
- ...SYSTEM,
117960
+ ...SYSTEM2,
117573
117961
  { api_slug: "name", title: "Name", type: "text", system: true },
117574
117962
  { api_slug: "domains", title: "Domains", type: "domain", is_multiselect: true, is_unique: true, system: true },
117575
117963
  { api_slug: "description", title: "Description", type: "text", system: true },
@@ -117578,7 +117966,7 @@ function standard(dealStages, categories) {
117578
117966
  ...TAIL
117579
117967
  ] },
117580
117968
  deals: { singular: "Deal", plural: "Deals", attributes: [
117581
- ...SYSTEM,
117969
+ ...SYSTEM2,
117582
117970
  { api_slug: "name", title: "Deal name", type: "text", is_required: true, system: true },
117583
117971
  { api_slug: "stage", title: "Deal stage", type: "status", is_required: true, options: dealStages, system: true },
117584
117972
  { api_slug: "owner", title: "Deal owner", type: "actor-reference", is_required: true, system: true },
@@ -117751,12 +118139,12 @@ function attioTwin() {
117751
118139
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
117752
118140
  for (const route11 of [...attioRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle14(route11));
117753
118141
  app2.all("*", unknownRoute10);
117754
- return { name: "attio", basePath: "", app: app2, migrate: migrate22, seed: seed23, credentials: credentials22, actions: {}, checks: {}, dumpState: dumpState22, coverage: attioCoverage };
118142
+ return { name: "attio", basePath: "", app: app2, migrate: migrate23, seed: seed23, credentials: credentials22, actions: {}, checks: {}, dumpState: dumpState22, coverage: attioCoverage };
117755
118143
  }
117756
118144
 
117757
118145
  // packages/server/src/twins/dropbox/db.ts
117758
118146
  import { createHash as createHash33 } from "node:crypto";
117759
- var SCHEMA14 = `
118147
+ var SCHEMA15 = `
117760
118148
  CREATE TABLE dbx_entries (
117761
118149
  path_lower TEXT PRIMARY KEY, path_display TEXT NOT NULL, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, rev TEXT, content BLOB,
117762
118150
  client_modified_ms INTEGER, server_modified_ms INTEGER, uploaded_by TEXT, shared_folder_id TEXT
@@ -117770,8 +118158,8 @@ CREATE TABLE dbx_changes (seq INTEGER PRIMARY KEY, path_lower TEXT NOT NULL);
117770
118158
  CREATE TABLE dbx_temp_links (token TEXT PRIMARY KEY, path_lower TEXT NOT NULL, rev TEXT NOT NULL, expires_ms INTEGER NOT NULL);
117771
118159
  CREATE TABLE dbx_people (email TEXT PRIMARY KEY, name TEXT NOT NULL, same_team INTEGER NOT NULL);
117772
118160
  `;
117773
- function migrate23(db2) {
117774
- db2.exec(SCHEMA14);
118161
+ function migrate24(db2) {
118162
+ db2.exec(SCHEMA15);
117775
118163
  }
117776
118164
  var account5 = (ctx) => JSON.parse(ctx.store.meta.get("dropbox.account"));
117777
118165
  var getEntry = (ctx, pathLower) => ctx.store.db.prepare("SELECT * FROM dbx_entries WHERE path_lower = ?").get(pathLower);
@@ -118551,7 +118939,7 @@ async function handle15(c) {
118551
118939
  function dropboxTwin() {
118552
118940
  const app2 = new Hono3();
118553
118941
  app2.all("*", handle15);
118554
- return { name: "dropbox", basePath: "", app: app2, migrate: migrate23, seed: seed24, credentials: credentials23, dumpState: dumpState23, actions: {}, checks: {}, coverage: dropboxCoverage };
118942
+ return { name: "dropbox", basePath: "", app: app2, migrate: migrate24, seed: seed24, credentials: credentials23, dumpState: dumpState23, actions: {}, checks: {}, coverage: dropboxCoverage };
118555
118943
  }
118556
118944
 
118557
118945
  // packages/server/src/twins/resend/request.ts
@@ -118648,7 +119036,7 @@ function unknownRoute11(c) {
118648
119036
  }
118649
119037
 
118650
119038
  // packages/server/src/twins/resend/routes.ts
118651
- function migrate24(db2) {
119039
+ function migrate25(db2) {
118652
119040
  db2.exec(`
118653
119041
  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);
118654
119042
  CREATE INDEX resend_objects_kind ON resend_objects (kind, created_ms);
@@ -119287,7 +119675,7 @@ function resendTwin() {
119287
119675
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
119288
119676
  for (const route11 of [...resendRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle16(route11));
119289
119677
  app2.all("*", unknownRoute11);
119290
- return { name: "resend", basePath: "", app: app2, migrate: migrate24, seed: seed25, credentials: credentials24, actions: {}, checks: {}, dumpState: dumpState24, coverage: resendCoverage };
119678
+ return { name: "resend", basePath: "", app: app2, migrate: migrate25, seed: seed25, credentials: credentials24, actions: {}, checks: {}, dumpState: dumpState24, coverage: resendCoverage };
119291
119679
  }
119292
119680
 
119293
119681
  // packages/server/src/twins/microsoft-word/db.ts
@@ -119452,7 +119840,7 @@ function quickXorHash(data5) {
119452
119840
  }
119453
119841
 
119454
119842
  // packages/server/src/twins/microsoft-word/db.ts
119455
- var SCHEMA15 = `
119843
+ var SCHEMA16 = `
119456
119844
  CREATE TABLE ms_users (email TEXT PRIMARY KEY, id TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, job_title TEXT);
119457
119845
  CREATE TABLE ms_items (
119458
119846
  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,
@@ -119465,8 +119853,8 @@ CREATE TABLE ms_permissions (
119465
119853
  );
119466
119854
  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);
119467
119855
  `;
119468
- function migrate25(db2) {
119469
- db2.exec(SCHEMA15);
119856
+ function migrate26(db2) {
119857
+ db2.exec(SCHEMA16);
119470
119858
  }
119471
119859
  var hex3 = (value4) => createHash36("sha256").update(value4).digest("hex");
119472
119860
  var guid3 = (key3) => {
@@ -119488,7 +119876,7 @@ var childrenOf2 = (ctx, id12) => ctx.store.db.prepare("SELECT * FROM ms_items WH
119488
119876
  var userOf = (ctx, email10) => ctx.store.db.prepare("SELECT * FROM ms_users WHERE email = ?").get(email10);
119489
119877
  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" };
119490
119878
  var mimeFor = (name5) => MIME[/\.([A-Za-z0-9]+)$/.exec(name5)?.[1]?.toLowerCase() ?? ""] ?? "application/octet-stream";
119491
- function pathOf(ctx, item2) {
119879
+ function pathOf2(ctx, item2) {
119492
119880
  const parts3 = [];
119493
119881
  for (let node5 = item2; node5 && node5.kind !== "root"; node5 = node5.parent_id ? getItem(ctx, node5.parent_id) : void 0) parts3.unshift(node5.name);
119494
119882
  return parts3.length ? `/${parts3.join("/")}` : "";
@@ -119562,7 +119950,7 @@ function credentials25(ctx) {
119562
119950
  }
119563
119951
  function dumpState25(ctx) {
119564
119952
  const db2 = ctx.store.db, iso19 = (ms) => new Date(ms).toISOString();
119565
- 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);
119953
+ 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);
119566
119954
  const paths2 = new Map(items.map((entry2) => [entry2.item.id, entry2.path]));
119567
119955
  return {
119568
119956
  ...config8(ctx),
@@ -119640,7 +120028,7 @@ function identity3(ctx, email10) {
119640
120028
  return { user: { email: email10, id: user8?.id ?? guid3(`user:${email10}`), displayName: user8?.display_name ?? email10 } };
119641
120029
  }
119642
120030
  function itemJson(ctx, item2) {
119643
- const { driveId, me: me4, tenant } = config8(ctx), path4 = pathOf(ctx, item2), web = `https://${tenant.domain.split(".")[0]}-my.sharepoint.com/personal/${slug5(me4)}/Documents`;
120031
+ const { driveId, me: me4, tenant } = config8(ctx), path4 = pathOf2(ctx, item2), web = `https://${tenant.domain.split(".")[0]}-my.sharepoint.com/personal/${slug5(me4)}/Documents`;
119644
120032
  const tag3 = guid3(`etag:${item2.id}`).toUpperCase(), parent2 = item2.parent_id ? getItem(ctx, item2.parent_id) : void 0;
119645
120033
  const size = item2.kind === "file" ? item2.content?.length ?? 0 : childrenSize(ctx, item2);
119646
120034
  const shared = sharedScope(ctx, item2);
@@ -119656,7 +120044,7 @@ function itemJson(ctx, item2) {
119656
120044
  size,
119657
120045
  createdBy: identity3(ctx, item2.created_by),
119658
120046
  lastModifiedBy: identity3(ctx, item2.modified_by),
119659
- parentReference: { driveType: "business", driveId, ...parent2 && { id: parent2.id, name: parent2.kind === "root" ? "Documents" : parent2.name, path: `/drive/root:${pathOf(ctx, parent2)}` } },
120047
+ parentReference: { driveType: "business", driveId, ...parent2 && { id: parent2.id, name: parent2.kind === "root" ? "Documents" : parent2.name, path: `/drive/root:${pathOf2(ctx, parent2)}` } },
119660
120048
  fileSystemInfo: { createdDateTime: iso7(item2.created_ms), lastModifiedDateTime: iso7(item2.modified_ms) },
119661
120049
  ...item2.description !== null && { description: item2.description },
119662
120050
  ...item2.kind === "file" ? { file: { mimeType: item2.mime_type, hashes: { quickXorHash: quickXorHash(item2.content ?? Buffer.alloc(0)) } } } : { folder: { childCount: childrenOf2(ctx, item2.id).length } },
@@ -119685,7 +120073,7 @@ function permissionJson(ctx, row, inheritedFrom) {
119685
120073
  roles: roles2,
119686
120074
  ...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/${slug5(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 } },
119687
120075
  ...row.expires_ms !== null && { expirationDateTime: iso7(row.expires_ms) },
119688
- ...inheritedFrom && { inheritedFrom: { driveId: config8(ctx).driveId, id: inheritedFrom.id, path: `/drive/root:${pathOf(ctx, inheritedFrom)}` } }
120076
+ ...inheritedFrom && { inheritedFrom: { driveId: config8(ctx).driveId, id: inheritedFrom.id, path: `/drive/root:${pathOf2(ctx, inheritedFrom)}` } }
119689
120077
  };
119690
120078
  }
119691
120079
  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"]);
@@ -120262,11 +120650,11 @@ async function handle17(c) {
120262
120650
  function microsoftWordTwin() {
120263
120651
  const app2 = new Hono3();
120264
120652
  app2.all("*", handle17);
120265
- return { name: "microsoft-word", basePath: "", app: app2, migrate: migrate25, seed: seed26, credentials: credentials25, dumpState: dumpState25, actions: {}, checks: {}, coverage: microsoftWordCoverage };
120653
+ return { name: "microsoft-word", basePath: "", app: app2, migrate: migrate26, seed: seed26, credentials: credentials25, dumpState: dumpState25, actions: {}, checks: {}, coverage: microsoftWordCoverage };
120266
120654
  }
120267
120655
 
120268
120656
  // packages/server/src/twins/shopify/db.ts
120269
- function migrate26(db2) {
120657
+ function migrate27(db2) {
120270
120658
  db2.exec(`
120271
120659
  CREATE TABLE shopify_objects (gid TEXT PRIMARY KEY, kind TEXT NOT NULL, num INTEGER NOT NULL, parent TEXT, json TEXT NOT NULL);
120272
120660
  CREATE INDEX shopify_objects_kind ON shopify_objects (kind, num);
@@ -120571,7 +120959,7 @@ function compare7(op, a, b) {
120571
120959
  }
120572
120960
  }
120573
120961
  var wordsOf = (text21) => text21.toLowerCase().split(/[^\p{L}\p{N}*]+/u).filter(Boolean);
120574
- function textMatch(values2, wanted, contains2, words4 = false) {
120962
+ function textMatch(values2, wanted, contains3, words4 = false) {
120575
120963
  const options3 = wanted.split(",").map((v) => v.trim().toLowerCase()).filter(Boolean);
120576
120964
  return values2.some((raw3) => {
120577
120965
  if (raw3 === null) return false;
@@ -120580,7 +120968,7 @@ function textMatch(values2, wanted, contains2, words4 = false) {
120580
120968
  const have = wordsOf(v);
120581
120969
  return options3.some((o) => wordsOf(o).every((w) => have.some((h) => w.endsWith("*") ? h.startsWith(w.slice(0, -1)) : h === w)));
120582
120970
  }
120583
- 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);
120971
+ 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);
120584
120972
  });
120585
120973
  }
120586
120974
  function search7(items, query10, documented, fields11, nowMs) {
@@ -120642,7 +121030,7 @@ function decode3(cursor4) {
120642
121030
  return null;
120643
121031
  }
120644
121032
  }
120645
- function connection2(items, args, key3, shape3) {
121033
+ function connection2(items, args, key3, shape4) {
120646
121034
  const { first, last, after, before } = args;
120647
121035
  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" } });
120648
121036
  for (const [name5, n] of [["first", first], ["last", last]]) {
@@ -120666,16 +121054,16 @@ function connection2(items, args, key3, shape3) {
120666
121054
  };
120667
121055
  return {
120668
121056
  get edges() {
120669
- return page15.map((item2) => ({ cursor: cursor4(item2), node: shape3(item2) }));
121057
+ return page15.map((item2) => ({ cursor: cursor4(item2), node: shape4(item2) }));
120670
121058
  },
120671
121059
  get nodes() {
120672
- return page15.map(shape3);
121060
+ return page15.map(shape4);
120673
121061
  },
120674
121062
  pageInfo: { hasNextPage: end < ordered2.length, hasPreviousPage: start > 0, startCursor: page15.length ? cursor4(page15[0]) : null, endCursor: page15.length ? cursor4(page15[page15.length - 1]) : null }
120675
121063
  };
120676
121064
  }
120677
121065
  var byNum = (d) => ({ id: numOf(d.gid) });
120678
- var pathOf2 = (path4) => path4 ? [...pathOf2(path4.prev), path4.key] : [];
121066
+ var pathOf3 = (path4) => path4 ? [...pathOf3(path4.prev), path4.key] : [];
120679
121067
  var firstOf = (items, n) => typeof n === "number" ? items.slice(0, Math.max(0, n)) : items;
120680
121068
  var currencyOf = (ctx) => all6(ctx, "Shop")[0].currency;
120681
121069
  var bag = (ctx, c) => {
@@ -121014,7 +121402,7 @@ function customerShape(req, c) {
121014
121402
  },
121015
121403
  defaultAddress: addressShape(c.address),
121016
121404
  addresses: ({ first }) => firstOf(c.address ? [addressShape(c.address)] : [], first),
121017
- orders: (args, _req, info) => ordersConnection(req, orders(), args, pathOf2(info.path))
121405
+ orders: (args, _req, info) => ordersConnection(req, orders(), args, pathOf3(info.path))
121018
121406
  };
121019
121407
  }
121020
121408
  function orderShape(req, o) {
@@ -121532,21 +121920,21 @@ var now6 = (req) => req.ctx.clock.nowMs();
121532
121920
  var field2 = (...parts3) => parts3.map(String);
121533
121921
  function queryRoot(req) {
121534
121922
  const ctx = req.ctx;
121535
- const one7 = (kind, shape3) => ({ id: id12 }) => {
121923
+ const one7 = (kind, shape4) => ({ id: id12 }) => {
121536
121924
  const d = loadKind(ctx, kind, checkId(id12));
121537
- return d ? shape3(req, d) : null;
121925
+ return d ? shape4(req, d) : null;
121538
121926
  };
121539
121927
  return {
121540
121928
  shop: () => shopShape(req),
121541
- orders: (args, _r, info) => ordersConnection(req, all6(ctx, "Order"), args, pathOf2(info.path)),
121929
+ orders: (args, _r, info) => ordersConnection(req, all6(ctx, "Order"), args, pathOf3(info.path)),
121542
121930
  order: one7("Order", orderShape),
121543
- products: (args, _r, info) => productsConnection(req, args, pathOf2(info.path)),
121931
+ products: (args, _r, info) => productsConnection(req, args, pathOf3(info.path)),
121544
121932
  product: one7("Product", productShape),
121545
- productVariants: (args, _r, info) => variantsConnection(req, args, pathOf2(info.path)),
121933
+ productVariants: (args, _r, info) => variantsConnection(req, args, pathOf3(info.path)),
121546
121934
  productVariant: one7("ProductVariant", variantShape),
121547
- customers: (args, _r, info) => customersConnection(req, args, pathOf2(info.path)),
121935
+ customers: (args, _r, info) => customersConnection(req, args, pathOf3(info.path)),
121548
121936
  customer: one7("Customer", customerShape),
121549
- locations: (args, _r, info) => locationsConnection(req, args, pathOf2(info.path)),
121937
+ locations: (args, _r, info) => locationsConnection(req, args, pathOf3(info.path)),
121550
121938
  // Without an id, Shopify returns the primary location.
121551
121939
  location: ({ id: id12 }) => {
121552
121940
  const d = id12 === void 0 || id12 === null ? all6(ctx, "Location")[0] : loadKind(ctx, "Location", checkId(id12));
@@ -121576,12 +121964,12 @@ function idempotency2(req, info, args) {
121576
121964
  return { key: key3, fingerprint: `${name5}
121577
121965
  ${JSON.stringify(args)}` };
121578
121966
  }
121579
- function once(req, info, args, run3, shape3, mismatch) {
121967
+ function once(req, info, args, run3, shape4, mismatch) {
121580
121968
  const idem = idempotency2(req, info, args);
121581
121969
  if (!idem) return run3().payload;
121582
121970
  const db2 = req.ctx.store.db;
121583
121971
  const seen = db2.prepare("SELECT fingerprint, response FROM shopify_idempotency WHERE key = ?").get(idem.key);
121584
- if (seen) return seen.fingerprint === idem.fingerprint && seen.response ? shape3(seen.response) : mismatch();
121972
+ if (seen) return seen.fingerprint === idem.fingerprint && seen.response ? shape4(seen.response) : mismatch();
121585
121973
  const result = run3();
121586
121974
  if (result.made) db2.prepare("INSERT INTO shopify_idempotency (key, fingerprint, response) VALUES (?, ?, ?)").run(idem.key, idem.fingerprint, result.made);
121587
121975
  return result.payload;
@@ -121938,14 +122326,14 @@ function inventoryAdjust(req, input2) {
121938
122326
  changes.push({ item: item2.gid, location: location.gid, delta: c.delta, before: current, ledger: c.ledgerDocumentUri ?? null, on_hand: quantities(ctx, l).on_hand });
121939
122327
  });
121940
122328
  if (errors2.length) return fail6(errors2);
121941
- const at2 = now6(req), recorded = [];
122329
+ const at2 = now6(req), recorded2 = [];
121942
122330
  for (const c of changes) {
121943
122331
  const column = input2.name;
121944
122332
  ctx.store.db.prepare(`UPDATE shopify_inventory SET ${column} = ${column} + ?, updated_ms = ? WHERE item = ? AND location = ?`).run(c.delta, at2, c.item, c.location);
121945
- recorded.push({ name: input2.name, delta: c.delta, after: c.before + c.delta, item: c.item, location: c.location, ledger: c.ledger });
121946
- 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 });
122333
+ recorded2.push({ name: input2.name, delta: c.delta, after: c.before + c.delta, item: c.item, location: c.location, ledger: c.ledger });
122334
+ 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 });
121947
122335
  }
121948
- const group5 = save8(ctx, "InventoryAdjustmentGroup", { gid: gid("InventoryAdjustmentGroup", nextNum(ctx, "InventoryAdjustmentGroup")), reason: input2.reason, reference: input2.referenceDocumentUri ?? null, created_ms: at2, changes: recorded });
122336
+ const group5 = save8(ctx, "InventoryAdjustmentGroup", { gid: gid("InventoryAdjustmentGroup", nextNum(ctx, "InventoryAdjustmentGroup")), reason: input2.reason, reference: input2.referenceDocumentUri ?? null, created_ms: at2, changes: recorded2 });
121949
122337
  return { made: group5.gid, payload: { inventoryAdjustmentGroup: adjustmentGroupShape(req, group5), userErrors: [] } };
121950
122338
  }
121951
122339
  function inventorySet(req, input2) {
@@ -121970,13 +122358,13 @@ function inventorySet(req, input2) {
121970
122358
  sets.push({ item: item2.gid, location: location.gid, delta: q.quantity - current, available: have.available, on_hand: have.on_hand });
121971
122359
  });
121972
122360
  if (errors2.length) return fail6(errors2);
121973
- const at2 = now6(req), recorded = [];
122361
+ const at2 = now6(req), recorded2 = [];
121974
122362
  for (const s of sets) {
121975
122363
  setAvailable(ctx, s.item, s.location, s.available + s.delta, at2);
121976
- 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 });
121977
- 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 });
122364
+ 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 });
122365
+ 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 });
121978
122366
  }
121979
- const group5 = save8(ctx, "InventoryAdjustmentGroup", { gid: gid("InventoryAdjustmentGroup", nextNum(ctx, "InventoryAdjustmentGroup")), reason: input2.reason, reference: input2.referenceDocumentUri ?? null, created_ms: at2, changes: recorded });
122367
+ const group5 = save8(ctx, "InventoryAdjustmentGroup", { gid: gid("InventoryAdjustmentGroup", nextNum(ctx, "InventoryAdjustmentGroup")), reason: input2.reason, reference: input2.referenceDocumentUri ?? null, created_ms: at2, changes: recorded2 });
121980
122368
  return { made: group5.gid, payload: { inventoryAdjustmentGroup: adjustmentGroupShape(req, group5), userErrors: [] } };
121981
122369
  }
121982
122370
  function customerWrite(req, input2, create2) {
@@ -122568,7 +122956,7 @@ function shopifyTwin() {
122568
122956
  const app2 = new Hono3();
122569
122957
  app2.post("/admin/api/:version/graphql.json", handleGraphql2);
122570
122958
  app2.all("*", unknownRoute12);
122571
- return { name: "shopify", basePath: "", app: app2, migrate: migrate26, seed: seed27, credentials: credentials26, actions: {}, checks: {}, dumpState: dumpState26, coverage: shopifyCoverage };
122959
+ return { name: "shopify", basePath: "", app: app2, migrate: migrate27, seed: seed27, credentials: credentials26, actions: {}, checks: {}, dumpState: dumpState26, coverage: shopifyCoverage };
122572
122960
  }
122573
122961
 
122574
122962
  // packages/server/src/twins/lob/db.ts
@@ -122874,7 +123262,7 @@ function assetUrl(ctx, kind, id12) {
122874
123262
  }
122875
123263
 
122876
123264
  // packages/server/src/twins/lob/db.ts
122877
- var SCHEMA16 = `
123265
+ var SCHEMA17 = `
122878
123266
  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);
122879
123267
  CREATE INDEX lob_directory_street ON lob_directory (primary_line, zip5);
122880
123268
  CREATE TABLE lob_addresses (
@@ -122895,8 +123283,8 @@ CREATE TABLE lob_mail (
122895
123283
  CREATE TABLE lob_files (id TEXT PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, bytes BLOB NOT NULL);
122896
123284
  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));
122897
123285
  `;
122898
- function migrate27(db2) {
122899
- db2.exec(SCHEMA16);
123286
+ function migrate28(db2) {
123287
+ db2.exec(SCHEMA17);
122900
123288
  }
122901
123289
  var LENGTH = { adr: 16, ltr: 16, psc: 16, chk: 16, bank: 15, tmpl: 15, vrsn: 15, file: 16 };
122902
123290
  var seededId4 = (prefix2, key3) => `${prefix2}_${createHash40("sha256").update(`lob:${prefix2}:${key3}`).digest("hex").slice(0, LENGTH[prefix2])}`;
@@ -123985,11 +124373,11 @@ async function handle18(c) {
123985
124373
  function lobTwin() {
123986
124374
  const app2 = new Hono3();
123987
124375
  app2.all("*", handle18);
123988
- return { name: "lob", basePath: "/v1", app: app2, migrate: migrate27, seed: seed28, credentials: credentials27, dumpState: dumpState27, actions: {}, checks: {}, coverage: lobCoverage };
124376
+ return { name: "lob", basePath: "/v1", app: app2, migrate: migrate28, seed: seed28, credentials: credentials27, dumpState: dumpState27, actions: {}, checks: {}, coverage: lobCoverage };
123989
124377
  }
123990
124378
 
123991
124379
  // packages/server/src/twins/paypal/db.ts
123992
- function migrate28(db2) {
124380
+ function migrate29(db2) {
123993
124381
  db2.exec(`
123994
124382
  CREATE TABLE paypal_objects (id TEXT PRIMARY KEY, kind TEXT NOT NULL, created_ms INTEGER NOT NULL, json TEXT NOT NULL);
123995
124383
  CREATE INDEX paypal_objects_kind ON paypal_objects (kind, created_ms);
@@ -124534,8 +124922,8 @@ var orderRoutes = [
124534
124922
  description: u.description
124535
124923
  });
124536
124924
  save9(r.ctx, "authorization", touch3(r, a));
124537
- const shape3 = captureShape(r, c);
124538
- return [201, r.prefer === "representation" ? shape3 : { id: shape3.id, status: shape3.status, links: shape3.links }];
124925
+ const shape4 = captureShape(r, c);
124926
+ return [201, r.prefer === "representation" ? shape4 : { id: shape4.id, status: shape4.status, links: shape4.links }];
124539
124927
  }
124540
124928
  },
124541
124929
  {
@@ -124570,8 +124958,8 @@ var orderRoutes = [
124570
124958
  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");
124571
124959
  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 });
124572
124960
  save9(r.ctx, "capture", { ...c, update_ms: r.ctx.clock.nowMs() });
124573
- const shape3 = refundShape2(r, x);
124574
- return [201, r.prefer === "representation" ? shape3 : { id: shape3.id, status: shape3.status, links: shape3.links }];
124961
+ const shape4 = refundShape2(r, x);
124962
+ return [201, r.prefer === "representation" ? shape4 : { id: shape4.id, status: shape4.status, links: shape4.links }];
124575
124963
  }
124576
124964
  },
124577
124965
  { 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"))) }
@@ -125311,11 +125699,11 @@ function paypalTwin() {
125311
125699
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
125312
125700
  for (const route11 of [...paypalRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle19(route11));
125313
125701
  app2.all("*", unknownRoute13);
125314
- return { name: "paypal", basePath: "", app: app2, migrate: migrate28, seed: seed29, credentials: credentials28, actions: {}, checks: {}, dumpState: dumpState28, coverage: paypalCoverage };
125702
+ return { name: "paypal", basePath: "", app: app2, migrate: migrate29, seed: seed29, credentials: credentials28, actions: {}, checks: {}, dumpState: dumpState28, coverage: paypalCoverage };
125315
125703
  }
125316
125704
 
125317
125705
  // packages/server/src/twins/jira/db.ts
125318
- function migrate29(db2) {
125706
+ function migrate30(db2) {
125319
125707
  db2.exec(`
125320
125708
  CREATE TABLE jira_site (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL);
125321
125709
  CREATE TABLE jira_users (account_id TEXT PRIMARY KEY, seq INTEGER NOT NULL, json TEXT NOT NULL);
@@ -127436,7 +127824,7 @@ function jiraTwin() {
127436
127824
  else for (const api3 of ["3", "2"]) app2.on(route11.method, `/rest/api/${api3}${route11.path}`, handle20(route11, api3));
127437
127825
  }
127438
127826
  app2.all("*", unknownRoute14);
127439
- return { name: "jira", basePath: "", app: app2, migrate: migrate29, seed: seed30, credentials: credentials29, actions: {}, checks: {}, dumpState: dumpState29, coverage: jiraCoverage };
127827
+ return { name: "jira", basePath: "", app: app2, migrate: migrate30, seed: seed30, credentials: credentials29, actions: {}, checks: {}, dumpState: dumpState29, coverage: jiraCoverage };
127440
127828
  }
127441
127829
 
127442
127830
  // packages/server/src/twins/kalshi/index.ts
@@ -127484,7 +127872,7 @@ function rsaPrivateKey(secrets) {
127484
127872
  }
127485
127873
 
127486
127874
  // packages/server/src/twins/kalshi/db.ts
127487
- var SCHEMA17 = `
127875
+ var SCHEMA18 = `
127488
127876
  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);
127489
127877
  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);
127490
127878
  CREATE TABLE kx_markets (
@@ -127506,8 +127894,8 @@ CREATE TABLE kx_fills (
127506
127894
  );
127507
127895
  CREATE TABLE kx_deposits (id INTEGER PRIMARY KEY, amount INTEGER NOT NULL, at_ms INTEGER NOT NULL);
127508
127896
  `;
127509
- function migrate30(db2) {
127510
- db2.exec(SCHEMA17);
127897
+ function migrate31(db2) {
127898
+ db2.exec(SCHEMA18);
127511
127899
  }
127512
127900
  var ONE = 1e4;
127513
127901
  var dollars2 = (price3) => (price3 / ONE).toFixed(4);
@@ -128534,12 +128922,12 @@ async function handle21(c) {
128534
128922
  function kalshiTwin() {
128535
128923
  const app2 = new Hono3();
128536
128924
  app2.all("*", handle21);
128537
- return { name: "kalshi", basePath: "/trade-api/v2", app: app2, migrate: migrate30, seed: seed31, credentials: credentials30, dumpState: dumpState30, actions: {}, checks: {}, coverage: kalshiCoverage };
128925
+ return { name: "kalshi", basePath: "/trade-api/v2", app: app2, migrate: migrate31, seed: seed31, credentials: credentials30, dumpState: dumpState30, actions: {}, checks: {}, coverage: kalshiCoverage };
128538
128926
  }
128539
128927
 
128540
128928
  // packages/server/src/twins/intercom/request.ts
128541
128929
  import { createHash as createHash43 } from "node:crypto";
128542
- function migrate31(db2) {
128930
+ function migrate32(db2) {
128543
128931
  db2.exec(`
128544
128932
  CREATE TABLE intercom_objects (kind TEXT NOT NULL, id TEXT NOT NULL, seq INTEGER NOT NULL, json TEXT NOT NULL, PRIMARY KEY (kind, id));
128545
128933
  CREATE INDEX intercom_objects_seq ON intercom_objects (kind, seq);
@@ -129754,11 +130142,11 @@ function intercomTwin() {
129754
130142
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
129755
130143
  for (const route11 of [...intercomRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle22(route11));
129756
130144
  app2.all("*", unknownRoute15);
129757
- return { name: "intercom", basePath: "", app: app2, migrate: migrate31, seed: seed32, credentials: credentials31, actions: {}, checks: {}, dumpState: dumpState31, coverage: intercomCoverage };
130145
+ return { name: "intercom", basePath: "", app: app2, migrate: migrate32, seed: seed32, credentials: credentials31, actions: {}, checks: {}, dumpState: dumpState31, coverage: intercomCoverage };
129758
130146
  }
129759
130147
 
129760
130148
  // packages/server/src/twins/zendesk/db.ts
129761
- var SCHEMA18 = `
130149
+ var SCHEMA19 = `
129762
130150
  CREATE TABLE zd_users (
129763
130151
  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,
129764
130152
  suspended INTEGER NOT NULL, external_id TEXT, default_group_id INTEGER, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL
@@ -129775,8 +130163,8 @@ CREATE TABLE zd_audits (id INTEGER PRIMARY KEY, ticket_id INTEGER NOT NULL, auth
129775
130163
  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);
129776
130164
  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);
129777
130165
  `;
129778
- function migrate32(db2) {
129779
- db2.exec(SCHEMA18);
130166
+ function migrate33(db2) {
130167
+ db2.exec(SCHEMA19);
129780
130168
  }
129781
130169
  var BASES2 = { user: 21457810001, organization: 360041201001, group: 360000118001, ticket: 4101, comment: 31870100001, audit: 31870200001, macro: 360101000001, view: 360102000001 };
129782
130170
  function nextId6(ctx, kind) {
@@ -129962,20 +130350,20 @@ var ordered = (order4, actual, term) => {
129962
130350
  if (b < 0 || a < 0) return term.op === ":" && term.value.toLowerCase() === "none" && actual === null;
129963
130351
  return term.op === ":" ? a === b : term.op === "<" ? a < b : term.op === ">" ? a > b : term.op === "<=" ? a <= b : a >= b;
129964
130352
  };
129965
- var contains = (haystack, needle) => haystack.toLowerCase().includes(needle.toLowerCase());
130353
+ var contains2 = (haystack, needle) => haystack.toLowerCase().includes(needle.toLowerCase());
129966
130354
  var person3 = (world4, id12, value4) => {
129967
130355
  if (value4 === "none") return id12 === null;
129968
130356
  if (id12 === null) return false;
129969
130357
  const user8 = world4.users.get(id12);
129970
- return value4 === "me" ? id12 === world4.me.id : !!user8 && (String(user8.id) === value4 || user8.email === value4.toLowerCase() || contains(user8.name, value4));
130358
+ return value4 === "me" ? id12 === world4.me.id : !!user8 && (String(user8.id) === value4 || user8.email === value4.toLowerCase() || contains2(user8.name, value4));
129971
130359
  };
129972
- var named2 = (map2, id12, value4) => value4 === "none" ? id12 === null : id12 !== null && (String(id12) === value4 || contains(map2.get(id12)?.name ?? "", value4));
130360
+ var named2 = (map2, id12, value4) => value4 === "none" ? id12 === null : id12 !== null && (String(id12) === value4 || contains2(map2.get(id12)?.name ?? "", value4));
129973
130361
  function ticketMatches(world4, ticket2, term) {
129974
130362
  const tags4 = tagsOf(ticket2.tags);
129975
130363
  switch (term.key) {
129976
130364
  case null: {
129977
130365
  const text21 = [ticket2.subject, ticket2.description, ...commentsOf2(world4.ctx, ticket2.id).map((comment8) => comment8.body), ...tags4].join("\n");
129978
- return contains(text21, term.value);
130366
+ return contains2(text21, term.value);
129979
130367
  }
129980
130368
  case "status":
129981
130369
  return ordered(STATUSES2, ticket2.status, term);
@@ -129997,11 +130385,11 @@ function ticketMatches(world4, ticket2, term) {
129997
130385
  case "tag":
129998
130386
  return tags4.includes(term.value.toLowerCase());
129999
130387
  case "subject":
130000
- return contains(ticket2.subject, term.value);
130388
+ return contains2(ticket2.subject, term.value);
130001
130389
  case "description":
130002
- return contains(ticket2.description, term.value);
130390
+ return contains2(ticket2.description, term.value);
130003
130391
  case "comment":
130004
- return commentsOf2(world4.ctx, ticket2.id).some((comment8) => contains(comment8.body, term.value));
130392
+ return commentsOf2(world4.ctx, ticket2.id).some((comment8) => contains2(comment8.body, term.value));
130005
130393
  case "via":
130006
130394
  return ticket2.via === term.value.toLowerCase();
130007
130395
  case "external_id":
@@ -130020,10 +130408,10 @@ function ticketMatches(world4, ticket2, term) {
130020
130408
  function userMatches2(world4, user8, term) {
130021
130409
  switch (term.key) {
130022
130410
  case null:
130023
- return contains(`${user8.name}
130411
+ return contains2(`${user8.name}
130024
130412
  ${user8.email ?? ""}`, term.value);
130025
130413
  case "name":
130026
- return contains(user8.name, term.value);
130414
+ return contains2(user8.name, term.value);
130027
130415
  case "email":
130028
130416
  return (user8.email ?? "") === term.value.toLowerCase() || term.value.startsWith("*") && (user8.email ?? "").endsWith(term.value.slice(1).toLowerCase());
130029
130417
  case "role":
@@ -130047,10 +130435,10 @@ ${user8.email ?? ""}`, term.value);
130047
130435
  function organizationMatches(world4, organization4, term) {
130048
130436
  switch (term.key) {
130049
130437
  case null:
130050
- return contains(`${organization4.name}
130438
+ return contains2(`${organization4.name}
130051
130439
  ${JSON.parse(organization4.domains).join(" ")}`, term.value);
130052
130440
  case "name":
130053
- return contains(organization4.name, term.value);
130441
+ return contains2(organization4.name, term.value);
130054
130442
  case "tags":
130055
130443
  case "tag":
130056
130444
  return tagsOf(organization4.tags).includes(term.value.toLowerCase());
@@ -130062,7 +130450,7 @@ ${JSON.parse(organization4.domains).join(" ")}`, term.value);
130062
130450
  }
130063
130451
  }
130064
130452
  function groupMatches(world4, group5, term) {
130065
- if (term.key === null || term.key === "name") return contains(group5.name, term.value);
130453
+ if (term.key === null || term.key === "name") return contains2(group5.name, term.value);
130066
130454
  return world4.unsupported(`the group search property ${term.key}`);
130067
130455
  }
130068
130456
 
@@ -130886,11 +131274,11 @@ async function handle23(c) {
130886
131274
  function zendeskTwin() {
130887
131275
  const app2 = new Hono3();
130888
131276
  app2.all("*", handle23);
130889
- return { name: "zendesk", basePath: "/api/v2", app: app2, migrate: migrate32, seed: seed33, credentials: credentials32, dumpState: dumpState32, actions: {}, checks: {}, coverage: zendeskCoverage };
131277
+ return { name: "zendesk", basePath: "/api/v2", app: app2, migrate: migrate33, seed: seed33, credentials: credentials32, dumpState: dumpState32, actions: {}, checks: {}, coverage: zendeskCoverage };
130890
131278
  }
130891
131279
 
130892
131280
  // packages/server/src/twins/google-calendar/request.ts
130893
- function migrate33(db2) {
131281
+ function migrate34(db2) {
130894
131282
  db2.exec(`
130895
131283
  CREATE TABLE gcal_owner (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL);
130896
131284
  CREATE TABLE gcal_calendars (id TEXT PRIMARY KEY, seq INTEGER NOT NULL, json TEXT NOT NULL);
@@ -131489,12 +131877,12 @@ function listEvents3(r, cal, only4) {
131489
131877
  defaultReminders: writable2(cal) ? [{ method: "popup", minutes: 10 }] : [],
131490
131878
  ...p2.next && { nextPageToken: p2.next },
131491
131879
  items: p2.slice.map(({ e, at: at2 }) => {
131492
- const shape3 = eventShape2(r, e, tz, at2, limited);
131493
- if (maxAttendees !== null && shape3.attendees?.length > maxAttendees) {
131494
- shape3.attendees = shape3.attendees.filter((a) => a.self).slice(0, 1);
131495
- shape3.attendeesOmitted = true;
131880
+ const shape4 = eventShape2(r, e, tz, at2, limited);
131881
+ if (maxAttendees !== null && shape4.attendees?.length > maxAttendees) {
131882
+ shape4.attendees = shape4.attendees.filter((a) => a.self).slice(0, 1);
131883
+ shape4.attendeesOmitted = true;
131496
131884
  }
131497
- return shape3;
131885
+ return shape4;
131498
131886
  })
131499
131887
  };
131500
131888
  }
@@ -131910,12 +132298,12 @@ function googleCalendarTwin() {
131910
132298
  const rank = (path4) => path4.split("/").filter((s) => s.startsWith(":")).length;
131911
132299
  for (const route11 of [...calendarRoutes].sort((a, b) => rank(a.path) - rank(b.path))) app2.on(route11.method, route11.path, handle24(route11));
131912
132300
  app2.all("*", unknownRoute16);
131913
- return { name: "google-calendar", basePath: "", unprefixedPaths: /^\/calendar\/v3\//, app: app2, migrate: migrate33, seed: seed34, credentials: credentials33, actions: {}, checks: {}, dumpState: dumpState33, coverage: googleCalendarCoverage };
132301
+ return { name: "google-calendar", basePath: "", unprefixedPaths: /^\/calendar\/v3\//, app: app2, migrate: migrate34, seed: seed34, credentials: credentials33, actions: {}, checks: {}, dumpState: dumpState33, coverage: googleCalendarCoverage };
131914
132302
  }
131915
132303
 
131916
132304
  // packages/server/src/twins/twilio/db.ts
131917
132305
  import { createHash as createHash45 } from "node:crypto";
131918
- var SCHEMA19 = `
132306
+ var SCHEMA20 = `
131919
132307
  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);
131920
132308
  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);
131921
132309
  CREATE TABLE tw_messages (
@@ -131932,8 +132320,8 @@ CREATE TABLE tw_verifications (
131932
132320
  created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL
131933
132321
  );
131934
132322
  `;
131935
- function migrate34(db2) {
131936
- db2.exec(SCHEMA19);
132323
+ function migrate35(db2) {
132324
+ db2.exec(SCHEMA20);
131937
132325
  }
131938
132326
  var seededSid = (prefix2, key3) => `${prefix2}${createHash45("sha256").update(`twilio:${prefix2}:${key3}`).digest("hex").slice(0, 32)}`;
131939
132327
  var newSid = (ctx, prefix2) => `${prefix2}${ctx.ids.hex(32)}`;
@@ -132592,11 +132980,11 @@ async function handle25(c) {
132592
132980
  function twilioTwin() {
132593
132981
  const app2 = new Hono3();
132594
132982
  app2.all("*", handle25);
132595
- return { name: "twilio", basePath: "", app: app2, migrate: migrate34, seed: seed35, credentials: credentials34, dumpState: dumpState34, actions: {}, checks: {}, coverage: twilioCoverage };
132983
+ return { name: "twilio", basePath: "", app: app2, migrate: migrate35, seed: seed35, credentials: credentials34, dumpState: dumpState34, actions: {}, checks: {}, coverage: twilioCoverage };
132596
132984
  }
132597
132985
 
132598
132986
  // packages/server/src/twins/asana/db.ts
132599
- var SCHEMA20 = `
132987
+ var SCHEMA21 = `
132600
132988
  CREATE TABLE as_users (gid TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, name TEXT NOT NULL);
132601
132989
  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);
132602
132990
  CREATE TABLE as_project_members (project TEXT NOT NULL, user TEXT NOT NULL, PRIMARY KEY (project, user));
@@ -132609,8 +132997,8 @@ CREATE TABLE as_memberships (task TEXT NOT NULL, project TEXT NOT NULL, section
132609
132997
  CREATE TABLE as_followers (task TEXT NOT NULL, user TEXT NOT NULL, PRIMARY KEY (task, user));
132610
132998
  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);
132611
132999
  `;
132612
- function migrate35(db2) {
132613
- db2.exec(SCHEMA20);
133000
+ function migrate36(db2) {
133001
+ db2.exec(SCHEMA21);
132614
133002
  }
132615
133003
  var BASES3 = { workspace: 1200000000000001, user: 1201000000000001, project: 1205000000000001, section: 1206000000000001, task: 1208000000000001, story: 1210000000000001 };
132616
133004
  function nextGid(ctx, kind) {
@@ -132908,22 +133296,22 @@ function treeOf(fields11) {
132908
133296
  }
132909
133297
  return root2;
132910
133298
  }
132911
- function shape2(ctx, value4, tree) {
132912
- if (Array.isArray(value4)) return value4.map((item2) => shape2(ctx, item2, tree));
133299
+ function shape3(ctx, value4, tree) {
133300
+ if (Array.isArray(value4)) return value4.map((item2) => shape3(ctx, item2, tree));
132913
133301
  if (value4 === null || typeof value4 !== "object") return value4;
132914
133302
  let record8 = value4;
132915
133303
  if (record8.resource_type && record8.gid && [...tree.keys()].some((field3) => !(field3 in record8))) record8 = expand2(ctx, record8);
132916
133304
  const out = "gid" in record8 ? { gid: record8.gid } : {};
132917
- for (const [field3, child2] of tree) if (field3 in record8) out[field3] = child2.size ? shape2(ctx, record8[field3], child2) : record8[field3];
133305
+ for (const [field3, child2] of tree) if (field3 in record8) out[field3] = child2.size ? shape3(ctx, record8[field3], child2) : record8[field3];
132918
133306
  return out;
132919
133307
  }
132920
133308
  function one5(call2, full2) {
132921
133309
  const tree = treeOf(call2.url.searchParams.get("opt_fields"));
132922
- return json26({ data: tree ? shape2(call2.ctx, full2, tree) : full2 });
133310
+ return json26({ data: tree ? shape3(call2.ctx, full2, tree) : full2 });
132923
133311
  }
132924
133312
  function list13(call2, items, full2, compact2) {
132925
133313
  const params9 = call2.url.searchParams, tree = treeOf(params9.get("opt_fields"));
132926
- const render = (item2) => tree ? shape2(call2.ctx, full2(item2), tree) : compact2(item2);
133314
+ const render = (item2) => tree ? shape3(call2.ctx, full2(item2), tree) : compact2(item2);
132927
133315
  if (params9.get("limit") === null) return json26({ data: items.map(render) });
132928
133316
  const limit = Number(params9.get("limit")), offset16 = params9.get("offset");
132929
133317
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw bad("limit: Value must be between 1 and 100");
@@ -133285,7 +133673,7 @@ function searchTasks(call2) {
133285
133673
  return (x < y ? -1 : x > y ? 1 : a.gid < b.gid ? -1 : 1) * (ascending ? 1 : -1);
133286
133674
  });
133287
133675
  const tree = treeOf(params9.get("opt_fields"));
133288
- return json26({ data: tasks.slice(0, limit).map((task2) => tree ? shape2(ctx, taskFull(ctx, task2), tree) : taskCompact(task2)) });
133676
+ return json26({ data: tasks.slice(0, limit).map((task2) => tree ? shape3(ctx, taskFull(ctx, task2), tree) : taskCompact(task2)) });
133289
133677
  }
133290
133678
  var route8 = (method2, path4, write4, handle30, notes6) => ({ method: method2, path: path4, write: write4, handle: handle30, ...notes6 && { notes: notes6 }, pattern: new RegExp(`^${path4.replace(/\{[^}]+\}/g, "([^/]+)")}$`) });
133291
133679
  var API = "/api/1.0";
@@ -133409,11 +133797,11 @@ async function handle26(c) {
133409
133797
  function asanaTwin() {
133410
133798
  const app2 = new Hono3();
133411
133799
  app2.all("*", handle26);
133412
- return { name: "asana", basePath: "/api/1.0", app: app2, migrate: migrate35, seed: seed36, credentials: credentials35, dumpState: dumpState35, actions: {}, checks: {}, coverage: asanaCoverage };
133800
+ return { name: "asana", basePath: "/api/1.0", app: app2, migrate: migrate36, seed: seed36, credentials: credentials35, dumpState: dumpState35, actions: {}, checks: {}, coverage: asanaCoverage };
133413
133801
  }
133414
133802
 
133415
133803
  // packages/server/src/twins/discord/db.ts
133416
- var SCHEMA21 = `
133804
+ var SCHEMA22 = `
133417
133805
  CREATE TABLE dc_users (id TEXT PRIMARY KEY, username TEXT NOT NULL UNIQUE, global_name TEXT, bot INTEGER NOT NULL);
133418
133806
  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);
133419
133807
  CREATE TABLE dc_members (user_id TEXT PRIMARY KEY, nick TEXT, roles TEXT NOT NULL, joined_ms INTEGER NOT NULL);
@@ -133427,8 +133815,8 @@ CREATE TABLE dc_messages (
133427
133815
  );
133428
133816
  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));
133429
133817
  `;
133430
- function migrate36(db2) {
133431
- db2.exec(SCHEMA21);
133818
+ function migrate37(db2) {
133819
+ db2.exec(SCHEMA22);
133432
133820
  }
133433
133821
  var TEXT3 = 0;
133434
133822
  var DM = 1;
@@ -134069,11 +134457,11 @@ async function handle27(c) {
134069
134457
  function discordTwin() {
134070
134458
  const app2 = new Hono3();
134071
134459
  app2.all("*", handle27);
134072
- return { name: "discord", basePath: "/api/v10", app: app2, migrate: migrate36, seed: seed37, credentials: credentials36, dumpState: dumpState36, actions: {}, checks: {}, coverage: discordCoverage };
134460
+ return { name: "discord", basePath: "/api/v10", app: app2, migrate: migrate37, seed: seed37, credentials: credentials36, dumpState: dumpState36, actions: {}, checks: {}, coverage: discordCoverage };
134073
134461
  }
134074
134462
 
134075
134463
  // packages/server/src/twins/sentry/db.ts
134076
- function migrate37(db2) {
134464
+ function migrate38(db2) {
134077
134465
  db2.exec(`
134078
134466
  CREATE TABLE sentry_org (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL);
134079
134467
  CREATE TABLE sentry_members (id TEXT PRIMARY KEY, seq INTEGER NOT NULL, json TEXT NOT NULL);
@@ -135020,8 +135408,8 @@ function apply(ctx, i, by2, c, ms) {
135020
135408
  const same2 = c.assign?.type === i.assignee?.type && c.assign?.id === i.assignee?.id;
135021
135409
  if (!same2) {
135022
135410
  i.assignee = c.assign;
135023
- const shape3 = actorShape(ctx, c.assign);
135024
- 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);
135411
+ const shape4 = actorShape(ctx, c.assign);
135412
+ 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);
135025
135413
  else activity(ctx, i, "unassigned", by2, {}, ms);
135026
135414
  }
135027
135415
  delta.assignedTo = actorShape(ctx, i.assignee);
@@ -136133,11 +136521,11 @@ function sentryTwin() {
136133
136521
  if (route11.path.startsWith(ISSUE)) app2.on(route11.method, `/api/0/issues/:issue${route11.path.slice(ISSUE.length)}`, handle28(route11));
136134
136522
  }
136135
136523
  app2.all("*", unknownRoute17);
136136
- return { name: "sentry", basePath: "", app: app2, migrate: migrate37, seed: seed38, credentials: credentials37, actions: { capture: capture2 }, checks: {}, dumpState: dumpState37, coverage: sentryCoverage };
136524
+ return { name: "sentry", basePath: "", app: app2, migrate: migrate38, seed: seed38, credentials: credentials37, actions: { capture: capture2 }, checks: {}, dumpState: dumpState37, coverage: sentryCoverage };
136137
136525
  }
136138
136526
 
136139
136527
  // packages/server/src/twins/airtable/db.ts
136140
- var SCHEMA22 = `
136528
+ var SCHEMA23 = `
136141
136529
  CREATE TABLE at_users (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, position INTEGER NOT NULL);
136142
136530
  CREATE TABLE at_bases (id TEXT PRIMARY KEY, name TEXT NOT NULL, permission TEXT NOT NULL, position INTEGER NOT NULL);
136143
136531
  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);
@@ -136153,8 +136541,8 @@ CREATE TABLE at_comments (
136153
136541
  created_ms INTEGER NOT NULL, updated_ms INTEGER, deleted_ms INTEGER
136154
136542
  );
136155
136543
  `;
136156
- function migrate38(db2) {
136157
- db2.exec(SCHEMA22);
136544
+ function migrate39(db2) {
136545
+ db2.exec(SCHEMA23);
136158
136546
  }
136159
136547
  var BASE625 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
136160
136548
  function newId7(ctx, kind) {
@@ -137487,7 +137875,7 @@ async function handle29(c) {
137487
137875
  function airtableTwin() {
137488
137876
  const app2 = new Hono3();
137489
137877
  app2.all("*", handle29);
137490
- return { name: "airtable", basePath: "/v0", app: app2, migrate: migrate38, seed: seed39, credentials: credentials38, dumpState: dumpState38, actions: {}, checks: {}, coverage: airtableCoverage };
137878
+ return { name: "airtable", basePath: "/v0", app: app2, migrate: migrate39, seed: seed39, credentials: credentials38, dumpState: dumpState38, actions: {}, checks: {}, coverage: airtableCoverage };
137491
137879
  }
137492
137880
 
137493
137881
  // packages/server/src/registry.ts
@@ -137516,6 +137904,7 @@ function envInfo(env, origin, port) {
137516
137904
  };
137517
137905
  }
137518
137906
  const mcp = Object.fromEntries(Object.entries(env.mcpTokens).map(([tool, token2]) => [tool, { url: `${origin}/e/${env.id}/mcp/${tool}`, token: token2 }]));
137907
+ 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 } }));
137519
137908
  return {
137520
137909
  id: env.id,
137521
137910
  sceneId: env.scene.id,
@@ -137523,6 +137912,7 @@ function envInfo(env, origin, port) {
137523
137912
  timeScale: env.scene.time_scale,
137524
137913
  services: services2,
137525
137914
  ...Object.keys(mcp).length ? { mcp } : {},
137915
+ ...tools.length ? { tools } : {},
137526
137916
  ...env.sandbox ? { sandbox: { ...structuredClone(env.sandbox), seed: env.seed } } : {}
137527
137917
  };
137528
137918
  }
@@ -138370,7 +138760,7 @@ function addressedEvent(env, event3) {
138370
138760
  // packages/server/src/sessions.ts
138371
138761
  function agentCalls(env) {
138372
138762
  let calls2;
138373
- return { first: (pattern) => (calls2 ??= env.trace.list().filter((entry2) => entry2.source === "agent")).find(compileTracePattern(pattern)) };
138763
+ return { first: (pattern) => (calls2 ??= env.trace.list().filter((entry2) => entry2.source === "agent")).find(compileTracePattern(pattern, sceneTools(env))) };
138374
138764
  }
138375
138765
  function lastTimedActorMs(env) {
138376
138766
  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;
@@ -138565,12 +138955,13 @@ var TrialSessions = class {
138565
138955
  env.touchLease();
138566
138956
  return { env, session: { ...record8.session } };
138567
138957
  }
138568
- done(token2) {
138958
+ done(token2, answer) {
138569
138959
  const { env, session } = this.authenticate(token2, true);
138570
138960
  return env.serialize(() => {
138571
138961
  this.authenticate(token2, true);
138572
138962
  const record8 = this.#record(env, session.id);
138573
138963
  if (record8.session.state === "prepared") throw new AnchaError("SESSION_CONFLICT", "session has not started");
138964
+ 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 } });
138574
138965
  if (record8.session.state === "running") record8.session.state = "done";
138575
138966
  });
138576
138967
  }
@@ -138928,7 +139319,8 @@ function sessionRoutes(opts, sessions) {
138928
139319
  signal: c.req.raw.signal
138929
139320
  })));
138930
139321
  app2.post("/done", async (c) => {
138931
- await sessions.done(token2(c.req.header("authorization")));
139322
+ const body6 = await c.req.json().catch(() => void 0);
139323
+ await sessions.done(token2(c.req.header("authorization")), body6 && typeof body6 === "object" && "output" in body6 ? { output: body6.output } : void 0);
138932
139324
  return c.json({ ok: true });
138933
139325
  });
138934
139326
  app2.get("/events", async (c) => {
@@ -139221,6 +139613,12 @@ function createApp(opts) {
139221
139613
  ...response5 !== void 0 && { response: response5 },
139222
139614
  gap: res.status === 501 || res.headers.has(GAP_HEADER),
139223
139615
  // Extract before TraceRecorder caps response bodies; never infer a harness fault from status.
139616
+ ...res.headers.has(SETUP_ISSUE_HEADER) && { issue: {
139617
+ kind: "tools",
139618
+ owner: "harness",
139619
+ service,
139620
+ message: typeof response5 === "object" && response5 !== null && typeof response5.error === "string" ? response5.error : "the test stopped before the agent ran"
139621
+ } },
139224
139622
  ...res.headers.has(INTERNAL_ERROR_HEADER) && { issue: {
139225
139623
  kind: "twin",
139226
139624
  owner: "harness",
@@ -142448,11 +142846,11 @@ function build() {
142448
142846
  const ResultTypeSchema = string2();
142449
142847
  const ResultMetaSchema = looseObject({ [SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) });
142450
142848
  const wireMeta = ResultMetaSchema.optional();
142451
- function wireResult(shape3) {
142849
+ function wireResult(shape4) {
142452
142850
  return looseObject({
142453
142851
  _meta: wireMeta,
142454
142852
  resultType: ResultTypeSchema.default("complete"),
142455
- ...shape3
142853
+ ...shape4
142456
142854
  });
142457
142855
  }
142458
142856
  const ResultSchema$1 = wireResult({});
@@ -142665,10 +143063,10 @@ function build() {
142665
143063
  "server/discover": dispatchRequest("server/discover", {}),
142666
143064
  "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape)
142667
143065
  };
142668
- function liftedResult(shape3) {
143066
+ function liftedResult(shape4) {
142669
143067
  return looseObject({
142670
143068
  _meta: wireMeta,
142671
- ...shape3
143069
+ ...shape4
142672
143070
  });
142673
143071
  }
142674
143072
  const dispatchResultSchemas = {
@@ -154456,9 +154854,9 @@ var McpServer = class {
154456
154854
  };
154457
154855
  this._registeredPrompts[name5] = registeredPrompt;
154458
154856
  if (argsSchema) {
154459
- const shape3 = getSchemaShape(argsSchema);
154460
- if (shape3) {
154461
- if (Object.values(shape3).some((field3) => {
154857
+ const shape4 = getSchemaShape(argsSchema);
154858
+ if (shape4) {
154859
+ if (Object.values(shape4).some((field3) => {
154462
154860
  return isCompletable(unwrapOptionalSchema(field3));
154463
154861
  })) this.setCompletionRequestHandler();
154464
154862
  }
@@ -156059,8 +156457,8 @@ function slackMcpServer(info, request4) {
156059
156457
  if (!service) throw new AnchaError("USAGE", "this sandbox does not include Slack");
156060
156458
  const client = createVendorClient(info, "slack", "/api/", request4);
156061
156459
  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." });
156062
- for (const [method2, description2, shape3] of definitions2) {
156063
- 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) => {
156460
+ for (const [method2, description2, shape4] of definitions2) {
156461
+ 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) => {
156064
156462
  return client.result("POST", method2, args, context2.mcpReq.signal);
156065
156463
  });
156066
156464
  }
@@ -156183,9 +156581,9 @@ function safePath(path4, allowRoot = false) {
156183
156581
  return allowRoot && path4 === "" || path4.length > 0 && !path4.includes("\\") && !path4.includes("\0") && path4.split("/").every((part) => part !== "" && part !== "." && part !== "..");
156184
156582
  }
156185
156583
  function registerGithubRepositoryTools(server, api3) {
156186
- const invoke2 = async (method2, path4, body6, signal, shape3) => {
156584
+ const invoke2 = async (method2, path4, body6, signal, shape4) => {
156187
156585
  const response5 = await api3.call(method2, path4, body6, signal);
156188
- return mcpJsonResult(response5.isError ? response5.value : shape3(response5.value), response5.isError);
156586
+ return mcpJsonResult(response5.isError ? response5.value : shape4(response5.value), response5.isError);
156189
156587
  };
156190
156588
  server.registerTool("list_commits", {
156191
156589
  description: "List commits in a branch with native pagination.",
@@ -156685,8 +157083,34 @@ function datadogMcpServer(info, request4) {
156685
157083
  return server;
156686
157084
  }
156687
157085
 
157086
+ // backend/src/mcp/agent-tools.ts
157087
+ function traced2(schema) {
157088
+ return { "~standard": { version: 1, vendor: "ancha", validate: (value4) => ({ value: value4 }), jsonSchema: { input: () => schema, output: () => schema } } };
157089
+ }
157090
+ function callToolResult(answer) {
157091
+ if (answer.wrap === "mcp" && answer.raw && typeof answer.raw === "object") return answer.raw;
157092
+ if (answer.error !== void 0) return mcpTextResult(answer.error, true);
157093
+ return typeof answer.result === "string" ? mcpTextResult(answer.result) : mcpJsonResult(answer.result ?? null);
157094
+ }
157095
+ function agentToolsMcpServer(info, request4) {
157096
+ if (!info.services.tools) throw new AnchaError("USAGE", "this world has no tools from a trace");
157097
+ const client = createVendorClient(info, "tools", "", request4);
157098
+ const server = new McpServer({ name: "ancha-tools", version: "1.0.0" }, { instructions: "The agent's own tools, answered as production answered them." });
157099
+ for (const tool of info.tools ?? []) {
157100
+ server.registerTool(
157101
+ tool.name,
157102
+ { ...tool.description && { description: tool.description }, inputSchema: traced2(tool.schema ?? { type: "object" }) },
157103
+ async (args, context2) => {
157104
+ const { value: value4, isError } = await client.call("POST", `/tools/${encodeURIComponent(tool.name)}`, { args }, context2.mcpReq.signal);
157105
+ return isError && value4?.error && !("source" in value4) ? mcpJsonResult(value4, true) : callToolResult(value4);
157106
+ }
157107
+ );
157108
+ }
157109
+ return server;
157110
+ }
157111
+
156688
157112
  // backend/src/mcp/http.ts
156689
- var factories = { slack: slackMcpServer, github: githubMcpServer, pagerduty: pagerdutyMcpServer, datadog: datadogMcpServer };
157113
+ var factories = { slack: slackMcpServer, github: githubMcpServer, pagerduty: pagerdutyMcpServer, datadog: datadogMcpServer, tools: agentToolsMcpServer };
156690
157114
  var names2 = { slack: SLACK_MCP_TOOL_NAMES, github: GITHUB_MCP_TOOL_NAMES, pagerduty: PAGERDUTY_MCP_TOOL_NAMES, datadog: DATADOG_MCP_TOOL_NAMES };
156691
157115
  var mcpTwins = Object.fromEntries(Object.entries(factories).map(([tool, factory]) => [
156692
157116
  tool,
@@ -156705,7 +157129,7 @@ var mcpTwins = Object.fromEntries(Object.entries(factories).map(([tool, factory]
156705
157129
  onerror: () => {
156706
157130
  }
156707
157131
  });
156708
- const known2 = new Set(names2[tool]);
157132
+ const known2 = new Set(tool === "tools" ? (info.tools ?? []).map((t) => t.name) : names2[tool]);
156709
157133
  return {
156710
157134
  close: () => handler.close(),
156711
157135
  async fetch(input2) {