@autohq/cli 0.1.683 → 0.1.685

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.
Files changed (3) hide show
  1. package/dist/agent-bridge.js +3653 -86
  2. package/dist/index.js +4893 -3848
  3. package/package.json +1 -1
@@ -3729,7 +3729,7 @@ var require_identity = __commonJS({
3729
3729
  var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type");
3730
3730
  var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
3731
3731
  var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
3732
- var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
3732
+ var isMap2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
3733
3733
  var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
3734
3734
  var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
3735
3735
  var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
@@ -3765,7 +3765,7 @@ var require_identity = __commonJS({
3765
3765
  exports.isAlias = isAlias;
3766
3766
  exports.isCollection = isCollection;
3767
3767
  exports.isDocument = isDocument;
3768
- exports.isMap = isMap;
3768
+ exports.isMap = isMap2;
3769
3769
  exports.isNode = isNode;
3770
3770
  exports.isPair = isPair;
3771
3771
  exports.isScalar = isScalar;
@@ -7875,9 +7875,9 @@ var require_resolve_flow_collection = __commonJS({
7875
7875
  var blockMsg = "Block collections are not allowed within flow collections";
7876
7876
  var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
7877
7877
  function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc2, onError, tag) {
7878
- const isMap = fc2.start.source === "{";
7879
- const fcName = isMap ? "flow map" : "flow sequence";
7880
- const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
7878
+ const isMap2 = fc2.start.source === "{";
7879
+ const fcName = isMap2 ? "flow map" : "flow sequence";
7880
+ const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
7881
7881
  const coll = new NodeClass(ctx.schema);
7882
7882
  coll.flow = true;
7883
7883
  const atRoot = ctx.atRoot;
@@ -7913,7 +7913,7 @@ var require_resolve_flow_collection = __commonJS({
7913
7913
  offset = props.end;
7914
7914
  continue;
7915
7915
  }
7916
- if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
7916
+ if (!isMap2 && ctx.options.strict && utilContainsNewline.containsNewline(key))
7917
7917
  onError(
7918
7918
  key,
7919
7919
  // checked by containsNewline()
@@ -7953,7 +7953,7 @@ var require_resolve_flow_collection = __commonJS({
7953
7953
  }
7954
7954
  }
7955
7955
  }
7956
- if (!isMap && !sep6 && !props.found) {
7956
+ if (!isMap2 && !sep6 && !props.found) {
7957
7957
  const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep6, null, props, onError);
7958
7958
  coll.items.push(valueNode);
7959
7959
  offset = valueNode.range[2];
@@ -7976,7 +7976,7 @@ var require_resolve_flow_collection = __commonJS({
7976
7976
  startOnNewline: false
7977
7977
  });
7978
7978
  if (valueProps.found) {
7979
- if (!isMap && !props.found && ctx.options.strict) {
7979
+ if (!isMap2 && !props.found && ctx.options.strict) {
7980
7980
  if (sep6)
7981
7981
  for (const st2 of sep6) {
7982
7982
  if (st2 === valueProps.found)
@@ -8008,7 +8008,7 @@ var require_resolve_flow_collection = __commonJS({
8008
8008
  const pair = new Pair.Pair(keyNode, valueNode);
8009
8009
  if (ctx.options.keepSourceTokens)
8010
8010
  pair.srcToken = collItem;
8011
- if (isMap) {
8011
+ if (isMap2) {
8012
8012
  const map2 = coll;
8013
8013
  if (utilMapIncludes.mapIncludes(ctx, map2.items, keyNode))
8014
8014
  onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
@@ -8024,7 +8024,7 @@ var require_resolve_flow_collection = __commonJS({
8024
8024
  offset = valueNode ? valueNode.range[2] : valueProps.end;
8025
8025
  }
8026
8026
  }
8027
- const expectedEnd = isMap ? "}" : "]";
8027
+ const expectedEnd = isMap2 ? "}" : "]";
8028
8028
  const [ce2, ...ee2] = fc2.end;
8029
8029
  let cePos = offset;
8030
8030
  if (ce2?.source === expectedEnd)
@@ -9993,7 +9993,7 @@ var require_lexer = __commonJS({
9993
9993
  var require_line_counter = __commonJS({
9994
9994
  "../../node_modules/yaml/dist/parse/line-counter.js"(exports) {
9995
9995
  "use strict";
9996
- var LineCounter = class {
9996
+ var LineCounter2 = class {
9997
9997
  constructor() {
9998
9998
  this.lineStarts = [];
9999
9999
  this.addNewLine = (offset) => this.lineStarts.push(offset);
@@ -10016,7 +10016,7 @@ var require_line_counter = __commonJS({
10016
10016
  };
10017
10017
  }
10018
10018
  };
10019
- exports.LineCounter = LineCounter;
10019
+ exports.LineCounter = LineCounter2;
10020
10020
  }
10021
10021
  });
10022
10022
 
@@ -10910,7 +10910,7 @@ var require_public_api = __commonJS({
10910
10910
  const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null;
10911
10911
  return { lineCounter: lineCounter$1, prettyErrors };
10912
10912
  }
10913
- function parseAllDocuments2(source, options = {}) {
10913
+ function parseAllDocuments(source, options = {}) {
10914
10914
  const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
10915
10915
  const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
10916
10916
  const composer$1 = new composer.Composer(options);
@@ -10985,7 +10985,7 @@ var require_public_api = __commonJS({
10985
10985
  return new Document.Document(value, _replacer, options).toString(options);
10986
10986
  }
10987
10987
  exports.parse = parse5;
10988
- exports.parseAllDocuments = parseAllDocuments2;
10988
+ exports.parseAllDocuments = parseAllDocuments;
10989
10989
  exports.parseDocument = parseDocument;
10990
10990
  exports.stringify = stringify;
10991
10991
  }
@@ -33191,11 +33191,11 @@ function decryptRuntimeBridgeBootstrap(input) {
33191
33191
  return { bootstrap, ignoredKeys: ignoredPlaintextKeys(raw) };
33192
33192
  }
33193
33193
  function ignoredPlaintextKeys(raw) {
33194
- const record2 = external_exports.record(external_exports.string(), external_exports.unknown()).parse(raw);
33194
+ const record3 = external_exports.record(external_exports.string(), external_exports.unknown()).parse(raw);
33195
33195
  const knownKeys = new Set(
33196
33196
  Object.keys(RuntimeBridgeBootstrapPlaintextSchema.shape)
33197
33197
  );
33198
- return Object.keys(record2).filter((key) => !knownKeys.has(key));
33198
+ return Object.keys(record3).filter((key) => !knownKeys.has(key));
33199
33199
  }
33200
33200
  function deriveBootstrapKey(accessToken, salt) {
33201
33201
  return Buffer.from(
@@ -33218,7 +33218,7 @@ function bootstrapAdditionalData(input) {
33218
33218
  // package.json
33219
33219
  var package_default = {
33220
33220
  name: "@autohq/cli",
33221
- version: "0.1.683",
33221
+ version: "0.1.685",
33222
33222
  license: "SEE LICENSE IN README.md",
33223
33223
  publishConfig: {
33224
33224
  access: "public"
@@ -34751,6 +34751,20 @@ var SERVICE_ACCOUNT_SCOPE_PRESETS = {
34751
34751
  };
34752
34752
  var ServiceAccountScopePresetSchema = external_exports.enum(["read-only", "applier"]);
34753
34753
 
34754
+ // ../../packages/schemas/src/capability-attenuation.ts
34755
+ function grantedCapabilityLevel(capability) {
34756
+ return typeof capability === "string" ? capability : capability.level;
34757
+ }
34758
+ function unattributedCapabilityLevel(capability) {
34759
+ return typeof capability === "string" ? void 0 : capability.unattributed;
34760
+ }
34761
+ function effectiveCapabilityLevel(capability, requesterEligible) {
34762
+ return requesterEligible ? grantedCapabilityLevel(capability) : unattributedCapabilityLevel(capability) ?? grantedCapabilityLevel(capability);
34763
+ }
34764
+ function capabilityLevelAtMost(input) {
34765
+ return input.levels.indexOf(input.floor) <= input.levels.indexOf(input.grant);
34766
+ }
34767
+
34754
34768
  // ../../packages/schemas/src/conversation.ts
34755
34769
  var CONVERSATION_ROLES = [
34756
34770
  "system",
@@ -35125,25 +35139,25 @@ var ClaudeCodeStreamRecordSchema = external_exports.discriminatedUnion("type", [
35125
35139
  ClaudeCodeResultRecordSchema
35126
35140
  ]);
35127
35141
  function parseClaudeCodeStreamRecord(parsed) {
35128
- const record2 = ClaudeCodeStreamRecordSchema.parse(parsed);
35129
- if (record2.type === "system") {
35130
- const projection = systemProjection(record2);
35142
+ const record3 = ClaudeCodeStreamRecordSchema.parse(parsed);
35143
+ if (record3.type === "system") {
35144
+ const projection = systemProjection(record3);
35131
35145
  return {
35132
35146
  projections: projection ? [projection] : []
35133
35147
  };
35134
35148
  }
35135
- if (record2.type === "assistant" || record2.type === "user") {
35149
+ if (record3.type === "assistant" || record3.type === "user") {
35136
35150
  return {
35137
- projections: record2.type === "assistant" ? assistantContentProjections(
35138
- record2.message,
35139
- record2.message.id ?? UNKNOWN_MESSAGE_ID
35140
- ) : userContentProjections(record2.message)
35151
+ projections: record3.type === "assistant" ? assistantContentProjections(
35152
+ record3.message,
35153
+ record3.message.id ?? UNKNOWN_MESSAGE_ID
35154
+ ) : userContentProjections(record3.message)
35141
35155
  };
35142
35156
  }
35143
- const isError = record2.is_error === true || record2.subtype === "error";
35144
- const sdkErrorMessage = record2.errors?.map((error51) => error51.trim()).filter(Boolean).join("\n");
35145
- const errorMessage10 = isError ? record2.error ?? record2.result ?? (sdkErrorMessage || void 0) ?? "claude-code reported an error" : void 0;
35146
- const usage = claudeCodeUsageFromRecord(record2);
35157
+ const isError = record3.is_error === true || record3.subtype === "error";
35158
+ const sdkErrorMessage = record3.errors?.map((error51) => error51.trim()).filter(Boolean).join("\n");
35159
+ const errorMessage10 = isError ? record3.error ?? record3.result ?? (sdkErrorMessage || void 0) ?? "claude-code reported an error" : void 0;
35160
+ const usage = claudeCodeUsageFromRecord(record3);
35147
35161
  return {
35148
35162
  projections: [],
35149
35163
  result: {
@@ -35153,8 +35167,8 @@ function parseClaudeCodeStreamRecord(parsed) {
35153
35167
  }
35154
35168
  };
35155
35169
  }
35156
- function isClaudeCodeInterruptMarker(record2) {
35157
- const parsed = ClaudeCodeInterruptMarkerRecordSchema.safeParse(record2);
35170
+ function isClaudeCodeInterruptMarker(record3) {
35171
+ const parsed = ClaudeCodeInterruptMarkerRecordSchema.safeParse(record3);
35158
35172
  if (!parsed.success) {
35159
35173
  return false;
35160
35174
  }
@@ -35205,19 +35219,19 @@ function textContent(text) {
35205
35219
  ]
35206
35220
  };
35207
35221
  }
35208
- function systemProjection(record2) {
35209
- if (record2.subtype === "init") {
35222
+ function systemProjection(record3) {
35223
+ if (record3.subtype === "init") {
35210
35224
  return {
35211
35225
  role: "system",
35212
35226
  kind: "status",
35213
35227
  content: textContent(
35214
- `claude-code session started${record2.model ? ` (${record2.model})` : ""}`
35228
+ `claude-code session started${record3.model ? ` (${record3.model})` : ""}`
35215
35229
  )
35216
35230
  };
35217
35231
  }
35218
- if (record2.subtype === "api_retry") {
35219
- const attempt = record2.attempt;
35220
- const maxRetries = record2.max_retries;
35232
+ if (record3.subtype === "api_retry") {
35233
+ const attempt = record3.attempt;
35234
+ const maxRetries = record3.max_retries;
35221
35235
  return {
35222
35236
  role: "system",
35223
35237
  kind: "status",
@@ -35343,9 +35357,9 @@ function userContentProjections(message) {
35343
35357
  }
35344
35358
  return projections;
35345
35359
  }
35346
- function claudeCodeUsageFromRecord(record2) {
35347
- const aggregate = record2.usage;
35348
- const modelUsage = record2.modelUsage;
35360
+ function claudeCodeUsageFromRecord(record3) {
35361
+ const aggregate = record3.usage;
35362
+ const modelUsage = record3.modelUsage;
35349
35363
  if (!aggregate && !modelUsage) {
35350
35364
  return void 0;
35351
35365
  }
@@ -35364,7 +35378,7 @@ function claudeCodeUsageFromRecord(record2) {
35364
35378
  outputTokens: tokenCount(aggregate?.output_tokens),
35365
35379
  cacheCreationTokens: tokenCount(aggregate?.cache_creation_input_tokens),
35366
35380
  cacheReadTokens: tokenCount(aggregate?.cache_read_input_tokens),
35367
- totalCostUsd: usdAmount(record2.total_cost_usd),
35381
+ totalCostUsd: usdAmount(record3.total_cost_usd),
35368
35382
  perModel
35369
35383
  };
35370
35384
  }
@@ -35817,6 +35831,193 @@ function parseApprovalRequest(method, requestId, params) {
35817
35831
  }
35818
35832
  }
35819
35833
 
35834
+ // ../../packages/schemas/src/pricing.ts
35835
+ var UnknownPricingVersionError = class extends Error {
35836
+ constructor(version2) {
35837
+ super(`Unknown pricing rate-card version: ${version2}`);
35838
+ this.name = "UnknownPricingVersionError";
35839
+ }
35840
+ };
35841
+ var UnknownPricingModelError = class extends Error {
35842
+ constructor(model, version2) {
35843
+ super(`No pricing for model "${model}" in rate card ${version2}`);
35844
+ this.name = "UnknownPricingModelError";
35845
+ }
35846
+ };
35847
+ var RATE_CARD_2026_06_23 = {
35848
+ version: "2026-06-23",
35849
+ effectiveAt: "2026-06-23T00:00:00.000Z",
35850
+ models: {
35851
+ "claude-opus-4-8": opusTier(),
35852
+ "claude-opus-4-7": opusTier(),
35853
+ "claude-opus-4-6": opusTier(),
35854
+ "claude-sonnet-4-6": tier(3, 15),
35855
+ "claude-haiku-4-5": tier(1, 5),
35856
+ "claude-haiku-4-5-20251001": tier(1, 5),
35857
+ "claude-fable-5": tier(10, 50),
35858
+ // OpenAI gpt-5.3-codex, standard tier: input $1.75/Mtok, cached input
35859
+ // $0.175/Mtok, output $14.00/Mtok. Source (verified 2026-06-23):
35860
+ // https://developers.openai.com/api/docs/models/gpt-5.3-codex and
35861
+ // https://developers.openai.com/api/docs/pricing (priority tier is 2x; we
35862
+ // bill standard).
35863
+ "gpt-5.3-codex": openAiTier({
35864
+ input: 1.75,
35865
+ cachedInput: 0.175,
35866
+ output: 14
35867
+ })
35868
+ }
35869
+ };
35870
+ var RATE_CARD_2026_07_04 = {
35871
+ version: "2026-07-04",
35872
+ effectiveAt: "2026-07-04T00:00:00.000Z",
35873
+ models: {
35874
+ ...RATE_CARD_2026_06_23.models,
35875
+ // OpenAI gpt-5.5, standard tier: input $5.00/Mtok, cached input
35876
+ // $0.50/Mtok, output $30.00/Mtok. Source (verified 2026-07-04):
35877
+ // https://developers.openai.com/api/docs/models/gpt-5.5 and
35878
+ // https://developers.openai.com/api/docs/pricing (priority tier is 2x; we
35879
+ // bill standard).
35880
+ "gpt-5.5": openAiTier({
35881
+ input: 5,
35882
+ cachedInput: 0.5,
35883
+ output: 30
35884
+ }),
35885
+ // OpenAI may echo the dated snapshot id on responses even when callers send
35886
+ // the `gpt-5.5` alias. Price that dated id identically so usage enrichment
35887
+ // keeps recording codex-default spend instead of dropping unknown models.
35888
+ "gpt-5.5-2026-04-23": openAiTier({
35889
+ input: 5,
35890
+ cachedInput: 0.5,
35891
+ output: 30
35892
+ })
35893
+ }
35894
+ };
35895
+ var RATE_CARD_2026_07_07 = {
35896
+ version: "2026-07-07",
35897
+ effectiveAt: "2026-07-07T00:00:00.000Z",
35898
+ models: {
35899
+ ...RATE_CARD_2026_07_04.models,
35900
+ // Anthropic Claude Sonnet 5 list price: input $3/Mtok, output $15/Mtok
35901
+ // (same tier as Sonnet 4.6). Anthropic runs an introductory $2/$10 rate
35902
+ // through 2026-08-31; we bill list, matching the rest of the card.
35903
+ "claude-sonnet-5": tier(3, 15)
35904
+ }
35905
+ };
35906
+ var RATE_CARD_2026_07_09 = {
35907
+ version: "2026-07-09",
35908
+ effectiveAt: "2026-07-09T00:00:00.000Z",
35909
+ models: {
35910
+ ...RATE_CARD_2026_07_07.models,
35911
+ // OpenAI GPT-5.6 Sol preview price: input $5.00/Mtok, cache writes
35912
+ // $6.25/Mtok, cached reads $0.50/Mtok, and output $30.00/Mtok. Source
35913
+ // (verified 2026-07-09):
35914
+ // https://help.openai.com/en/articles/20001325-a-preview-of-gpt-5-6-sol-terra-and-luna
35915
+ "gpt-5.6-sol": openAiCacheWriteTier({
35916
+ input: 5,
35917
+ output: 30
35918
+ })
35919
+ }
35920
+ };
35921
+ var RATE_CARD_2026_07_30 = {
35922
+ version: "2026-07-30",
35923
+ effectiveAt: "2026-07-30T00:00:00.000Z",
35924
+ models: {
35925
+ ...RATE_CARD_2026_07_09.models,
35926
+ "gpt-5.6-terra": openAiLongContextTier({
35927
+ input: 2,
35928
+ output: 12
35929
+ }),
35930
+ "gpt-5.6-luna": openAiLongContextTier({
35931
+ input: 0.2,
35932
+ output: 1.2
35933
+ })
35934
+ }
35935
+ };
35936
+ var RATE_CARD_2026_09_01 = {
35937
+ version: "2026-09-01",
35938
+ effectiveAt: "2026-09-01T00:00:00.000Z",
35939
+ models: {
35940
+ ...RATE_CARD_2026_07_30.models,
35941
+ "claude-fable-5-1": fable51Tier(),
35942
+ "claude-mythos-5-1": fable51Tier()
35943
+ }
35944
+ };
35945
+ var RATE_CARD_2026_09_04 = {
35946
+ version: "2026-09-04",
35947
+ effectiveAt: "2026-09-04T00:00:00.000Z",
35948
+ models: {
35949
+ ...RATE_CARD_2026_09_01.models,
35950
+ "gpt-6-astra": openAiLongContextTier({
35951
+ input: 10,
35952
+ output: 50
35953
+ })
35954
+ }
35955
+ };
35956
+ var PRICING_RATE_CARDS = {
35957
+ [RATE_CARD_2026_06_23.version]: RATE_CARD_2026_06_23,
35958
+ [RATE_CARD_2026_07_04.version]: RATE_CARD_2026_07_04,
35959
+ [RATE_CARD_2026_07_07.version]: RATE_CARD_2026_07_07,
35960
+ [RATE_CARD_2026_07_09.version]: RATE_CARD_2026_07_09,
35961
+ [RATE_CARD_2026_07_30.version]: RATE_CARD_2026_07_30,
35962
+ [RATE_CARD_2026_09_01.version]: RATE_CARD_2026_09_01,
35963
+ [RATE_CARD_2026_09_04.version]: RATE_CARD_2026_09_04
35964
+ };
35965
+ var CURRENT_PRICING_VERSION = RATE_CARD_2026_09_04.version;
35966
+ function getModelPricing(model, pricingVersion = CURRENT_PRICING_VERSION) {
35967
+ const card = PRICING_RATE_CARDS[pricingVersion];
35968
+ if (!card) {
35969
+ throw new UnknownPricingVersionError(pricingVersion);
35970
+ }
35971
+ const pricing = card.models[model];
35972
+ if (!pricing) {
35973
+ throw new UnknownPricingModelError(model, pricingVersion);
35974
+ }
35975
+ return pricing;
35976
+ }
35977
+ function tier(inputUsdPerMtok, outputUsdPerMtok) {
35978
+ return {
35979
+ inputUsdPerMtok,
35980
+ outputUsdPerMtok,
35981
+ cacheWrite5mUsdPerMtok: inputUsdPerMtok * 1.25,
35982
+ cacheReadUsdPerMtok: inputUsdPerMtok * 0.1
35983
+ };
35984
+ }
35985
+ function opusTier() {
35986
+ return tier(5, 25);
35987
+ }
35988
+ function fable51Tier() {
35989
+ return {
35990
+ ...tier(10, 50),
35991
+ cacheReadUsdPerMtok: 0.25
35992
+ };
35993
+ }
35994
+ function openAiTier(rates) {
35995
+ return {
35996
+ inputUsdPerMtok: rates.input,
35997
+ outputUsdPerMtok: rates.output,
35998
+ cacheWrite5mUsdPerMtok: rates.input,
35999
+ cacheReadUsdPerMtok: rates.cachedInput
36000
+ };
36001
+ }
36002
+ function openAiCacheWriteTier(rates) {
36003
+ return {
36004
+ inputUsdPerMtok: rates.input,
36005
+ outputUsdPerMtok: rates.output,
36006
+ cacheWrite5mUsdPerMtok: rates.input * 1.25,
36007
+ cacheReadUsdPerMtok: rates.input * 0.1
36008
+ };
36009
+ }
36010
+ function openAiLongContextTier(rates) {
36011
+ return {
36012
+ ...openAiCacheWriteTier(rates),
36013
+ longContext: {
36014
+ thresholdInputTokens: 272e3,
36015
+ inputMultiplier: 2,
36016
+ outputMultiplier: 1.5
36017
+ }
36018
+ };
36019
+ }
36020
+
35820
36021
  // ../../packages/schemas/src/model-selection.ts
35821
36022
  var MODEL_API_TOKEN_PROVIDERS = [
35822
36023
  "anthropic",
@@ -35842,6 +36043,13 @@ var CODEX_MAX_REASONING_EFFORTS = [
35842
36043
  ...CODEX_REASONING_EFFORTS,
35843
36044
  "max"
35844
36045
  ];
36046
+ var CODEX_ASTRA_REASONING_EFFORTS = [
36047
+ "low",
36048
+ "medium",
36049
+ "high",
36050
+ "xhigh",
36051
+ "max"
36052
+ ];
35845
36053
  var ClaudeCodeReasoningEffortSchema = external_exports.enum(
35846
36054
  CLAUDE_CODE_REASONING_EFFORTS
35847
36055
  );
@@ -35894,6 +36102,3023 @@ var ModelRoutingConfigSchema = external_exports.object({
35894
36102
  // authored fields are mutually exclusive at validation).
35895
36103
  fallbackModelIds: external_exports.array(external_exports.string().min(1)).min(1).max(2).optional()
35896
36104
  }).strict();
36105
+ var InvalidModelSelectionError = class extends Error {
36106
+ constructor(message) {
36107
+ super(message);
36108
+ this.name = "InvalidModelSelectionError";
36109
+ }
36110
+ };
36111
+ var HARNESS_MODEL_RULES = {
36112
+ "claude-code": {
36113
+ defaultProvider: "anthropic",
36114
+ providers: ["anthropic"],
36115
+ defaultModel: "claude-opus-4-8",
36116
+ curatedModels: {
36117
+ anthropic: [
36118
+ "claude-opus-4-8",
36119
+ "fable",
36120
+ "claude-fable-5-1",
36121
+ "claude-mythos-5-1",
36122
+ "claude-fable-5",
36123
+ "claude-opus-4-7",
36124
+ "claude-opus-4-6",
36125
+ "claude-sonnet-5",
36126
+ "claude-sonnet-4-6",
36127
+ "claude-haiku-4-5",
36128
+ "claude-haiku-4-5-20251001"
36129
+ ]
36130
+ },
36131
+ curatedModelMetadata: {
36132
+ anthropic: {
36133
+ fable: {
36134
+ displayName: "Claude Fable 5.1",
36135
+ availability: "generally_available"
36136
+ },
36137
+ "claude-fable-5-1": {
36138
+ displayName: "Claude Fable 5.1",
36139
+ availability: "generally_available"
36140
+ },
36141
+ "claude-mythos-5-1": {
36142
+ displayName: "Claude Mythos 5.1",
36143
+ availability: "limited_access",
36144
+ availabilityLabel: "Project Glasswing"
36145
+ }
36146
+ }
36147
+ },
36148
+ openProviderPatterns: {},
36149
+ // The pinned Claude Agent SDK applies "high" when the effort option is
36150
+ // omitted, so "high" is what default-effort sessions have always run at.
36151
+ defaultReasoningEffort: "high",
36152
+ reasoningEfforts: CLAUDE_CODE_REASONING_EFFORTS,
36153
+ reasoningEffortsByModel: {}
36154
+ },
36155
+ codex: {
36156
+ defaultProvider: "openai",
36157
+ providers: ["openai", "openrouter"],
36158
+ defaultModel: "gpt-5.6-sol",
36159
+ curatedModels: {
36160
+ openai: [
36161
+ "gpt-6-astra",
36162
+ "gpt-5.6-sol",
36163
+ "gpt-5.6-terra",
36164
+ "gpt-5.6-luna",
36165
+ "gpt-5.5",
36166
+ "gpt-5.3-codex"
36167
+ ]
36168
+ },
36169
+ curatedModelMetadata: {
36170
+ openai: {
36171
+ "gpt-6-astra": {
36172
+ displayName: "GPT-6 Astra",
36173
+ availability: "limited_access",
36174
+ availabilityLabel: "Trusted Access Program"
36175
+ }
36176
+ }
36177
+ },
36178
+ openProviderPatterns: {
36179
+ openrouter: OPENROUTER_MODEL_SLUG_PATTERN
36180
+ },
36181
+ defaultReasoningEffort: "medium",
36182
+ reasoningEfforts: CODEX_REASONING_EFFORTS,
36183
+ reasoningEffortsByModel: {
36184
+ openai: {
36185
+ "gpt-6-astra": {
36186
+ defaultEffort: "medium",
36187
+ efforts: CODEX_ASTRA_REASONING_EFFORTS
36188
+ },
36189
+ "gpt-5.6-sol": {
36190
+ defaultEffort: "medium",
36191
+ efforts: CODEX_MAX_REASONING_EFFORTS
36192
+ },
36193
+ "gpt-5.6-terra": {
36194
+ defaultEffort: "medium",
36195
+ efforts: CODEX_MAX_REASONING_EFFORTS
36196
+ },
36197
+ "gpt-5.6-luna": {
36198
+ defaultEffort: "medium",
36199
+ efforts: CODEX_MAX_REASONING_EFFORTS
36200
+ },
36201
+ "gpt-5.5": {
36202
+ defaultEffort: "medium",
36203
+ efforts: CODEX_REASONING_EFFORTS
36204
+ },
36205
+ "gpt-5.3-codex": {
36206
+ defaultEffort: "medium",
36207
+ efforts: CODEX_REASONING_EFFORTS
36208
+ }
36209
+ },
36210
+ openrouter: {
36211
+ "moonshotai/kimi-k3": {
36212
+ defaultEffort: "high",
36213
+ efforts: ["high", "xhigh"]
36214
+ },
36215
+ "z-ai/glm-5.2": {
36216
+ defaultEffort: "high",
36217
+ efforts: ["high", "xhigh"]
36218
+ },
36219
+ "x-ai/grok-4.5": {
36220
+ defaultEffort: "high",
36221
+ efforts: ["medium", "high"]
36222
+ },
36223
+ "anthropic/claude-sonnet-5": {
36224
+ defaultEffort: "medium",
36225
+ efforts: ["low", "medium", "high", "xhigh"]
36226
+ },
36227
+ "moonshotai/kimi-k2.7-code": {
36228
+ defaultEffort: "high",
36229
+ efforts: ["high", "xhigh"]
36230
+ }
36231
+ }
36232
+ }
36233
+ }
36234
+ };
36235
+ function modelRulesForHarness(harness) {
36236
+ return HARNESS_MODEL_RULES[harness];
36237
+ }
36238
+ var MODEL_WIRE_ID_ALIASES = {
36239
+ fable: "claude-fable-5-1"
36240
+ };
36241
+ function resolveModelWireId(id) {
36242
+ return MODEL_WIRE_ID_ALIASES[id] ?? id;
36243
+ }
36244
+ function reasoningEffortRulesForModelSelection(input) {
36245
+ const rules = modelRulesForHarness(input.harness);
36246
+ const model = resolveModelSelectionForHarness(input.harness, input.model);
36247
+ return rules.reasoningEffortsByModel[model.provider]?.[model.id] ?? {
36248
+ defaultEffort: rules.defaultReasoningEffort,
36249
+ efforts: rules.reasoningEfforts
36250
+ };
36251
+ }
36252
+ function resolveModelSelectionForHarness(harness, selection) {
36253
+ const rules = modelRulesForHarness(harness);
36254
+ const provider = selection?.provider ?? rules.defaultProvider;
36255
+ const id = selection?.id ?? rules.defaultModel;
36256
+ validateModelProviderForHarness(harness, provider);
36257
+ validateModelIdForProvider({ harness, provider, id });
36258
+ return { provider, id };
36259
+ }
36260
+ function validateReasoningEffortForHarness(input) {
36261
+ if (!input.reasoningEffort) {
36262
+ return;
36263
+ }
36264
+ const rules = reasoningEffortRulesForModelSelection({
36265
+ harness: input.harness,
36266
+ model: input.model
36267
+ });
36268
+ if (!rules.efforts.includes(input.reasoningEffort)) {
36269
+ throw new InvalidModelSelectionError(
36270
+ `${input.harness} does not support reasoning effort "${input.reasoningEffort}"`
36271
+ );
36272
+ }
36273
+ }
36274
+ function validateAgentModelOpenRouterForHarness(spec, context) {
36275
+ const openrouter = spec.model?.openrouter;
36276
+ if (!openrouter) {
36277
+ return;
36278
+ }
36279
+ if (spec.resolvedModel?.provider !== "openrouter") {
36280
+ context.addIssue({
36281
+ code: external_exports.ZodIssueCode.custom,
36282
+ path: ["model", "openrouter"],
36283
+ message: `model.openrouter is only valid when the resolved provider is openrouter (got ${spec.resolvedModel?.provider ?? "none"})`
36284
+ });
36285
+ return;
36286
+ }
36287
+ const primaryId = spec.resolvedModel.id;
36288
+ const seen = /* @__PURE__ */ new Set();
36289
+ for (const [index, id] of openrouter.models.entries()) {
36290
+ if (id === primaryId) {
36291
+ context.addIssue({
36292
+ code: external_exports.ZodIssueCode.custom,
36293
+ path: ["model", "openrouter", "models", index],
36294
+ message: "model.openrouter.models must not include the primary model id (it is prepended automatically)"
36295
+ });
36296
+ return;
36297
+ }
36298
+ if (seen.has(id)) {
36299
+ context.addIssue({
36300
+ code: external_exports.ZodIssueCode.custom,
36301
+ path: ["model", "openrouter", "models", index],
36302
+ message: "model.openrouter.models must not contain duplicate entries"
36303
+ });
36304
+ return;
36305
+ }
36306
+ seen.add(id);
36307
+ }
36308
+ }
36309
+ function validateAgentModelFallbacksForHarness(spec, context) {
36310
+ const fallbacks = spec.model?.fallbacks;
36311
+ if (!fallbacks || fallbacks.length === 0) {
36312
+ return;
36313
+ }
36314
+ if (spec.model?.openrouter) {
36315
+ context.addIssue({
36316
+ code: external_exports.ZodIssueCode.custom,
36317
+ path: ["model", "fallbacks"],
36318
+ message: "model.fallbacks and model.openrouter cannot be combined"
36319
+ });
36320
+ return;
36321
+ }
36322
+ const primary = spec.resolvedModel;
36323
+ if (!primary) {
36324
+ return;
36325
+ }
36326
+ const seenIds = /* @__PURE__ */ new Set([primary.id]);
36327
+ for (const [index, fallback] of fallbacks.entries()) {
36328
+ let resolved;
36329
+ try {
36330
+ resolved = resolveModelSelectionForHarness(spec.harness, {
36331
+ provider: fallback.provider ?? primary.provider,
36332
+ id: fallback.id
36333
+ });
36334
+ } catch (error51) {
36335
+ context.addIssue({
36336
+ code: external_exports.ZodIssueCode.custom,
36337
+ path: ["model", "fallbacks", index],
36338
+ message: error51 instanceof Error ? error51.message : String(error51)
36339
+ });
36340
+ continue;
36341
+ }
36342
+ if (resolved.provider !== primary.provider) {
36343
+ context.addIssue({
36344
+ code: external_exports.ZodIssueCode.custom,
36345
+ path: ["model", "fallbacks", index, "provider"],
36346
+ message: `model.fallbacks entries must resolve to the primary's provider (${primary.provider}); got ${resolved.provider}`
36347
+ });
36348
+ continue;
36349
+ }
36350
+ if (seenIds.has(resolved.id)) {
36351
+ context.addIssue({
36352
+ code: external_exports.ZodIssueCode.custom,
36353
+ path: ["model", "fallbacks", index, "id"],
36354
+ message: "model.fallbacks ids must be distinct and must not repeat the primary model id"
36355
+ });
36356
+ continue;
36357
+ }
36358
+ seenIds.add(resolved.id);
36359
+ try {
36360
+ validateReasoningEffortForHarness({
36361
+ harness: spec.harness,
36362
+ model: resolved,
36363
+ reasoningEffort: spec.reasoningEffort
36364
+ });
36365
+ } catch (error51) {
36366
+ context.addIssue({
36367
+ code: external_exports.ZodIssueCode.custom,
36368
+ path: ["model", "fallbacks", index],
36369
+ message: error51 instanceof Error ? error51.message : String(error51)
36370
+ });
36371
+ }
36372
+ }
36373
+ }
36374
+ function validateAgentModelFieldsForHarness(spec, context) {
36375
+ const harness = spec.harness;
36376
+ if (harness !== "claude-code" && harness !== "codex") {
36377
+ return;
36378
+ }
36379
+ let resolvedModel;
36380
+ try {
36381
+ resolvedModel = resolveModelSelectionForHarness(harness, spec.model);
36382
+ } catch (error51) {
36383
+ context.addIssue({
36384
+ code: external_exports.ZodIssueCode.custom,
36385
+ path: ["model"],
36386
+ message: error51 instanceof Error ? error51.message : String(error51)
36387
+ });
36388
+ }
36389
+ try {
36390
+ validateReasoningEffortForHarness({
36391
+ harness,
36392
+ model: resolvedModel,
36393
+ reasoningEffort: spec.reasoningEffort
36394
+ });
36395
+ } catch (error51) {
36396
+ context.addIssue({
36397
+ code: external_exports.ZodIssueCode.custom,
36398
+ path: ["reasoningEffort"],
36399
+ message: error51 instanceof Error ? error51.message : String(error51)
36400
+ });
36401
+ }
36402
+ validateAgentModelOpenRouterForHarness(
36403
+ { harness, model: spec.model, resolvedModel },
36404
+ context
36405
+ );
36406
+ validateAgentModelFallbacksForHarness(
36407
+ {
36408
+ harness,
36409
+ model: spec.model,
36410
+ reasoningEffort: spec.reasoningEffort,
36411
+ resolvedModel
36412
+ },
36413
+ context
36414
+ );
36415
+ }
36416
+ function validateModelProviderForHarness(harness, provider) {
36417
+ const rules = modelRulesForHarness(harness);
36418
+ if (!rules.providers.includes(provider)) {
36419
+ throw new InvalidModelSelectionError(
36420
+ `${harness} does not support ${provider} models`
36421
+ );
36422
+ }
36423
+ }
36424
+ function validateModelIdForProvider(input) {
36425
+ const rules = modelRulesForHarness(input.harness);
36426
+ const curated = rules.curatedModels[input.provider];
36427
+ if (curated?.includes(input.id)) {
36428
+ validatePricingForClosedProviderSelection(input);
36429
+ return;
36430
+ }
36431
+ const pattern = rules.openProviderPatterns[input.provider];
36432
+ if (pattern?.test(input.id)) {
36433
+ return;
36434
+ }
36435
+ if (curated) {
36436
+ throw new InvalidModelSelectionError(
36437
+ `${input.provider} model "${input.id}" is not available for ${input.harness}`
36438
+ );
36439
+ }
36440
+ throw new InvalidModelSelectionError(
36441
+ `${input.provider} model ids are not open for ${input.harness}`
36442
+ );
36443
+ }
36444
+ function validatePricingForClosedProviderSelection(input) {
36445
+ if (input.provider === "openrouter") {
36446
+ return;
36447
+ }
36448
+ try {
36449
+ getModelPricing(resolveModelWireId(input.id));
36450
+ } catch (error51) {
36451
+ if (error51 instanceof UnknownPricingModelError || error51 instanceof UnknownPricingVersionError) {
36452
+ throw new InvalidModelSelectionError(
36453
+ `${input.provider} model "${input.id}" cannot be scheduled for ${input.harness} without current pricing`
36454
+ );
36455
+ }
36456
+ throw error51;
36457
+ }
36458
+ }
36459
+
36460
+ // ../../packages/schemas/src/resources.ts
36461
+ var ResourceNameSchema = external_exports.string().trim().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/);
36462
+ var StringMapSchema = external_exports.record(external_exports.string().min(1), external_exports.string());
36463
+ var MetadataInputSchema = external_exports.object({
36464
+ name: ResourceNameSchema,
36465
+ labels: StringMapSchema.optional(),
36466
+ annotations: StringMapSchema.optional()
36467
+ });
36468
+ var MetadataSchema = MetadataInputSchema.extend({
36469
+ uid: OpaqueIdSchema2,
36470
+ generation: external_exports.number().int().positive(),
36471
+ resourceVersion: external_exports.string().min(1),
36472
+ createdAt: external_exports.string().datetime(),
36473
+ updatedAt: external_exports.string().datetime()
36474
+ });
36475
+ function resourceEnvelopeSchema(spec) {
36476
+ return external_exports.object({
36477
+ metadata: MetadataSchema,
36478
+ spec
36479
+ });
36480
+ }
36481
+ function resourceApplySchema(spec) {
36482
+ return external_exports.object({
36483
+ metadata: MetadataInputSchema,
36484
+ spec
36485
+ });
36486
+ }
36487
+
36488
+ // ../../packages/schemas/src/connections.ts
36489
+ var ConnectionNameSchema = ResourceNameSchema;
36490
+ var ProviderConnectionReferenceSchema = external_exports.object({
36491
+ provider: ProviderNameSchema,
36492
+ connection: ConnectionNameSchema
36493
+ });
36494
+ var ProjectConnectionAllocationSpecSchema = external_exports.object({
36495
+ provider: ProviderNameSchema
36496
+ });
36497
+ var ProjectConnectionAllocationResourceSchema = resourceEnvelopeSchema(
36498
+ ProjectConnectionAllocationSpecSchema
36499
+ );
36500
+ var GithubConnectionAccountSchema = external_exports.object({
36501
+ login: external_exports.string().trim().min(1),
36502
+ type: external_exports.enum(["User", "Organization"])
36503
+ });
36504
+ var GithubConnectionRepositorySchema = external_exports.object({
36505
+ id: external_exports.number().int().positive().optional(),
36506
+ fullName: external_exports.string().trim().min(1)
36507
+ });
36508
+ var GITHUB_CONNECTION_EVENTS = [
36509
+ "installation",
36510
+ "installation_repositories",
36511
+ "push",
36512
+ "pull_request",
36513
+ "check_run",
36514
+ "issues",
36515
+ "issue_comment",
36516
+ "pull_request_review",
36517
+ "pull_request_review_comment",
36518
+ "pull_request_review_thread",
36519
+ // `workflow_run` fires when a GitHub Actions run completes. Auto ingests
36520
+ // only `action=completed` as `github.workflow_run.completed` — the general
36521
+ // "CI on main finished" primitive that `check_run.completed` cannot cover
36522
+ // because check runs hard-require PR association.
36523
+ "workflow_run",
36524
+ // `commit_comment` fires on a new comment attached to a commit (the
36525
+ // quickstart deploy comment that carries the site URL). Auto ingests only
36526
+ // `action=created` as `github.commit_comment.created`.
36527
+ "commit_comment"
36528
+ ];
36529
+ var GithubConnectionEventSchema = external_exports.enum(GITHUB_CONNECTION_EVENTS);
36530
+ var GithubConnectionSpecSchema = external_exports.object({
36531
+ provider: external_exports.literal("github"),
36532
+ installationId: external_exports.string().trim().min(1),
36533
+ account: GithubConnectionAccountSchema,
36534
+ repositorySelection: external_exports.enum(["all", "selected"]).default("all"),
36535
+ repositories: external_exports.array(GithubConnectionRepositorySchema).default([]),
36536
+ events: external_exports.array(GithubConnectionEventSchema).min(1).default(["pull_request"])
36537
+ });
36538
+ var ConnectionSpecSchema = GithubConnectionSpecSchema;
36539
+ var ConnectionResourceSchema = resourceEnvelopeSchema(ConnectionSpecSchema);
36540
+ var ConnectionApplyRequestSchema = resourceApplySchema(ConnectionSpecSchema);
36541
+ var ConnectionStartReturnToSchema = external_exports.enum([
36542
+ "onboarding",
36543
+ "connections"
36544
+ ]);
36545
+ var GithubRepositoryPickerDestinationSchema = external_exports.enum([
36546
+ "settings",
36547
+ "onboarding",
36548
+ "sessions",
36549
+ "agents"
36550
+ ]);
36551
+ var GithubRepositoryPickerContinuationSchema = external_exports.object({
36552
+ organizationId: OrganizationIdSchema,
36553
+ projectId: ProjectIdSchema,
36554
+ destination: GithubRepositoryPickerDestinationSchema
36555
+ });
36556
+ var ConnectionStartRequestSchema = external_exports.object({
36557
+ organizationId: OrganizationIdSchema.optional(),
36558
+ provider: ProviderNameSchema,
36559
+ allowProjectId: ProjectIdSchema.optional(),
36560
+ returnTo: ConnectionStartReturnToSchema.optional(),
36561
+ githubRepositoryPickerDestination: GithubRepositoryPickerDestinationSchema.optional(),
36562
+ replace: external_exports.object({
36563
+ connection: ConnectionNameSchema,
36564
+ removeFirst: external_exports.boolean().default(false)
36565
+ }).optional()
36566
+ }).superRefine((value, context) => {
36567
+ if (value.githubRepositoryPickerDestination && (value.provider !== "github" || !value.allowProjectId)) {
36568
+ context.addIssue({
36569
+ code: "custom",
36570
+ message: "GitHub repository picker continuations require a GitHub project connection",
36571
+ path: ["githubRepositoryPickerDestination"]
36572
+ });
36573
+ }
36574
+ });
36575
+ var ConnectionProviderDescriptorSchema = external_exports.object({
36576
+ provider: ProviderNameSchema,
36577
+ displayName: external_exports.string().trim().min(1),
36578
+ credentialKind: ProviderCredentialKindSchema,
36579
+ oauthManualRedirectSetup: external_exports.object({
36580
+ mode: external_exports.enum(["self_service", "provider_approval"]),
36581
+ explanation: external_exports.string().trim().min(1),
36582
+ instructions: external_exports.array(external_exports.string().trim().min(1)).min(1),
36583
+ callbackUrl: external_exports.string().trim().url(),
36584
+ documentationAction: external_exports.object({
36585
+ label: external_exports.string().trim().min(1),
36586
+ url: external_exports.string().trim().url()
36587
+ }),
36588
+ settingsAction: external_exports.object({
36589
+ label: external_exports.string().trim().min(1),
36590
+ url: external_exports.string().trim().url()
36591
+ }).optional()
36592
+ }).optional()
36593
+ });
36594
+ var ConnectionProviderListResponseSchema = external_exports.object({
36595
+ providers: external_exports.array(ConnectionProviderDescriptorSchema)
36596
+ });
36597
+ var ConnectionStartResponseSchema = external_exports.discriminatedUnion("status", [
36598
+ external_exports.object({
36599
+ status: external_exports.literal("authorization_required"),
36600
+ provider: ProviderNameSchema,
36601
+ authorizationUrl: external_exports.string().trim().url(),
36602
+ message: external_exports.string().trim().min(1)
36603
+ }),
36604
+ external_exports.object({
36605
+ status: external_exports.literal("not_implemented"),
36606
+ provider: ProviderNameSchema,
36607
+ message: external_exports.string().trim().min(1)
36608
+ }),
36609
+ // Providers with no OAuth (Telegram): the user completes manual provider-side
36610
+ // steps, then submits the resulting token to the provider's connection
36611
+ // endpoint. `steps` is ordered, human-readable wizard guidance.
36612
+ external_exports.object({
36613
+ status: external_exports.literal("token_required"),
36614
+ provider: ProviderNameSchema,
36615
+ message: external_exports.string().trim().min(1),
36616
+ steps: external_exports.array(external_exports.string().trim().min(1)).min(1)
36617
+ })
36618
+ ]);
36619
+ var TelegramConnectionCreateRequestSchema = external_exports.object({
36620
+ organizationId: OrganizationIdSchema.optional(),
36621
+ token: external_exports.string().trim().min(1),
36622
+ name: ConnectionNameSchema.optional(),
36623
+ validateOnly: external_exports.boolean().default(false),
36624
+ /** Grant this project access to the connection once created. */
36625
+ allowProjectId: ProjectIdSchema.optional()
36626
+ });
36627
+ var TelegramManagerBotSummarySchema = external_exports.object({
36628
+ botUserId: external_exports.string().trim().min(1),
36629
+ botUsername: external_exports.string().trim().min(1),
36630
+ botName: external_exports.string().trim().min(1)
36631
+ });
36632
+ var TelegramConnectionCreateResponseSchema = external_exports.discriminatedUnion(
36633
+ "status",
36634
+ [
36635
+ external_exports.object({
36636
+ status: external_exports.literal("invalid_token"),
36637
+ message: external_exports.string().trim().min(1)
36638
+ }),
36639
+ external_exports.object({
36640
+ status: external_exports.literal("management_mode_disabled"),
36641
+ manager: TelegramManagerBotSummarySchema,
36642
+ message: external_exports.string().trim().min(1)
36643
+ }),
36644
+ external_exports.object({
36645
+ status: external_exports.literal("validated"),
36646
+ manager: TelegramManagerBotSummarySchema,
36647
+ message: external_exports.string().trim().min(1)
36648
+ }),
36649
+ external_exports.object({
36650
+ status: external_exports.literal("connected"),
36651
+ connection: ConnectionNameSchema,
36652
+ manager: TelegramManagerBotSummarySchema,
36653
+ organizationId: OrganizationIdSchema,
36654
+ message: external_exports.string().trim().min(1)
36655
+ })
36656
+ ]
36657
+ );
36658
+ var ModelProviderConnectionCreateRequestSchema = external_exports.object({
36659
+ organizationId: OrganizationIdSchema.optional(),
36660
+ provider: ModelApiTokenProviderSchema,
36661
+ token: external_exports.string().trim().min(1),
36662
+ name: ConnectionNameSchema.default("default"),
36663
+ /** Grant this project access to the connection once created. */
36664
+ allowProjectId: ProjectIdSchema.optional()
36665
+ });
36666
+ var ModelProviderConnectionCreateResponseSchema = external_exports.object({
36667
+ status: external_exports.literal("connected"),
36668
+ provider: ModelApiTokenProviderSchema,
36669
+ connection: ConnectionNameSchema,
36670
+ providerGrantId: external_exports.string().trim().min(1),
36671
+ organizationId: OrganizationIdSchema,
36672
+ message: external_exports.string().trim().min(1)
36673
+ });
36674
+ var ConnectionAllowRequestSchema = external_exports.object({
36675
+ organizationId: OrganizationIdSchema.optional(),
36676
+ provider: ProviderNameSchema,
36677
+ projectId: ProjectIdSchema,
36678
+ connection: ConnectionNameSchema.optional()
36679
+ });
36680
+ var SlackConfigTokenRegisterRequestSchema = external_exports.object({
36681
+ connection: ConnectionNameSchema.optional(),
36682
+ workspace: external_exports.string().trim().min(1).optional(),
36683
+ refreshToken: external_exports.string().trim().min(1)
36684
+ });
36685
+ var SlackConfigTokenRegisterResponseSchema = external_exports.object({
36686
+ status: external_exports.literal("registered"),
36687
+ connection: ConnectionNameSchema,
36688
+ workspace: external_exports.string().trim().min(1),
36689
+ expiresAt: external_exports.string().datetime()
36690
+ });
36691
+ var ConnectionAllowResponseSchema = external_exports.object({
36692
+ status: external_exports.literal("allocated"),
36693
+ provider: ProviderNameSchema,
36694
+ projectId: ProjectIdSchema,
36695
+ connection: ConnectionNameSchema,
36696
+ providerGrantId: external_exports.string().trim().min(1),
36697
+ message: external_exports.string().trim().min(1)
36698
+ });
36699
+ var ConnectionRemoveRequestSchema = external_exports.object({
36700
+ organizationId: OrganizationIdSchema.optional(),
36701
+ provider: ProviderNameSchema,
36702
+ connection: ConnectionNameSchema
36703
+ });
36704
+ var ConnectionRemoveResponseSchema = external_exports.object({
36705
+ status: external_exports.literal("removed"),
36706
+ provider: ProviderNameSchema,
36707
+ connection: ConnectionNameSchema,
36708
+ providerGrantId: external_exports.string().trim().min(1),
36709
+ message: external_exports.string().trim().min(1)
36710
+ });
36711
+
36712
+ // ../../packages/schemas/src/mounts.ts
36713
+ var AbsoluteMountPathSchema = external_exports.string().trim().min(1).refine((value) => value.startsWith("/"), {
36714
+ message: "Mount paths must be absolute"
36715
+ });
36716
+ var GITHUB_MOUNT_CAPABILITY_LEVELS = [
36717
+ "none",
36718
+ "read",
36719
+ "write"
36720
+ ];
36721
+ var GithubMountCapabilityLevelSchema = external_exports.enum(
36722
+ GITHUB_MOUNT_CAPABILITY_LEVELS
36723
+ );
36724
+ var GithubMountCapabilitySchema = external_exports.union([
36725
+ GithubMountCapabilityLevelSchema,
36726
+ external_exports.object({
36727
+ level: GithubMountCapabilityLevelSchema,
36728
+ unattributed: GithubMountCapabilityLevelSchema
36729
+ }).strict().superRefine((capability, context) => {
36730
+ if (!capabilityLevelAtMost({
36731
+ floor: capability.unattributed,
36732
+ grant: capability.level,
36733
+ levels: GITHUB_MOUNT_CAPABILITY_LEVELS
36734
+ })) {
36735
+ context.addIssue({
36736
+ code: external_exports.ZodIssueCode.custom,
36737
+ message: "unattributed capability level must not exceed level",
36738
+ path: ["unattributed"]
36739
+ });
36740
+ }
36741
+ })
36742
+ ]);
36743
+ var GITHUB_MOUNT_MERGE_CAPABILITY_LEVELS = ["none", "write"];
36744
+ var GithubMountMergeCapabilityLevelSchema = external_exports.enum(
36745
+ GITHUB_MOUNT_MERGE_CAPABILITY_LEVELS
36746
+ );
36747
+ var GithubMountMergeCapabilitySchema = external_exports.union([
36748
+ GithubMountMergeCapabilityLevelSchema,
36749
+ external_exports.object({
36750
+ level: GithubMountMergeCapabilityLevelSchema,
36751
+ unattributed: GithubMountMergeCapabilityLevelSchema
36752
+ }).strict().superRefine((capability, context) => {
36753
+ if (!capabilityLevelAtMost({
36754
+ floor: capability.unattributed,
36755
+ grant: capability.level,
36756
+ levels: GITHUB_MOUNT_MERGE_CAPABILITY_LEVELS
36757
+ })) {
36758
+ context.addIssue({
36759
+ code: external_exports.ZodIssueCode.custom,
36760
+ message: "unattributed capability level must not exceed level",
36761
+ path: ["unattributed"]
36762
+ });
36763
+ }
36764
+ })
36765
+ ]);
36766
+ var DEFAULT_GITHUB_MOUNT_CAPABILITIES = {
36767
+ contents: "write",
36768
+ pullRequests: "write",
36769
+ issues: "write",
36770
+ checks: "read",
36771
+ actions: "read",
36772
+ workflows: "none",
36773
+ secrets: "none",
36774
+ merge: "none"
36775
+ };
36776
+ var GitMountAuthSchema = external_exports.discriminatedUnion("kind", [
36777
+ external_exports.object({
36778
+ kind: external_exports.literal("none")
36779
+ }),
36780
+ external_exports.object({
36781
+ kind: external_exports.literal("githubApp"),
36782
+ installationId: external_exports.string().trim().min(1).optional(),
36783
+ commitAuthor: external_exports.object({
36784
+ name: external_exports.string().trim().min(1),
36785
+ email: external_exports.string().trim().min(1).refine((value) => value.includes("@"), {
36786
+ message: "Git commit author email must contain @"
36787
+ })
36788
+ }).optional(),
36789
+ capabilities: external_exports.object({
36790
+ contents: GithubMountCapabilitySchema.default("write"),
36791
+ pullRequests: GithubMountCapabilitySchema.default("write"),
36792
+ issues: GithubMountCapabilitySchema.default("write"),
36793
+ checks: GithubMountCapabilitySchema.default("read"),
36794
+ actions: GithubMountCapabilitySchema.default("read"),
36795
+ workflows: GithubMountCapabilitySchema.default("none"),
36796
+ // Grants the GitHub Actions secrets API (repository and environment
36797
+ // secrets). Secret values are write-only on GitHub's side; read grants
36798
+ // listing secret names, never values.
36799
+ secrets: GithubMountCapabilitySchema.default("none"),
36800
+ merge: GithubMountMergeCapabilitySchema.default("none")
36801
+ }).strict().superRefine((capabilities, context) => {
36802
+ if (grantedCapabilityLevel(capabilities.merge) === "write" && (grantedCapabilityLevel(capabilities.contents) !== "write" || grantedCapabilityLevel(capabilities.pullRequests) !== "write")) {
36803
+ context.addIssue({
36804
+ code: external_exports.ZodIssueCode.custom,
36805
+ message: "merge: write requires contents: write and pullRequests: write",
36806
+ path: ["merge"]
36807
+ });
36808
+ }
36809
+ const unattributed = effectiveGithubMountCapabilities(
36810
+ capabilities,
36811
+ false
36812
+ );
36813
+ if (unattributed.merge === "write" && (unattributed.contents !== "write" || unattributed.pullRequests !== "write")) {
36814
+ context.addIssue({
36815
+ code: external_exports.ZodIssueCode.custom,
36816
+ message: "unattributed merge: write requires unattributed contents: write and pullRequests: write",
36817
+ path: ["merge"]
36818
+ });
36819
+ }
36820
+ }).default({ ...DEFAULT_GITHUB_MOUNT_CAPABILITIES })
36821
+ })
36822
+ ]);
36823
+ var GitMountSchema = external_exports.object({
36824
+ kind: external_exports.literal("git"),
36825
+ repository: external_exports.string().trim().min(1),
36826
+ mountPath: AbsoluteMountPathSchema,
36827
+ ref: external_exports.string().trim().min(1).optional(),
36828
+ depth: external_exports.number().int().positive().optional(),
36829
+ auth: GitMountAuthSchema.default({
36830
+ kind: "none"
36831
+ })
36832
+ });
36833
+ var AgentMountSchema = external_exports.discriminatedUnion("kind", [GitMountSchema]);
36834
+ function effectiveGithubMountCapabilities(capabilities, requesterEligible) {
36835
+ return {
36836
+ actions: effectiveCapabilityLevel(capabilities.actions, requesterEligible),
36837
+ checks: effectiveCapabilityLevel(capabilities.checks, requesterEligible),
36838
+ contents: effectiveCapabilityLevel(
36839
+ capabilities.contents,
36840
+ requesterEligible
36841
+ ),
36842
+ issues: effectiveCapabilityLevel(capabilities.issues, requesterEligible),
36843
+ merge: effectiveCapabilityLevel(capabilities.merge, requesterEligible),
36844
+ pullRequests: effectiveCapabilityLevel(
36845
+ capabilities.pullRequests,
36846
+ requesterEligible
36847
+ ),
36848
+ secrets: effectiveCapabilityLevel(capabilities.secrets, requesterEligible),
36849
+ workflows: effectiveCapabilityLevel(
36850
+ capabilities.workflows,
36851
+ requesterEligible
36852
+ )
36853
+ };
36854
+ }
36855
+
36856
+ // ../../packages/schemas/src/github-sync.ts
36857
+ var GITHUB_SYNC_AUTO_PATH = ".auto";
36858
+ var GITHUB_SYNC_CI_WATCHDOG_DEFAULT_DELAY_MS = 15e3;
36859
+ var GithubSyncRepositoryFullNameSchema = external_exports.string().trim().min(1).regex(/^[^/\s]+\/[^/\s]+$/, {
36860
+ message: "repository must be in owner/name form"
36861
+ });
36862
+ var GithubSyncProductionBranchSchema = external_exports.string().trim().min(1).max(255).refine((branch) => !branch.startsWith("/") && !branch.endsWith("/"), {
36863
+ message: "branch must not start or end with /"
36864
+ });
36865
+ var GithubSyncCiWatchdogWorkflowSchema = external_exports.object({
36866
+ workflowId: external_exports.string().trim().min(1).max(255)
36867
+ }).strict();
36868
+ var GithubSyncCiWatchdogSchema = external_exports.object({
36869
+ workflows: external_exports.array(GithubSyncCiWatchdogWorkflowSchema).max(10).default([]),
36870
+ checkDelayMs: external_exports.number().int().nonnegative().default(GITHUB_SYNC_CI_WATCHDOG_DEFAULT_DELAY_MS)
36871
+ }).strict();
36872
+ var GithubSyncBindingSchema = external_exports.object({
36873
+ id: external_exports.string().trim().min(1),
36874
+ organizationId: OrganizationIdSchema,
36875
+ projectId: ProjectIdSchema,
36876
+ providerGrantId: ProviderGrantIdSchema,
36877
+ installationId: external_exports.string().trim().min(1),
36878
+ repoFullName: GithubSyncRepositoryFullNameSchema,
36879
+ repoId: external_exports.string().trim().min(1).nullable(),
36880
+ productionBranch: GithubSyncProductionBranchSchema,
36881
+ autoPath: external_exports.literal(GITHUB_SYNC_AUTO_PATH),
36882
+ ciWatchdog: GithubSyncCiWatchdogSchema,
36883
+ enabled: external_exports.boolean(),
36884
+ lastPlannedSha: external_exports.string().trim().min(1).nullable(),
36885
+ lastAppliedSha: external_exports.string().trim().min(1).nullable(),
36886
+ createdAt: external_exports.string().datetime(),
36887
+ updatedAt: external_exports.string().datetime()
36888
+ });
36889
+ var GithubSyncBindingCreateRequestSchema = external_exports.object({
36890
+ connection: external_exports.string().trim().min(1).optional(),
36891
+ repo: GithubSyncRepositoryFullNameSchema,
36892
+ repoId: external_exports.string().trim().min(1).optional(),
36893
+ branch: GithubSyncProductionBranchSchema.optional(),
36894
+ ciWatchdog: GithubSyncCiWatchdogSchema.optional()
36895
+ });
36896
+ var GithubSyncInitialSyncSchema = external_exports.object({
36897
+ started: external_exports.boolean(),
36898
+ headSha: external_exports.string().trim().min(1).optional(),
36899
+ workflowId: external_exports.string().trim().min(1).optional(),
36900
+ reason: external_exports.enum([
36901
+ "no_auto_directory",
36902
+ "already_applied",
36903
+ "probe_failed",
36904
+ "start_failed"
36905
+ ]).optional()
36906
+ });
36907
+ var GithubSyncBindingCreateResponseSchema = external_exports.object({
36908
+ binding: GithubSyncBindingSchema,
36909
+ created: external_exports.boolean(),
36910
+ initialSync: GithubSyncInitialSyncSchema.optional()
36911
+ });
36912
+ var GithubSyncBindingListResponseSchema = external_exports.object({
36913
+ bindings: external_exports.array(GithubSyncBindingSchema)
36914
+ });
36915
+ var GithubSyncBindingDisableResponseSchema = external_exports.object({
36916
+ binding: GithubSyncBindingSchema.nullable()
36917
+ });
36918
+ var GithubSyncTriggerArtifactSchema = external_exports.object({
36919
+ type: external_exports.string().trim().min(1),
36920
+ externalId: external_exports.string().trim().min(1),
36921
+ payload: JsonValueSchema2.optional()
36922
+ }).strict();
36923
+ var GithubSyncWorkflowInputSchema = external_exports.discriminatedUnion("kind", [
36924
+ external_exports.object({
36925
+ kind: external_exports.literal("pull_request"),
36926
+ bindingId: external_exports.string().trim().min(1),
36927
+ organizationId: OrganizationIdSchema,
36928
+ projectId: ProjectIdSchema,
36929
+ providerGrantId: ProviderGrantIdSchema,
36930
+ installationId: external_exports.string().trim().min(1),
36931
+ repoFullName: GithubSyncRepositoryFullNameSchema,
36932
+ repoId: external_exports.string().trim().min(1).optional(),
36933
+ productionBranch: GithubSyncProductionBranchSchema,
36934
+ autoPath: external_exports.literal(GITHUB_SYNC_AUTO_PATH),
36935
+ pullRequestNumber: external_exports.number().int().positive(),
36936
+ headSha: external_exports.string().trim().min(1),
36937
+ baseSha: external_exports.string().trim().min(1).optional(),
36938
+ baseRef: GithubSyncProductionBranchSchema,
36939
+ triggerArtifact: GithubSyncTriggerArtifactSchema.optional()
36940
+ }),
36941
+ external_exports.object({
36942
+ kind: external_exports.literal("push"),
36943
+ bindingId: external_exports.string().trim().min(1),
36944
+ organizationId: OrganizationIdSchema,
36945
+ projectId: ProjectIdSchema,
36946
+ providerGrantId: ProviderGrantIdSchema,
36947
+ installationId: external_exports.string().trim().min(1),
36948
+ repoFullName: GithubSyncRepositoryFullNameSchema,
36949
+ repoId: external_exports.string().trim().min(1).optional(),
36950
+ productionBranch: GithubSyncProductionBranchSchema,
36951
+ autoPath: external_exports.literal(GITHUB_SYNC_AUTO_PATH),
36952
+ ref: external_exports.string().trim().min(1),
36953
+ branch: GithubSyncProductionBranchSchema,
36954
+ before: external_exports.string().trim().min(1).optional(),
36955
+ after: external_exports.string().trim().min(1),
36956
+ triggerArtifact: GithubSyncTriggerArtifactSchema.optional()
36957
+ }),
36958
+ // Synthetic re-apply triggered by a managed-template version bump (not a
36959
+ // webhook). The tenant's `.auto` is unchanged — only our registry changed —
36960
+ // so this arm skips the `no_auto_changes` early-out and applies the production
36961
+ // branch HEAD (`after`, which the sweep resolves before starting the run).
36962
+ // It is otherwise push-shaped. New waves carry the complete bounded
36963
+ // `templates` set plus a deterministic `waveId`; legacy single-template
36964
+ // coordinates remain accepted only so in-flight workflows can replay.
36965
+ external_exports.object({
36966
+ kind: external_exports.literal("template_push"),
36967
+ bindingId: external_exports.string().trim().min(1),
36968
+ organizationId: OrganizationIdSchema,
36969
+ projectId: ProjectIdSchema,
36970
+ providerGrantId: ProviderGrantIdSchema,
36971
+ installationId: external_exports.string().trim().min(1),
36972
+ repoFullName: GithubSyncRepositoryFullNameSchema,
36973
+ repoId: external_exports.string().trim().min(1).optional(),
36974
+ productionBranch: GithubSyncProductionBranchSchema,
36975
+ autoPath: external_exports.literal(GITHUB_SYNC_AUTO_PATH),
36976
+ before: external_exports.string().trim().min(1).optional(),
36977
+ after: external_exports.string().trim().min(1),
36978
+ // Legacy single-template coordinates remain optional so in-flight
36979
+ // workflows started by a pre-wave worker can finish after deployment.
36980
+ templateName: external_exports.string().trim().min(1).optional(),
36981
+ version: external_exports.string().trim().min(1).optional(),
36982
+ waveId: external_exports.string().trim().min(1).optional(),
36983
+ // A bounded operator repair can re-run an already-terminal wave without
36984
+ // reusing its completed Temporal workflow or apply operation. Ordinary
36985
+ // subscription sweeps omit this field.
36986
+ retryAttempt: external_exports.number().int().positive().max(9).optional(),
36987
+ templates: external_exports.array(
36988
+ external_exports.object({
36989
+ name: external_exports.string().trim().min(1),
36990
+ version: external_exports.string().trim().min(1)
36991
+ })
36992
+ ).min(1).max(50).optional(),
36993
+ triggerArtifact: GithubSyncTriggerArtifactSchema.optional()
36994
+ }).superRefine((input, context) => {
36995
+ const legacy = Boolean(input.templateName && input.version);
36996
+ const wave = Boolean(input.waveId && input.templates);
36997
+ if (legacy === wave) {
36998
+ context.addIssue({
36999
+ code: "custom",
37000
+ message: "template_push requires exactly one of legacy templateName/version or waveId/templates"
37001
+ });
37002
+ }
37003
+ if (input.retryAttempt && !wave) {
37004
+ context.addIssue({
37005
+ code: "custom",
37006
+ message: "template_push retryAttempt requires waveId/templates"
37007
+ });
37008
+ }
37009
+ }),
37010
+ // Synthetic authoritative re-apply triggered by one durable connection
37011
+ // lifecycle occurrence. The event id makes retries reuse the same workflow,
37012
+ // while a later remove/re-allow occurrence can re-run at the same git SHA.
37013
+ external_exports.object({
37014
+ kind: external_exports.literal("connection_push"),
37015
+ bindingId: external_exports.string().trim().min(1),
37016
+ organizationId: OrganizationIdSchema,
37017
+ projectId: ProjectIdSchema,
37018
+ providerGrantId: ProviderGrantIdSchema,
37019
+ installationId: external_exports.string().trim().min(1),
37020
+ repoFullName: GithubSyncRepositoryFullNameSchema,
37021
+ repoId: external_exports.string().trim().min(1).optional(),
37022
+ productionBranch: GithubSyncProductionBranchSchema,
37023
+ autoPath: external_exports.literal(GITHUB_SYNC_AUTO_PATH),
37024
+ before: external_exports.string().trim().min(1).optional(),
37025
+ after: external_exports.string().trim().min(1),
37026
+ connectionEventId: external_exports.string().trim().min(1),
37027
+ triggerArtifact: GithubSyncTriggerArtifactSchema.optional()
37028
+ })
37029
+ ]);
37030
+ var GithubSyncWorkflowResultSchema = external_exports.discriminatedUnion("status", [
37031
+ external_exports.object({
37032
+ status: external_exports.literal("skipped"),
37033
+ reason: external_exports.string().trim().min(1)
37034
+ }),
37035
+ external_exports.object({
37036
+ status: external_exports.literal("planned"),
37037
+ changed: external_exports.boolean(),
37038
+ checkRunId: external_exports.number().int().positive().optional()
37039
+ }),
37040
+ external_exports.object({
37041
+ status: external_exports.literal("applied"),
37042
+ changed: external_exports.boolean(),
37043
+ checkRunId: external_exports.number().int().positive().optional()
37044
+ }),
37045
+ external_exports.object({
37046
+ status: external_exports.literal("failed"),
37047
+ message: external_exports.string().trim().min(1),
37048
+ checkRunId: external_exports.number().int().positive().optional()
37049
+ })
37050
+ ]);
37051
+
37052
+ // ../../packages/schemas/src/github-mcp-catalog.ts
37053
+ var GITHUB_MCP_TOOL_NAMES = [
37054
+ "actions_get",
37055
+ "actions_list",
37056
+ "actions_run_trigger",
37057
+ "add_comment_to_pending_review",
37058
+ "add_issue_comment",
37059
+ "add_reply_to_pull_request_comment",
37060
+ "create_branch",
37061
+ "create_or_update_file",
37062
+ "create_pull_request",
37063
+ "create_repository",
37064
+ "delete_file",
37065
+ "fork_repository",
37066
+ "get_commit",
37067
+ "get_file_contents",
37068
+ "get_job_logs",
37069
+ "get_label",
37070
+ "get_latest_release",
37071
+ "get_release_by_tag",
37072
+ "get_tag",
37073
+ "issue_read",
37074
+ "issue_write",
37075
+ "list_branches",
37076
+ "list_commits",
37077
+ "list_issue_types",
37078
+ "list_issues",
37079
+ "list_pull_requests",
37080
+ "list_releases",
37081
+ "list_repository_collaborators",
37082
+ "list_tags",
37083
+ "merge_pull_request",
37084
+ "pull_request_read",
37085
+ "pull_request_review_write",
37086
+ "push_files",
37087
+ "search_code",
37088
+ "search_commits",
37089
+ "search_issues",
37090
+ "search_pull_requests",
37091
+ "search_repositories",
37092
+ "sub_issue_write",
37093
+ "update_pull_request",
37094
+ "update_pull_request_branch"
37095
+ ];
37096
+ var GITHUB_MCP_PROXY_TOOL_NAMES = [
37097
+ "actions_secret_list",
37098
+ "actions_secret_write",
37099
+ "delete_issue_comment",
37100
+ "download_comment_attachment",
37101
+ "enable_pull_request_auto_merge",
37102
+ "enqueue_pull_request",
37103
+ "rerun_failed_jobs",
37104
+ "rerun_failed_jobs_for_pr_head",
37105
+ "upsert_issue_comment"
37106
+ ];
37107
+ var GITHUB_MCP_SELECTABLE_TOOL_NAMES = [
37108
+ ...GITHUB_MCP_TOOL_NAMES,
37109
+ ...GITHUB_MCP_PROXY_TOOL_NAMES
37110
+ ];
37111
+ var GITHUB_MCP_MERGE_TOOLS = [
37112
+ "merge_pull_request",
37113
+ "enable_pull_request_auto_merge",
37114
+ "enqueue_pull_request"
37115
+ ];
37116
+ var GITHUB_MCP_SECRETS_TOOLS = [
37117
+ "actions_secret_list",
37118
+ "actions_secret_write"
37119
+ ];
37120
+ var GITHUB_MCP_SECRETS_WRITE_TOOLS = [
37121
+ "actions_secret_write"
37122
+ ];
37123
+ var GITHUB_MCP_ACTIONS_WRITE_TOOLS = [
37124
+ "rerun_failed_jobs",
37125
+ "rerun_failed_jobs_for_pr_head"
37126
+ ];
37127
+ var GITHUB_MCP_WRITE_TOOLS = [
37128
+ "actions_run_trigger",
37129
+ "add_comment_to_pending_review",
37130
+ "add_issue_comment",
37131
+ "add_reply_to_pull_request_comment",
37132
+ "create_branch",
37133
+ "create_or_update_file",
37134
+ "create_pull_request",
37135
+ "create_repository",
37136
+ "delete_file",
37137
+ "fork_repository",
37138
+ "issue_write",
37139
+ "merge_pull_request",
37140
+ "pull_request_review_write",
37141
+ "push_files",
37142
+ "sub_issue_write",
37143
+ "update_pull_request",
37144
+ "update_pull_request_branch"
37145
+ ];
37146
+ var githubMcpToolNameSet = new Set(
37147
+ GITHUB_MCP_TOOL_NAMES
37148
+ );
37149
+ var GITHUB_MCP_ATTRIBUTION_EXEMPT_PROXY_TOOLS = /* @__PURE__ */ new Set([
37150
+ "actions_secret_list",
37151
+ "download_comment_attachment",
37152
+ "delete_issue_comment"
37153
+ ]);
37154
+ var githubMcpWriteToolSet = /* @__PURE__ */ new Set([
37155
+ ...GITHUB_MCP_WRITE_TOOLS,
37156
+ ...GITHUB_MCP_PROXY_TOOL_NAMES.filter(
37157
+ (name) => !GITHUB_MCP_ATTRIBUTION_EXEMPT_PROXY_TOOLS.has(name)
37158
+ )
37159
+ ]);
37160
+ var githubMcpProxyToolSet = new Set(
37161
+ GITHUB_MCP_PROXY_TOOL_NAMES
37162
+ );
37163
+ var githubMcpMergeToolSet = new Set(
37164
+ GITHUB_MCP_MERGE_TOOLS
37165
+ );
37166
+ var githubMcpSecretsToolSet = new Set(
37167
+ GITHUB_MCP_SECRETS_TOOLS
37168
+ );
37169
+ var githubMcpSecretsWriteToolSet = new Set(
37170
+ GITHUB_MCP_SECRETS_WRITE_TOOLS
37171
+ );
37172
+ var githubMcpActionsWriteToolSet = new Set(
37173
+ GITHUB_MCP_ACTIONS_WRITE_TOOLS
37174
+ );
37175
+
37176
+ // ../../packages/schemas/src/secrets.ts
37177
+ var SECRET_ENCRYPTION_ALGORITHM = "AES-256-GCM";
37178
+ var SecretEnvNameSchema = external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
37179
+ var SecretCiphertextFieldSchema = external_exports.string().trim().min(1).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/);
37180
+ var SecretAesGcmIvSchema = external_exports.string().trim().regex(/^[A-Za-z0-9+/]{16}$/);
37181
+ var SecretAesGcmAuthTagSchema = external_exports.string().trim().regex(/^[A-Za-z0-9+/]{22}==$/);
37182
+ var SecretEnvValueSchema = external_exports.union([
37183
+ external_exports.string(),
37184
+ external_exports.object({
37185
+ $secret: ResourceNameSchema,
37186
+ optional: external_exports.boolean().optional()
37187
+ })
37188
+ ]);
37189
+ var SecretEnvSchema = external_exports.record(
37190
+ SecretEnvNameSchema,
37191
+ SecretEnvValueSchema
37192
+ );
37193
+ var EncryptedSecretValueSchema = external_exports.object({
37194
+ keyVersion: external_exports.string().trim().min(1),
37195
+ algorithm: external_exports.literal(SECRET_ENCRYPTION_ALGORITHM),
37196
+ ciphertext: SecretCiphertextFieldSchema,
37197
+ valueIv: SecretAesGcmIvSchema,
37198
+ valueAuthTag: SecretAesGcmAuthTagSchema,
37199
+ encryptedDek: SecretCiphertextFieldSchema,
37200
+ dekIv: SecretAesGcmIvSchema,
37201
+ dekAuthTag: SecretAesGcmAuthTagSchema
37202
+ });
37203
+ var SecretDescriptionSchema = external_exports.string().trim().max(1024);
37204
+ var SECRET_IDLE_EXPIRY_MAX_SECONDS = 10 * 365 * 24 * 60 * 60;
37205
+ var SecretExpiresAtSchema = external_exports.string().datetime({ offset: true });
37206
+ var SecretIdleExpirySecondsSchema = external_exports.number().int().min(1).max(SECRET_IDLE_EXPIRY_MAX_SECONDS);
37207
+ var SECRET_INJECTION_HOST_PATTERN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/;
37208
+ var SECRET_INJECTION_HEADER_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
37209
+ var SECRET_INJECTION_FORBIDDEN_HEADERS = /* @__PURE__ */ new Set([
37210
+ "connection",
37211
+ "content-length",
37212
+ "host",
37213
+ "transfer-encoding"
37214
+ ]);
37215
+ var SecretInjectionHostSchema = external_exports.string().trim().toLowerCase().regex(
37216
+ SECRET_INJECTION_HOST_PATTERN,
37217
+ "Injection hosts must be exact lowercase hostnames (no wildcards, schemes, ports, or paths)"
37218
+ );
37219
+ var SecretInjectionHeaderSchema = external_exports.string().trim().min(1).max(128).regex(SECRET_INJECTION_HEADER_PATTERN, "Invalid HTTP header name").refine(
37220
+ (header) => !SECRET_INJECTION_FORBIDDEN_HEADERS.has(header.toLowerCase()),
37221
+ "This header cannot carry an injected secret"
37222
+ );
37223
+ var SecretInjectionSchema = external_exports.object({
37224
+ hosts: external_exports.array(SecretInjectionHostSchema).min(1).max(16),
37225
+ header: SecretInjectionHeaderSchema,
37226
+ format: external_exports.string().min(1).max(256).refine(
37227
+ (format) => format.includes("{value}"),
37228
+ "Injection format must contain the {value} placeholder"
37229
+ ).optional()
37230
+ });
37231
+ var SecretSetRequestSchema = external_exports.object({
37232
+ value: external_exports.string(),
37233
+ description: SecretDescriptionSchema.nullable().optional(),
37234
+ protected: external_exports.boolean().optional(),
37235
+ injection: SecretInjectionSchema.nullable().optional(),
37236
+ expiresAt: SecretExpiresAtSchema.nullable().optional(),
37237
+ idleExpirySeconds: SecretIdleExpirySecondsSchema.nullable().optional()
37238
+ });
37239
+ var SecretExpiryUpdateRequestSchema = external_exports.object({
37240
+ expiresAt: SecretExpiresAtSchema.nullable().optional(),
37241
+ idleExpirySeconds: SecretIdleExpirySecondsSchema.nullable().optional()
37242
+ }).refine(
37243
+ (input) => input.expiresAt !== void 0 || input.idleExpirySeconds !== void 0,
37244
+ { message: "Provide expiresAt and/or idleExpirySeconds" }
37245
+ );
37246
+ var SecretRotateRequestSchema = external_exports.object({
37247
+ value: external_exports.string()
37248
+ });
37249
+ var SecretMetadataSchema = external_exports.object({
37250
+ id: external_exports.string().trim().min(1),
37251
+ organizationId: external_exports.string().trim().min(1),
37252
+ projectId: external_exports.string().trim().min(1).nullable(),
37253
+ name: ResourceNameSchema,
37254
+ description: external_exports.string().nullable(),
37255
+ protected: external_exports.boolean(),
37256
+ // Defaulted rather than required so a newer client parsing an older
37257
+ // server's metadata (deploy skew) treats an absent injection as plain
37258
+ // env delivery.
37259
+ injection: SecretInjectionSchema.nullable().default(null),
37260
+ createdAt: external_exports.string().datetime(),
37261
+ updatedAt: external_exports.string().datetime(),
37262
+ lastRotatedAt: external_exports.string().datetime().nullable(),
37263
+ lastAccessedAt: external_exports.string().datetime().nullable(),
37264
+ // Like injection, defaulted for deploy skew: an older server that never sends
37265
+ // expiry fields parses as a secret that never expires.
37266
+ expiresAt: external_exports.string().datetime().nullable().default(null),
37267
+ idleExpirySeconds: external_exports.number().int().nullable().default(null),
37268
+ // Computed server-side: true when expiresAt has passed or the secret has
37269
+ // been unused past idleExpirySeconds. Expired secrets resolve as absent
37270
+ // everywhere but stay listed so operators can see and delete them.
37271
+ expired: external_exports.boolean().default(false)
37272
+ });
37273
+ var SecretSetResponseSchema = external_exports.object({
37274
+ secret: SecretMetadataSchema
37275
+ });
37276
+ var SecretListResponseSchema = external_exports.object({
37277
+ secrets: external_exports.array(SecretMetadataSchema)
37278
+ });
37279
+ var SecretDeleteResponseSchema = external_exports.object({
37280
+ secret: SecretMetadataSchema
37281
+ });
37282
+ var SecretExpiryUpdateResponseSchema = external_exports.object({
37283
+ secret: SecretMetadataSchema
37284
+ });
37285
+ var SecretRevealResponseSchema = external_exports.object({
37286
+ secret: SecretMetadataSchema,
37287
+ value: external_exports.string()
37288
+ });
37289
+
37290
+ // ../../packages/schemas/src/persisted-agent-grammar.ts
37291
+ function normalizePersistedAgentGrammar(spec) {
37292
+ const triggers = Array.isArray(spec.triggers) ? spec.triggers : [];
37293
+ const session = record2(spec.session);
37294
+ const legacyGrammar = triggers.some(triggerUsesLegacyGrammar) || bindingsUseLegacyGrammar(spec.bindings) || session?.observeSpawnedSessions !== void 0;
37295
+ if (!legacyGrammar) {
37296
+ return spec;
37297
+ }
37298
+ const bindings = normalizePersistedBindings({
37299
+ bindings: spec.bindings,
37300
+ observeSpawnedSessions: session?.observeSpawnedSessions !== false,
37301
+ triggers
37302
+ });
37303
+ const normalizedSession = session ? Object.fromEntries(
37304
+ Object.entries(session).filter(
37305
+ ([key]) => key !== "observeSpawnedSessions"
37306
+ )
37307
+ ) : spec.session;
37308
+ return {
37309
+ ...spec,
37310
+ bindings,
37311
+ triggers: normalizePersistedTriggers(triggers, spec.bindings),
37312
+ ...session ? { session: normalizedSession } : {}
37313
+ };
37314
+ }
37315
+ function normalizePersistedBindings(input) {
37316
+ const policies = /* @__PURE__ */ new Map();
37317
+ const bindings = record2(input.bindings) ?? {};
37318
+ for (const [storedTarget, value] of Object.entries(bindings)) {
37319
+ const entry = record2(value);
37320
+ const target = finalTarget(storedTarget);
37321
+ if (!entry || !target) continue;
37322
+ mergePolicy(policies, target, {
37323
+ lifecycle: entry.lifecycle === "held" || entry.lifecycle === "agent" || entry.continuity === "agent" ? "agent" : "session",
37324
+ bindOn: [
37325
+ ...Array.isArray(entry.bindOn) ? entry.bindOn.filter(
37326
+ (action) => typeof action === "string"
37327
+ ) : [],
37328
+ ...entry.bind === "onAttributedEvent" ? ["attribution"] : []
37329
+ ]
37330
+ });
37331
+ }
37332
+ for (const trigger of input.triggers) {
37333
+ const candidate = record2(trigger);
37334
+ const routing = record2(candidate?.routing);
37335
+ if (!routing) continue;
37336
+ const inline = record2(routing.bind);
37337
+ const storedTarget = typeof inline?.target === "string" ? inline.target : typeof routing.target === "string" ? routing.target : null;
37338
+ const target = storedTarget ? finalTarget(storedTarget) : null;
37339
+ if (!target) continue;
37340
+ const lifecycleSource = inline ?? routing;
37341
+ mergePolicy(policies, target, {
37342
+ lifecycle: lifecycleSource.lifecycle === "held" || lifecycleSource.lifecycle === "agent" || lifecycleSource.continuity === "agent" ? "agent" : "session",
37343
+ bindOn: []
37344
+ });
37345
+ }
37346
+ mergePolicy(policies, "chat.thread", {
37347
+ lifecycle: "session",
37348
+ bindOn: ["send"]
37349
+ });
37350
+ mergePolicy(policies, "auto.connection.authorization_attempt", {
37351
+ lifecycle: "agent",
37352
+ bindOn: ["authorization"]
37353
+ });
37354
+ if (input.observeSpawnedSessions) {
37355
+ mergePolicy(policies, "auto.session", {
37356
+ lifecycle: "session",
37357
+ bindOn: ["spawn"]
37358
+ });
37359
+ }
37360
+ return Object.fromEntries(
37361
+ [...policies.entries()].map(([target, policy]) => [
37362
+ target,
37363
+ {
37364
+ lifecycle: policy.lifecycle,
37365
+ ...policy.bindOn.size > 0 ? { bindOn: [...policy.bindOn].sort() } : {}
37366
+ }
37367
+ ])
37368
+ );
37369
+ }
37370
+ function normalizePersistedTriggers(triggers, bindings) {
37371
+ const legacyMentionBinding = Object.entries(record2(bindings) ?? {}).some(
37372
+ ([target, value]) => (target === "slack.thread" || target === "chat.thread") && record2(value)?.bind === "onMention"
37373
+ );
37374
+ return triggers.flatMap((trigger) => {
37375
+ const candidate = record2(trigger);
37376
+ const routing = record2(candidate?.routing);
37377
+ if (!candidate || !routing) return [trigger];
37378
+ if (routing.target === "auto.task" || record2(routing.bind)?.target === "auto.task") {
37379
+ return [];
37380
+ }
37381
+ const events = triggerEvents(candidate);
37382
+ const inlineMentionBinding = routing.kind === "deliver" && record2(routing.bind) !== null;
37383
+ if (events.includes("chat.message.mentioned") && events.some((event) => event !== "chat.message.mentioned") && (legacyMentionBinding || inlineMentionBinding)) {
37384
+ const mention = { ...candidate };
37385
+ delete mention.events;
37386
+ mention.event = "chat.message.mentioned";
37387
+ const remaining = { ...candidate };
37388
+ delete remaining.event;
37389
+ remaining.events = events.filter(
37390
+ (event) => event !== "chat.message.mentioned"
37391
+ );
37392
+ remaining.routing = inlineMentionBinding ? Object.fromEntries(
37393
+ Object.entries(routing).filter(([key]) => key !== "bind")
37394
+ ) : routing;
37395
+ return [
37396
+ normalizePersistedTrigger(mention, true),
37397
+ normalizePersistedTrigger(remaining, false)
37398
+ ];
37399
+ }
37400
+ return [
37401
+ normalizePersistedTrigger(
37402
+ candidate,
37403
+ events.length === 1 && events[0] === "chat.message.mentioned" && (legacyMentionBinding || inlineMentionBinding)
37404
+ )
37405
+ ];
37406
+ });
37407
+ }
37408
+ function normalizePersistedTrigger(trigger, mentionBinding) {
37409
+ const routing = record2(trigger.routing);
37410
+ if (!routing) return trigger;
37411
+ if (routing.kind !== "spawn" && routing.kind !== "bind" && routing.kind !== "deliver" && routing.kind !== "deliverOrSpawn") {
37412
+ return trigger;
37413
+ }
37414
+ const routeBy = record2(routing.routeBy);
37415
+ if (routing.routeBy !== void 0 && (!routeBy || routeBy.kind !== "singleton" && routeBy.kind !== "ownedArtifact" && routeBy.kind !== "allLiveSessions" && routeBy.kind !== "allLiveRuns" && routeBy.kind !== "attributedSessions" && routeBy.kind !== "attributedRuns")) {
37416
+ return trigger;
37417
+ }
37418
+ const { routing: _routing, ...normalized } = trigger;
37419
+ const onUnmatched = onUnmatchedPolicy(routing.onUnmatched);
37420
+ const events = triggerEvents(trigger);
37421
+ const inlineBind = record2(routing.bind);
37422
+ let route;
37423
+ if (inlineBind && routing.kind !== "deliver") {
37424
+ route = targetRoute(inlineBind.target, "spawn");
37425
+ } else if (routing.kind === "spawn" && events.length > 0 && events.every((event) => event.startsWith("chat.message."))) {
37426
+ route = targetRoute("chat.thread", "spawn");
37427
+ } else if (routing.kind === "spawn") {
37428
+ route = { to: "new" };
37429
+ } else if (routing.kind === "bind") {
37430
+ route = targetRoute(routing.target, onUnmatched);
37431
+ } else {
37432
+ if (routeBy?.kind === "allLiveSessions" || routeBy?.kind === "allLiveRuns") {
37433
+ route = { to: "all" };
37434
+ } else if (routeBy?.kind === "attributedSessions" || routeBy?.kind === "attributedRuns") {
37435
+ route = targetRoute("chat.thread", onUnmatched);
37436
+ } else if (routeBy?.kind === "ownedArtifact") {
37437
+ route = targetRoute(routeBy.artifactType, onUnmatched);
37438
+ } else if (mentionBinding && onUnmatched === "spawn") {
37439
+ route = targetRoute("chat.thread", "spawn");
37440
+ } else {
37441
+ route = {
37442
+ to: "slot",
37443
+ onUnmatched: routing.kind === "deliverOrSpawn" ? "spawn" : onUnmatched
37444
+ };
37445
+ }
37446
+ }
37447
+ const effects = {};
37448
+ if (routing.kind === "bind" && routing.release) {
37449
+ effects.release = {
37450
+ target: typeof routing.target === "string" ? finalTarget(routing.target) : routing.target
37451
+ };
37452
+ }
37453
+ if (mentionBinding && !(record2(route.to)?.target === "chat.thread" && route.onUnmatched === "spawn")) {
37454
+ effects.bind = { target: "chat.thread" };
37455
+ }
37456
+ const deliveryGuard = record2(routing.deliveryGuard);
37457
+ const where = record2(normalized.where);
37458
+ const persistedWhere = record2(route.to)?.target === "chat.thread" && where?.["$.auto.authored"] === void 0 ? { ...where ?? {}, "$.auto.authored": false } : normalized.where;
37459
+ return {
37460
+ ...normalized,
37461
+ ...persistedWhere === void 0 ? {} : { where: persistedWhere },
37462
+ route,
37463
+ ...deliveryGuard?.kind === "managedCheckSuccess" && typeof deliveryGuard.check === "string" ? { guard: { managedCheckSuccess: deliveryGuard.check } } : {},
37464
+ ...Object.keys(effects).length > 0 ? { effects } : {}
37465
+ };
37466
+ }
37467
+ function targetRoute(target, onUnmatched) {
37468
+ return {
37469
+ to: { target: typeof target === "string" ? finalTarget(target) : target },
37470
+ onUnmatched
37471
+ };
37472
+ }
37473
+ function mergePolicy(policies, target, incoming) {
37474
+ const current = policies.get(target);
37475
+ policies.set(target, {
37476
+ lifecycle: current?.lifecycle === "agent" || incoming.lifecycle === "agent" ? "agent" : "session",
37477
+ bindOn: /* @__PURE__ */ new Set([...current?.bindOn ?? [], ...incoming.bindOn])
37478
+ });
37479
+ }
37480
+ function triggerUsesLegacyGrammar(value) {
37481
+ return record2(value)?.routing !== void 0;
37482
+ }
37483
+ function bindingsUseLegacyGrammar(value) {
37484
+ const bindings = record2(value);
37485
+ if (!bindings) return false;
37486
+ return Object.entries(bindings).some(([target, value2]) => {
37487
+ const entry = record2(value2);
37488
+ return target === "slack.thread" || entry?.continuity !== void 0 || entry?.bind !== void 0 || entry?.context !== void 0 || entry?.eventContext !== void 0 || entry?.lifecycle === "manual" || entry?.lifecycle === "held";
37489
+ });
37490
+ }
37491
+ function triggerEvents(trigger) {
37492
+ if (Array.isArray(trigger.events)) {
37493
+ return trigger.events.filter(
37494
+ (event) => typeof event === "string"
37495
+ );
37496
+ }
37497
+ return typeof trigger.event === "string" ? [trigger.event] : [];
37498
+ }
37499
+ function finalTarget(target) {
37500
+ if (target === "auto.task" || target === "agent.singleton" || target === "chat.message") {
37501
+ return null;
37502
+ }
37503
+ return target === "slack.thread" ? "chat.thread" : target;
37504
+ }
37505
+ function onUnmatchedPolicy(value) {
37506
+ return value === "warn" || value === "error" || value === "spawn" || value === "drop" ? value : "drop";
37507
+ }
37508
+ function record2(value) {
37509
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
37510
+ }
37511
+
37512
+ // ../../packages/schemas/src/session-bindings.ts
37513
+ var BINDING_TARGET_TYPES = [
37514
+ "github.pull_request",
37515
+ "github.issue",
37516
+ "chat.thread",
37517
+ "linear.issue",
37518
+ "webhook.key",
37519
+ "provider.entity",
37520
+ "auto.connection.authorization_attempt",
37521
+ "auto.session"
37522
+ ];
37523
+ var PERSISTED_BINDING_TARGET_TYPES = [
37524
+ "github.pull_request",
37525
+ "github.issue",
37526
+ "slack.thread",
37527
+ "chat.thread",
37528
+ "chat.message",
37529
+ "agent.singleton",
37530
+ "linear.issue",
37531
+ "webhook.key",
37532
+ "provider.entity",
37533
+ "auto.connection.authorization_attempt",
37534
+ "auto.session",
37535
+ "auto.task"
37536
+ ];
37537
+ var TRIGGER_BINDING_TARGET_TYPES = [
37538
+ ...BINDING_TARGET_TYPES
37539
+ ];
37540
+ var OWNER_RELEASABLE_HELD_BINDING_TARGET_TYPES = [
37541
+ "auto.connection.authorization_attempt"
37542
+ ];
37543
+ var SESSION_BINDING_SOURCES = [
37544
+ "trigger_spawn",
37545
+ "agent_tool",
37546
+ "chat_send",
37547
+ "system"
37548
+ ];
37549
+ var SESSION_BINDING_STATUSES = ["active", "released"];
37550
+ var BINDING_LIFECYCLES = ["session", "agent"];
37551
+ var BINDING_BOUND_CAUSES = [
37552
+ "spawn",
37553
+ "trigger",
37554
+ "attribution",
37555
+ "holder",
37556
+ "chat",
37557
+ "authorization",
37558
+ "system",
37559
+ "takeover",
37560
+ "legacy"
37561
+ ];
37562
+ var BINDING_RELEASED_CAUSES = [
37563
+ "session_terminal",
37564
+ "target_terminal",
37565
+ "holder",
37566
+ "operator",
37567
+ "takeover",
37568
+ "legacy"
37569
+ ];
37570
+ var SESSION_BINDING_RELEASE_POLICIES = ["manual", "held"];
37571
+ var SESSION_BINDING_CONTINUITIES = ["session", "agent"];
37572
+ var SESSION_BINDING_RELEASED_BY = [
37573
+ "agent_tool",
37574
+ "archive",
37575
+ "complete",
37576
+ "trigger_release",
37577
+ "operator",
37578
+ "takeover"
37579
+ ];
37580
+ var PERSISTED_SESSION_BINDING_RELEASED_BY = [
37581
+ ...SESSION_BINDING_RELEASED_BY,
37582
+ "task_terminal"
37583
+ ];
37584
+ var BindingTargetTypeSchema = external_exports.enum(BINDING_TARGET_TYPES);
37585
+ var PersistedBindingTargetTypeSchema = external_exports.enum(
37586
+ PERSISTED_BINDING_TARGET_TYPES
37587
+ );
37588
+ var TriggerBindingTargetTypeSchema = external_exports.enum(
37589
+ TRIGGER_BINDING_TARGET_TYPES
37590
+ );
37591
+ var OwnerReleasableHeldBindingTargetTypeSchema = external_exports.enum(
37592
+ OWNER_RELEASABLE_HELD_BINDING_TARGET_TYPES
37593
+ );
37594
+ var SessionBindingSourceSchema = external_exports.enum(SESSION_BINDING_SOURCES);
37595
+ var SessionBindingStatusSchema = external_exports.enum(SESSION_BINDING_STATUSES);
37596
+ var BindingLifecycleSchema = external_exports.enum(BINDING_LIFECYCLES);
37597
+ var BindingBoundCauseSchema = external_exports.enum(BINDING_BOUND_CAUSES);
37598
+ var BindingReleasedCauseSchema = external_exports.enum(BINDING_RELEASED_CAUSES);
37599
+ var SessionBindingReleasePolicySchema = external_exports.enum(
37600
+ SESSION_BINDING_RELEASE_POLICIES
37601
+ );
37602
+ var SessionBindingContinuitySchema = external_exports.enum(
37603
+ SESSION_BINDING_CONTINUITIES
37604
+ );
37605
+ var SessionBindingReleasedBySchema = external_exports.enum(
37606
+ SESSION_BINDING_RELEASED_BY
37607
+ );
37608
+ var PersistedSessionBindingReleasedBySchema = external_exports.enum(
37609
+ PERSISTED_SESSION_BINDING_RELEASED_BY
37610
+ );
37611
+ var BindingTargetSchema = external_exports.object({
37612
+ type: BindingTargetTypeSchema,
37613
+ externalId: external_exports.string().min(1)
37614
+ });
37615
+ var BINDING_ACTIONS = [
37616
+ "send",
37617
+ "attribution",
37618
+ "spawn",
37619
+ "authorization"
37620
+ ];
37621
+ var BindingActionSchema = external_exports.enum(BINDING_ACTIONS);
37622
+ var BINDING_ACTION_LEGAL_TARGETS = {
37623
+ send: /* @__PURE__ */ new Set(["chat.thread"]),
37624
+ attribution: /* @__PURE__ */ new Set(["github.pull_request"]),
37625
+ spawn: /* @__PURE__ */ new Set(["auto.session"]),
37626
+ authorization: /* @__PURE__ */ new Set([
37627
+ "auto.connection.authorization_attempt"
37628
+ ])
37629
+ };
37630
+
37631
+ // ../../packages/schemas/src/work-provenance.ts
37632
+ var StableKeySchema = external_exports.string().trim().min(1).max(512);
37633
+ var SnapshotNameSchema = external_exports.string().trim().min(1).max(256);
37634
+ var SourceIdSchema = external_exports.string().trim().min(1).max(512);
37635
+ var principalBase = {
37636
+ stableKey: StableKeySchema,
37637
+ displayName: SnapshotNameSchema
37638
+ };
37639
+ var schedulePrincipalSchema = external_exports.object({
37640
+ kind: external_exports.literal("schedule"),
37641
+ ...principalBase,
37642
+ scheduleId: SourceIdSchema,
37643
+ agentResourceId: SourceIdSchema,
37644
+ agentName: SnapshotNameSchema,
37645
+ triggerId: SourceIdSchema.nullable().default(null),
37646
+ triggerName: SnapshotNameSchema.nullable().default(null),
37647
+ triggerOrdinal: external_exports.number().int().nonnegative(),
37648
+ cron: external_exports.string().trim().min(1).max(512).nullable().default(null),
37649
+ timezone: external_exports.string().trim().min(1).max(128).nullable().default(null)
37650
+ });
37651
+ var webhookPrincipalSchema = external_exports.object({
37652
+ kind: external_exports.literal("webhook"),
37653
+ ...principalBase,
37654
+ endpointId: SourceIdSchema,
37655
+ endpointName: SnapshotNameSchema.nullable().default(null)
37656
+ });
37657
+ var serviceAccountPrincipalSchema = external_exports.object({
37658
+ kind: external_exports.literal("service_account"),
37659
+ ...principalBase,
37660
+ serviceAccountId: SourceIdSchema
37661
+ });
37662
+ var providerIntegrationPrincipalSchema = external_exports.object({
37663
+ kind: external_exports.literal("provider_integration"),
37664
+ ...principalBase,
37665
+ provider: ProviderNameSchema,
37666
+ connectionId: SourceIdSchema.nullable().default(null)
37667
+ });
37668
+ var systemPrincipalSchema = external_exports.object({
37669
+ kind: external_exports.literal("system"),
37670
+ ...principalBase,
37671
+ systemId: SourceIdSchema
37672
+ });
37673
+ var agentPrincipalSchema = external_exports.object({
37674
+ kind: external_exports.literal("agent"),
37675
+ ...principalBase,
37676
+ agentResourceId: SourceIdSchema,
37677
+ agentName: SnapshotNameSchema,
37678
+ sessionId: SessionIdSchema2
37679
+ });
37680
+ var AutomationPrincipalSchema = external_exports.discriminatedUnion("kind", [
37681
+ schedulePrincipalSchema,
37682
+ webhookPrincipalSchema,
37683
+ serviceAccountPrincipalSchema,
37684
+ providerIntegrationPrincipalSchema,
37685
+ systemPrincipalSchema,
37686
+ agentPrincipalSchema
37687
+ ]);
37688
+ var AutomationPrincipalAuthoringSchema = external_exports.discriminatedUnion("kind", [
37689
+ schedulePrincipalSchema.strict(),
37690
+ webhookPrincipalSchema.strict(),
37691
+ serviceAccountPrincipalSchema.strict(),
37692
+ providerIntegrationPrincipalSchema.strict(),
37693
+ systemPrincipalSchema.strict(),
37694
+ agentPrincipalSchema.strict()
37695
+ ]);
37696
+ var scheduleCauseSchema = external_exports.object({
37697
+ kind: external_exports.literal("schedule"),
37698
+ sourceEventId: SourceIdSchema,
37699
+ scheduledAt: external_exports.string().datetime()
37700
+ });
37701
+ var childSessionCauseSchema = external_exports.object({
37702
+ kind: external_exports.literal("child_session"),
37703
+ sourceSessionId: SessionIdSchema2
37704
+ });
37705
+ var githubArtifactCauseSchema = external_exports.object({
37706
+ kind: external_exports.literal("github_artifact"),
37707
+ sourceEventId: SourceIdSchema,
37708
+ sourceSessionId: SessionIdSchema2,
37709
+ sourceBindingId: SourceIdSchema,
37710
+ sourceArtifactAttributionId: SourceIdSchema
37711
+ });
37712
+ var WorkProvenanceCauseSchema = external_exports.discriminatedUnion("kind", [
37713
+ scheduleCauseSchema,
37714
+ childSessionCauseSchema,
37715
+ githubArtifactCauseSchema
37716
+ ]);
37717
+ var WorkProvenanceCauseAuthoringSchema = external_exports.discriminatedUnion("kind", [
37718
+ scheduleCauseSchema.strict(),
37719
+ childSessionCauseSchema.strict(),
37720
+ githubArtifactCauseSchema.strict()
37721
+ ]);
37722
+ var WorkProvenanceFields = {
37723
+ version: external_exports.literal(1),
37724
+ root: AutomationPrincipalSchema,
37725
+ actor: AutomationPrincipalSchema,
37726
+ cause: WorkProvenanceCauseSchema
37727
+ };
37728
+ var WorkProvenanceSchema = external_exports.object(WorkProvenanceFields);
37729
+ var WorkProvenanceAuthoringSchema = external_exports.object({
37730
+ version: external_exports.literal(1),
37731
+ root: AutomationPrincipalAuthoringSchema,
37732
+ actor: AutomationPrincipalAuthoringSchema,
37733
+ cause: WorkProvenanceCauseAuthoringSchema
37734
+ }).strict();
37735
+
37736
+ // ../../packages/schemas/src/requester-spend.ts
37737
+ var ExactUsdSchema = external_exports.string().regex(
37738
+ /^(0|[1-9]\d*)(\.\d{1,10})?$/,
37739
+ "Expected an exact non-negative USD decimal"
37740
+ );
37741
+ var RequesterSpendOverrideInputSchema = external_exports.object({
37742
+ active: external_exports.boolean(),
37743
+ reason: external_exports.string().trim().min(1).max(500).nullable(),
37744
+ expiresAt: external_exports.string().datetime().nullable()
37745
+ });
37746
+ var RequesterSpendUpdateRequestSchema = external_exports.object({
37747
+ expectedVersion: external_exports.number().int().nonnegative().nullable(),
37748
+ dailyLimitUsd: ExactUsdSchema.nullable(),
37749
+ monthlyLimitUsd: ExactUsdSchema.nullable(),
37750
+ override: RequesterSpendOverrideInputSchema
37751
+ });
37752
+ var RequesterSpendSourceSchema = external_exports.object({
37753
+ sourceKey: external_exports.string().min(1),
37754
+ provider: external_exports.string().min(1).nullable(),
37755
+ externalId: external_exports.string().min(1).nullable(),
37756
+ accountRef: external_exports.string().min(1).nullable(),
37757
+ displayName: external_exports.string().min(1).nullable(),
37758
+ avatarUrl: external_exports.string().url().nullable(),
37759
+ automationActor: AutomationPrincipalSchema.nullable().optional(),
37760
+ automationCauseKind: external_exports.enum(["schedule", "child_session", "github_artifact"]).nullable().optional(),
37761
+ totalUsd: ExactUsdSchema,
37762
+ dailyUsd: ExactUsdSchema,
37763
+ monthlyUsd: ExactUsdSchema
37764
+ });
37765
+ var RequesterSpendOverrideStateSchema = external_exports.object({
37766
+ active: external_exports.boolean(),
37767
+ effective: external_exports.boolean(),
37768
+ reason: external_exports.string().nullable(),
37769
+ expiresAt: external_exports.string().datetime().nullable(),
37770
+ setByUserId: external_exports.string().min(1).nullable(),
37771
+ setAt: external_exports.string().datetime().nullable()
37772
+ });
37773
+ var RequesterSpendPeriodSchema = external_exports.object({
37774
+ usageUsd: ExactUsdSchema,
37775
+ limitUsd: ExactUsdSchema.nullable(),
37776
+ resetsAt: external_exports.string().datetime(),
37777
+ capped: external_exports.boolean()
37778
+ });
37779
+ var RequesterSpendRowSchema = external_exports.object({
37780
+ kind: external_exports.enum(["user", "automation", "unattributed"]),
37781
+ requesterKey: external_exports.string().min(1),
37782
+ requesterUserId: external_exports.string().min(1).nullable(),
37783
+ displayName: external_exports.string().min(1).nullable(),
37784
+ avatarUrl: external_exports.string().url().nullable(),
37785
+ automationRoot: AutomationPrincipalSchema.nullable().optional(),
37786
+ totalUsd: ExactUsdSchema,
37787
+ daily: RequesterSpendPeriodSchema,
37788
+ monthly: RequesterSpendPeriodSchema,
37789
+ override: RequesterSpendOverrideStateSchema,
37790
+ capped: external_exports.boolean(),
37791
+ controlVersion: external_exports.number().int().nonnegative().nullable(),
37792
+ manageable: external_exports.boolean(),
37793
+ sources: external_exports.array(RequesterSpendSourceSchema)
37794
+ });
37795
+ var RequesterSpendListResponseSchema = external_exports.object({
37796
+ asOf: external_exports.string().datetime(),
37797
+ timezone: external_exports.literal("UTC"),
37798
+ canManage: external_exports.boolean(),
37799
+ requesters: external_exports.array(RequesterSpendRowSchema)
37800
+ });
37801
+ var RequesterSpendUpdateResponseSchema = external_exports.object({
37802
+ requester: RequesterSpendRowSchema
37803
+ });
37804
+ var REQUESTER_SPEND_ERROR_CODES = [
37805
+ "invalid_request",
37806
+ "requester_not_found",
37807
+ "version_conflict",
37808
+ "unauthorized",
37809
+ "forbidden"
37810
+ ];
37811
+ var RequesterSpendErrorCodeSchema = external_exports.enum(
37812
+ REQUESTER_SPEND_ERROR_CODES
37813
+ );
37814
+ var RequesterSpendErrorResponseSchema = external_exports.object({
37815
+ error: external_exports.string(),
37816
+ code: RequesterSpendErrorCodeSchema,
37817
+ issues: external_exports.array(external_exports.unknown()).optional(),
37818
+ currentVersion: external_exports.number().int().nonnegative().nullable().optional()
37819
+ });
37820
+
37821
+ // ../../packages/schemas/src/spend-caps.ts
37822
+ var USD_DECIMAL_ERROR = "must be a nonnegative decimal string with at most 10 integer and 10 fractional digits";
37823
+ function canonicalUsdDecimal(value) {
37824
+ const [integer2, fraction] = value.split(".");
37825
+ const trimmedFraction = fraction?.replace(/0+$/, "");
37826
+ return trimmedFraction ? `${integer2}.${trimmedFraction}` : integer2 ?? "0";
37827
+ }
37828
+ var SpendCapUsdSchema = ExactUsdSchema.refine(
37829
+ (value) => (value.split(".")[0]?.length ?? 0) <= 10,
37830
+ USD_DECIMAL_ERROR
37831
+ ).transform(canonicalUsdDecimal);
37832
+ var AgentSpendCapsFields = {
37833
+ dailyUsd: SpendCapUsdSchema.optional(),
37834
+ monthlyUsd: SpendCapUsdSchema.optional(),
37835
+ maxPerSessionUsd: SpendCapUsdSchema.optional()
37836
+ };
37837
+ var AgentSpendCapsSchema = external_exports.object(AgentSpendCapsFields);
37838
+ var AgentSpendCapsAuthoringSchema = external_exports.object(AgentSpendCapsFields).strict();
37839
+ var SessionSpendCapSnapshotSchema = external_exports.object({
37840
+ configuredMaxUsd: SpendCapUsdSchema.nullable()
37841
+ });
37842
+ var AgentSpendCapWindowStatusSchema = external_exports.object({
37843
+ usageUsd: ExactUsdSchema,
37844
+ configuredLimitUsd: SpendCapUsdSchema.nullable(),
37845
+ hit: external_exports.boolean(),
37846
+ resetsAt: external_exports.string().datetime()
37847
+ });
37848
+ var AgentSpendCapStatusSchema = external_exports.object({
37849
+ daily: AgentSpendCapWindowStatusSchema,
37850
+ monthly: AgentSpendCapWindowStatusSchema
37851
+ });
37852
+ var SessionSpendCapStatusSchema = external_exports.object({
37853
+ usageUsd: ExactUsdSchema,
37854
+ configuredMaxUsd: SpendCapUsdSchema.nullable(),
37855
+ hit: external_exports.boolean()
37856
+ });
37857
+
37858
+ // ../../packages/schemas/src/tools.ts
37859
+ var REMOTE_MCP_TRANSPORTS = ["streamable_http"];
37860
+ var LOCAL_TOOL_IMPLEMENTATIONS = [
37861
+ "auto",
37862
+ "chat",
37863
+ "pagerduty",
37864
+ "ping"
37865
+ ];
37866
+ var BILLING_CAPABILITY_LEVELS = ["none", "read", "write"];
37867
+ var BillingCapabilityLevelSchema = external_exports.enum(BILLING_CAPABILITY_LEVELS);
37868
+ var PROJECT_MEMBER_CAPABILITY_LEVELS = ["none", "read"];
37869
+ var ProjectMemberCapabilityLevelSchema = external_exports.enum(
37870
+ PROJECT_MEMBER_CAPABILITY_LEVELS
37871
+ );
37872
+ var WAITLIST_REPORTING_CAPABILITY_LEVELS = ["none", "read"];
37873
+ var WaitlistReportingCapabilityLevelSchema = external_exports.enum(
37874
+ WAITLIST_REPORTING_CAPABILITY_LEVELS
37875
+ );
37876
+ var RUNTIME_CAPABILITY_LEVELS = ["none", "read", "write"];
37877
+ var RuntimeCapabilityLevelSchema = external_exports.enum(RUNTIME_CAPABILITY_LEVELS);
37878
+ var CONNECTION_CAPABILITY_LEVELS = ["none", "read", "write"];
37879
+ var ConnectionCapabilityLevelSchema = external_exports.enum(
37880
+ CONNECTION_CAPABILITY_LEVELS
37881
+ );
37882
+ var SECRET_CAPABILITY_LEVELS = ["none", "read", "write"];
37883
+ var SecretCapabilityLevelSchema = external_exports.enum(SECRET_CAPABILITY_LEVELS);
37884
+ var WEBHOOK_CAPABILITY_LEVELS = ["none", "write"];
37885
+ var WebhookCapabilityLevelSchema = external_exports.enum(WEBHOOK_CAPABILITY_LEVELS);
37886
+ function attenuatedCapabilitySchema(input) {
37887
+ return external_exports.union([
37888
+ input.levelSchema,
37889
+ external_exports.object({
37890
+ level: input.levelSchema,
37891
+ unattributed: input.levelSchema
37892
+ }).strict().superRefine((capability, context) => {
37893
+ if (!capabilityLevelAtMost({
37894
+ floor: capability.unattributed,
37895
+ grant: capability.level,
37896
+ levels: input.levels
37897
+ })) {
37898
+ context.addIssue({
37899
+ code: external_exports.ZodIssueCode.custom,
37900
+ message: "unattributed capability level must not exceed level",
37901
+ path: ["unattributed"]
37902
+ });
37903
+ }
37904
+ })
37905
+ ]);
37906
+ }
37907
+ var BillingCapabilitySchema = attenuatedCapabilitySchema({
37908
+ levelSchema: BillingCapabilityLevelSchema,
37909
+ levels: BILLING_CAPABILITY_LEVELS
37910
+ });
37911
+ var ProjectMemberCapabilitySchema = attenuatedCapabilitySchema({
37912
+ levelSchema: ProjectMemberCapabilityLevelSchema,
37913
+ levels: PROJECT_MEMBER_CAPABILITY_LEVELS
37914
+ });
37915
+ var WaitlistReportingCapabilitySchema = external_exports.literal("read");
37916
+ var RuntimeCapabilitySchema = attenuatedCapabilitySchema({
37917
+ levelSchema: RuntimeCapabilityLevelSchema,
37918
+ levels: RUNTIME_CAPABILITY_LEVELS
37919
+ });
37920
+ var ConnectionCapabilitySchema = attenuatedCapabilitySchema({
37921
+ levelSchema: ConnectionCapabilityLevelSchema,
37922
+ levels: CONNECTION_CAPABILITY_LEVELS
37923
+ });
37924
+ var SecretCapabilitySchema = attenuatedCapabilitySchema({
37925
+ levelSchema: SecretCapabilityLevelSchema,
37926
+ levels: SECRET_CAPABILITY_LEVELS
37927
+ });
37928
+ var WebhookCapabilitySchema = attenuatedCapabilitySchema({
37929
+ levelSchema: WebhookCapabilityLevelSchema,
37930
+ levels: WEBHOOK_CAPABILITY_LEVELS
37931
+ });
37932
+ var LocalAutoToolCapabilitiesSchema = external_exports.object({
37933
+ billing: BillingCapabilitySchema.default("none"),
37934
+ projectMembers: ProjectMemberCapabilitySchema.default("none"),
37935
+ // Optional preserves legacy persisted tool snapshots byte-for-byte while
37936
+ // making absence an explicit deny at every read site.
37937
+ waitlistReporting: WaitlistReportingCapabilitySchema.optional(),
37938
+ runtimes: RuntimeCapabilitySchema.default("none"),
37939
+ connections: ConnectionCapabilitySchema.optional(),
37940
+ secrets: SecretCapabilitySchema.optional(),
37941
+ webhooks: WebhookCapabilitySchema.optional()
37942
+ }).strict().default({
37943
+ billing: "none",
37944
+ projectMembers: "none",
37945
+ runtimes: "none"
37946
+ });
37947
+ var SecretReferenceSchema = external_exports.object({
37948
+ $secret: ResourceNameSchema
37949
+ });
37950
+ var NoToolAuthSchema = external_exports.object({
37951
+ kind: external_exports.literal("none")
37952
+ });
37953
+ var OptionalConnectionField = {
37954
+ optional: external_exports.boolean().optional()
37955
+ };
37956
+ var McpOAuthToolAuthSchema = external_exports.object({
37957
+ kind: external_exports.literal("mcp_oauth"),
37958
+ connection: ResourceNameSchema,
37959
+ ...OptionalConnectionField
37960
+ });
37961
+ var ConnectionToolAuthSchema = ProviderConnectionReferenceSchema.extend({
37962
+ kind: external_exports.literal("connection"),
37963
+ ...OptionalConnectionField
37964
+ });
37965
+ var ConnectionsToolAuthSchema = external_exports.object({
37966
+ kind: external_exports.literal("connections"),
37967
+ connections: external_exports.array(ProviderConnectionReferenceSchema).min(1),
37968
+ ...OptionalConnectionField
37969
+ });
37970
+ var ConnectionMcpToolNameSchema = external_exports.string().trim().min(1, "Connection-backed MCP tool names must not be empty");
37971
+ var ConnectionMcpToolAllowlistSchema = external_exports.array(ConnectionMcpToolNameSchema).min(1, "Connection-backed MCP tool allowlists must name at least one tool").superRefine((tools, context) => {
37972
+ const seen = /* @__PURE__ */ new Set();
37973
+ for (const [index, tool] of tools.entries()) {
37974
+ if (seen.has(tool)) {
37975
+ context.addIssue({
37976
+ code: external_exports.ZodIssueCode.custom,
37977
+ message: "Connection-backed MCP tool names must be unique after trimming",
37978
+ path: [index]
37979
+ });
37980
+ }
37981
+ seen.add(tool);
37982
+ }
37983
+ });
37984
+ var ConnectionBackedToolSchema = ProviderConnectionReferenceSchema.extend({
37985
+ kind: external_exports.literal("connection"),
37986
+ description: external_exports.string().trim().min(1).optional(),
37987
+ tools: ConnectionMcpToolAllowlistSchema.optional(),
37988
+ ...OptionalConnectionField
37989
+ });
37990
+ var ToolAliasSchema = ResourceNameSchema.refine(
37991
+ (value) => value !== "workspace",
37992
+ {
37993
+ message: 'Tool alias "workspace" is reserved by Claude Code'
37994
+ }
37995
+ );
37996
+ function remoteMcpUrlSchema(input) {
37997
+ return external_exports.string().trim().url().refine(
37998
+ (value) => {
37999
+ const url2 = new URL(value);
38000
+ if (url2.protocol === "https:") {
38001
+ return true;
38002
+ }
38003
+ if (!input?.allowInsecureLocal || url2.protocol !== "http:") {
38004
+ return false;
38005
+ }
38006
+ return url2.hostname === "localhost" || url2.hostname === "127.0.0.1";
38007
+ },
38008
+ {
38009
+ message: "Remote MCP URLs must use https; http is only allowed for explicit local development parsing"
38010
+ }
38011
+ );
38012
+ }
38013
+ function remoteMcpToolSchema(input) {
38014
+ return external_exports.object({
38015
+ kind: external_exports.literal("mcp_remote"),
38016
+ description: external_exports.string().trim().min(1).optional(),
38017
+ url: remoteMcpUrlSchema(input),
38018
+ transport: external_exports.enum(REMOTE_MCP_TRANSPORTS).default("streamable_http"),
38019
+ auth: external_exports.discriminatedUnion("kind", [
38020
+ NoToolAuthSchema,
38021
+ external_exports.object({
38022
+ kind: external_exports.literal("bearer"),
38023
+ token: SecretReferenceSchema
38024
+ }),
38025
+ McpOAuthToolAuthSchema,
38026
+ ProviderConnectionReferenceSchema.extend({
38027
+ kind: external_exports.literal("provider_oauth"),
38028
+ ...OptionalConnectionField
38029
+ })
38030
+ ]).default({ kind: "none" })
38031
+ });
38032
+ }
38033
+ var RemoteMcpToolSchema = remoteMcpToolSchema();
38034
+ var LocalAutoToolSchema = external_exports.object({
38035
+ kind: external_exports.literal("local"),
38036
+ implementation: external_exports.literal("auto"),
38037
+ description: external_exports.string().trim().min(1).optional(),
38038
+ capabilities: LocalAutoToolCapabilitiesSchema,
38039
+ auth: NoToolAuthSchema.default({ kind: "none" })
38040
+ });
38041
+ var LocalPingToolSchema = external_exports.object({
38042
+ kind: external_exports.literal("local"),
38043
+ implementation: external_exports.literal("ping"),
38044
+ description: external_exports.string().trim().min(1).optional(),
38045
+ auth: NoToolAuthSchema.default({ kind: "none" })
38046
+ });
38047
+ var LocalChatToolSchema = external_exports.object({
38048
+ kind: external_exports.literal("local"),
38049
+ implementation: external_exports.literal("chat"),
38050
+ description: external_exports.string().trim().min(1).optional(),
38051
+ auth: external_exports.discriminatedUnion("kind", [
38052
+ ConnectionToolAuthSchema,
38053
+ ConnectionsToolAuthSchema
38054
+ ])
38055
+ });
38056
+ var LocalPagerDutyToolSchema = external_exports.object({
38057
+ kind: external_exports.literal("local"),
38058
+ implementation: external_exports.literal("pagerduty"),
38059
+ description: external_exports.string().trim().min(1).optional(),
38060
+ capabilities: external_exports.object({
38061
+ addNote: external_exports.literal("supported").default("supported"),
38062
+ acknowledge: external_exports.literal("supported").default("supported"),
38063
+ pageOrEscalate: external_exports.literal("unsupported").default("unsupported")
38064
+ }).strict().default({
38065
+ addNote: "supported",
38066
+ acknowledge: "supported",
38067
+ pageOrEscalate: "unsupported"
38068
+ }),
38069
+ auth: ProviderConnectionReferenceSchema.extend({
38070
+ kind: external_exports.literal("connection"),
38071
+ provider: external_exports.literal("pagerduty"),
38072
+ ...OptionalConnectionField
38073
+ })
38074
+ });
38075
+ var LocalToolSchema = external_exports.discriminatedUnion(
38076
+ "implementation",
38077
+ [
38078
+ LocalAutoToolSchema,
38079
+ LocalChatToolSchema,
38080
+ LocalPagerDutyToolSchema,
38081
+ LocalPingToolSchema
38082
+ ],
38083
+ {
38084
+ error: `Unsupported local tool implementation. Supported implementations: ${LOCAL_TOOL_IMPLEMENTATIONS.join(", ")}`
38085
+ }
38086
+ );
38087
+ var PersistedLocalToolSchema = external_exports.preprocess(
38088
+ normalizePersistedTaskEraLocalAutoTool,
38089
+ LocalToolSchema
38090
+ );
38091
+ function normalizePersistedTaskEraLocalAutoTool(value) {
38092
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
38093
+ return value;
38094
+ }
38095
+ const tool = value;
38096
+ if (tool.kind !== "local" || tool.implementation !== "auto" || typeof tool.capabilities !== "object" || tool.capabilities === null || Array.isArray(tool.capabilities)) {
38097
+ return value;
38098
+ }
38099
+ const {
38100
+ tasks: _tasks,
38101
+ taskManagement: _taskManagement,
38102
+ ...capabilities
38103
+ } = tool.capabilities;
38104
+ return { ...tool, capabilities };
38105
+ }
38106
+ var GithubToolSchema = external_exports.object({
38107
+ kind: external_exports.literal("github"),
38108
+ description: external_exports.string().trim().min(1).optional(),
38109
+ tools: external_exports.array(external_exports.enum(GITHUB_MCP_SELECTABLE_TOOL_NAMES)).min(1).optional()
38110
+ });
38111
+ var ToolSpecSchema = external_exports.discriminatedUnion("kind", [
38112
+ RemoteMcpToolSchema,
38113
+ ConnectionBackedToolSchema,
38114
+ LocalToolSchema
38115
+ ]);
38116
+ var AgentToolConnectRequestSchema = external_exports.object({
38117
+ redirectUri: external_exports.string().trim().url().refine(
38118
+ (value) => {
38119
+ const url2 = new URL(value);
38120
+ if (url2.protocol === "https:") {
38121
+ return true;
38122
+ }
38123
+ return url2.protocol === "http:" && (url2.hostname === "localhost" || url2.hostname === "127.0.0.1");
38124
+ },
38125
+ {
38126
+ message: "Agent tool OAuth redirect URIs must use https, except localhost loopback callbacks may use http"
38127
+ }
38128
+ ).optional()
38129
+ });
38130
+ var AgentToolConnectResponseSchema = external_exports.discriminatedUnion("status", [
38131
+ external_exports.object({
38132
+ status: external_exports.literal("authorization_required"),
38133
+ agent: ResourceNameSchema.optional(),
38134
+ tool: ResourceNameSchema,
38135
+ connection: ResourceNameSchema,
38136
+ authorizationUrl: external_exports.string().trim().url(),
38137
+ message: external_exports.string().trim().min(1)
38138
+ }),
38139
+ external_exports.object({
38140
+ status: external_exports.literal("connected"),
38141
+ agent: ResourceNameSchema.optional(),
38142
+ tool: ResourceNameSchema,
38143
+ connection: ResourceNameSchema,
38144
+ message: external_exports.string().trim().min(1)
38145
+ })
38146
+ ]);
38147
+ var AgentToolConnectCompleteResponseSchema = external_exports.object({
38148
+ status: external_exports.literal("connected"),
38149
+ agent: ResourceNameSchema.optional(),
38150
+ tool: ResourceNameSchema,
38151
+ connection: ResourceNameSchema,
38152
+ projectId: ProjectIdSchema
38153
+ });
38154
+ var InlineAgentToolSchema = RemoteMcpToolSchema.extend({
38155
+ disabled: external_exports.boolean().optional()
38156
+ }).or(
38157
+ ConnectionBackedToolSchema.extend({
38158
+ disabled: external_exports.boolean().optional()
38159
+ })
38160
+ ).or(
38161
+ LocalToolSchema.and(
38162
+ external_exports.object({
38163
+ disabled: external_exports.boolean().optional()
38164
+ })
38165
+ )
38166
+ ).or(
38167
+ GithubToolSchema.extend({
38168
+ disabled: external_exports.boolean().optional()
38169
+ })
38170
+ );
38171
+ var AgentToolRefSchema = InlineAgentToolSchema;
38172
+ var AgentToolsSchema = external_exports.record(ToolAliasSchema, AgentToolRefSchema);
38173
+
38174
+ // ../../packages/schemas/src/trigger-filters.ts
38175
+ var TriggerFilterScalarSchema = external_exports.union([
38176
+ external_exports.null(),
38177
+ external_exports.string(),
38178
+ external_exports.number(),
38179
+ external_exports.boolean()
38180
+ ]);
38181
+ var TriggerFilterPathSchema = external_exports.string().refine(
38182
+ (path2) => {
38183
+ if (path2.length === 0 || path2.trim() !== path2) {
38184
+ return false;
38185
+ }
38186
+ if (path2.startsWith("$.")) {
38187
+ const segments = path2.slice(2).split(".");
38188
+ return segments.length > 0 && segments.every(
38189
+ (segment) => segment.length > 0 && segment.trim() === segment
38190
+ );
38191
+ }
38192
+ return !path2.includes(".");
38193
+ },
38194
+ {
38195
+ message: "Trigger filter paths must be a single bare key or use $.path.segments"
38196
+ }
38197
+ );
38198
+ var TriggerFilterClauseSchema = external_exports.union([
38199
+ TriggerFilterScalarSchema,
38200
+ external_exports.object({ contains: TriggerFilterScalarSchema }).strict(),
38201
+ external_exports.object({ exists: external_exports.boolean() }).strict(),
38202
+ external_exports.object({ in: external_exports.array(TriggerFilterScalarSchema).min(1) }).strict(),
38203
+ external_exports.object({ notIn: external_exports.array(TriggerFilterScalarSchema).min(1) }).strict(),
38204
+ external_exports.object({ changedTo: TriggerFilterScalarSchema }).strict()
38205
+ ]);
38206
+ var TriggerFilterRecordSchema = external_exports.record(
38207
+ TriggerFilterPathSchema,
38208
+ TriggerFilterClauseSchema
38209
+ );
38210
+ var TriggerFilterSchema = TriggerFilterRecordSchema.default({});
38211
+
38212
+ // ../../packages/schemas/src/trigger-router.ts
38213
+ var TRIGGER_ON_UNMATCHED_POLICIES = [
38214
+ "drop",
38215
+ "warn",
38216
+ "error",
38217
+ "spawn"
38218
+ ];
38219
+ var OnUnmatchedSchema = external_exports.enum(TRIGGER_ON_UNMATCHED_POLICIES);
38220
+ var RouteSchema = external_exports.union([
38221
+ external_exports.object({ to: external_exports.literal("new") }).strict(),
38222
+ external_exports.object({
38223
+ to: external_exports.literal("slot"),
38224
+ onUnmatched: OnUnmatchedSchema
38225
+ }).strict(),
38226
+ external_exports.object({ to: external_exports.literal("all") }).strict(),
38227
+ external_exports.object({
38228
+ to: external_exports.object({ target: BindingTargetTypeSchema }).strict(),
38229
+ onUnmatched: OnUnmatchedSchema
38230
+ }).strict()
38231
+ ]);
38232
+ var TriggerEffectTargetSchema = external_exports.object({ target: BindingTargetTypeSchema }).strict();
38233
+ var TriggerEffectsSchema = external_exports.object({
38234
+ bind: TriggerEffectTargetSchema.optional(),
38235
+ release: TriggerEffectTargetSchema.optional(),
38236
+ complete: external_exports.literal(true).optional()
38237
+ }).strict();
38238
+ var TriggerGuardSchema = external_exports.object({ managedCheckSuccess: ResourceNameSchema }).strict();
38239
+ var SourceEventRequestSchema = external_exports.object({
38240
+ organizationId: external_exports.string().trim().min(1),
38241
+ projectId: external_exports.string().trim().min(1).nullable().optional(),
38242
+ providerGrantId: external_exports.string().trim().min(1).nullable().optional(),
38243
+ webhookEndpointId: external_exports.string().trim().min(1).nullable().optional(),
38244
+ /** Address the event to one agent; only its triggers may match. */
38245
+ targetAgentResourceId: external_exports.string().trim().min(1).nullable().optional(),
38246
+ event: external_exports.string().trim().min(1),
38247
+ payload: JsonValueSchema2.default({}),
38248
+ dedupKey: external_exports.string().trim().min(1),
38249
+ occurredAt: external_exports.string().datetime().optional()
38250
+ });
38251
+ var EventRoutingWorkflowInputSchema = external_exports.discriminatedUnion("kind", [
38252
+ external_exports.object({
38253
+ kind: external_exports.literal("trigger"),
38254
+ eventRecordId: external_exports.string().uuid()
38255
+ }).strict(),
38256
+ external_exports.object({
38257
+ kind: external_exports.literal("command"),
38258
+ commandId: SessionCommandIdSchema2
38259
+ }).strict()
38260
+ ]);
38261
+ var HeartbeatTickWorkflowInputSchema = external_exports.preprocess(
38262
+ normalizeLegacyHeartbeatTickWorkflowInput,
38263
+ external_exports.object({
38264
+ scheduleId: external_exports.string().trim().min(1),
38265
+ organizationId: external_exports.string().trim().min(1),
38266
+ projectId: external_exports.string().trim().min(1).nullable(),
38267
+ agentResourceId: external_exports.string().trim().min(1),
38268
+ agentName: external_exports.string().trim().min(1).max(256).nullable().default(null),
38269
+ triggerId: external_exports.string().trim().min(1).max(512).nullable().default(null),
38270
+ triggerOrdinal: external_exports.number().int().nonnegative(),
38271
+ cron: external_exports.string().trim().min(1).max(512).nullable().default(null),
38272
+ timezone: external_exports.string().trim().min(1).max(128).nullable().default(null),
38273
+ event: external_exports.string().trim().min(1)
38274
+ }).strict()
38275
+ );
38276
+ var GithubPullRequestMergeabilityWorkflowInputSchema = external_exports.object({
38277
+ organizationId: external_exports.string().trim().min(1),
38278
+ providerGrantId: external_exports.string().trim().min(1),
38279
+ source: external_exports.string().trim().min(1),
38280
+ eventPayload: JsonValueSchema2,
38281
+ artifactExternalId: external_exports.string().trim().min(1),
38282
+ installationId: external_exports.string().trim().min(1),
38283
+ repoFullName: external_exports.string().trim().min(1),
38284
+ pullRequestNumber: external_exports.number().int().positive(),
38285
+ headSha: external_exports.string().trim().min(1),
38286
+ headRef: external_exports.string().trim().min(1).optional(),
38287
+ baseSha: external_exports.string().trim().min(1).optional(),
38288
+ ciWatchdogWorkflows: external_exports.array(GithubSyncCiWatchdogWorkflowSchema).max(10).default([]),
38289
+ retryDelaysMs: external_exports.array(external_exports.number().int().nonnegative()).default([1e3, 2e3, 5e3, 1e4, 15e3]),
38290
+ ciWorkflowRunCheckDelayMs: external_exports.number().int().nonnegative().default(GITHUB_SYNC_CI_WATCHDOG_DEFAULT_DELAY_MS)
38291
+ }).strict();
38292
+ var GithubPullRequestMergeabilityWorkflowResultSchema = external_exports.union([
38293
+ external_exports.object({
38294
+ kind: external_exports.literal("conflict"),
38295
+ eventRecordId: external_exports.string().uuid(),
38296
+ created: external_exports.boolean(),
38297
+ dispatch: external_exports.literal("started"),
38298
+ workflowId: external_exports.string().min(1)
38299
+ }),
38300
+ external_exports.object({
38301
+ kind: external_exports.literal("not_conflict"),
38302
+ mergeable: external_exports.boolean().nullable(),
38303
+ mergeableState: external_exports.string().optional(),
38304
+ // Present when the pull request was behind its base with auto-merge
38305
+ // enabled: "updated" if a branch update was requested, "skipped" if
38306
+ // GitHub rejected it (e.g. the head moved since lookup).
38307
+ branchUpdate: external_exports.enum(["updated", "skipped"]).optional(),
38308
+ ciWorkflowDispatch: external_exports.enum(["dispatched", "present", "skipped"]).optional()
38309
+ })
38310
+ ]);
38311
+ var EventRoutingTriggerResultSchema = external_exports.object({
38312
+ eventRecordId: external_exports.string().uuid(),
38313
+ matchedTriggers: external_exports.number().int().nonnegative(),
38314
+ deliveries: external_exports.number().int().nonnegative()
38315
+ });
38316
+ function normalizeLegacyHeartbeatTickWorkflowInput(input) {
38317
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
38318
+ return input;
38319
+ }
38320
+ if ("agentResourceId" in input || !("sessionResourceId" in input)) {
38321
+ return input;
38322
+ }
38323
+ const { sessionResourceId, ...rest } = input;
38324
+ return {
38325
+ ...rest,
38326
+ agentResourceId: sessionResourceId
38327
+ };
38328
+ }
38329
+
38330
+ // ../../packages/schemas/src/agents.ts
38331
+ var RESOURCE_KIND_AGENT = "agent";
38332
+ var AGENT_HARNESSES = ["claude-code", "codex"];
38333
+ var AgentHarnessSchema = external_exports.enum(AGENT_HARNESSES);
38334
+ var TriggerCheckTimeoutSchema = external_exports.object({
38335
+ seconds: external_exports.number().int().min(1).max(7 * 24 * 60 * 60),
38336
+ conclusion: external_exports.enum(["success", "failure", "skipped"])
38337
+ }).strict();
38338
+ var AgentArchiveAfterInactiveSchema = external_exports.object({
38339
+ seconds: external_exports.number().int().min(60).max(365 * 24 * 60 * 60)
38340
+ }).strict();
38341
+ var AgentSessionPolicySchema = external_exports.object({
38342
+ archiveAfterInactive: AgentArchiveAfterInactiveSchema.optional()
38343
+ }).strict().default({});
38344
+ var AgentConcurrencySchema = external_exports.number().int().refine((value) => value === 1, {
38345
+ message: "Only `concurrency: 1` is supported; larger pools are a deliberate non-goal for now (see docs/agent-concurrency.md)"
38346
+ });
38347
+ var AgentReplacePolicySchema = external_exports.literal("auto");
38348
+ var AgentManagesSchema = external_exports.array(ResourceNameSchema).max(64);
38349
+ var AgentConnectionsSchema = external_exports.union([
38350
+ external_exports.literal("all"),
38351
+ external_exports.literal("none"),
38352
+ external_exports.array(ConnectionNameSchema),
38353
+ external_exports.object({
38354
+ exclude: external_exports.array(ConnectionNameSchema)
38355
+ }).strict()
38356
+ ]);
38357
+ var TriggerEventSchema = external_exports.string().trim().min(1);
38358
+ var TriggerEventsSchema = external_exports.array(TriggerEventSchema).min(1).superRefine((events, context) => {
38359
+ const seen = /* @__PURE__ */ new Set();
38360
+ for (const [index, event] of events.entries()) {
38361
+ if (seen.has(event)) {
38362
+ context.addIssue({
38363
+ code: external_exports.ZodIssueCode.custom,
38364
+ path: [index],
38365
+ message: "Trigger events must be unique"
38366
+ });
38367
+ }
38368
+ seen.add(event);
38369
+ }
38370
+ });
38371
+ var PAYLOAD_PREFIXED_TEMPLATE_TOKEN = /\{\{\s*(payload(?:\.[A-Za-z0-9_.-]+)?)\s*\}\}/g;
38372
+ function refineNoPayloadPrefixedTemplateTokens(value, context) {
38373
+ if (value === void 0) {
38374
+ return;
38375
+ }
38376
+ const offending = new Set(
38377
+ [...value.matchAll(PAYLOAD_PREFIXED_TEMPLATE_TOKEN)].map(
38378
+ (match) => match[0]
38379
+ )
38380
+ );
38381
+ if (offending.size > 0) {
38382
+ context.addIssue({
38383
+ code: external_exports.ZodIssueCode.custom,
38384
+ message: `Template renders against the event payload; drop the "payload." prefix (use "{{github.\u2026}}", not "{{payload.github.\u2026}}"). Offending tokens: ${[...offending].join(", ")}`
38385
+ });
38386
+ }
38387
+ }
38388
+ function templateField(guard) {
38389
+ const field = external_exports.string().trim().min(1).max(2e4).optional();
38390
+ return guard === "authoring" ? field.superRefine(refineNoPayloadPrefixedTemplateTokens) : field;
38391
+ }
38392
+ function attachedUserPromptField() {
38393
+ return external_exports.string().min(1).max(2e4).refine((value) => value.trim().length > 0, {
38394
+ message: "Attached user prompt must contain non-whitespace text"
38395
+ }).optional();
38396
+ }
38397
+ function displayTitleField(guard) {
38398
+ const field = external_exports.union([
38399
+ external_exports.literal("infer"),
38400
+ external_exports.string().trim().min(1).max(2e4)
38401
+ ]);
38402
+ return (guard === "authoring" ? field.superRefine((value, context) => {
38403
+ if (value !== "infer") {
38404
+ refineNoPayloadPrefixedTemplateTokens(value, context);
38405
+ }
38406
+ }) : field).optional();
38407
+ }
38408
+ var TriggerChecksField = external_exports.array(
38409
+ external_exports.object({
38410
+ name: ResourceNameSchema,
38411
+ displayName: external_exports.string().trim().min(1).max(256),
38412
+ description: external_exports.string().trim().min(1).max(65535),
38413
+ instructions: external_exports.string().trim().min(1).max(2e4).optional(),
38414
+ timeout: TriggerCheckTimeoutSchema.optional(),
38415
+ beginTimeout: TriggerCheckTimeoutSchema.optional(),
38416
+ completeTimeout: TriggerCheckTimeoutSchema.optional()
38417
+ }).strict().superRefine((check2, context) => {
38418
+ if (check2.timeout && check2.beginTimeout) {
38419
+ context.addIssue({
38420
+ code: external_exports.ZodIssueCode.custom,
38421
+ path: ["beginTimeout"],
38422
+ message: "Use either timeout or beginTimeout for the creation-to-begin timeout, not both"
38423
+ });
38424
+ }
38425
+ })
38426
+ ).optional();
38427
+ function triggerSharedFields(guard) {
38428
+ return {
38429
+ message: templateField(guard),
38430
+ attachedUserPrompt: attachedUserPromptField(),
38431
+ checks: TriggerChecksField,
38432
+ // Catch-all flag: a `fallback` trigger fires only when no normal (non-
38433
+ // fallback) trigger on the same endpoint + eventKey matched its `where`.
38434
+ // It is the one cross-trigger negation the per-payload matcher cannot
38435
+ // express, so it must be an explicit flag rather than overloaded empty
38436
+ // `where` (which already means match-all). See the trigger-router partition
38437
+ // in packages/db/src/trigger-router/triggers.ts.
38438
+ fallback: external_exports.boolean().default(false),
38439
+ route: RouteSchema,
38440
+ effects: TriggerEffectsSchema.optional(),
38441
+ guard: TriggerGuardSchema.optional()
38442
+ };
38443
+ }
38444
+ var TriggerEventSourceFields = {
38445
+ connection: ConnectionNameSchema.optional(),
38446
+ // Mark a connection-bound trigger optional so apply silently skips it (rather
38447
+ // than failing) when the referenced connection has no active grant. The
38448
+ // skipped trigger is omitted from the applied agent and re-activates on the
38449
+ // next apply/sync once the connection is set up.
38450
+ optional: external_exports.boolean().optional(),
38451
+ endpoint: external_exports.string().trim().min(1).optional(),
38452
+ auth: external_exports.discriminatedUnion("kind", [
38453
+ external_exports.object({
38454
+ kind: external_exports.literal("hmac_sha256"),
38455
+ secretRef: external_exports.string().trim().min(1)
38456
+ }),
38457
+ external_exports.object({
38458
+ kind: external_exports.literal("bearer_token"),
38459
+ secretRef: external_exports.string().trim().min(1)
38460
+ }),
38461
+ external_exports.object({
38462
+ kind: external_exports.literal("none")
38463
+ })
38464
+ ]).optional()
38465
+ };
38466
+ function triggerBaseSchema(guard) {
38467
+ return external_exports.object({
38468
+ event: TriggerEventSchema,
38469
+ ...triggerSharedFields(guard),
38470
+ ...TriggerEventSourceFields
38471
+ }).strict().superRefine((trigger, context) => {
38472
+ validateTriggerChecks(trigger, context, [trigger.event]);
38473
+ validateAttachedUserPrompt(trigger, context, guard);
38474
+ });
38475
+ }
38476
+ function triggerDefinitionBaseSchema(guard) {
38477
+ return external_exports.object({
38478
+ event: TriggerEventSchema.optional(),
38479
+ events: TriggerEventsSchema.optional(),
38480
+ ...triggerSharedFields(guard),
38481
+ ...TriggerEventSourceFields
38482
+ }).strict().superRefine((trigger, context) => {
38483
+ if (trigger.event && trigger.events) {
38484
+ context.addIssue({
38485
+ code: external_exports.ZodIssueCode.custom,
38486
+ path: ["events"],
38487
+ message: "Use either event or events, not both"
38488
+ });
38489
+ }
38490
+ if (!trigger.event && !trigger.events) {
38491
+ context.addIssue({
38492
+ code: external_exports.ZodIssueCode.custom,
38493
+ path: ["event"],
38494
+ message: "Trigger requires event or events"
38495
+ });
38496
+ }
38497
+ validateTriggerChecks(
38498
+ trigger,
38499
+ context,
38500
+ trigger.event ? [trigger.event] : trigger.events ?? []
38501
+ );
38502
+ validateAttachedUserPrompt(trigger, context, guard);
38503
+ });
38504
+ }
38505
+ function heartbeatTriggerBaseSchema(guard) {
38506
+ return external_exports.object({
38507
+ kind: external_exports.literal("heartbeat"),
38508
+ event: external_exports.never().optional(),
38509
+ connection: external_exports.never().optional(),
38510
+ optional: external_exports.never().optional(),
38511
+ endpoint: external_exports.never().optional(),
38512
+ auth: external_exports.never().optional(),
38513
+ cron: external_exports.string().trim().min(1).max(512),
38514
+ timezone: external_exports.string().trim().min(1).max(128).default("UTC"),
38515
+ ...triggerSharedFields(guard)
38516
+ }).strict().superRefine((trigger, context) => {
38517
+ validateTriggerChecks(trigger, context, ["heartbeat"]);
38518
+ validateAttachedUserPrompt(trigger, context, guard);
38519
+ });
38520
+ }
38521
+ var TriggerSchema = triggerBaseSchema("stored").extend({
38522
+ where: external_exports.record(external_exports.string(), JsonValueSchema2).default({})
38523
+ });
38524
+ var ApplyTriggerSchema = triggerBaseSchema("authoring").extend({
38525
+ where: TriggerFilterSchema
38526
+ });
38527
+ var HeartbeatTriggerSchema = heartbeatTriggerBaseSchema(
38528
+ "stored"
38529
+ ).extend({
38530
+ where: external_exports.record(external_exports.string(), JsonValueSchema2).default({})
38531
+ });
38532
+ var ApplyHeartbeatTriggerSchema = heartbeatTriggerBaseSchema(
38533
+ "authoring"
38534
+ ).extend({
38535
+ where: TriggerFilterSchema
38536
+ });
38537
+ var TriggerDefinitionSchema = triggerDefinitionBaseSchema("stored").extend({
38538
+ where: external_exports.record(external_exports.string(), JsonValueSchema2).default({})
38539
+ });
38540
+ var ApplyTriggerDefinitionSchema = triggerDefinitionBaseSchema(
38541
+ "authoring"
38542
+ ).extend({
38543
+ where: TriggerFilterSchema
38544
+ });
38545
+ var TriggersSchema = external_exports.array(external_exports.union([TriggerDefinitionSchema, HeartbeatTriggerSchema])).transform(expandTriggerDefinitions).superRefine(validateAttributedRunsTriggerPairing);
38546
+ var ApplyTriggersSchema = external_exports.array(external_exports.union([ApplyTriggerDefinitionSchema, ApplyHeartbeatTriggerSchema])).transform(expandApplyTriggerDefinitions).superRefine(validateAttributedRunsTriggerPairing);
38547
+ var AVATAR_ASSET_EXTENSIONS = [".png", ".jpg", ".jpeg"];
38548
+ var MAX_AVATAR_ASSET_BYTES = 2 * 1024 * 1024;
38549
+ var AGENT_IDENTITY_DESCRIPTION_MAX_LENGTH = 140;
38550
+ function agentIdentityDescriptionLength(value) {
38551
+ let length = 0;
38552
+ for (const char of value) {
38553
+ const codePoint = char.codePointAt(0) ?? 0;
38554
+ if (codePoint < 32 || codePoint > 126) {
38555
+ length += 6 * char.length;
38556
+ } else if (char === '"' || char === "\\" || char === "/") {
38557
+ length += 2;
38558
+ } else {
38559
+ length += 1;
38560
+ }
38561
+ }
38562
+ return length;
38563
+ }
38564
+ function clampAgentIdentityDescription(value) {
38565
+ if (agentIdentityDescriptionLength(value) <= AGENT_IDENTITY_DESCRIPTION_MAX_LENGTH) {
38566
+ return value;
38567
+ }
38568
+ let clamped = "";
38569
+ let length = 0;
38570
+ for (const char of value) {
38571
+ const charLength = agentIdentityDescriptionLength(char);
38572
+ if (length + charLength > AGENT_IDENTITY_DESCRIPTION_MAX_LENGTH) break;
38573
+ clamped += char;
38574
+ length += charLength;
38575
+ }
38576
+ return clamped.trimEnd();
38577
+ }
38578
+ var SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
38579
+ function isAvatarAssetPathShapeValid(asset) {
38580
+ const normalized = asset.trim().replaceAll("\\", "/");
38581
+ if (normalized.length === 0) return false;
38582
+ if (normalized.startsWith("/")) return false;
38583
+ if (/^[A-Za-z]:\//.test(normalized)) return false;
38584
+ if (normalized.split("/").includes("..")) return false;
38585
+ if (!normalized.startsWith(".auto/assets/")) return false;
38586
+ const lower = normalized.toLowerCase();
38587
+ return AVATAR_ASSET_EXTENSIONS.some((ext) => lower.endsWith(ext));
38588
+ }
38589
+ var AgentIdentitySchema = external_exports.object({
38590
+ displayName: external_exports.string().trim().min(1).max(80).optional(),
38591
+ username: external_exports.string().trim().min(1).max(80).optional(),
38592
+ avatar: external_exports.object({
38593
+ asset: external_exports.string().trim().min(1).max(1024).refine(isAvatarAssetPathShapeValid, {
38594
+ message: "avatar.asset must be a relative path under .auto/assets with a .png, .jpg, or .jpeg extension"
38595
+ }),
38596
+ // Content hash of the stored asset bytes. When the apply carries the
38597
+ // asset's bytes, the server re-derives and overwrites this value. When
38598
+ // it does not, a declared hash resolves only an already-stored or
38599
+ // built-in catalog avatar (managed templates bake references this
38600
+ // way); it can never attach arbitrary bytes.
38601
+ sha256: external_exports.string().regex(SHA256_HEX_PATTERN).optional()
38602
+ }).strict().optional(),
38603
+ description: external_exports.string().trim().min(1).refine(
38604
+ (value) => agentIdentityDescriptionLength(value) <= AGENT_IDENTITY_DESCRIPTION_MAX_LENGTH,
38605
+ {
38606
+ message: `description must be at most ${AGENT_IDENTITY_DESCRIPTION_MAX_LENGTH} characters as Slack counts them (a non-ASCII character like "\u2014" counts as 6)`
38607
+ }
38608
+ ).optional()
38609
+ }).strict().refine((identity) => Object.keys(identity).length > 0, {
38610
+ message: "Identity requires at least one field"
38611
+ });
38612
+ var PersistedAgentIdentitySchema = external_exports.preprocess(
38613
+ normalizePersistedAgentIdentity,
38614
+ AgentIdentitySchema.optional()
38615
+ );
38616
+ function normalizePersistedAgentIdentity(value) {
38617
+ if (typeof value !== "object" || value === null) return value;
38618
+ const identity = value;
38619
+ if (typeof identity.description !== "string") return value;
38620
+ if (agentIdentityDescriptionLength(identity.description) <= AGENT_IDENTITY_DESCRIPTION_MAX_LENGTH) {
38621
+ return value;
38622
+ }
38623
+ const clamped = clampAgentIdentityDescription(identity.description);
38624
+ const normalizedIdentity = { ...identity };
38625
+ if (clamped.length > 0) normalizedIdentity.description = clamped;
38626
+ else delete normalizedIdentity.description;
38627
+ return Object.keys(normalizedIdentity).length > 0 ? normalizedIdentity : void 0;
38628
+ }
38629
+ var BindingLifecycleSpecSchema = external_exports.object({
38630
+ lifecycle: external_exports.enum(["session", "agent"]).default("session"),
38631
+ bindOn: external_exports.array(BindingActionSchema).optional()
38632
+ }).strict();
38633
+ var AgentBindingsSchema = external_exports.record(external_exports.string(), BindingLifecycleSpecSchema).superRefine((bindings, context) => {
38634
+ for (const key of Object.keys(bindings)) {
38635
+ const parsed = BindingTargetTypeSchema.safeParse(key);
38636
+ if (!parsed.success) {
38637
+ context.addIssue({
38638
+ code: external_exports.ZodIssueCode.custom,
38639
+ path: [key],
38640
+ message: `\`${key}\` is not a valid binding target type`
38641
+ });
38642
+ }
38643
+ }
38644
+ });
38645
+ var AgentSpecFieldsSchema = external_exports.object({
38646
+ harness: external_exports.enum(AGENT_HARNESSES).optional(),
38647
+ model: AgentModelSelectionSchema.optional(),
38648
+ reasoningEffort: AgentReasoningEffortSchema.optional(),
38649
+ systemPrompt: external_exports.string().trim().min(1).max(1e5).optional(),
38650
+ environment: ResourceNameSchema.optional(),
38651
+ identity: external_exports.union([ResourceNameSchema, AgentIdentitySchema]).optional(),
38652
+ initialPrompt: templateField("stored"),
38653
+ displayTitle: displayTitleField("stored"),
38654
+ env: SecretEnvSchema.default({}),
38655
+ mounts: external_exports.array(AgentMountSchema).default([]),
38656
+ triggers: TriggersSchema.default([]),
38657
+ session: AgentSessionPolicySchema,
38658
+ spendCaps: AgentSpendCapsSchema.optional(),
38659
+ concurrency: AgentConcurrencySchema.optional(),
38660
+ replace: AgentReplacePolicySchema.optional(),
38661
+ onReplace: external_exports.string().trim().min(1).max(2e4).optional(),
38662
+ manages: AgentManagesSchema.optional(),
38663
+ bindings: AgentBindingsSchema.default({}),
38664
+ workingDirectory: external_exports.string().trim().min(1).optional(),
38665
+ connections: AgentConnectionsSchema.optional(),
38666
+ tools: AgentToolsSchema.default({})
38667
+ });
38668
+ function validateRunnableConfig(spec, context) {
38669
+ if (!spec.harness) {
38670
+ context.addIssue({
38671
+ code: external_exports.ZodIssueCode.custom,
38672
+ path: ["harness"],
38673
+ message: "Agent requires harness"
38674
+ });
38675
+ }
38676
+ if (!spec.environment) {
38677
+ context.addIssue({
38678
+ code: external_exports.ZodIssueCode.custom,
38679
+ path: ["environment"],
38680
+ message: "Agent requires environment"
38681
+ });
38682
+ }
38683
+ }
38684
+ var AgentSpecSchema = AgentSpecFieldsSchema.superRefine(
38685
+ (spec, context) => {
38686
+ validateRunnableConfig(spec, context);
38687
+ validateAgentModelFieldsForHarness(spec, context);
38688
+ }
38689
+ );
38690
+ var AgentApplySpecFieldsSchema = AgentSpecFieldsSchema.extend({
38691
+ initialPrompt: templateField("authoring"),
38692
+ displayTitle: displayTitleField("authoring"),
38693
+ triggers: ApplyTriggersSchema.default([]),
38694
+ spendCaps: AgentSpendCapsAuthoringSchema.optional()
38695
+ });
38696
+ var AgentApplySpecSchema = AgentApplySpecFieldsSchema.superRefine(
38697
+ (spec, context) => {
38698
+ validateRunnableConfig(spec, context);
38699
+ validateAgentModelFieldsForHarness(spec, context);
38700
+ validateConcurrencyConfig(spec, context);
38701
+ validateBindingsConfig(spec, context);
38702
+ validateTriggerGuardConfig(spec, context);
38703
+ validateTriggerEffectsConfig(spec, context);
38704
+ }
38705
+ );
38706
+ function validateTriggerEffectsConfig(spec, context) {
38707
+ for (const [index, trigger] of spec.triggers.entries()) {
38708
+ if (!trigger.effects?.bind || typeof trigger.route.to !== "object" || trigger.route.onUnmatched !== "spawn" || trigger.effects.bind.target !== trigger.route.to.target) {
38709
+ continue;
38710
+ }
38711
+ context.addIssue({
38712
+ code: external_exports.ZodIssueCode.custom,
38713
+ path: ["triggers", index, "effects", "bind"],
38714
+ message: "`effects.bind` cannot duplicate a target route with `onUnmatched: spawn`; that route claims its target atomically during session creation"
38715
+ });
38716
+ }
38717
+ }
38718
+ function validateTriggerGuardConfig(spec, context) {
38719
+ const managedCheckNames = new Set(
38720
+ spec.triggers.flatMap(
38721
+ (trigger) => (trigger.checks ?? []).map((check2) => check2.name)
38722
+ )
38723
+ );
38724
+ for (const [index, trigger] of spec.triggers.entries()) {
38725
+ if (!trigger.guard) {
38726
+ continue;
38727
+ }
38728
+ if (typeof trigger.route.to !== "object" || trigger.route.to.target !== "github.pull_request") {
38729
+ context.addIssue({
38730
+ code: external_exports.ZodIssueCode.custom,
38731
+ path: ["triggers", index, "guard", "managedCheckSuccess"],
38732
+ message: "`guard.managedCheckSuccess` requires `route.to.target: github.pull_request`: managed check cycles and authoritative head state are pull-request scoped"
38733
+ });
38734
+ }
38735
+ if (!managedCheckNames.has(trigger.guard.managedCheckSuccess)) {
38736
+ context.addIssue({
38737
+ code: external_exports.ZodIssueCode.custom,
38738
+ path: ["triggers", index, "guard", "managedCheckSuccess"],
38739
+ message: "`guard.managedCheckSuccess` must name a managed check declared in this agent's `triggers[].checks`"
38740
+ });
38741
+ }
38742
+ }
38743
+ }
38744
+ function validateConcurrencyConfig(spec, context) {
38745
+ if (spec.concurrency === void 0 && spec.replace !== void 0) {
38746
+ context.addIssue({
38747
+ code: external_exports.ZodIssueCode.custom,
38748
+ path: ["replace"],
38749
+ message: "`replace` requires `concurrency` (the cap it manages)"
38750
+ });
38751
+ }
38752
+ if (spec.onReplace !== void 0 && spec.replace === void 0) {
38753
+ context.addIssue({
38754
+ code: external_exports.ZodIssueCode.custom,
38755
+ path: ["onReplace"],
38756
+ message: "`onReplace` requires `replace: auto` (it is the rebuild prompt delivered to platform-spawned replacements; nothing consumes it otherwise)"
38757
+ });
38758
+ }
38759
+ if (spec.concurrency !== void 0) {
38760
+ return;
38761
+ }
38762
+ const hasSlotClaimingSpawn = spec.triggers.some(
38763
+ (trigger) => isSlotRoute(trigger) && trigger.route.onUnmatched === "spawn"
38764
+ );
38765
+ if (hasSlotClaimingSpawn) {
38766
+ return;
38767
+ }
38768
+ for (const [index, trigger] of spec.triggers.entries()) {
38769
+ if (isSlotRoute(trigger)) {
38770
+ context.addIssue({
38771
+ code: external_exports.ZodIssueCode.custom,
38772
+ path: ["triggers", index, "route", "to"],
38773
+ message: "A `route.to: slot` trigger resolves the agent's concurrency slot; set `concurrency: 1` on the agent or use `onUnmatched: spawn`"
38774
+ });
38775
+ }
38776
+ }
38777
+ }
38778
+ function isSlotRoute(trigger) {
38779
+ return trigger.route.to === "slot";
38780
+ }
38781
+ function validateBindingActions(bindings, context) {
38782
+ for (const [target, config2] of Object.entries(bindings)) {
38783
+ const parsed = BindingTargetTypeSchema.safeParse(target);
38784
+ const targetType = parsed.success ? parsed.data : null;
38785
+ const actions = config2.bindOn ?? [];
38786
+ const seen = /* @__PURE__ */ new Set();
38787
+ for (const [index, action] of actions.entries()) {
38788
+ if (seen.has(action)) {
38789
+ context.addIssue({
38790
+ code: external_exports.ZodIssueCode.custom,
38791
+ path: ["bindings", target, "bindOn", index],
38792
+ message: "Binding actions must be unique"
38793
+ });
38794
+ }
38795
+ seen.add(action);
38796
+ const legal = BINDING_ACTION_LEGAL_TARGETS[action];
38797
+ if (targetType && legal.has(targetType)) {
38798
+ continue;
38799
+ }
38800
+ const legalList = [...legal].join(", ");
38801
+ context.addIssue({
38802
+ code: external_exports.ZodIssueCode.custom,
38803
+ path: ["bindings", target, "bindOn", index],
38804
+ message: `\`bindOn: ${action}\` is legal only for [${legalList}]; "${target}" is not a valid target for this binding action`
38805
+ });
38806
+ }
38807
+ }
38808
+ }
38809
+ function validateBindingsConfig(spec, context) {
38810
+ if (spec.bindings) validateBindingActions(spec.bindings, context);
38811
+ }
38812
+ var AgentStatusSchema = external_exports.object({
38813
+ runCount: external_exports.number().int().nonnegative().default(0),
38814
+ lastActivityAt: external_exports.string().datetime().nullable().default(null)
38815
+ }).default({ runCount: 0, lastActivityAt: null });
38816
+ var AgentResourceOriginSchema = external_exports.enum(["authored", "built_in"]);
38817
+ var AgentResourceSchema = resourceEnvelopeSchema(
38818
+ AgentSpecSchema
38819
+ ).extend({
38820
+ status: AgentStatusSchema,
38821
+ origin: AgentResourceOriginSchema.optional()
38822
+ });
38823
+ var PersistedAgentResourceSchema = external_exports.preprocess(
38824
+ normalizePersistedAgentResource,
38825
+ AgentResourceSchema
38826
+ );
38827
+ function normalizePersistedAgentResource(value) {
38828
+ if (typeof value !== "object" || value === null) return value;
38829
+ const resource = value;
38830
+ if (!resource.spec) return value;
38831
+ const normalizedSpec = normalizePersistedAgentSpec(resource.spec);
38832
+ const normalizedIdentity = normalizePersistedAgentIdentity(
38833
+ normalizedSpec.identity
38834
+ );
38835
+ return {
38836
+ ...resource,
38837
+ spec: {
38838
+ ...normalizedSpec,
38839
+ identity: normalizedIdentity
38840
+ }
38841
+ };
38842
+ }
38843
+ function normalizePersistedAgentSpec(spec) {
38844
+ const normalized = normalizePersistedAgentGrammar(spec);
38845
+ const bindings = normalizePersistedTaskEraBindings(normalized.bindings);
38846
+ const tools = normalizePersistedTaskEraTools(normalized.tools);
38847
+ return { ...normalized, bindings, tools };
38848
+ }
38849
+ function normalizePersistedTaskEraBindings(value) {
38850
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
38851
+ return value;
38852
+ }
38853
+ const { "auto.task": _retiredTaskBinding, ...bindings } = value;
38854
+ return bindings;
38855
+ }
38856
+ function normalizePersistedTaskEraTools(value) {
38857
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
38858
+ return value;
38859
+ }
38860
+ return Object.fromEntries(
38861
+ Object.entries(value).map(([name, tool]) => {
38862
+ if (typeof tool !== "object" || tool === null || Array.isArray(tool)) {
38863
+ return [name, tool];
38864
+ }
38865
+ const candidate = tool;
38866
+ if (candidate.kind !== "local" || candidate.implementation !== "auto" || typeof candidate.capabilities !== "object" || candidate.capabilities === null || Array.isArray(candidate.capabilities)) {
38867
+ return [name, tool];
38868
+ }
38869
+ const {
38870
+ tasks: _tasks,
38871
+ taskManagement: _taskManagement,
38872
+ ...capabilities
38873
+ } = candidate.capabilities;
38874
+ return [name, { ...candidate, capabilities }];
38875
+ })
38876
+ );
38877
+ }
38878
+ var AgentApplyRequestSchema = resourceApplySchema(AgentApplySpecSchema);
38879
+ var ApplyTriggerReceiptSchema = external_exports.object({
38880
+ event: external_exports.string().trim().min(1),
38881
+ endpoint: external_exports.string().trim().min(1),
38882
+ ingestUrl: external_exports.string().trim().min(1),
38883
+ status: external_exports.literal("ready")
38884
+ });
38885
+ var AgentApplyResponseSchema = external_exports.union([
38886
+ AgentResourceSchema,
38887
+ external_exports.object({
38888
+ resource: AgentResourceSchema,
38889
+ triggers: external_exports.array(ApplyTriggerReceiptSchema)
38890
+ })
38891
+ ]);
38892
+ var AGENT_TELEGRAM_IDENTITY_STATUSES = [
38893
+ "pending",
38894
+ "realized",
38895
+ "broken",
38896
+ "retired"
38897
+ ];
38898
+ var AgentTelegramIdentityStatusSchema = external_exports.enum(
38899
+ AGENT_TELEGRAM_IDENTITY_STATUSES
38900
+ );
38901
+ var AgentPresenceIdentitySchema = external_exports.object({
38902
+ identityId: external_exports.string().trim().min(1),
38903
+ provider: external_exports.string().trim().min(1),
38904
+ connection: external_exports.string().trim().min(1),
38905
+ workspace: external_exports.string().trim().min(1),
38906
+ realized: external_exports.boolean(),
38907
+ appId: external_exports.string().trim().min(1).optional(),
38908
+ botUserId: external_exports.string().trim().min(1).optional(),
38909
+ teamId: external_exports.string().trim().min(1).optional(),
38910
+ // Telegram-realized identities: the persona bot's @username and lifecycle
38911
+ // state (creation is human-confirmed in Telegram, so identities can sit
38912
+ // `pending` between the connect step and the managed_bot webhook).
38913
+ botUsername: external_exports.string().trim().min(1).optional(),
38914
+ telegramStatus: AgentTelegramIdentityStatusSchema.optional(),
38915
+ /**
38916
+ * Telegram privacy-mode state verified during connect: true means privacy
38917
+ * mode is disabled and the persona sees all group messages. Not writable
38918
+ * via the Bot API — flipping it is a BotFather step (/setprivacy), or add
38919
+ * the persona as a group admin.
38920
+ */
38921
+ canReadAllGroupMessages: external_exports.boolean().optional(),
38922
+ // Avatar drift surface: the agent's desired avatar hash + public URL, and
38923
+ // the hash last confirmed applied to the provider app icon. Providers offer
38924
+ // no API for app icons, so application is a guided manual step recorded via
38925
+ // the presence icon endpoint.
38926
+ avatarSha256: external_exports.string().regex(SHA256_HEX_PATTERN).optional(),
38927
+ avatarUrl: external_exports.string().trim().min(1).optional(),
38928
+ appliedIconSha256: external_exports.string().regex(SHA256_HEX_PATTERN).optional(),
38929
+ /**
38930
+ * Scopes the current agent-app scope set requests that this realized
38931
+ * identity's install never granted. Computed at read time; non-empty means
38932
+ * the install predates a scope addition and `auto agents connect
38933
+ * <agent> --reconnect` refreshes it.
38934
+ */
38935
+ missingScopes: external_exports.array(external_exports.string().trim().min(1)).optional()
38936
+ });
38937
+ var AgentPresenceResponseSchema = external_exports.object({
38938
+ agent: ResourceNameSchema,
38939
+ identities: external_exports.array(AgentPresenceIdentitySchema)
38940
+ });
38941
+ var AgentPresenceConnectRequestSchema = external_exports.object({
38942
+ /**
38943
+ * Rerun the install OAuth for already-realized identities too. The repair
38944
+ * path for a stranded bot token (e.g. the single-use refresh token was
38945
+ * consumed but the rotated pair failed to persist): the stored app
38946
+ * credentials are reused, so this never creates a new Slack app.
38947
+ */
38948
+ reconnect: external_exports.boolean().default(false)
38949
+ });
38950
+ var AgentPresenceConnectPendingSchema = external_exports.object({
38951
+ identityId: external_exports.string().trim().min(1),
38952
+ connection: external_exports.string().trim().min(1),
38953
+ workspace: external_exports.string().trim().min(1),
38954
+ /**
38955
+ * The URL the operator opens to realize this identity: the Slack install
38956
+ * authorize URL, or the Telegram managed-bot creation deep link.
38957
+ */
38958
+ authorizationUrl: external_exports.string().trim().url(),
38959
+ /**
38960
+ * Telegram only: the pre-filled bot username in the creation dialog. The
38961
+ * user can edit it there, so it is a suggestion, not the final identity.
38962
+ */
38963
+ suggestedUsername: external_exports.string().trim().min(1).optional()
38964
+ });
38965
+ var AgentPresenceConnectResponseSchema = external_exports.object({
38966
+ agent: ResourceNameSchema,
38967
+ pending: external_exports.array(AgentPresenceConnectPendingSchema),
38968
+ realized: external_exports.array(AgentPresenceIdentitySchema),
38969
+ message: external_exports.string().trim().min(1)
38970
+ });
38971
+ var AgentPresenceIconRequestSchema = external_exports.object({
38972
+ sha256: external_exports.string().regex(SHA256_HEX_PATTERN)
38973
+ });
38974
+ var AgentPresenceIconResponseSchema = external_exports.object({
38975
+ agent: ResourceNameSchema,
38976
+ identityId: external_exports.string().trim().min(1),
38977
+ appliedIconSha256: external_exports.string().regex(SHA256_HEX_PATTERN)
38978
+ });
38979
+ var AgentPresenceCompleteResponseSchema = external_exports.object({
38980
+ status: external_exports.literal("connected"),
38981
+ agent: ResourceNameSchema,
38982
+ connection: external_exports.string().trim().min(1),
38983
+ workspace: external_exports.string().trim().min(1),
38984
+ organizationId: external_exports.string().trim().min(1),
38985
+ botUserId: external_exports.string().trim().min(1)
38986
+ });
38987
+ function validateAttachedUserPrompt(trigger, context, guard) {
38988
+ if (guard === "authoring" && trigger.attachedUserPrompt !== void 0 && !routeCanSpawn(trigger.route)) {
38989
+ context.addIssue({
38990
+ code: external_exports.ZodIssueCode.custom,
38991
+ path: ["attachedUserPrompt"],
38992
+ message: "Attached user prompt is supported only for routes that can spawn a session"
38993
+ });
38994
+ }
38995
+ }
38996
+ function routeCanSpawn(route) {
38997
+ return route.to === "new" || (route.to === "slot" || typeof route.to === "object") && route.onUnmatched === "spawn";
38998
+ }
38999
+ function validateTriggerChecks(trigger, context, eventKeys) {
39000
+ const checks = trigger.checks ?? [];
39001
+ if (checks.length === 0) {
39002
+ return;
39003
+ }
39004
+ if (eventKeys.some((event) => !event.startsWith("github.pull_request."))) {
39005
+ context.addIssue({
39006
+ code: external_exports.ZodIssueCode.custom,
39007
+ path: ["checks"],
39008
+ message: "Trigger checks are only supported for GitHub pull request events"
39009
+ });
39010
+ }
39011
+ const names = /* @__PURE__ */ new Set();
39012
+ const displayNames = /* @__PURE__ */ new Set();
39013
+ for (const [index, check2] of checks.entries()) {
39014
+ if (names.has(check2.name)) {
39015
+ context.addIssue({
39016
+ code: external_exports.ZodIssueCode.custom,
39017
+ path: ["checks", index, "name"],
39018
+ message: "Trigger check names must be unique"
39019
+ });
39020
+ }
39021
+ names.add(check2.name);
39022
+ if (displayNames.has(check2.displayName)) {
39023
+ context.addIssue({
39024
+ code: external_exports.ZodIssueCode.custom,
39025
+ path: ["checks", index, "displayName"],
39026
+ message: "Trigger check display names must be unique"
39027
+ });
39028
+ }
39029
+ displayNames.add(check2.displayName);
39030
+ }
39031
+ }
39032
+ function expandTriggerDefinitions(triggers) {
39033
+ const expanded = [];
39034
+ for (const trigger of triggers) {
39035
+ if (trigger.kind === "heartbeat") {
39036
+ expanded.push(trigger);
39037
+ continue;
39038
+ }
39039
+ const { events, ...singleTrigger } = trigger;
39040
+ for (const event of trigger.event ? [trigger.event] : events ?? []) {
39041
+ expanded.push({
39042
+ ...singleTrigger,
39043
+ event
39044
+ });
39045
+ }
39046
+ }
39047
+ return expanded;
39048
+ }
39049
+ function expandApplyTriggerDefinitions(triggers) {
39050
+ const expanded = [];
39051
+ for (const trigger of triggers) {
39052
+ if (trigger.kind === "heartbeat") {
39053
+ expanded.push(trigger);
39054
+ continue;
39055
+ }
39056
+ const { events, ...singleTrigger } = trigger;
39057
+ for (const event of trigger.event ? [trigger.event] : events ?? []) {
39058
+ expanded.push({
39059
+ ...singleTrigger,
39060
+ event
39061
+ });
39062
+ }
39063
+ }
39064
+ return expanded;
39065
+ }
39066
+ function validateAttributedRunsTriggerPairing(triggers, context) {
39067
+ for (const [index, trigger] of triggers.entries()) {
39068
+ if (trigger.kind === "heartbeat" || !trigger.event) {
39069
+ continue;
39070
+ }
39071
+ const eventTrigger = trigger;
39072
+ if (!isAttributedSessionsDeliverTrigger(eventTrigger) || !isChatMessageEvent(eventTrigger)) {
39073
+ continue;
39074
+ }
39075
+ if (hasFilterValue(eventTrigger, "$.auto.authored", false)) {
39076
+ continue;
39077
+ }
39078
+ context.addIssue({
39079
+ code: external_exports.ZodIssueCode.custom,
39080
+ path: [index, "where", "$.auto.authored"],
39081
+ message: 'Chat thread routes must filter out Auto-authored messages with "$.auto.authored": false.'
39082
+ });
39083
+ }
39084
+ for (const [spawnIndex, spawnTrigger] of triggers.entries()) {
39085
+ if (spawnTrigger.kind === "heartbeat" || !spawnTrigger.event) {
39086
+ continue;
39087
+ }
39088
+ if (!isSpawnTrigger(spawnTrigger)) {
39089
+ continue;
39090
+ }
39091
+ for (const [deliverIndex, deliverTrigger] of triggers.entries()) {
39092
+ if (deliverTrigger.kind === "heartbeat" || !deliverTrigger.event || spawnIndex === deliverIndex || spawnTrigger.event !== deliverTrigger.event || !isAttributedSessionsDeliverTrigger(deliverTrigger)) {
39093
+ continue;
39094
+ }
39095
+ if (hasAutoAttributionsExists(spawnTrigger, false) && hasAutoAttributionsExists(deliverTrigger, true)) {
39096
+ continue;
39097
+ }
39098
+ context.addIssue({
39099
+ code: external_exports.ZodIssueCode.custom,
39100
+ path: [deliverIndex, "route"],
39101
+ message: 'Overlapping spawn and chat thread routes on the same event must use mutually exclusive "$.auto.attributions" filters: spawn requires { exists: false }, delivery requires { exists: true }.'
39102
+ });
39103
+ }
39104
+ }
39105
+ }
39106
+ function isSpawnTrigger(trigger) {
39107
+ return routeCanSpawn(trigger.route);
39108
+ }
39109
+ function isAttributedSessionsDeliverTrigger(trigger) {
39110
+ return typeof trigger.route.to === "object" && trigger.route.to.target === "chat.thread";
39111
+ }
39112
+ function hasAutoAttributionsExists(trigger, expected) {
39113
+ const clause = trigger.where?.["$.auto.attributions"];
39114
+ return clause !== null && typeof clause === "object" && !Array.isArray(clause) && Reflect.get(clause, "exists") === expected;
39115
+ }
39116
+ function isChatMessageEvent(trigger) {
39117
+ return trigger.event.startsWith("chat.message.");
39118
+ }
39119
+ function hasFilterValue(trigger, path2, expected) {
39120
+ return trigger.where?.[path2] === expected;
39121
+ }
35897
39122
 
35898
39123
  // ../../packages/schemas/src/requester.ts
35899
39124
  var RequesterOriginSchema = external_exports.discriminatedUnion("kind", [
@@ -36224,6 +39449,125 @@ var SessionCommandRecordSchema = external_exports.discriminatedUnion("kind", [
36224
39449
  })
36225
39450
  ]);
36226
39451
 
39452
+ // ../../packages/schemas/src/validation-diagnostics.ts
39453
+ var AUTO_VALIDATION_DIAGNOSTIC_CATALOG_VERSION = 1;
39454
+ var AUTO_VALIDATION_DIAGNOSTIC_CATALOG = {
39455
+ "auto.validation.input.dialect_conflict": {
39456
+ severity: "error",
39457
+ message: "Choose exactly one supported validation input dialect.",
39458
+ owner: "schemas/project-apply"
39459
+ },
39460
+ "auto.validation.input.invalid_shape": {
39461
+ severity: "error",
39462
+ message: "The validation input does not match the selected dialect.",
39463
+ owner: "schemas/project-apply"
39464
+ },
39465
+ "auto.validation.authoring.facade_required": {
39466
+ severity: "error",
39467
+ message: "This file uses a typed resource envelope where an authoring facade is required.",
39468
+ owner: "schemas/project-apply-files"
39469
+ },
39470
+ "auto.validation.parse.yaml_invalid": {
39471
+ severity: "error",
39472
+ message: "The Auto authoring file could not be parsed as YAML or JSON.",
39473
+ owner: "schemas/project-apply-files"
39474
+ },
39475
+ "auto.validation.schema_version.invalid": {
39476
+ severity: "error",
39477
+ message: "The authored schema version must be a positive integer.",
39478
+ owner: "schemas/project-apply-files"
39479
+ },
39480
+ "auto.validation.schema_version.unsupported": {
39481
+ severity: "error",
39482
+ message: "This Auto release does not support the authored schema version.",
39483
+ owner: "schemas/project-apply-files"
39484
+ },
39485
+ "auto.validation.authoring.unknown_field": {
39486
+ severity: "error",
39487
+ message: "The versioned authoring document contains an unknown field.",
39488
+ owner: "schemas/project-apply-files"
39489
+ },
39490
+ "auto.validation.schema.invalid": {
39491
+ severity: "error",
39492
+ message: "The Auto resource does not match its schema.",
39493
+ owner: "schemas/project-apply-files"
39494
+ },
39495
+ "auto.validation.legacy.unknown": {
39496
+ severity: "error",
39497
+ message: "Auto validation failed without a recognized diagnostic code.",
39498
+ owner: "schemas/project-apply"
39499
+ }
39500
+ };
39501
+ var AUTO_VALIDATION_DIAGNOSTIC_CODES = Object.freeze(
39502
+ Object.keys(AUTO_VALIDATION_DIAGNOSTIC_CATALOG)
39503
+ );
39504
+ var AutoValidationDiagnosticSchema = external_exports.object({
39505
+ catalogVersion: external_exports.number().int().positive(),
39506
+ // Keep readers forward-compatible with codes added by a newer producer.
39507
+ // Catalog membership is enforced when this version creates diagnostics.
39508
+ code: external_exports.string().min(1),
39509
+ severity: external_exports.enum(["error", "warning", "info"]),
39510
+ blocking: external_exports.boolean(),
39511
+ message: external_exports.string().min(1),
39512
+ path: external_exports.array(external_exports.union([external_exports.string(), external_exports.number().int()])).optional(),
39513
+ location: external_exports.object({
39514
+ file: external_exports.string().min(1),
39515
+ line: external_exports.number().int().positive().optional(),
39516
+ column: external_exports.number().int().positive().optional(),
39517
+ documentIndex: external_exports.number().int().nonnegative().optional()
39518
+ }).optional(),
39519
+ remediation: external_exports.object({
39520
+ summary: external_exports.string().min(1),
39521
+ correctedCall: JsonValueSchema2.optional()
39522
+ }).optional()
39523
+ });
39524
+ function autoValidationDiagnostic(input) {
39525
+ const catalogEntry = AUTO_VALIDATION_DIAGNOSTIC_CATALOG[input.code];
39526
+ return AutoValidationDiagnosticSchema.parse({
39527
+ catalogVersion: AUTO_VALIDATION_DIAGNOSTIC_CATALOG_VERSION,
39528
+ code: input.code,
39529
+ severity: catalogEntry.severity,
39530
+ blocking: input.blocking ?? true,
39531
+ message: catalogEntry.message,
39532
+ ...input.path ? { path: input.path } : {},
39533
+ ...input.location ? { location: input.location } : {},
39534
+ ...input.remediation ? { remediation: input.remediation } : {}
39535
+ });
39536
+ }
39537
+ var AutoValidationDiagnosticError = class extends Error {
39538
+ diagnostic;
39539
+ // Compiler-owned, content-free provenance for immediate telemetry. Keep it
39540
+ // off the serialized diagnostic contract and immutable after first resolve.
39541
+ #authoringOrigin;
39542
+ constructor(message, diagnostic) {
39543
+ super(message);
39544
+ this.name = "AutoValidationDiagnosticError";
39545
+ this.diagnostic = diagnostic;
39546
+ }
39547
+ get authoringOrigin() {
39548
+ return this.#authoringOrigin;
39549
+ }
39550
+ withAuthoringOrigin(origin) {
39551
+ this.#authoringOrigin ??= origin;
39552
+ return this;
39553
+ }
39554
+ toJSON() {
39555
+ return {
39556
+ name: this.name,
39557
+ message: this.message,
39558
+ diagnostic: this.diagnostic
39559
+ };
39560
+ }
39561
+ };
39562
+ function autoValidationDiagnosticFromError(error51) {
39563
+ if (error51 instanceof AutoValidationDiagnosticError) {
39564
+ return error51.diagnostic;
39565
+ }
39566
+ return autoValidationDiagnostic({
39567
+ code: "auto.validation.legacy.unknown"
39568
+ });
39569
+ }
39570
+
36227
39571
  // ../../packages/schemas/src/runtime-log.ts
36228
39572
  var RUNTIME_LOG_LEVELS = ["debug", "info", "warn", "error"];
36229
39573
  var RuntimeLogLevelSchema = external_exports.enum(RUNTIME_LOG_LEVELS);
@@ -71600,6 +74944,220 @@ function one(e, t) {
71600
74944
  return null;
71601
74945
  }
71602
74946
 
74947
+ // ../../packages/schemas/src/project-apply-files/source.ts
74948
+ var import_yaml = __toESM(require_dist(), 1);
74949
+
74950
+ // ../../packages/schemas/src/project-apply-files/schema-version.ts
74951
+ var CURRENT_AUTHORED_SCHEMA_VERSION = 1;
74952
+ var LEGACY_AUTHORED_SCHEMA_DIALECT = Object.freeze({
74953
+ kind: "legacy"
74954
+ });
74955
+ var AUTHORED_SCHEMA_MIGRATIONS = Object.freeze([]);
74956
+ var CURRENT_AUTHORED_SCHEMA_DIALECT = Object.freeze({
74957
+ kind: "versioned",
74958
+ version: CURRENT_AUTHORED_SCHEMA_VERSION
74959
+ });
74960
+ function selectAuthoredSchemaDocument(input) {
74961
+ if (!isRecord(input.document) || !Object.hasOwn(input.document, "schemaVersion")) {
74962
+ return {
74963
+ dialect: LEGACY_AUTHORED_SCHEMA_DIALECT,
74964
+ value: input.document
74965
+ };
74966
+ }
74967
+ const version2 = input.document.schemaVersion;
74968
+ if (typeof version2 !== "number" || !isPositiveInteger(version2)) {
74969
+ throw malformedSchemaVersionError(input);
74970
+ }
74971
+ if (version2 > CURRENT_AUTHORED_SCHEMA_VERSION) {
74972
+ throw unsupportedSchemaVersionError(input, version2);
74973
+ }
74974
+ const { schemaVersion: _controlField, ...body } = input.document;
74975
+ return {
74976
+ dialect: CURRENT_AUTHORED_SCHEMA_DIALECT,
74977
+ value: migrateAuthoredSchemaDocument({
74978
+ document: body,
74979
+ fromVersion: version2,
74980
+ toVersion: CURRENT_AUTHORED_SCHEMA_VERSION,
74981
+ migrations: AUTHORED_SCHEMA_MIGRATIONS
74982
+ })
74983
+ };
74984
+ }
74985
+ function migrateAuthoredSchemaDocument(input) {
74986
+ if (!isPositiveInteger(input.fromVersion) || !isPositiveInteger(input.toVersion)) {
74987
+ throw new Error(
74988
+ "Authored schema migration endpoints must be positive integers"
74989
+ );
74990
+ }
74991
+ if (input.fromVersion > input.toVersion) {
74992
+ throw new Error(
74993
+ `Authored schema migrations cannot move backward from ${input.fromVersion} to ${input.toVersion}`
74994
+ );
74995
+ }
74996
+ let document2 = structuredClone(input.document);
74997
+ for (let version2 = input.fromVersion; version2 < input.toVersion; version2 += 1) {
74998
+ const edges = input.migrations.filter(
74999
+ (edge) => edge.fromVersion === version2
75000
+ );
75001
+ if (edges.length !== 1 || edges[0]?.toVersion !== version2 + 1) {
75002
+ throw new Error(
75003
+ `Authored schema migration chain requires exactly one ${version2} -> ${version2 + 1} edge`
75004
+ );
75005
+ }
75006
+ document2 = edges[0].migrate(structuredClone(document2));
75007
+ }
75008
+ return document2;
75009
+ }
75010
+ function malformedSchemaVersionError(input) {
75011
+ return new AutoValidationDiagnosticError(
75012
+ `Invalid schemaVersion in ${documentLabel(input)}: expected a positive integer`,
75013
+ autoValidationDiagnostic({
75014
+ code: "auto.validation.schema_version.invalid",
75015
+ path: ["schemaVersion"],
75016
+ location: diagnosticLocation(input),
75017
+ remediation: {
75018
+ summary: `Set schemaVersion to ${CURRENT_AUTHORED_SCHEMA_VERSION}, or remove it to retain the legacy dialect.`
75019
+ }
75020
+ })
75021
+ );
75022
+ }
75023
+ function unsupportedSchemaVersionError(input, version2) {
75024
+ return new AutoValidationDiagnosticError(
75025
+ `Unsupported schemaVersion ${version2} in ${documentLabel(input)}: this Auto release supports through ${CURRENT_AUTHORED_SCHEMA_VERSION}`,
75026
+ autoValidationDiagnostic({
75027
+ code: "auto.validation.schema_version.unsupported",
75028
+ path: ["schemaVersion"],
75029
+ location: diagnosticLocation(input),
75030
+ remediation: {
75031
+ summary: "Upgrade Auto to a release that supports this authored schema version, then validate again."
75032
+ }
75033
+ })
75034
+ );
75035
+ }
75036
+ function documentLabel(input) {
75037
+ return `${input.location.file} document ${input.documentIndex + 1}`;
75038
+ }
75039
+ function diagnosticLocation(input) {
75040
+ return {
75041
+ ...input.topLevelLocations.schemaVersion ?? input.location,
75042
+ documentIndex: input.documentIndex
75043
+ };
75044
+ }
75045
+ function isRecord(value) {
75046
+ return typeof value === "object" && value !== null && !Array.isArray(value);
75047
+ }
75048
+ function isPositiveInteger(value) {
75049
+ return Number.isInteger(value) && value > 0;
75050
+ }
75051
+
75052
+ // ../../packages/schemas/src/project-apply-files/source.ts
75053
+ var APPLY_DIRECTORIES = {
75054
+ [RESOURCE_KIND_AGENT]: "agents"
75055
+ };
75056
+ var PROJECT_APPLY_RESOURCE_DIRECTORIES = Object.freeze([
75057
+ APPLY_DIRECTORIES[RESOURCE_KIND_AGENT]
75058
+ ]);
75059
+ function readSourceDocuments(file2) {
75060
+ const source = Buffer.from(file2.contentBase64, "base64").toString("utf8");
75061
+ const lineCounter = new import_yaml.LineCounter();
75062
+ let parsedDocuments;
75063
+ try {
75064
+ parsedDocuments = (0, import_yaml.parseAllDocuments)(source, {
75065
+ keepSourceTokens: true,
75066
+ lineCounter
75067
+ });
75068
+ const parseError = parsedDocuments.flatMap((document2) => document2.errors).at(0);
75069
+ if (parseError) {
75070
+ throw parseError;
75071
+ }
75072
+ } catch {
75073
+ throw new AutoValidationDiagnosticError(
75074
+ `Invalid apply file ${file2.path}: YAML or JSON could not be parsed`,
75075
+ autoValidationDiagnostic({
75076
+ code: "auto.validation.parse.yaml_invalid",
75077
+ location: { file: file2.path },
75078
+ remediation: {
75079
+ summary: "Fix the YAML or JSON syntax in this file, then validate again."
75080
+ }
75081
+ })
75082
+ );
75083
+ }
75084
+ return parsedDocuments.flatMap((document2, documentIndex) => {
75085
+ if (document2.contents === null) {
75086
+ return [];
75087
+ }
75088
+ const value = sourceDocumentValue(document2, file2.path);
75089
+ const location = sourceNodeLocation(
75090
+ document2.contents,
75091
+ file2.path,
75092
+ lineCounter
75093
+ );
75094
+ const topLevelLocations = topLevelSourceLocations(
75095
+ document2.contents,
75096
+ file2.path,
75097
+ lineCounter
75098
+ );
75099
+ const selected = selectAuthoredSchemaDocument({
75100
+ document: value,
75101
+ documentIndex,
75102
+ location,
75103
+ topLevelLocations
75104
+ });
75105
+ return [
75106
+ {
75107
+ ...selected,
75108
+ documentIndex,
75109
+ location,
75110
+ topLevelLocations
75111
+ }
75112
+ ];
75113
+ });
75114
+ }
75115
+ function sourceDocumentValue(document2, file2) {
75116
+ try {
75117
+ return document2.toJSON();
75118
+ } catch {
75119
+ throw invalidSourceSyntaxError(file2);
75120
+ }
75121
+ }
75122
+ function invalidSourceSyntaxError(file2) {
75123
+ return new AutoValidationDiagnosticError(
75124
+ `Invalid apply file ${file2}: YAML or JSON could not be parsed`,
75125
+ autoValidationDiagnostic({
75126
+ code: "auto.validation.parse.yaml_invalid",
75127
+ location: { file: file2 },
75128
+ remediation: {
75129
+ summary: "Fix the YAML or JSON syntax in this file, then validate again."
75130
+ }
75131
+ })
75132
+ );
75133
+ }
75134
+ function normalizeSourcePath(path2) {
75135
+ return path2.replaceAll("\\", "/").replace(/^\/+|\/+$/g, "");
75136
+ }
75137
+ function topLevelSourceLocations(node, file2, lineCounter) {
75138
+ if (!(0, import_yaml.isMap)(node)) {
75139
+ return {};
75140
+ }
75141
+ return Object.fromEntries(
75142
+ node.items.flatMap((pair) => {
75143
+ const key = pair.key?.toJSON?.();
75144
+ if (typeof key !== "string") {
75145
+ return [];
75146
+ }
75147
+ return [[key, sourceNodeLocation(pair.key, file2, lineCounter)]];
75148
+ })
75149
+ );
75150
+ }
75151
+ function sourceNodeLocation(node, file2, lineCounter) {
75152
+ const range = node?.range;
75153
+ const position = lineCounter.linePos(range?.[0] ?? 0);
75154
+ return {
75155
+ file: normalizeSourcePath(file2),
75156
+ line: position.line,
75157
+ column: position.col
75158
+ };
75159
+ }
75160
+
71603
75161
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
71604
75162
  var LATEST_PROTOCOL_VERSION = "2025-11-25";
71605
75163
  var DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26";
@@ -73121,9 +76679,6 @@ var UrlElicitationRequiredError = class extends McpError {
73121
76679
  }
73122
76680
  };
73123
76681
 
73124
- // src/commands/agent-bridge/harness/agent-facing-auto-mcp.ts
73125
- var import_yaml = __toESM(require_dist(), 1);
73126
-
73127
76682
  // src/lib/project-apply-filesystem-source.ts
73128
76683
  import { readFileSync as readFileSync2, readdirSync as readdirSync2 } from "fs";
73129
76684
  import { basename as basename3, dirname as dirname4, join as join5, relative as relative2, resolve as resolve5 } from "path";
@@ -73286,12 +76841,12 @@ async function createClaudeAutoMcpServer(input) {
73286
76841
  });
73287
76842
  const transformed = input.transformDryRun ? transformToolsListResponse(JSON.stringify(listResponse)) : { body: JSON.stringify(listResponse), pathsCompatible: false };
73288
76843
  const listed = JSON.parse(transformed.body);
73289
- if (isRecord(listed.error)) {
76844
+ if (isRecord3(listed.error)) {
73290
76845
  throw new AgentBridgeTerminalPrepareError(
73291
76846
  typeof listed.error.message === "string" ? listed.error.message : `Auto MCP server ${input.name} failed tools/list`
73292
76847
  );
73293
76848
  }
73294
- const result = isRecord(listed.result) ? listed.result : {};
76849
+ const result = isRecord3(listed.result) ? listed.result : {};
73295
76850
  const tools = Array.isArray(result.tools) ? result.tools : [];
73296
76851
  const sdkServer = tJe({ name: input.name, version: "1" });
73297
76852
  sdkServer.instance.server.registerCapabilities({ tools: {} });
@@ -73324,7 +76879,7 @@ async function createClaudeAutoMcpServer(input) {
73324
76879
  message,
73325
76880
  commandId: exactActiveCommandId(input.activeTurnCommandIds)
73326
76881
  });
73327
- if (isRecord(response.error)) {
76882
+ if (isRecord3(response.error)) {
73328
76883
  return {
73329
76884
  content: [
73330
76885
  {
@@ -73364,7 +76919,7 @@ function parseJsonRpcResponseBody(body) {
73364
76919
  }
73365
76920
  try {
73366
76921
  const candidate = JSON.parse(line.slice("data:".length).trim());
73367
- if (isRecord(candidate)) {
76922
+ if (isRecord3(candidate)) {
73368
76923
  parsed = candidate;
73369
76924
  }
73370
76925
  } catch {
@@ -73376,7 +76931,7 @@ function parseJsonRpcResponseBody(body) {
73376
76931
  return parsed;
73377
76932
  }
73378
76933
  function asCallToolResult(value) {
73379
- if (isRecord(value) && Array.isArray(value.content)) {
76934
+ if (isRecord3(value) && Array.isArray(value.content)) {
73380
76935
  return value;
73381
76936
  }
73382
76937
  return {
@@ -73384,7 +76939,7 @@ function asCallToolResult(value) {
73384
76939
  };
73385
76940
  }
73386
76941
  function agentFacingDryRunTool(tool) {
73387
- if (!isRecord(tool) || tool.name !== DRY_RUN_TOOL_NAME) {
76942
+ if (!isRecord3(tool) || tool.name !== DRY_RUN_TOOL_NAME) {
73388
76943
  return tool;
73389
76944
  }
73390
76945
  if (typeof tool.description !== "string" || !tool.description.includes(AUTO_RESOURCES_DRY_RUN_PATHS_PROTOCOL_MARKER)) {
@@ -73413,7 +76968,7 @@ function agentFacingDryRunTool(tool) {
73413
76968
  };
73414
76969
  }
73415
76970
  function resolveAgentFacingDryRun(input) {
73416
- if (!isRecord(input.arguments)) {
76971
+ if (!isRecord3(input.arguments)) {
73417
76972
  throw new Error(`Dry-run arguments must be an object. ${correctedCall}`);
73418
76973
  }
73419
76974
  const argumentsValue = input.arguments;
@@ -73571,9 +77126,12 @@ function readContainedTextFile(cwdRoot, path2) {
73571
77126
  }
73572
77127
  function localImportPaths(content, importerPath) {
73573
77128
  const imports = [];
73574
- for (const document2 of (0, import_yaml.parseAllDocuments)(content)) {
73575
- const value = document2.toJS();
73576
- if (!isRecord(value) || !Array.isArray(value.imports)) {
77129
+ for (const document2 of readSourceDocuments({
77130
+ path: importerPath,
77131
+ contentBase64: Buffer.from(content, "utf8").toString("base64")
77132
+ })) {
77133
+ const value = document2.value;
77134
+ if (!isRecord3(value) || !Array.isArray(value.imports)) {
73577
77135
  continue;
73578
77136
  }
73579
77137
  for (const importPath of value.imports) {
@@ -73745,8 +77303,8 @@ async function startAutoMcpProxy(input) {
73745
77303
  return { server, url: `http://127.0.0.1:${address.port}/mcp` };
73746
77304
  }
73747
77305
  function prepareDryRunToolCall(input) {
73748
- const params = isRecord(input.message.params) ? input.message.params : {};
73749
- const argumentsValue = isRecord(params.arguments) ? params.arguments : {};
77306
+ const params = isRecord3(input.message.params) ? input.message.params : {};
77307
+ const argumentsValue = isRecord3(params.arguments) ? params.arguments : {};
73750
77308
  const hasLegacyDialect = ["files", "resources"].some(
73751
77309
  (key) => Object.hasOwn(argumentsValue, key)
73752
77310
  );
@@ -73781,6 +77339,15 @@ function prepareDryRunToolCall(input) {
73781
77339
  if (error51 instanceof Error && error51.message === "legacy-pass-through") {
73782
77340
  return { kind: "forward", message: input.message };
73783
77341
  }
77342
+ if (error51 instanceof AutoValidationDiagnosticError) {
77343
+ return toolError(
77344
+ input.message.id,
77345
+ JSON.stringify({
77346
+ error: error51.message,
77347
+ diagnostic: autoValidationDiagnosticFromError(error51)
77348
+ })
77349
+ );
77350
+ }
73784
77351
  return toolError(
73785
77352
  input.message.id,
73786
77353
  error51 instanceof Error ? error51.message : String(error51)
@@ -73791,7 +77358,7 @@ function transformToolsListResponse(body) {
73791
77358
  const parsed = JSON.parse(body);
73792
77359
  let compatible = false;
73793
77360
  const transformed = transformJsonRpcMessages(parsed, (message) => {
73794
- if (!isRecord(message.result) || !Array.isArray(message.result.tools)) {
77361
+ if (!isRecord3(message.result) || !Array.isArray(message.result.tools)) {
73795
77362
  return message;
73796
77363
  }
73797
77364
  const tools = message.result.tools.map((tool) => {
@@ -73808,16 +77375,16 @@ function transformToolsListResponse(body) {
73808
77375
  function transformJsonRpcMessages(value, transform2) {
73809
77376
  if (Array.isArray(value)) {
73810
77377
  return value.map(
73811
- (message) => isRecord(message) ? transform2(message) : message
77378
+ (message) => isRecord3(message) ? transform2(message) : message
73812
77379
  );
73813
77380
  }
73814
- return isRecord(value) ? transform2(value) : value;
77381
+ return isRecord3(value) ? transform2(value) : value;
73815
77382
  }
73816
77383
  function isToolsListRequest(value) {
73817
- return isRecord(value) && value.method === "tools/list";
77384
+ return isRecord3(value) && value.method === "tools/list";
73818
77385
  }
73819
77386
  function isDryRunToolCall(value) {
73820
- if (!isRecord(value) || value.method !== "tools/call" || !isRecord(value.params)) {
77387
+ if (!isRecord3(value) || value.method !== "tools/call" || !isRecord3(value.params)) {
73821
77388
  return false;
73822
77389
  }
73823
77390
  return value.params.name === DRY_RUN_TOOL_NAME;
@@ -73890,7 +77457,7 @@ function writeResponse(response, status, headers, body) {
73890
77457
  }
73891
77458
  response.end(body);
73892
77459
  }
73893
- function isRecord(value) {
77460
+ function isRecord3(value) {
73894
77461
  return typeof value === "object" && value !== null && !Array.isArray(value);
73895
77462
  }
73896
77463
 
@@ -77576,12 +81143,12 @@ function canonicalizeMcpResultValue(value) {
77576
81143
  if (typeof value !== "object" || value === null) {
77577
81144
  return { value, deduplicatedBranches: 0 };
77578
81145
  }
77579
- const record2 = value;
77580
- const duplicateContentIndexes = equivalentMcpTextContentIndexes(record2);
81146
+ const record3 = value;
81147
+ const duplicateContentIndexes = equivalentMcpTextContentIndexes(record3);
77581
81148
  let deduplicatedBranches = duplicateContentIndexes.size;
77582
81149
  let changed = duplicateContentIndexes.size > 0;
77583
81150
  const canonical = /* @__PURE__ */ Object.create(null);
77584
- for (const [key, item] of Object.entries(record2)) {
81151
+ for (const [key, item] of Object.entries(record3)) {
77585
81152
  if (key === "content" && Array.isArray(item)) {
77586
81153
  const retainedContent = duplicateContentIndexes.size > 0 ? item.filter(
77587
81154
  (_contentItem, index) => !duplicateContentIndexes.has(index)
@@ -77625,9 +81192,9 @@ function isPlainMcpTextBlock(value) {
77625
81192
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
77626
81193
  return false;
77627
81194
  }
77628
- const record2 = value;
77629
- const keys = Object.keys(record2);
77630
- return keys.length === 2 && record2.type === "text" && typeof record2.text === "string";
81195
+ const record3 = value;
81196
+ const keys = Object.keys(record3);
81197
+ return keys.length === 2 && record3.type === "text" && typeof record3.text === "string";
77631
81198
  }
77632
81199
  function parseJson(value) {
77633
81200
  try {
@@ -79948,15 +83515,15 @@ function fileClaudeSessionResumeStore(path2 = CLAUDE_SESSION_RESUME_PATH) {
79948
83515
  if (!existsSync2(path2)) {
79949
83516
  return null;
79950
83517
  }
79951
- const record2 = parseResumeRecord(readFileSync4(path2, "utf8"));
79952
- if (!record2 || record2.sessionId !== sessionId) {
83518
+ const record3 = parseResumeRecord(readFileSync4(path2, "utf8"));
83519
+ if (!record3 || record3.sessionId !== sessionId) {
79953
83520
  return null;
79954
83521
  }
79955
- return record2.agentId;
83522
+ return record3.agentId;
79956
83523
  },
79957
- write(record2) {
83524
+ write(record3) {
79958
83525
  mkdirSync2(dirname5(path2), { recursive: true });
79959
- writeFileSync(path2, `${JSON.stringify(record2)}
83526
+ writeFileSync(path2, `${JSON.stringify(record3)}
79960
83527
  `, "utf8");
79961
83528
  }
79962
83529
  };
@@ -80084,15 +83651,15 @@ function fileClaudeReadStateStore(path2 = CLAUDE_READ_STATE_PATH) {
80084
83651
  if (!existsSync3(path2)) {
80085
83652
  return null;
80086
83653
  }
80087
- const record2 = parseReadStateRecord(readFileSync5(path2, "utf8"));
80088
- if (!record2 || record2.sessionId !== sessionId) {
83654
+ const record3 = parseReadStateRecord(readFileSync5(path2, "utf8"));
83655
+ if (!record3 || record3.sessionId !== sessionId) {
80089
83656
  return null;
80090
83657
  }
80091
- return record2.entries;
83658
+ return record3.entries;
80092
83659
  },
80093
- write(record2) {
83660
+ write(record3) {
80094
83661
  mkdirSync3(dirname6(path2), { recursive: true });
80095
- writeFileSync2(path2, `${JSON.stringify(record2)}
83662
+ writeFileSync2(path2, `${JSON.stringify(record3)}
80096
83663
  `, "utf8");
80097
83664
  }
80098
83665
  };
@@ -82414,15 +85981,15 @@ function fileCodexThreadResumeStore(path2 = CODEX_THREAD_RESUME_PATH) {
82414
85981
  if (!existsSync4(path2)) {
82415
85982
  return null;
82416
85983
  }
82417
- const record2 = parseResumeRecord2(readFileSync6(path2, "utf8"));
82418
- if (!record2 || record2.sessionId !== sessionId) {
85984
+ const record3 = parseResumeRecord2(readFileSync6(path2, "utf8"));
85985
+ if (!record3 || record3.sessionId !== sessionId) {
82419
85986
  return null;
82420
85987
  }
82421
- return record2.threadId;
85988
+ return record3.threadId;
82422
85989
  },
82423
- write(record2) {
85990
+ write(record3) {
82424
85991
  mkdirSync4(dirname7(path2), { recursive: true });
82425
- writeFileSync3(path2, `${JSON.stringify(record2)}
85992
+ writeFileSync3(path2, `${JSON.stringify(record3)}
82426
85993
  `, "utf8");
82427
85994
  }
82428
85995
  };
@@ -83946,11 +87513,11 @@ function idFromResult(result, field) {
83946
87513
  if (result === null || typeof result !== "object") {
83947
87514
  return null;
83948
87515
  }
83949
- const record2 = Reflect.get(result, field);
83950
- if (record2 === null || typeof record2 !== "object") {
87516
+ const record3 = Reflect.get(result, field);
87517
+ if (record3 === null || typeof record3 !== "object") {
83951
87518
  return null;
83952
87519
  }
83953
- const id = Reflect.get(record2, "id");
87520
+ const id = Reflect.get(record3, "id");
83954
87521
  return typeof id === "string" && id.length > 0 ? id : null;
83955
87522
  }
83956
87523
  function errorMessage8(error51) {