@chosengeneration/light-code 0.89.0 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +24 -3
  2. package/dist/cli.cjs +1910 -1313
  3. package/dist/server.cjs +1279 -716
  4. package/package.json +1 -1
package/dist/server.cjs CHANGED
@@ -104,54 +104,54 @@ var require_errors = __commonJS({
104
104
  "../../node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/core/errors.js"(exports2, module2) {
105
105
  "use strict";
106
106
  var UndiciError = class extends Error {
107
- constructor(message3) {
108
- super(message3);
107
+ constructor(message4) {
108
+ super(message4);
109
109
  this.name = "UndiciError";
110
110
  this.code = "UND_ERR";
111
111
  }
112
112
  };
113
113
  var ConnectTimeoutError = class _ConnectTimeoutError extends UndiciError {
114
- constructor(message3) {
115
- super(message3);
114
+ constructor(message4) {
115
+ super(message4);
116
116
  Error.captureStackTrace(this, _ConnectTimeoutError);
117
117
  this.name = "ConnectTimeoutError";
118
- this.message = message3 || "Connect Timeout Error";
118
+ this.message = message4 || "Connect Timeout Error";
119
119
  this.code = "UND_ERR_CONNECT_TIMEOUT";
120
120
  }
121
121
  };
122
122
  var HeadersTimeoutError = class _HeadersTimeoutError extends UndiciError {
123
- constructor(message3) {
124
- super(message3);
123
+ constructor(message4) {
124
+ super(message4);
125
125
  Error.captureStackTrace(this, _HeadersTimeoutError);
126
126
  this.name = "HeadersTimeoutError";
127
- this.message = message3 || "Headers Timeout Error";
127
+ this.message = message4 || "Headers Timeout Error";
128
128
  this.code = "UND_ERR_HEADERS_TIMEOUT";
129
129
  }
130
130
  };
131
131
  var HeadersOverflowError = class _HeadersOverflowError extends UndiciError {
132
- constructor(message3) {
133
- super(message3);
132
+ constructor(message4) {
133
+ super(message4);
134
134
  Error.captureStackTrace(this, _HeadersOverflowError);
135
135
  this.name = "HeadersOverflowError";
136
- this.message = message3 || "Headers Overflow Error";
136
+ this.message = message4 || "Headers Overflow Error";
137
137
  this.code = "UND_ERR_HEADERS_OVERFLOW";
138
138
  }
139
139
  };
140
140
  var BodyTimeoutError = class _BodyTimeoutError extends UndiciError {
141
- constructor(message3) {
142
- super(message3);
141
+ constructor(message4) {
142
+ super(message4);
143
143
  Error.captureStackTrace(this, _BodyTimeoutError);
144
144
  this.name = "BodyTimeoutError";
145
- this.message = message3 || "Body Timeout Error";
145
+ this.message = message4 || "Body Timeout Error";
146
146
  this.code = "UND_ERR_BODY_TIMEOUT";
147
147
  }
148
148
  };
149
149
  var ResponseStatusCodeError = class _ResponseStatusCodeError extends UndiciError {
150
- constructor(message3, statusCode, headers, body) {
151
- super(message3);
150
+ constructor(message4, statusCode, headers, body) {
151
+ super(message4);
152
152
  Error.captureStackTrace(this, _ResponseStatusCodeError);
153
153
  this.name = "ResponseStatusCodeError";
154
- this.message = message3 || "Response Status Code Error";
154
+ this.message = message4 || "Response Status Code Error";
155
155
  this.code = "UND_ERR_RESPONSE_STATUS_CODE";
156
156
  this.body = body;
157
157
  this.status = statusCode;
@@ -160,108 +160,108 @@ var require_errors = __commonJS({
160
160
  }
161
161
  };
162
162
  var InvalidArgumentError = class _InvalidArgumentError extends UndiciError {
163
- constructor(message3) {
164
- super(message3);
163
+ constructor(message4) {
164
+ super(message4);
165
165
  Error.captureStackTrace(this, _InvalidArgumentError);
166
166
  this.name = "InvalidArgumentError";
167
- this.message = message3 || "Invalid Argument Error";
167
+ this.message = message4 || "Invalid Argument Error";
168
168
  this.code = "UND_ERR_INVALID_ARG";
169
169
  }
170
170
  };
171
171
  var InvalidReturnValueError = class _InvalidReturnValueError extends UndiciError {
172
- constructor(message3) {
173
- super(message3);
172
+ constructor(message4) {
173
+ super(message4);
174
174
  Error.captureStackTrace(this, _InvalidReturnValueError);
175
175
  this.name = "InvalidReturnValueError";
176
- this.message = message3 || "Invalid Return Value Error";
176
+ this.message = message4 || "Invalid Return Value Error";
177
177
  this.code = "UND_ERR_INVALID_RETURN_VALUE";
178
178
  }
179
179
  };
180
180
  var RequestAbortedError = class _RequestAbortedError extends UndiciError {
181
- constructor(message3) {
182
- super(message3);
181
+ constructor(message4) {
182
+ super(message4);
183
183
  Error.captureStackTrace(this, _RequestAbortedError);
184
184
  this.name = "AbortError";
185
- this.message = message3 || "Request aborted";
185
+ this.message = message4 || "Request aborted";
186
186
  this.code = "UND_ERR_ABORTED";
187
187
  }
188
188
  };
189
189
  var InformationalError = class _InformationalError extends UndiciError {
190
- constructor(message3) {
191
- super(message3);
190
+ constructor(message4) {
191
+ super(message4);
192
192
  Error.captureStackTrace(this, _InformationalError);
193
193
  this.name = "InformationalError";
194
- this.message = message3 || "Request information";
194
+ this.message = message4 || "Request information";
195
195
  this.code = "UND_ERR_INFO";
196
196
  }
197
197
  };
198
198
  var RequestContentLengthMismatchError = class _RequestContentLengthMismatchError extends UndiciError {
199
- constructor(message3) {
200
- super(message3);
199
+ constructor(message4) {
200
+ super(message4);
201
201
  Error.captureStackTrace(this, _RequestContentLengthMismatchError);
202
202
  this.name = "RequestContentLengthMismatchError";
203
- this.message = message3 || "Request body length does not match content-length header";
203
+ this.message = message4 || "Request body length does not match content-length header";
204
204
  this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
205
205
  }
206
206
  };
207
207
  var ResponseContentLengthMismatchError = class _ResponseContentLengthMismatchError extends UndiciError {
208
- constructor(message3) {
209
- super(message3);
208
+ constructor(message4) {
209
+ super(message4);
210
210
  Error.captureStackTrace(this, _ResponseContentLengthMismatchError);
211
211
  this.name = "ResponseContentLengthMismatchError";
212
- this.message = message3 || "Response body length does not match content-length header";
212
+ this.message = message4 || "Response body length does not match content-length header";
213
213
  this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
214
214
  }
215
215
  };
216
216
  var ClientDestroyedError = class _ClientDestroyedError extends UndiciError {
217
- constructor(message3) {
218
- super(message3);
217
+ constructor(message4) {
218
+ super(message4);
219
219
  Error.captureStackTrace(this, _ClientDestroyedError);
220
220
  this.name = "ClientDestroyedError";
221
- this.message = message3 || "The client is destroyed";
221
+ this.message = message4 || "The client is destroyed";
222
222
  this.code = "UND_ERR_DESTROYED";
223
223
  }
224
224
  };
225
225
  var ClientClosedError = class _ClientClosedError extends UndiciError {
226
- constructor(message3) {
227
- super(message3);
226
+ constructor(message4) {
227
+ super(message4);
228
228
  Error.captureStackTrace(this, _ClientClosedError);
229
229
  this.name = "ClientClosedError";
230
- this.message = message3 || "The client is closed";
230
+ this.message = message4 || "The client is closed";
231
231
  this.code = "UND_ERR_CLOSED";
232
232
  }
233
233
  };
234
234
  var SocketError = class _SocketError extends UndiciError {
235
- constructor(message3, socket) {
236
- super(message3);
235
+ constructor(message4, socket) {
236
+ super(message4);
237
237
  Error.captureStackTrace(this, _SocketError);
238
238
  this.name = "SocketError";
239
- this.message = message3 || "Socket error";
239
+ this.message = message4 || "Socket error";
240
240
  this.code = "UND_ERR_SOCKET";
241
241
  this.socket = socket;
242
242
  }
243
243
  };
244
244
  var NotSupportedError = class _NotSupportedError extends UndiciError {
245
- constructor(message3) {
246
- super(message3);
245
+ constructor(message4) {
246
+ super(message4);
247
247
  Error.captureStackTrace(this, _NotSupportedError);
248
248
  this.name = "NotSupportedError";
249
- this.message = message3 || "Not supported error";
249
+ this.message = message4 || "Not supported error";
250
250
  this.code = "UND_ERR_NOT_SUPPORTED";
251
251
  }
252
252
  };
253
253
  var BalancedPoolMissingUpstreamError = class extends UndiciError {
254
- constructor(message3) {
255
- super(message3);
254
+ constructor(message4) {
255
+ super(message4);
256
256
  Error.captureStackTrace(this, NotSupportedError);
257
257
  this.name = "MissingUpstreamError";
258
- this.message = message3 || "No upstream has been added to the BalancedPool";
258
+ this.message = message4 || "No upstream has been added to the BalancedPool";
259
259
  this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
260
260
  }
261
261
  };
262
262
  var HTTPParserError = class _HTTPParserError extends Error {
263
- constructor(message3, code, data) {
264
- super(message3);
263
+ constructor(message4, code, data) {
264
+ super(message4);
265
265
  Error.captureStackTrace(this, _HTTPParserError);
266
266
  this.name = "HTTPParserError";
267
267
  this.code = code ? `HPE_${code}` : void 0;
@@ -269,20 +269,20 @@ var require_errors = __commonJS({
269
269
  }
270
270
  };
271
271
  var ResponseExceededMaxSizeError = class _ResponseExceededMaxSizeError extends UndiciError {
272
- constructor(message3) {
273
- super(message3);
272
+ constructor(message4) {
273
+ super(message4);
274
274
  Error.captureStackTrace(this, _ResponseExceededMaxSizeError);
275
275
  this.name = "ResponseExceededMaxSizeError";
276
- this.message = message3 || "Response content exceeded max size";
276
+ this.message = message4 || "Response content exceeded max size";
277
277
  this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
278
278
  }
279
279
  };
280
280
  var RequestRetryError = class _RequestRetryError extends UndiciError {
281
- constructor(message3, code, { headers, data }) {
282
- super(message3);
281
+ constructor(message4, code, { headers, data }) {
282
+ super(message4);
283
283
  Error.captureStackTrace(this, _RequestRetryError);
284
284
  this.name = "RequestRetryError";
285
- this.message = message3 || "Request retry error";
285
+ this.message = message4 || "Request retry error";
286
286
  this.code = "UND_ERR_REQ_RETRY";
287
287
  this.statusCode = code;
288
288
  this.data = data;
@@ -3761,15 +3761,15 @@ var require_webidl = __commonJS({
3761
3761
  webidl.converters = {};
3762
3762
  webidl.util = {};
3763
3763
  webidl.errors = {};
3764
- webidl.errors.exception = function(message3) {
3765
- return new TypeError(`${message3.header}: ${message3.message}`);
3764
+ webidl.errors.exception = function(message4) {
3765
+ return new TypeError(`${message4.header}: ${message4.message}`);
3766
3766
  };
3767
3767
  webidl.errors.conversionFailed = function(context) {
3768
3768
  const plural = context.types.length === 1 ? "" : " one of";
3769
- const message3 = `${context.argument} could not be converted to${plural}: ${context.types.join(", ")}.`;
3769
+ const message4 = `${context.argument} could not be converted to${plural}: ${context.types.join(", ")}.`;
3770
3770
  return webidl.errors.exception({
3771
3771
  header: context.prefix,
3772
- message: message3
3772
+ message: message4
3773
3773
  });
3774
3774
  };
3775
3775
  webidl.errors.invalidArgument = function(context) {
@@ -6911,12 +6911,12 @@ var require_client = __commonJS({
6911
6911
  socket.unshift(data.slice(offset));
6912
6912
  } else if (ret !== constants.ERROR.OK) {
6913
6913
  const ptr = llhttp.llhttp_get_error_reason(this.ptr);
6914
- let message3 = "";
6914
+ let message4 = "";
6915
6915
  if (ptr) {
6916
6916
  const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
6917
- message3 = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
6917
+ message4 = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
6918
6918
  }
6919
- throw new HTTPParserError(message3, constants.ERROR[ret], data.slice(offset));
6919
+ throw new HTTPParserError(message4, constants.ERROR[ret], data.slice(offset));
6920
6920
  }
6921
6921
  } catch (err) {
6922
6922
  util.destroy(socket, err);
@@ -9762,11 +9762,11 @@ var require_mock_errors = __commonJS({
9762
9762
  "use strict";
9763
9763
  var { UndiciError } = require_errors();
9764
9764
  var MockNotMatchedError = class _MockNotMatchedError extends UndiciError {
9765
- constructor(message3) {
9766
- super(message3);
9765
+ constructor(message4) {
9766
+ super(message4);
9767
9767
  Error.captureStackTrace(this, _MockNotMatchedError);
9768
9768
  this.name = "MockNotMatchedError";
9769
- this.message = message3 || "The request does not match any registered mock dispatches";
9769
+ this.message = message4 || "The request does not match any registered mock dispatches";
9770
9770
  this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
9771
9771
  }
9772
9772
  };
@@ -18118,12 +18118,12 @@ var require_errors2 = __commonJS({
18118
18118
  }
18119
18119
  return [E.schemaPath, schPath];
18120
18120
  }
18121
- function extraErrorProps(cxt, { params, message: message3 }, keyValues) {
18121
+ function extraErrorProps(cxt, { params, message: message4 }, keyValues) {
18122
18122
  const { keyword, data, schemaValue, it } = cxt;
18123
18123
  const { opts, propertyName, topSchemaRef, schemaPath } = it;
18124
18124
  keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
18125
18125
  if (opts.messages) {
18126
- keyValues.push([E.message, typeof message3 == "function" ? message3(cxt) : message3]);
18126
+ keyValues.push([E.message, typeof message4 == "function" ? message4(cxt) : message4]);
18127
18127
  }
18128
18128
  if (opts.verbose) {
18129
18129
  keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
@@ -20949,11 +20949,11 @@ var require_core = __commonJS({
20949
20949
  }
20950
20950
  const valid = this.validate($schema, schema2);
20951
20951
  if (!valid && throwOrLogError) {
20952
- const message3 = "schema is invalid: " + this.errorsText();
20952
+ const message4 = "schema is invalid: " + this.errorsText();
20953
20953
  if (this.opts.validateSchema === "log")
20954
- this.logger.error(message3);
20954
+ this.logger.error(message4);
20955
20955
  else
20956
- throw new Error(message3);
20956
+ throw new Error(message4);
20957
20957
  }
20958
20958
  return valid;
20959
20959
  }
@@ -24512,8 +24512,8 @@ var FetchHttpClient = class {
24512
24512
  var import_promises = __toESM(require("node:fs/promises"), 1);
24513
24513
  var import_node_path = __toESM(require("node:path"), 1);
24514
24514
  var TlsConfigError = class extends Error {
24515
- constructor(message3) {
24516
- super(message3);
24515
+ constructor(message4) {
24516
+ super(message4);
24517
24517
  this.name = "TlsConfigError";
24518
24518
  }
24519
24519
  };
@@ -25760,14 +25760,14 @@ function prefixIssues(path35, issues) {
25760
25760
  return iss;
25761
25761
  });
25762
25762
  }
25763
- function unwrapMessage(message3) {
25764
- return typeof message3 === "string" ? message3 : message3?.message;
25763
+ function unwrapMessage(message4) {
25764
+ return typeof message4 === "string" ? message4 : message4?.message;
25765
25765
  }
25766
25766
  function finalizeIssue(iss, ctx, config2) {
25767
- const message3 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
25767
+ const message4 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
25768
25768
  const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
25769
25769
  rest.path ?? (rest.path = []);
25770
- rest.message = message3;
25770
+ rest.message = message4;
25771
25771
  if (ctx?.reportInput) {
25772
25772
  rest.input = _input;
25773
25773
  }
@@ -39684,6 +39684,23 @@ var pythonConfigSchema = external_exports.object({
39684
39684
  * User-scope only for the same reason as `uvPath`: it names a program that gets run.
39685
39685
  */
39686
39686
  interpreterPath: external_exports.string(),
39687
+ /**
39688
+ * A running Jupyter kernel to execute tools **inside**, named by its connection file.
39689
+ *
39690
+ * Set so a notebook can drive Light Code and have its tools see the session's own state —
39691
+ * the dataframe already loaded, the model already fitted. With it, a tool call is executed
39692
+ * in that kernel rather than in this worker's own interpreter.
39693
+ *
39694
+ * **The notebook names it; nothing here guesses.** A kernel knows its own connection file
39695
+ * and nothing outside it does, so with two kernels running a guess means executing inside
39696
+ * the wrong notebook. See `python/jupyter.ts` for the argument and for the one line a
39697
+ * notebook needs.
39698
+ *
39699
+ * Covered by `python` being user-scope only (invariant 5), and it belongs there on its own
39700
+ * merits: a repository able to set it would run this machine's approved tools against a
39701
+ * session of its choosing.
39702
+ */
39703
+ jupyterConnectionFile: external_exports.string(),
39687
39704
  /**
39688
39705
  * Package index for tool dependencies. §3 treats `uv` resolving PyPI as *our* egress
39689
39706
  * rather than the user's, so pointing it at an internal mirror is the expected
@@ -40491,8 +40508,8 @@ var configSchema = external_exports.object({
40491
40508
  }).partial();
40492
40509
  var ConfigValidationError = class extends Error {
40493
40510
  issues;
40494
- constructor(message3, issues) {
40495
- super(message3);
40511
+ constructor(message4, issues) {
40512
+ super(message4);
40496
40513
  this.issues = issues;
40497
40514
  this.name = "ConfigValidationError";
40498
40515
  }
@@ -40773,6 +40790,16 @@ function isSubsequence(needle, haystack) {
40773
40790
  return false;
40774
40791
  }
40775
40792
 
40793
+ // ../../packages/core/dist/context/mentionGlob.js
40794
+ function mentionSegment(query) {
40795
+ const trimmed = query.trim();
40796
+ const separator = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
40797
+ return trimmed.slice(separator + 1);
40798
+ }
40799
+
40800
+ // ../../packages/core/dist/python/jupyter.js
40801
+ var JUPYTER_CONNECTION_ENV = "LIGHT_CODE_JUPYTER_CONNECTION_FILE";
40802
+
40776
40803
  // ../../packages/core/dist/guide/steps.js
40777
40804
  var GUIDE_STEPS = [
40778
40805
  {
@@ -41357,22 +41384,22 @@ var Logger = class {
41357
41384
  this.knownSecrets = options.knownSecrets ?? (() => []);
41358
41385
  this.sink = options.sink ?? ((line) => console.log(line));
41359
41386
  }
41360
- debug(message3, ...args) {
41361
- this.write("debug", message3, args);
41387
+ debug(message4, ...args) {
41388
+ this.write("debug", message4, args);
41362
41389
  }
41363
- info(message3, ...args) {
41364
- this.write("info", message3, args);
41390
+ info(message4, ...args) {
41391
+ this.write("info", message4, args);
41365
41392
  }
41366
- warn(message3, ...args) {
41367
- this.write("warn", message3, args);
41393
+ warn(message4, ...args) {
41394
+ this.write("warn", message4, args);
41368
41395
  }
41369
- error(message3, ...args) {
41370
- this.write("error", message3, args);
41396
+ error(message4, ...args) {
41397
+ this.write("error", message4, args);
41371
41398
  }
41372
- write(level, message3, args) {
41399
+ write(level, message4, args) {
41373
41400
  if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level])
41374
41401
  return;
41375
- const rendered = [message3, ...args.map(formatArg)].join(" ");
41402
+ const rendered = [message4, ...args.map(formatArg)].join(" ");
41376
41403
  this.sink(`[${level}] ${redact(rendered, this.knownSecrets())}`);
41377
41404
  }
41378
41405
  };
@@ -41757,8 +41784,8 @@ function readPath2(source, dottedPath) {
41757
41784
  }, source);
41758
41785
  }
41759
41786
  var ApigeeAuthError = class extends Error {
41760
- constructor(message3) {
41761
- super(message3);
41787
+ constructor(message4) {
41788
+ super(message4);
41762
41789
  this.name = "ApigeeAuthError";
41763
41790
  }
41764
41791
  };
@@ -41890,7 +41917,7 @@ function describeTlsError(error51) {
41890
41917
  chain.push(current);
41891
41918
  current = current.cause;
41892
41919
  }
41893
- const message3 = error51 instanceof Error ? error51.message : String(error51);
41920
+ const message4 = error51 instanceof Error ? error51.message : String(error51);
41894
41921
  const combined = chain.map((link) => `${link.code ?? ""} ${link instanceof Error ? link.message : String(link)}`).join(" ");
41895
41922
  if (/UNABLE_TO_VERIFY_LEAF_SIGNATURE|SELF_SIGNED_CERT|UNABLE_TO_GET_ISSUER_CERT|unable to get local issuer|unable to verify the first certificate/i.test(combined)) {
41896
41923
  return "the server certificate could not be verified. If your network intercepts TLS, add the corporate root CA (caFile, or NODE_EXTRA_CA_CERTS).";
@@ -41912,7 +41939,7 @@ function describeTlsError(error51) {
41912
41939
  }
41913
41940
  const deepest = chain[chain.length - 1];
41914
41941
  const deepestMessage = deepest instanceof Error ? deepest.message : String(deepest);
41915
- return message3 === "fetch failed" && deepestMessage !== message3 ? deepestMessage : message3;
41942
+ return message4 === "fetch failed" && deepestMessage !== message4 ? deepestMessage : message4;
41916
41943
  }
41917
41944
 
41918
41945
  // ../../packages/core/dist/providers/auth/certs.js
@@ -41920,8 +41947,8 @@ var import_node_crypto2 = __toESM(require("node:crypto"), 1);
41920
41947
  var import_promises3 = __toESM(require("node:fs/promises"), 1);
41921
41948
  var import_node_path6 = __toESM(require("node:path"), 1);
41922
41949
  var CertError = class extends Error {
41923
- constructor(message3) {
41924
- super(message3);
41950
+ constructor(message4) {
41951
+ super(message4);
41925
41952
  this.name = "CertError";
41926
41953
  }
41927
41954
  };
@@ -41960,11 +41987,11 @@ function assertKeyMatchesCert(cert, key, passphrase) {
41960
41987
  try {
41961
41988
  privateKey = import_node_crypto2.default.createPrivateKey(passphrase !== void 0 ? { key, passphrase } : { key });
41962
41989
  } catch (error51) {
41963
- const message3 = error51 instanceof Error ? error51.message : String(error51);
41964
- if (/bad decrypt|bad password|passphrase/i.test(message3)) {
41990
+ const message4 = error51 instanceof Error ? error51.message : String(error51);
41991
+ if (/bad decrypt|bad password|passphrase/i.test(message4)) {
41965
41992
  throw new CertError("The private key is encrypted and the passphrase is missing or wrong.");
41966
41993
  }
41967
- throw new CertError(`The private key could not be parsed: ${message3}`);
41994
+ throw new CertError(`The private key could not be parsed: ${message4}`);
41968
41995
  }
41969
41996
  const probe2 = Buffer.from("light-code-key-match-probe");
41970
41997
  try {
@@ -42031,8 +42058,8 @@ function checkExpiry(notAfter, now = /* @__PURE__ */ new Date()) {
42031
42058
 
42032
42059
  // ../../packages/core/dist/providers/auth/factory.js
42033
42060
  var AuthConfigError = class extends Error {
42034
- constructor(message3) {
42035
- super(message3);
42061
+ constructor(message4) {
42062
+ super(message4);
42036
42063
  this.name = "AuthConfigError";
42037
42064
  }
42038
42065
  };
@@ -42564,21 +42591,21 @@ function partialMarkerLength(buffer, marker) {
42564
42591
  function describeRequestError(error51, url2) {
42565
42592
  return `Could not reach ${url2}: ${describeTlsError(error51)}`;
42566
42593
  }
42567
- function toWireMessage(message3) {
42568
- if (message3.role === "user" && message3.images !== void 0 && message3.images.length > 0) {
42569
- const parts = message3.images.map((image) => ({
42594
+ function toWireMessage(message4) {
42595
+ if (message4.role === "user" && message4.images !== void 0 && message4.images.length > 0) {
42596
+ const parts = message4.images.map((image) => ({
42570
42597
  type: "image_url",
42571
42598
  image_url: { url: `data:${image.mediaType};base64,${image.data}` }
42572
42599
  }));
42573
- if (message3.content.length > 0)
42574
- parts.push({ type: "text", text: message3.content });
42600
+ if (message4.content.length > 0)
42601
+ parts.push({ type: "text", text: message4.content });
42575
42602
  return { role: "user", content: parts };
42576
42603
  }
42577
- if (message3.role === "assistant") {
42578
- const wire = { role: "assistant", content: message3.content };
42579
- if (message3.toolCalls !== void 0 && message3.toolCalls.length > 0) {
42580
- wire.content = message3.content.length > 0 ? message3.content : null;
42581
- wire.tool_calls = message3.toolCalls.map((call) => ({
42604
+ if (message4.role === "assistant") {
42605
+ const wire = { role: "assistant", content: message4.content };
42606
+ if (message4.toolCalls !== void 0 && message4.toolCalls.length > 0) {
42607
+ wire.content = message4.content.length > 0 ? message4.content : null;
42608
+ wire.tool_calls = message4.toolCalls.map((call) => ({
42582
42609
  id: call.id,
42583
42610
  type: "function",
42584
42611
  function: { name: call.name, arguments: call.arguments }
@@ -42586,10 +42613,10 @@ function toWireMessage(message3) {
42586
42613
  }
42587
42614
  return wire;
42588
42615
  }
42589
- if (message3.role === "tool") {
42590
- return { role: "tool", tool_call_id: message3.toolCallId, content: message3.content };
42616
+ if (message4.role === "tool") {
42617
+ return { role: "tool", tool_call_id: message4.toolCallId, content: message4.content };
42591
42618
  }
42592
- return { role: message3.role, content: message3.content };
42619
+ return { role: message4.role, content: message4.content };
42593
42620
  }
42594
42621
  var OpenAIProvider = class {
42595
42622
  http;
@@ -42845,13 +42872,13 @@ var AnthropicProvider = class {
42845
42872
  }
42846
42873
  };
42847
42874
  function toAnthropicMessages(messages) {
42848
- const system = messages.find((message3) => message3.role === "system")?.content;
42875
+ const system = messages.find((message4) => message4.role === "system")?.content;
42849
42876
  const wireMessages = [];
42850
- for (const message3 of messages) {
42851
- if (message3.role === "system")
42877
+ for (const message4 of messages) {
42878
+ if (message4.role === "system")
42852
42879
  continue;
42853
- if (message3.role === "tool") {
42854
- const block = { type: "tool_result", tool_use_id: message3.toolCallId, content: message3.content };
42880
+ if (message4.role === "tool") {
42881
+ const block = { type: "tool_result", tool_use_id: message4.toolCallId, content: message4.content };
42855
42882
  const previous = wireMessages[wireMessages.length - 1];
42856
42883
  if (previous?.role === "user" && Array.isArray(previous.content) && isToolResultBlocks(previous.content)) {
42857
42884
  ;
@@ -42861,16 +42888,16 @@ function toAnthropicMessages(messages) {
42861
42888
  }
42862
42889
  continue;
42863
42890
  }
42864
- if (message3.role === "user") {
42891
+ if (message4.role === "user") {
42865
42892
  const blocks2 = [];
42866
- for (const image of message3.images ?? []) {
42893
+ for (const image of message4.images ?? []) {
42867
42894
  blocks2.push({
42868
42895
  type: "image",
42869
42896
  source: { type: "base64", media_type: image.mediaType, data: image.data }
42870
42897
  });
42871
42898
  }
42872
- if (message3.content.length > 0)
42873
- blocks2.push({ type: "text", text: message3.content });
42899
+ if (message4.content.length > 0)
42900
+ blocks2.push({ type: "text", text: message4.content });
42874
42901
  const previous = wireMessages[wireMessages.length - 1];
42875
42902
  if (previous?.role === "user" && Array.isArray(previous.content)) {
42876
42903
  ;
@@ -42881,9 +42908,9 @@ function toAnthropicMessages(messages) {
42881
42908
  continue;
42882
42909
  }
42883
42910
  const blocks = [];
42884
- if (message3.content.length > 0)
42885
- blocks.push({ type: "text", text: message3.content });
42886
- for (const toolCall of message3.toolCalls ?? []) {
42911
+ if (message4.content.length > 0)
42912
+ blocks.push({ type: "text", text: message4.content });
42913
+ for (const toolCall of message4.toolCalls ?? []) {
42887
42914
  blocks.push({
42888
42915
  type: "tool_use",
42889
42916
  id: toolCall.id,
@@ -42971,9 +42998,9 @@ async function* parseAnthropicStream(body, url2, signal, logger) {
42971
42998
  return;
42972
42999
  } else if (eventType === "error") {
42973
43000
  const error51 = parsed.error;
42974
- const message3 = typeof error51?.message === "string" ? error51.message : "The provider reported an error.";
42975
- logger?.debug("anthropic stream error", message3);
42976
- yield { type: "error", error: message3 };
43001
+ const message4 = typeof error51?.message === "string" ? error51.message : "The provider reported an error.";
43002
+ logger?.debug("anthropic stream error", message4);
43003
+ yield { type: "error", error: message4 };
42977
43004
  return;
42978
43005
  }
42979
43006
  }
@@ -43078,26 +43105,26 @@ var GeminiProvider = class {
43078
43105
  };
43079
43106
  function buildIdToName(messages) {
43080
43107
  const map2 = /* @__PURE__ */ new Map();
43081
- for (const message3 of messages) {
43082
- if (message3.role !== "assistant")
43108
+ for (const message4 of messages) {
43109
+ if (message4.role !== "assistant")
43083
43110
  continue;
43084
- for (const toolCall of message3.toolCalls ?? [])
43111
+ for (const toolCall of message4.toolCalls ?? [])
43085
43112
  map2.set(toolCall.id, toolCall.name);
43086
43113
  }
43087
43114
  return map2;
43088
43115
  }
43089
43116
  function toGeminiContents(messages) {
43090
- const systemInstruction = messages.find((message3) => message3.role === "system")?.content;
43117
+ const systemInstruction = messages.find((message4) => message4.role === "system")?.content;
43091
43118
  const idToName = buildIdToName(messages);
43092
43119
  const contents = [];
43093
- for (const message3 of messages) {
43094
- if (message3.role === "system")
43120
+ for (const message4 of messages) {
43121
+ if (message4.role === "system")
43095
43122
  continue;
43096
- if (message3.role === "tool") {
43123
+ if (message4.role === "tool") {
43097
43124
  const part = {
43098
43125
  functionResponse: {
43099
- name: idToName.get(message3.toolCallId) ?? message3.toolCallId,
43100
- response: { result: message3.content }
43126
+ name: idToName.get(message4.toolCallId) ?? message4.toolCallId,
43127
+ response: { result: message4.content }
43101
43128
  }
43102
43129
  };
43103
43130
  const previous = contents[contents.length - 1];
@@ -43109,13 +43136,13 @@ function toGeminiContents(messages) {
43109
43136
  }
43110
43137
  continue;
43111
43138
  }
43112
- if (message3.role === "user") {
43139
+ if (message4.role === "user") {
43113
43140
  const parts2 = [];
43114
- for (const image of message3.images ?? []) {
43141
+ for (const image of message4.images ?? []) {
43115
43142
  parts2.push({ inlineData: { mimeType: image.mediaType, data: image.data } });
43116
43143
  }
43117
- if (message3.content.length > 0)
43118
- parts2.push({ text: message3.content });
43144
+ if (message4.content.length > 0)
43145
+ parts2.push({ text: message4.content });
43119
43146
  const previous = contents[contents.length - 1];
43120
43147
  if (previous?.role === "user" && Array.isArray(previous.parts)) {
43121
43148
  ;
@@ -43126,9 +43153,9 @@ function toGeminiContents(messages) {
43126
43153
  continue;
43127
43154
  }
43128
43155
  const parts = [];
43129
- if (message3.content.length > 0)
43130
- parts.push({ text: message3.content });
43131
- for (const toolCall of message3.toolCalls ?? []) {
43156
+ if (message4.content.length > 0)
43157
+ parts.push({ text: message4.content });
43158
+ for (const toolCall of message4.toolCalls ?? []) {
43132
43159
  parts.push({ functionCall: { name: toolCall.name, args: safeParseArguments2(toolCall.arguments) } });
43133
43160
  }
43134
43161
  if (parts.length > 0)
@@ -43230,23 +43257,23 @@ function computeBreakdown(messages, tools, contextWindow) {
43230
43257
  let system = 0;
43231
43258
  let history = 0;
43232
43259
  let results = 0;
43233
- for (const message3 of messages) {
43234
- if (message3.role === "system") {
43235
- system += estimateTokens(message3.content);
43260
+ for (const message4 of messages) {
43261
+ if (message4.role === "system") {
43262
+ system += estimateTokens(message4.content);
43236
43263
  continue;
43237
43264
  }
43238
- if (message3.role === "tool") {
43239
- results += estimateTokens(message3.content);
43265
+ if (message4.role === "tool") {
43266
+ results += estimateTokens(message4.content);
43240
43267
  continue;
43241
43268
  }
43242
- history += estimateTokens(message3.content);
43243
- if (message3.role === "assistant") {
43244
- for (const toolCall of message3.toolCalls ?? []) {
43269
+ history += estimateTokens(message4.content);
43270
+ if (message4.role === "assistant") {
43271
+ for (const toolCall of message4.toolCalls ?? []) {
43245
43272
  history += estimateTokens(toolCall.name) + estimateTokens(toolCall.arguments);
43246
43273
  }
43247
43274
  }
43248
- if (message3.role === "user") {
43249
- history += (message3.images?.length ?? 0) * 1e3;
43275
+ if (message4.role === "user") {
43276
+ history += (message4.images?.length ?? 0) * 1e3;
43250
43277
  }
43251
43278
  }
43252
43279
  const toolDefinitions = tools.reduce((total, tool) => total + estimateTokens(tool.name) + estimateTokens(tool.description) + estimateTokens(JSON.stringify(tool.parameters ?? {})), 0);
@@ -43274,10 +43301,10 @@ function readFilePath(argumentsJson) {
43274
43301
  }
43275
43302
  function dropSupersededReads(messages) {
43276
43303
  const keyByCallId = /* @__PURE__ */ new Map();
43277
- for (const message3 of messages) {
43278
- if (message3.role !== "assistant")
43304
+ for (const message4 of messages) {
43305
+ if (message4.role !== "assistant")
43279
43306
  continue;
43280
- for (const toolCall of message3.toolCalls ?? []) {
43307
+ for (const toolCall of message4.toolCalls ?? []) {
43281
43308
  if (toolCall.name !== "read_file")
43282
43309
  continue;
43283
43310
  const path35 = readFilePath(toolCall.arguments);
@@ -43287,27 +43314,27 @@ function dropSupersededReads(messages) {
43287
43314
  }
43288
43315
  }
43289
43316
  const lastCallIdForKey = /* @__PURE__ */ new Map();
43290
- for (const message3 of messages) {
43291
- if (message3.role !== "tool")
43317
+ for (const message4 of messages) {
43318
+ if (message4.role !== "tool")
43292
43319
  continue;
43293
- const key = keyByCallId.get(message3.toolCallId);
43320
+ const key = keyByCallId.get(message4.toolCallId);
43294
43321
  if (key !== void 0)
43295
- lastCallIdForKey.set(key, message3.toolCallId);
43322
+ lastCallIdForKey.set(key, message4.toolCallId);
43296
43323
  }
43297
43324
  const survivors = new Set(lastCallIdForKey.values());
43298
43325
  let supersededCount = 0;
43299
43326
  let charactersSaved = 0;
43300
- const result = messages.map((message3) => {
43301
- if (message3.role !== "tool")
43302
- return message3;
43303
- const key = keyByCallId.get(message3.toolCallId);
43304
- if (key === void 0 || survivors.has(message3.toolCallId))
43305
- return message3;
43306
- if (message3.content.length <= SUPERSEDED_MARKER.length)
43307
- return message3;
43327
+ const result = messages.map((message4) => {
43328
+ if (message4.role !== "tool")
43329
+ return message4;
43330
+ const key = keyByCallId.get(message4.toolCallId);
43331
+ if (key === void 0 || survivors.has(message4.toolCallId))
43332
+ return message4;
43333
+ if (message4.content.length <= SUPERSEDED_MARKER.length)
43334
+ return message4;
43308
43335
  supersededCount += 1;
43309
- charactersSaved += message3.content.length - SUPERSEDED_MARKER.length;
43310
- return { role: "tool", toolCallId: message3.toolCallId, content: SUPERSEDED_MARKER };
43336
+ charactersSaved += message4.content.length - SUPERSEDED_MARKER.length;
43337
+ return { role: "tool", toolCallId: message4.toolCallId, content: SUPERSEDED_MARKER };
43311
43338
  });
43312
43339
  return { messages: result, supersededCount, charactersSaved };
43313
43340
  }
@@ -43319,10 +43346,10 @@ var FORGET_DOCS_TOOL = "forget_docs";
43319
43346
  function dropEvictedDocs(messages) {
43320
43347
  let cutoff = -1;
43321
43348
  const evictableCallIds = /* @__PURE__ */ new Set();
43322
- messages.forEach((message3, index) => {
43323
- if (message3.role !== "assistant")
43349
+ messages.forEach((message4, index) => {
43350
+ if (message4.role !== "assistant")
43324
43351
  return;
43325
- for (const toolCall of message3.toolCalls ?? []) {
43352
+ for (const toolCall of message4.toolCalls ?? []) {
43326
43353
  if (toolCall.name === FORGET_DOCS_TOOL)
43327
43354
  cutoff = index;
43328
43355
  else if (EVICTABLE_TOOLS.has(toolCall.name))
@@ -43334,16 +43361,16 @@ function dropEvictedDocs(messages) {
43334
43361
  }
43335
43362
  let evictedCount = 0;
43336
43363
  let charactersSaved = 0;
43337
- const result = messages.map((message3, index) => {
43338
- if (message3.role !== "tool" || index > cutoff)
43339
- return message3;
43340
- if (!evictableCallIds.has(message3.toolCallId))
43341
- return message3;
43342
- if (message3.content.length <= EVICTED_MARKER.length)
43343
- return message3;
43364
+ const result = messages.map((message4, index) => {
43365
+ if (message4.role !== "tool" || index > cutoff)
43366
+ return message4;
43367
+ if (!evictableCallIds.has(message4.toolCallId))
43368
+ return message4;
43369
+ if (message4.content.length <= EVICTED_MARKER.length)
43370
+ return message4;
43344
43371
  evictedCount += 1;
43345
- charactersSaved += message3.content.length - EVICTED_MARKER.length;
43346
- return { role: "tool", toolCallId: message3.toolCallId, content: EVICTED_MARKER };
43372
+ charactersSaved += message4.content.length - EVICTED_MARKER.length;
43373
+ return { role: "tool", toolCallId: message4.toolCallId, content: EVICTED_MARKER };
43347
43374
  });
43348
43375
  return { messages: result, evictedCount, charactersSaved };
43349
43376
  }
@@ -43471,25 +43498,25 @@ function isSafeBoundary(messages, index) {
43471
43498
  return false;
43472
43499
  const callIdsBefore = /* @__PURE__ */ new Set();
43473
43500
  for (let i = 0; i < index; i += 1) {
43474
- const message3 = messages[i];
43475
- if (message3?.role === "assistant") {
43476
- for (const toolCall of message3.toolCalls ?? [])
43501
+ const message4 = messages[i];
43502
+ if (message4?.role === "assistant") {
43503
+ for (const toolCall of message4.toolCalls ?? [])
43477
43504
  callIdsBefore.add(toolCall.id);
43478
43505
  }
43479
- if (message3?.role === "tool")
43480
- callIdsBefore.delete(message3.toolCallId);
43506
+ if (message4?.role === "tool")
43507
+ callIdsBefore.delete(message4.toolCallId);
43481
43508
  }
43482
43509
  return callIdsBefore.size === 0;
43483
43510
  }
43484
43511
  function buildSummaryPrompt(messages) {
43485
- const transcript = messages.map((message3) => {
43486
- if (message3.role === "tool")
43487
- return `[tool result] ${message3.content}`;
43488
- if (message3.role === "assistant") {
43489
- const calls = (message3.toolCalls ?? []).map((call) => `${call.name}(${call.arguments})`).join(", ");
43490
- return `[assistant] ${message3.content}${calls.length > 0 ? ` -> ${calls}` : ""}`;
43491
- }
43492
- return `[${message3.role}] ${message3.content}`;
43512
+ const transcript = messages.map((message4) => {
43513
+ if (message4.role === "tool")
43514
+ return `[tool result] ${message4.content}`;
43515
+ if (message4.role === "assistant") {
43516
+ const calls = (message4.toolCalls ?? []).map((call) => `${call.name}(${call.arguments})`).join(", ");
43517
+ return `[assistant] ${message4.content}${calls.length > 0 ? ` -> ${calls}` : ""}`;
43518
+ }
43519
+ return `[${message4.role}] ${message4.content}`;
43493
43520
  }).join("\n");
43494
43521
  return [
43495
43522
  "Summarise the earlier part of this coding session so it can replace the original",
@@ -43511,8 +43538,8 @@ function buildSummaryPrompt(messages) {
43511
43538
  ].join("\n");
43512
43539
  }
43513
43540
  var SUMMARY_PREFIX = "[Earlier in this session \u2014 summarised to save context]\n";
43514
- function isSummaryMessage(message3) {
43515
- return message3.role === "user" && message3.content.startsWith(SUMMARY_PREFIX);
43541
+ function isSummaryMessage(message4) {
43542
+ return message4.role === "user" && message4.content.startsWith(SUMMARY_PREFIX);
43516
43543
  }
43517
43544
  function shouldCompact(messages, estimatedTokens, contextWindow, options = {}) {
43518
43545
  const trigger = options.triggerFraction ?? DEFAULTS2.triggerFraction;
@@ -43526,8 +43553,8 @@ function shouldCompact(messages, estimatedTokens, contextWindow, options = {}) {
43526
43553
  async function compactHistory(messages, provider, options = {}) {
43527
43554
  const keepRecent = options.keepRecent ?? DEFAULTS2.keepRecent;
43528
43555
  const unchanged = { messages: [...messages], compacted: false, summarisedCount: 0 };
43529
- const systemMessages = messages.filter((message3) => message3.role === "system");
43530
- const rest = messages.filter((message3) => message3.role !== "system");
43556
+ const systemMessages = messages.filter((message4) => message4.role === "system");
43557
+ const rest = messages.filter((message4) => message4.role !== "system");
43531
43558
  if (rest.length <= keepRecent)
43532
43559
  return unchanged;
43533
43560
  const boundary = findSafeBoundary(rest, rest.length - keepRecent);
@@ -43549,7 +43576,7 @@ async function compactHistory(messages, provider, options = {}) {
43549
43576
  if (summary.trim().length === 0)
43550
43577
  return unchanged;
43551
43578
  const summaryMessage = { role: "user", content: `${SUMMARY_PREFIX}${summary.trim()}` };
43552
- const before = toSummarise.reduce((total, message3) => total + estimateTokens(message3.content), 0);
43579
+ const before = toSummarise.reduce((total, message4) => total + estimateTokens(message4.content), 0);
43553
43580
  if (estimateTokens(summaryMessage.content) >= before)
43554
43581
  return unchanged;
43555
43582
  return {
@@ -43580,8 +43607,8 @@ var Conversation = class {
43580
43607
  * was written, and a stale prompt would describe a world that no longer exists.
43581
43608
  */
43582
43609
  restore(messages) {
43583
- const systemPrompt = this.messages.find((message3) => message3.role === "system");
43584
- const restored = messages.filter((message3) => message3.role !== "system");
43610
+ const systemPrompt = this.messages.find((message4) => message4.role === "system");
43611
+ const restored = messages.filter((message4) => message4.role !== "system");
43585
43612
  this.messages = systemPrompt !== void 0 ? [systemPrompt, ...restored] : [...restored];
43586
43613
  this.compaction = void 0;
43587
43614
  }
@@ -43590,7 +43617,7 @@ var Conversation = class {
43590
43617
  this.restore([]);
43591
43618
  }
43592
43619
  isEmpty() {
43593
- return this.messages.every((message3) => message3.role === "system");
43620
+ return this.messages.every((message4) => message4.role === "system");
43594
43621
  }
43595
43622
  /**
43596
43623
  * Replaces the system prompt, keeping the rest of the history.
@@ -43601,7 +43628,7 @@ var Conversation = class {
43601
43628
  * doing it per turn would be expensive and invisible.
43602
43629
  */
43603
43630
  setSystemPrompt(prompt) {
43604
- const existing = this.messages.findIndex((message3) => message3.role === "system");
43631
+ const existing = this.messages.findIndex((message4) => message4.role === "system");
43605
43632
  if (existing === -1)
43606
43633
  this.messages.unshift({ role: "system", content: prompt });
43607
43634
  else
@@ -43609,7 +43636,7 @@ var Conversation = class {
43609
43636
  }
43610
43637
  /** The current system prompt, so a caller can tell whether it needs replacing. */
43611
43638
  systemPrompt() {
43612
- return this.messages.find((message3) => message3.role === "system")?.content;
43639
+ return this.messages.find((message4) => message4.role === "system")?.content;
43613
43640
  }
43614
43641
  addUserMessage(content, images) {
43615
43642
  this.messages.push(images !== void 0 && images.length > 0 ? { role: "user", content, images } : { role: "user", content });
@@ -43639,8 +43666,8 @@ var Conversation = class {
43639
43666
  const compaction = this.compaction;
43640
43667
  if (compaction === void 0)
43641
43668
  return [...this.messages];
43642
- const system = this.messages.filter((message3) => message3.role === "system");
43643
- const rest = this.messages.filter((message3) => message3.role !== "system");
43669
+ const system = this.messages.filter((message4) => message4.role === "system");
43670
+ const rest = this.messages.filter((message4) => message4.role !== "system");
43644
43671
  return [...system, compaction.summary, ...rest.slice(compaction.replacedCount)];
43645
43672
  }
43646
43673
  /**
@@ -45128,7 +45155,28 @@ function matchRiskyCommand(command, rules) {
45128
45155
  // ../../packages/core/dist/approval/safeCommands.js
45129
45156
  var SHELL_METACHARACTERS = [";", "&", "|", ">", "<", "`", "$", "(", ")", "{", "}", "\n", "\r"];
45130
45157
  var DEFAULT_SAFE_COMMANDS = [
45131
- // Reading and printing.
45158
+ /*
45159
+ * ## Windows first, because that is where this runs
45160
+ *
45161
+ * Reported from real use: Auto mode still asked about "a lot of read-only commands". The list
45162
+ * was written entirely in Unix program names, and `execute_command` spawns with `shell: true`,
45163
+ * which on Windows is `%ComSpec%` - **cmd.exe**. So the two commonest read-only operations on
45164
+ * the primary platform, `type` and `findstr`, were not on the list at all, and neither was
45165
+ * anything else cmd provides.
45166
+ *
45167
+ * This is the same fault as 0.104.0's, one level up: that one covered `python` and missed
45168
+ * `py`, `python.exe` and an interpreter reached by path. This one covered `cat` and `grep` and
45169
+ * missed the shell they would have to run in. **Every miss is a prompt, and enough of them is
45170
+ * the mode being unusable rather than careful.**
45171
+ */
45172
+ // Reading and printing - cmd.exe.
45173
+ "type ",
45174
+ "more ",
45175
+ "tree",
45176
+ "vol",
45177
+ "ver",
45178
+ "chdir",
45179
+ // Reading and printing - POSIX, and the same names under Git Bash or WSL.
45132
45180
  "ls",
45133
45181
  "dir ",
45134
45182
  "pwd",
@@ -45141,15 +45189,59 @@ var DEFAULT_SAFE_COMMANDS = [
45141
45189
  "echo ",
45142
45190
  "which ",
45143
45191
  "where ",
45144
- "sed -n",
45192
+ "whoami",
45193
+ "hostname",
45194
+ "uname",
45195
+ /*
45196
+ * `date /t` and not `date`. In cmd.exe a bare `date` **prompts** for a new one and waits on
45197
+ * stdin, so auto-approving it would hang the tool until its timeout and report that as the
45198
+ * command being slow. `/t` prints and exits. POSIX `date` prints either way, and a shell that
45199
+ * has it will not have been reached by this entry.
45200
+ */
45201
+ "date /t",
45202
+ "printenv",
45203
+ "basename ",
45204
+ "dirname ",
45205
+ "realpath ",
45206
+ "readlink ",
45207
+ "nl ",
45208
+ "cut ",
45209
+ "comm ",
45210
+ "paste ",
45145
45211
  "sort ",
45146
45212
  "uniq ",
45147
45213
  "diff ",
45148
- // Searching. `find` is deliberately absent — see the note above.
45214
+ "cmp ",
45215
+ "du ",
45216
+ "df ",
45217
+ /*
45218
+ * `sed -n` and not `sed`, deliberately. `sed -i` edits in place - the program is only
45219
+ * read-only in part, so the phrase is what gets vouched for rather than the name. Same reason
45220
+ * `git status` is here and `git` is not.
45221
+ */
45222
+ "sed -n",
45223
+ // Hashes and dumps, for "is this the same file".
45224
+ "md5sum ",
45225
+ "sha1sum ",
45226
+ "sha256sum ",
45227
+ "cksum ",
45228
+ "od ",
45229
+ "xxd ",
45230
+ "certutil -hashfile",
45231
+ // Searching. `find` is deliberately absent - see the note above.
45149
45232
  "grep ",
45233
+ "findstr ",
45150
45234
  "rg ",
45151
45235
  "fd ",
45152
- // Git, read-only subcommands only.
45236
+ "ag ",
45237
+ /*
45238
+ * ## Git, read-only subcommands only
45239
+ *
45240
+ * Named one phrase at a time rather than trusting the program, because `git` as a whole is
45241
+ * emphatically not read-only. Anything that writes a ref, an object or the working tree is
45242
+ * absent: no `tag` (it lists with no argument and *creates* with one, and a prefix cannot tell
45243
+ * them apart), no `stash` beyond `list`, no `fetch`, no `checkout`, no `restore`.
45244
+ */
45153
45245
  "git status",
45154
45246
  "git log",
45155
45247
  "git diff",
@@ -45157,27 +45249,188 @@ var DEFAULT_SAFE_COMMANDS = [
45157
45249
  "git branch",
45158
45250
  "git blame",
45159
45251
  "git remote -v",
45160
- // Versions and compiling. Compiling is not executing; `python -c` and `python <file>` are.
45252
+ "git rev-parse",
45253
+ "git rev-list",
45254
+ "git ls-files",
45255
+ "git ls-tree",
45256
+ "git ls-remote",
45257
+ "git for-each-ref",
45258
+ "git show-ref",
45259
+ "git symbolic-ref",
45260
+ "git cat-file",
45261
+ "git describe",
45262
+ "git shortlog",
45263
+ "git name-rev",
45264
+ "git whatchanged",
45265
+ "git diff-tree",
45266
+ "git grep",
45267
+ "git check-ignore",
45268
+ "git count-objects",
45269
+ "git stash list",
45270
+ "git config --get",
45271
+ "git config --list",
45272
+ "git --version",
45273
+ /*
45274
+ * ## Versions
45275
+ *
45276
+ * A version flag cannot be made to do anything else, and "which toolchain is this" is the
45277
+ * question an agent asks first in an unfamiliar repository.
45278
+ */
45161
45279
  "python --version",
45162
45280
  "python3 --version",
45163
- "python -m py_compile",
45164
- "python3 -m py_compile",
45281
+ "py --version",
45282
+ "python -V",
45283
+ "python3 -V",
45284
+ "py -V",
45165
45285
  "node --version",
45286
+ "node -v",
45166
45287
  "npm --version",
45288
+ "npm -v",
45167
45289
  "pnpm --version",
45290
+ "pnpm -v",
45291
+ "yarn --version",
45292
+ "npx --version",
45293
+ "pip --version",
45294
+ "tsc --version",
45295
+ "go version",
45296
+ "cargo --version",
45297
+ "rustc --version",
45298
+ "java -version",
45299
+ "javac -version",
45300
+ "dotnet --version",
45301
+ "dotnet --info",
45302
+ "ruby --version",
45303
+ "perl --version",
45304
+ "php --version",
45305
+ "terraform version",
45306
+ "docker --version",
45307
+ /*
45308
+ * ## Listing what is installed
45309
+ *
45310
+ * All read-only. `npm install` and friends are a long way from here: these are the query
45311
+ * subcommands, named individually for the same reason the git ones are.
45312
+ */
45313
+ "pip list",
45314
+ "pip show ",
45315
+ "pip freeze",
45316
+ "npm ls",
45317
+ "npm list",
45318
+ "pnpm list",
45319
+ "pnpm why ",
45320
+ /*
45321
+ * ## Compiling and checking, which is not running
45322
+ *
45323
+ * `python -m py_compile` is here because compiling is not executing; `python -c` is not,
45324
+ * because it is. `compileall` walks a tree and writes bytecode beside the sources without ever
45325
+ * importing them, and it is how anybody compiles a *project* rather than one file.
45326
+ *
45327
+ * **Three near-misses are deliberately absent, and each fails one of the two questions:**
45328
+ * `eslint` and `ruff check` both take `--fix` and rewrite the files, so the program can write
45329
+ * through its own flags; `black` writes unless `--check` is given, so only the phrase carrying
45330
+ * `--check` is vouched for; and `pytest` runs the code it collects, which is the second
45331
+ * question, not the first.
45332
+ */
45333
+ "python -m py_compile",
45334
+ "python3 -m py_compile",
45335
+ "py -m py_compile",
45336
+ "python -m compileall",
45337
+ "python3 -m compileall",
45338
+ "py -m compileall",
45339
+ "python -m json.tool",
45168
45340
  "tsc --noEmit",
45169
- "npx tsc --noEmit"
45341
+ "npx tsc --noEmit",
45342
+ "mypy ",
45343
+ "pyright ",
45344
+ "flake8 ",
45345
+ "pylint ",
45346
+ "black --check",
45347
+ "prettier --check",
45348
+ "cargo check",
45349
+ "go vet",
45350
+ "go build -n"
45170
45351
  ];
45171
45352
  function couldChain(command) {
45172
45353
  return SHELL_METACHARACTERS.some((character) => command.includes(character));
45173
45354
  }
45355
+ var INERT_PYTHON_FLAGS = {
45356
+ // Boolean: no value follows.
45357
+ "-B": 0,
45358
+ "-E": 0,
45359
+ "-I": 0,
45360
+ "-O": 0,
45361
+ "-OO": 0,
45362
+ "-P": 0,
45363
+ "-q": 0,
45364
+ "-S": 0,
45365
+ "-s": 0,
45366
+ "-u": 0,
45367
+ "-v": 0,
45368
+ // A value follows as a separate token. `-Xdev` and `-X dev` are both valid, so the glued
45369
+ // form is handled by prefix below rather than here.
45370
+ "-X": 1,
45371
+ "-W": 1
45372
+ };
45373
+ var PYTHON_PROGRAMS = /* @__PURE__ */ new Set(["python", "python3", "py"]);
45374
+ function stripInertPythonFlags(command) {
45375
+ const parts = command.split(" ");
45376
+ const program = parts[0];
45377
+ if (program === void 0 || !PYTHON_PROGRAMS.has(program.toLowerCase()))
45378
+ return command;
45379
+ const kept = [program];
45380
+ let index = 1;
45381
+ while (index < parts.length) {
45382
+ const part = parts[index];
45383
+ if (part === void 0)
45384
+ break;
45385
+ if (part.length === 0) {
45386
+ index += 1;
45387
+ continue;
45388
+ }
45389
+ const arity = INERT_PYTHON_FLAGS[part];
45390
+ if (arity !== void 0) {
45391
+ index += 1 + arity;
45392
+ continue;
45393
+ }
45394
+ if (/^-[XW]./.test(part)) {
45395
+ index += 1;
45396
+ continue;
45397
+ }
45398
+ if (program.toLowerCase() === "py" && /^-\d+(\.\d+)?(-(32|64|arm64))?$/.test(part)) {
45399
+ index += 1;
45400
+ continue;
45401
+ }
45402
+ break;
45403
+ }
45404
+ kept.push(...parts.slice(index));
45405
+ return kept.join(" ");
45406
+ }
45407
+ function normaliseProgram(command) {
45408
+ const trimmed = command.trim();
45409
+ let program;
45410
+ let rest;
45411
+ if (trimmed.startsWith('"')) {
45412
+ const close = trimmed.indexOf('"', 1);
45413
+ if (close === -1)
45414
+ return trimmed;
45415
+ program = trimmed.slice(1, close);
45416
+ rest = trimmed.slice(close + 1);
45417
+ } else {
45418
+ const space = trimmed.indexOf(" ");
45419
+ program = space === -1 ? trimmed : trimmed.slice(0, space);
45420
+ rest = space === -1 ? "" : trimmed.slice(space);
45421
+ }
45422
+ const lastSeparator = Math.max(program.lastIndexOf("/"), program.lastIndexOf("\\"));
45423
+ const base = program.slice(lastSeparator + 1);
45424
+ const bare = base.replace(/\.(exe|cmd|bat|com)$/i, "");
45425
+ return bare.length === 0 ? trimmed : bare + rest;
45426
+ }
45174
45427
  function isSafeCommand(command, options) {
45175
45428
  const trimmed = command.trim();
45176
45429
  if (trimmed.length === 0)
45177
45430
  return false;
45178
45431
  if (couldChain(trimmed))
45179
45432
  return false;
45180
- const haystack = trimmed.toLowerCase();
45433
+ const haystack = stripInertPythonFlags(normaliseProgram(trimmed)).toLowerCase();
45181
45434
  const prefixes = [
45182
45435
  ...options?.extra ?? [],
45183
45436
  ...options?.builtin === false ? [] : DEFAULT_SAFE_COMMANDS
@@ -45250,6 +45503,16 @@ var ALWAYS_ASK_TOOLS = /* @__PURE__ */ new Set([
45250
45503
  * whatever DoTheThing does.
45251
45504
  */
45252
45505
  "excel_run_macro",
45506
+ /*
45507
+ * It reads files off this machine and puts them into a message addressed to other people.
45508
+ *
45509
+ * Nothing is sent - the draft opens on screen and the user decides - so the act being approved
45510
+ * is the composing, and specifically which files and which recipients. "Auto-approve commands"
45511
+ * is a statement about running commands, and reading it as permission to attach whatever the
45512
+ * model names to whoever it names is a grant nobody knowingly made. The preview lists both by
45513
+ * name rather than by count, which is only useful if somebody is shown it.
45514
+ */
45515
+ "outlook_create_draft",
45253
45516
  /*
45254
45517
  * The plan is what holds the assistant to work the user agreed, so a category toggle must
45255
45518
  * never stand in for reading the change. Auto-approving this would mean an agent could widen
@@ -45698,8 +45961,8 @@ function describeExpertBudget(spend, limits, pricing) {
45698
45961
  // ../../packages/core/dist/rag/vectorStore.js
45699
45962
  var VectorStoreError = class extends Error {
45700
45963
  status;
45701
- constructor(message3, status) {
45702
- super(message3);
45964
+ constructor(message4, status) {
45965
+ super(message4);
45703
45966
  this.status = status;
45704
45967
  this.name = "VectorStoreError";
45705
45968
  }
@@ -45707,8 +45970,8 @@ var VectorStoreError = class extends Error {
45707
45970
 
45708
45971
  // ../../packages/core/dist/rag/opensearch/client.js
45709
45972
  var OpenSearchError = class extends VectorStoreError {
45710
- constructor(message3, status) {
45711
- super(message3, status);
45973
+ constructor(message4, status) {
45974
+ super(message4, status);
45712
45975
  this.name = "OpenSearchError";
45713
45976
  }
45714
45977
  };
@@ -47005,8 +47268,8 @@ async function syncVectorStores(options) {
47005
47268
 
47006
47269
  // ../../packages/core/dist/rag/embedder.js
47007
47270
  var EmbedderError = class extends Error {
47008
- constructor(message3) {
47009
- super(message3);
47271
+ constructor(message4) {
47272
+ super(message4);
47010
47273
  this.name = "EmbedderError";
47011
47274
  }
47012
47275
  };
@@ -47348,7 +47611,7 @@ ${hit.text}`;
47348
47611
  ].join("\n")
47349
47612
  };
47350
47613
  } catch (error51) {
47351
- const message3 = error51 instanceof Error ? error51.message : String(error51);
47614
+ const message4 = error51 instanceof Error ? error51.message : String(error51);
47352
47615
  options.observer?.record({
47353
47616
  at: startedAt,
47354
47617
  source: "search_codebase",
@@ -47356,9 +47619,9 @@ ${hit.text}`;
47356
47619
  collection: options.index,
47357
47620
  hits: 0,
47358
47621
  elapsedMs: Date.now() - startedAt,
47359
- error: message3
47622
+ error: message4
47360
47623
  });
47361
- return { content: message3, isError: true };
47624
+ return { content: message4, isError: true };
47362
47625
  }
47363
47626
  }
47364
47627
  };
@@ -47526,7 +47789,7 @@ function createSearchTeamSkillsTool(options) {
47526
47789
  });
47527
47790
  return { content: renderTeamSkillHits(found, params.query) };
47528
47791
  } catch (error51) {
47529
- const message3 = error51 instanceof Error ? error51.message : String(error51);
47792
+ const message4 = error51 instanceof Error ? error51.message : String(error51);
47530
47793
  options.observer?.record({
47531
47794
  at: startedAt,
47532
47795
  source: "search_team_skills",
@@ -47535,9 +47798,9 @@ function createSearchTeamSkillsTool(options) {
47535
47798
  collection: options.collections.join(" \u2192 "),
47536
47799
  hits: 0,
47537
47800
  elapsedMs: Date.now() - startedAt,
47538
- error: message3
47801
+ error: message4
47539
47802
  });
47540
- return { content: message3, isError: true };
47803
+ return { content: message4, isError: true };
47541
47804
  }
47542
47805
  }
47543
47806
  };
@@ -49618,15 +49881,15 @@ async function refreshMail(options) {
49618
49881
  complete: []
49619
49882
  };
49620
49883
  }
49621
- function toRecord(message3) {
49622
- const status = parseStatusTag(message3.subject);
49884
+ function toRecord(message4) {
49885
+ const status = parseStatusTag(message4.subject);
49623
49886
  return {
49624
- id: message3.id,
49625
- subject: message3.subject,
49626
- sender: message3.sender,
49627
- receivedAt: message3.receivedAt,
49628
- folder: message3.folder,
49629
- preview: message3.preview,
49887
+ id: message4.id,
49888
+ subject: message4.subject,
49889
+ sender: message4.sender,
49890
+ receivedAt: message4.receivedAt,
49891
+ folder: message4.folder,
49892
+ preview: message4.preview,
49630
49893
  ...status !== void 0 ? { status } : {}
49631
49894
  };
49632
49895
  }
@@ -49665,7 +49928,7 @@ async function syncMail(options) {
49665
49928
  const backward = await options.harvest(backRequests, { limit: remaining, previewChars });
49666
49929
  backfilled = backward.messages.length;
49667
49930
  candidates = [...candidates, ...backward.messages.map(toRecord)];
49668
- const returnedFor = new Set(backward.messages.map((message3) => message3.folder));
49931
+ const returnedFor = new Set(backward.messages.map((message4) => message4.folder));
49669
49932
  for (const path35 of behind) {
49670
49933
  if (!returnedFor.has(path35))
49671
49934
  completed.push(path35);
@@ -50344,8 +50607,8 @@ var STORED = 0;
50344
50607
  var DEFLATED = 8;
50345
50608
  var MAX_ENTRY_BYTES = 128 * 1024 * 1024;
50346
50609
  var ZipError = class extends Error {
50347
- constructor(message3) {
50348
- super(message3);
50610
+ constructor(message4) {
50611
+ super(message4);
50349
50612
  this.name = "ZipError";
50350
50613
  }
50351
50614
  };
@@ -50429,8 +50692,8 @@ var ZipArchive = class _ZipArchive {
50429
50692
 
50430
50693
  // ../../packages/core/dist/documents/extract.js
50431
50694
  var DocumentError = class extends Error {
50432
- constructor(message3) {
50433
- super(message3);
50695
+ constructor(message4) {
50696
+ super(message4);
50434
50697
  this.name = "DocumentError";
50435
50698
  }
50436
50699
  };
@@ -52717,8 +52980,8 @@ var ServerResultSchema = union([
52717
52980
  CreateTaskResultSchema
52718
52981
  ]);
52719
52982
  var McpError = class _McpError extends Error {
52720
- constructor(code, message3, data) {
52721
- super(`MCP error ${code}: ${message3}`);
52983
+ constructor(code, message4, data) {
52984
+ super(`MCP error ${code}: ${message4}`);
52722
52985
  this.code = code;
52723
52986
  this.data = data;
52724
52987
  this.name = "McpError";
@@ -52726,19 +52989,19 @@ var McpError = class _McpError extends Error {
52726
52989
  /**
52727
52990
  * Factory method to create the appropriate error type based on the error code and data
52728
52991
  */
52729
- static fromError(code, message3, data) {
52992
+ static fromError(code, message4, data) {
52730
52993
  if (code === ErrorCode.UrlElicitationRequired && data) {
52731
52994
  const errorData = data;
52732
52995
  if (errorData.elicitations) {
52733
- return new UrlElicitationRequiredError(errorData.elicitations, message3);
52996
+ return new UrlElicitationRequiredError(errorData.elicitations, message4);
52734
52997
  }
52735
52998
  }
52736
- return new _McpError(code, message3, data);
52999
+ return new _McpError(code, message4, data);
52737
53000
  }
52738
53001
  };
52739
53002
  var UrlElicitationRequiredError = class extends McpError {
52740
- constructor(elicitations, message3 = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
52741
- super(ErrorCode.UrlElicitationRequired, message3, {
53003
+ constructor(elicitations, message4 = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
53004
+ super(ErrorCode.UrlElicitationRequired, message4, {
52742
53005
  elicitations
52743
53006
  });
52744
53007
  }
@@ -52821,15 +53084,15 @@ var Protocol = class {
52821
53084
  let queuedMessage;
52822
53085
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
52823
53086
  if (queuedMessage.type === "response" || queuedMessage.type === "error") {
52824
- const message3 = queuedMessage.message;
52825
- const requestId = message3.id;
53087
+ const message4 = queuedMessage.message;
53088
+ const requestId = message4.id;
52826
53089
  const resolver = this._requestResolvers.get(requestId);
52827
53090
  if (resolver) {
52828
53091
  this._requestResolvers.delete(requestId);
52829
53092
  if (queuedMessage.type === "response") {
52830
- resolver(message3);
53093
+ resolver(message4);
52831
53094
  } else {
52832
- const errorMessage = message3;
53095
+ const errorMessage = message4;
52833
53096
  const error51 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
52834
53097
  resolver(error51);
52835
53098
  }
@@ -52968,16 +53231,16 @@ var Protocol = class {
52968
53231
  this._onerror(error51);
52969
53232
  };
52970
53233
  const _onmessage = this._transport?.onmessage;
52971
- this._transport.onmessage = (message3, extra) => {
52972
- _onmessage?.(message3, extra);
52973
- if (isJSONRPCResultResponse(message3) || isJSONRPCErrorResponse(message3)) {
52974
- this._onresponse(message3);
52975
- } else if (isJSONRPCRequest(message3)) {
52976
- this._onrequest(message3, extra);
52977
- } else if (isJSONRPCNotification(message3)) {
52978
- this._onnotification(message3);
53234
+ this._transport.onmessage = (message4, extra) => {
53235
+ _onmessage?.(message4, extra);
53236
+ if (isJSONRPCResultResponse(message4) || isJSONRPCErrorResponse(message4)) {
53237
+ this._onresponse(message4);
53238
+ } else if (isJSONRPCRequest(message4)) {
53239
+ this._onrequest(message4, extra);
53240
+ } else if (isJSONRPCNotification(message4)) {
53241
+ this._onnotification(message4);
52979
53242
  } else {
52980
- this._onerror(new Error(`Unknown message type: ${JSON.stringify(message3)}`));
53243
+ this._onerror(new Error(`Unknown message type: ${JSON.stringify(message4)}`));
52981
53244
  }
52982
53245
  };
52983
53246
  await this._transport.start();
@@ -53587,12 +53850,12 @@ var Protocol = class {
53587
53850
  * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
53588
53851
  * simply propagates the error.
53589
53852
  */
53590
- async _enqueueTaskMessage(taskId, message3, sessionId) {
53853
+ async _enqueueTaskMessage(taskId, message4, sessionId) {
53591
53854
  if (!this._taskStore || !this._taskMessageQueue) {
53592
53855
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
53593
53856
  }
53594
53857
  const maxQueueSize = this._options?.maxTaskQueueSize;
53595
- await this._taskMessageQueue.enqueue(taskId, message3, sessionId, maxQueueSize);
53858
+ await this._taskMessageQueue.enqueue(taskId, message4, sessionId, maxQueueSize);
53596
53859
  }
53597
53860
  /**
53598
53861
  * Clears the message queue for a task and rejects any pending request resolvers.
@@ -53602,9 +53865,9 @@ var Protocol = class {
53602
53865
  async _clearTaskQueue(taskId, sessionId) {
53603
53866
  if (this._taskMessageQueue) {
53604
53867
  const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
53605
- for (const message3 of messages) {
53606
- if (message3.type === "request" && isJSONRPCRequest(message3.message)) {
53607
- const requestId = message3.message.id;
53868
+ for (const message4 of messages) {
53869
+ if (message4.type === "request" && isJSONRPCRequest(message4.message)) {
53870
+ const requestId = message4.message.id;
53608
53871
  const resolver = this._requestResolvers.get(requestId);
53609
53872
  if (resolver) {
53610
53873
  resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
@@ -53849,9 +54112,9 @@ var ExperimentalClientTasks = class {
53849
54112
  };
53850
54113
  const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
53851
54114
  const validator = clientInternal.getToolOutputValidator(params.name);
53852
- for await (const message3 of stream) {
53853
- if (message3.type === "result" && validator) {
53854
- const result = message3.result;
54115
+ for await (const message4 of stream) {
54116
+ if (message4.type === "result" && validator) {
54117
+ const result = message4.result;
53855
54118
  if (!result.structuredContent && !result.isError) {
53856
54119
  yield {
53857
54120
  type: "error",
@@ -53882,7 +54145,7 @@ var ExperimentalClientTasks = class {
53882
54145
  }
53883
54146
  }
53884
54147
  }
53885
- yield message3;
54148
+ yield message4;
53886
54149
  }
53887
54150
  }
53888
54151
  /**
@@ -54536,8 +54799,8 @@ var ReadBuffer = class {
54536
54799
  function deserializeMessage(line) {
54537
54800
  return JSONRPCMessageSchema.parse(JSON.parse(line));
54538
54801
  }
54539
- function serializeMessage(message3) {
54540
- return JSON.stringify(message3) + "\n";
54802
+ function serializeMessage(message4) {
54803
+ return JSON.stringify(message4) + "\n";
54541
54804
  }
54542
54805
 
54543
54806
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1_ed45788dfbfe808cc09dd7daea6bd385/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
@@ -54656,11 +54919,11 @@ var StdioClientTransport = class {
54656
54919
  processReadBuffer() {
54657
54920
  while (true) {
54658
54921
  try {
54659
- const message3 = this._readBuffer.readMessage();
54660
- if (message3 === null) {
54922
+ const message4 = this._readBuffer.readMessage();
54923
+ if (message4 === null) {
54661
54924
  break;
54662
54925
  }
54663
- this.onmessage?.(message3);
54926
+ this.onmessage?.(message4);
54664
54927
  } catch (error51) {
54665
54928
  this.onerror?.(error51);
54666
54929
  }
@@ -54696,12 +54959,12 @@ var StdioClientTransport = class {
54696
54959
  }
54697
54960
  this._readBuffer.clear();
54698
54961
  }
54699
- send(message3) {
54962
+ send(message4) {
54700
54963
  return new Promise((resolve) => {
54701
54964
  if (!this._process?.stdin) {
54702
54965
  throw new Error("Not connected");
54703
54966
  }
54704
- const json2 = serializeMessage(message3);
54967
+ const json2 = serializeMessage(message4);
54705
54968
  if (this._process.stdin.write(json2)) {
54706
54969
  resolve();
54707
54970
  } else {
@@ -54713,8 +54976,8 @@ var StdioClientTransport = class {
54713
54976
 
54714
54977
  // ../../node_modules/.pnpm/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/index.js
54715
54978
  var ParseError = class extends Error {
54716
- constructor(message3, options) {
54717
- super(message3), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
54979
+ constructor(message4, options) {
54980
+ super(message4), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
54718
54981
  }
54719
54982
  };
54720
54983
  var LF = 10;
@@ -54930,9 +55193,9 @@ var ErrorEvent = class extends Event {
54930
55193
  return inspect(inspectableError(this), options);
54931
55194
  }
54932
55195
  };
54933
- function syntaxError(message3) {
55196
+ function syntaxError(message4) {
54934
55197
  const DomException = globalThis.DOMException;
54935
- return typeof DomException == "function" ? new DomException(message3, "SyntaxError") : new SyntaxError(message3);
55198
+ return typeof DomException == "function" ? new DomException(message4, "SyntaxError") : new SyntaxError(message4);
54936
55199
  }
54937
55200
  function flattenError2(err) {
54938
55201
  return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError2).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError2(err.cause)}` : err.message : `${err}`;
@@ -55144,10 +55407,10 @@ getRequestOptions_fn = function() {
55144
55407
  * @param code - The HTTP status code, if available
55145
55408
  * @internal
55146
55409
  */
55147
- failConnection_fn = function(message3, code) {
55410
+ failConnection_fn = function(message4, code) {
55148
55411
  var _a3;
55149
55412
  __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
55150
- const errorEvent = new ErrorEvent("error", { code, message: message3 });
55413
+ const errorEvent = new ErrorEvent("error", { code, message: message4 });
55151
55414
  (_a3 = __privateGet(this, _onError)) == null || _a3.call(this, errorEvent), this.dispatchEvent(errorEvent);
55152
55415
  }, /**
55153
55416
  * Schedules a reconnection attempt against the EventSource endpoint.
@@ -55156,12 +55419,12 @@ failConnection_fn = function(message3, code) {
55156
55419
  * @param code - The HTTP status code, if available
55157
55420
  * @internal
55158
55421
  */
55159
- scheduleReconnect_fn = function(message3, code) {
55422
+ scheduleReconnect_fn = function(message4, code) {
55160
55423
  var _a3;
55161
55424
  if (__privateGet(this, _readyState) === this.CLOSED)
55162
55425
  return;
55163
55426
  __privateSet(this, _readyState, this.CONNECTING);
55164
- const errorEvent = new ErrorEvent("error", { code, message: message3 });
55427
+ const errorEvent = new ErrorEvent("error", { code, message: message4 });
55165
55428
  (_a3 = __privateGet(this, _onError)) == null || _a3.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
55166
55429
  }, _reconnect = /* @__PURE__ */ new WeakMap(), /**
55167
55430
  * ReadyState representing an EventSource currently trying to connect
@@ -55420,8 +55683,8 @@ function checkResourceAllowed({ requestedResource, configuredResource }) {
55420
55683
 
55421
55684
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1_ed45788dfbfe808cc09dd7daea6bd385/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
55422
55685
  var OAuthError = class extends Error {
55423
- constructor(message3, errorUri) {
55424
- super(message3);
55686
+ constructor(message4, errorUri) {
55687
+ super(message4);
55425
55688
  this.errorUri = errorUri;
55426
55689
  this.name = this.constructor.name;
55427
55690
  }
@@ -55515,8 +55778,8 @@ var OAUTH_ERRORS = {
55515
55778
 
55516
55779
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1_ed45788dfbfe808cc09dd7daea6bd385/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
55517
55780
  var UnauthorizedError = class extends Error {
55518
- constructor(message3) {
55519
- super(message3 ?? "Unauthorized");
55781
+ constructor(message4) {
55782
+ super(message4 ?? "Unauthorized");
55520
55783
  }
55521
55784
  };
55522
55785
  function isClientAuthMethod(method) {
@@ -56056,8 +56319,8 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
56056
56319
 
56057
56320
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1_ed45788dfbfe808cc09dd7daea6bd385/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
56058
56321
  var SseError = class extends Error {
56059
- constructor(code, message3, event) {
56060
- super(`SSE error: ${message3}`);
56322
+ constructor(code, message4, event) {
56323
+ super(`SSE error: ${message4}`);
56061
56324
  this.code = code;
56062
56325
  this.event = event;
56063
56326
  }
@@ -56160,14 +56423,14 @@ var SSEClientTransport = class {
56160
56423
  });
56161
56424
  this._eventSource.onmessage = (event) => {
56162
56425
  const messageEvent = event;
56163
- let message3;
56426
+ let message4;
56164
56427
  try {
56165
- message3 = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
56428
+ message4 = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
56166
56429
  } catch (error51) {
56167
56430
  this.onerror?.(error51);
56168
56431
  return;
56169
56432
  }
56170
- this.onmessage?.(message3);
56433
+ this.onmessage?.(message4);
56171
56434
  };
56172
56435
  });
56173
56436
  }
@@ -56200,7 +56463,7 @@ var SSEClientTransport = class {
56200
56463
  this._eventSource?.close();
56201
56464
  this.onclose?.();
56202
56465
  }
56203
- async send(message3) {
56466
+ async send(message4) {
56204
56467
  if (!this._endpoint) {
56205
56468
  throw new Error("Not connected");
56206
56469
  }
@@ -56211,7 +56474,7 @@ var SSEClientTransport = class {
56211
56474
  ...this._requestInit,
56212
56475
  method: "POST",
56213
56476
  headers,
56214
- body: JSON.stringify(message3),
56477
+ body: JSON.stringify(message4),
56215
56478
  signal: this._abortController?.signal
56216
56479
  };
56217
56480
  const response = await (this._fetch ?? fetch)(this._endpoint, init);
@@ -56230,7 +56493,7 @@ var SSEClientTransport = class {
56230
56493
  if (result !== "AUTHORIZED") {
56231
56494
  throw new UnauthorizedError();
56232
56495
  }
56233
- return this.send(message3);
56496
+ return this.send(message4);
56234
56497
  }
56235
56498
  throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
56236
56499
  }
@@ -56295,8 +56558,8 @@ var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
56295
56558
  maxRetries: 2
56296
56559
  };
56297
56560
  var StreamableHTTPError = class extends Error {
56298
- constructor(code, message3) {
56299
- super(`Streamable HTTP error: ${message3}`);
56561
+ constructor(code, message4) {
56562
+ super(`Streamable HTTP error: ${message4}`);
56300
56563
  this.code = code;
56301
56564
  }
56302
56565
  };
@@ -56448,14 +56711,14 @@ var StreamableHTTPClientTransport = class {
56448
56711
  }
56449
56712
  if (!event.event || event.event === "message") {
56450
56713
  try {
56451
- const message3 = JSONRPCMessageSchema.parse(JSON.parse(event.data));
56452
- if (isJSONRPCResultResponse(message3)) {
56714
+ const message4 = JSONRPCMessageSchema.parse(JSON.parse(event.data));
56715
+ if (isJSONRPCResultResponse(message4)) {
56453
56716
  receivedResponse = true;
56454
56717
  if (replayMessageId !== void 0) {
56455
- message3.id = replayMessageId;
56718
+ message4.id = replayMessageId;
56456
56719
  }
56457
56720
  }
56458
- this.onmessage?.(message3);
56721
+ this.onmessage?.(message4);
56459
56722
  } catch (error51) {
56460
56723
  this.onerror?.(error51);
56461
56724
  }
@@ -56521,11 +56784,11 @@ var StreamableHTTPClientTransport = class {
56521
56784
  this._abortController?.abort();
56522
56785
  this.onclose?.();
56523
56786
  }
56524
- async send(message3, options) {
56787
+ async send(message4, options) {
56525
56788
  try {
56526
56789
  const { resumptionToken, onresumptiontoken } = options || {};
56527
56790
  if (resumptionToken) {
56528
- this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message3) ? message3.id : void 0 }).catch((err) => this.onerror?.(err));
56791
+ this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message4) ? message4.id : void 0 }).catch((err) => this.onerror?.(err));
56529
56792
  return;
56530
56793
  }
56531
56794
  const headers = await this._commonHeaders();
@@ -56535,7 +56798,7 @@ var StreamableHTTPClientTransport = class {
56535
56798
  ...this._requestInit,
56536
56799
  method: "POST",
56537
56800
  headers,
56538
- body: JSON.stringify(message3),
56801
+ body: JSON.stringify(message4),
56539
56802
  signal: this._abortController?.signal
56540
56803
  };
56541
56804
  const response = await (this._fetch ?? fetch)(this._url, init);
@@ -56562,7 +56825,7 @@ var StreamableHTTPClientTransport = class {
56562
56825
  throw new UnauthorizedError();
56563
56826
  }
56564
56827
  this._hasCompletedAuthFlow = true;
56565
- return this.send(message3);
56828
+ return this.send(message4);
56566
56829
  }
56567
56830
  if (response.status === 403 && this._authProvider) {
56568
56831
  const { resourceMetadataUrl, scope, error: error51 } = extractWWWAuthenticateParams(response);
@@ -56587,7 +56850,7 @@ var StreamableHTTPClientTransport = class {
56587
56850
  if (result !== "AUTHORIZED") {
56588
56851
  throw new UnauthorizedError();
56589
56852
  }
56590
- return this.send(message3);
56853
+ return this.send(message4);
56591
56854
  }
56592
56855
  }
56593
56856
  throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
@@ -56596,12 +56859,12 @@ var StreamableHTTPClientTransport = class {
56596
56859
  this._lastUpscopingHeader = void 0;
56597
56860
  if (response.status === 202) {
56598
56861
  await response.body?.cancel();
56599
- if (isInitializedNotification(message3)) {
56862
+ if (isInitializedNotification(message4)) {
56600
56863
  this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
56601
56864
  }
56602
56865
  return;
56603
56866
  }
56604
- const messages = Array.isArray(message3) ? message3 : [message3];
56867
+ const messages = Array.isArray(message4) ? message4 : [message4];
56605
56868
  const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
56606
56869
  const contentType2 = response.headers.get("content-type");
56607
56870
  const responseMediaType = mediaTypeEssence(contentType2);
@@ -57036,11 +57299,11 @@ var McpRegistry = class {
57036
57299
  this.appendLog(name, "Connected.");
57037
57300
  await this.refreshTools(name);
57038
57301
  } catch (error51) {
57039
- const message3 = error51 instanceof Error ? error51.message : String(error51);
57040
- this.logger?.warn(`MCP server "${name}" failed to connect: ${message3}`);
57302
+ const message4 = error51 instanceof Error ? error51.message : String(error51);
57303
+ this.logger?.warn(`MCP server "${name}" failed to connect: ${message4}`);
57041
57304
  this.statuses.set(name, "failed");
57042
- this.errors.set(name, message3);
57043
- this.appendLog(name, `Failed: ${message3}`);
57305
+ this.errors.set(name, message4);
57306
+ this.appendLog(name, `Failed: ${message4}`);
57044
57307
  this.events.onStateChanged();
57045
57308
  }
57046
57309
  }
@@ -57154,8 +57417,8 @@ var import_node_child_process4 = require("node:child_process");
57154
57417
  var import_promises7 = __toESM(require("node:fs/promises"), 1);
57155
57418
  var import_node_path15 = __toESM(require("node:path"), 1);
57156
57419
  var UvError = class extends Error {
57157
- constructor(message3) {
57158
- super(message3);
57420
+ constructor(message4) {
57421
+ super(message4);
57159
57422
  this.name = "UvError";
57160
57423
  }
57161
57424
  };
@@ -57304,8 +57567,8 @@ var import_node_child_process5 = require("node:child_process");
57304
57567
  var import_node_readline = require("node:readline");
57305
57568
  var PythonWorkerError = class extends Error {
57306
57569
  traceback;
57307
- constructor(message3, traceback) {
57308
- super(message3);
57570
+ constructor(message4, traceback) {
57571
+ super(message4);
57309
57572
  this.traceback = traceback;
57310
57573
  this.name = "PythonWorkerError";
57311
57574
  }
@@ -58716,12 +58979,12 @@ function makeWriteTool(context, options) {
58716
58979
  described = await context.worker.validate(params.name, filePath);
58717
58980
  } catch (error51) {
58718
58981
  await restore();
58719
- const message3 = error51 instanceof Error ? error51.message : String(error51);
58982
+ const message4 = error51 instanceof Error ? error51.message : String(error51);
58720
58983
  const traceback = error51.traceback;
58721
58984
  return {
58722
58985
  content: `The tool was not saved.
58723
58986
 
58724
- ${message3}
58987
+ ${message4}
58725
58988
 
58726
58989
  ${traceback ?? ""}`.trim(),
58727
58990
  isError: true
@@ -58857,12 +59120,12 @@ run(${JSON.stringify(params, null, 2)})`
58857
59120
  --- stdout ---
58858
59121
  ${printed}` : value };
58859
59122
  } catch (error51) {
58860
- const message3 = error51 instanceof Error ? error51.message : String(error51);
59123
+ const message4 = error51 instanceof Error ? error51.message : String(error51);
58861
59124
  const traceback = error51.traceback;
58862
59125
  return {
58863
- content: traceback !== void 0 ? `${message3}
59126
+ content: traceback !== void 0 ? `${message4}
58864
59127
 
58865
- ${traceback}` : message3,
59128
+ ${traceback}` : message4,
58866
59129
  isError: true
58867
59130
  };
58868
59131
  }
@@ -58871,7 +59134,7 @@ ${traceback}` : message3,
58871
59134
  }
58872
59135
 
58873
59136
  // ../../packages/core/dist/python/workerSource.js
58874
- var PYTHON_WORKER_SOURCE = '"""Light Code\'s Python tool worker.\r\n\r\nOne long-lived process per workspace, speaking JSON-RPC over stdio. It owns three jobs the\r\nTypeScript side cannot do for itself:\r\n\r\n* deriving a JSON Schema from ``run``\'s type hints, so tool metadata is never hand-written\r\n and therefore never drifts from the code (CLAUDE.md \xA713);\r\n* importing and reloading tool modules, so a tool edited mid-session takes effect without\r\n restarting;\r\n* running the tool.\r\n\r\nFraming is one JSON object per line. Length-prefixing would be sturdier, but a tool that\r\nprints to stdout is *common* \u2014 so the reader tolerates unparseable lines instead, treating\r\nthem as the tool\'s own output rather than corrupting the channel.\r\n"""\r\n\r\nfrom __future__ import annotations\r\n\r\nimport importlib.util\r\nimport inspect\r\nimport io\r\nimport json\r\nimport re\r\nimport sys\r\nimport traceback\r\nimport types\r\nfrom contextlib import redirect_stdout\r\nfrom pathlib import Path\r\nfrom typing import Any\r\n\r\n# Loaded modules, keyed by tool name, so a reload replaces rather than shadows.\r\n_MODULES: dict[str, Any] = {}\r\n\r\n\r\ndef _respond(payload: dict[str, Any]) -> None:\r\n """Write one frame.\r\n\r\n Always to the real stdout, captured at import time \u2014 a tool that reassigns\r\n ``sys.stdout`` would otherwise silently swallow every subsequent reply.\r\n """\r\n _REAL_STDOUT.write(json.dumps(payload) + "\\n")\r\n _REAL_STDOUT.flush()\r\n\r\n\r\n_REAL_STDOUT = sys.stdout\r\n_REAL_STDIN = sys.stdin\r\n\r\n# Counts nested calls out to the host, so a loop is stopped rather than left to fill the pipe.\r\n_CALL_DEPTH = 0\r\n_MAX_DEPTH = 4\r\n_CURRENT_TOOL = ""\r\n_CALL_SEQ = 0\r\n\r\n\r\nclass ToolError(RuntimeError):\r\n """A tool this one called came back with a failure."""\r\n\r\n\r\ndef call_tool(name: str, **arguments: Any) -> Any:\r\n """Calls another tool and returns its result.\r\n\r\n Available to every tool as ``light_code.call_tool``. Only other Python tools and MCP\r\n tools can be reached; see the host for why.\r\n\r\n This blocks the worker, which is correct: the tool asked for something and cannot\r\n continue without it. The host may prompt the user before running it, so it can take as\r\n long as a person takes to answer.\r\n """\r\n global _CALL_DEPTH\r\n if _CALL_DEPTH >= _MAX_DEPTH:\r\n raise ToolError(\r\n f"tool calls are nested {_MAX_DEPTH} deep, which is almost certainly a loop - "\r\n "a tool calling itself, or two calling each other"\r\n )\r\n\r\n global _CALL_SEQ\r\n _CALL_SEQ += 1\r\n # A counter, not ``id()``: CPython reuses an address the moment the object is collected, so\r\n # two calls in a row could be handed the same token.\r\n token = f"cb{_CALL_SEQ}"\r\n _CALL_DEPTH += 1\r\n try:\r\n _respond(\r\n {\r\n "callback": token,\r\n "method": "call_tool",\r\n "name": name,\r\n "arguments": arguments,\r\n "caller": _CURRENT_TOOL,\r\n }\r\n )\r\n # Read until the answer to *this* call arrives. Anything else on the stream would be a\r\n # protocol error rather than something to skip, so it is reported rather than ignored.\r\n while True:\r\n line = _REAL_STDIN.readline()\r\n if not line:\r\n raise ToolError("the host closed the connection while waiting for " + name)\r\n line = line.strip()\r\n if not line:\r\n continue\r\n frame = json.loads(line)\r\n\r\n if frame.get("callback") == token:\r\n if frame.get("ok"):\r\n return frame.get("value")\r\n raise ToolError(frame.get("error") or f"{name} failed")\r\n\r\n # An ordinary request, arriving while this tool is blocked.\r\n #\r\n # It happens for real: the tool this one called is *another Python tool*, so the host\r\n # sends it down the same pipe while we are still waiting. Skipping it would deadlock \u2014\r\n # the host waits for a reply that nobody is reading for \u2014 and treating it as an\r\n # out-of-order answer, which the first version did, fails every nested call between\r\n # two Python tools. So it is served here and the wait resumes.\r\n if "method" in frame:\r\n request_id = frame.get("id")\r\n try:\r\n _respond({"id": request_id, "ok": True, "value": _handle(frame)})\r\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\r\n _respond(\r\n {\r\n "id": request_id,\r\n "ok": False,\r\n "error": f"{type(error).__name__}: {error}",\r\n "traceback": traceback.format_exc(),\r\n }\r\n )\r\n continue\r\n\r\n raise ToolError(\r\n "unexpected frame while waiting for " + name + "; this is a bug in Light Code"\r\n )\r\n finally:\r\n _CALL_DEPTH -= 1\r\n\r\n\r\ndef _install_helper_module() -> None:\r\n """Publishes ``light_code`` so a tool can ``import light_code`` and call other tools.\r\n\r\n A real module in ``sys.modules`` rather than a builtin or an injected global: a tool is\r\n an ordinary Python file that must also be readable, lintable and runnable on its own\r\n terms, and magic names appearing from nowhere break every one of those.\r\n """\r\n if "light_code" in sys.modules:\r\n return\r\n module = types.ModuleType("light_code")\r\n module.call_tool = call_tool # type: ignore[attr-defined]\r\n module.ToolError = ToolError # type: ignore[attr-defined]\r\n sys.modules["light_code"] = module\r\n\r\n\r\ndef _load(name: str, path: str) -> Any:\r\n """Imports a tool module from an explicit path, replacing any previous version."""\r\n _install_helper_module()\r\n spec = importlib.util.spec_from_file_location(f"light_code_tool_{name}", path)\r\n if spec is None or spec.loader is None:\r\n raise ImportError(f"could not load {path}")\r\n module = importlib.util.module_from_spec(spec)\r\n # Executed with the tool\'s own stdout captured: a print at import time would otherwise\r\n # land in the middle of the JSON-RPC stream.\r\n with redirect_stdout(io.StringIO()):\r\n spec.loader.exec_module(module)\r\n if not hasattr(module, "run"):\r\n raise AttributeError(f"{path} defines no `run` function")\r\n _MODULES[name] = module\r\n return module\r\n\r\n\r\ndef _google_arg_docs(doc: str) -> dict[str, str]:\r\n """Pulls parameter descriptions out of a Google-style ``Args:`` block.\r\n\r\n Best-effort by design. A missing description costs the model a hint; a parser that threw\r\n would cost it the whole tool.\r\n """\r\n docs: dict[str, str] = {}\r\n match = re.search(r"^\\s*Args:\\s*$(.*?)(?=^\\s*\\w+:\\s*$|\\Z)", doc, re.MULTILINE | re.DOTALL)\r\n if not match:\r\n return docs\r\n for line in match.group(1).splitlines():\r\n entry = re.match(r"\\s*(\\w+)\\s*(?:\\([^)]*\\))?\\s*:\\s*(.+)", line)\r\n if entry:\r\n docs[entry.group(1)] = entry.group(2).strip()\r\n return docs\r\n\r\n\r\n#: Annotations the fallback can map without pydantic. Anything else becomes a string,\r\n#: which is lossy but callable.\r\n_PRIMITIVE_TYPES: dict[Any, str] = {\r\n str: "string",\r\n bool: "boolean",\r\n int: "integer",\r\n float: "number",\r\n list: "array",\r\n dict: "object",\r\n}\r\n\r\n\r\ndef _fallback_schema(run: Any) -> dict[str, Any]:\r\n """Derives a schema from bare annotations, for when pydantic is not installed.\r\n\r\n Worth doing properly rather than declaring everything a string: a ``bool`` advertised as\r\n a string means the model sends ``"true"`` and the tool receives the string ``"true"``,\r\n which is truthy for every value including ``"false"``. Silent, and wrong.\r\n """\r\n signature = inspect.signature(run)\r\n properties: dict[str, Any] = {}\r\n required: list[str] = []\r\n\r\n for name, parameter in signature.parameters.items():\r\n if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):\r\n continue\r\n annotation = parameter.annotation\r\n # A string annotation appears under `from __future__ import annotations`; resolving\r\n # it properly needs typing.get_type_hints, which can itself fail on a forward ref.\r\n if isinstance(annotation, str):\r\n annotation = {"str": str, "bool": bool, "int": int, "float": float}.get(annotation, inspect.Parameter.empty)\r\n properties[name] = {"type": _PRIMITIVE_TYPES.get(annotation, "string")}\r\n if parameter.default is parameter.empty:\r\n required.append(name)\r\n\r\n return {"type": "object", "properties": properties, "required": required}\r\n\r\n\r\ndef _schema_for(module: Any) -> dict[str, Any]:\r\n """Derives the parameter schema from ``run``\'s type hints.\r\n\r\n pydantic when available, because it handles unions, defaults, nested models and\r\n ``Optional`` correctly. The fallback treats every parameter as a string, which is worse\r\n but still callable \u2014 better than refusing to register a tool because pydantic is missing.\r\n """\r\n run = module.run\r\n try:\r\n from pydantic import TypeAdapter\r\n\r\n schema = TypeAdapter(run).json_schema()\r\n properties = schema.get("properties", {})\r\n except Exception: # noqa: BLE001 - any pydantic failure falls back rather than failing\r\n schema = _fallback_schema(run)\r\n properties = schema["properties"]\r\n\r\n doc = inspect.getdoc(run) or inspect.getdoc(module) or ""\r\n for name, description in _google_arg_docs(doc).items():\r\n if name in properties:\r\n properties[name]["description"] = description\r\n\r\n schema.setdefault("type", "object")\r\n schema["properties"] = properties\r\n return schema\r\n\r\n\r\ndef _describe(name: str, path: str) -> dict[str, Any]:\r\n module = _load(name, path)\r\n # The module docstring, not run\'s: it describes the tool, whereas run\'s docstring\r\n # usually documents the parameters.\r\n description = (inspect.getdoc(module) or inspect.getdoc(module.run) or "").strip()\r\n return {"name": name, "description": description, "schema": _schema_for(module)}\r\n\r\n\r\ndef _handle(request: dict[str, Any]) -> dict[str, Any]:\r\n method = request.get("method")\r\n params = request.get("params") or {}\r\n\r\n if method == "ping":\r\n return {"ok": True, "python": sys.version}\r\n\r\n if method == "describe":\r\n return _describe(params["name"], params["path"])\r\n\r\n if method == "validate":\r\n # Parsed before importing, so a syntax error is reported as one rather than as\r\n # whatever the import machinery happens to raise.\r\n source = Path(params["path"]).read_text(encoding="utf-8")\r\n compile(source, params["path"], "exec")\r\n return _describe(params["name"], params["path"])\r\n\r\n if method == "call":\r\n name = params["name"]\r\n # Recorded so a nested call can say *who* is asking. An approval prompt naming only the\r\n # callee is the prompt people click through.\r\n global _CURRENT_TOOL\r\n _CURRENT_TOOL = name\r\n module = _MODULES.get(name)\r\n if module is None:\r\n module = _load(name, params["path"])\r\n # Reloaded when the caller says the file changed, so an edit mid-session takes\r\n # effect without a restart.\r\n if params.get("reload"):\r\n module = _load(name, params["path"])\r\n\r\n captured = io.StringIO()\r\n with redirect_stdout(captured):\r\n result = module.run(**(params.get("arguments") or {}))\r\n printed = captured.getvalue()\r\n return {\r\n "result": result,\r\n # Returned rather than discarded: a print is how people debug, and swallowing it\r\n # makes a misbehaving tool impossible to diagnose from the chat.\r\n "stdout": printed,\r\n }\r\n\r\n raise ValueError(f"unknown method: {method}")\r\n\r\n\r\ndef main() -> None:\r\n for line in sys.stdin:\r\n line = line.strip()\r\n if not line:\r\n continue\r\n try:\r\n request = json.loads(line)\r\n except json.JSONDecodeError:\r\n continue\r\n\r\n request_id = request.get("id")\r\n try:\r\n _respond({"id": request_id, "ok": True, "value": _handle(request)})\r\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\r\n # The traceback is the payload: \xA713 requires a failed tool to return it to the\r\n # model so it can fix its own code, rather than a one-line summary it cannot act on.\r\n _respond(\r\n {\r\n "id": request_id,\r\n "ok": False,\r\n "error": f"{type(error).__name__}: {error}",\r\n "traceback": traceback.format_exc(),\r\n }\r\n )\r\n\r\n\r\nif __name__ == "__main__":\r\n main()\r\n';
59137
+ var PYTHON_WORKER_SOURCE = '"""Light Code\'s Python tool worker.\n\nOne long-lived process per workspace, speaking JSON-RPC over stdio. It owns three jobs the\nTypeScript side cannot do for itself:\n\n* deriving a JSON Schema from ``run``\'s type hints, so tool metadata is never hand-written\n and therefore never drifts from the code (CLAUDE.md \xA713);\n* importing and reloading tool modules, so a tool edited mid-session takes effect without\n restarting;\n* running the tool.\n\nFraming is one JSON object per line. Length-prefixing would be sturdier, but a tool that\nprints to stdout is *common* \u2014 so the reader tolerates unparseable lines instead, treating\nthem as the tool\'s own output rather than corrupting the channel.\n"""\n\nfrom __future__ import annotations\n\nimport importlib.util\nimport inspect\nimport io\nimport json\nimport os\nimport re\nimport sys\nimport time\nimport traceback\nimport types\nfrom contextlib import redirect_stdout\nfrom pathlib import Path\nfrom typing import Any\n\n# Loaded modules, keyed by tool name, so a reload replaces rather than shadows.\n_MODULES: dict[str, Any] = {}\n\n\ndef _respond(payload: dict[str, Any]) -> None:\n """Write one frame.\n\n Always to the real stdout, captured at import time \u2014 a tool that reassigns\n ``sys.stdout`` would otherwise silently swallow every subsequent reply.\n """\n _REAL_STDOUT.write(json.dumps(payload) + "\\n")\n _REAL_STDOUT.flush()\n\n\n_REAL_STDOUT = sys.stdout\n_REAL_STDIN = sys.stdin\n\n# Counts nested calls out to the host, so a loop is stopped rather than left to fill the pipe.\n_CALL_DEPTH = 0\n_MAX_DEPTH = 4\n_CURRENT_TOOL = ""\n_CALL_SEQ = 0\n\n\nclass ToolError(RuntimeError):\n """A tool this one called came back with a failure."""\n\n\ndef call_tool(name: str, **arguments: Any) -> Any:\n """Calls another tool and returns its result.\n\n Available to every tool as ``light_code.call_tool``. Only other Python tools and MCP\n tools can be reached; see the host for why.\n\n This blocks the worker, which is correct: the tool asked for something and cannot\n continue without it. The host may prompt the user before running it, so it can take as\n long as a person takes to answer.\n """\n global _CALL_DEPTH\n if _CALL_DEPTH >= _MAX_DEPTH:\n raise ToolError(\n f"tool calls are nested {_MAX_DEPTH} deep, which is almost certainly a loop - "\n "a tool calling itself, or two calling each other"\n )\n\n global _CALL_SEQ\n _CALL_SEQ += 1\n # A counter, not ``id()``: CPython reuses an address the moment the object is collected, so\n # two calls in a row could be handed the same token.\n token = f"cb{_CALL_SEQ}"\n _CALL_DEPTH += 1\n try:\n _respond(\n {\n "callback": token,\n "method": "call_tool",\n "name": name,\n "arguments": arguments,\n "caller": _CURRENT_TOOL,\n }\n )\n # Read until the answer to *this* call arrives. Anything else on the stream would be a\n # protocol error rather than something to skip, so it is reported rather than ignored.\n while True:\n line = _REAL_STDIN.readline()\n if not line:\n raise ToolError("the host closed the connection while waiting for " + name)\n line = line.strip()\n if not line:\n continue\n frame = json.loads(line)\n\n if frame.get("callback") == token:\n if frame.get("ok"):\n return frame.get("value")\n raise ToolError(frame.get("error") or f"{name} failed")\n\n # An ordinary request, arriving while this tool is blocked.\n #\n # It happens for real: the tool this one called is *another Python tool*, so the host\n # sends it down the same pipe while we are still waiting. Skipping it would deadlock \u2014\n # the host waits for a reply that nobody is reading for \u2014 and treating it as an\n # out-of-order answer, which the first version did, fails every nested call between\n # two Python tools. So it is served here and the wait resumes.\n if "method" in frame:\n request_id = frame.get("id")\n try:\n _respond({"id": request_id, "ok": True, "value": _handle(frame)})\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\n _respond(\n {\n "id": request_id,\n "ok": False,\n "error": f"{type(error).__name__}: {error}",\n "traceback": traceback.format_exc(),\n }\n )\n continue\n\n raise ToolError(\n "unexpected frame while waiting for " + name + "; this is a bug in Light Code"\n )\n finally:\n _CALL_DEPTH -= 1\n\n\ndef _install_helper_module() -> None:\n """Publishes ``light_code`` so a tool can ``import light_code`` and call other tools.\n\n A real module in ``sys.modules`` rather than a builtin or an injected global: a tool is\n an ordinary Python file that must also be readable, lintable and runnable on its own\n terms, and magic names appearing from nowhere break every one of those.\n """\n if "light_code" in sys.modules:\n return\n module = types.ModuleType("light_code")\n module.call_tool = call_tool # type: ignore[attr-defined]\n module.ToolError = ToolError # type: ignore[attr-defined]\n sys.modules["light_code"] = module\n\n\n# --- running in somebody\'s live Jupyter kernel ---------------------------------------------\n#\n# Requested so that a notebook can drive Light Code and have its tools see the session\'s own\n# state - the dataframe that is already loaded, the model that took ten minutes to fit.\n#\n# ## Why the kernel is named to us rather than discovered by us\n#\n# A kernel knows its own connection file (``ipykernel.get_connection_file()``); nothing outside\n# it does. From another process all you can do is list ``<runtime-dir>/kernel-*.json`` and\n# guess, and with more than one kernel running - the ordinary case for anybody who uses\n# Jupyter - a guess means running somebody\'s tool inside the wrong notebook. That is the same\n# refusal the Excel tools make about attaching: answering "the session I have open" with a\n# different one is worse than asking.\n#\n# So the connection file arrives in ``LIGHT_CODE_JUPYTER_CONNECTION_FILE``, and the host has a\n# discovery helper that only ever *offers* candidates.\n#\n# ## Why the result comes back behind a marker\n#\n# The same reason the identity and credential wrappers do it (CLAUDE.md section 14): a kernel\n# is full of libraries that print. Licence banners, deprecation warnings and progress bars all\n# arrive on the same channel as the answer, and reading "the output" would hand back a log line\n# while looking like it had worked.\n\n_KERNEL_MARKER = "__LIGHT_CODE_RESULT__"\n_kernel_client: Any = None\n\n\ndef _kernel_connection_file() -> str:\n return (os.environ.get("LIGHT_CODE_JUPYTER_CONNECTION_FILE") or "").strip()\n\n\ndef _kernel() -> Any:\n """The client for the configured kernel, connected once and kept.\n\n Reconnecting per call would pay the handshake every time and, worse, would lose the\n channel\'s message ordering guarantees mid-conversation.\n """\n global _kernel_client\n if _kernel_client is not None:\n return _kernel_client\n\n connection_file = _kernel_connection_file()\n if not connection_file:\n raise RuntimeError("no Jupyter kernel is configured for this session")\n if not Path(connection_file).exists():\n raise RuntimeError(\n f"the kernel connection file is gone: {connection_file}. The kernel it described "\n "has probably been shut down or restarted - restart the notebook\'s Light Code "\n "session so it picks up the new one."\n )\n\n try:\n from jupyter_client import BlockingKernelClient\n except ImportError as error:\n raise RuntimeError(\n "running tools in a Jupyter kernel needs jupyter_client, which is not importable "\n "from this interpreter. It ships with Jupyter, so install it into the same "\n "environment the kernel runs in: pip install jupyter_client"\n ) from error\n\n client = BlockingKernelClient()\n client.load_connection_file(connection_file)\n client.start_channels()\n try:\n # Proves the kernel is actually there before any tool is run. Without it the first\n # failure is a silent timeout in the middle of somebody\'s tool, which reads as the tool\n # hanging rather than as the kernel being gone.\n client.wait_for_ready(timeout=20)\n except RuntimeError as error:\n client.stop_channels()\n raise RuntimeError(\n f"connected to the kernel described by {connection_file} but it never became "\n "ready. It may be busy running a cell, or it may have died."\n ) from error\n\n _kernel_client = client\n # Sent here, on the one path that produces a connected client.\n #\n # The first version defined `_kernel_preamble` and never called it, so every tool call\n # arrived at a kernel that had never heard of `_lc_json` and failed with a NameError on\n # line 1. Nothing in the TypeScript, the schema or the wiring was wrong, and no test of\n # any of them could have seen it - it took starting a real kernel and asking it. That is\n # the same shape as `s3.tools` shipping with nothing on the other end.\n _kernel_run(client, _kernel_preamble(), timeout=30)\n return client\n\n\ndef _kernel_preamble() -> str:\n """Code run in the kernel before any tool is, exactly once.\n\n Everything it defines is prefixed and kept in one dict, because this is *somebody\'s\n notebook*: a bare ``json`` or ``run`` left in their globals would shadow their own name and\n break a cell they wrote, a long way from anything they would connect to us.\n\n ## It also installs ``light_code`` in the kernel, and that is not optional\n\n A tool written against ``light_code.call_tool`` imports that module. The worker registers\n it in *its own* ``sys.modules``, which the kernel has never heard of - so without this,\n moving a tool into a kernel turns a working tool into an ImportError whose message points\n at the tool rather than at the move. Found by running it, not by reading it.\n\n ``call_tool`` raises there rather than working, and says why: the callback rides on this\n worker\'s stdio and the kernel has no route back to the host. An honest refusal beats a\n name that exists and hangs.\n\n ``session`` is the point of the whole feature - it *is* the notebook\'s namespace, so a\n tool can read the dataframe that is already loaded.\n """\n return (\n "import json as _lc_json, io as _lc_io, pathlib as _lc_path, sys as _lc_sys, "\n "types as _lc_types, traceback as _lc_tb\\n"\n "from contextlib import redirect_stdout as _lc_redirect\\n"\n "_lc_tools = globals().setdefault(\'_lc_tools\', {})\\n"\n "if \'light_code\' not in _lc_sys.modules:\\n"\n " _lc_helper = _lc_types.ModuleType(\'light_code\')\\n"\n " _lc_helper.session = globals()\\n"\n " class _LcToolError(RuntimeError):\\n"\n " pass\\n"\n " def _lc_no_call(*_a, **_k):\\n"\n " raise _LcToolError(\'call_tool is not available to a tool running inside "\n "a Jupyter kernel: the callback channel belongs to the Light Code worker, and the "\n "kernel has no route back to the host.\')\\n"\n " _lc_helper.call_tool = _lc_no_call\\n"\n " _lc_helper.ToolError = _LcToolError\\n"\n " _lc_sys.modules[\'light_code\'] = _lc_helper\\n"\n )\n\n\ndef _kernel_call_code(name: str, path: str, arguments: dict[str, Any], reload: bool) -> str:\n """The code sent to the kernel for one tool call.\n\n The tool\'s source is executed **in the kernel**, so its imports resolve against the\n kernel\'s environment and its ``run`` sees the kernel\'s globals if it asks for them. The\n module is cached there between calls, and reloaded on the same signal the local path uses.\n """\n payload = json.dumps(\n {"name": name, "path": path, "arguments": arguments, "reload": bool(reload)}\n )\n # A single JSON literal rather than interpolated values: every one of these is\n # model-supplied, and building source by concatenation is how a quote in an argument\n # becomes a syntax error at best (CLAUDE.md section 16\'s rule, applied to code rather than\n # to a command line).\n return (\n f"_lc_req = _lc_json.loads({payload!r})\\n"\n "_lc_out = _lc_io.StringIO()\\n"\n "try:\\n"\n " if _lc_req[\'reload\'] or _lc_req[\'name\'] not in _lc_tools:\\n"\n " _lc_mod = _lc_types.ModuleType(\'light_code_tool_\' + _lc_req[\'name\'])\\n"\n " _lc_mod.__file__ = _lc_req[\'path\']\\n"\n # The notebook\'s own namespace, as a module-level name, so the simplest possible\n # tool - `session[\'df\']` - needs no import at all. This is the whole feature.\n " _lc_mod.session = globals()\\n"\n " _lc_src = _lc_path.Path(_lc_req[\'path\']).read_text(encoding=\'utf-8\')\\n"\n " with _lc_redirect(_lc_out):\\n"\n " exec(compile(_lc_src, _lc_req[\'path\'], \'exec\'), _lc_mod.__dict__)\\n"\n " if not hasattr(_lc_mod, \'run\'):\\n"\n " raise AttributeError(_lc_req[\'path\'] + \' defines no `run` function\')\\n"\n " _lc_tools[_lc_req[\'name\']] = _lc_mod\\n"\n " with _lc_redirect(_lc_out):\\n"\n " _lc_value = _lc_tools[_lc_req[\'name\']].run(**_lc_req[\'arguments\'])\\n"\n " try:\\n"\n " _lc_json.dumps(_lc_value)\\n"\n " _lc_payload = {\'ok\': True, \'result\': _lc_value, "\n "\'stdout\': _lc_out.getvalue()}\\n"\n " except TypeError:\\n"\n # A DataFrame, a model, a connection - returned rather than refused. `repr` is what a\n # notebook would have shown, and losing the answer because it does not serialise would\n # be the worst outcome of a feature whose point is reaching live objects.\n " _lc_payload = {\'ok\': True, \'result\': repr(_lc_value), \'repr\': True, "\n "\'stdout\': _lc_out.getvalue()}\\n"\n "except Exception as _lc_err:\\n"\n " _lc_payload = {\'ok\': False, \'error\': type(_lc_err).__name__ + \': \' + str(_lc_err), "\n "\'traceback\': _lc_tb.format_exc(), \'stdout\': _lc_out.getvalue()}\\n"\n f"print({_KERNEL_MARKER!r} + _lc_json.dumps(_lc_payload))\\n"\n )\n\n\ndef _kernel_execute(code: str, timeout: float) -> dict[str, Any]:\n """Runs code in the kernel and reads back the marked result.\n\n Output that is not the marker is the kernel\'s own chatter and is kept separately, so a\n library\'s banner is never mistaken for the answer.\n """\n return _kernel_run(_kernel(), code, timeout)\n\n\ndef _kernel_run(client: Any, code: str, timeout: float) -> dict[str, Any]:\n """The same, against a client already in hand.\n\n Split out so the preamble can be sent from inside ``_kernel`` - going through\n ``_kernel_execute`` there would call back into ``_kernel`` before it had returned.\n """\n msg_id = client.execute(code, store_history=False)\n\n answer: dict[str, Any] | None = None\n chatter: list[str] = []\n deadline = time.monotonic() + timeout\n\n while True:\n remaining = deadline - time.monotonic()\n if remaining <= 0:\n raise TimeoutError(\n "the kernel did not answer in time. It is probably busy running a cell - a "\n "kernel runs one thing at a time, so a tool waits for whatever is already going."\n )\n try:\n message = client.get_iopub_msg(timeout=min(remaining, 1.0))\n except Exception: # noqa: BLE001 - an empty queue is the ordinary case, so poll again\n continue\n\n if message.get("parent_header", {}).get("msg_id") != msg_id:\n # Somebody else\'s cell. Ignored rather than read: this is a shared kernel and the\n # user is still using it.\n continue\n\n kind = message.get("msg_type")\n content = message.get("content", {})\n if kind == "stream":\n for line in content.get("text", "").splitlines():\n if line.startswith(_KERNEL_MARKER):\n answer = json.loads(line[len(_KERNEL_MARKER):])\n else:\n chatter.append(line)\n elif kind == "error":\n # Raised *before* the tool\'s own code could print the marker: a bad compile, or the\n # kernel dying. The tool\'s own exceptions come back inside the payload instead.\n raise RuntimeError(\n "the kernel refused the call: " + "\\n".join(content.get("traceback", []))\n )\n elif kind == "status" and content.get("execution_state") == "idle":\n break\n\n if answer is None:\n if _KERNEL_MARKER not in code:\n # Setup rather than a call: it is not meant to print anything.\n return {}\n raise RuntimeError(\n "the kernel finished without returning a result. If it was restarted mid-call, "\n "reconnect the notebook\'s Light Code session."\n )\n if chatter:\n answer["stdout"] = (answer.get("stdout") or "") + "\\n".join(chatter)\n return answer\n\n\ndef _load(name: str, path: str) -> Any:\n """Imports a tool module from an explicit path, replacing any previous version."""\n _install_helper_module()\n spec = importlib.util.spec_from_file_location(f"light_code_tool_{name}", path)\n if spec is None or spec.loader is None:\n raise ImportError(f"could not load {path}")\n module = importlib.util.module_from_spec(spec)\n # Executed with the tool\'s own stdout captured: a print at import time would otherwise\n # land in the middle of the JSON-RPC stream.\n with redirect_stdout(io.StringIO()):\n spec.loader.exec_module(module)\n if not hasattr(module, "run"):\n raise AttributeError(f"{path} defines no `run` function")\n _MODULES[name] = module\n return module\n\n\ndef _google_arg_docs(doc: str) -> dict[str, str]:\n """Pulls parameter descriptions out of a Google-style ``Args:`` block.\n\n Best-effort by design. A missing description costs the model a hint; a parser that threw\n would cost it the whole tool.\n """\n docs: dict[str, str] = {}\n match = re.search(r"^\\s*Args:\\s*$(.*?)(?=^\\s*\\w+:\\s*$|\\Z)", doc, re.MULTILINE | re.DOTALL)\n if not match:\n return docs\n for line in match.group(1).splitlines():\n entry = re.match(r"\\s*(\\w+)\\s*(?:\\([^)]*\\))?\\s*:\\s*(.+)", line)\n if entry:\n docs[entry.group(1)] = entry.group(2).strip()\n return docs\n\n\n#: Annotations the fallback can map without pydantic. Anything else becomes a string,\n#: which is lossy but callable.\n_PRIMITIVE_TYPES: dict[Any, str] = {\n str: "string",\n bool: "boolean",\n int: "integer",\n float: "number",\n list: "array",\n dict: "object",\n}\n\n\ndef _fallback_schema(run: Any) -> dict[str, Any]:\n """Derives a schema from bare annotations, for when pydantic is not installed.\n\n Worth doing properly rather than declaring everything a string: a ``bool`` advertised as\n a string means the model sends ``"true"`` and the tool receives the string ``"true"``,\n which is truthy for every value including ``"false"``. Silent, and wrong.\n """\n signature = inspect.signature(run)\n properties: dict[str, Any] = {}\n required: list[str] = []\n\n for name, parameter in signature.parameters.items():\n if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):\n continue\n annotation = parameter.annotation\n # A string annotation appears under `from __future__ import annotations`; resolving\n # it properly needs typing.get_type_hints, which can itself fail on a forward ref.\n if isinstance(annotation, str):\n annotation = {"str": str, "bool": bool, "int": int, "float": float}.get(annotation, inspect.Parameter.empty)\n properties[name] = {"type": _PRIMITIVE_TYPES.get(annotation, "string")}\n if parameter.default is parameter.empty:\n required.append(name)\n\n return {"type": "object", "properties": properties, "required": required}\n\n\ndef _schema_for(module: Any) -> dict[str, Any]:\n """Derives the parameter schema from ``run``\'s type hints.\n\n pydantic when available, because it handles unions, defaults, nested models and\n ``Optional`` correctly. The fallback treats every parameter as a string, which is worse\n but still callable \u2014 better than refusing to register a tool because pydantic is missing.\n """\n run = module.run\n try:\n from pydantic import TypeAdapter\n\n schema = TypeAdapter(run).json_schema()\n properties = schema.get("properties", {})\n except Exception: # noqa: BLE001 - any pydantic failure falls back rather than failing\n schema = _fallback_schema(run)\n properties = schema["properties"]\n\n doc = inspect.getdoc(run) or inspect.getdoc(module) or ""\n for name, description in _google_arg_docs(doc).items():\n if name in properties:\n properties[name]["description"] = description\n\n schema.setdefault("type", "object")\n schema["properties"] = properties\n return schema\n\n\ndef _describe(name: str, path: str) -> dict[str, Any]:\n module = _load(name, path)\n # The module docstring, not run\'s: it describes the tool, whereas run\'s docstring\n # usually documents the parameters.\n description = (inspect.getdoc(module) or inspect.getdoc(module.run) or "").strip()\n return {"name": name, "description": description, "schema": _schema_for(module)}\n\n\ndef _handle(request: dict[str, Any]) -> dict[str, Any]:\n method = request.get("method")\n params = request.get("params") or {}\n\n if method == "ping":\n connection_file = _kernel_connection_file()\n # Reported rather than merely configured, so the Python tab can say *which* kernel\n # tools run in. "It is using my notebook" is not something anybody should have to\n # infer from a tool seeing a variable it should not have.\n return {\n "ok": True,\n "python": sys.version,\n **({"jupyterConnectionFile": connection_file} if connection_file else {}),\n }\n\n if method == "describe":\n return _describe(params["name"], params["path"])\n\n if method == "validate":\n # Parsed before importing, so a syntax error is reported as one rather than as\n # whatever the import machinery happens to raise.\n source = Path(params["path"]).read_text(encoding="utf-8")\n compile(source, params["path"], "exec")\n return _describe(params["name"], params["path"])\n\n if method == "call":\n name = params["name"]\n # Recorded so a nested call can say *who* is asking. An approval prompt naming only the\n # callee is the prompt people click through.\n global _CURRENT_TOOL\n _CURRENT_TOOL = name\n\n if _kernel_connection_file():\n """Run it where the user\'s own session is.\n\n The whole call goes over, source and all, so the tool\'s imports resolve against\n the kernel\'s environment rather than this one - which is the point: the notebook\n has the libraries and the loaded data, and this process has neither.\n\n The registry is unchanged by this. A tool still had to be approved here, with its\n source shown, before it could ever be called - so running it elsewhere widens\n where the code runs and not who may run it.\n """\n answer = _kernel_execute(\n _kernel_call_code(\n name,\n params["path"],\n params.get("arguments") or {},\n bool(params.get("reload")),\n ),\n # Generous, and bounded anyway by the host\'s own per-tool timeout. A kernel\n # runs one thing at a time, so a tool legitimately waits behind whatever cell\n # the user just ran.\n timeout=float(params.get("timeoutSeconds") or 600),\n )\n if not answer.get("ok"):\n # Re-raised rather than returned, so it reaches the model as a failure with a\n # traceback exactly as a local one does. Section 13 wants the traceback: it is\n # what lets the model fix its own code.\n error = RuntimeError(answer.get("error") or "the tool failed in the kernel")\n error.kernel_traceback = answer.get("traceback") # type: ignore[attr-defined]\n raise error\n return {\n "result": answer.get("result"),\n "stdout": answer.get("stdout") or "",\n "ranInKernel": True,\n # Said out loud when the value could not be JSON, so nobody reads a repr as\n # the structure it is a picture of.\n **({"resultIsRepr": True} if answer.get("repr") else {}),\n }\n\n module = _MODULES.get(name)\n if module is None:\n module = _load(name, params["path"])\n # Reloaded when the caller says the file changed, so an edit mid-session takes\n # effect without a restart.\n if params.get("reload"):\n module = _load(name, params["path"])\n\n captured = io.StringIO()\n with redirect_stdout(captured):\n result = module.run(**(params.get("arguments") or {}))\n printed = captured.getvalue()\n return {\n "result": result,\n # Returned rather than discarded: a print is how people debug, and swallowing it\n # makes a misbehaving tool impossible to diagnose from the chat.\n "stdout": printed,\n }\n\n raise ValueError(f"unknown method: {method}")\n\n\ndef main() -> None:\n for line in sys.stdin:\n line = line.strip()\n if not line:\n continue\n try:\n request = json.loads(line)\n except json.JSONDecodeError:\n continue\n\n request_id = request.get("id")\n try:\n _respond({"id": request_id, "ok": True, "value": _handle(request)})\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\n # The traceback is the payload: \xA713 requires a failed tool to return it to the\n # model so it can fix its own code, rather than a one-line summary it cannot act on.\n _respond(\n {\n "id": request_id,\n "ok": False,\n "error": f"{type(error).__name__}: {error}",\n # The kernel\'s own traceback when the failure happened there. Ours would\n # be a stack through this file, which says nothing about the tool and is\n # the one thing section 13 wants the model to be able to act on.\n "traceback": getattr(error, "kernel_traceback", None)\n or traceback.format_exc(),\n }\n )\n\n\nif __name__ == "__main__":\n main()\n';
58875
59138
 
58876
59139
  // ../../packages/core/dist/python/manager.js
58877
59140
  var PythonManager = class {
@@ -58910,6 +59173,8 @@ var PythonManager = class {
58910
59173
  * changed variable would apply at the next window rather than the next call.
58911
59174
  */
58912
59175
  envEntries = [];
59176
+ /** The Jupyter kernel tools run in, when this session was given one. See `jupyter.ts`. */
59177
+ jupyterConnectionFile;
58913
59178
  envFingerprint = "";
58914
59179
  missingEnv = [];
58915
59180
  constructor(options) {
@@ -58941,7 +59206,11 @@ var PythonManager = class {
58941
59206
  }
58942
59207
  this.enabled = true;
58943
59208
  this.envEntries = pythonEnvEntries(config2.env);
58944
- const fingerprint = JSON.stringify(this.envEntries);
59209
+ const fromEnvironment = (process.env[JUPYTER_CONNECTION_ENV] ?? "").trim();
59210
+ const fromConfig = (config2.jupyterConnectionFile ?? "").trim();
59211
+ const kernel = fromEnvironment.length > 0 ? fromEnvironment : fromConfig;
59212
+ this.jupyterConnectionFile = kernel.length > 0 ? kernel : void 0;
59213
+ const fingerprint = JSON.stringify([this.envEntries, this.jupyterConnectionFile]);
58945
59214
  if (fingerprint !== this.envFingerprint) {
58946
59215
  this.envFingerprint = fingerprint;
58947
59216
  if (this.worker !== void 0) {
@@ -59260,7 +59529,22 @@ var PythonManager = class {
59260
59529
  async childEnv() {
59261
59530
  const resolved = await resolvePythonEnv(this.envEntries, this.options.secrets);
59262
59531
  this.missingEnv = resolved.missing;
59263
- return minimalPythonEnv({ ...this.options.sessionEnv?.() ?? {}, ...resolved.env });
59532
+ return minimalPythonEnv({
59533
+ ...this.options.sessionEnv?.() ?? {},
59534
+ /*
59535
+ * The Jupyter kernel tools run in, when the session was given one.
59536
+ *
59537
+ * Here rather than at the spawn site for this function's own reason: the worker, `uv
59538
+ * venv` and a dependency install must all agree about which environment they are in, and
59539
+ * a variable set at one of three places is the drift this file exists to prevent.
59540
+ *
59541
+ * Before `resolved.env`, so a user who declares the same name in `python.env` wins. They
59542
+ * have said something more specific than the session default, and silently overriding a
59543
+ * declaration would be the setting not working.
59544
+ */
59545
+ ...this.jupyterConnectionFile !== void 0 ? { [JUPYTER_CONNECTION_ENV]: this.jupyterConnectionFile } : {},
59546
+ ...resolved.env
59547
+ });
59264
59548
  }
59265
59549
  async dispose() {
59266
59550
  const worker = this.worker;
@@ -59522,7 +59806,7 @@ function createSearchDocsTool(options) {
59522
59806
  ].filter((line) => line.length > 0).join("\n")
59523
59807
  };
59524
59808
  } catch (error51) {
59525
- const message3 = error51 instanceof Error ? error51.message : String(error51);
59809
+ const message4 = error51 instanceof Error ? error51.message : String(error51);
59526
59810
  options.observer?.record({
59527
59811
  at: startedAt,
59528
59812
  source: "search_docs",
@@ -59530,9 +59814,9 @@ function createSearchDocsTool(options) {
59530
59814
  ...options.retrieval !== void 0 ? { collection: options.retrieval.index } : {},
59531
59815
  hits: 0,
59532
59816
  elapsedMs: Date.now() - startedAt,
59533
- error: message3
59817
+ error: message4
59534
59818
  });
59535
- return { content: message3, isError: true };
59819
+ return { content: message4, isError: true };
59536
59820
  }
59537
59821
  }
59538
59822
  };
@@ -59634,16 +59918,16 @@ var MAX_CONTINUE_NUDGES = 1;
59634
59918
  var UNANSWERED = "This tool call never reported a result \u2014 the turn ended before it did. Nothing can be assumed about whether it ran or what it changed. If it still matters, call it again; otherwise carry on.";
59635
59919
  function repairUnansweredToolCalls(messages) {
59636
59920
  const answered = /* @__PURE__ */ new Set();
59637
- for (const message3 of messages) {
59638
- if (message3.role === "tool" && message3.toolCallId !== void 0)
59639
- answered.add(message3.toolCallId);
59921
+ for (const message4 of messages) {
59922
+ if (message4.role === "tool" && message4.toolCallId !== void 0)
59923
+ answered.add(message4.toolCallId);
59640
59924
  }
59641
59925
  const repaired = [];
59642
- for (const message3 of messages) {
59643
- repaired.push(message3);
59644
- if (message3.role !== "assistant" || message3.toolCalls === void 0)
59926
+ for (const message4 of messages) {
59927
+ repaired.push(message4);
59928
+ if (message4.role !== "assistant" || message4.toolCalls === void 0)
59645
59929
  continue;
59646
- for (const call of message3.toolCalls) {
59930
+ for (const call of message4.toolCalls) {
59647
59931
  if (answered.has(call.id))
59648
59932
  continue;
59649
59933
  repaired.push({ role: "tool", toolCallId: call.id, content: UNANSWERED });
@@ -60002,9 +60286,9 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
60002
60286
  conversation.addToolResultMessage(toolCall.id, forModel);
60003
60287
  events.onToolResult(toolCall, result);
60004
60288
  const queued = options.drainQueuedMessages?.() ?? [];
60005
- for (const message3 of queued) {
60006
- conversation.addUserMessage(message3.text, message3.images);
60007
- events.onQueuedMessageConsumed?.(message3.text);
60289
+ for (const message4 of queued) {
60290
+ conversation.addUserMessage(message4.text, message4.images);
60291
+ events.onQueuedMessageConsumed?.(message4.text);
60008
60292
  }
60009
60293
  if (queued.length > 0) {
60010
60294
  iteration = -1;
@@ -62188,6 +62472,140 @@ function Invoke-OutlookHarvest {\r
62188
62472
  \`Display\` opens Outlook's own read window - the real message, with its formatting, exactly as\r
62189
62473
  the user would see it if they had found it themselves. Nothing is modified and nothing is sent.\r
62190
62474
  #>\r
62475
+ <#\r
62476
+ Composes a message and puts it on screen. It never sends one.\r
62477
+ \r
62478
+ ## The rule this is built around\r
62479
+ \r
62480
+ Requested in exactly these terms: create the mail, attach what it needs, fill in the\r
62481
+ recipients if they were given, show it to the user, and let *them* press Send. So there is\r
62482
+ no Send call in here at all - not behind a flag, not behind a parameter. A flag would be one\r
62483
+ typo away from sending somebody's half-written mail to a distribution list, and the whole\r
62484
+ value of the feature is that a person reads it first.\r
62485
+ \r
62486
+ ## Why it is not saved either\r
62487
+ \r
62488
+ Display() shows the message without filing it. Closing the window then offers to save it,\r
62489
+ which is Outlook's own behaviour and the user's escape hatch - the same reasoning that leaves\r
62490
+ an edited workbook dirty rather than saving it for them. Saving to Drafts here would leave\r
62491
+ an item behind every time somebody decided against sending.\r
62492
+ \r
62493
+ ## Recipients are resolved, not just typed in\r
62494
+ \r
62495
+ Assigning a string to .To leaves it unresolved, so an unknown or ambiguous name sits there\r
62496
+ looking correct and fails at send time in front of whoever is sending it. Recipients.Add plus\r
62497
+ ResolveAll checks each one now, and the ones that did not resolve are reported back by name\r
62498
+ so the assistant can say which. An unresolvable address is still left in place rather than\r
62499
+ dropped: it may be an external address Outlook has no entry for, and silently removing a\r
62500
+ recipient is the worst of the available failures.\r
62501
+ #>\r
62502
+ function Invoke-OutlookCreateDraft {\r
62503
+ param($Request)\r
62504
+ \r
62505
+ # Attached, never launched, exactly as everything else here is. Creating an item on an\r
62506
+ # application that is not running would start Outlook invisibly and put the draft somewhere\r
62507
+ # nobody is looking.\r
62508
+ $app = Get-OfficeApp -ProgId 'Outlook.Application' -AttachOnly $true\r
62509
+ $mail = $app.CreateItem(0) # olMailItem\r
62510
+ \r
62511
+ $unresolved = @()\r
62512
+ # olTo = 1, olCC = 2, olBCC = 3.\r
62513
+ $buckets = @(\r
62514
+ @{ Values = $Request.to; Type = 1 },\r
62515
+ @{ Values = $Request.cc; Type = 2 },\r
62516
+ @{ Values = $Request.bcc; Type = 3 }\r
62517
+ )\r
62518
+ foreach ($bucket in $buckets) {\r
62519
+ if ($null -eq $bucket.Values) { continue }\r
62520
+ foreach ($address in $bucket.Values) {\r
62521
+ $text = [string]$address\r
62522
+ if ([string]::IsNullOrWhiteSpace($text)) { continue }\r
62523
+ $recipient = $mail.Recipients.Add($text.Trim())\r
62524
+ $recipient.Type = $bucket.Type\r
62525
+ if (-not $recipient.Resolve()) { $unresolved += $text.Trim() }\r
62526
+ }\r
62527
+ }\r
62528
+ \r
62529
+ if ($null -ne $Request.subject) { $mail.Subject = [string]$Request.subject }\r
62530
+ \r
62531
+ <#\r
62532
+ Attachments are added before the body is written, and that ordering is load-bearing.\r
62533
+ \r
62534
+ An inline image is an attachment carrying a content id that the HTML refers to as\r
62535
+ "cid:whatever". Setting HTMLBody first and attaching afterwards leaves Outlook holding a\r
62536
+ body whose img tags point at nothing - it renders as a broken-image placeholder, which\r
62537
+ looks like the picture failed to attach rather than like the order being wrong.\r
62538
+ #>\r
62539
+ $attached = @()\r
62540
+ $missing = @()\r
62541
+ $inlineCids = @{}\r
62542
+ \r
62543
+ if ($null -ne $Request.attachments) {\r
62544
+ foreach ($file in $Request.attachments) {\r
62545
+ $path = [string]$file\r
62546
+ if ([string]::IsNullOrWhiteSpace($path)) { continue }\r
62547
+ if (-not (Test-Path -LiteralPath $path)) { $missing += $path; continue }\r
62548
+ $null = $mail.Attachments.Add((Resolve-Path -LiteralPath $path).Path)\r
62549
+ $attached += (Split-Path -Leaf $path)\r
62550
+ }\r
62551
+ }\r
62552
+ \r
62553
+ if ($null -ne $Request.inlineImages) {\r
62554
+ foreach ($image in $Request.inlineImages) {\r
62555
+ $path = [string]$image.path\r
62556
+ if ([string]::IsNullOrWhiteSpace($path)) { continue }\r
62557
+ if (-not (Test-Path -LiteralPath $path)) { $missing += $path; continue }\r
62558
+ \r
62559
+ $item = $mail.Attachments.Add((Resolve-Path -LiteralPath $path).Path)\r
62560
+ $cid = [string]$image.cid\r
62561
+ if ([string]::IsNullOrWhiteSpace($cid)) { $cid = 'img' + [string]($inlineCids.Count + 1) }\r
62562
+ \r
62563
+ <#\r
62564
+ PR_ATTACH_CONTENT_ID_W. This is what makes an attachment an *embedded* picture\r
62565
+ rather than a paperclip: without it the file is attached and the img tag has\r
62566
+ nothing to resolve against.\r
62567
+ \r
62568
+ Wrapped because the property is refused on some stores and some older builds, and\r
62569
+ an image that arrives as an ordinary attachment is a far better outcome than a\r
62570
+ draft that could not be created at all. What it degrades to is reported rather\r
62571
+ than hidden, so the assistant can say the picture is attached but not inline.\r
62572
+ #>\r
62573
+ try {\r
62574
+ $item.PropertyAccessor.SetProperty(\r
62575
+ 'http://schemas.microsoft.com/mapi/proptag/0x3712001F', $cid)\r
62576
+ $inlineCids[$cid] = (Split-Path -Leaf $path)\r
62577
+ } catch {\r
62578
+ $attached += (Split-Path -Leaf $path)\r
62579
+ }\r
62580
+ }\r
62581
+ }\r
62582
+ \r
62583
+ $body = if ($null -ne $Request.body) { [string]$Request.body } else { '' }\r
62584
+ if ($Request.html -eq $true) {\r
62585
+ $mail.HTMLBody = $body\r
62586
+ } else {\r
62587
+ $mail.Body = $body\r
62588
+ }\r
62589
+ \r
62590
+ <#\r
62591
+ Shown, not sent and not saved.\r
62592
+ \r
62593
+ Display($false) is the non-modal form: the worker must not block waiting for a window\r
62594
+ somebody may leave open for an hour, and a modal call here would hold the single request\r
62595
+ pipe and time out every other Office tool behind it.\r
62596
+ #>\r
62597
+ $mail.Display($false)\r
62598
+ \r
62599
+ return @{\r
62600
+ displayed = $true\r
62601
+ subject = [string]$mail.Subject\r
62602
+ attached = @($attached)\r
62603
+ inline = @($inlineCids.Keys)\r
62604
+ missing = @($missing)\r
62605
+ unresolved = @($unresolved)\r
62606
+ }\r
62607
+ }\r
62608
+ \r
62191
62609
  function Invoke-OutlookDisplay {\r
62192
62610
  param($Request)\r
62193
62611
  \r
@@ -62318,6 +62736,7 @@ function Invoke-Request {\r
62318
62736
  'outlook.folders' { return Invoke-OutlookFolders -Request $Request }\r
62319
62737
  'outlook.validateFolder' { return Invoke-OutlookValidateFolder -Request $Request }\r
62320
62738
  'outlook.harvest' { return Invoke-OutlookHarvest -Request $Request }\r
62739
+ 'outlook.createDraft' { return Invoke-OutlookCreateDraft -Request $Request }\r
62321
62740
  'outlook.display' { return Invoke-OutlookDisplay -Request $Request }\r
62322
62741
  'outlook.search' { return Invoke-OutlookSearch -Request $Request }\r
62323
62742
  'outlook.read' { return Invoke-OutlookRead -Request $Request }\r
@@ -62441,21 +62860,21 @@ var OfficeBridge = class {
62441
62860
  index = this.buffer.indexOf("\n");
62442
62861
  if (line.length === 0)
62443
62862
  continue;
62444
- let message3;
62863
+ let message4;
62445
62864
  try {
62446
- message3 = JSON.parse(line);
62865
+ message4 = JSON.parse(line);
62447
62866
  } catch {
62448
62867
  this.options.logger.warn(`office worker: unparsed output ${line.slice(0, 200)}`);
62449
62868
  continue;
62450
62869
  }
62451
- const pending = message3.id === void 0 ? void 0 : this.waiting.get(message3.id);
62870
+ const pending = message4.id === void 0 ? void 0 : this.waiting.get(message4.id);
62452
62871
  if (pending === void 0)
62453
62872
  continue;
62454
- this.waiting.delete(message3.id);
62455
- if (message3.ok === true)
62456
- pending.resolve(message3.result);
62873
+ this.waiting.delete(message4.id);
62874
+ if (message4.ok === true)
62875
+ pending.resolve(message4.result);
62457
62876
  else
62458
- pending.reject(new Error(message3.error ?? "The Excel/Outlook helper reported an unknown failure."));
62877
+ pending.reject(new Error(message4.error ?? "The Excel/Outlook helper reported an unknown failure."));
62459
62878
  }
62460
62879
  }
62461
62880
  async dispose() {
@@ -62765,6 +63184,129 @@ function deriveIndexName(input) {
62765
63184
  return slug === void 0 ? `${prefix}-${digest}` : `${prefix}-${slug}-${digest}`;
62766
63185
  }
62767
63186
 
63187
+ // ../../packages/core/dist/tools/outlookDraft.js
63188
+ var addresses = external_exports.array(external_exports.string().min(1)).max(100).optional();
63189
+ var paramsSchema11 = external_exports.object({
63190
+ to: addresses.describe("Recipients. Email addresses, or names Outlook can resolve."),
63191
+ cc: addresses.describe("Carbon-copy recipients."),
63192
+ bcc: addresses.describe("Blind carbon-copy recipients."),
63193
+ subject: external_exports.string().max(500).optional().describe("Subject line."),
63194
+ body: external_exports.string().max(2e5).optional().describe("The message body. Plain text unless html is true."),
63195
+ html: external_exports.boolean().optional().describe('Treat body as HTML. Required if you are embedding images: refer to each one as <img src="cid:THE_CID"> using the cid you gave it in inlineImages.'),
63196
+ attachments: external_exports.array(external_exports.string().min(1)).max(20).optional().describe("Files to attach, as paths. They appear as ordinary attachments."),
63197
+ inlineImages: external_exports.array(external_exports.object({
63198
+ path: external_exports.string().min(1).describe("The image file."),
63199
+ cid: external_exports.string().min(1).max(80).regex(/^[A-Za-z0-9._-]+$/, "A cid may only contain letters, digits, dot, underscore and hyphen.").describe("The id your HTML refers to as cid:THIS.")
63200
+ })).max(20).optional().describe('Images shown inside the message rather than as attachments. Needs html: true and an <img src="cid:..."> in the body for each one.')
63201
+ });
63202
+ function message2(error51) {
63203
+ return error51 instanceof Error ? error51.message : String(error51);
63204
+ }
63205
+ function filesIn(params) {
63206
+ return [
63207
+ ...(params.attachments ?? []).map((path35) => ({ path: path35, inline: false })),
63208
+ ...(params.inlineImages ?? []).map((image) => ({ path: image.path, inline: true }))
63209
+ ];
63210
+ }
63211
+ function createOutlookDraftTool(options) {
63212
+ return {
63213
+ name: "outlook_create_draft",
63214
+ group: "command",
63215
+ description: 'Compose an email in the running Outlook and show it to the user, with recipients, subject, body, attachments and embedded images filled in. It is NEVER sent \u2014 it opens on screen and the user decides whether to send it, so write the message as if it is going out exactly as written. For an embedded image set html: true, list the file in inlineImages with a cid, and put <img src="cid:THAT_CID"> in the body; anything in attachments instead arrives as an ordinary attachment. Leave out recipients the user did not give you rather than guessing at them.',
63216
+ parametersSchema: paramsSchema11,
63217
+ /**
63218
+ * Ground truth: who it is addressed to, what it says, and what is attached — by name.
63219
+ *
63220
+ * Every recipient listed rather than counted, for `open_email`'s reason: "send to 12
63221
+ * people" hides which twelve, and the recipient list is the part of a draft that does the
63222
+ * damage if it is wrong. The body is shown in full up to a limit, because the user is being
63223
+ * asked to approve putting *this text* in front of a colleague.
63224
+ */
63225
+ async preview(params) {
63226
+ const lines = ["Compose a message in Outlook and show it to you. Nothing is sent.", ""];
63227
+ const recipients = [
63228
+ ["To", params.to],
63229
+ ["Cc", params.cc],
63230
+ ["Bcc", params.bcc]
63231
+ ];
63232
+ for (const [label, list] of recipients) {
63233
+ if (list !== void 0 && list.length > 0)
63234
+ lines.push(`${label}: ${list.join(", ")}`);
63235
+ }
63236
+ if (params.to === void 0 || params.to.length === 0) {
63237
+ lines.push("To: (nobody \u2014 you will fill this in)");
63238
+ }
63239
+ lines.push(`Subject: ${params.subject ?? "(none)"}`);
63240
+ const files = filesIn(params);
63241
+ if (files.length > 0) {
63242
+ lines.push("");
63243
+ lines.push("Files from this machine, put into the message:");
63244
+ for (const file2 of files) {
63245
+ lines.push(` ${file2.path}${file2.inline ? " (shown inside the message)" : ""}`);
63246
+ }
63247
+ }
63248
+ const body = params.body ?? "";
63249
+ lines.push("");
63250
+ lines.push(params.html === true ? "Body (HTML):" : "Body:");
63251
+ lines.push(body.length > 4e3 ? `${body.slice(0, 4e3)}
63252
+ \u2026(${String(body.length - 4e3)} more characters)` : body);
63253
+ return { kind: "text", text: lines.join("\n") };
63254
+ },
63255
+ async execute(params, context) {
63256
+ const attachments = [];
63257
+ const inlineImages = [];
63258
+ for (const file2 of params.attachments ?? []) {
63259
+ const resolved = await resolveToolPath(context, file2);
63260
+ if (!resolved.ok)
63261
+ return { content: resolved.message, isError: true };
63262
+ attachments.push(resolved.realPath);
63263
+ }
63264
+ for (const image of params.inlineImages ?? []) {
63265
+ const resolved = await resolveToolPath(context, image.path);
63266
+ if (!resolved.ok)
63267
+ return { content: resolved.message, isError: true };
63268
+ inlineImages.push({ path: resolved.realPath, cid: image.cid });
63269
+ }
63270
+ if (params.html !== true && inlineImages.length > 0) {
63271
+ return {
63272
+ content: 'Embedded images need html: true, and a plain-text body was given. Set html: true and write the body as HTML with an <img src="cid:..."> for each image, or move them to attachments to send them as ordinary attachments.',
63273
+ isError: true
63274
+ };
63275
+ }
63276
+ try {
63277
+ const result = await options.bridge.request({
63278
+ op: "outlook.createDraft",
63279
+ ...params.to !== void 0 ? { to: params.to } : {},
63280
+ ...params.cc !== void 0 ? { cc: params.cc } : {},
63281
+ ...params.bcc !== void 0 ? { bcc: params.bcc } : {},
63282
+ ...params.subject !== void 0 ? { subject: params.subject } : {},
63283
+ ...params.body !== void 0 ? { body: params.body } : {},
63284
+ ...params.html !== void 0 ? { html: params.html } : {},
63285
+ ...attachments.length > 0 ? { attachments } : {},
63286
+ ...inlineImages.length > 0 ? { inlineImages } : {}
63287
+ });
63288
+ const lines = [
63289
+ `The draft is open in Outlook: "${result.subject.length > 0 ? result.subject : "(no subject)"}".`,
63290
+ "It has NOT been sent. The user sends it, or edits it first, or closes it."
63291
+ ];
63292
+ if (result.attached.length > 0)
63293
+ lines.push(`Attached: ${result.attached.join(", ")}.`);
63294
+ if (result.inline.length > 0)
63295
+ lines.push(`Embedded in the body: ${result.inline.join(", ")}.`);
63296
+ if (result.missing.length > 0) {
63297
+ lines.push(`Could not be found, so they are NOT in the message: ${result.missing.join(", ")}. Tell the user, since the draft is already open.`);
63298
+ }
63299
+ if (result.unresolved.length > 0) {
63300
+ lines.push(`Outlook could not resolve these recipients: ${result.unresolved.join(", ")}. They are still on the message. Check the spelling with the user, or they may simply be external addresses your address book has no entry for.`);
63301
+ }
63302
+ return { content: lines.join("\n") };
63303
+ } catch (error51) {
63304
+ return { content: message2(error51), isError: true };
63305
+ }
63306
+ }
63307
+ };
63308
+ }
63309
+
62768
63310
  // ../../packages/core/dist/office/vbaCheck.js
62769
63311
  function splitLine(line) {
62770
63312
  let bare = "";
@@ -62914,7 +63456,7 @@ function createExcelRunMacroTool(options) {
62914
63456
  const found = await findMacroSource(options, params.workbook, params.macro);
62915
63457
  source = found ?? `(the source of "${params.macro}" could not be found \u2014 it may live in a module this cannot read)`;
62916
63458
  } catch (error51) {
62917
- source = `(the source could not be read: ${message2(error51)})`;
63459
+ source = `(the source could not be read: ${message3(error51)})`;
62918
63460
  }
62919
63461
  return {
62920
63462
  kind: "text",
@@ -62948,7 +63490,7 @@ function createExcelRunMacroTool(options) {
62948
63490
  }
62949
63491
  return { content: lines.join("\n"), ...result.failed ? { isError: true } : {} };
62950
63492
  } catch (error51) {
62951
- return { content: message2(error51), isError: true };
63493
+ return { content: message3(error51), isError: true };
62952
63494
  }
62953
63495
  }
62954
63496
  };
@@ -62972,7 +63514,7 @@ function createExcelEvaluateTool(options) {
62972
63514
  }
62973
63515
  return { content: `${result.expression} on ${result.sheet} gives: ${result.value ?? "(empty)"}` };
62974
63516
  } catch (error51) {
62975
- return { content: message2(error51), isError: true };
63517
+ return { content: message3(error51), isError: true };
62976
63518
  }
62977
63519
  }
62978
63520
  };
@@ -63032,7 +63574,7 @@ function createExcelCheckMacroTool(options) {
63032
63574
  ].join("\n")
63033
63575
  };
63034
63576
  } catch (error51) {
63035
- return { content: message2(error51), isError: true };
63577
+ return { content: message3(error51), isError: true };
63036
63578
  }
63037
63579
  }
63038
63580
  };
@@ -63075,7 +63617,7 @@ function describeChanges(before, after) {
63075
63617
  }
63076
63618
  return changes;
63077
63619
  }
63078
- function message2(error51) {
63620
+ function message3(error51) {
63079
63621
  return error51 instanceof Error ? error51.message : String(error51);
63080
63622
  }
63081
63623
 
@@ -63143,7 +63685,7 @@ var formFieldSchema = external_exports.object({
63143
63685
  defaultValue: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()]).optional(),
63144
63686
  multiline: external_exports.boolean().optional().describe("For `string` and `list`: renders a text area rather than a single line.")
63145
63687
  });
63146
- var paramsSchema11 = external_exports.object({
63688
+ var paramsSchema12 = external_exports.object({
63147
63689
  title: external_exports.string().min(1).describe("What this form is for, in a few words."),
63148
63690
  description: external_exports.string().optional().describe("Optional sentence above the fields."),
63149
63691
  fields: external_exports.array(formFieldSchema).min(1).max(20)
@@ -63153,7 +63695,7 @@ function createAskUserFormTool() {
63153
63695
  name: "ask_user_form",
63154
63696
  group: "always",
63155
63697
  description: 'Ask the user for structured input with a small form. Use it when you need several specific values rather than a sentence. Field types: string, number, boolean (a checkbox), choice (a dropdown over `options`), and list (one box the user fills with comma-separated values, answered as an array \u2014 use it for "which ids", not one field per id). The turn continues with the answers, so prefer this over ask_followup_question when the inputs are known and typed. Not for permission: acting still needs its own approval.',
63156
- parametersSchema: paramsSchema11,
63698
+ parametersSchema: paramsSchema12,
63157
63699
  async execute(params, context) {
63158
63700
  if (context.requestForm === void 0) {
63159
63701
  return {
@@ -63431,7 +63973,7 @@ function taskSummary(task) {
63431
63973
  createdAt: task.createdAt,
63432
63974
  updatedAt: task.updatedAt,
63433
63975
  // The system prompt is not part of what the user said or saw.
63434
- messageCount: task.messages.filter((message3) => message3.role !== "system").length
63976
+ messageCount: task.messages.filter((message4) => message4.role !== "system").length
63435
63977
  };
63436
63978
  }
63437
63979
 
@@ -64343,10 +64885,10 @@ ${preview.text}` } : {}
64343
64885
  activeTaskId = id;
64344
64886
  await services.workspaceState.set(ACTIVE_TASK_KEY, id);
64345
64887
  }
64346
- function post(message3) {
64347
- if (backgroundRun && isTranscriptMessage(message3.type))
64888
+ function post(message4) {
64889
+ if (backgroundRun && isTranscriptMessage(message4.type))
64348
64890
  return;
64349
- transport.post(message3);
64891
+ transport.post(message4);
64350
64892
  }
64351
64893
  let backgroundRun = false;
64352
64894
  let userTurnRunning = false;
@@ -64376,6 +64918,7 @@ ${preview.text}` } : {}
64376
64918
  let cachedApprovals = {};
64377
64919
  let cachedRiskyCommands = riskyCommandRules();
64378
64920
  let cachedSafeCommands = {};
64921
+ let cachedCommandRules = {};
64379
64922
  let cachedMaxIterations = 25;
64380
64923
  let cachedAccentColor = "#22C55E";
64381
64924
  let cachedTheme;
@@ -64628,6 +65171,7 @@ ${preview.text}` } : {}
64628
65171
  const { config: config2 } = await configManager.load();
64629
65172
  cachedApprovals = approvalsFrom(config2.approvals);
64630
65173
  cachedRiskyCommands = riskyCommandRules(config2.commands);
65174
+ cachedCommandRules = config2.commands ?? {};
64631
65175
  cachedSafeCommands = {
64632
65176
  ...config2.commands?.safe !== void 0 ? { extra: config2.commands.safe } : {},
64633
65177
  ...config2.commands?.builtinSafe !== void 0 ? { builtin: config2.commands.builtinSafe } : {}
@@ -64721,9 +65265,9 @@ ${preview.text}` } : {}
64721
65265
  if (recovery === void 0)
64722
65266
  return;
64723
65267
  const where = recovery.quarantinedTo === void 0 ? "" : ` The damaged file was kept as ${recovery.quarantinedTo}.`;
64724
- const message3 = `Your ${recovery.scope} settings file could not be read and was restored from the last good copy.${where} Anything changed immediately before this may need setting again.`;
64725
- logger.warn(message3);
64726
- post({ type: "error", message: message3 });
65268
+ const message4 = `Your ${recovery.scope} settings file could not be read and was restored from the last good copy.${where} Anything changed immediately before this may need setting again.`;
65269
+ logger.warn(message4);
65270
+ post({ type: "error", message: message4 });
64727
65271
  }
64728
65272
  function settingsMessageFrom(approvals = cachedApprovals) {
64729
65273
  return {
@@ -64736,6 +65280,7 @@ ${preview.text}` } : {}
64736
65280
  ...cachedTheme === void 0 ? {} : { theme: cachedTheme },
64737
65281
  ...cachedToolTimeoutSeconds === void 0 ? {} : { toolTimeoutSeconds: cachedToolTimeoutSeconds },
64738
65282
  readRoots: cachedReadRoots,
65283
+ commandRules: cachedCommandRules,
64739
65284
  ...cachedProgrammingProfileId !== void 0 ? { programmingProfileId: cachedProgrammingProfileId } : {},
64740
65285
  ...hostCapabilities()
64741
65286
  };
@@ -64746,6 +65291,23 @@ ${preview.text}` } : {}
64746
65291
  cachedApprovals = next;
64747
65292
  post(settingsMessageFrom(next));
64748
65293
  }
65294
+ async function handleSetCommandRules(rules) {
65295
+ const risky = (rules.risky ?? []).map((rule) => ({
65296
+ contains: rule.contains.trim(),
65297
+ ...rule.reason !== void 0 && rule.reason.trim().length > 0 ? { reason: rule.reason.trim() } : {},
65298
+ ...rule.refuse === true ? { refuse: true } : {}
65299
+ })).filter((rule) => rule.contains.length > 0);
65300
+ const safe = (rules.safe ?? []).map((prefix) => prefix.trim()).filter((prefix) => prefix.length > 0);
65301
+ const commands = {
65302
+ ...risky.length > 0 ? { risky } : {},
65303
+ ...safe.length > 0 ? { safe } : {},
65304
+ // Both default on, so only the switched-off case is worth recording.
65305
+ ...rules.builtinRisky === false ? { builtinRisky: false } : {},
65306
+ ...rules.builtinSafe === false ? { builtinSafe: false } : {}
65307
+ };
65308
+ await configManager.save("user", { commands });
65309
+ await postSettings();
65310
+ }
64749
65311
  function hostCapabilities() {
64750
65312
  return {
64751
65313
  nativeGuide: ui.openWalkthrough !== void 0,
@@ -64856,31 +65418,31 @@ ${preview.text}` } : {}
64856
65418
  combined.register(createCreateRoleTool(rolePromptAccess), { dispatchOnly: dispatcher });
64857
65419
  combined.register(createDeleteRoleTool(rolePromptAccess), { dispatchOnly: dispatcher });
64858
65420
  combined.register(createNotifyTool({
64859
- notify: (message3, level, details) => {
65421
+ notify: (message4, level, details) => {
64860
65422
  if (details !== void 0) {
64861
65423
  void (async () => {
64862
- const saved = await saveReport(message3, details);
65424
+ const saved = await saveReport(message4, details);
64863
65425
  if (saved !== void 0)
64864
65426
  lastReportPath = saved;
64865
- const open = await ui.showActionMessage(message3, "Open report", level);
65427
+ const open = await ui.showActionMessage(message4, "Open report", level);
64866
65428
  if (!open)
64867
65429
  return;
64868
65430
  if (saved !== void 0 && ui.openFile !== void 0)
64869
65431
  await ui.openFile(saved);
64870
65432
  else
64871
- await ui.openDocument({ title: message3, content: details });
65433
+ await ui.openDocument({ title: message4, content: details });
64872
65434
  })();
64873
65435
  return;
64874
65436
  }
64875
65437
  const taskId = runningScheduleId !== void 0 ? activeTaskId : void 0;
64876
65438
  if (taskId === void 0) {
64877
65439
  if (level === "warning")
64878
- ui.showWarning(message3);
65440
+ ui.showWarning(message4);
64879
65441
  else
64880
- ui.showInfo(message3);
65442
+ ui.showInfo(message4);
64881
65443
  return;
64882
65444
  }
64883
- void openFromNotification(message3, level, taskId);
65445
+ void openFromNotification(message4, level, taskId);
64884
65446
  }
64885
65447
  }));
64886
65448
  if (skillsDir !== void 0) {
@@ -65007,6 +65569,7 @@ ${preview.text}` } : {}
65007
65569
  combined.register(createOutlookFoldersTool(officeOptions));
65008
65570
  combined.register(createOutlookSearchTool(officeOptions));
65009
65571
  combined.register(createOutlookReadTool(officeOptions));
65572
+ combined.register(createOutlookDraftTool(officeOptions));
65010
65573
  }
65011
65574
  }
65012
65575
  const hasHiddenTools = dispatcher && combined.dispatchOnlyList().length > 0;
@@ -65592,7 +66155,7 @@ ${direction}` : attachMentions(text, mentions);
65592
66155
  post({ type: "checkpointAvailable" });
65593
66156
  },
65594
66157
  onDone: () => post({ type: "done" }),
65595
- onError: (message3) => post({ type: "error", message: message3 })
66158
+ onError: (message4) => post({ type: "error", message: message4 })
65596
66159
  }, turnOptions);
65597
66160
  } catch (error51) {
65598
66161
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
@@ -65867,9 +66430,7 @@ ${direction}` : attachMentions(text, mentions);
65867
66430
  return;
65868
66431
  }
65869
66432
  try {
65870
- const segment = query.slice(query.lastIndexOf("/") + 1);
65871
- const pattern = segment.length > 0 ? `**/*${segment}*` : "**/*";
65872
- const found = await ui.findFiles(pattern, MENTION_SCAN_LIMIT, mentionExcludes(cachedMentionExcludes));
66433
+ const found = await ui.findFiles(mentionSegment(query), MENTION_SCAN_LIMIT, mentionExcludes(cachedMentionExcludes));
65873
66434
  const paths = found.map((absolute) => import_node_path27.default.relative(workspaceRoot, absolute).split(import_node_path27.default.sep).join("/")).filter(matchesMentionQuery(query)).sort(compareMentionCandidates(query)).slice(0, MENTION_RESULT_LIMIT);
65874
66435
  post({ type: "mentionCandidates", query, paths });
65875
66436
  } catch (error51) {
@@ -68352,8 +68913,8 @@ ${direction}` : attachMentions(text, mentions);
68352
68913
  }
68353
68914
  }
68354
68915
  async function handlePreviewImport() {
68355
- const fail = (message3) => {
68356
- post({ type: "shareSections", direction: "import", sections: [], selected: [], error: message3 });
68916
+ const fail = (message4) => {
68917
+ post({ type: "shareSections", direction: "import", sections: [], selected: [], error: message4 });
68357
68918
  };
68358
68919
  try {
68359
68920
  const source = await ui.showOpenDialog({ kind: "file", extensions: ["json"] });
@@ -68948,8 +69509,8 @@ ${direction}` : attachMentions(text, mentions);
68948
69509
  });
68949
69510
  }
68950
69511
  const unsubscribe = transport.onMessage((raw) => {
68951
- const message3 = raw;
68952
- if (message3.type === "sendMessage") {
69512
+ const message4 = raw;
69513
+ if (message4.type === "sendMessage") {
68953
69514
  if (activeAbortController !== void 0) {
68954
69515
  logger.warn("Ignoring sendMessage: a turn is already in progress.");
68955
69516
  return;
@@ -68961,290 +69522,292 @@ ${direction}` : attachMentions(text, mentions);
68961
69522
  }
68962
69523
  userTurnRunning = true;
68963
69524
  try {
68964
- await handleSendMessage(message3.text, message3.images);
69525
+ await handleSendMessage(message4.text, message4.images);
68965
69526
  } finally {
68966
69527
  userTurnRunning = false;
68967
69528
  }
68968
69529
  })();
68969
- } else if (message3.type === "requestMentionCandidates") {
68970
- reportFailure("handleMentionCandidates", handleMentionCandidates(message3.query));
68971
- } else if (message3.type === "queueMessage") {
69530
+ } else if (message4.type === "requestMentionCandidates") {
69531
+ reportFailure("handleMentionCandidates", handleMentionCandidates(message4.query));
69532
+ } else if (message4.type === "queueMessage") {
68972
69533
  queuedMessages.push({
68973
- text: message3.text,
68974
- ...message3.images !== void 0 && message3.images.length > 0 ? { images: message3.images } : {}
69534
+ text: message4.text,
69535
+ ...message4.images !== void 0 && message4.images.length > 0 ? { images: message4.images } : {}
68975
69536
  });
68976
69537
  postQueued();
68977
- } else if (message3.type === "unqueueMessage") {
68978
- queuedMessages.splice(message3.index, 1);
69538
+ } else if (message4.type === "unqueueMessage") {
69539
+ queuedMessages.splice(message4.index, 1);
68979
69540
  postQueued();
68980
- } else if (message3.type === "cancel") {
69541
+ } else if (message4.type === "cancel") {
68981
69542
  queuedMessages = [];
68982
69543
  postQueued();
68983
69544
  activeAbortController?.abort();
68984
69545
  userGate.denyAll();
68985
69546
  settleAllForms();
68986
- } else if (message3.type === "approvalResponse") {
68987
- userGate.resolve(message3.id, message3.decision);
68988
- } else if (message3.type === "formResponse") {
68989
- const resolve = pendingForms.get(message3.id);
69547
+ } else if (message4.type === "approvalResponse") {
69548
+ userGate.resolve(message4.id, message4.decision);
69549
+ } else if (message4.type === "formResponse") {
69550
+ const resolve = pendingForms.get(message4.id);
68990
69551
  if (resolve !== void 0) {
68991
- pendingForms.delete(message3.id);
68992
- resolve(message3.submitted ? answerFromResponse(pendingFormFields.get(message3.id) ?? [], message3.values) : { submitted: false, values: {} });
68993
- pendingFormFields.delete(message3.id);
69552
+ pendingForms.delete(message4.id);
69553
+ resolve(message4.submitted ? answerFromResponse(pendingFormFields.get(message4.id) ?? [], message4.values) : { submitted: false, values: {} });
69554
+ pendingFormFields.delete(message4.id);
68994
69555
  }
68995
- } else if (message3.type === "approvalResponseAlways") {
68996
- reportFailure("handleAlwaysAllow", handleAlwaysAllow(message3.id, message3.scope));
68997
- } else if (message3.type === "rollback") {
69556
+ } else if (message4.type === "approvalResponseAlways") {
69557
+ reportFailure("handleAlwaysAllow", handleAlwaysAllow(message4.id, message4.scope));
69558
+ } else if (message4.type === "rollback") {
68998
69559
  reportFailure("handleRollback", handleRollback());
68999
- } else if (message3.type === "requestSettings") {
69560
+ } else if (message4.type === "requestSettings") {
69000
69561
  reportFailure("postSettings", postSettings());
69001
- } else if (message3.type === "requestTasks") {
69562
+ } else if (message4.type === "requestTasks") {
69002
69563
  reportFailure("postTasks", postTasks());
69003
- } else if (message3.type === "openTask") {
69004
- reportFailure("openTask", openTask(message3.id));
69005
- } else if (message3.type === "deleteTask") {
69006
- reportFailure("deleteTask", deleteTask(message3.id));
69007
- } else if (message3.type === "newTask") {
69564
+ } else if (message4.type === "openTask") {
69565
+ reportFailure("openTask", openTask(message4.id));
69566
+ } else if (message4.type === "deleteTask") {
69567
+ reportFailure("deleteTask", deleteTask(message4.id));
69568
+ } else if (message4.type === "newTask") {
69008
69569
  reportFailure("startNewTask", startNewTask());
69009
- } else if (message3.type === "setMode") {
69010
- reportFailure("handleSetMode", handleSetMode(message3.modeId));
69011
- } else if (message3.type === "setMaxIterations") {
69012
- void configManager.save("user", { maxIterations: message3.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
69013
- } else if (message3.type === "setProgrammingProfile") {
69570
+ } else if (message4.type === "setMode") {
69571
+ reportFailure("handleSetMode", handleSetMode(message4.modeId));
69572
+ } else if (message4.type === "setMaxIterations") {
69573
+ void configManager.save("user", { maxIterations: message4.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
69574
+ } else if (message4.type === "setProgrammingProfile") {
69014
69575
  void configManager.load().then(async ({ config: config2 }) => {
69015
69576
  const next = { ...config2 };
69016
- if (message3.id.length === 0)
69577
+ if (message4.id.length === 0)
69017
69578
  delete next.programmingProfileId;
69018
69579
  else
69019
- next.programmingProfileId = message3.id;
69580
+ next.programmingProfileId = message4.id;
69020
69581
  await configManager.save("user", next);
69021
69582
  await postSettings();
69022
69583
  }).catch((error51) => post({ type: "error", message: String(error51) }));
69023
- } else if (message3.type === "setReadRoots") {
69584
+ } else if (message4.type === "setReadRoots") {
69024
69585
  void configManager.save("user", {
69025
69586
  filesystem: {
69026
- readRoots: message3.roots.map((root) => root.trim()).filter((root) => root.length > 0)
69587
+ readRoots: message4.roots.map((root) => root.trim()).filter((root) => root.length > 0)
69027
69588
  }
69028
69589
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
69029
- } else if (message3.type === "setAccentColor") {
69590
+ } else if (message4.type === "setCommandRules") {
69591
+ reportFailure("handleSetCommandRules", handleSetCommandRules(message4.rules));
69592
+ } else if (message4.type === "setAccentColor") {
69030
69593
  void configManager.save("user", {
69031
69594
  ui: {
69032
- accentColor: message3.value,
69595
+ accentColor: message4.value,
69033
69596
  expertColor: cachedExpertColor,
69034
69597
  ...cachedTheme === void 0 ? {} : { theme: cachedTheme }
69035
69598
  }
69036
69599
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
69037
- } else if (message3.type === "setToolTimeoutFor") {
69038
- reportFailure("handleSetToolTimeoutFor", handleSetToolTimeoutFor(message3.name, message3.seconds));
69039
- } else if (message3.type === "setToolTimeout") {
69600
+ } else if (message4.type === "setToolTimeoutFor") {
69601
+ reportFailure("handleSetToolTimeoutFor", handleSetToolTimeoutFor(message4.name, message4.seconds));
69602
+ } else if (message4.type === "setToolTimeout") {
69040
69603
  void configManager.save("user", {
69041
- tools: message3.seconds === void 0 ? {} : { timeoutSeconds: message3.seconds }
69604
+ tools: message4.seconds === void 0 ? {} : { timeoutSeconds: message4.seconds }
69042
69605
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
69043
- } else if (message3.type === "setTheme") {
69606
+ } else if (message4.type === "setTheme") {
69044
69607
  void configManager.save("user", {
69045
69608
  ui: {
69046
69609
  accentColor: cachedAccentColor,
69047
69610
  expertColor: cachedExpertColor,
69048
- theme: message3.theme
69611
+ theme: message4.theme
69049
69612
  }
69050
69613
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
69051
- } else if (message3.type === "setExpertColor") {
69614
+ } else if (message4.type === "setExpertColor") {
69052
69615
  void configManager.save("user", {
69053
69616
  ui: {
69054
69617
  accentColor: cachedAccentColor,
69055
- expertColor: message3.value,
69618
+ expertColor: message4.value,
69056
69619
  ...cachedTheme === void 0 ? {} : { theme: cachedTheme }
69057
69620
  }
69058
69621
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
69059
- } else if (message3.type === "setAutoApprove") {
69060
- reportFailure("handleSetAutoApprove", handleSetAutoApprove(message3.group, message3.enabled));
69061
- } else if (message3.type === "revokeAllowedTool") {
69622
+ } else if (message4.type === "setAutoApprove") {
69623
+ reportFailure("handleSetAutoApprove", handleSetAutoApprove(message4.group, message4.enabled));
69624
+ } else if (message4.type === "revokeAllowedTool") {
69062
69625
  reportFailure("saveApprovals", saveApprovals({
69063
69626
  ...cachedApprovals,
69064
- allowedTools: removeFromAllowlist(message3.toolName, cachedApprovals.allowedTools ?? [])
69627
+ allowedTools: removeFromAllowlist(message4.toolName, cachedApprovals.allowedTools ?? [])
69065
69628
  }));
69066
- } else if (message3.type === "revokeAllowedCommand") {
69629
+ } else if (message4.type === "revokeAllowedCommand") {
69067
69630
  reportFailure("saveApprovals", saveApprovals({
69068
69631
  ...cachedApprovals,
69069
- allowedCommands: removeFromAllowlist(message3.command, cachedApprovals.allowedCommands ?? [])
69632
+ allowedCommands: removeFromAllowlist(message4.command, cachedApprovals.allowedCommands ?? [])
69070
69633
  }));
69071
- } else if (message3.type === "requestMcp") {
69634
+ } else if (message4.type === "requestMcp") {
69072
69635
  reportFailure("handleRequestMcp", handleRequestMcp());
69073
- } else if (message3.type === "saveMcpServers") {
69074
- reportFailure("handleSaveMcpServers", handleSaveMcpServers(message3.json));
69075
- } else if (message3.type === "saveMcpServer") {
69076
- reportFailure("handleSaveMcpServer", handleSaveMcpServer(message3.name, message3.previousName, message3.config));
69077
- } else if (message3.type === "duplicateMcpServer") {
69078
- reportFailure("handleDuplicateMcpServer", handleDuplicateMcpServer(message3.name));
69079
- } else if (message3.type === "deleteMcpServer") {
69080
- reportFailure("handleDeleteMcpServer", handleDeleteMcpServer(message3.name));
69081
- } else if (message3.type === "browseForPath") {
69082
- reportFailure("handleBrowseForPath", handleBrowseForPath(message3.purpose, message3.kind, message3.extensions));
69083
- } else if (message3.type === "probePythonEnv") {
69084
- reportFailure("handleProbePythonEnv", handleProbePythonEnv(message3.venvDir, message3.script));
69085
- } else if (message3.type === "connectMcpServer") {
69086
- void mcp.connectServer(message3.name);
69087
- } else if (message3.type === "restartMcpServer") {
69088
- void mcp.restart(message3.name);
69089
- } else if (message3.type === "setMcpServerEnabled") {
69090
- reportFailure("updateMcpServer", updateMcpServer(message3.name, (entry) => ({
69636
+ } else if (message4.type === "saveMcpServers") {
69637
+ reportFailure("handleSaveMcpServers", handleSaveMcpServers(message4.json));
69638
+ } else if (message4.type === "saveMcpServer") {
69639
+ reportFailure("handleSaveMcpServer", handleSaveMcpServer(message4.name, message4.previousName, message4.config));
69640
+ } else if (message4.type === "duplicateMcpServer") {
69641
+ reportFailure("handleDuplicateMcpServer", handleDuplicateMcpServer(message4.name));
69642
+ } else if (message4.type === "deleteMcpServer") {
69643
+ reportFailure("handleDeleteMcpServer", handleDeleteMcpServer(message4.name));
69644
+ } else if (message4.type === "browseForPath") {
69645
+ reportFailure("handleBrowseForPath", handleBrowseForPath(message4.purpose, message4.kind, message4.extensions));
69646
+ } else if (message4.type === "probePythonEnv") {
69647
+ reportFailure("handleProbePythonEnv", handleProbePythonEnv(message4.venvDir, message4.script));
69648
+ } else if (message4.type === "connectMcpServer") {
69649
+ void mcp.connectServer(message4.name);
69650
+ } else if (message4.type === "restartMcpServer") {
69651
+ void mcp.restart(message4.name);
69652
+ } else if (message4.type === "setMcpServerEnabled") {
69653
+ reportFailure("updateMcpServer", updateMcpServer(message4.name, (entry) => ({
69091
69654
  ...entry,
69092
- disabled: !message3.enabled
69655
+ disabled: !message4.enabled
69093
69656
  })).then(() => postMcp()));
69094
- } else if (message3.type === "setMcpToolTimeout") {
69095
- reportFailure("handleSetToolTimeout", handleSetToolTimeout(message3.server, message3.tool, message3.seconds));
69096
- } else if (message3.type === "setMcpToolPermission") {
69097
- reportFailure("handleSetToolPermission", handleSetToolPermission(message3.server, message3.tool, message3.permission));
69098
- } else if (message3.type === "requestSearch") {
69657
+ } else if (message4.type === "setMcpToolTimeout") {
69658
+ reportFailure("handleSetToolTimeout", handleSetToolTimeout(message4.server, message4.tool, message4.seconds));
69659
+ } else if (message4.type === "setMcpToolPermission") {
69660
+ reportFailure("handleSetToolPermission", handleSetToolPermission(message4.server, message4.tool, message4.permission));
69661
+ } else if (message4.type === "requestSearch") {
69099
69662
  reportFailure("postSearch", postSearch());
69100
69663
  reportFailure("postDispatcher", postDispatcher());
69101
69664
  post({ type: "searchLog", entries: [...searchLog.list()] });
69102
- } else if (message3.type === "saveSearchConnection") {
69103
- reportFailure("handleSaveSearchConnection", handleSaveSearchConnection(message3.connection));
69104
- } else if (message3.type === "deleteSearchConnection") {
69105
- reportFailure("handleDeleteSearchConnection", handleDeleteSearchConnection(message3.id));
69106
- } else if (message3.type === "setActiveSearchConnection") {
69107
- void (message3.forProject === true ? configManager.saveForWorkspace({ activeVectorStoreId: message3.id }) : configManager.save("user", { activeVectorStoreId: message3.id })).then(async () => {
69665
+ } else if (message4.type === "saveSearchConnection") {
69666
+ reportFailure("handleSaveSearchConnection", handleSaveSearchConnection(message4.connection));
69667
+ } else if (message4.type === "deleteSearchConnection") {
69668
+ reportFailure("handleDeleteSearchConnection", handleDeleteSearchConnection(message4.id));
69669
+ } else if (message4.type === "setActiveSearchConnection") {
69670
+ void (message4.forProject === true ? configManager.saveForWorkspace({ activeVectorStoreId: message4.id }) : configManager.save("user", { activeVectorStoreId: message4.id })).then(async () => {
69108
69671
  await postSearch();
69109
69672
  await postProjectSettings();
69110
69673
  }).catch((error51) => post({ type: "error", message: String(error51) }));
69111
- } else if (message3.type === "requestProjectSettings") {
69674
+ } else if (message4.type === "requestProjectSettings") {
69112
69675
  reportFailure("postProjectSettings", postProjectSettings());
69113
- } else if (message3.type === "clearProjectSettings") {
69676
+ } else if (message4.type === "clearProjectSettings") {
69114
69677
  reportFailure("handleClearProjectSettings", handleClearProjectSettings());
69115
- } else if (message3.type === "requestSearchIndexes") {
69116
- reportFailure("handleRequestSearchIndexes", handleRequestSearchIndexes(message3.connection));
69117
- } else if (message3.type === "testSearchConnection") {
69118
- reportFailure("handleTestSearchConnection", handleTestSearchConnection(message3.connection));
69119
- } else if (message3.type === "syncVectorStore") {
69120
- reportFailure("handleSyncVectorStore", handleSyncVectorStore(message3.fromId));
69121
- } else if (message3.type === "clearDocsIndex") {
69122
- reportFailure("handleClearDocsIndex", handleClearDocsIndex(message3.kind));
69123
- } else if (message3.type === "clearCodebaseIndex") {
69678
+ } else if (message4.type === "requestSearchIndexes") {
69679
+ reportFailure("handleRequestSearchIndexes", handleRequestSearchIndexes(message4.connection));
69680
+ } else if (message4.type === "testSearchConnection") {
69681
+ reportFailure("handleTestSearchConnection", handleTestSearchConnection(message4.connection));
69682
+ } else if (message4.type === "syncVectorStore") {
69683
+ reportFailure("handleSyncVectorStore", handleSyncVectorStore(message4.fromId));
69684
+ } else if (message4.type === "clearDocsIndex") {
69685
+ reportFailure("handleClearDocsIndex", handleClearDocsIndex(message4.kind));
69686
+ } else if (message4.type === "clearCodebaseIndex") {
69124
69687
  reportFailure("handleClearCodebaseIndex", handleClearCodebaseIndex());
69125
- } else if (message3.type === "openStandingSkill") {
69688
+ } else if (message4.type === "openStandingSkill") {
69126
69689
  reportFailure("handleOpenStandingSkill", handleOpenStandingSkill());
69127
- } else if (message3.type === "setOffice") {
69690
+ } else if (message4.type === "setOffice") {
69128
69691
  void configManager.load().then(async () => {
69129
69692
  await configManager.save("user", {
69130
- office: { excel: message3.excel, outlook: message3.outlook }
69693
+ office: { excel: message4.excel, outlook: message4.outlook }
69131
69694
  });
69132
69695
  await loadSettings();
69133
69696
  await postTools();
69134
- if (!message3.excel && !message3.outlook) {
69697
+ if (!message4.excel && !message4.outlook) {
69135
69698
  await officeBridge?.dispose();
69136
69699
  officeBridge = void 0;
69137
69700
  }
69138
69701
  }).catch((error51) => post({ type: "error", message: String(error51) }));
69139
- } else if (message3.type === "indexDocs") {
69140
- reportFailure("handleIndexDocs", handleIndexDocs(message3.kind));
69141
- } else if (message3.type === "runSearchProbe") {
69142
- reportFailure("handleSearchProbe", handleSearchProbe(message3.query, message3.target));
69143
- } else if (message3.type === "clearSearchLog") {
69702
+ } else if (message4.type === "indexDocs") {
69703
+ reportFailure("handleIndexDocs", handleIndexDocs(message4.kind));
69704
+ } else if (message4.type === "runSearchProbe") {
69705
+ reportFailure("handleSearchProbe", handleSearchProbe(message4.query, message4.target));
69706
+ } else if (message4.type === "clearSearchLog") {
69144
69707
  searchLog.clear();
69145
- } else if (message3.type === "setDispatcher") {
69146
- reportFailure("saveRetrieval", saveRetrieval({ dispatcher: message3.enabled }).then(() => {
69708
+ } else if (message4.type === "setDispatcher") {
69709
+ reportFailure("saveRetrieval", saveRetrieval({ dispatcher: message4.enabled }).then(() => {
69147
69710
  reportFailure("postDispatcher", postDispatcher());
69148
- if (message3.enabled)
69711
+ if (message4.enabled)
69149
69712
  scheduleDocsReindex("dispatcher enabled");
69150
69713
  }));
69151
- } else if (message3.type === "setSkillRetrieval") {
69152
- reportFailure("saveRetrieval", saveRetrieval({ skills: message3.enabled }).then(() => {
69714
+ } else if (message4.type === "setSkillRetrieval") {
69715
+ reportFailure("saveRetrieval", saveRetrieval({ skills: message4.enabled }).then(() => {
69153
69716
  reportFailure("postDispatcher", postDispatcher());
69154
- if (message3.enabled)
69717
+ if (message4.enabled)
69155
69718
  scheduleDocsReindex("skill retrieval enabled");
69156
69719
  }));
69157
- } else if (message3.type === "startIndexing") {
69720
+ } else if (message4.type === "startIndexing") {
69158
69721
  reportFailure("handleStartIndexing", handleStartIndexing());
69159
- } else if (message3.type === "attachTeamAlias") {
69722
+ } else if (message4.type === "attachTeamAlias") {
69160
69723
  reportFailure("handleAttachTeamAlias", handleAttachTeamAlias());
69161
- } else if (message3.type === "publishTeamSkills") {
69724
+ } else if (message4.type === "publishTeamSkills") {
69162
69725
  reportFailure("handlePublishTeamSkills", handlePublishTeamSkills());
69163
- } else if (message3.type === "syncMail") {
69726
+ } else if (message4.type === "syncMail") {
69164
69727
  reportFailure("runMailSync", runMailSync("requested"));
69165
- } else if (message3.type === "pruneMail") {
69728
+ } else if (message4.type === "pruneMail") {
69166
69729
  reportFailure("handlePruneMail", handlePruneMail());
69167
- } else if (message3.type === "requestOutlookFolders") {
69168
- reportFailure("handleRequestOutlookFolders", handleRequestOutlookFolders(message3.depth, message3.force === true));
69169
- } else if (message3.type === "validateMailFolder") {
69170
- reportFailure("handleValidateMailFolder", handleValidateMailFolder(message3.path));
69171
- } else if (message3.type === "requestMailStatus") {
69730
+ } else if (message4.type === "requestOutlookFolders") {
69731
+ reportFailure("handleRequestOutlookFolders", handleRequestOutlookFolders(message4.depth, message4.force === true));
69732
+ } else if (message4.type === "validateMailFolder") {
69733
+ reportFailure("handleValidateMailFolder", handleValidateMailFolder(message4.path));
69734
+ } else if (message4.type === "requestMailStatus") {
69172
69735
  reportFailure("loadSettings", loadSettings().then((config2) => {
69173
69736
  reconcileMailTimer(config2);
69174
69737
  reconcileDatasetTimers(config2);
69175
69738
  return postMailStatus();
69176
69739
  }));
69177
- } else if (message3.type === "saveMailSettings") {
69740
+ } else if (message4.type === "saveMailSettings") {
69178
69741
  reportFailure("handleSaveMailSettings", handleSaveMailSettings({
69179
- enabled: message3.enabled,
69180
- folders: message3.folders,
69181
- includeSubfolders: message3.includeSubfolders,
69182
- syncMinutes: message3.syncMinutes,
69183
- retentionMonths: message3.retentionMonths,
69184
- ...message3.storeId !== void 0 ? { storeId: message3.storeId } : {}
69742
+ enabled: message4.enabled,
69743
+ folders: message4.folders,
69744
+ includeSubfolders: message4.includeSubfolders,
69745
+ syncMinutes: message4.syncMinutes,
69746
+ retentionMonths: message4.retentionMonths,
69747
+ ...message4.storeId !== void 0 ? { storeId: message4.storeId } : {}
69185
69748
  }));
69186
- } else if (message3.type === "clearTeamSkills") {
69749
+ } else if (message4.type === "clearTeamSkills") {
69187
69750
  reportFailure("handleClearTeamSkills", handleClearTeamSkills());
69188
- } else if (message3.type === "refreshMail") {
69189
- reportFailure("handleRefreshMail", handleRefreshMail(message3.days));
69190
- } else if (message3.type === "requestDatasetStatus") {
69751
+ } else if (message4.type === "refreshMail") {
69752
+ reportFailure("handleRefreshMail", handleRefreshMail(message4.days));
69753
+ } else if (message4.type === "requestDatasetStatus") {
69191
69754
  reportFailure("postDatasetStatus", postDatasetStatus());
69192
- } else if (message3.type === "saveDataset") {
69193
- reportFailure("handleSaveDataset", handleSaveDataset(message3.dataset));
69194
- } else if (message3.type === "deleteDataset") {
69195
- reportFailure("handleDeleteDataset", handleDeleteDataset(message3.id));
69196
- } else if (message3.type === "syncDataset") {
69197
- reportFailure("runDatasetSync", runDatasetSync(message3.id, "manual"));
69198
- } else if (message3.type === "clearDataset") {
69199
- reportFailure("handleClearDataset", handleClearDataset(message3.id, message3.resync === true));
69200
- } else if (message3.type === "clearMailIndex") {
69201
- reportFailure("handleClearMailIndex", handleClearMailIndex(message3.resync === true));
69202
- } else if (message3.type === "requestSkillImage") {
69203
- reportFailure("handleSkillImage", handleSkillImage(message3.skill, message3.image));
69204
- } else if (message3.type === "requestS3") {
69755
+ } else if (message4.type === "saveDataset") {
69756
+ reportFailure("handleSaveDataset", handleSaveDataset(message4.dataset));
69757
+ } else if (message4.type === "deleteDataset") {
69758
+ reportFailure("handleDeleteDataset", handleDeleteDataset(message4.id));
69759
+ } else if (message4.type === "syncDataset") {
69760
+ reportFailure("runDatasetSync", runDatasetSync(message4.id, "manual"));
69761
+ } else if (message4.type === "clearDataset") {
69762
+ reportFailure("handleClearDataset", handleClearDataset(message4.id, message4.resync === true));
69763
+ } else if (message4.type === "clearMailIndex") {
69764
+ reportFailure("handleClearMailIndex", handleClearMailIndex(message4.resync === true));
69765
+ } else if (message4.type === "requestSkillImage") {
69766
+ reportFailure("handleSkillImage", handleSkillImage(message4.skill, message4.image));
69767
+ } else if (message4.type === "requestS3") {
69205
69768
  reportFailure("postS3", postS3());
69206
- } else if (message3.type === "saveS3Connection") {
69207
- reportFailure("handleSaveS3Connection", handleSaveS3Connection(message3.connection, message3.secret, message3.sessionToken));
69208
- } else if (message3.type === "deleteS3Connection") {
69209
- reportFailure("handleDeleteS3Connection", handleDeleteS3Connection(message3.id));
69210
- } else if (message3.type === "saveS3Mirrors") {
69211
- reportFailure("handleSaveS3Mirrors", handleSaveS3Mirrors(message3.kind, message3.mirrors));
69212
- } else if (message3.type === "syncS3") {
69213
- reportFailure("handleSyncS3", handleSyncS3(message3.kind));
69214
- } else if (message3.type === "saveSkillsAlias") {
69215
- reportFailure("handleSaveSkillsAlias", handleSaveSkillsAlias(message3.aliases));
69216
- } else if (message3.type === "cancelIndexing") {
69217
- if (message3.kind === void 0) {
69769
+ } else if (message4.type === "saveS3Connection") {
69770
+ reportFailure("handleSaveS3Connection", handleSaveS3Connection(message4.connection, message4.secret, message4.sessionToken));
69771
+ } else if (message4.type === "deleteS3Connection") {
69772
+ reportFailure("handleDeleteS3Connection", handleDeleteS3Connection(message4.id));
69773
+ } else if (message4.type === "saveS3Mirrors") {
69774
+ reportFailure("handleSaveS3Mirrors", handleSaveS3Mirrors(message4.kind, message4.mirrors));
69775
+ } else if (message4.type === "syncS3") {
69776
+ reportFailure("handleSyncS3", handleSyncS3(message4.kind));
69777
+ } else if (message4.type === "saveSkillsAlias") {
69778
+ reportFailure("handleSaveSkillsAlias", handleSaveSkillsAlias(message4.aliases));
69779
+ } else if (message4.type === "cancelIndexing") {
69780
+ if (message4.kind === void 0) {
69218
69781
  indexingAbort?.abort();
69219
69782
  for (const controller of indexingAborts.values())
69220
69783
  controller.abort();
69221
- } else if (message3.kind === "codebase") {
69784
+ } else if (message4.kind === "codebase") {
69222
69785
  indexingAbort?.abort();
69223
69786
  } else {
69224
- indexingAborts.get(message3.kind)?.abort();
69787
+ indexingAborts.get(message4.kind)?.abort();
69225
69788
  }
69226
- } else if (message3.type === "saveEmbedder") {
69227
- reportFailure("handleSaveEmbedder", handleSaveEmbedder(message3.profileId, message3.model, message3.dimensions, message3.indexName, message3.indexPrefix, message3.indexAliases));
69228
- } else if (message3.type === "requestEmbedderModels") {
69229
- reportFailure("handleRequestEmbedderModels", handleRequestEmbedderModels(message3.profileId));
69230
- } else if (message3.type === "openWalkthrough") {
69789
+ } else if (message4.type === "saveEmbedder") {
69790
+ reportFailure("handleSaveEmbedder", handleSaveEmbedder(message4.profileId, message4.model, message4.dimensions, message4.indexName, message4.indexPrefix, message4.indexAliases));
69791
+ } else if (message4.type === "requestEmbedderModels") {
69792
+ reportFailure("handleRequestEmbedderModels", handleRequestEmbedderModels(message4.profileId));
69793
+ } else if (message4.type === "openWalkthrough") {
69231
69794
  void ui.openWalkthrough?.();
69232
- } else if (message3.type === "requestTools") {
69795
+ } else if (message4.type === "requestTools") {
69233
69796
  reportFailure("postTools", postTools());
69234
- } else if (message3.type === "requestSchedules") {
69797
+ } else if (message4.type === "requestSchedules") {
69235
69798
  reportFailure("postSchedules", postSchedules());
69236
- } else if (message3.type === "saveSchedule") {
69237
- reportFailure("handleSaveSchedule", handleSaveSchedule(message3.schedule));
69238
- } else if (message3.type === "duplicateSchedule") {
69239
- reportFailure("handleDuplicateSchedule", handleDuplicateSchedule(message3.id));
69240
- } else if (message3.type === "deleteSchedule") {
69241
- reportFailure("handleDeleteSchedule", handleDeleteSchedule(message3.id));
69242
- } else if (message3.type === "setScheduleEnabled") {
69243
- reportFailure("handleSetScheduleEnabled", handleSetScheduleEnabled(message3.id, message3.enabled));
69244
- } else if (message3.type === "setTaskExpertLimits") {
69245
- const next = message3.maxSpendUsd === void 0 && message3.maxConsultations === void 0 ? void 0 : {
69246
- ...message3.maxSpendUsd !== void 0 ? { maxSpendUsd: message3.maxSpendUsd } : {},
69247
- ...message3.maxConsultations !== void 0 ? { maxConsultations: message3.maxConsultations } : {}
69799
+ } else if (message4.type === "saveSchedule") {
69800
+ reportFailure("handleSaveSchedule", handleSaveSchedule(message4.schedule));
69801
+ } else if (message4.type === "duplicateSchedule") {
69802
+ reportFailure("handleDuplicateSchedule", handleDuplicateSchedule(message4.id));
69803
+ } else if (message4.type === "deleteSchedule") {
69804
+ reportFailure("handleDeleteSchedule", handleDeleteSchedule(message4.id));
69805
+ } else if (message4.type === "setScheduleEnabled") {
69806
+ reportFailure("handleSetScheduleEnabled", handleSetScheduleEnabled(message4.id, message4.enabled));
69807
+ } else if (message4.type === "setTaskExpertLimits") {
69808
+ const next = message4.maxSpendUsd === void 0 && message4.maxConsultations === void 0 ? void 0 : {
69809
+ ...message4.maxSpendUsd !== void 0 ? { maxSpendUsd: message4.maxSpendUsd } : {},
69810
+ ...message4.maxConsultations !== void 0 ? { maxConsultations: message4.maxConsultations } : {}
69248
69811
  };
69249
69812
  taskExpertLimits = next;
69250
69813
  postExpertSpend();
@@ -69261,17 +69824,17 @@ ${direction}` : attachMentions(text, mentions);
69261
69824
  await postExpert({ redetect: false });
69262
69825
  }).catch((error51) => post({ type: "error", message: String(error51) }));
69263
69826
  }
69264
- } else if (message3.type === "setExpertKeepAlive") {
69827
+ } else if (message4.type === "setExpertKeepAlive") {
69265
69828
  void configManager.load().then(async ({ config: config2 }) => {
69266
69829
  await configManager.save("user", {
69267
69830
  ...config2,
69268
- expert: { ...config2.expert, keepAlive: message3.enabled }
69831
+ expert: { ...config2.expert, keepAlive: message4.enabled }
69269
69832
  });
69270
69833
  await postExpert({ redetect: false });
69271
69834
  }).catch((error51) => post({ type: "error", message: String(error51) }));
69272
- } else if (message3.type === "measureExpertCost") {
69835
+ } else if (message4.type === "measureExpertCost") {
69273
69836
  reportFailure("handleMeasureExpertCost", handleMeasureExpertCost());
69274
- } else if (message3.type === "clearExpertPricing") {
69837
+ } else if (message4.type === "clearExpertPricing") {
69275
69838
  void configManager.load().then(async ({ config: config2 }) => {
69276
69839
  const expert = { ...config2.expert };
69277
69840
  delete expert.pricing;
@@ -69279,61 +69842,61 @@ ${direction}` : attachMentions(text, mentions);
69279
69842
  await configManager.save("user", { ...config2, expert });
69280
69843
  await postExpert({ redetect: false });
69281
69844
  }).catch((error51) => post({ type: "error", message: String(error51) }));
69282
- } else if (message3.type === "assessJunior") {
69283
- reportFailure("handleAssessJunior", handleAssessJunior(message3.profileId));
69284
- } else if (message3.type === "clearAssessment") {
69285
- reportFailure("handleClearAssessment", handleClearAssessment(message3.model, message3.profileLabel));
69286
- } else if (message3.type === "restartScheduler") {
69845
+ } else if (message4.type === "assessJunior") {
69846
+ reportFailure("handleAssessJunior", handleAssessJunior(message4.profileId));
69847
+ } else if (message4.type === "clearAssessment") {
69848
+ reportFailure("handleClearAssessment", handleClearAssessment(message4.model, message4.profileLabel));
69849
+ } else if (message4.type === "restartScheduler") {
69287
69850
  restartScheduleTimer();
69288
69851
  logger.info("schedule timer restarted by the user");
69289
69852
  reportFailure("postSchedules", postSchedules());
69290
- } else if (message3.type === "deleteScheduleRun") {
69291
- reportFailure("handleDeleteScheduleRun", handleDeleteScheduleRun(message3.id, message3.at));
69292
- } else if (message3.type === "clearScheduleRuns") {
69293
- reportFailure("handleClearScheduleRuns", handleClearScheduleRuns(message3.id));
69294
- } else if (message3.type === "openScheduleRun") {
69295
- reportFailure("openRunTranscript", openRunTranscript(message3.taskId, message3.title));
69296
- } else if (message3.type === "runScheduleNow") {
69297
- reportFailure("runSchedule", runSchedule(message3.id, "manual"));
69298
- } else if (message3.type === "requestSkills") {
69853
+ } else if (message4.type === "deleteScheduleRun") {
69854
+ reportFailure("handleDeleteScheduleRun", handleDeleteScheduleRun(message4.id, message4.at));
69855
+ } else if (message4.type === "clearScheduleRuns") {
69856
+ reportFailure("handleClearScheduleRuns", handleClearScheduleRuns(message4.id));
69857
+ } else if (message4.type === "openScheduleRun") {
69858
+ reportFailure("openRunTranscript", openRunTranscript(message4.taskId, message4.title));
69859
+ } else if (message4.type === "runScheduleNow") {
69860
+ reportFailure("runSchedule", runSchedule(message4.id, "manual"));
69861
+ } else if (message4.type === "requestSkills") {
69299
69862
  reportFailure("postSkills", postSkills());
69300
- } else if (message3.type === "saveSkillDirs") {
69863
+ } else if (message4.type === "saveSkillDirs") {
69301
69864
  void configManager.save("user", {
69302
69865
  skills: {
69303
- ...message3.dir.trim().length > 0 ? { dir: message3.dir.trim() } : {},
69304
- paths: message3.paths.map((entry) => entry.trim()).filter((entry) => entry.length > 0)
69866
+ ...message4.dir.trim().length > 0 ? { dir: message4.dir.trim() } : {},
69867
+ paths: message4.paths.map((entry) => entry.trim()).filter((entry) => entry.length > 0)
69305
69868
  }
69306
69869
  }).then(() => postSkills()).catch((error51) => post({ type: "error", message: String(error51) }));
69307
- } else if (message3.type === "openManagedFile") {
69308
- reportFailure("handleOpenManagedFile", handleOpenManagedFile(message3.path));
69309
- } else if (message3.type === "deletePythonTool") {
69310
- reportFailure("handleDeletePythonTool", handleDeletePythonTool(message3.name));
69311
- } else if (message3.type === "approvePythonTool") {
69312
- reportFailure("handleApprovePythonTool", handleApprovePythonTool(message3.name));
69313
- } else if (message3.type === "deleteSkillFile") {
69314
- reportFailure("handleDeleteSkillFile", handleDeleteSkillFile(message3.name));
69315
- } else if (message3.type === "requestPython") {
69870
+ } else if (message4.type === "openManagedFile") {
69871
+ reportFailure("handleOpenManagedFile", handleOpenManagedFile(message4.path));
69872
+ } else if (message4.type === "deletePythonTool") {
69873
+ reportFailure("handleDeletePythonTool", handleDeletePythonTool(message4.name));
69874
+ } else if (message4.type === "approvePythonTool") {
69875
+ reportFailure("handleApprovePythonTool", handleApprovePythonTool(message4.name));
69876
+ } else if (message4.type === "deleteSkillFile") {
69877
+ reportFailure("handleDeleteSkillFile", handleDeleteSkillFile(message4.name));
69878
+ } else if (message4.type === "requestPython") {
69316
69879
  reportFailure("postPython", postPython());
69317
- } else if (message3.type === "setPython") {
69318
- reportFailure("handleSetPython", handleSetPython(message3));
69319
- } else if (message3.type === "requestNetwork") {
69880
+ } else if (message4.type === "setPython") {
69881
+ reportFailure("handleSetPython", handleSetPython(message4));
69882
+ } else if (message4.type === "requestNetwork") {
69320
69883
  reportFailure("postNetwork", postNetwork());
69321
- } else if (message3.type === "saveNetwork") {
69322
- reportFailure("handleSaveNetwork", handleSaveNetwork(message3.settings));
69323
- } else if (message3.type === "requestExpert") {
69884
+ } else if (message4.type === "saveNetwork") {
69885
+ reportFailure("handleSaveNetwork", handleSaveNetwork(message4.settings));
69886
+ } else if (message4.type === "requestExpert") {
69324
69887
  reportFailure("postExpert", postExpert());
69325
- } else if (message3.type === "setPlan") {
69326
- reportFailure("applyPlan", applyPlan(message3.plan));
69327
- } else if (message3.type === "requestPlan") {
69888
+ } else if (message4.type === "setPlan") {
69889
+ reportFailure("applyPlan", applyPlan(message4.plan));
69890
+ } else if (message4.type === "requestPlan") {
69328
69891
  post({ type: "plan", plan: activePlan ?? "" });
69329
69892
  postPlanProgress();
69330
- } else if (message3.type === "requestPlanProgress") {
69893
+ } else if (message4.type === "requestPlanProgress") {
69331
69894
  postPlanProgress();
69332
- } else if (message3.type === "requestAgents") {
69895
+ } else if (message4.type === "requestAgents") {
69333
69896
  reportFailure("postAgents", postAgents());
69334
- } else if (message3.type === "setAgentRole") {
69335
- const assignment = message3.assignment;
69336
- const role = message3.role;
69897
+ } else if (message4.type === "setAgentRole") {
69898
+ const assignment = message4.assignment;
69899
+ const role = message4.role;
69337
69900
  if (!isAgentRole(role, cachedAgentDefinitions)) {
69338
69901
  post({ type: "error", message: `There is no "${role}" role.` });
69339
69902
  return;
@@ -69351,9 +69914,9 @@ ${direction}` : attachMentions(text, mentions);
69351
69914
  }
69352
69915
  return { ...current, roles };
69353
69916
  }));
69354
- } else if (message3.type === "setAgentPrompt") {
69355
- const role = message3.role;
69356
- const prompt = message3.prompt;
69917
+ } else if (message4.type === "setAgentPrompt") {
69918
+ const role = message4.role;
69919
+ const prompt = message4.prompt;
69357
69920
  if (!isAgentRole(role, cachedAgentDefinitions)) {
69358
69921
  post({ type: "error", message: `There is no "${role}" role.` });
69359
69922
  return;
@@ -69372,11 +69935,11 @@ ${direction}` : attachMentions(text, mentions);
69372
69935
  }
69373
69936
  return { ...current, roles };
69374
69937
  }));
69375
- } else if (message3.type === "setAgentBudget") {
69376
- const matters = message3.matters;
69938
+ } else if (message4.type === "setAgentBudget") {
69939
+ const matters = message4.matters;
69377
69940
  reportFailure("saveAgents", saveAgents((current) => ({ ...current, budgetMatters: matters })));
69378
- } else if (message3.type === "setTeamGuidance") {
69379
- const guidance = message3.guidance;
69941
+ } else if (message4.type === "setTeamGuidance") {
69942
+ const guidance = message4.guidance;
69380
69943
  reportFailure("saveAgents", saveAgents((current) => {
69381
69944
  if (guidance === void 0 || guidance.trim().length === 0 || guidance === DEFAULT_TEAM_GUIDANCE) {
69382
69945
  const rest = { ...current };
@@ -69385,12 +69948,12 @@ ${direction}` : attachMentions(text, mentions);
69385
69948
  }
69386
69949
  return { ...current, teamGuidance: guidance };
69387
69950
  }));
69388
- } else if (message3.type === "saveCustomRole") {
69389
- reportFailure("handleSaveCustomRole", handleSaveCustomRole(message3));
69390
- } else if (message3.type === "deleteCustomRole") {
69391
- reportFailure("handleDeleteCustomRole", handleDeleteCustomRole(message3.id));
69392
- } else if (message3.type === "setRoleThinking") {
69393
- const role = message3.role;
69951
+ } else if (message4.type === "saveCustomRole") {
69952
+ reportFailure("handleSaveCustomRole", handleSaveCustomRole(message4));
69953
+ } else if (message4.type === "deleteCustomRole") {
69954
+ reportFailure("handleDeleteCustomRole", handleDeleteCustomRole(message4.id));
69955
+ } else if (message4.type === "setRoleThinking") {
69956
+ const role = message4.role;
69394
69957
  if (!isAgentRole(role, cachedAgentDefinitions)) {
69395
69958
  post({ type: "error", message: `There is no "${role}" role.` });
69396
69959
  return;
@@ -69398,17 +69961,17 @@ ${direction}` : attachMentions(text, mentions);
69398
69961
  reportFailure("saveAgents", saveAgents((current) => {
69399
69962
  const roles = { ...current.roles ?? {} };
69400
69963
  const existing = roles[role] ?? { kind: "profile" };
69401
- if (message3.level === void 0) {
69964
+ if (message4.level === void 0) {
69402
69965
  const rest = { ...existing };
69403
69966
  delete rest.thinking;
69404
69967
  roles[role] = rest;
69405
69968
  } else {
69406
- roles[role] = { ...existing, thinking: message3.level };
69969
+ roles[role] = { ...existing, thinking: message4.level };
69407
69970
  }
69408
69971
  return { ...current, roles };
69409
69972
  }));
69410
- } else if (message3.type === "setRoleEnabled") {
69411
- const role = message3.role;
69973
+ } else if (message4.type === "setRoleEnabled") {
69974
+ const role = message4.role;
69412
69975
  if (!isAgentRole(role, cachedAgentDefinitions)) {
69413
69976
  post({ type: "error", message: `There is no "${role}" role.` });
69414
69977
  return;
@@ -69417,35 +69980,35 @@ ${direction}` : attachMentions(text, mentions);
69417
69980
  const roles = { ...current.roles ?? {} };
69418
69981
  roles[role] = {
69419
69982
  ...roles[role] ?? { kind: "profile" },
69420
- enabled: message3.enabled
69983
+ enabled: message4.enabled
69421
69984
  };
69422
69985
  return { ...current, roles };
69423
69986
  }));
69424
- } else if (message3.type === "setRoleWrite") {
69425
- const role = message3.role;
69987
+ } else if (message4.type === "setRoleWrite") {
69988
+ const role = message4.role;
69426
69989
  if (!isAgentRole(role, cachedAgentDefinitions)) {
69427
69990
  post({ type: "error", message: `There is no "${role}" role.` });
69428
69991
  return;
69429
69992
  }
69430
69993
  reportFailure("saveAgents", saveAgents((current) => {
69431
69994
  const roles = { ...current.roles ?? {} };
69432
- roles[role] = { ...roles[role] ?? { kind: "profile" }, write: message3.canWrite };
69995
+ roles[role] = { ...roles[role] ?? { kind: "profile" }, write: message4.canWrite };
69433
69996
  return { ...current, roles };
69434
69997
  }));
69435
- } else if (message3.type === "setRoleTools") {
69436
- const role = message3.role;
69998
+ } else if (message4.type === "setRoleTools") {
69999
+ const role = message4.role;
69437
70000
  if (!isAgentRole(role, cachedAgentDefinitions)) {
69438
70001
  post({ type: "error", message: `There is no "${role}" role.` });
69439
70002
  return;
69440
70003
  }
69441
70004
  reportFailure("saveAgents", saveAgents((current) => {
69442
70005
  const roles = { ...current.roles ?? {} };
69443
- roles[role] = { ...roles[role] ?? { kind: "profile" }, tools: message3.usesTools };
70006
+ roles[role] = { ...roles[role] ?? { kind: "profile" }, tools: message4.usesTools };
69444
70007
  return { ...current, roles };
69445
70008
  }));
69446
- } else if (message3.type === "setAgentColor") {
69447
- const role = message3.role;
69448
- const color = message3.color;
70009
+ } else if (message4.type === "setAgentColor") {
70010
+ const role = message4.role;
70011
+ const color = message4.color;
69449
70012
  if (!isColourableAgent(role, cachedAgentDefinitions)) {
69450
70013
  post({ type: "error", message: `There is no "${role}" role.` });
69451
70014
  return;
@@ -69454,47 +70017,47 @@ ${direction}` : attachMentions(text, mentions);
69454
70017
  ...current,
69455
70018
  colors: { ...current.colors ?? {}, [role]: color }
69456
70019
  })));
69457
- } else if (message3.type === "setExpert") {
69458
- reportFailure("handleSetExpert", handleSetExpert(message3.enabled, message3.path, message3.model, {
69459
- ...message3.maxSpendUsd !== void 0 ? { maxSpendUsd: message3.maxSpendUsd } : {},
69460
- ...message3.maxConsultations !== void 0 ? { maxConsultations: message3.maxConsultations } : {},
69461
- ...message3.profileId !== void 0 ? { profileId: message3.profileId } : {}
70020
+ } else if (message4.type === "setExpert") {
70021
+ reportFailure("handleSetExpert", handleSetExpert(message4.enabled, message4.path, message4.model, {
70022
+ ...message4.maxSpendUsd !== void 0 ? { maxSpendUsd: message4.maxSpendUsd } : {},
70023
+ ...message4.maxConsultations !== void 0 ? { maxConsultations: message4.maxConsultations } : {},
70024
+ ...message4.profileId !== void 0 ? { profileId: message4.profileId } : {}
69462
70025
  }));
69463
- } else if (message3.type === "requestProfiles") {
70026
+ } else if (message4.type === "requestProfiles") {
69464
70027
  reportFailure("postProfiles", postProfiles());
69465
70028
  reportFailure("postCapabilities", postCapabilities());
69466
- } else if (message3.type === "saveProfile") {
69467
- reportFailure("handleSaveProfile", handleSaveProfile(message3.profile));
69468
- } else if (message3.type === "requestModels") {
69469
- reportFailure("handleRequestModels", handleRequestModels(message3.profile));
69470
- } else if (message3.type === "testConnection") {
69471
- reportFailure("handleTestConnection", handleTestConnection(message3.profile));
69472
- } else if (message3.type === "duplicateProfile") {
69473
- reportFailure("handleDuplicateProfile", handleDuplicateProfile(message3.id));
69474
- } else if (message3.type === "deleteProfile") {
69475
- reportFailure("handleDeleteProfile", handleDeleteProfile(message3.id));
69476
- } else if (message3.type === "setActiveProfile") {
69477
- reportFailure("handleSetActiveProfile", handleSetActiveProfile(message3.id, message3.forProject));
69478
- } else if (message3.type === "declinePythonTools") {
69479
- reportFailure("handleDeclinePythonTools", handleDeclinePythonTools(message3.names));
69480
- } else if (message3.type === "restorePythonTool") {
69481
- reportFailure("handleRestorePythonTool", handleRestorePythonTool(message3.name));
69482
- } else if (message3.type === "approvePythonTools") {
69483
- reportFailure("handleApprovePythonTools", handleApprovePythonTools(message3.names));
69484
- } else if (message3.type === "requestPythonToolSource") {
69485
- reportFailure("handleRequestPythonToolSource", handleRequestPythonToolSource(message3.name));
69486
- } else if (message3.type === "previewBucketSkillDelete") {
69487
- reportFailure("handlePreviewBucketSkillDelete", handlePreviewBucketSkillDelete(message3.name, message3.sourceDir));
69488
- } else if (message3.type === "deleteSkillFromBucket") {
69489
- reportFailure("handleDeleteSkillFromBucket", handleDeleteSkillFromBucket(message3.name, message3.sourceDir, message3.keys));
69490
- } else if (message3.type === "requestShareSections") {
70029
+ } else if (message4.type === "saveProfile") {
70030
+ reportFailure("handleSaveProfile", handleSaveProfile(message4.profile));
70031
+ } else if (message4.type === "requestModels") {
70032
+ reportFailure("handleRequestModels", handleRequestModels(message4.profile));
70033
+ } else if (message4.type === "testConnection") {
70034
+ reportFailure("handleTestConnection", handleTestConnection(message4.profile));
70035
+ } else if (message4.type === "duplicateProfile") {
70036
+ reportFailure("handleDuplicateProfile", handleDuplicateProfile(message4.id));
70037
+ } else if (message4.type === "deleteProfile") {
70038
+ reportFailure("handleDeleteProfile", handleDeleteProfile(message4.id));
70039
+ } else if (message4.type === "setActiveProfile") {
70040
+ reportFailure("handleSetActiveProfile", handleSetActiveProfile(message4.id, message4.forProject));
70041
+ } else if (message4.type === "declinePythonTools") {
70042
+ reportFailure("handleDeclinePythonTools", handleDeclinePythonTools(message4.names));
70043
+ } else if (message4.type === "restorePythonTool") {
70044
+ reportFailure("handleRestorePythonTool", handleRestorePythonTool(message4.name));
70045
+ } else if (message4.type === "approvePythonTools") {
70046
+ reportFailure("handleApprovePythonTools", handleApprovePythonTools(message4.names));
70047
+ } else if (message4.type === "requestPythonToolSource") {
70048
+ reportFailure("handleRequestPythonToolSource", handleRequestPythonToolSource(message4.name));
70049
+ } else if (message4.type === "previewBucketSkillDelete") {
70050
+ reportFailure("handlePreviewBucketSkillDelete", handlePreviewBucketSkillDelete(message4.name, message4.sourceDir));
70051
+ } else if (message4.type === "deleteSkillFromBucket") {
70052
+ reportFailure("handleDeleteSkillFromBucket", handleDeleteSkillFromBucket(message4.name, message4.sourceDir, message4.keys));
70053
+ } else if (message4.type === "requestShareSections") {
69491
70054
  reportFailure("handleRequestShareSections", handleRequestShareSections());
69492
- } else if (message3.type === "previewImport") {
70055
+ } else if (message4.type === "previewImport") {
69493
70056
  reportFailure("handlePreviewImport", handlePreviewImport());
69494
- } else if (message3.type === "exportConfig") {
69495
- reportFailure("handleExportConfig", handleExportConfig(message3.sections));
69496
- } else if (message3.type === "importConfig") {
69497
- reportFailure("handleImportConfig", handleImportConfig(message3));
70057
+ } else if (message4.type === "exportConfig") {
70058
+ reportFailure("handleExportConfig", handleExportConfig(message4.sections));
70059
+ } else if (message4.type === "importConfig") {
70060
+ reportFailure("handleImportConfig", handleImportConfig(message4));
69498
70061
  }
69499
70062
  });
69500
70063
  void (async () => {
@@ -69515,8 +70078,8 @@ ${direction}` : attachMentions(text, mentions);
69515
70078
  post({ type: "taskRestored", taskId: void 0, entries: [] });
69516
70079
  }
69517
70080
  })();
69518
- async function openFromNotification(message3, level, taskId) {
69519
- const open = await ui.showActionMessage(message3, "Open", level);
70081
+ async function openFromNotification(message4, level, taskId) {
70082
+ const open = await ui.showActionMessage(message4, "Open", level);
69520
70083
  if (!open)
69521
70084
  return;
69522
70085
  await ui.revealPanel();
@@ -69924,9 +70487,9 @@ ${contents}
69924
70487
  function lastAssistantSummary() {
69925
70488
  const messages = conversation.toArray();
69926
70489
  for (let index = messages.length - 1; index >= 0; index--) {
69927
- const message3 = messages[index];
69928
- if (message3?.role === "assistant" && typeof message3.content === "string" && message3.content.trim().length > 0) {
69929
- return message3.content.trim();
70490
+ const message4 = messages[index];
70491
+ if (message4?.role === "assistant" && typeof message4.content === "string" && message4.content.trim().length > 0) {
70492
+ return message4.content.trim();
69930
70493
  }
69931
70494
  }
69932
70495
  return "";
@@ -70059,7 +70622,7 @@ this becomes an ordinary skill: listed by name, read only when it looks relevant
70059
70622
  var MAX_TITLE_LENGTH = 60;
70060
70623
  var FALLBACK_TITLE = "Untitled task";
70061
70624
  function deriveTitle(messages) {
70062
- const firstUserMessage = messages.find((message3) => message3.role === "user");
70625
+ const firstUserMessage = messages.find((message4) => message4.role === "user");
70063
70626
  if (firstUserMessage === void 0)
70064
70627
  return FALLBACK_TITLE;
70065
70628
  const collapsed = firstUserMessage.content.replace(/\s+/g, " ").trim();
@@ -70293,28 +70856,28 @@ function toolCallReason(raw) {
70293
70856
  }
70294
70857
  function toTranscript(messages) {
70295
70858
  const resultsByCallId = /* @__PURE__ */ new Map();
70296
- for (const message3 of messages) {
70297
- if (message3.role === "tool")
70298
- resultsByCallId.set(message3.toolCallId, message3.content);
70859
+ for (const message4 of messages) {
70860
+ if (message4.role === "tool")
70861
+ resultsByCallId.set(message4.toolCallId, message4.content);
70299
70862
  }
70300
70863
  const entries = [];
70301
70864
  let informedBy;
70302
- for (const message3 of messages) {
70303
- if (message3.role === "system" || message3.role === "tool")
70865
+ for (const message4 of messages) {
70866
+ if (message4.role === "system" || message4.role === "tool")
70304
70867
  continue;
70305
- if (message3.role === "user") {
70306
- entries.push({ kind: "text", role: "user", content: message3.content });
70868
+ if (message4.role === "user") {
70869
+ entries.push({ kind: "text", role: "user", content: message4.content });
70307
70870
  continue;
70308
70871
  }
70309
- if (message3.content.length > 0) {
70872
+ if (message4.content.length > 0) {
70310
70873
  entries.push({
70311
70874
  kind: "text",
70312
70875
  role: "assistant",
70313
- content: message3.content,
70876
+ content: message4.content,
70314
70877
  ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
70315
70878
  });
70316
70879
  }
70317
- for (const toolCall of message3.toolCalls ?? []) {
70880
+ for (const toolCall of message4.toolCalls ?? []) {
70318
70881
  const result = resultsByCallId.get(toolCall.id);
70319
70882
  const asChart = chartFromToolCall(toolCall.name, toolCall.arguments);
70320
70883
  if (asChart !== void 0) {
@@ -70407,11 +70970,11 @@ function decodeArguments(raw) {
70407
70970
  }
70408
70971
 
70409
70972
  // ../../packages/core/dist/history/redactTask.js
70410
- function redactMessage(message3, knownSecrets) {
70411
- if (message3.role === "assistant") {
70412
- const redacted = { role: "assistant", content: redact(message3.content, knownSecrets) };
70413
- if (message3.toolCalls !== void 0 && message3.toolCalls.length > 0) {
70414
- redacted.toolCalls = message3.toolCalls.map((call) => ({
70973
+ function redactMessage(message4, knownSecrets) {
70974
+ if (message4.role === "assistant") {
70975
+ const redacted = { role: "assistant", content: redact(message4.content, knownSecrets) };
70976
+ if (message4.toolCalls !== void 0 && message4.toolCalls.length > 0) {
70977
+ redacted.toolCalls = message4.toolCalls.map((call) => ({
70415
70978
  ...call,
70416
70979
  // Arguments are model-authored, but a model can echo a secret it was shown.
70417
70980
  arguments: redact(call.arguments, knownSecrets)
@@ -70419,16 +70982,16 @@ function redactMessage(message3, knownSecrets) {
70419
70982
  }
70420
70983
  return redacted;
70421
70984
  }
70422
- if (message3.role === "tool") {
70423
- return { role: "tool", toolCallId: message3.toolCallId, content: redact(message3.content, knownSecrets) };
70985
+ if (message4.role === "tool") {
70986
+ return { role: "tool", toolCallId: message4.toolCallId, content: redact(message4.content, knownSecrets) };
70424
70987
  }
70425
- return { role: message3.role, content: redact(message3.content, knownSecrets) };
70988
+ return { role: message4.role, content: redact(message4.content, knownSecrets) };
70426
70989
  }
70427
70990
  function redactTask(task, knownSecrets) {
70428
70991
  return {
70429
70992
  ...task,
70430
70993
  title: redact(task.title, knownSecrets),
70431
- messages: task.messages.map((message3) => redactMessage(message3, knownSecrets))
70994
+ messages: task.messages.map((message4) => redactMessage(message4, knownSecrets))
70432
70995
  };
70433
70996
  }
70434
70997
 
@@ -71001,7 +71564,7 @@ function applyDiff(originalContent, diffText) {
71001
71564
  }
71002
71565
 
71003
71566
  // ../../packages/core/dist/tools/applyDiff/index.js
71004
- var paramsSchema12 = external_exports.object({
71567
+ var paramsSchema13 = external_exports.object({
71005
71568
  path: external_exports.string().min(1).describe("Path to the file, relative to the workspace root."),
71006
71569
  diff: external_exports.string().min(1).describe("One or more SEARCH/REPLACE blocks in the standard marker format, targeting this one file.")
71007
71570
  });
@@ -71009,7 +71572,7 @@ var applyDiffTool = {
71009
71572
  name: "apply_diff",
71010
71573
  group: "edit",
71011
71574
  description: "Apply one or more SEARCH/REPLACE blocks to an existing file. The file must have been read with read_file this session. All blocks are validated before any are applied.",
71012
- parametersSchema: paramsSchema12,
71575
+ parametersSchema: paramsSchema13,
71013
71576
  async execute(params, context) {
71014
71577
  const resolved = await resolveToolPath(context, params.path, { write: true });
71015
71578
  if (!resolved.ok)
@@ -71057,35 +71620,35 @@ var applyDiffTool = {
71057
71620
  };
71058
71621
 
71059
71622
  // ../../packages/core/dist/tools/askFollowupQuestion.js
71060
- var paramsSchema13 = external_exports.object({
71623
+ var paramsSchema14 = external_exports.object({
71061
71624
  question: external_exports.string().min(1).describe("The clarifying question to ask the user.")
71062
71625
  });
71063
71626
  var askFollowupQuestionTool = {
71064
71627
  name: "ask_followup_question",
71065
71628
  group: "always",
71066
71629
  description: "Ask the user a clarifying question. Ends this turn; the user's next message is the answer.",
71067
- parametersSchema: paramsSchema13,
71630
+ parametersSchema: paramsSchema14,
71068
71631
  async execute(params) {
71069
71632
  return { content: params.question };
71070
71633
  }
71071
71634
  };
71072
71635
 
71073
71636
  // ../../packages/core/dist/tools/attemptCompletion.js
71074
- var paramsSchema14 = external_exports.object({
71637
+ var paramsSchema15 = external_exports.object({
71075
71638
  result: external_exports.string().min(1).describe("The final result to present to the user.")
71076
71639
  });
71077
71640
  var attemptCompletionTool = {
71078
71641
  name: "attempt_completion",
71079
71642
  group: "always",
71080
71643
  description: "Signal that the task is complete and present the final result. Terminates the loop.",
71081
- parametersSchema: paramsSchema14,
71644
+ parametersSchema: paramsSchema15,
71082
71645
  async execute(params) {
71083
71646
  return { content: params.result };
71084
71647
  }
71085
71648
  };
71086
71649
 
71087
71650
  // ../../packages/core/dist/tools/executeCommand.js
71088
- var paramsSchema15 = external_exports.object({
71651
+ var paramsSchema16 = external_exports.object({
71089
71652
  command: external_exports.string().min(1).describe("The shell command to run."),
71090
71653
  cwd: external_exports.string().optional().describe("Working directory, relative to the workspace root. Defaults to the workspace root.")
71091
71654
  });
@@ -71094,7 +71657,7 @@ var executeCommandTool = {
71094
71657
  name: "execute_command",
71095
71658
  group: "command",
71096
71659
  description: "Run a shell command in the workspace and return its combined stdout/stderr and exit code.",
71097
- parametersSchema: paramsSchema15,
71660
+ parametersSchema: paramsSchema16,
71098
71661
  async execute(params, context) {
71099
71662
  const cwd = params.cwd !== void 0 ? params.cwd : context.workspaceRoot;
71100
71663
  const proc = context.terminal.run(params.command, {
@@ -71144,7 +71707,7 @@ function describeRipgrepFailure(error51, what) {
71144
71707
  }
71145
71708
 
71146
71709
  // ../../packages/core/dist/tools/listFiles.js
71147
- var paramsSchema16 = external_exports.object({
71710
+ var paramsSchema17 = external_exports.object({
71148
71711
  path: external_exports.string().min(1).default(".").describe("Directory to list, relative to the workspace root."),
71149
71712
  recursive: external_exports.boolean().optional().describe("List the full subtree instead of just this directory."),
71150
71713
  /**
@@ -71185,7 +71748,7 @@ var listFilesTool = {
71185
71748
  name: "list_files",
71186
71749
  group: "read",
71187
71750
  description: "List files in a directory. Set recursive to list the full subtree (ignores node_modules and .git).",
71188
- parametersSchema: paramsSchema16,
71751
+ parametersSchema: paramsSchema17,
71189
71752
  async execute(params, context) {
71190
71753
  const resolved = await resolveToolPath(context, params.path);
71191
71754
  if (!resolved.ok)
@@ -71216,7 +71779,7 @@ var listFilesTool = {
71216
71779
  };
71217
71780
 
71218
71781
  // ../../packages/core/dist/tools/readFile.js
71219
- var paramsSchema17 = external_exports.object({
71782
+ var paramsSchema18 = external_exports.object({
71220
71783
  path: external_exports.string().min(1).describe("Path to the file, relative to the workspace root."),
71221
71784
  offset: external_exports.number().int().min(1).optional().describe("1-based line number to start from."),
71222
71785
  limit: external_exports.number().int().min(1).optional().describe("Maximum number of lines to return."),
@@ -71228,7 +71791,7 @@ var readFileTool = {
71228
71791
  name: "read_file",
71229
71792
  group: "read",
71230
71793
  description: "Read a file with line numbers. Use offset/limit to read a window, or tail to read from the end \u2014 a large log must be read in parts rather than all at once.",
71231
- parametersSchema: paramsSchema17,
71794
+ parametersSchema: paramsSchema18,
71232
71795
  async execute(params, context) {
71233
71796
  const resolved = await resolveToolPath(context, params.path);
71234
71797
  if (!resolved.ok)
@@ -71316,7 +71879,7 @@ function realPathName(realPath) {
71316
71879
  }
71317
71880
 
71318
71881
  // ../../packages/core/dist/tools/readDocument.js
71319
- var paramsSchema18 = external_exports.object({
71882
+ var paramsSchema19 = external_exports.object({
71320
71883
  path: external_exports.string().min(1).describe("Path to the document, relative to the workspace root."),
71321
71884
  sheet: external_exports.string().optional().describe("For a spreadsheet: the worksheet name, or its 1-based number. Defaults to the first."),
71322
71885
  offset: external_exports.number().int().min(1).optional().describe("1-based line of the extracted text to start from."),
@@ -71326,7 +71889,7 @@ var readDocumentTool = {
71326
71889
  name: "read_document",
71327
71890
  group: "read",
71328
71891
  description: "Read a Word document (.docx), spreadsheet (.xlsx), PDF or HTML page as plain text. Use this instead of read_file for those formats \u2014 read_file returns unreadable binary for them. Supports offset/limit for long documents, and a sheet name for workbooks.",
71329
- parametersSchema: paramsSchema18,
71892
+ parametersSchema: paramsSchema19,
71330
71893
  async execute(params, context) {
71331
71894
  const resolved = await resolveToolPath(context, params.path);
71332
71895
  if (!resolved.ok)
@@ -71366,7 +71929,7 @@ var readDocumentTool = {
71366
71929
 
71367
71930
  // ../../packages/core/dist/tools/searchFiles.js
71368
71931
  var import_node_child_process11 = require("node:child_process");
71369
- var paramsSchema19 = external_exports.object({
71932
+ var paramsSchema20 = external_exports.object({
71370
71933
  path: external_exports.string().min(1).default(".").describe("Directory to search, relative to the workspace root."),
71371
71934
  pattern: external_exports.string().min(1).describe("Regular expression to search for."),
71372
71935
  filePattern: external_exports.string().optional().describe('Glob to restrict which files are searched, e.g. "*.ts".'),
@@ -71397,7 +71960,7 @@ var searchFilesTool = {
71397
71960
  name: "search_files",
71398
71961
  group: "read",
71399
71962
  description: "Search for a regular expression across files, with surrounding context lines.",
71400
- parametersSchema: paramsSchema19,
71963
+ parametersSchema: paramsSchema20,
71401
71964
  async execute(params, context) {
71402
71965
  const resolved = await resolveToolPath(context, params.path);
71403
71966
  if (!resolved.ok)
@@ -71420,7 +71983,7 @@ var searchFilesTool = {
71420
71983
 
71421
71984
  // ../../packages/core/dist/tools/writeToFile.js
71422
71985
  var import_node_path28 = __toESM(require("node:path"), 1);
71423
- var paramsSchema20 = external_exports.object({
71986
+ var paramsSchema21 = external_exports.object({
71424
71987
  path: external_exports.string().min(1).describe("Path to the file, relative to the workspace root."),
71425
71988
  content: external_exports.string().describe("Full file content to write.")
71426
71989
  });
@@ -71428,7 +71991,7 @@ var writeToFileTool = {
71428
71991
  name: "write_to_file",
71429
71992
  group: "edit",
71430
71993
  description: 'Write full file content, creating the file (and any missing parent directories) if it does not exist. An existing file must have been read with read_file this session before it can be overwritten. If the user asked for a "tool" and create_python_tool exists, use that instead \u2014 a script written here is just a file, and nothing can call it.',
71431
- parametersSchema: paramsSchema20,
71994
+ parametersSchema: paramsSchema21,
71432
71995
  async execute(params, context) {
71433
71996
  const resolved = await resolveToolPath(context, params.path, { write: true });
71434
71997
  if (!resolved.ok)
@@ -71458,7 +72021,7 @@ var writeToFileTool = {
71458
72021
  };
71459
72022
 
71460
72023
  // ../../packages/core/dist/tools/readToolResult.js
71461
- var paramsSchema21 = external_exports.object({
72024
+ var paramsSchema22 = external_exports.object({
71462
72025
  handle: external_exports.string().min(1).describe("The handle from a truncated tool result."),
71463
72026
  offset: external_exports.number().int().min(0).default(0).describe("0-based line to start from."),
71464
72027
  limit: external_exports.number().int().min(1).default(200).describe("Maximum number of lines to return.")
@@ -71468,7 +72031,7 @@ function createReadToolResultTool(store) {
71468
72031
  name: "read_tool_result",
71469
72032
  group: "read",
71470
72033
  description: "Read more of a previously truncated tool result, by handle, with an offset.",
71471
- parametersSchema: paramsSchema21,
72034
+ parametersSchema: paramsSchema22,
71472
72035
  async execute(params) {
71473
72036
  const content = await store.read(params.handle, params.offset, params.limit);
71474
72037
  if (content === void 0) {
@@ -72154,11 +72717,11 @@ async function readAll(response) {
72154
72717
  }
72155
72718
  function describeFailure(status, body, key) {
72156
72719
  const code = matchTag(body, "Code");
72157
- const message3 = matchTag(body, "Message");
72720
+ const message4 = matchTag(body, "Message");
72158
72721
  const what = key === void 0 ? "" : ` for "${key}"`;
72159
72722
  if (code === void 0)
72160
72723
  return `S3 request failed${what} with status ${String(status)}.`;
72161
- return `S3 ${code}${what}: ${message3 ?? `status ${String(status)}`}`;
72724
+ return `S3 ${code}${what}: ${message4 ?? `status ${String(status)}`}`;
72162
72725
  }
72163
72726
  function matchTag(xml, tag) {
72164
72727
  const match = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(xml);
@@ -73597,8 +74160,8 @@ var FileWorkspaceState = class {
73597
74160
  };
73598
74161
  function createBrowserUi(workspaceRoot, post) {
73599
74162
  return {
73600
- showInfo: (message3) => post(`[info] ${message3}`),
73601
- showWarning: (message3) => post(`[warn] ${message3}`),
74163
+ showInfo: (message4) => post(`[info] ${message4}`),
74164
+ showWarning: (message4) => post(`[warn] ${message4}`),
73602
74165
  showOpenDialog: async () => void 0,
73603
74166
  showSaveDialog: async () => void 0,
73604
74167
  /*
@@ -73606,8 +74169,8 @@ function createBrowserUi(workspaceRoot, post) {
73606
74169
  * and `HostUi`'s contract is that no method may be load-bearing (§19) — so resolving false
73607
74170
  * is the honest answer rather than a reason to block the feature here.
73608
74171
  */
73609
- showActionMessage: async (message3, _action, level) => {
73610
- post(`[${level}] ${message3}`);
74172
+ showActionMessage: async (message4, _action, level) => {
74173
+ post(`[${level}] ${message4}`);
73611
74174
  return false;
73612
74175
  },
73613
74176
  // Nothing to reveal: the browser UI is whatever tab the user already has open.
@@ -73641,9 +74204,9 @@ function createBrowserUi(workspaceRoot, post) {
73641
74204
  * A plain recursive walk, since there is no editor index to borrow. Pruned at the
73642
74205
  * directories that would otherwise dominate the result and the runtime.
73643
74206
  */
73644
- async findFiles(pattern, limit, excludeFolders) {
74207
+ async findFiles(segment, limit, excludeFolders) {
73645
74208
  if (workspaceRoot === void 0) return [];
73646
- const needle = pattern.replace(/^\*\*\//, "").replace(/\*/g, "").toLowerCase();
74209
+ const needle = segment.toLowerCase();
73647
74210
  const skip = new Set(excludeFolders);
73648
74211
  const found = [];
73649
74212
  const walk = async (dir, depth) => {
@@ -73912,7 +74475,7 @@ async function startServer(options) {
73912
74475
  // Server-sent events framing. `\n\n` terminates an event, so a newline inside the
73913
74476
  // payload would split it — JSON.stringify already guarantees none, but the data line is
73914
74477
  // written explicitly rather than relying on that.
73915
- post: (message3) => write(`data: ${JSON.stringify(message3)}
74478
+ post: (message4) => write(`data: ${JSON.stringify(message4)}
73916
74479
 
73917
74480
  `),
73918
74481
  onMessage: (listener) => {
@@ -73928,8 +74491,8 @@ async function startServer(options) {
73928
74491
  * one handed to anything in between is how a route ends up calling something undefined.
73929
74492
  */
73930
74493
  resync: () => void 0,
73931
- deliver: (message3) => {
73932
- for (const listener of listeners) listener(message3);
74494
+ deliver: (message4) => {
74495
+ for (const listener of listeners) listener(message4);
73933
74496
  },
73934
74497
  attach: (response) => {
73935
74498
  sink = response;