@slock-ai/daemon 0.57.5 → 0.57.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -166,6 +166,8 @@ function routeFamilyForPath(pathname) {
166
166
  if (normalized === "/internal/agent-api/tasks" || normalized.startsWith("/internal/agent-api/tasks/")) {
167
167
  return "tasks";
168
168
  }
169
+ if (/^\/internal\/agent-api\/attachments\/[^/]+\/comments/.test(normalized)) return "agent-api/attachments/comments";
170
+ if (/^\/api\/attachments\/[^/]+\/comments/.test(normalized)) return "agent-api/attachments/comments";
169
171
  if (normalized.startsWith("/internal/agent-api/attachments/")) return "agent-api/attachments";
170
172
  if (normalized.startsWith("/api/attachments/")) return "attachments/download";
171
173
  if (/^\/internal\/agent-api\/messages\/[^/]+\/reactions$/.test(normalized)) return "agent-api/messages/reactions";
@@ -1046,6 +1048,12 @@ var DEVICE_CODE_OPTION = {
1046
1048
  flags: "--device-code <code>",
1047
1049
  description: "The device_code returned by `slock agent login start`"
1048
1050
  };
1051
+ function mergeParentLoginOpts(options, command) {
1052
+ if (command && typeof command.optsWithGlobals === "function") {
1053
+ return { ...command.optsWithGlobals(), ...options };
1054
+ }
1055
+ return options;
1056
+ }
1049
1057
  var agentLoginCommand = defineCommand(
1050
1058
  {
1051
1059
  name: "login",
@@ -1084,7 +1092,8 @@ var agentLoginStartCommand = defineCommand(
1084
1092
  description: "Begin device-code login and print the browser handoff, then exit (does not wait for approval).",
1085
1093
  options: [SERVER_OPTION, AGENT_OPTION, CLIENT_NAME_OPTION, PROFILE_SLUG_OPTION, PROFILE_DIR_OPTION]
1086
1094
  },
1087
- async (ctx, options) => {
1095
+ async (ctx, rawOptions, command) => {
1096
+ const options = mergeParentLoginOpts(rawOptions, command);
1088
1097
  validateServerAgent(options);
1089
1098
  const paths = resolveProfilePaths(options);
1090
1099
  let authorization;
@@ -1105,7 +1114,8 @@ var agentLoginWaitCommand = defineCommand(
1105
1114
  description: "Wait for the user to approve a `login start` request, then mint and save the credential.",
1106
1115
  options: [SERVER_OPTION, AGENT_OPTION, DEVICE_CODE_OPTION, PROFILE_SLUG_OPTION, PROFILE_DIR_OPTION]
1107
1116
  },
1108
- async (ctx, options) => {
1117
+ async (ctx, rawOptions, command) => {
1118
+ const options = mergeParentLoginOpts(rawOptions, command);
1109
1119
  validateServerAgent(options);
1110
1120
  if (!options.deviceCode?.trim()) {
1111
1121
  throw cliError("INVALID_ARG", "--device-code is required (the value printed by `slock agent login start`).");
@@ -1131,7 +1141,8 @@ var agentLoginStatusCommand = defineCommand(
1131
1141
  description: "Report whether the local profile credential is usable, expired, or needs re-login.",
1132
1142
  options: [SERVER_OPTION, AGENT_OPTION, PROFILE_SLUG_OPTION, PROFILE_DIR_OPTION]
1133
1143
  },
1134
- async (ctx, options) => {
1144
+ async (ctx, rawOptions, command) => {
1145
+ const options = mergeParentLoginOpts(rawOptions, command);
1135
1146
  validateServerAgent(options);
1136
1147
  const paths = resolveProfilePaths(options);
1137
1148
  if (!await profileFileExists(paths.credentialPath)) {
@@ -1264,7 +1275,8 @@ async function mintAndPersist(ctx, options, accessToken, paths) {
1264
1275
  ctx.io.stdout.write(
1265
1276
  `state: authorized
1266
1277
  Logged in as '${minted.agentName}' on ${options.server}. Credential saved to ${paths.credentialPath}.
1267
- Next: run \`slock manual get slock-cli-overview\` to learn the Slock CLI, then use \`slock --profile ${paths.profileSlug} \u2026\` for all commands.
1278
+ Next (if you are the human operator): start your agent with SLOCK_PROFILE=${paths.profileSlug} in its environment, and let the agent run \`slock manual get slock-cli-overview\` to learn the Slock CLI.
1279
+ Next (if you are the agent): run \`slock manual get slock-cli-overview\`, then use \`slock --profile ${paths.profileSlug} \u2026\` for all commands.
1268
1280
  `
1269
1281
  );
1270
1282
  }
@@ -2337,10 +2349,10 @@ function mergeDefs(...defs) {
2337
2349
  function cloneDef(schema) {
2338
2350
  return mergeDefs(schema._zod.def);
2339
2351
  }
2340
- function getElementAtPath(obj, path7) {
2341
- if (!path7)
2352
+ function getElementAtPath(obj, path8) {
2353
+ if (!path8)
2342
2354
  return obj;
2343
- return path7.reduce((acc, key) => acc?.[key], obj);
2355
+ return path8.reduce((acc, key) => acc?.[key], obj);
2344
2356
  }
2345
2357
  function promiseAllObject(promisesObj) {
2346
2358
  const keys = Object.keys(promisesObj);
@@ -2723,11 +2735,11 @@ function aborted(x, startIndex = 0) {
2723
2735
  }
2724
2736
  return false;
2725
2737
  }
2726
- function prefixIssues(path7, issues) {
2738
+ function prefixIssues(path8, issues) {
2727
2739
  return issues.map((iss) => {
2728
2740
  var _a2;
2729
2741
  (_a2 = iss).path ?? (_a2.path = []);
2730
- iss.path.unshift(path7);
2742
+ iss.path.unshift(path8);
2731
2743
  return iss;
2732
2744
  });
2733
2745
  }
@@ -2909,8 +2921,8 @@ function formatError(error48, mapper = (issue2) => issue2.message) {
2909
2921
  return fieldErrors;
2910
2922
  }
2911
2923
  function treeifyError(error48, mapper = (issue2) => issue2.message) {
2912
- const result = { errors: [] };
2913
- const processError = (error49, path7 = []) => {
2924
+ const result2 = { errors: [] };
2925
+ const processError = (error49, path8 = []) => {
2914
2926
  var _a2, _b;
2915
2927
  for (const issue2 of error49.issues) {
2916
2928
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -2920,12 +2932,12 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
2920
2932
  } else if (issue2.code === "invalid_element") {
2921
2933
  processError({ issues: issue2.issues }, issue2.path);
2922
2934
  } else {
2923
- const fullpath = [...path7, ...issue2.path];
2935
+ const fullpath = [...path8, ...issue2.path];
2924
2936
  if (fullpath.length === 0) {
2925
- result.errors.push(mapper(issue2));
2937
+ result2.errors.push(mapper(issue2));
2926
2938
  continue;
2927
2939
  }
2928
- let curr = result;
2940
+ let curr = result2;
2929
2941
  let i = 0;
2930
2942
  while (i < fullpath.length) {
2931
2943
  const el = fullpath[i];
@@ -2948,12 +2960,12 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
2948
2960
  }
2949
2961
  };
2950
2962
  processError(error48);
2951
- return result;
2963
+ return result2;
2952
2964
  }
2953
2965
  function toDotPath(_path) {
2954
2966
  const segs = [];
2955
- const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2956
- for (const seg of path7) {
2967
+ const path8 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2968
+ for (const seg of path8) {
2957
2969
  if (typeof seg === "number")
2958
2970
  segs.push(`[${seg}]`);
2959
2971
  else if (typeof seg === "symbol")
@@ -2982,52 +2994,52 @@ function prettifyError(error48) {
2982
2994
  // ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js
2983
2995
  var _parse = (_Err) => (schema, value, _ctx, _params) => {
2984
2996
  const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
2985
- const result = schema._zod.run({ value, issues: [] }, ctx);
2986
- if (result instanceof Promise) {
2997
+ const result2 = schema._zod.run({ value, issues: [] }, ctx);
2998
+ if (result2 instanceof Promise) {
2987
2999
  throw new $ZodAsyncError();
2988
3000
  }
2989
- if (result.issues.length) {
2990
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
3001
+ if (result2.issues.length) {
3002
+ const e = new (_params?.Err ?? _Err)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config())));
2991
3003
  captureStackTrace(e, _params?.callee);
2992
3004
  throw e;
2993
3005
  }
2994
- return result.value;
3006
+ return result2.value;
2995
3007
  };
2996
3008
  var parse = /* @__PURE__ */ _parse($ZodRealError);
2997
3009
  var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
2998
3010
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
2999
- let result = schema._zod.run({ value, issues: [] }, ctx);
3000
- if (result instanceof Promise)
3001
- result = await result;
3002
- if (result.issues.length) {
3003
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
3011
+ let result2 = schema._zod.run({ value, issues: [] }, ctx);
3012
+ if (result2 instanceof Promise)
3013
+ result2 = await result2;
3014
+ if (result2.issues.length) {
3015
+ const e = new (params?.Err ?? _Err)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config())));
3004
3016
  captureStackTrace(e, params?.callee);
3005
3017
  throw e;
3006
3018
  }
3007
- return result.value;
3019
+ return result2.value;
3008
3020
  };
3009
3021
  var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
3010
3022
  var _safeParse = (_Err) => (schema, value, _ctx) => {
3011
3023
  const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
3012
- const result = schema._zod.run({ value, issues: [] }, ctx);
3013
- if (result instanceof Promise) {
3024
+ const result2 = schema._zod.run({ value, issues: [] }, ctx);
3025
+ if (result2 instanceof Promise) {
3014
3026
  throw new $ZodAsyncError();
3015
3027
  }
3016
- return result.issues.length ? {
3028
+ return result2.issues.length ? {
3017
3029
  success: false,
3018
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
3019
- } : { success: true, data: result.value };
3030
+ error: new (_Err ?? $ZodError)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config())))
3031
+ } : { success: true, data: result2.value };
3020
3032
  };
3021
3033
  var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
3022
3034
  var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
3023
3035
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
3024
- let result = schema._zod.run({ value, issues: [] }, ctx);
3025
- if (result instanceof Promise)
3026
- result = await result;
3027
- return result.issues.length ? {
3036
+ let result2 = schema._zod.run({ value, issues: [] }, ctx);
3037
+ if (result2 instanceof Promise)
3038
+ result2 = await result2;
3039
+ return result2.issues.length ? {
3028
3040
  success: false,
3029
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
3030
- } : { success: true, data: result.value };
3041
+ error: new _Err(result2.issues.map((iss) => finalizeIssue(iss, ctx, config())))
3042
+ } : { success: true, data: result2.value };
3031
3043
  };
3032
3044
  var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
3033
3045
  var _encode = (_Err) => (schema, value, _ctx) => {
@@ -3728,22 +3740,22 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst,
3728
3740
  });
3729
3741
  };
3730
3742
  });
3731
- function handleCheckPropertyResult(result, payload, property) {
3732
- if (result.issues.length) {
3733
- payload.issues.push(...prefixIssues(property, result.issues));
3743
+ function handleCheckPropertyResult(result2, payload, property) {
3744
+ if (result2.issues.length) {
3745
+ payload.issues.push(...prefixIssues(property, result2.issues));
3734
3746
  }
3735
3747
  }
3736
3748
  var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => {
3737
3749
  $ZodCheck.init(inst, def);
3738
3750
  inst._zod.check = (payload) => {
3739
- const result = def.schema._zod.run({
3751
+ const result2 = def.schema._zod.run({
3740
3752
  value: payload.value[def.property],
3741
3753
  issues: []
3742
3754
  }, {});
3743
- if (result instanceof Promise) {
3744
- return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property));
3755
+ if (result2 instanceof Promise) {
3756
+ return result2.then((result3) => handleCheckPropertyResult(result3, payload, def.property));
3745
3757
  }
3746
- handleCheckPropertyResult(result, payload, def.property);
3758
+ handleCheckPropertyResult(result2, payload, def.property);
3747
3759
  return;
3748
3760
  };
3749
3761
  });
@@ -3903,13 +3915,13 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
3903
3915
  }
3904
3916
  return handleCanaryResult(canary, payload, ctx);
3905
3917
  }
3906
- const result = inst._zod.parse(payload, ctx);
3907
- if (result instanceof Promise) {
3918
+ const result2 = inst._zod.parse(payload, ctx);
3919
+ if (result2 instanceof Promise) {
3908
3920
  if (ctx.async === false)
3909
3921
  throw new $ZodAsyncError();
3910
- return result.then((result2) => runChecks(result2, checks, ctx));
3922
+ return result2.then((result3) => runChecks(result3, checks, ctx));
3911
3923
  }
3912
- return runChecks(result, checks, ctx);
3924
+ return runChecks(result2, checks, ctx);
3913
3925
  };
3914
3926
  }
3915
3927
  defineLazy(inst, "~standard", () => ({
@@ -4418,11 +4430,11 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
4418
4430
  return payload;
4419
4431
  };
4420
4432
  });
4421
- function handleArrayResult(result, final, index) {
4422
- if (result.issues.length) {
4423
- final.issues.push(...prefixIssues(index, result.issues));
4433
+ function handleArrayResult(result2, final, index) {
4434
+ if (result2.issues.length) {
4435
+ final.issues.push(...prefixIssues(index, result2.issues));
4424
4436
  }
4425
- final.value[index] = result.value;
4437
+ final.value[index] = result2.value;
4426
4438
  }
4427
4439
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
4428
4440
  $ZodType.init(inst, def);
@@ -4441,14 +4453,14 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
4441
4453
  const proms = [];
4442
4454
  for (let i = 0; i < input.length; i++) {
4443
4455
  const item = input[i];
4444
- const result = def.element._zod.run({
4456
+ const result2 = def.element._zod.run({
4445
4457
  value: item,
4446
4458
  issues: []
4447
4459
  }, ctx);
4448
- if (result instanceof Promise) {
4449
- proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));
4460
+ if (result2 instanceof Promise) {
4461
+ proms.push(result2.then((result3) => handleArrayResult(result3, payload, i)));
4450
4462
  } else {
4451
- handleArrayResult(result, payload, i);
4463
+ handleArrayResult(result2, payload, i);
4452
4464
  }
4453
4465
  }
4454
4466
  if (proms.length) {
@@ -4457,19 +4469,19 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
4457
4469
  return payload;
4458
4470
  };
4459
4471
  });
4460
- function handlePropertyResult(result, final, key, input, isOptionalOut) {
4461
- if (result.issues.length) {
4472
+ function handlePropertyResult(result2, final, key, input, isOptionalOut) {
4473
+ if (result2.issues.length) {
4462
4474
  if (isOptionalOut && !(key in input)) {
4463
4475
  return;
4464
4476
  }
4465
- final.issues.push(...prefixIssues(key, result.issues));
4477
+ final.issues.push(...prefixIssues(key, result2.issues));
4466
4478
  }
4467
- if (result.value === void 0) {
4479
+ if (result2.value === void 0) {
4468
4480
  if (key in input) {
4469
4481
  final.value[key] = void 0;
4470
4482
  }
4471
4483
  } else {
4472
- final.value[key] = result.value;
4484
+ final.value[key] = result2.value;
4473
4485
  }
4474
4486
  }
4475
4487
  function normalizeDef(def) {
@@ -4685,9 +4697,9 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
4685
4697
  };
4686
4698
  });
4687
4699
  function handleUnionResults(results, final, inst, ctx) {
4688
- for (const result of results) {
4689
- if (result.issues.length === 0) {
4690
- final.value = result.value;
4700
+ for (const result2 of results) {
4701
+ if (result2.issues.length === 0) {
4702
+ final.value = result2.value;
4691
4703
  return final;
4692
4704
  }
4693
4705
  }
@@ -4700,7 +4712,7 @@ function handleUnionResults(results, final, inst, ctx) {
4700
4712
  code: "invalid_union",
4701
4713
  input: final.value,
4702
4714
  inst,
4703
- errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
4715
+ errors: results.map((result2) => result2.issues.map((iss) => finalizeIssue(iss, ctx, config())))
4704
4716
  });
4705
4717
  return final;
4706
4718
  }
@@ -4730,17 +4742,17 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
4730
4742
  let async = false;
4731
4743
  const results = [];
4732
4744
  for (const option of def.options) {
4733
- const result = option._zod.run({
4745
+ const result2 = option._zod.run({
4734
4746
  value: payload.value,
4735
4747
  issues: []
4736
4748
  }, ctx);
4737
- if (result instanceof Promise) {
4738
- results.push(result);
4749
+ if (result2 instanceof Promise) {
4750
+ results.push(result2);
4739
4751
  async = true;
4740
4752
  } else {
4741
- if (result.issues.length === 0)
4742
- return result;
4743
- results.push(result);
4753
+ if (result2.issues.length === 0)
4754
+ return result2;
4755
+ results.push(result2);
4744
4756
  }
4745
4757
  }
4746
4758
  if (!async)
@@ -4761,7 +4773,7 @@ function handleExclusiveUnionResults(results, final, inst, ctx) {
4761
4773
  code: "invalid_union",
4762
4774
  input: final.value,
4763
4775
  inst,
4764
- errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
4776
+ errors: results.map((result2) => result2.issues.map((iss) => finalizeIssue(iss, ctx, config())))
4765
4777
  });
4766
4778
  } else {
4767
4779
  final.issues.push({
@@ -4786,15 +4798,15 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
4786
4798
  let async = false;
4787
4799
  const results = [];
4788
4800
  for (const option of def.options) {
4789
- const result = option._zod.run({
4801
+ const result2 = option._zod.run({
4790
4802
  value: payload.value,
4791
4803
  issues: []
4792
4804
  }, ctx);
4793
- if (result instanceof Promise) {
4794
- results.push(result);
4805
+ if (result2 instanceof Promise) {
4806
+ results.push(result2);
4795
4807
  async = true;
4796
4808
  } else {
4797
- results.push(result);
4809
+ results.push(result2);
4798
4810
  }
4799
4811
  }
4800
4812
  if (!async)
@@ -4929,7 +4941,7 @@ function mergeValues(a, b) {
4929
4941
  }
4930
4942
  return { valid: false, mergeErrorPath: [] };
4931
4943
  }
4932
- function handleIntersectionResults(result, left, right) {
4944
+ function handleIntersectionResults(result2, left, right) {
4933
4945
  const unrecKeys = /* @__PURE__ */ new Map();
4934
4946
  let unrecIssue;
4935
4947
  for (const iss of left.issues) {
@@ -4941,7 +4953,7 @@ function handleIntersectionResults(result, left, right) {
4941
4953
  unrecKeys.get(k).l = true;
4942
4954
  }
4943
4955
  } else {
4944
- result.issues.push(iss);
4956
+ result2.issues.push(iss);
4945
4957
  }
4946
4958
  }
4947
4959
  for (const iss of right.issues) {
@@ -4952,21 +4964,21 @@ function handleIntersectionResults(result, left, right) {
4952
4964
  unrecKeys.get(k).r = true;
4953
4965
  }
4954
4966
  } else {
4955
- result.issues.push(iss);
4967
+ result2.issues.push(iss);
4956
4968
  }
4957
4969
  }
4958
4970
  const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
4959
4971
  if (bothKeys.length && unrecIssue) {
4960
- result.issues.push({ ...unrecIssue, keys: bothKeys });
4972
+ result2.issues.push({ ...unrecIssue, keys: bothKeys });
4961
4973
  }
4962
- if (aborted(result))
4963
- return result;
4974
+ if (aborted(result2))
4975
+ return result2;
4964
4976
  const merged = mergeValues(left.value, right.value);
4965
4977
  if (!merged.valid) {
4966
4978
  throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
4967
4979
  }
4968
- result.value = merged.data;
4969
- return result;
4980
+ result2.value = merged.data;
4981
+ return result2;
4970
4982
  }
4971
4983
  var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
4972
4984
  $ZodType.init(inst, def);
@@ -5006,28 +5018,28 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
5006
5018
  if (i >= optStart)
5007
5019
  continue;
5008
5020
  }
5009
- const result = item._zod.run({
5021
+ const result2 = item._zod.run({
5010
5022
  value: input[i],
5011
5023
  issues: []
5012
5024
  }, ctx);
5013
- if (result instanceof Promise) {
5014
- proms.push(result.then((result2) => handleTupleResult(result2, payload, i)));
5025
+ if (result2 instanceof Promise) {
5026
+ proms.push(result2.then((result3) => handleTupleResult(result3, payload, i)));
5015
5027
  } else {
5016
- handleTupleResult(result, payload, i);
5028
+ handleTupleResult(result2, payload, i);
5017
5029
  }
5018
5030
  }
5019
5031
  if (def.rest) {
5020
5032
  const rest = input.slice(items.length);
5021
5033
  for (const el of rest) {
5022
5034
  i++;
5023
- const result = def.rest._zod.run({
5035
+ const result2 = def.rest._zod.run({
5024
5036
  value: el,
5025
5037
  issues: []
5026
5038
  }, ctx);
5027
- if (result instanceof Promise) {
5028
- proms.push(result.then((result2) => handleTupleResult(result2, payload, i)));
5039
+ if (result2 instanceof Promise) {
5040
+ proms.push(result2.then((result3) => handleTupleResult(result3, payload, i)));
5029
5041
  } else {
5030
- handleTupleResult(result, payload, i);
5042
+ handleTupleResult(result2, payload, i);
5031
5043
  }
5032
5044
  }
5033
5045
  }
@@ -5036,11 +5048,11 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
5036
5048
  return payload;
5037
5049
  };
5038
5050
  });
5039
- function handleTupleResult(result, final, index) {
5040
- if (result.issues.length) {
5041
- final.issues.push(...prefixIssues(index, result.issues));
5051
+ function handleTupleResult(result2, final, index) {
5052
+ if (result2.issues.length) {
5053
+ final.issues.push(...prefixIssues(index, result2.issues));
5042
5054
  }
5043
- final.value[index] = result.value;
5055
+ final.value[index] = result2.value;
5044
5056
  }
5045
5057
  var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
5046
5058
  $ZodType.init(inst, def);
@@ -5063,19 +5075,19 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
5063
5075
  for (const key of values) {
5064
5076
  if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
5065
5077
  recordKeys.add(typeof key === "number" ? key.toString() : key);
5066
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
5067
- if (result instanceof Promise) {
5068
- proms.push(result.then((result2) => {
5069
- if (result2.issues.length) {
5070
- payload.issues.push(...prefixIssues(key, result2.issues));
5078
+ const result2 = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
5079
+ if (result2 instanceof Promise) {
5080
+ proms.push(result2.then((result3) => {
5081
+ if (result3.issues.length) {
5082
+ payload.issues.push(...prefixIssues(key, result3.issues));
5071
5083
  }
5072
- payload.value[key] = result2.value;
5084
+ payload.value[key] = result3.value;
5073
5085
  }));
5074
5086
  } else {
5075
- if (result.issues.length) {
5076
- payload.issues.push(...prefixIssues(key, result.issues));
5087
+ if (result2.issues.length) {
5088
+ payload.issues.push(...prefixIssues(key, result2.issues));
5077
5089
  }
5078
- payload.value[key] = result.value;
5090
+ payload.value[key] = result2.value;
5079
5091
  }
5080
5092
  }
5081
5093
  }
@@ -5128,19 +5140,19 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
5128
5140
  }
5129
5141
  continue;
5130
5142
  }
5131
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
5132
- if (result instanceof Promise) {
5133
- proms.push(result.then((result2) => {
5134
- if (result2.issues.length) {
5135
- payload.issues.push(...prefixIssues(key, result2.issues));
5143
+ const result2 = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
5144
+ if (result2 instanceof Promise) {
5145
+ proms.push(result2.then((result3) => {
5146
+ if (result3.issues.length) {
5147
+ payload.issues.push(...prefixIssues(key, result3.issues));
5136
5148
  }
5137
- payload.value[keyResult.value] = result2.value;
5149
+ payload.value[keyResult.value] = result3.value;
5138
5150
  }));
5139
5151
  } else {
5140
- if (result.issues.length) {
5141
- payload.issues.push(...prefixIssues(key, result.issues));
5152
+ if (result2.issues.length) {
5153
+ payload.issues.push(...prefixIssues(key, result2.issues));
5142
5154
  }
5143
- payload.value[keyResult.value] = result.value;
5155
+ payload.value[keyResult.value] = result2.value;
5144
5156
  }
5145
5157
  }
5146
5158
  }
@@ -5227,22 +5239,22 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
5227
5239
  const proms = [];
5228
5240
  payload.value = /* @__PURE__ */ new Set();
5229
5241
  for (const item of input) {
5230
- const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
5231
- if (result instanceof Promise) {
5232
- proms.push(result.then((result2) => handleSetResult(result2, payload)));
5242
+ const result2 = def.valueType._zod.run({ value: item, issues: [] }, ctx);
5243
+ if (result2 instanceof Promise) {
5244
+ proms.push(result2.then((result3) => handleSetResult(result3, payload)));
5233
5245
  } else
5234
- handleSetResult(result, payload);
5246
+ handleSetResult(result2, payload);
5235
5247
  }
5236
5248
  if (proms.length)
5237
5249
  return Promise.all(proms).then(() => payload);
5238
5250
  return payload;
5239
5251
  };
5240
5252
  });
5241
- function handleSetResult(result, final) {
5242
- if (result.issues.length) {
5243
- final.issues.push(...result.issues);
5253
+ function handleSetResult(result2, final) {
5254
+ if (result2.issues.length) {
5255
+ final.issues.push(...result2.issues);
5244
5256
  }
5245
- final.value.add(result.value);
5257
+ final.value.add(result2.value);
5246
5258
  }
5247
5259
  var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
5248
5260
  $ZodType.init(inst, def);
@@ -5322,11 +5334,11 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) =>
5322
5334
  return payload;
5323
5335
  };
5324
5336
  });
5325
- function handleOptionalResult(result, input) {
5326
- if (result.issues.length && input === void 0) {
5337
+ function handleOptionalResult(result2, input) {
5338
+ if (result2.issues.length && input === void 0) {
5327
5339
  return { issues: [], value: void 0 };
5328
5340
  }
5329
- return result;
5341
+ return result2;
5330
5342
  }
5331
5343
  var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
5332
5344
  $ZodType.init(inst, def);
@@ -5341,10 +5353,10 @@ var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
5341
5353
  });
5342
5354
  inst._zod.parse = (payload, ctx) => {
5343
5355
  if (def.innerType._zod.optin === "optional") {
5344
- const result = def.innerType._zod.run(payload, ctx);
5345
- if (result instanceof Promise)
5346
- return result.then((r) => handleOptionalResult(r, payload.value));
5347
- return handleOptionalResult(result, payload.value);
5356
+ const result2 = def.innerType._zod.run(payload, ctx);
5357
+ if (result2 instanceof Promise)
5358
+ return result2.then((r) => handleOptionalResult(r, payload.value));
5359
+ return handleOptionalResult(result2, payload.value);
5348
5360
  }
5349
5361
  if (payload.value === void 0) {
5350
5362
  return payload;
@@ -5389,11 +5401,11 @@ var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
5389
5401
  payload.value = def.defaultValue;
5390
5402
  return payload;
5391
5403
  }
5392
- const result = def.innerType._zod.run(payload, ctx);
5393
- if (result instanceof Promise) {
5394
- return result.then((result2) => handleDefaultResult(result2, def));
5404
+ const result2 = def.innerType._zod.run(payload, ctx);
5405
+ if (result2 instanceof Promise) {
5406
+ return result2.then((result3) => handleDefaultResult(result3, def));
5395
5407
  }
5396
- return handleDefaultResult(result, def);
5408
+ return handleDefaultResult(result2, def);
5397
5409
  };
5398
5410
  });
5399
5411
  function handleDefaultResult(payload, def) {
@@ -5423,11 +5435,11 @@ var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def
5423
5435
  return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
5424
5436
  });
5425
5437
  inst._zod.parse = (payload, ctx) => {
5426
- const result = def.innerType._zod.run(payload, ctx);
5427
- if (result instanceof Promise) {
5428
- return result.then((result2) => handleNonOptionalResult(result2, inst));
5438
+ const result2 = def.innerType._zod.run(payload, ctx);
5439
+ if (result2 instanceof Promise) {
5440
+ return result2.then((result3) => handleNonOptionalResult(result3, inst));
5429
5441
  }
5430
- return handleNonOptionalResult(result, inst);
5442
+ return handleNonOptionalResult(result2, inst);
5431
5443
  };
5432
5444
  });
5433
5445
  function handleNonOptionalResult(payload, inst) {
@@ -5447,14 +5459,14 @@ var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
5447
5459
  if (ctx.direction === "backward") {
5448
5460
  throw new $ZodEncodeError("ZodSuccess");
5449
5461
  }
5450
- const result = def.innerType._zod.run(payload, ctx);
5451
- if (result instanceof Promise) {
5452
- return result.then((result2) => {
5453
- payload.value = result2.issues.length === 0;
5462
+ const result2 = def.innerType._zod.run(payload, ctx);
5463
+ if (result2 instanceof Promise) {
5464
+ return result2.then((result3) => {
5465
+ payload.value = result3.issues.length === 0;
5454
5466
  return payload;
5455
5467
  });
5456
5468
  }
5457
- payload.value = result.issues.length === 0;
5469
+ payload.value = result2.issues.length === 0;
5458
5470
  return payload;
5459
5471
  };
5460
5472
  });
@@ -5467,15 +5479,15 @@ var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
5467
5479
  if (ctx.direction === "backward") {
5468
5480
  return def.innerType._zod.run(payload, ctx);
5469
5481
  }
5470
- const result = def.innerType._zod.run(payload, ctx);
5471
- if (result instanceof Promise) {
5472
- return result.then((result2) => {
5473
- payload.value = result2.value;
5474
- if (result2.issues.length) {
5482
+ const result2 = def.innerType._zod.run(payload, ctx);
5483
+ if (result2 instanceof Promise) {
5484
+ return result2.then((result3) => {
5485
+ payload.value = result3.value;
5486
+ if (result3.issues.length) {
5475
5487
  payload.value = def.catchValue({
5476
5488
  ...payload,
5477
5489
  error: {
5478
- issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
5490
+ issues: result3.issues.map((iss) => finalizeIssue(iss, ctx, config()))
5479
5491
  },
5480
5492
  input: payload.value
5481
5493
  });
@@ -5484,12 +5496,12 @@ var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
5484
5496
  return payload;
5485
5497
  });
5486
5498
  }
5487
- payload.value = result.value;
5488
- if (result.issues.length) {
5499
+ payload.value = result2.value;
5500
+ if (result2.issues.length) {
5489
5501
  payload.value = def.catchValue({
5490
5502
  ...payload,
5491
5503
  error: {
5492
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
5504
+ issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
5493
5505
  },
5494
5506
  input: payload.value
5495
5507
  });
@@ -5564,24 +5576,24 @@ var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => {
5564
5576
  }
5565
5577
  };
5566
5578
  });
5567
- function handleCodecAResult(result, def, ctx) {
5568
- if (result.issues.length) {
5569
- result.aborted = true;
5570
- return result;
5579
+ function handleCodecAResult(result2, def, ctx) {
5580
+ if (result2.issues.length) {
5581
+ result2.aborted = true;
5582
+ return result2;
5571
5583
  }
5572
5584
  const direction = ctx.direction || "forward";
5573
5585
  if (direction === "forward") {
5574
- const transformed = def.transform(result.value, result);
5586
+ const transformed = def.transform(result2.value, result2);
5575
5587
  if (transformed instanceof Promise) {
5576
- return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));
5588
+ return transformed.then((value) => handleCodecTxResult(result2, value, def.out, ctx));
5577
5589
  }
5578
- return handleCodecTxResult(result, transformed, def.out, ctx);
5590
+ return handleCodecTxResult(result2, transformed, def.out, ctx);
5579
5591
  } else {
5580
- const transformed = def.reverseTransform(result.value, result);
5592
+ const transformed = def.reverseTransform(result2.value, result2);
5581
5593
  if (transformed instanceof Promise) {
5582
- return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));
5594
+ return transformed.then((value) => handleCodecTxResult(result2, value, def.in, ctx));
5583
5595
  }
5584
- return handleCodecTxResult(result, transformed, def.in, ctx);
5596
+ return handleCodecTxResult(result2, transformed, def.in, ctx);
5585
5597
  }
5586
5598
  }
5587
5599
  function handleCodecTxResult(left, value, nextSchema, ctx) {
@@ -5601,11 +5613,11 @@ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
5601
5613
  if (ctx.direction === "backward") {
5602
5614
  return def.innerType._zod.run(payload, ctx);
5603
5615
  }
5604
- const result = def.innerType._zod.run(payload, ctx);
5605
- if (result instanceof Promise) {
5606
- return result.then(handleReadonlyResult);
5616
+ const result2 = def.innerType._zod.run(payload, ctx);
5617
+ if (result2 instanceof Promise) {
5618
+ return result2.then(handleReadonlyResult);
5607
5619
  }
5608
- return handleReadonlyResult(result);
5620
+ return handleReadonlyResult(result2);
5609
5621
  };
5610
5622
  });
5611
5623
  function handleReadonlyResult(payload) {
@@ -5667,11 +5679,11 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
5667
5679
  }
5668
5680
  return function(...args) {
5669
5681
  const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;
5670
- const result = Reflect.apply(func, this, parsedArgs);
5682
+ const result2 = Reflect.apply(func, this, parsedArgs);
5671
5683
  if (inst._def.output) {
5672
- return parse(inst._def.output, result);
5684
+ return parse(inst._def.output, result2);
5673
5685
  }
5674
- return result;
5686
+ return result2;
5675
5687
  };
5676
5688
  };
5677
5689
  inst.implementAsync = (func) => {
@@ -5680,11 +5692,11 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
5680
5692
  }
5681
5693
  return async function(...args) {
5682
5694
  const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;
5683
- const result = await Reflect.apply(func, this, parsedArgs);
5695
+ const result2 = await Reflect.apply(func, this, parsedArgs);
5684
5696
  if (inst._def.output) {
5685
- return await parseAsync(inst._def.output, result);
5697
+ return await parseAsync(inst._def.output, result2);
5686
5698
  }
5687
- return result;
5699
+ return result2;
5688
5700
  };
5689
5701
  };
5690
5702
  inst._zod.parse = (payload, _ctx) => {
@@ -5768,8 +5780,8 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
5768
5780
  return;
5769
5781
  };
5770
5782
  });
5771
- function handleRefineResult(result, payload, input, inst) {
5772
- if (!result) {
5783
+ function handleRefineResult(result2, payload, input, inst) {
5784
+ if (!result2) {
5773
5785
  const _iss = {
5774
5786
  code: "custom",
5775
5787
  input,
@@ -8887,12 +8899,12 @@ var error26 = () => {
8887
8899
  }
8888
8900
  };
8889
8901
  function getSizing(origin, unitType, inclusive, targetShouldBe) {
8890
- const result = Sizable[origin] ?? null;
8891
- if (result === null)
8892
- return result;
8902
+ const result2 = Sizable[origin] ?? null;
8903
+ if (result2 === null)
8904
+ return result2;
8893
8905
  return {
8894
- unit: result.unit[unitType],
8895
- verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"]
8906
+ unit: result2.unit[unitType],
8907
+ verb: result2.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"]
8896
8908
  };
8897
8909
  }
8898
8910
  const FormatDictionary = {
@@ -12486,11 +12498,11 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
12486
12498
  }
12487
12499
  return seen.schema;
12488
12500
  }
12489
- const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };
12490
- ctx.seen.set(schema, result);
12501
+ const result2 = { schema: {}, count: 1, cycle: void 0, path: _params.path };
12502
+ ctx.seen.set(schema, result2);
12491
12503
  const overrideSchema = schema._zod.toJSONSchema?.();
12492
12504
  if (overrideSchema) {
12493
- result.schema = overrideSchema;
12505
+ result2.schema = overrideSchema;
12494
12506
  } else {
12495
12507
  const params = {
12496
12508
  ..._params,
@@ -12498,9 +12510,9 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
12498
12510
  path: _params.path
12499
12511
  };
12500
12512
  if (schema._zod.processJSONSchema) {
12501
- schema._zod.processJSONSchema(ctx, result.schema, params);
12513
+ schema._zod.processJSONSchema(ctx, result2.schema, params);
12502
12514
  } else {
12503
- const _json = result.schema;
12515
+ const _json = result2.schema;
12504
12516
  const processor = ctx.processors[def.type];
12505
12517
  if (!processor) {
12506
12518
  throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
@@ -12509,22 +12521,22 @@ function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
12509
12521
  }
12510
12522
  const parent = schema._zod.parent;
12511
12523
  if (parent) {
12512
- if (!result.ref)
12513
- result.ref = parent;
12524
+ if (!result2.ref)
12525
+ result2.ref = parent;
12514
12526
  process2(parent, ctx, params);
12515
12527
  ctx.seen.get(parent).isParent = true;
12516
12528
  }
12517
12529
  }
12518
12530
  const meta3 = ctx.metadataRegistry.get(schema);
12519
12531
  if (meta3)
12520
- Object.assign(result.schema, meta3);
12532
+ Object.assign(result2.schema, meta3);
12521
12533
  if (ctx.io === "input" && isTransforming(schema)) {
12522
- delete result.schema.examples;
12523
- delete result.schema.default;
12534
+ delete result2.schema.examples;
12535
+ delete result2.schema.default;
12524
12536
  }
12525
- if (ctx.io === "input" && result.schema._prefault)
12526
- (_a2 = result.schema).default ?? (_a2.default = result.schema._prefault);
12527
- delete result.schema._prefault;
12537
+ if (ctx.io === "input" && result2.schema._prefault)
12538
+ (_a2 = result2.schema).default ?? (_a2.default = result2.schema._prefault);
12539
+ delete result2.schema._prefault;
12528
12540
  const _result = ctx.seen.get(schema);
12529
12541
  return _result.schema;
12530
12542
  }
@@ -12687,13 +12699,13 @@ function finalize(ctx, schema) {
12687
12699
  for (const entry of [...ctx.seen.entries()].reverse()) {
12688
12700
  flattenRef(entry[0]);
12689
12701
  }
12690
- const result = {};
12702
+ const result2 = {};
12691
12703
  if (ctx.target === "draft-2020-12") {
12692
- result.$schema = "https://json-schema.org/draft/2020-12/schema";
12704
+ result2.$schema = "https://json-schema.org/draft/2020-12/schema";
12693
12705
  } else if (ctx.target === "draft-07") {
12694
- result.$schema = "http://json-schema.org/draft-07/schema#";
12706
+ result2.$schema = "http://json-schema.org/draft-07/schema#";
12695
12707
  } else if (ctx.target === "draft-04") {
12696
- result.$schema = "http://json-schema.org/draft-04/schema#";
12708
+ result2.$schema = "http://json-schema.org/draft-04/schema#";
12697
12709
  } else if (ctx.target === "openapi-3.0") {
12698
12710
  } else {
12699
12711
  }
@@ -12701,9 +12713,9 @@ function finalize(ctx, schema) {
12701
12713
  const id = ctx.external.registry.get(schema)?.id;
12702
12714
  if (!id)
12703
12715
  throw new Error("Schema is missing an `id` property");
12704
- result.$id = ctx.external.uri(id);
12716
+ result2.$id = ctx.external.uri(id);
12705
12717
  }
12706
- Object.assign(result, root.def ?? root.schema);
12718
+ Object.assign(result2, root.def ?? root.schema);
12707
12719
  const defs = ctx.external?.defs ?? {};
12708
12720
  for (const entry of ctx.seen.entries()) {
12709
12721
  const seen = entry[1];
@@ -12715,14 +12727,14 @@ function finalize(ctx, schema) {
12715
12727
  } else {
12716
12728
  if (Object.keys(defs).length > 0) {
12717
12729
  if (ctx.target === "draft-2020-12") {
12718
- result.$defs = defs;
12730
+ result2.$defs = defs;
12719
12731
  } else {
12720
- result.definitions = defs;
12732
+ result2.definitions = defs;
12721
12733
  }
12722
12734
  }
12723
12735
  }
12724
12736
  try {
12725
- const finalized = JSON.parse(JSON.stringify(result));
12737
+ const finalized = JSON.parse(JSON.stringify(result2));
12726
12738
  Object.defineProperty(finalized, "~standard", {
12727
12739
  value: {
12728
12740
  ...schema["~standard"],
@@ -13424,8 +13436,8 @@ var JSONSchemaGenerator = class {
13424
13436
  this.ctx.external = _params.external;
13425
13437
  }
13426
13438
  extractDefs(this.ctx, schema);
13427
- const result = finalize(this.ctx, schema);
13428
- const { "~standard": _, ...plainResult } = result;
13439
+ const result2 = finalize(this.ctx, schema);
13440
+ const { "~standard": _, ...plainResult } = result2;
13429
13441
  return plainResult;
13430
13442
  }
13431
13443
  };
@@ -14930,13 +14942,13 @@ function resolveRef(ref, ctx) {
14930
14942
  if (!ref.startsWith("#")) {
14931
14943
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14932
14944
  }
14933
- const path7 = ref.slice(1).split("/").filter(Boolean);
14934
- if (path7.length === 0) {
14945
+ const path8 = ref.slice(1).split("/").filter(Boolean);
14946
+ if (path8.length === 0) {
14935
14947
  return ctx.rootSchema;
14936
14948
  }
14937
14949
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14938
- if (path7[0] === defsKey) {
14939
- const key = path7[1];
14950
+ if (path8[0] === defsKey) {
14951
+ const key = path8[1];
14940
14952
  if (!key || !ctx.defs[key]) {
14941
14953
  throw new Error(`Reference not found: ${ref}`);
14942
14954
  }
@@ -15161,11 +15173,11 @@ function convertBaseSchema(schema, ctx) {
15161
15173
  } else if (schemasToIntersect.length === 1) {
15162
15174
  zodSchema = schemasToIntersect[0];
15163
15175
  } else {
15164
- let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
15176
+ let result2 = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
15165
15177
  for (let i = 2; i < schemasToIntersect.length; i++) {
15166
- result = z.intersection(result, schemasToIntersect[i]);
15178
+ result2 = z.intersection(result2, schemasToIntersect[i]);
15167
15179
  }
15168
- zodSchema = result;
15180
+ zodSchema = result2;
15169
15181
  }
15170
15182
  break;
15171
15183
  }
@@ -15256,12 +15268,12 @@ function convertSchema(schema, ctx) {
15256
15268
  if (schema.allOf.length === 0) {
15257
15269
  baseSchema = hasExplicitType ? baseSchema : z.any();
15258
15270
  } else {
15259
- let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
15271
+ let result2 = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
15260
15272
  const startIdx = hasExplicitType ? 0 : 1;
15261
15273
  for (let i = startIdx; i < schema.allOf.length; i++) {
15262
- result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
15274
+ result2 = z.intersection(result2, convertSchema(schema.allOf[i], ctx));
15263
15275
  }
15264
- baseSchema = result;
15276
+ baseSchema = result2;
15265
15277
  }
15266
15278
  }
15267
15279
  if (schema.nullable === true && ctx.version === "openapi-3.0") {
@@ -15815,6 +15827,14 @@ var DISPLAY_PLAN_CONFIG = {
15815
15827
  // src/agentCommsCore/bridge.ts
15816
15828
  var AGENT_COMMS_PROTOCOL_VERSION = "agent-comms-core.v1";
15817
15829
  var AGENT_PROOF_SCHEMA_VERSION = "agent-proof.v1";
15830
+ var AgentCommsBridgeLockError = class extends Error {
15831
+ constructor(lockPath, owner) {
15832
+ super("slock agent bridge is already running for this profile/agent/adapter state.");
15833
+ this.lockPath = lockPath;
15834
+ this.owner = owner;
15835
+ }
15836
+ code = "BRIDGE_ALREADY_RUNNING";
15837
+ };
15818
15838
  function resolveAgentCommsBridgeStateDir(input) {
15819
15839
  if (input.stateDir) return input.stateDir;
15820
15840
  const env = input.env ?? process.env;
@@ -15834,7 +15854,9 @@ function createFileAgentCommsBridgeStore(input) {
15834
15854
  rootDir,
15835
15855
  sessionFile: path4.join(rootDir, "session.json"),
15836
15856
  wakeHintsFile: path4.join(rootDir, "wake-hints.jsonl"),
15837
- proofFile: path4.join(rootDir, "proofs.jsonl")
15857
+ proofFile: path4.join(rootDir, "proofs.jsonl"),
15858
+ lockFile: path4.join(rootDir, "bridge.lock"),
15859
+ logFile: path4.join(rootDir, "bridge.log")
15838
15860
  };
15839
15861
  fs2.mkdirSync(rootDir, { recursive: true, mode: 448 });
15840
15862
  return {
@@ -15867,9 +15889,40 @@ function createFileAgentCommsBridgeStore(input) {
15867
15889
  },
15868
15890
  appendProof(proof2) {
15869
15891
  appendJsonl(paths.proofFile, proof2);
15892
+ },
15893
+ appendLog(event) {
15894
+ try {
15895
+ rotateBridgeLogIfNeeded(paths.logFile);
15896
+ appendJsonl(paths.logFile, { ts: (/* @__PURE__ */ new Date()).toISOString(), ...event });
15897
+ } catch {
15898
+ }
15899
+ },
15900
+ removeWakeHint(hint) {
15901
+ const key = wakeHintKey(hint);
15902
+ const pending = readJsonl(paths.wakeHintsFile);
15903
+ const remaining = pending.filter((candidate) => wakeHintKey(candidate) !== key);
15904
+ if (remaining.length === pending.length) return;
15905
+ fs2.writeFileSync(
15906
+ paths.wakeHintsFile,
15907
+ remaining.map((entry) => JSON.stringify(entry)).join("\n") + (remaining.length > 0 ? "\n" : ""),
15908
+ { mode: 384 }
15909
+ );
15870
15910
  }
15871
15911
  };
15872
15912
  }
15913
+ function acquireAgentCommsBridgeLock(input) {
15914
+ const store = createFileAgentCommsBridgeStore(input);
15915
+ const ownerId = input.ownerId ?? `owner_${randomUUID()}`;
15916
+ const owner = {
15917
+ ownerId,
15918
+ pid: process.pid,
15919
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
15920
+ profileSlug: requireProfileSlug(input.agentContext),
15921
+ agentId: input.agentContext.agentId,
15922
+ adapterInstance: input.adapterInstance ?? "default"
15923
+ };
15924
+ return acquireLockFile(store.paths.lockFile, ownerId, owner, false);
15925
+ }
15873
15926
  async function runAgentCommsBridgeOnce(input) {
15874
15927
  if (input.agentContext.clientMode !== "self-hosted-runner") {
15875
15928
  throw new Error("slock agent bridge requires a self-hosted profile credential; run with `slock --profile <slug> agent bridge`.");
@@ -15909,7 +15962,8 @@ async function runAgentCommsBridgeOnce(input) {
15909
15962
  runtimeSession: input.runtimeSession ?? null,
15910
15963
  now,
15911
15964
  output,
15912
- store
15965
+ store,
15966
+ recentInjections: input.recentInjections
15913
15967
  });
15914
15968
  }
15915
15969
  }
@@ -15917,7 +15971,12 @@ async function runAgentCommsBridgeOnce(input) {
15917
15971
  const since = existingSession?.lastSeenHintSeq ?? "latest";
15918
15972
  const fetched = await input.source.fetchWakeHints({ since, limit: input.limit ?? 50 });
15919
15973
  let lastSeenHintSeq = existingSession?.lastSeenHintSeq;
15974
+ let processedHintCount = 0;
15920
15975
  for (const hint of fetched.hints) {
15976
+ const seq = wakeHintSeq(hint);
15977
+ if (typeof seq === "number" && typeof lastSeenHintSeq === "number" && seq <= lastSeenHintSeq) {
15978
+ continue;
15979
+ }
15921
15980
  const attemptId = `attempt_${randomUUID()}`;
15922
15981
  const serverDelivered = proof(identity, hint, attemptId, "server_delivered", now);
15923
15982
  store.appendProof(serverDelivered);
@@ -15935,10 +15994,11 @@ async function runAgentCommsBridgeOnce(input) {
15935
15994
  runtimeSession: input.runtimeSession ?? null,
15936
15995
  now,
15937
15996
  output,
15938
- store
15997
+ store,
15998
+ recentInjections: input.recentInjections
15939
15999
  });
15940
- const seq = wakeHintSeq(hint);
15941
16000
  if (typeof seq === "number") lastSeenHintSeq = Math.max(lastSeenHintSeq ?? 0, seq);
16001
+ processedHintCount += 1;
15942
16002
  }
15943
16003
  const fetchedLastSeq = typeof fetched.last_seen_hint_seq === "number" ? fetched.last_seen_hint_seq : typeof fetched.last_hint_seq === "number" ? fetched.last_hint_seq : void 0;
15944
16004
  if (typeof fetchedLastSeq === "number") lastSeenHintSeq = Math.max(lastSeenHintSeq ?? 0, fetchedLastSeq);
@@ -15946,9 +16006,76 @@ async function runAgentCommsBridgeOnce(input) {
15946
16006
  coreSessionId,
15947
16007
  ...typeof lastSeenHintSeq === "number" ? { lastSeenHintSeq } : {}
15948
16008
  });
15949
- output.push(lifecycle(identity, fetched.hints.length > 0 ? "handoff_pending" : "listening_idle", now));
16009
+ output.push(lifecycle(identity, processedHintCount > 0 ? "handoff_pending" : "listening_idle", now));
15950
16010
  return output;
15951
16011
  }
16012
+ var BRIDGE_LOG_MAX_BYTES = 5 * 1024 * 1024;
16013
+ function rotateBridgeLogIfNeeded(logFile) {
16014
+ try {
16015
+ const stat2 = fs2.statSync(logFile);
16016
+ if (stat2.size < BRIDGE_LOG_MAX_BYTES) return;
16017
+ fs2.renameSync(logFile, `${logFile}.1`);
16018
+ } catch {
16019
+ }
16020
+ }
16021
+ async function runAgentCommsBridgeReconcile(input) {
16022
+ const profileSlug = requireProfileSlug(input.agentContext);
16023
+ const adapterInstance = input.adapterInstance ?? "default";
16024
+ const store = createFileAgentCommsBridgeStore({
16025
+ agentContext: input.agentContext,
16026
+ env: input.env,
16027
+ stateDir: input.stateDir,
16028
+ adapterInstance
16029
+ });
16030
+ const existingSession = store.readSession();
16031
+ const sessionBefore = existingSession ? { ...existingSession } : null;
16032
+ const identity = {
16033
+ agentId: input.agentContext.agentId,
16034
+ profileSlug,
16035
+ adapterInstance,
16036
+ coreSessionId: input.coreSessionId ?? existingSession?.coreSessionId ?? `core_${randomUUID()}`
16037
+ };
16038
+ const now = input.now ?? (() => /* @__PURE__ */ new Date());
16039
+ const events = [];
16040
+ const graceMs = input.graceMs ?? 3e4;
16041
+ const recent = input.recentInjections;
16042
+ const fetched = await input.source.fetchWakeHints({ since: 0, limit: input.limit ?? 50 });
16043
+ let reinjected = 0;
16044
+ let skippedRecent = 0;
16045
+ for (const hint of fetched.hints) {
16046
+ const key = wakeHintKey(hint);
16047
+ const injectedAt = recent?.get(key);
16048
+ if (typeof injectedAt === "number" && now().getTime() - injectedAt < graceMs) {
16049
+ skippedRecent += 1;
16050
+ continue;
16051
+ }
16052
+ const attemptId = `attempt_${randomUUID()}`;
16053
+ store.appendWakeHintIfAbsent(hint);
16054
+ events.push(handoff(identity, hint, attemptId, true, now));
16055
+ await maybeRunWakeAdapter({
16056
+ identity,
16057
+ hint,
16058
+ attemptId,
16059
+ wakeAdapter: input.wakeAdapter,
16060
+ runtimeSession: input.runtimeSession ?? null,
16061
+ now,
16062
+ output: events,
16063
+ store,
16064
+ recentInjections: recent
16065
+ });
16066
+ reinjected += 1;
16067
+ }
16068
+ const sessionAfter = store.readSession();
16069
+ if (JSON.stringify(sessionAfter) !== JSON.stringify(sessionBefore)) {
16070
+ throw new Error("bridge reconcile must not modify session state (cursor-orthogonality)");
16071
+ }
16072
+ return {
16073
+ pendingCount: fetched.hints.length,
16074
+ reinjectedCount: reinjected,
16075
+ skippedRecentCount: skippedRecent,
16076
+ events
16077
+ };
16078
+ }
15952
16079
  async function maybeRunWakeAdapter(input) {
15953
16080
  if (!input.wakeAdapter) return;
15954
16081
  const wakeInput = wakeAttemptInput({
@@ -15961,6 +16088,18 @@ async function maybeRunWakeAdapter(input) {
15961
16088
  const event = await wakeAdapterEvent(input.wakeAdapter, wakeInput);
15962
16089
  input.store.appendProof(event);
15963
16090
  input.output.push(event);
16091
+ if (event.proofLevel === "wake_injected") {
16092
+ input.store.removeWakeHint(input.hint);
16093
+ if (input.recentInjections) {
16094
+ input.recentInjections.set(wakeHintKey(input.hint), input.now().getTime());
16095
+ if (input.recentInjections.size > 1e3) {
16096
+ const cutoff = input.now().getTime() - 6e5;
16097
+ for (const [key, ts] of input.recentInjections) {
16098
+ if (ts < cutoff) input.recentInjections.delete(key);
16099
+ }
16100
+ }
16101
+ }
16102
+ }
15964
16103
  }
15965
16104
  function wakeAttemptInput(input) {
15966
16105
  return {
@@ -16099,6 +16238,58 @@ function appendJsonl(filePath, value) {
16099
16238
  fs2.appendFileSync(filePath, `${JSON.stringify(value)}
16100
16239
  `, { mode: 384 });
16101
16240
  }
16241
+ function acquireLockFile(lockPath, ownerId, owner, retried) {
16242
+ fs2.mkdirSync(path4.dirname(lockPath), { recursive: true, mode: 448 });
16243
+ try {
16244
+ const fd = fs2.openSync(lockPath, "wx", 384);
16245
+ fs2.writeFileSync(fd, `${JSON.stringify(owner, null, 2)}
16246
+ `);
16247
+ fs2.closeSync(fd);
16248
+ } catch (err) {
16249
+ if (err.code !== "EEXIST") throw err;
16250
+ const existing = readLockOwner(lockPath);
16251
+ if (!retried && isStaleLockOwner(existing)) {
16252
+ try {
16253
+ fs2.unlinkSync(lockPath);
16254
+ } catch {
16255
+ }
16256
+ return acquireLockFile(lockPath, ownerId, owner, true);
16257
+ }
16258
+ throw new AgentCommsBridgeLockError(lockPath, existing);
16259
+ }
16260
+ let released = false;
16261
+ return {
16262
+ path: lockPath,
16263
+ ownerId,
16264
+ release() {
16265
+ if (released) return;
16266
+ released = true;
16267
+ const existing = readLockOwner(lockPath);
16268
+ if (existing?.ownerId === ownerId) {
16269
+ fs2.unlinkSync(lockPath);
16270
+ }
16271
+ }
16272
+ };
16273
+ }
16274
+ function readLockOwner(lockPath) {
16275
+ try {
16276
+ return JSON.parse(fs2.readFileSync(lockPath, "utf-8"));
16277
+ } catch {
16278
+ return null;
16279
+ }
16280
+ }
16281
+ function isStaleLockOwner(owner) {
16282
+ if (!owner || typeof owner !== "object") return false;
16283
+ const pid = owner.pid;
16284
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false;
16285
+ try {
16286
+ process.kill(pid, 0);
16287
+ return false;
16288
+ } catch (err) {
16289
+ const code = err.code;
16290
+ return code === "ESRCH";
16291
+ }
16292
+ }
16102
16293
  function requireProfileSlug(agentContext) {
16103
16294
  if (!agentContext.profileSlug) {
16104
16295
  throw new Error("slock agent bridge requires SLOCK_PROFILE / --profile so state is profile-scoped.");
@@ -16300,10 +16491,13 @@ var agentBridgeCommand = defineCommand(
16300
16491
  { flags: "--state-dir <path>", description: "Override bridge state directory for tests/debugging." },
16301
16492
  { flags: "--adapter-instance <id>", description: "Wake adapter instance id for per-agent state partitioning." },
16302
16493
  { flags: "--limit <n>", description: "Maximum events to pull per iteration." },
16303
- { flags: "--wake-adapter <kind>", description: "Enable a wake adapter. Supported: claude-code-channels." },
16304
- { flags: "--claude-channel-endpoint <url>", description: "Localhost wake endpoint exposed by the Slock Claude Code channel plugin." },
16305
- { flags: "--claude-channel-token <token>", description: "Optional shared token for the Claude Code channel plugin wake endpoint." },
16306
- { flags: "--runtime-session <id>", description: "Optional runtime session id when the adapter endpoint does not return one." }
16494
+ { flags: "--wake-adapter <kind>", description: "Enable a wake adapter. Supported: wake-endpoint (runtime-neutral; claude-code-channels is a compatible alias)." },
16495
+ { flags: "--wake-endpoint <url>", description: "Localhost wake endpoint exposed by the runtime's Slock channel plugin (see docs/wake-endpoint-contract.md in raft-external-agents)." },
16496
+ { flags: "--wake-endpoint-token <token>", description: "Optional shared token for the runtime wake endpoint (env: SLOCK_WAKE_ENDPOINT_TOKEN)." },
16497
+ { flags: "--claude-channel-endpoint <url>", description: "Compatible alias of --wake-endpoint (historical Claude Code naming)." },
16498
+ { flags: "--claude-channel-token <token>", description: "Compatible alias of --wake-endpoint-token (historical Claude Code naming)." },
16499
+ { flags: "--runtime-session <id>", description: "Optional runtime session id when the adapter endpoint does not return one." },
16500
+ { flags: "--reconcile-interval-ms <ms>", description: "Re-peek the full server-pending set every <ms> and re-wake hints that were injected but never consumed (0 disables; default 120000)." }
16307
16501
  ]
16308
16502
  },
16309
16503
  async (ctx, options) => {
@@ -16316,33 +16510,147 @@ var agentBridgeCommand = defineCommand(
16316
16510
  });
16317
16511
  }
16318
16512
  const pollIntervalMs = parsePositiveInt(options.pollIntervalMs, 5e3, "poll-interval-ms");
16513
+ const reconcileIntervalMs = options.reconcileIntervalMs === "0" ? 0 : parsePositiveInt(options.reconcileIntervalMs, 12e4, "reconcile-interval-ms");
16319
16514
  const limit = parsePositiveInt(options.limit, 50, "limit");
16320
- const source = createAgentApiWakeHintSource(ctx.createApiClient(agentContext));
16321
- const wakeAdapter = createWakeAdapter(options);
16515
+ const client = ctx.createApiClient(agentContext);
16516
+ const pollSource = createAgentApiWakeHintSource(client);
16517
+ const streamSource = options.once ? null : createAgentApiWakeHintStreamSource(client, ctx.env);
16518
+ const wakeAdapter = createWakeAdapter(options, ctx.env);
16519
+ let bridgeLock;
16520
+ try {
16521
+ bridgeLock = acquireAgentCommsBridgeLock({
16522
+ agentContext,
16523
+ env: ctx.env,
16524
+ stateDir: options.stateDir,
16525
+ adapterInstance: options.adapterInstance
16526
+ });
16527
+ } catch (err) {
16528
+ if (err instanceof AgentCommsBridgeLockError) {
16529
+ throw new CliError({
16530
+ code: err.code,
16531
+ message: "slock agent bridge is already running for this profile/agent/adapter state.",
16532
+ suggestedNextAction: `Stop the existing bridge or use a different --adapter-instance. Lock: ${err.lockPath}`
16533
+ });
16534
+ }
16535
+ throw err;
16536
+ }
16537
+ const logStore = createFileAgentCommsBridgeStore({
16538
+ agentContext,
16539
+ env: ctx.env,
16540
+ stateDir: options.stateDir,
16541
+ adapterInstance: options.adapterInstance
16542
+ });
16322
16543
  const emit = (value) => {
16544
+ logStore.appendLog(value);
16323
16545
  if (options.json) {
16324
16546
  writeText(ctx.io, `${JSON.stringify(value)}
16325
16547
  `);
16326
16548
  }
16327
16549
  };
16328
- let replayPending = true;
16329
- do {
16330
- const events = await runAgentCommsBridgeOnce({
16331
- agentContext,
16332
- source,
16333
- env: ctx.env,
16334
- stateDir: options.stateDir,
16335
- adapterInstance: options.adapterInstance,
16336
- limit,
16337
- replayPending,
16338
- wakeAdapter,
16339
- runtimeSession: options.runtimeSession ?? null
16340
- });
16341
- for (const event of events) emit(event);
16342
- replayPending = false;
16343
- if (options.once) break;
16344
- await sleep(pollIntervalMs);
16345
- } while (true);
16550
+ try {
16551
+ let replayPending = true;
16552
+ let consecutiveFailures = 0;
16553
+ let mode = streamSource ? "stream" : "poll";
16554
+ let pollFallbackOnce = false;
16555
+ const recentInjections = /* @__PURE__ */ new Map();
16556
+ const reconcileGraceMs = Math.min(3e4, Math.max(1, Math.floor(reconcileIntervalMs / 2)) || 3e4);
16557
+ let lastReconcileAt = Date.now();
16558
+ emit({ type: "bridge_process_started", pid: process.pid, mode, pollIntervalMs, reconcileIntervalMs });
16559
+ do {
16560
+ const source = mode === "stream" && streamSource ? streamSource : pollSource;
16561
+ try {
16562
+ const events = await runAgentCommsBridgeOnce({
16563
+ agentContext,
16564
+ source,
16565
+ env: ctx.env,
16566
+ stateDir: options.stateDir,
16567
+ adapterInstance: options.adapterInstance,
16568
+ limit,
16569
+ replayPending,
16570
+ wakeAdapter,
16571
+ runtimeSession: options.runtimeSession ?? null,
16572
+ recentInjections
16573
+ });
16574
+ for (const event of events) emit(event);
16575
+ if (consecutiveFailures > 0) {
16576
+ emit({ type: "bridge_recovered", afterFailures: consecutiveFailures });
16577
+ ctx.io.stderr.write(`bridge: recovered after ${consecutiveFailures} transient failure(s); bridge resumed.
16578
+ `);
16579
+ consecutiveFailures = 0;
16580
+ }
16581
+ replayPending = false;
16582
+ } catch (err) {
16583
+ if (options.once || classifyBridgeLoopError(err) === "fatal") {
16584
+ if (!(mode === "stream" && isWakeStreamUnavailable(err))) {
16585
+ const errorCode3 = err instanceof CliError ? err.code : err?.name ?? "Error";
16586
+ emit({ type: "bridge_fatal", errorCode: errorCode3, message: (err?.message ?? String(err)).slice(0, 200) });
16587
+ }
16588
+ if (mode === "stream" && isWakeStreamUnavailable(err)) {
16589
+ mode = "poll";
16590
+ emit({ type: "bridge_stream_unavailable", fallback: "poll", message: err.message });
16591
+ ctx.io.stderr.write(`bridge: wake-hint stream unavailable; falling back to polling.
16592
+ `);
16593
+ continue;
16594
+ }
16595
+ throw err;
16596
+ }
16597
+ replayPending = false;
16598
+ consecutiveFailures += 1;
16599
+ const delayMs = bridgeRetryDelayMs(consecutiveFailures, pollIntervalMs);
16600
+ const errorCode2 = err instanceof CliError ? err.code : err?.name ?? "Error";
16601
+ const message = (err?.message ?? String(err)).slice(0, 200);
16602
+ emit({ type: "bridge_retry", consecutiveFailures, delayMs, errorCode: errorCode2, message });
16603
+ ctx.io.stderr.write(
16604
+ `bridge: transient failure (${errorCode2}: ${message}); retry #${consecutiveFailures} in ${Math.round(delayMs / 1e3)}s. Pending wakes are not lost; \`slock message check\` still works directly.
16605
+ `
16606
+ );
16607
+ await sleep(delayMs);
16608
+ if (mode === "stream") {
16609
+ pollFallbackOnce = true;
16610
+ mode = "poll";
16611
+ }
16612
+ continue;
16613
+ }
16614
+ if (options.once) break;
16615
+ if (reconcileIntervalMs > 0 && Date.now() - lastReconcileAt >= reconcileIntervalMs) {
16616
+ lastReconcileAt = Date.now();
16617
+ try {
16618
+ const reconcile = await runAgentCommsBridgeReconcile({
16619
+ agentContext,
16620
+ source: pollSource,
16621
+ env: ctx.env,
16622
+ stateDir: options.stateDir,
16623
+ adapterInstance: options.adapterInstance,
16624
+ limit,
16625
+ wakeAdapter,
16626
+ runtimeSession: options.runtimeSession ?? null,
16627
+ recentInjections,
16628
+ graceMs: reconcileGraceMs
16629
+ });
16630
+ for (const event of reconcile.events) emit(event);
16631
+ emit({
16632
+ type: "reconcile_peek",
16633
+ pendingCount: reconcile.pendingCount,
16634
+ reinjectedCount: reconcile.reinjectedCount,
16635
+ skippedRecentCount: reconcile.skippedRecentCount
16636
+ });
16637
+ } catch (err) {
16638
+ const message = (err?.message ?? String(err)).slice(0, 200);
16639
+ emit({ type: "reconcile_failed", message });
16640
+ }
16641
+ }
16642
+ if (mode === "stream") continue;
16643
+ if (pollFallbackOnce && streamSource) {
16644
+ pollFallbackOnce = false;
16645
+ mode = "stream";
16646
+ continue;
16647
+ }
16648
+ await sleep(pollIntervalMs);
16649
+ } while (true);
16650
+ } finally {
16651
+ await streamSource?.close();
16652
+ bridgeLock.release();
16653
+ }
16346
16654
  }
16347
16655
  );
16348
16656
  function registerAgentBridgeCommand(parent, runtimeOptions) {
@@ -16370,6 +16678,155 @@ function createAgentApiWakeHintSource(client) {
16370
16678
  }
16371
16679
  };
16372
16680
  }
16681
+ function createAgentApiWakeHintStreamSource(client, env = process.env) {
16682
+ if (!client.requestRaw) return null;
16683
+ let reader = null;
16684
+ let bufferedText = "";
16685
+ let pendingEvent = {};
16686
+ const idleTimeoutMs = parseWakeStreamIdleTimeoutMs(env);
16687
+ async function close() {
16688
+ const current = reader;
16689
+ reader = null;
16690
+ bufferedText = "";
16691
+ pendingEvent = {};
16692
+ if (current) await current.cancel().catch(() => void 0);
16693
+ }
16694
+ async function ensureReader(since) {
16695
+ if (reader) return reader;
16696
+ const query = new URLSearchParams({ since: String(since) });
16697
+ const response = await client.requestRaw("GET", `/internal/agent-api/wake-hints/stream?${query.toString()}`);
16698
+ if (!response.ok) {
16699
+ throw new CliError({
16700
+ code: response.status === 404 || response.status === 405 || response.status === 501 ? "BRIDGE_WAKE_STREAM_UNAVAILABLE" : response.status >= 500 ? "SERVER_5XX" : "BRIDGE_WAKE_STREAM_FAILED",
16701
+ message: response.error ?? `HTTP ${response.status}`
16702
+ });
16703
+ }
16704
+ if (!response.response.body) {
16705
+ throw new TypeError("wake-hint stream response has no body");
16706
+ }
16707
+ reader = response.response.body.getReader();
16708
+ return reader;
16709
+ }
16710
+ async function nextEvent(since) {
16711
+ const decoder = new TextDecoder();
16712
+ while (true) {
16713
+ try {
16714
+ const buffered = drainSseEvents();
16715
+ if (buffered) return buffered;
16716
+ } catch (err) {
16717
+ await close();
16718
+ const message = err instanceof Error ? err.message : String(err);
16719
+ throw new TypeError(`wake-hint stream parse failed: ${message}`);
16720
+ }
16721
+ const current = await ensureReader(since);
16722
+ let chunk;
16723
+ try {
16724
+ chunk = await readWithIdleWatchdog(current, idleTimeoutMs);
16725
+ } catch (err) {
16726
+ await close();
16727
+ throw err;
16728
+ }
16729
+ const { done, value } = chunk;
16730
+ if (done) {
16731
+ await close();
16732
+ throw new TypeError("wake-hint stream ended");
16733
+ }
16734
+ bufferedText += decoder.decode(value, { stream: true });
16735
+ let result2;
16736
+ try {
16737
+ result2 = drainSseEvents();
16738
+ } catch (err) {
16739
+ await close();
16740
+ const message = err instanceof Error ? err.message : String(err);
16741
+ throw new TypeError(`wake-hint stream parse failed: ${message}`);
16742
+ }
16743
+ if (result2) return result2;
16744
+ return { hints: [], last_seen_hint_seq: null, has_more: false };
16745
+ }
16746
+ }
16747
+ function drainSseEvents() {
16748
+ while (true) {
16749
+ const newline = bufferedText.indexOf("\n");
16750
+ if (newline < 0) return null;
16751
+ const rawLine = bufferedText.slice(0, newline);
16752
+ bufferedText = bufferedText.slice(newline + 1);
16753
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
16754
+ if (line === "") {
16755
+ const result2 = sseEventToWakeHints(pendingEvent);
16756
+ pendingEvent = {};
16757
+ if (result2) return result2;
16758
+ continue;
16759
+ }
16760
+ if (line.startsWith(":")) continue;
16761
+ const separator = line.indexOf(":");
16762
+ const field = separator >= 0 ? line.slice(0, separator) : line;
16763
+ const value = separator >= 0 ? line.slice(separator + (line[separator + 1] === " " ? 2 : 1)) : "";
16764
+ if (field === "event") pendingEvent.event = value;
16765
+ if (field === "id") pendingEvent.id = value;
16766
+ if (field === "data") pendingEvent.data = pendingEvent.data === void 0 ? value : `${pendingEvent.data}
16767
+ ${value}`;
16768
+ }
16769
+ }
16770
+ return {
16771
+ async fetchWakeHints(input) {
16772
+ return nextEvent(input.since);
16773
+ },
16774
+ close
16775
+ };
16776
+ }
16777
+ function sseEventToWakeHints(event) {
16778
+ if (!event.data || event.event && event.event !== "wake-hint") return null;
16779
+ const parsed = JSON.parse(event.data);
16780
+ const eventSeq = Number(event.id);
16781
+ const hint = {
16782
+ ...parsed,
16783
+ ...!Number.isNaN(eventSeq) && typeof parsed.seq !== "number" ? { seq: eventSeq } : {}
16784
+ };
16785
+ const seq = typeof hint.seq === "number" ? hint.seq : Number.isNaN(eventSeq) ? null : eventSeq;
16786
+ return {
16787
+ hints: [hint],
16788
+ last_seen_hint_seq: seq,
16789
+ has_more: false
16790
+ };
16791
+ }
16792
+ function readWithIdleWatchdog(reader, idleTimeoutMs) {
16793
+ let timeout = null;
16794
+ const timeoutPromise = new Promise((_, reject) => {
16795
+ timeout = setTimeout(() => {
16796
+ reject(new TypeError(`wake-hint stream idle timeout after ${idleTimeoutMs}ms`));
16797
+ }, idleTimeoutMs);
16798
+ });
16799
+ return Promise.race([reader.read(), timeoutPromise]).finally(() => {
16800
+ if (timeout) clearTimeout(timeout);
16801
+ });
16802
+ }
16803
+ var BRIDGE_WAKE_STREAM_IDLE_TIMEOUT_MS = 6e4;
16804
+ function parseWakeStreamIdleTimeoutMs(env) {
16805
+ const raw = env.SLOCK_BRIDGE_WAKE_STREAM_IDLE_TIMEOUT_MS;
16806
+ if (raw === void 0) return BRIDGE_WAKE_STREAM_IDLE_TIMEOUT_MS;
16807
+ const parsed = Number(raw);
16808
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : BRIDGE_WAKE_STREAM_IDLE_TIMEOUT_MS;
16809
+ }
16810
+ function isWakeStreamUnavailable(err) {
16811
+ return err instanceof CliError && err.code === "BRIDGE_WAKE_STREAM_UNAVAILABLE";
16812
+ }
16813
+ function classifyBridgeLoopError(err) {
16814
+ if (err instanceof CliError) {
16815
+ return err.code === "SERVER_5XX" ? "retryable" : "fatal";
16816
+ }
16817
+ if (err instanceof Error) {
16818
+ const text = `${err.name}: ${err.message} ${err.cause?.message ?? ""}`;
16819
+ if (/wake-hint stream (ended|idle timeout|parse failed)|fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|EPIPE|socket|network|UND_ERR/i.test(text)) {
16820
+ return "retryable";
16821
+ }
16822
+ }
16823
+ return "fatal";
16824
+ }
16825
+ var BRIDGE_RETRY_MAX_DELAY_MS = 6e4;
16826
+ function bridgeRetryDelayMs(consecutiveFailures, pollIntervalMs) {
16827
+ const exp = Math.min(consecutiveFailures - 1, 10);
16828
+ return Math.min(pollIntervalMs * 2 ** exp, BRIDGE_RETRY_MAX_DELAY_MS);
16829
+ }
16373
16830
  function parsePositiveInt(raw, fallback, label) {
16374
16831
  if (raw === void 0) return fallback;
16375
16832
  const parsed = Number(raw);
@@ -16381,17 +16838,17 @@ function parsePositiveInt(raw, fallback, label) {
16381
16838
  }
16382
16839
  return parsed;
16383
16840
  }
16384
- function createWakeAdapter(options) {
16841
+ function createWakeAdapter(options, env = process.env) {
16385
16842
  if (!options.wakeAdapter) return void 0;
16386
- if (options.wakeAdapter !== "claude-code-channels") {
16843
+ if (options.wakeAdapter !== "wake-endpoint" && options.wakeAdapter !== "claude-code-channels") {
16387
16844
  throw new CliError({
16388
16845
  code: "INVALID_ARG",
16389
- message: "--wake-adapter must be `claude-code-channels`"
16846
+ message: "--wake-adapter must be `wake-endpoint` (or the compatible alias `claude-code-channels`)"
16390
16847
  });
16391
16848
  }
16392
16849
  return createClaudeCodeChannelsWakeAdapter({
16393
- endpointUrl: options.claudeChannelEndpoint,
16394
- token: options.claudeChannelToken
16850
+ endpointUrl: options.wakeEndpoint ?? options.claudeChannelEndpoint,
16851
+ token: options.wakeEndpointToken ?? options.claudeChannelToken ?? env.SLOCK_WAKE_ENDPOINT_TOKEN ?? env.SLOCK_CLAUDE_CHANNEL_TOKEN
16395
16852
  });
16396
16853
  }
16397
16854
  function sleep(ms) {
@@ -16980,6 +17437,54 @@ function registerThreadUnfollowCommand(parent, runtimeOptions) {
16980
17437
  registerCliCommand(parent, threadUnfollowCommand, runtimeOptions);
16981
17438
  }
16982
17439
 
17440
+ // src/commands/message/_consumedSeqState.ts
17441
+ import fs3 from "fs";
17442
+ import os2 from "os";
17443
+ import path5 from "path";
17444
+ function stateFilePath(agentId) {
17445
+ return path5.join(
17446
+ process.env.SLOCK_CLI_CONSUMED_SEQ_STATE_DIR ?? os2.tmpdir(),
17447
+ "slock-cli-consumed-seq",
17448
+ agentId,
17449
+ "consumed-seqs.json"
17450
+ );
17451
+ }
17452
+ function readState(agentId) {
17453
+ try {
17454
+ const parsed = JSON.parse(fs3.readFileSync(stateFilePath(agentId), "utf8"));
17455
+ return typeof parsed === "object" && parsed ? parsed : {};
17456
+ } catch {
17457
+ return {};
17458
+ }
17459
+ }
17460
+ function recordConsumedSeqs(agentId, entries) {
17461
+ const updates = Object.entries(entries).filter(
17462
+ ([target, seq]) => target.length > 0 && Number.isFinite(seq) && seq > 0
17463
+ );
17464
+ if (updates.length === 0) return;
17465
+ const state = readState(agentId);
17466
+ const targets = state.targets ?? {};
17467
+ let changed = false;
17468
+ for (const [target, seq] of updates) {
17469
+ const prior = targets[target];
17470
+ if (!Number.isFinite(prior) || seq > prior) {
17471
+ targets[target] = seq;
17472
+ changed = true;
17473
+ }
17474
+ }
17475
+ if (!changed) return;
17476
+ const filePath = stateFilePath(agentId);
17477
+ try {
17478
+ fs3.mkdirSync(path5.dirname(filePath), { recursive: true });
17479
+ fs3.writeFileSync(filePath, JSON.stringify({ targets }), "utf8");
17480
+ } catch {
17481
+ }
17482
+ }
17483
+ function getConsumedSeq(agentId, target) {
17484
+ const seq = readState(agentId).targets?.[target];
17485
+ return Number.isFinite(seq) && seq > 0 ? seq : void 0;
17486
+ }
17487
+
16983
17488
  // src/commands/message/_format.ts
16984
17489
  function toLocalTime(iso) {
16985
17490
  const d = new Date(iso);
@@ -17092,18 +17597,18 @@ Your last read position: seq ${data.last_read_seq}. Use slock message read --cha
17092
17597
 
17093
17598
  ${formatted}${footer}`;
17094
17599
  }
17095
- function renderSearchSource(result) {
17096
- if (result.channelType === "thread") {
17097
- const shortId = typeof result.channelName === "string" && result.channelName.startsWith("thread-") ? result.channelName.slice(7) : typeof result.threadId === "string" && result.threadId ? result.threadId.slice(0, 8) : result.channelName;
17098
- if (result.parentChannelType === "dm") {
17099
- return `dm:${neutralizeSlockRefLiterals(result.parentChannelName ?? "unknown")}:${shortId}`;
17600
+ function renderSearchSource(result2) {
17601
+ if (result2.channelType === "thread") {
17602
+ const shortId = typeof result2.channelName === "string" && result2.channelName.startsWith("thread-") ? result2.channelName.slice(7) : typeof result2.threadId === "string" && result2.threadId ? result2.threadId.slice(0, 8) : result2.channelName;
17603
+ if (result2.parentChannelType === "dm") {
17604
+ return `dm:${neutralizeSlockRefLiterals(result2.parentChannelName ?? "unknown")}:${shortId}`;
17100
17605
  }
17101
- return `thread:${neutralizeSlockRefLiterals(result.parentChannelName ?? "unknown")}:${shortId}`;
17606
+ return `thread:${neutralizeSlockRefLiterals(result2.parentChannelName ?? "unknown")}:${shortId}`;
17102
17607
  }
17103
- if (result.channelType === "dm") {
17104
- return `dm:${neutralizeSlockRefLiterals(result.channelName ?? "unknown")}`;
17608
+ if (result2.channelType === "dm") {
17609
+ return `dm:${neutralizeSlockRefLiterals(result2.channelName ?? "unknown")}`;
17105
17610
  }
17106
- return `channel:${neutralizeSlockRefLiterals(result.channelName ?? "unknown")}`;
17611
+ return `channel:${neutralizeSlockRefLiterals(result2.channelName ?? "unknown")}`;
17107
17612
  }
17108
17613
  var PREVIEW_BEFORE_CHARS = 80;
17109
17614
  var PREVIEW_AFTER_CHARS = 120;
@@ -17209,16 +17714,16 @@ function renderSearchPreview(content, query) {
17209
17714
  }
17210
17715
  function formatSearchResults(query, data) {
17211
17716
  if (!data.results || data.results.length === 0) return "No search results.";
17212
- const formatted = data.results.map((result, index) => {
17213
- const ref = `msg:${result.id}`;
17214
- const content = result.content ?? result.snippet ?? "";
17215
- const sender = neutralizeSlockRefLiterals(result.senderName ?? "unknown");
17216
- const senderType = result.senderType ? ` (${result.senderType})` : "";
17717
+ const formatted = data.results.map((result2, index) => {
17718
+ const ref = `msg:${result2.id}`;
17719
+ const content = result2.content ?? result2.snippet ?? "";
17720
+ const sender = neutralizeSlockRefLiterals(result2.senderName ?? "unknown");
17721
+ const senderType = result2.senderType ? ` (${result2.senderType})` : "";
17217
17722
  return [
17218
17723
  `<result ref="${ref}">`,
17219
- `Source: ${renderSearchSource(result)}`,
17724
+ `Source: ${renderSearchSource(result2)}`,
17220
17725
  `Sender: ${sender}${senderType}`,
17221
- `Time: ${result.createdAt ? toLocalTime(result.createdAt) : "-"}`,
17726
+ `Time: ${result2.createdAt ? toLocalTime(result2.createdAt) : "-"}`,
17222
17727
  "",
17223
17728
  "<preview>",
17224
17729
  renderSearchPreview(content, query),
@@ -17260,17 +17765,17 @@ ${opts.heldAction} Review the bounded context shown here, then choose one path.$
17260
17765
  }
17261
17766
 
17262
17767
  // src/commands/message/_continueDraftState.ts
17263
- import fs3 from "fs";
17264
- import os2 from "os";
17265
- import path5 from "path";
17768
+ import fs4 from "fs";
17769
+ import os3 from "os";
17770
+ import path6 from "path";
17266
17771
  var DEFAULT_LOCAL_DRAFT_TTL_MS = 10 * 60 * 1e3;
17267
- function stateFilePath(agentId) {
17268
- return path5.join(process.env.SLOCK_CLI_DRAFT_STATE_DIR ?? os2.tmpdir(), "slock-cli-attested-send", agentId, "continue-state.json");
17772
+ function stateFilePath2(agentId) {
17773
+ return path6.join(process.env.SLOCK_CLI_DRAFT_STATE_DIR ?? os3.tmpdir(), "slock-cli-attested-send", agentId, "continue-state.json");
17269
17774
  }
17270
- function readState(agentId) {
17271
- const filePath = stateFilePath(agentId);
17775
+ function readState2(agentId) {
17776
+ const filePath = stateFilePath2(agentId);
17272
17777
  try {
17273
- const raw = fs3.readFileSync(filePath, "utf8");
17778
+ const raw = fs4.readFileSync(filePath, "utf8");
17274
17779
  const parsed = JSON.parse(raw);
17275
17780
  return typeof parsed === "object" && parsed ? parsed : {};
17276
17781
  } catch {
@@ -17278,12 +17783,12 @@ function readState(agentId) {
17278
17783
  }
17279
17784
  }
17280
17785
  function writeState(agentId, state) {
17281
- const filePath = stateFilePath(agentId);
17282
- fs3.mkdirSync(path5.dirname(filePath), { recursive: true });
17283
- fs3.writeFileSync(filePath, JSON.stringify(state), "utf8");
17786
+ const filePath = stateFilePath2(agentId);
17787
+ fs4.mkdirSync(path6.dirname(filePath), { recursive: true });
17788
+ fs4.writeFileSync(filePath, JSON.stringify(state), "utf8");
17284
17789
  }
17285
17790
  function getSavedDraft(agentId, target) {
17286
- const state = readState(agentId);
17791
+ const state = readState2(agentId);
17287
17792
  const draft = state.targets?.[target];
17288
17793
  if (!draft || typeof draft === "string") return null;
17289
17794
  if (typeof draft.content !== "string") return null;
@@ -17304,7 +17809,7 @@ function getSavedDraft(agentId, target) {
17304
17809
  };
17305
17810
  }
17306
17811
  function setSavedDraft(agentId, target, draft) {
17307
- const state = readState(agentId);
17812
+ const state = readState2(agentId);
17308
17813
  const targets = state.targets ?? {};
17309
17814
  targets[target] = {
17310
17815
  content: draft.content,
@@ -17316,7 +17821,7 @@ function setSavedDraft(agentId, target, draft) {
17316
17821
  writeState(agentId, { targets });
17317
17822
  }
17318
17823
  function clearSavedDraft(agentId, target) {
17319
- const state = readState(agentId);
17824
+ const state = readState2(agentId);
17320
17825
  if (!state.targets || !(target in state.targets)) return;
17321
17826
  delete state.targets[target];
17322
17827
  writeState(agentId, state);
@@ -17513,6 +18018,9 @@ var messageSendCommand = defineCommand(
17513
18018
  previousDraftReholdCount = previousDraft?.reholdCount ?? 0;
17514
18019
  seenUpToSeq = previousDraft?.seenUpToSeq;
17515
18020
  }
18021
+ if (seenUpToSeq === void 0) {
18022
+ seenUpToSeq = getConsumedSeq(agentContext.agentId, opts.target);
18023
+ }
17516
18024
  const body = {
17517
18025
  target: opts.target,
17518
18026
  content: outgoingContent,
@@ -17541,6 +18049,9 @@ var messageSendCommand = defineCommand(
17541
18049
  }
17542
18050
  const data = res.data;
17543
18051
  if (data.state === "held") {
18052
+ if (typeof data.seenUpToSeq === "number" && Number.isFinite(data.seenUpToSeq)) {
18053
+ recordConsumedSeqs(agentContext.agentId, { [opts.target]: data.seenUpToSeq });
18054
+ }
17544
18055
  setSavedDraft(agentContext.agentId, opts.target, {
17545
18056
  content: outgoingContent,
17546
18057
  attachmentIds: outgoingAttachmentIds,
@@ -17570,31 +18081,72 @@ function registerSendCommand(parent, runtimeOptions = {}) {
17570
18081
  }
17571
18082
 
17572
18083
  // src/commands/message/_inbox.ts
18084
+ var MAX_DRAIN_ROUNDS = 50;
18085
+ function sortedMessages(messages) {
18086
+ return [...messages].sort((a, b) => {
18087
+ const aSeq = Number.isInteger(a.seq) && a.seq > 0 ? a.seq : Number.MAX_SAFE_INTEGER;
18088
+ const bSeq = Number.isInteger(b.seq) && b.seq > 0 ? b.seq : Number.MAX_SAFE_INTEGER;
18089
+ return aSeq - bSeq;
18090
+ });
18091
+ }
18092
+ function result(messages, opts = {}) {
18093
+ return {
18094
+ messages: sortedMessages(messages),
18095
+ ...opts.ackFailure ? { ackFailure: opts.ackFailure } : {},
18096
+ ...opts.drainedMore ? { drainedMore: true } : {},
18097
+ ...opts.hasMore ? { hasMore: true } : {},
18098
+ ...opts.drainComplete ? { drainComplete: true } : {}
18099
+ };
18100
+ }
18101
+ function hasMoreField(data) {
18102
+ if (!data) return false;
18103
+ return Object.prototype.hasOwnProperty.call(data, "has_more") || Object.prototype.hasOwnProperty.call(data, "hasMore");
18104
+ }
17573
18105
  async function drainInbox(ctx, opts, client = new ApiClient(ctx)) {
17574
18106
  const agentPath = `/internal/agent/${encodeURIComponent(ctx.agentId)}`;
17575
18107
  const failCode = opts.block ? "WAIT_FAILED" : "CHECK_FAILED";
17576
18108
  const query = [];
17577
18109
  if (opts.block) query.push("block=true");
17578
18110
  if (opts.block && opts.timeoutMs !== void 0) query.push(`timeout=${opts.timeoutMs}`);
17579
- const path7 = query.length > 0 ? `${agentPath}/receive?${query.join("&")}` : `${agentPath}/receive`;
17580
- const res = await client.request("GET", path7);
17581
- if (!res.ok) {
17582
- throw new CliError({
17583
- code: res.status >= 500 ? "SERVER_5XX" : failCode,
17584
- message: res.error ?? `HTTP ${res.status}`
17585
- });
17586
- }
17587
- const messages = res.data?.messages ?? [];
17588
- if (ctx.clientMode === "managed-runner" || ctx.clientMode === "self-hosted-runner") {
17589
- return { messages };
18111
+ const path8 = query.length > 0 ? `${agentPath}/receive?${query.join("&")}` : `${agentPath}/receive`;
18112
+ const allMessages = [];
18113
+ let sawHasMore = false;
18114
+ for (let round = 0; round < MAX_DRAIN_ROUNDS; round += 1) {
18115
+ const res = await client.request("GET", path8);
18116
+ if (!res.ok) {
18117
+ if (allMessages.length > 0) {
18118
+ return result(allMessages, { drainedMore: sawHasMore, hasMore: true });
18119
+ }
18120
+ throw new CliError({
18121
+ code: res.status >= 500 ? "SERVER_5XX" : failCode,
18122
+ message: res.error ?? `HTTP ${res.status}`
18123
+ });
18124
+ }
18125
+ const messages = res.data?.messages ?? [];
18126
+ allMessages.push(...messages);
18127
+ const hasMore = res.data?.has_more === true || res.data?.hasMore === true;
18128
+ const hasExplicitHasMore = hasMoreField(res.data);
18129
+ const drainComplete = hasExplicitHasMore && !hasMore && allMessages.length > 0;
18130
+ sawHasMore = sawHasMore || hasMore;
18131
+ if (ctx.clientMode === "managed-runner" || ctx.clientMode === "self-hosted-runner") {
18132
+ if (hasMore && messages.length > 0) continue;
18133
+ return result(allMessages, { drainedMore: sawHasMore, hasMore, drainComplete });
18134
+ }
18135
+ const seqs = messages.map((m) => m.seq).filter((s) => Number.isInteger(s) && s > 0);
18136
+ if (seqs.length === 0) return result(allMessages, { drainedMore: sawHasMore, hasMore, drainComplete });
18137
+ const ack = await client.request("POST", `${agentPath}/receive-ack`, { seqs });
18138
+ if (!ack.ok) {
18139
+ const ackCode = ack.status >= 500 ? "SERVER_5XX" : "ACK_FAILED";
18140
+ const ackMessage = ack.error ?? `HTTP ${ack.status}`;
18141
+ return result(allMessages, {
18142
+ ackFailure: { code: ackCode, message: ackMessage },
18143
+ drainedMore: sawHasMore,
18144
+ hasMore
18145
+ });
18146
+ }
18147
+ if (!hasMore) return result(allMessages, { drainedMore: sawHasMore, drainComplete });
17590
18148
  }
17591
- const seqs = messages.map((m) => m.seq).filter((s) => Number.isInteger(s) && s > 0);
17592
- if (seqs.length === 0) return { messages };
17593
- const ack = await client.request("POST", `${agentPath}/receive-ack`, { seqs });
17594
- if (ack.ok) return { messages };
17595
- const ackCode = ack.status >= 500 ? "SERVER_5XX" : "ACK_FAILED";
17596
- const ackMessage = ack.error ?? `HTTP ${ack.status}`;
17597
- return { messages, ackFailure: { code: ackCode, message: ackMessage } };
18149
+ return result(allMessages, { drainedMore: sawHasMore, hasMore: true });
17598
18150
  }
17599
18151
 
17600
18152
  // src/commands/message/check.ts
@@ -17605,13 +18157,21 @@ var messageCheckCommand = defineCommand(
17605
18157
  },
17606
18158
  async (ctx) => {
17607
18159
  const agentContext = ctx.loadAgentContext();
17608
- const result = await drainInbox(
18160
+ const result2 = await drainInbox(
17609
18161
  agentContext,
17610
18162
  { block: false },
17611
18163
  ctx.createApiClient(agentContext)
17612
18164
  );
17613
- writeText(ctx.io, `${formatMessages(result.messages)}
17614
- `);
18165
+ const drainStatus = result2.hasMore ? "\nMore messages are pending. Run `slock message check` again.\n" : result2.drainComplete ? "\nNo more new messages.\n" : "\n";
18166
+ writeText(ctx.io, `${formatMessages(result2.messages)}${drainStatus}`);
18167
+ const consumed = {};
18168
+ for (const m of result2.messages) {
18169
+ const seq = typeof m.seq === "number" && Number.isFinite(m.seq) ? m.seq : null;
18170
+ if (seq === null) continue;
18171
+ const target = formatTarget(m);
18172
+ if (!consumed[target] || seq > consumed[target]) consumed[target] = seq;
18173
+ }
18174
+ recordConsumedSeqs(agentContext.agentId, consumed);
17615
18175
  }
17616
18176
  );
17617
18177
  function registerCheckCommand(parent, runtimeOptions) {
@@ -17716,6 +18276,12 @@ var messageReadCommand = defineCommand(
17716
18276
  })}
17717
18277
  `
17718
18278
  );
18279
+ const rows = res.data.messages ?? [];
18280
+ let maxSeq = 0;
18281
+ for (const row of rows) {
18282
+ if (typeof row.seq === "number" && Number.isFinite(row.seq) && row.seq > maxSeq) maxSeq = row.seq;
18283
+ }
18284
+ if (maxSeq > 0) recordConsumedSeqs(agentContext.agentId, { [readOpts.channel]: maxSeq });
17719
18285
  }
17720
18286
  );
17721
18287
  function registerReadCommand(parent, runtimeOptions) {
@@ -18187,6 +18753,76 @@ function registerAttachmentViewCommand(parent, runtimeOptions) {
18187
18753
  registerCliCommand(parent, attachmentViewCommand, runtimeOptions);
18188
18754
  }
18189
18755
 
18756
+ // src/commands/attachment/comments.ts
18757
+ function anchorSummary(anchor) {
18758
+ if (anchor.type === "md-section") {
18759
+ const title = anchor.data.headingTitle ?? anchor.data.headingId;
18760
+ return typeof title === "string" && title ? `\xA7 ${title}` : "\xA7 section";
18761
+ }
18762
+ if (anchor.type === "lines" || anchor.type === "csv-rows") {
18763
+ const start = Number(anchor.data.start);
18764
+ const end = Number(anchor.data.end ?? start);
18765
+ if (!Number.isFinite(start)) return anchor.type;
18766
+ const prefix = anchor.type === "lines" ? "L" : "rows ";
18767
+ return start === (Number.isFinite(end) ? end : start) ? `${prefix}${start}` : `${prefix}${start}\u2013${end}`;
18768
+ }
18769
+ if (anchor.type === "html-region") {
18770
+ const quote = anchor.data.quote;
18771
+ if (typeof quote === "string" && quote.trim().length > 0) {
18772
+ const trimmed = quote.trim();
18773
+ return trimmed.length > 60 ? `${trimmed.slice(0, 60)}\u2026` : trimmed;
18774
+ }
18775
+ return "HTML region";
18776
+ }
18777
+ return anchor.type;
18778
+ }
18779
+ var attachmentCommentsCommand = defineCommand(
18780
+ {
18781
+ name: "comments",
18782
+ description: "List comments scoped to an attachment",
18783
+ options: [
18784
+ { flags: "--id <attachmentId>", description: "Attachment UUID" },
18785
+ { flags: "--limit <n>", description: "Max comments to return (default 200)" }
18786
+ ]
18787
+ },
18788
+ async (ctx, opts) => {
18789
+ const id = opts.id?.trim();
18790
+ if (!id) {
18791
+ throw new CliError({ code: "INVALID_ARG", message: "--id is required" });
18792
+ }
18793
+ const agentContext = ctx.loadAgentContext();
18794
+ const client = ctx.createApiClient(agentContext);
18795
+ const limitParam = opts.limit && Number.isFinite(Number(opts.limit)) ? `?limit=${Number(opts.limit)}` : "";
18796
+ const res = await client.request(
18797
+ "GET",
18798
+ `/api/attachments/${encodeURIComponent(id)}/comments${limitParam}`
18799
+ );
18800
+ if (!res.ok || !res.data) {
18801
+ const code = res.status >= 500 ? "SERVER_5XX" : "COMMENTS_FAILED";
18802
+ throw new CliError({ code, message: res.error ?? `HTTP ${res.status}` });
18803
+ }
18804
+ const { comments, threadChannelId } = res.data;
18805
+ if (comments.length === 0) {
18806
+ writeText(ctx.io, `No comments on attachment ${id.slice(0, 8)}.
18807
+ `);
18808
+ return;
18809
+ }
18810
+ const lines = [`## Comments on attachment ${id.slice(0, 8)} (${comments.length})`];
18811
+ for (const c of comments) {
18812
+ const check2 = c.reactions.some((r) => r.emoji === "\u2705") ? " \u2705" : "";
18813
+ const anchor = c.anchor ? ` [anchor: ${anchorSummary(c.anchor)}]` : "";
18814
+ lines.push(`[msg=${c.id.slice(0, 8)} time=${c.createdAt} type=${c.senderType}]${check2}${anchor} @${c.senderName}: ${c.content}`);
18815
+ }
18816
+ if (threadChannelId) {
18817
+ lines.push(`(full conversation lives in thread channel ${threadChannelId})`);
18818
+ }
18819
+ writeText(ctx.io, lines.join("\n") + "\n");
18820
+ }
18821
+ );
18822
+ function registerAttachmentCommentsCommand(parent, runtimeOptions) {
18823
+ registerCliCommand(parent, attachmentCommentsCommand, runtimeOptions);
18824
+ }
18825
+
18190
18826
  // src/commands/task/_format.ts
18191
18827
  function formatTaskList(channel, data, statusFilter) {
18192
18828
  if (!data.tasks || data.tasks.length === 0) {
@@ -19021,10 +19657,12 @@ function registerIntegrationLoginCommand(parent, runtimeOptions = {}) {
19021
19657
  }
19022
19658
 
19023
19659
  // src/commands/integration/manifest.ts
19024
- import fs4 from "fs";
19025
- import os3 from "os";
19026
- import path6 from "path";
19660
+ import fs5 from "fs";
19661
+ import os4 from "os";
19662
+ import path7 from "path";
19027
19663
  var AGENT_MANIFEST_MAX_BYTES = 64 * 1024;
19664
+ var AGENT_MANIFEST_SCHEMA_V0 = "slock-agent-manifest.v0";
19665
+ var AGENT_MANIFEST_SCHEMA_V0_URL = "https://app.slock.ai/schemas/agent-manifest.v0.json";
19028
19666
  var AgentManifestFetchError = class extends Error {
19029
19667
  constructor(message, status) {
19030
19668
  super(message);
@@ -19032,6 +19670,12 @@ var AgentManifestFetchError = class extends Error {
19032
19670
  this.name = "AgentManifestFetchError";
19033
19671
  }
19034
19672
  };
19673
+ var AgentManifestResponseFormatError = class extends Error {
19674
+ constructor(message) {
19675
+ super(message);
19676
+ this.name = "AgentManifestResponseFormatError";
19677
+ }
19678
+ };
19035
19679
  function isRecord(value) {
19036
19680
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
19037
19681
  }
@@ -19065,8 +19709,8 @@ function requireCommand(value) {
19065
19709
  }
19066
19710
  function validateAgentManifestV0(value) {
19067
19711
  if (!isRecord(value)) throw new Error("manifest must be a JSON object");
19068
- if (value.schema !== "slock-agent-manifest.v0") {
19069
- throw new Error("manifest schema must be slock-agent-manifest.v0");
19712
+ if (value.schema !== AGENT_MANIFEST_SCHEMA_V0 && value.schema !== AGENT_MANIFEST_SCHEMA_V0_URL) {
19713
+ throw new Error(`manifest schema must be ${AGENT_MANIFEST_SCHEMA_V0}`);
19070
19714
  }
19071
19715
  const execution = value.execution;
19072
19716
  if (!isRecord(execution)) throw new Error("execution must be an object");
@@ -19086,7 +19730,7 @@ function validateAgentManifestV0(value) {
19086
19730
  throw new Error("context_check must be an object when present");
19087
19731
  }
19088
19732
  return {
19089
- schema: value.schema,
19733
+ schema: AGENT_MANIFEST_SCHEMA_V0,
19090
19734
  service: typeof value.service === "string" && value.service.trim() ? value.service.trim() : void 0,
19091
19735
  docs_url: value.docs_url === void 0 ? void 0 : requireUrl(value.docs_url, "docs_url"),
19092
19736
  execution: {
@@ -19122,7 +19766,7 @@ async function fetchAgentManifest(url2) {
19122
19766
  }
19123
19767
  const contentType = response.headers.get("content-type") ?? "";
19124
19768
  if (contentType && !contentType.includes("application/json")) {
19125
- throw new Error("manifest response must be application/json");
19769
+ throw new AgentManifestResponseFormatError("manifest response must be application/json");
19126
19770
  }
19127
19771
  const contentLength = Number(response.headers.get("content-length") ?? "");
19128
19772
  if (Number.isFinite(contentLength) && contentLength > AGENT_MANIFEST_MAX_BYTES) {
@@ -19137,7 +19781,7 @@ async function fetchAgentManifest(url2) {
19137
19781
  try {
19138
19782
  parsedJson = JSON.parse(raw);
19139
19783
  } catch (err) {
19140
- throw new Error(`manifest response is not valid JSON: ${err.message}`);
19784
+ throw new AgentManifestResponseFormatError(`manifest response is not valid JSON: ${err.message}`);
19141
19785
  }
19142
19786
  return validateAgentManifestV0(parsedJson);
19143
19787
  }
@@ -19146,8 +19790,8 @@ function sanitizePathSegment(value) {
19146
19790
  return segment || "service";
19147
19791
  }
19148
19792
  function resolveSlockHome(env) {
19149
- if (env.SLOCK_HOME?.trim()) return path6.resolve(env.SLOCK_HOME);
19150
- return path6.join(env.HOME ?? os3.homedir(), ".slock");
19793
+ if (env.SLOCK_HOME?.trim()) return path7.resolve(env.SLOCK_HOME);
19794
+ return path7.join(env.HOME ?? os4.homedir(), ".slock");
19151
19795
  }
19152
19796
  function buildLocalCliProfileEnv(input) {
19153
19797
  if (input.manifest.execution.mode !== "local_cli" || !input.manifest.execution.command) {
@@ -19160,15 +19804,15 @@ function buildLocalCliProfileEnv(input) {
19160
19804
  throw new Error("manifest must set credential_boundary.forbid_user_home=true for local_cli isolation");
19161
19805
  }
19162
19806
  const root = resolveSlockHome(input.env ?? process.env);
19163
- const profileHome = path6.join(
19807
+ const profileHome = path7.join(
19164
19808
  root,
19165
19809
  "integration-profiles",
19166
19810
  sanitizePathSegment(input.ctx.serverId ?? "server"),
19167
19811
  sanitizePathSegment(input.ctx.agentId),
19168
19812
  sanitizePathSegment(input.serviceId)
19169
19813
  );
19170
- fs4.mkdirSync(profileHome, { recursive: true, mode: 448 });
19171
- fs4.chmodSync(profileHome, 448);
19814
+ fs5.mkdirSync(profileHome, { recursive: true, mode: 448 });
19815
+ fs5.chmodSync(profileHome, 448);
19172
19816
  return {
19173
19817
  serviceId: input.serviceId,
19174
19818
  command: input.manifest.execution.command,
@@ -19177,10 +19821,10 @@ function buildLocalCliProfileEnv(input) {
19177
19821
  SLOCK_INTEGRATION_SERVICE: input.serviceId,
19178
19822
  SLOCK_INTEGRATION_PROFILE_HOME: profileHome,
19179
19823
  HOME: profileHome,
19180
- XDG_CONFIG_HOME: path6.join(profileHome, ".config"),
19181
- XDG_CACHE_HOME: path6.join(profileHome, ".cache"),
19182
- XDG_DATA_HOME: path6.join(profileHome, ".local", "share"),
19183
- XDG_STATE_HOME: path6.join(profileHome, ".local", "state")
19824
+ XDG_CONFIG_HOME: path7.join(profileHome, ".config"),
19825
+ XDG_CACHE_HOME: path7.join(profileHome, ".cache"),
19826
+ XDG_DATA_HOME: path7.join(profileHome, ".local", "share"),
19827
+ XDG_STATE_HOME: path7.join(profileHome, ".local", "state")
19184
19828
  }
19185
19829
  };
19186
19830
  }
@@ -19232,6 +19876,18 @@ function describeMissingManifest(input) {
19232
19876
  }
19233
19877
  return `${input.service.name} does not expose an agent behavior manifest; no local CLI env is required`;
19234
19878
  }
19879
+ function isInferredWellKnownManifest(service) {
19880
+ return service.agentManifestUrlSource === "well_known";
19881
+ }
19882
+ function noLocalEnvForMissingManifest(service) {
19883
+ return {
19884
+ kind: "no-local-env",
19885
+ service,
19886
+ manifestUrl: service.agentManifestUrl,
19887
+ manifest: null,
19888
+ message: describeMissingManifest({ service, manifestUrl: service.agentManifestUrl })
19889
+ };
19890
+ }
19235
19891
  var IntegrationEnvError = class extends Error {
19236
19892
  constructor(code, message) {
19237
19893
  super(message);
@@ -19255,13 +19911,10 @@ async function resolveIntegrationEnv(input) {
19255
19911
  manifest = await fetchManifestImpl(input.service.agentManifestUrl);
19256
19912
  } catch (err) {
19257
19913
  if (err instanceof AgentManifestFetchError && (err.status === 404 || err.status === 410)) {
19258
- return {
19259
- kind: "no-local-env",
19260
- service: input.service,
19261
- manifestUrl: input.service.agentManifestUrl,
19262
- manifest: null,
19263
- message: describeMissingManifest({ service: input.service, manifestUrl: input.service.agentManifestUrl })
19264
- };
19914
+ return noLocalEnvForMissingManifest(input.service);
19915
+ }
19916
+ if (isInferredWellKnownManifest(input.service) && err instanceof AgentManifestResponseFormatError) {
19917
+ return noLocalEnvForMissingManifest(input.service);
19265
19918
  }
19266
19919
  throw new IntegrationEnvError("INTEGRATION_MANIFEST_INVALID", err.message);
19267
19920
  }
@@ -19809,6 +20462,7 @@ registerReactCommand(messageCmd);
19809
20462
  var attachmentCmd = program.command("attachment").description("Attachment operations");
19810
20463
  registerAttachmentUploadCommand(attachmentCmd);
19811
20464
  registerAttachmentViewCommand(attachmentCmd);
20465
+ registerAttachmentCommentsCommand(attachmentCmd);
19812
20466
  var taskCmd = program.command("task").description("Task board operations");
19813
20467
  registerTaskListCommand(taskCmd);
19814
20468
  registerTaskCreateCommand(taskCmd);