@chosengeneration/light-code 0.74.0 → 0.77.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.
package/dist/server.js CHANGED
@@ -24482,6 +24482,8 @@ var FetchHttpClient = class {
24482
24482
  init.headers = options.headers;
24483
24483
  if (options.body !== void 0)
24484
24484
  init.body = options.body;
24485
+ if (options.bodyBytes !== void 0)
24486
+ init.body = options.bodyBytes;
24485
24487
  if (options.signal !== void 0)
24486
24488
  init.signal = options.signal;
24487
24489
  let target;
@@ -40171,6 +40173,55 @@ var mailIndexConfigSchema = external_exports.object({
40171
40173
  /** Characters of body kept per message, for showing a hit without reopening Outlook. */
40172
40174
  previewChars: external_exports.number().int().min(0).max(2e3)
40173
40175
  }).partial();
40176
+ var s3ConnectionSchema = external_exports.object({
40177
+ id: external_exports.string().min(1),
40178
+ label: external_exports.string().min(1),
40179
+ bucket: external_exports.string().min(1),
40180
+ region: external_exports.string().min(1),
40181
+ accessKeyId: external_exports.string().min(1),
40182
+ secretAccessKeyRef: external_exports.string().min(1),
40183
+ /** Only for temporary credentials. */
40184
+ sessionTokenRef: external_exports.string().optional(),
40185
+ /** Absent means the ordinary AWS endpoint for the region. */
40186
+ endpoint: external_exports.string().url().optional(),
40187
+ /** `host/bucket/key` instead of `bucket.host/key`, which internal deployments usually need. */
40188
+ pathStyle: external_exports.boolean().optional(),
40189
+ /**
40190
+ * Everything is confined to this prefix, when one is set.
40191
+ *
40192
+ * Not a convenience. It is the only thing bounding what the tools can reach in a bucket that may
40193
+ * hold far more than this project, and it is enforced on every key rather than trusted to the
40194
+ * model — `confine()`'s argument applied to a bucket instead of a disk.
40195
+ */
40196
+ prefix: external_exports.string().optional(),
40197
+ /** Refuses every write, so a bucket can be attached for reading with nothing to go wrong. */
40198
+ readOnly: external_exports.boolean().optional()
40199
+ });
40200
+ var s3MirrorSchema = external_exports.object({
40201
+ connectionId: external_exports.string().min(1),
40202
+ prefix: external_exports.string().optional(),
40203
+ /** Off by default: reading a bucket on every panel open is somebody's money and latency. */
40204
+ enabled: external_exports.boolean().optional()
40205
+ });
40206
+ var s3ConfigSchema = external_exports.object({
40207
+ connections: external_exports.array(s3ConnectionSchema).max(20).optional(),
40208
+ /**
40209
+ * Where skills are kept, when they live in a bucket rather than on this disk.
40210
+ *
40211
+ * Only the *files* move. They are still loaded, watched and indexed exactly as local ones are —
40212
+ * indexing stays as configured — so this names a sync, not a second kind of skill.
40213
+ */
40214
+ skills: s3MirrorSchema.optional(),
40215
+ /**
40216
+ * The same for Python tools, with one difference that is not a detail.
40217
+ *
40218
+ * A mirrored `.py` is **not** loaded on arrival. The hash-pinned registry (§13) refuses any tool
40219
+ * that was not approved with its source shown, so a bucket is how a tool *reaches* a machine,
40220
+ * and approval still happens on each one. Anybody with write access to the bucket would
40221
+ * otherwise be running code as this user on every machine that syncs.
40222
+ */
40223
+ tools: s3MirrorSchema.optional()
40224
+ });
40174
40225
  var configSchema = external_exports.object({
40175
40226
  profiles: external_exports.array(providerProfileSchema),
40176
40227
  /**
@@ -40192,6 +40243,8 @@ var configSchema = external_exports.object({
40192
40243
  * embedder would exfiltrate whatever gets indexed — sharper than the existing entries,
40193
40244
  * because the payload is source code.
40194
40245
  */
40246
+ /** User-scope only (invariant 5): it holds a bucket and a key that can write to it. */
40247
+ s3: s3ConfigSchema,
40195
40248
  vectorStores: external_exports.record(external_exports.string(), vectorStoreSchema),
40196
40249
  activeVectorStoreId: external_exports.string(),
40197
40250
  embedder: embedderConfigSchema,
@@ -40839,6 +40892,15 @@ var USER_SCOPE_ONLY_KEYS = [
40839
40892
  // Per-project settings live here, keyed by path. Same reasoning as `approvals` exactly: a repo
40840
40893
  // that could write its own entry would choose its own vector store and model for itself.
40841
40894
  "workspaces",
40895
+ /*
40896
+ * Holds a bucket, an endpoint and the reference to a key that can read and write it.
40897
+ *
40898
+ * The sharpest kind of entry on this list: a repository able to set it would point the upload
40899
+ * tool at a bucket of its choosing, and everything copied "into S3" would go to somebody else —
40900
+ * with the user watching a tool succeed. Same shape as `embedder`, with whatever the user
40901
+ * uploads as the payload.
40902
+ */
40903
+ "s3",
40842
40904
  // `expert.path` names an executable. A workspace able to set it would run a program of
40843
40905
  // its choosing as soon as the panel opened — the same threat as `python.uvPath`.
40844
40906
  // `expert.enabled` is here too, so a repo cannot switch on paid API calls by itself.
@@ -48486,26 +48548,26 @@ Each appears in its own window. Nothing is changed or sent.`
48486
48548
  async execute(params) {
48487
48549
  const ids = idsOf(params);
48488
48550
  const opened = [];
48489
- const failed = [];
48551
+ const failed2 = [];
48490
48552
  for (const id of ids) {
48491
48553
  try {
48492
48554
  opened.push((await options.display(id)).subject);
48493
48555
  } catch (error51) {
48494
- failed.push(`${id}: ${error51 instanceof Error ? error51.message : String(error51)}`);
48556
+ failed2.push(`${id}: ${error51 instanceof Error ? error51.message : String(error51)}`);
48495
48557
  }
48496
48558
  }
48497
48559
  if (opened.length === 0) {
48498
48560
  return { content: `Could not open any of them.
48499
- ${failed.join("\n")}`, isError: true };
48561
+ ${failed2.join("\n")}`, isError: true };
48500
48562
  }
48501
48563
  return {
48502
48564
  content: [
48503
48565
  `Opened ${String(opened.length)} message(s) in Outlook:`,
48504
48566
  ...opened.map((subject) => ` "${subject}"`),
48505
- ...failed.length === 0 ? [] : [
48567
+ ...failed2.length === 0 ? [] : [
48506
48568
  "",
48507
- `${String(failed.length)} could not be opened - moved or deleted since indexing:`,
48508
- ...failed.map((line) => ` ${line}`)
48569
+ `${String(failed2.length)} could not be opened - moved or deleted since indexing:`,
48570
+ ...failed2.map((line) => ` ${line}`)
48509
48571
  ]
48510
48572
  ].join("\n")
48511
48573
  };
@@ -57074,10 +57136,20 @@ function createWriteSkillTool(context) {
57074
57136
  }
57075
57137
  await fs10.writeFile(filePath, rendered, "utf8");
57076
57138
  await context.onChanged();
57139
+ let publishProblem;
57140
+ if (context.onSaved !== void 0) {
57141
+ try {
57142
+ await context.onSaved(params.name, rendered);
57143
+ } catch (error51) {
57144
+ publishProblem = error51 instanceof Error ? error51.message : String(error51);
57145
+ }
57146
+ }
57077
57147
  const collision = existed ? void 0 : await collisionWarning(params.name);
57078
57148
  return {
57079
57149
  content: `${existed ? "Updated" : "Recorded"} the skill "${params.name}" at ${filePath}.
57080
- Its summary will appear in your context from the next message onward.` + (collision === void 0 ? "" : `
57150
+ Its summary will appear in your context from the next message onward.` + (publishProblem === void 0 ? "" : `
57151
+
57152
+ Saved here, but NOT copied to the bucket: ${publishProblem}`) + (collision === void 0 ? "" : `
57081
57153
 
57082
57154
  ${collision}`),
57083
57155
  path: filePath
@@ -61642,6 +61714,10 @@ var NodeFileSystem = class {
61642
61714
  async writeFile(path32, contents) {
61643
61715
  await fs16.writeFile(path32, contents, "utf8");
61644
61716
  }
61717
+ /** The counterpart of `readBytes`, and deliberately as bare as `writeFile` beside it. */
61718
+ async writeBytes(path32, contents) {
61719
+ await fs16.writeFile(path32, contents);
61720
+ }
61645
61721
  async stat(path32) {
61646
61722
  const stat = await fs16.lstat(path32);
61647
61723
  return {
@@ -62060,6 +62136,10 @@ ${preview.text}` } : {}
62060
62136
  const defaultSkillsDir = workspaceRoot !== void 0 ? path23.join(workspaceRoot, ".lightcode", "skills") : void 0;
62061
62137
  let skillsDir = defaultSkillsDir;
62062
62138
  let extraSkillDirs = [];
62139
+ let mirroredSkillsDir;
62140
+ let mirroredToolsDir;
62141
+ let cachedSkillMirror;
62142
+ let lastSync = {};
62063
62143
  function resolveSkillDir(entry) {
62064
62144
  const trimmed = entry.trim();
62065
62145
  if (trimmed.length === 0)
@@ -62614,6 +62694,7 @@ ${preview.text}` } : {}
62614
62694
  let cachedOffice = {};
62615
62695
  let cachedMail = {};
62616
62696
  let cachedDatasets = [];
62697
+ let cachedS3 = { targets: [], problems: [] };
62617
62698
  let datasetSummaryForPrompt = [];
62618
62699
  let cachedPythonEnabled = false;
62619
62700
  const mailStore = new MailStore(storageDir);
@@ -62662,6 +62743,22 @@ ${preview.text}` } : {}
62662
62743
  cachedOffice = config2.office ?? {};
62663
62744
  cachedMail = config2.mail ?? {};
62664
62745
  cachedDatasets = config2.datasets ?? [];
62746
+ cachedS3 = await resolveS3({
62747
+ config: config2.s3,
62748
+ http: httpClient,
62749
+ secrets,
62750
+ /*
62751
+ * Through the one global resolver, so a corporate root certificate reaches S3 exactly as it
62752
+ * reaches the gateway and the vector store. §10: do not add another place to configure a CA.
62753
+ */
62754
+ tls: await resolveConnectionTls({
62755
+ ...config2.tls !== void 0 ? { global: config2.tls } : {},
62756
+ ...config2.certDir !== void 0 ? { certDir: config2.certDir } : {},
62757
+ onPaths: (paths) => {
62758
+ void Promise.all(paths.map((certPath) => denylist.add(certPath))).catch(() => void 0);
62759
+ }
62760
+ })
62761
+ });
62665
62762
  cachedPythonEnabled = config2.python?.dynamicTools === "on";
62666
62763
  datasetSummaryForPrompt = await Promise.all(cachedDatasets.map(async (dataset) => ({
62667
62764
  name: dataset.name,
@@ -62695,6 +62792,20 @@ ${preview.text}` } : {}
62695
62792
  cachedReadRoots = (config2.filesystem?.readRoots ?? []).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
62696
62793
  skillsDir = (config2.skills?.dir !== void 0 ? resolveSkillDir(config2.skills.dir) : void 0) ?? defaultSkillsDir;
62697
62794
  extraSkillDirs = (config2.skills?.paths ?? []).map(resolveSkillDir).filter((dir) => dir !== void 0);
62795
+ const skillMirror = config2.s3?.skills;
62796
+ cachedSkillMirror = skillMirror;
62797
+ if (skillMirror?.enabled === true) {
62798
+ mirroredSkillsDir = mirrorFolder({
62799
+ storageDir,
62800
+ connectionId: skillMirror.connectionId,
62801
+ kind: "skills",
62802
+ ...skillMirror.prefix !== void 0 ? { prefix: skillMirror.prefix } : {}
62803
+ });
62804
+ if (mirroredSkillsDir !== void 0)
62805
+ extraSkillDirs.push(mirroredSkillsDir);
62806
+ } else {
62807
+ mirroredSkillsDir = void 0;
62808
+ }
62698
62809
  return config2;
62699
62810
  }
62700
62811
  function announceConfigRecovery() {
@@ -62864,7 +62975,21 @@ ${preview.text}` } : {}
62864
62975
  submitForReview: (request) => services.submitForReview?.({ kind: "skill", ...request }) ?? Promise.resolve("")
62865
62976
  } : {}
62866
62977
  };
62867
- combined.register(createWriteSkillTool(context));
62978
+ const skillTarget = cachedSkillMirror?.enabled === true ? targetById(cachedS3, cachedSkillMirror.connectionId) : void 0;
62979
+ const mirrorPrefix = cachedSkillMirror?.prefix;
62980
+ combined.register(createWriteSkillTool({
62981
+ ...context,
62982
+ ...skillTarget !== void 0 && skillTarget.readOnly !== true ? {
62983
+ onSaved: async (name, content) => {
62984
+ await uploadToS3({
62985
+ target: skillTarget,
62986
+ ...mirrorPrefix !== void 0 ? { prefix: mirrorPrefix } : {},
62987
+ relative: `${name}.md`,
62988
+ contents: Buffer.from(content, "utf8")
62989
+ });
62990
+ }
62991
+ } : {}
62992
+ }));
62868
62993
  combined.register(createDeleteSkillTool(context));
62869
62994
  }
62870
62995
  if (workspaceRoot !== void 0) {
@@ -62899,6 +63024,8 @@ ${preview.text}` } : {}
62899
63024
  if (codebase !== void 0) {
62900
63025
  combined.register(createSearchCodebaseTool({ ...codebase, observer: searchLog }));
62901
63026
  }
63027
+ for (const tool of createS3Tools(cachedS3.targets))
63028
+ combined.register(tool);
62902
63029
  if (cachedDatasets.length > 0) {
62903
63030
  combined.register(createSearchDataTool({
62904
63031
  load: async () => Promise.all(cachedDatasets.map(async (dataset) => ({
@@ -65028,6 +65155,155 @@ ${direction}` : attachMentions(text, mentions);
65028
65155
  const digest = createHash3("sha256").update(path23.resolve(workspaceRoot).toLowerCase()).digest("hex").slice(0, 16);
65029
65156
  return `${config2?.embedder?.indexPrefix ?? DEFAULT_INDEX_PREFIX}-${digest}`;
65030
65157
  }
65158
+ async function postS3() {
65159
+ const { config: config2 } = await configManager.load();
65160
+ const connections = await Promise.all((config2.s3?.connections ?? []).map(async (connection) => ({
65161
+ id: connection.id,
65162
+ label: connection.label,
65163
+ bucket: connection.bucket,
65164
+ region: connection.region,
65165
+ accessKeyId: connection.accessKeyId,
65166
+ /*
65167
+ * Asked of the secret store rather than inferred from config holding a reference.
65168
+ *
65169
+ * Config and the store are two stores that can diverge, and letting one assert what only
65170
+ * the other knows is what made a vanished API key keep reading as "Set" for three
65171
+ * releases (section 19).
65172
+ */
65173
+ hasSecret: await secrets.get(connection.secretAccessKeyRef) !== void 0,
65174
+ ...connection.endpoint !== void 0 ? { endpoint: connection.endpoint } : {},
65175
+ ...connection.pathStyle !== void 0 ? { pathStyle: connection.pathStyle } : {},
65176
+ ...connection.prefix !== void 0 ? { prefix: connection.prefix } : {},
65177
+ ...connection.readOnly !== void 0 ? { readOnly: connection.readOnly } : {}
65178
+ })));
65179
+ post({
65180
+ type: "s3",
65181
+ connections,
65182
+ problems: cachedS3.problems,
65183
+ ...config2.s3?.skills !== void 0 ? { skills: config2.s3.skills } : {},
65184
+ ...config2.s3?.tools !== void 0 ? { tools: config2.s3.tools } : {},
65185
+ ...mirroredSkillsDir !== void 0 ? { skillsFolder: mirroredSkillsDir } : {},
65186
+ ...mirroredToolsDir !== void 0 ? { toolsFolder: mirroredToolsDir } : {},
65187
+ ...lastSync.skills !== void 0 ? { lastSkillsSync: lastSync.skills } : {},
65188
+ ...lastSync.tools !== void 0 ? { lastToolsSync: lastSync.tools } : {}
65189
+ });
65190
+ }
65191
+ const s3SecretRef = (id) => `s3:${id}:secret`;
65192
+ const s3TokenRef = (id) => `s3:${id}:sessionToken`;
65193
+ async function handleSaveS3Connection(input, secret, sessionToken) {
65194
+ const { config: config2 } = await configManager.load();
65195
+ const id = input.id ?? `s3-${Date.now().toString(36)}`;
65196
+ const existing = (config2.s3?.connections ?? []).find((connection) => connection.id === id);
65197
+ if (secret !== void 0 && secret.trim().length > 0) {
65198
+ await secrets.set(s3SecretRef(id), secret.trim());
65199
+ }
65200
+ if (sessionToken !== void 0 && sessionToken.trim().length > 0) {
65201
+ await secrets.set(s3TokenRef(id), sessionToken.trim());
65202
+ }
65203
+ const saved = {
65204
+ id,
65205
+ label: input.label.trim(),
65206
+ bucket: input.bucket.trim(),
65207
+ region: input.region.trim(),
65208
+ accessKeyId: input.accessKeyId.trim(),
65209
+ secretAccessKeyRef: s3SecretRef(id),
65210
+ ...existing?.sessionTokenRef !== void 0 || (sessionToken ?? "").trim().length > 0 ? { sessionTokenRef: s3TokenRef(id) } : {},
65211
+ ...input.endpoint !== void 0 && input.endpoint.trim().length > 0 ? { endpoint: input.endpoint.trim() } : {},
65212
+ ...input.pathStyle === true ? { pathStyle: true } : {},
65213
+ ...input.prefix !== void 0 && input.prefix.trim().length > 0 ? { prefix: input.prefix.trim() } : {},
65214
+ ...input.readOnly === true ? { readOnly: true } : {}
65215
+ };
65216
+ const others = (config2.s3?.connections ?? []).filter((connection) => connection.id !== id);
65217
+ await configManager.save("user", {
65218
+ s3: { ...config2.s3 ?? {}, connections: [...others, saved] }
65219
+ });
65220
+ await loadSettings();
65221
+ await postS3();
65222
+ }
65223
+ async function handleDeleteS3Connection(id) {
65224
+ const { config: config2 } = await configManager.load();
65225
+ await secrets.delete(s3SecretRef(id)).catch(() => void 0);
65226
+ await secrets.delete(s3TokenRef(id)).catch(() => void 0);
65227
+ const s3 = { ...config2.s3 ?? {} };
65228
+ s3.connections = (s3.connections ?? []).filter((connection) => connection.id !== id);
65229
+ if (s3.skills?.connectionId === id)
65230
+ delete s3.skills;
65231
+ if (s3.tools?.connectionId === id)
65232
+ delete s3.tools;
65233
+ await configManager.save("user", { s3 });
65234
+ await loadSettings();
65235
+ await postS3();
65236
+ }
65237
+ async function handleSaveS3Mirror(kind, connectionId, prefix, enabled) {
65238
+ const { config: config2 } = await configManager.load();
65239
+ const s3 = { ...config2.s3 ?? {} };
65240
+ if (connectionId.trim().length === 0)
65241
+ delete s3[kind];
65242
+ else {
65243
+ s3[kind] = {
65244
+ connectionId: connectionId.trim(),
65245
+ ...prefix !== void 0 && prefix.trim().length > 0 ? { prefix: prefix.trim() } : {},
65246
+ enabled
65247
+ };
65248
+ }
65249
+ await configManager.save("user", { s3 });
65250
+ await loadSettings();
65251
+ if (enabled && connectionId.trim().length > 0)
65252
+ await handleSyncS3(kind);
65253
+ else
65254
+ await postS3();
65255
+ }
65256
+ async function handleSyncS3(kind) {
65257
+ const { config: config2 } = await configManager.load();
65258
+ const mirror = config2.s3?.[kind];
65259
+ if (mirror === void 0) {
65260
+ lastSync = { ...lastSync, [kind]: "No bucket folder is configured." };
65261
+ await postS3();
65262
+ return;
65263
+ }
65264
+ const target = targetById(cachedS3, mirror.connectionId);
65265
+ if (target === void 0) {
65266
+ lastSync = {
65267
+ ...lastSync,
65268
+ [kind]: "That connection is not usable - check its key in the list above."
65269
+ };
65270
+ await postS3();
65271
+ return;
65272
+ }
65273
+ const localDir = mirrorFolder({
65274
+ storageDir,
65275
+ connectionId: mirror.connectionId,
65276
+ kind,
65277
+ ...mirror.prefix !== void 0 ? { prefix: mirror.prefix } : {}
65278
+ });
65279
+ if (kind === "tools")
65280
+ mirroredToolsDir = localDir;
65281
+ try {
65282
+ const result = await syncFromS3({
65283
+ target,
65284
+ ...mirror.prefix !== void 0 ? { prefix: mirror.prefix } : {},
65285
+ localDir,
65286
+ fs: new NodeFileSystem(),
65287
+ extensions: kind === "skills" ? [".md"] : [".py"]
65288
+ });
65289
+ const parts = [
65290
+ `${String(result.written.length)} updated`,
65291
+ `${String(result.unchanged)} unchanged`
65292
+ ];
65293
+ if (result.failed.length > 0)
65294
+ parts.push(`${String(result.failed.length)} failed`);
65295
+ lastSync = { ...lastSync, [kind]: `${(/* @__PURE__ */ new Date()).toLocaleTimeString()} - ${parts.join(", ")}` };
65296
+ for (const failure of result.failed)
65297
+ logger.warn(`s3 ${kind}: ${failure.key}`, failure.problem);
65298
+ if (kind === "skills") {
65299
+ await refreshSkills();
65300
+ postSkills();
65301
+ }
65302
+ } catch (error51) {
65303
+ lastSync = { ...lastSync, [kind]: error51 instanceof Error ? error51.message : String(error51) };
65304
+ }
65305
+ await postS3();
65306
+ }
65031
65307
  async function handleSaveSkillsAlias(aliases) {
65032
65308
  try {
65033
65309
  const { config: config2 } = await configManager.load();
@@ -66594,6 +66870,13 @@ ${direction}` : attachMentions(text, mentions);
66594
66870
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
66595
66871
  }
66596
66872
  }
66873
+ function reportFailure(operation, work) {
66874
+ work.catch((error51) => {
66875
+ const reason = error51 instanceof Error ? error51.message : String(error51);
66876
+ logger.warn(`${operation} failed`, reason);
66877
+ post({ type: "error", message: `${operation} failed: ${reason}` });
66878
+ });
66879
+ }
66597
66880
  const unsubscribe = transport.onMessage((raw) => {
66598
66881
  const message3 = raw;
66599
66882
  if (message3.type === "sendMessage") {
@@ -66614,7 +66897,7 @@ ${direction}` : attachMentions(text, mentions);
66614
66897
  }
66615
66898
  })();
66616
66899
  } else if (message3.type === "requestMentionCandidates") {
66617
- void handleMentionCandidates(message3.query);
66900
+ reportFailure("handleMentionCandidates", handleMentionCandidates(message3.query));
66618
66901
  } else if (message3.type === "queueMessage") {
66619
66902
  queuedMessages.push(message3.text);
66620
66903
  postQueued();
@@ -66637,21 +66920,21 @@ ${direction}` : attachMentions(text, mentions);
66637
66920
  pendingFormFields.delete(message3.id);
66638
66921
  }
66639
66922
  } else if (message3.type === "approvalResponseAlways") {
66640
- void handleAlwaysAllow(message3.id, message3.scope);
66923
+ reportFailure("handleAlwaysAllow", handleAlwaysAllow(message3.id, message3.scope));
66641
66924
  } else if (message3.type === "rollback") {
66642
- void handleRollback();
66925
+ reportFailure("handleRollback", handleRollback());
66643
66926
  } else if (message3.type === "requestSettings") {
66644
- void postSettings();
66927
+ reportFailure("postSettings", postSettings());
66645
66928
  } else if (message3.type === "requestTasks") {
66646
- void postTasks();
66929
+ reportFailure("postTasks", postTasks());
66647
66930
  } else if (message3.type === "openTask") {
66648
- void openTask(message3.id);
66931
+ reportFailure("openTask", openTask(message3.id));
66649
66932
  } else if (message3.type === "deleteTask") {
66650
- void deleteTask(message3.id);
66933
+ reportFailure("deleteTask", deleteTask(message3.id));
66651
66934
  } else if (message3.type === "newTask") {
66652
- void startNewTask();
66935
+ reportFailure("startNewTask", startNewTask());
66653
66936
  } else if (message3.type === "setMode") {
66654
- void handleSetMode(message3.modeId);
66937
+ reportFailure("handleSetMode", handleSetMode(message3.modeId));
66655
66938
  } else if (message3.type === "setMaxIterations") {
66656
66939
  void configManager.save("user", { maxIterations: message3.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
66657
66940
  } else if (message3.type === "setProgrammingProfile") {
@@ -66679,7 +66962,7 @@ ${direction}` : attachMentions(text, mentions);
66679
66962
  }
66680
66963
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
66681
66964
  } else if (message3.type === "setToolTimeoutFor") {
66682
- void handleSetToolTimeoutFor(message3.name, message3.seconds);
66965
+ reportFailure("handleSetToolTimeoutFor", handleSetToolTimeoutFor(message3.name, message3.seconds));
66683
66966
  } else if (message3.type === "setToolTimeout") {
66684
66967
  void configManager.save("user", {
66685
66968
  tools: message3.seconds === void 0 ? {} : { timeoutSeconds: message3.seconds }
@@ -66701,73 +66984,73 @@ ${direction}` : attachMentions(text, mentions);
66701
66984
  }
66702
66985
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
66703
66986
  } else if (message3.type === "setAutoApprove") {
66704
- void handleSetAutoApprove(message3.group, message3.enabled);
66987
+ reportFailure("handleSetAutoApprove", handleSetAutoApprove(message3.group, message3.enabled));
66705
66988
  } else if (message3.type === "revokeAllowedTool") {
66706
- void saveApprovals({
66989
+ reportFailure("saveApprovals", saveApprovals({
66707
66990
  ...cachedApprovals,
66708
66991
  allowedTools: removeFromAllowlist(message3.toolName, cachedApprovals.allowedTools ?? [])
66709
- });
66992
+ }));
66710
66993
  } else if (message3.type === "revokeAllowedCommand") {
66711
- void saveApprovals({
66994
+ reportFailure("saveApprovals", saveApprovals({
66712
66995
  ...cachedApprovals,
66713
66996
  allowedCommands: removeFromAllowlist(message3.command, cachedApprovals.allowedCommands ?? [])
66714
- });
66997
+ }));
66715
66998
  } else if (message3.type === "requestMcp") {
66716
- void handleRequestMcp();
66999
+ reportFailure("handleRequestMcp", handleRequestMcp());
66717
67000
  } else if (message3.type === "saveMcpServers") {
66718
- void handleSaveMcpServers(message3.json);
67001
+ reportFailure("handleSaveMcpServers", handleSaveMcpServers(message3.json));
66719
67002
  } else if (message3.type === "saveMcpServer") {
66720
- void handleSaveMcpServer(message3.name, message3.previousName, message3.config);
67003
+ reportFailure("handleSaveMcpServer", handleSaveMcpServer(message3.name, message3.previousName, message3.config));
66721
67004
  } else if (message3.type === "duplicateMcpServer") {
66722
- void handleDuplicateMcpServer(message3.name);
67005
+ reportFailure("handleDuplicateMcpServer", handleDuplicateMcpServer(message3.name));
66723
67006
  } else if (message3.type === "deleteMcpServer") {
66724
- void handleDeleteMcpServer(message3.name);
67007
+ reportFailure("handleDeleteMcpServer", handleDeleteMcpServer(message3.name));
66725
67008
  } else if (message3.type === "browseForPath") {
66726
- void handleBrowseForPath(message3.purpose, message3.kind, message3.extensions);
67009
+ reportFailure("handleBrowseForPath", handleBrowseForPath(message3.purpose, message3.kind, message3.extensions));
66727
67010
  } else if (message3.type === "probePythonEnv") {
66728
- void handleProbePythonEnv(message3.venvDir, message3.script);
67011
+ reportFailure("handleProbePythonEnv", handleProbePythonEnv(message3.venvDir, message3.script));
66729
67012
  } else if (message3.type === "connectMcpServer") {
66730
67013
  void mcp.connectServer(message3.name);
66731
67014
  } else if (message3.type === "restartMcpServer") {
66732
67015
  void mcp.restart(message3.name);
66733
67016
  } else if (message3.type === "setMcpServerEnabled") {
66734
- void updateMcpServer(message3.name, (entry) => ({
67017
+ reportFailure("updateMcpServer", updateMcpServer(message3.name, (entry) => ({
66735
67018
  ...entry,
66736
67019
  disabled: !message3.enabled
66737
- })).then(() => postMcp());
67020
+ })).then(() => postMcp()));
66738
67021
  } else if (message3.type === "setMcpToolTimeout") {
66739
- void handleSetToolTimeout(message3.server, message3.tool, message3.seconds);
67022
+ reportFailure("handleSetToolTimeout", handleSetToolTimeout(message3.server, message3.tool, message3.seconds));
66740
67023
  } else if (message3.type === "setMcpToolPermission") {
66741
- void handleSetToolPermission(message3.server, message3.tool, message3.permission);
67024
+ reportFailure("handleSetToolPermission", handleSetToolPermission(message3.server, message3.tool, message3.permission));
66742
67025
  } else if (message3.type === "requestSearch") {
66743
- void postSearch();
66744
- void postDispatcher();
67026
+ reportFailure("postSearch", postSearch());
67027
+ reportFailure("postDispatcher", postDispatcher());
66745
67028
  post({ type: "searchLog", entries: [...searchLog.list()] });
66746
67029
  } else if (message3.type === "saveSearchConnection") {
66747
- void handleSaveSearchConnection(message3.connection);
67030
+ reportFailure("handleSaveSearchConnection", handleSaveSearchConnection(message3.connection));
66748
67031
  } else if (message3.type === "deleteSearchConnection") {
66749
- void handleDeleteSearchConnection(message3.id);
67032
+ reportFailure("handleDeleteSearchConnection", handleDeleteSearchConnection(message3.id));
66750
67033
  } else if (message3.type === "setActiveSearchConnection") {
66751
67034
  void (message3.forProject === true ? configManager.saveForWorkspace({ activeVectorStoreId: message3.id }) : configManager.save("user", { activeVectorStoreId: message3.id })).then(async () => {
66752
67035
  await postSearch();
66753
67036
  await postProjectSettings();
66754
67037
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66755
67038
  } else if (message3.type === "requestProjectSettings") {
66756
- void postProjectSettings();
67039
+ reportFailure("postProjectSettings", postProjectSettings());
66757
67040
  } else if (message3.type === "clearProjectSettings") {
66758
- void handleClearProjectSettings();
67041
+ reportFailure("handleClearProjectSettings", handleClearProjectSettings());
66759
67042
  } else if (message3.type === "requestSearchIndexes") {
66760
- void handleRequestSearchIndexes(message3.connection);
67043
+ reportFailure("handleRequestSearchIndexes", handleRequestSearchIndexes(message3.connection));
66761
67044
  } else if (message3.type === "testSearchConnection") {
66762
- void handleTestSearchConnection(message3.connection);
67045
+ reportFailure("handleTestSearchConnection", handleTestSearchConnection(message3.connection));
66763
67046
  } else if (message3.type === "syncVectorStore") {
66764
- void handleSyncVectorStore(message3.fromId);
67047
+ reportFailure("handleSyncVectorStore", handleSyncVectorStore(message3.fromId));
66765
67048
  } else if (message3.type === "clearDocsIndex") {
66766
- void handleClearDocsIndex(message3.kind);
67049
+ reportFailure("handleClearDocsIndex", handleClearDocsIndex(message3.kind));
66767
67050
  } else if (message3.type === "clearCodebaseIndex") {
66768
- void handleClearCodebaseIndex();
67051
+ reportFailure("handleClearCodebaseIndex", handleClearCodebaseIndex());
66769
67052
  } else if (message3.type === "openStandingSkill") {
66770
- void handleOpenStandingSkill();
67053
+ reportFailure("handleOpenStandingSkill", handleOpenStandingSkill());
66771
67054
  } else if (message3.type === "setOffice") {
66772
67055
  void configManager.load().then(async () => {
66773
67056
  await configManager.save("user", {
@@ -66781,70 +67064,80 @@ ${direction}` : attachMentions(text, mentions);
66781
67064
  }
66782
67065
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66783
67066
  } else if (message3.type === "indexDocs") {
66784
- void handleIndexDocs(message3.kind);
67067
+ reportFailure("handleIndexDocs", handleIndexDocs(message3.kind));
66785
67068
  } else if (message3.type === "runSearchProbe") {
66786
- void handleSearchProbe(message3.query, message3.target);
67069
+ reportFailure("handleSearchProbe", handleSearchProbe(message3.query, message3.target));
66787
67070
  } else if (message3.type === "clearSearchLog") {
66788
67071
  searchLog.clear();
66789
67072
  } else if (message3.type === "setDispatcher") {
66790
- void saveRetrieval({ dispatcher: message3.enabled }).then(() => {
66791
- void postDispatcher();
67073
+ reportFailure("saveRetrieval", saveRetrieval({ dispatcher: message3.enabled }).then(() => {
67074
+ reportFailure("postDispatcher", postDispatcher());
66792
67075
  if (message3.enabled)
66793
67076
  scheduleDocsReindex("dispatcher enabled");
66794
- }).catch((error51) => post({ type: "error", message: String(error51) }));
67077
+ }));
66795
67078
  } else if (message3.type === "setSkillRetrieval") {
66796
- void saveRetrieval({ skills: message3.enabled }).then(() => {
66797
- void postDispatcher();
67079
+ reportFailure("saveRetrieval", saveRetrieval({ skills: message3.enabled }).then(() => {
67080
+ reportFailure("postDispatcher", postDispatcher());
66798
67081
  if (message3.enabled)
66799
67082
  scheduleDocsReindex("skill retrieval enabled");
66800
- }).catch((error51) => post({ type: "error", message: String(error51) }));
67083
+ }));
66801
67084
  } else if (message3.type === "startIndexing") {
66802
- void handleStartIndexing();
67085
+ reportFailure("handleStartIndexing", handleStartIndexing());
66803
67086
  } else if (message3.type === "attachTeamAlias") {
66804
- void handleAttachTeamAlias();
67087
+ reportFailure("handleAttachTeamAlias", handleAttachTeamAlias());
66805
67088
  } else if (message3.type === "publishTeamSkills") {
66806
- void handlePublishTeamSkills();
67089
+ reportFailure("handlePublishTeamSkills", handlePublishTeamSkills());
66807
67090
  } else if (message3.type === "syncMail") {
66808
- void runMailSync("requested");
67091
+ reportFailure("runMailSync", runMailSync("requested"));
66809
67092
  } else if (message3.type === "pruneMail") {
66810
- void handlePruneMail();
67093
+ reportFailure("handlePruneMail", handlePruneMail());
66811
67094
  } else if (message3.type === "requestOutlookFolders") {
66812
- void handleRequestOutlookFolders(message3.depth, message3.force === true);
67095
+ reportFailure("handleRequestOutlookFolders", handleRequestOutlookFolders(message3.depth, message3.force === true));
66813
67096
  } else if (message3.type === "validateMailFolder") {
66814
- void handleValidateMailFolder(message3.path);
67097
+ reportFailure("handleValidateMailFolder", handleValidateMailFolder(message3.path));
66815
67098
  } else if (message3.type === "requestMailStatus") {
66816
- void loadSettings().then((config2) => {
67099
+ reportFailure("loadSettings", loadSettings().then((config2) => {
66817
67100
  reconcileMailTimer(config2);
66818
67101
  reconcileDatasetTimers(config2);
66819
67102
  return postMailStatus();
66820
- });
67103
+ }));
66821
67104
  } else if (message3.type === "saveMailSettings") {
66822
- void handleSaveMailSettings({
67105
+ reportFailure("handleSaveMailSettings", handleSaveMailSettings({
66823
67106
  enabled: message3.enabled,
66824
67107
  folders: message3.folders,
66825
67108
  includeSubfolders: message3.includeSubfolders,
66826
67109
  syncMinutes: message3.syncMinutes,
66827
67110
  retentionMonths: message3.retentionMonths,
66828
67111
  ...message3.storeId !== void 0 ? { storeId: message3.storeId } : {}
66829
- });
67112
+ }));
66830
67113
  } else if (message3.type === "clearTeamSkills") {
66831
- void handleClearTeamSkills();
67114
+ reportFailure("handleClearTeamSkills", handleClearTeamSkills());
66832
67115
  } else if (message3.type === "refreshMail") {
66833
- void handleRefreshMail(message3.days);
67116
+ reportFailure("handleRefreshMail", handleRefreshMail(message3.days));
66834
67117
  } else if (message3.type === "requestDatasetStatus") {
66835
- void postDatasetStatus();
67118
+ reportFailure("postDatasetStatus", postDatasetStatus());
66836
67119
  } else if (message3.type === "saveDataset") {
66837
- void handleSaveDataset(message3.dataset);
67120
+ reportFailure("handleSaveDataset", handleSaveDataset(message3.dataset));
66838
67121
  } else if (message3.type === "deleteDataset") {
66839
- void handleDeleteDataset(message3.id);
67122
+ reportFailure("handleDeleteDataset", handleDeleteDataset(message3.id));
66840
67123
  } else if (message3.type === "syncDataset") {
66841
- void runDatasetSync(message3.id, "manual");
67124
+ reportFailure("runDatasetSync", runDatasetSync(message3.id, "manual"));
66842
67125
  } else if (message3.type === "clearDataset") {
66843
- void handleClearDataset(message3.id, message3.resync === true);
67126
+ reportFailure("handleClearDataset", handleClearDataset(message3.id, message3.resync === true));
66844
67127
  } else if (message3.type === "clearMailIndex") {
66845
- void handleClearMailIndex(message3.resync === true);
67128
+ reportFailure("handleClearMailIndex", handleClearMailIndex(message3.resync === true));
67129
+ } else if (message3.type === "requestS3") {
67130
+ reportFailure("postS3", postS3());
67131
+ } else if (message3.type === "saveS3Connection") {
67132
+ reportFailure("handleSaveS3Connection", handleSaveS3Connection(message3.connection, message3.secret, message3.sessionToken));
67133
+ } else if (message3.type === "deleteS3Connection") {
67134
+ reportFailure("handleDeleteS3Connection", handleDeleteS3Connection(message3.id));
67135
+ } else if (message3.type === "saveS3Mirror") {
67136
+ reportFailure("handleSaveS3Mirror", handleSaveS3Mirror(message3.kind, message3.connectionId, message3.prefix, message3.enabled));
67137
+ } else if (message3.type === "syncS3") {
67138
+ reportFailure("handleSyncS3", handleSyncS3(message3.kind));
66846
67139
  } else if (message3.type === "saveSkillsAlias") {
66847
- void handleSaveSkillsAlias(message3.aliases);
67140
+ reportFailure("handleSaveSkillsAlias", handleSaveSkillsAlias(message3.aliases));
66848
67141
  } else if (message3.type === "cancelIndexing") {
66849
67142
  if (message3.kind === void 0) {
66850
67143
  indexingAbort?.abort();
@@ -66856,23 +67149,23 @@ ${direction}` : attachMentions(text, mentions);
66856
67149
  indexingAborts.get(message3.kind)?.abort();
66857
67150
  }
66858
67151
  } else if (message3.type === "saveEmbedder") {
66859
- void handleSaveEmbedder(message3.profileId, message3.model, message3.dimensions, message3.indexName, message3.indexPrefix, message3.indexAliases);
67152
+ reportFailure("handleSaveEmbedder", handleSaveEmbedder(message3.profileId, message3.model, message3.dimensions, message3.indexName, message3.indexPrefix, message3.indexAliases));
66860
67153
  } else if (message3.type === "requestEmbedderModels") {
66861
- void handleRequestEmbedderModels(message3.profileId);
67154
+ reportFailure("handleRequestEmbedderModels", handleRequestEmbedderModels(message3.profileId));
66862
67155
  } else if (message3.type === "openWalkthrough") {
66863
67156
  void ui.openWalkthrough?.();
66864
67157
  } else if (message3.type === "requestTools") {
66865
- void postTools();
67158
+ reportFailure("postTools", postTools());
66866
67159
  } else if (message3.type === "requestSchedules") {
66867
- void postSchedules();
67160
+ reportFailure("postSchedules", postSchedules());
66868
67161
  } else if (message3.type === "saveSchedule") {
66869
- void handleSaveSchedule(message3.schedule);
67162
+ reportFailure("handleSaveSchedule", handleSaveSchedule(message3.schedule));
66870
67163
  } else if (message3.type === "duplicateSchedule") {
66871
- void handleDuplicateSchedule(message3.id);
67164
+ reportFailure("handleDuplicateSchedule", handleDuplicateSchedule(message3.id));
66872
67165
  } else if (message3.type === "deleteSchedule") {
66873
- void handleDeleteSchedule(message3.id);
67166
+ reportFailure("handleDeleteSchedule", handleDeleteSchedule(message3.id));
66874
67167
  } else if (message3.type === "setScheduleEnabled") {
66875
- void handleSetScheduleEnabled(message3.id, message3.enabled);
67168
+ reportFailure("handleSetScheduleEnabled", handleSetScheduleEnabled(message3.id, message3.enabled));
66876
67169
  } else if (message3.type === "setTaskExpertLimits") {
66877
67170
  const next = message3.maxSpendUsd === void 0 && message3.maxConsultations === void 0 ? void 0 : {
66878
67171
  ...message3.maxSpendUsd !== void 0 ? { maxSpendUsd: message3.maxSpendUsd } : {},
@@ -66902,7 +67195,7 @@ ${direction}` : attachMentions(text, mentions);
66902
67195
  await postExpert({ redetect: false });
66903
67196
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66904
67197
  } else if (message3.type === "measureExpertCost") {
66905
- void handleMeasureExpertCost();
67198
+ reportFailure("handleMeasureExpertCost", handleMeasureExpertCost());
66906
67199
  } else if (message3.type === "clearExpertPricing") {
66907
67200
  void configManager.load().then(async ({ config: config2 }) => {
66908
67201
  const expert = { ...config2.expert };
@@ -66912,23 +67205,23 @@ ${direction}` : attachMentions(text, mentions);
66912
67205
  await postExpert({ redetect: false });
66913
67206
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66914
67207
  } else if (message3.type === "assessJunior") {
66915
- void handleAssessJunior(message3.profileId);
67208
+ reportFailure("handleAssessJunior", handleAssessJunior(message3.profileId));
66916
67209
  } else if (message3.type === "clearAssessment") {
66917
- void handleClearAssessment(message3.model, message3.profileLabel);
67210
+ reportFailure("handleClearAssessment", handleClearAssessment(message3.model, message3.profileLabel));
66918
67211
  } else if (message3.type === "restartScheduler") {
66919
67212
  restartScheduleTimer();
66920
67213
  logger.info("schedule timer restarted by the user");
66921
- void postSchedules();
67214
+ reportFailure("postSchedules", postSchedules());
66922
67215
  } else if (message3.type === "deleteScheduleRun") {
66923
- void handleDeleteScheduleRun(message3.id, message3.at);
67216
+ reportFailure("handleDeleteScheduleRun", handleDeleteScheduleRun(message3.id, message3.at));
66924
67217
  } else if (message3.type === "clearScheduleRuns") {
66925
- void handleClearScheduleRuns(message3.id);
67218
+ reportFailure("handleClearScheduleRuns", handleClearScheduleRuns(message3.id));
66926
67219
  } else if (message3.type === "openScheduleRun") {
66927
- void openRunTranscript(message3.taskId, message3.title);
67220
+ reportFailure("openRunTranscript", openRunTranscript(message3.taskId, message3.title));
66928
67221
  } else if (message3.type === "runScheduleNow") {
66929
- void runSchedule(message3.id, "manual");
67222
+ reportFailure("runSchedule", runSchedule(message3.id, "manual"));
66930
67223
  } else if (message3.type === "requestSkills") {
66931
- void postSkills();
67224
+ reportFailure("postSkills", postSkills());
66932
67225
  } else if (message3.type === "saveSkillDirs") {
66933
67226
  void configManager.save("user", {
66934
67227
  skills: {
@@ -66937,32 +67230,32 @@ ${direction}` : attachMentions(text, mentions);
66937
67230
  }
66938
67231
  }).then(() => postSkills()).catch((error51) => post({ type: "error", message: String(error51) }));
66939
67232
  } else if (message3.type === "openManagedFile") {
66940
- void handleOpenManagedFile(message3.path);
67233
+ reportFailure("handleOpenManagedFile", handleOpenManagedFile(message3.path));
66941
67234
  } else if (message3.type === "deletePythonTool") {
66942
- void handleDeletePythonTool(message3.name);
67235
+ reportFailure("handleDeletePythonTool", handleDeletePythonTool(message3.name));
66943
67236
  } else if (message3.type === "approvePythonTool") {
66944
- void handleApprovePythonTool(message3.name);
67237
+ reportFailure("handleApprovePythonTool", handleApprovePythonTool(message3.name));
66945
67238
  } else if (message3.type === "deleteSkillFile") {
66946
- void handleDeleteSkillFile(message3.name);
67239
+ reportFailure("handleDeleteSkillFile", handleDeleteSkillFile(message3.name));
66947
67240
  } else if (message3.type === "requestPython") {
66948
- void postPython();
67241
+ reportFailure("postPython", postPython());
66949
67242
  } else if (message3.type === "setPython") {
66950
- void handleSetPython(message3);
67243
+ reportFailure("handleSetPython", handleSetPython(message3));
66951
67244
  } else if (message3.type === "requestNetwork") {
66952
- void postNetwork();
67245
+ reportFailure("postNetwork", postNetwork());
66953
67246
  } else if (message3.type === "saveNetwork") {
66954
- void handleSaveNetwork(message3.settings);
67247
+ reportFailure("handleSaveNetwork", handleSaveNetwork(message3.settings));
66955
67248
  } else if (message3.type === "requestExpert") {
66956
- void postExpert();
67249
+ reportFailure("postExpert", postExpert());
66957
67250
  } else if (message3.type === "setPlan") {
66958
- void applyPlan(message3.plan);
67251
+ reportFailure("applyPlan", applyPlan(message3.plan));
66959
67252
  } else if (message3.type === "requestPlan") {
66960
67253
  post({ type: "plan", plan: activePlan ?? "" });
66961
67254
  postPlanProgress();
66962
67255
  } else if (message3.type === "requestPlanProgress") {
66963
67256
  postPlanProgress();
66964
67257
  } else if (message3.type === "requestAgents") {
66965
- void postAgents();
67258
+ reportFailure("postAgents", postAgents());
66966
67259
  } else if (message3.type === "setAgentRole") {
66967
67260
  const assignment = message3.assignment;
66968
67261
  const role = message3.role;
@@ -66970,7 +67263,7 @@ ${direction}` : attachMentions(text, mentions);
66970
67263
  post({ type: "error", message: `There is no "${role}" role.` });
66971
67264
  return;
66972
67265
  }
66973
- void saveAgents((current) => {
67266
+ reportFailure("saveAgents", saveAgents((current) => {
66974
67267
  const roles = { ...current.roles ?? {} };
66975
67268
  if (assignment === void 0)
66976
67269
  delete roles[role];
@@ -66982,7 +67275,7 @@ ${direction}` : attachMentions(text, mentions);
66982
67275
  };
66983
67276
  }
66984
67277
  return { ...current, roles };
66985
- });
67278
+ }));
66986
67279
  } else if (message3.type === "setAgentPrompt") {
66987
67280
  const role = message3.role;
66988
67281
  const prompt = message3.prompt;
@@ -66990,7 +67283,7 @@ ${direction}` : attachMentions(text, mentions);
66990
67283
  post({ type: "error", message: `There is no "${role}" role.` });
66991
67284
  return;
66992
67285
  }
66993
- void saveAgents((current) => {
67286
+ reportFailure("saveAgents", saveAgents((current) => {
66994
67287
  const roles = { ...current.roles ?? {} };
66995
67288
  const existing = roles[role];
66996
67289
  if (prompt === void 0 || prompt === defaultPromptFor(role)) {
@@ -67003,31 +67296,31 @@ ${direction}` : attachMentions(text, mentions);
67003
67296
  roles[role] = { ...existing ?? { kind: "profile" }, prompt };
67004
67297
  }
67005
67298
  return { ...current, roles };
67006
- });
67299
+ }));
67007
67300
  } else if (message3.type === "setAgentBudget") {
67008
67301
  const matters = message3.matters;
67009
- void saveAgents((current) => ({ ...current, budgetMatters: matters }));
67302
+ reportFailure("saveAgents", saveAgents((current) => ({ ...current, budgetMatters: matters })));
67010
67303
  } else if (message3.type === "setTeamGuidance") {
67011
67304
  const guidance = message3.guidance;
67012
- void saveAgents((current) => {
67305
+ reportFailure("saveAgents", saveAgents((current) => {
67013
67306
  if (guidance === void 0 || guidance.trim().length === 0 || guidance === DEFAULT_TEAM_GUIDANCE) {
67014
67307
  const rest = { ...current };
67015
67308
  delete rest.teamGuidance;
67016
67309
  return rest;
67017
67310
  }
67018
67311
  return { ...current, teamGuidance: guidance };
67019
- });
67312
+ }));
67020
67313
  } else if (message3.type === "saveCustomRole") {
67021
- void handleSaveCustomRole(message3);
67314
+ reportFailure("handleSaveCustomRole", handleSaveCustomRole(message3));
67022
67315
  } else if (message3.type === "deleteCustomRole") {
67023
- void handleDeleteCustomRole(message3.id);
67316
+ reportFailure("handleDeleteCustomRole", handleDeleteCustomRole(message3.id));
67024
67317
  } else if (message3.type === "setRoleThinking") {
67025
67318
  const role = message3.role;
67026
67319
  if (!isAgentRole(role, cachedAgentDefinitions)) {
67027
67320
  post({ type: "error", message: `There is no "${role}" role.` });
67028
67321
  return;
67029
67322
  }
67030
- void saveAgents((current) => {
67323
+ reportFailure("saveAgents", saveAgents((current) => {
67031
67324
  const roles = { ...current.roles ?? {} };
67032
67325
  const existing = roles[role] ?? { kind: "profile" };
67033
67326
  if (message3.level === void 0) {
@@ -67038,43 +67331,43 @@ ${direction}` : attachMentions(text, mentions);
67038
67331
  roles[role] = { ...existing, thinking: message3.level };
67039
67332
  }
67040
67333
  return { ...current, roles };
67041
- });
67334
+ }));
67042
67335
  } else if (message3.type === "setRoleEnabled") {
67043
67336
  const role = message3.role;
67044
67337
  if (!isAgentRole(role, cachedAgentDefinitions)) {
67045
67338
  post({ type: "error", message: `There is no "${role}" role.` });
67046
67339
  return;
67047
67340
  }
67048
- void saveAgents((current) => {
67341
+ reportFailure("saveAgents", saveAgents((current) => {
67049
67342
  const roles = { ...current.roles ?? {} };
67050
67343
  roles[role] = {
67051
67344
  ...roles[role] ?? { kind: "profile" },
67052
67345
  enabled: message3.enabled
67053
67346
  };
67054
67347
  return { ...current, roles };
67055
- });
67348
+ }));
67056
67349
  } else if (message3.type === "setRoleWrite") {
67057
67350
  const role = message3.role;
67058
67351
  if (!isAgentRole(role, cachedAgentDefinitions)) {
67059
67352
  post({ type: "error", message: `There is no "${role}" role.` });
67060
67353
  return;
67061
67354
  }
67062
- void saveAgents((current) => {
67355
+ reportFailure("saveAgents", saveAgents((current) => {
67063
67356
  const roles = { ...current.roles ?? {} };
67064
67357
  roles[role] = { ...roles[role] ?? { kind: "profile" }, write: message3.canWrite };
67065
67358
  return { ...current, roles };
67066
- });
67359
+ }));
67067
67360
  } else if (message3.type === "setRoleTools") {
67068
67361
  const role = message3.role;
67069
67362
  if (!isAgentRole(role, cachedAgentDefinitions)) {
67070
67363
  post({ type: "error", message: `There is no "${role}" role.` });
67071
67364
  return;
67072
67365
  }
67073
- void saveAgents((current) => {
67366
+ reportFailure("saveAgents", saveAgents((current) => {
67074
67367
  const roles = { ...current.roles ?? {} };
67075
67368
  roles[role] = { ...roles[role] ?? { kind: "profile" }, tools: message3.usesTools };
67076
67369
  return { ...current, roles };
67077
- });
67370
+ }));
67078
67371
  } else if (message3.type === "setAgentColor") {
67079
67372
  const role = message3.role;
67080
67373
  const color = message3.color;
@@ -67082,35 +67375,35 @@ ${direction}` : attachMentions(text, mentions);
67082
67375
  post({ type: "error", message: `There is no "${role}" role.` });
67083
67376
  return;
67084
67377
  }
67085
- void saveAgents((current) => ({
67378
+ reportFailure("saveAgents", saveAgents((current) => ({
67086
67379
  ...current,
67087
67380
  colors: { ...current.colors ?? {}, [role]: color }
67088
- }));
67381
+ })));
67089
67382
  } else if (message3.type === "setExpert") {
67090
- void handleSetExpert(message3.enabled, message3.path, message3.model, {
67383
+ reportFailure("handleSetExpert", handleSetExpert(message3.enabled, message3.path, message3.model, {
67091
67384
  ...message3.maxSpendUsd !== void 0 ? { maxSpendUsd: message3.maxSpendUsd } : {},
67092
67385
  ...message3.maxConsultations !== void 0 ? { maxConsultations: message3.maxConsultations } : {},
67093
67386
  ...message3.profileId !== void 0 ? { profileId: message3.profileId } : {}
67094
- });
67387
+ }));
67095
67388
  } else if (message3.type === "requestProfiles") {
67096
- void postProfiles();
67097
- void postCapabilities();
67389
+ reportFailure("postProfiles", postProfiles());
67390
+ reportFailure("postCapabilities", postCapabilities());
67098
67391
  } else if (message3.type === "saveProfile") {
67099
- void handleSaveProfile(message3.profile);
67392
+ reportFailure("handleSaveProfile", handleSaveProfile(message3.profile));
67100
67393
  } else if (message3.type === "requestModels") {
67101
- void handleRequestModels(message3.profile);
67394
+ reportFailure("handleRequestModels", handleRequestModels(message3.profile));
67102
67395
  } else if (message3.type === "testConnection") {
67103
- void handleTestConnection(message3.profile);
67396
+ reportFailure("handleTestConnection", handleTestConnection(message3.profile));
67104
67397
  } else if (message3.type === "duplicateProfile") {
67105
- void handleDuplicateProfile(message3.id);
67398
+ reportFailure("handleDuplicateProfile", handleDuplicateProfile(message3.id));
67106
67399
  } else if (message3.type === "deleteProfile") {
67107
- void handleDeleteProfile(message3.id);
67400
+ reportFailure("handleDeleteProfile", handleDeleteProfile(message3.id));
67108
67401
  } else if (message3.type === "setActiveProfile") {
67109
- void handleSetActiveProfile(message3.id, message3.forProject);
67402
+ reportFailure("handleSetActiveProfile", handleSetActiveProfile(message3.id, message3.forProject));
67110
67403
  } else if (message3.type === "exportConfig") {
67111
- void handleExportConfig();
67404
+ reportFailure("handleExportConfig", handleExportConfig());
67112
67405
  } else if (message3.type === "importConfig") {
67113
- void handleImportConfig();
67406
+ reportFailure("handleImportConfig", handleImportConfig());
67114
67407
  }
67115
67408
  });
67116
67409
  void (async () => {
@@ -67625,6 +67918,8 @@ ${contents}
67625
67918
  }
67626
67919
  await postTasks();
67627
67920
  await postSettings();
67921
+ await postProfiles();
67922
+ await postS3();
67628
67923
  await postSchedules();
67629
67924
  } catch (error51) {
67630
67925
  logger.warn(`Could not resync the view: ${error51 instanceof Error ? error51.message : String(error51)}`);
@@ -69538,6 +69833,558 @@ That is a fault in the tool itself, or the source is unreachable from here. Fix
69538
69833
  };
69539
69834
  }
69540
69835
 
69836
+ // ../../packages/core/dist/s3/sigv4.js
69837
+ import { createHash as createHash4, createHmac } from "node:crypto";
69838
+ var EMPTY_PAYLOAD_SHA256 = createHash4("sha256").update("").digest("hex");
69839
+ function encodeSegment(segment) {
69840
+ return encodeURIComponent(segment).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
69841
+ }
69842
+ function canonicalPath(pathname) {
69843
+ if (pathname === "" || pathname === "/")
69844
+ return "/";
69845
+ return pathname.split("/").map((segment) => {
69846
+ let raw = segment;
69847
+ try {
69848
+ raw = decodeURIComponent(segment);
69849
+ } catch {
69850
+ }
69851
+ return encodeSegment(raw);
69852
+ }).join("/");
69853
+ }
69854
+ function canonicalQuery(search) {
69855
+ const parameters = [...new URLSearchParams(search).entries()].map(([name, value]) => [encodeSegment(name), encodeSegment(value)]).sort((a, b) => a[0] === b[0] ? a[1].localeCompare(b[1]) : a[0].localeCompare(b[0]));
69856
+ return parameters.map(([name, value]) => `${name}=${value}`).join("&");
69857
+ }
69858
+ function amzDate(now) {
69859
+ return `${now.toISOString().replace(/[-:]/g, "").slice(0, 15)}Z`;
69860
+ }
69861
+ function signingKey(secretAccessKey, date5, region, service) {
69862
+ const dateKey = createHmac("sha256", `AWS4${secretAccessKey}`).update(date5).digest();
69863
+ const regionKey = createHmac("sha256", dateKey).update(region).digest();
69864
+ const serviceKey = createHmac("sha256", regionKey).update(service).digest();
69865
+ return createHmac("sha256", serviceKey).update("aws4_request").digest();
69866
+ }
69867
+ function signRequest(input) {
69868
+ const service = input.service ?? "s3";
69869
+ const now = input.now ?? /* @__PURE__ */ new Date();
69870
+ const timestamp = amzDate(now);
69871
+ const date5 = timestamp.slice(0, 8);
69872
+ const url2 = new URL(input.url);
69873
+ const body = input.body ?? Buffer.alloc(0);
69874
+ const payloadHash = createHash4("sha256").update(body).digest("hex");
69875
+ const headers = {
69876
+ ...input.headers,
69877
+ host: url2.host,
69878
+ "x-amz-content-sha256": payloadHash,
69879
+ "x-amz-date": timestamp,
69880
+ ...input.sessionToken !== void 0 ? { "x-amz-security-token": input.sessionToken } : {}
69881
+ };
69882
+ const canonicalHeaderEntries = Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value.trim().replace(/\s+/g, " ")]).sort((a, b) => a[0].localeCompare(b[0]));
69883
+ const signedHeaders = canonicalHeaderEntries.map(([name]) => name).join(";");
69884
+ const canonicalRequest = [
69885
+ input.method.toUpperCase(),
69886
+ canonicalPath(url2.pathname),
69887
+ canonicalQuery(url2.search),
69888
+ `${canonicalHeaderEntries.map(([name, value]) => `${name}:${value}`).join("\n")}
69889
+ `,
69890
+ signedHeaders,
69891
+ payloadHash
69892
+ ].join("\n");
69893
+ const scope = `${date5}/${input.region}/${service}/aws4_request`;
69894
+ const stringToSign = [
69895
+ "AWS4-HMAC-SHA256",
69896
+ timestamp,
69897
+ scope,
69898
+ createHash4("sha256").update(canonicalRequest).digest("hex")
69899
+ ].join("\n");
69900
+ const signature = createHmac("sha256", signingKey(input.secretAccessKey, date5, input.region, service)).update(stringToSign).digest("hex");
69901
+ return {
69902
+ headers: {
69903
+ ...headers,
69904
+ Authorization: `AWS4-HMAC-SHA256 Credential=${input.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
69905
+ },
69906
+ canonicalRequest,
69907
+ stringToSign,
69908
+ signature
69909
+ };
69910
+ }
69911
+
69912
+ // ../../packages/core/dist/s3/client.js
69913
+ var S3Client = class {
69914
+ http;
69915
+ connection;
69916
+ tls;
69917
+ constructor(http, connection, tls2) {
69918
+ this.http = http;
69919
+ this.connection = connection;
69920
+ this.tls = tls2;
69921
+ }
69922
+ url(call) {
69923
+ const { bucket, region, endpoint, pathStyle } = this.connection;
69924
+ const origin = new URL(endpoint ?? `https://s3.${region}.amazonaws.com`);
69925
+ const key = call.key ?? "";
69926
+ const host = pathStyle === true ? origin.host : `${bucket}.${origin.host}`;
69927
+ const prefix = pathStyle === true ? `/${bucket}` : "";
69928
+ const path32 = key === "" ? "" : `/${key.split("/").map((part) => encodeURIComponent(part)).join("/")}`;
69929
+ const url2 = new URL(`${origin.protocol}//${host}${prefix}${path32}`);
69930
+ for (const [name, value] of Object.entries(call.query ?? {}))
69931
+ url2.searchParams.set(name, value);
69932
+ return url2.toString();
69933
+ }
69934
+ async send(call) {
69935
+ const url2 = this.url(call);
69936
+ const signed = signRequest({
69937
+ method: call.method,
69938
+ url: url2,
69939
+ headers: call.headers ?? {},
69940
+ ...call.bodyBytes !== void 0 ? { body: Buffer.from(call.bodyBytes) } : {},
69941
+ region: this.connection.region,
69942
+ accessKeyId: this.connection.accessKeyId,
69943
+ secretAccessKey: this.connection.secretAccessKey,
69944
+ ...this.connection.sessionToken !== void 0 ? { sessionToken: this.connection.sessionToken } : {}
69945
+ });
69946
+ const response = await this.http.request(url2, {
69947
+ method: call.method,
69948
+ headers: signed.headers,
69949
+ ...call.bodyBytes !== void 0 ? { bodyBytes: call.bodyBytes } : {},
69950
+ ...call.signal !== void 0 ? { signal: call.signal } : {},
69951
+ ...this.tls !== void 0 ? { tls: this.tls } : {}
69952
+ });
69953
+ const bytes = await readAll(response);
69954
+ return { status: response.status, text: bytes.toString("utf8"), bytes };
69955
+ }
69956
+ /**
69957
+ * Objects under a prefix.
69958
+ *
69959
+ * Follows the continuation token rather than stopping at the first page: a folder of 1,200 files
69960
+ * silently reported as 1,000 is the kind of wrong answer nobody thinks to check.
69961
+ */
69962
+ async list(prefix, limit = 1e3, signal) {
69963
+ const found = [];
69964
+ let token;
69965
+ while (found.length < limit) {
69966
+ const query = {
69967
+ "list-type": "2",
69968
+ "max-keys": String(Math.min(1e3, limit - found.length))
69969
+ };
69970
+ if (prefix !== "")
69971
+ query["prefix"] = prefix;
69972
+ if (token !== void 0)
69973
+ query["continuation-token"] = token;
69974
+ const result = await this.send({
69975
+ method: "GET",
69976
+ query,
69977
+ ...signal !== void 0 ? { signal } : {}
69978
+ });
69979
+ if (result.status !== 200)
69980
+ throw new Error(describeFailure(result.status, result.text));
69981
+ found.push(...parseListing(result.text));
69982
+ token = matchTag(result.text, "NextContinuationToken");
69983
+ if (token === void 0)
69984
+ break;
69985
+ }
69986
+ return found.slice(0, limit);
69987
+ }
69988
+ async get(key, signal) {
69989
+ const result = await this.send({
69990
+ method: "GET",
69991
+ key,
69992
+ ...signal !== void 0 ? { signal } : {}
69993
+ });
69994
+ if (result.status !== 200)
69995
+ throw new Error(describeFailure(result.status, result.text, key));
69996
+ return result.bytes;
69997
+ }
69998
+ async put(key, bytes, contentType2, signal) {
69999
+ const result = await this.send({
70000
+ method: "PUT",
70001
+ key,
70002
+ bodyBytes: bytes,
70003
+ ...contentType2 !== void 0 ? { headers: { "content-type": contentType2 } } : {},
70004
+ ...signal !== void 0 ? { signal } : {}
70005
+ });
70006
+ if (result.status !== 200 && result.status !== 204) {
70007
+ throw new Error(describeFailure(result.status, result.text, key));
70008
+ }
70009
+ }
70010
+ };
70011
+ async function readAll(response) {
70012
+ if (response.body === null)
70013
+ return Buffer.from(await response.text(), "utf8");
70014
+ const reader = response.body.getReader();
70015
+ const chunks = [];
70016
+ for (; ; ) {
70017
+ const { done, value } = await reader.read();
70018
+ if (done)
70019
+ break;
70020
+ if (value !== void 0)
70021
+ chunks.push(value);
70022
+ }
70023
+ return Buffer.concat(chunks);
70024
+ }
70025
+ function describeFailure(status, body, key) {
70026
+ const code = matchTag(body, "Code");
70027
+ const message3 = matchTag(body, "Message");
70028
+ const what = key === void 0 ? "" : ` for "${key}"`;
70029
+ if (code === void 0)
70030
+ return `S3 request failed${what} with status ${String(status)}.`;
70031
+ return `S3 ${code}${what}: ${message3 ?? `status ${String(status)}`}`;
70032
+ }
70033
+ function matchTag(xml, tag) {
70034
+ const match = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(xml);
70035
+ return match?.[1];
70036
+ }
70037
+ function parseListing(xml) {
70038
+ const objects = [];
70039
+ for (const block of xml.split("<Contents>").slice(1)) {
70040
+ const key = matchTag(block, "Key");
70041
+ if (key === void 0)
70042
+ continue;
70043
+ objects.push({
70044
+ key: decodeEntities3(key),
70045
+ size: Number(matchTag(block, "Size") ?? "0"),
70046
+ lastModified: matchTag(block, "LastModified") ?? ""
70047
+ });
70048
+ }
70049
+ return objects;
70050
+ }
70051
+ function decodeEntities3(value) {
70052
+ return value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&#39;", String.fromCharCode(39)).replaceAll("&amp;", "&");
70053
+ }
70054
+
70055
+ // ../../packages/core/dist/s3/keys.js
70056
+ function normalisePrefix(prefix) {
70057
+ const trimmed = (prefix ?? "").trim().replace(/^\/+/, "");
70058
+ if (trimmed === "")
70059
+ return "";
70060
+ return trimmed.endsWith("/") ? trimmed : `${trimmed}/`;
70061
+ }
70062
+ function confineKey(requested, prefix) {
70063
+ const clean = requested.trim().replace(/^\/+/, "");
70064
+ if (clean === "")
70065
+ return { ok: false, message: "No key was given." };
70066
+ if (clean.split("/").includes("..")) {
70067
+ return {
70068
+ ok: false,
70069
+ message: `"${requested}" contains "..", which S3 does not interpret as a parent folder \u2014 it would be part of the key. Give the key as it appears in the bucket.`
70070
+ };
70071
+ }
70072
+ const base = normalisePrefix(prefix);
70073
+ if (base === "")
70074
+ return { ok: true, key: clean };
70075
+ const key = clean.startsWith(base) ? clean : `${base}${clean}`;
70076
+ if (!key.startsWith(base)) {
70077
+ return { ok: false, message: `"${requested}" is outside "${base}", which this connection is limited to.` };
70078
+ }
70079
+ return { ok: true, key };
70080
+ }
70081
+ function displayKey(key, prefix) {
70082
+ const base = normalisePrefix(prefix);
70083
+ return base !== "" && key.startsWith(base) ? key.slice(base.length) : key;
70084
+ }
70085
+
70086
+ // ../../packages/core/dist/s3/resolve.js
70087
+ async function resolveS3(options) {
70088
+ const targets = [];
70089
+ const problems = [];
70090
+ for (const connection of options.config?.connections ?? []) {
70091
+ const secret = await options.secrets.get(connection.secretAccessKeyRef);
70092
+ if (secret === void 0 || secret.trim().length === 0) {
70093
+ problems.push({
70094
+ label: connection.label,
70095
+ problem: "Its secret access key is not in storage. Open Settings \u2192 Skills and enter it again \u2014 a key is never written to the config file, so one can go missing while the connection stays."
70096
+ });
70097
+ continue;
70098
+ }
70099
+ const sessionToken = connection.sessionTokenRef === void 0 ? void 0 : await options.secrets.get(connection.sessionTokenRef);
70100
+ const client = new S3Client(options.http, {
70101
+ bucket: connection.bucket,
70102
+ region: connection.region,
70103
+ accessKeyId: connection.accessKeyId,
70104
+ secretAccessKey: secret,
70105
+ ...sessionToken !== void 0 ? { sessionToken } : {},
70106
+ ...connection.endpoint !== void 0 ? { endpoint: connection.endpoint } : {},
70107
+ ...connection.pathStyle !== void 0 ? { pathStyle: connection.pathStyle } : {}
70108
+ }, options.tls);
70109
+ targets.push({
70110
+ id: connection.id,
70111
+ label: connection.label,
70112
+ bucket: connection.bucket,
70113
+ client,
70114
+ ...connection.prefix !== void 0 ? { prefix: connection.prefix } : {},
70115
+ ...connection.readOnly !== void 0 ? { readOnly: connection.readOnly } : {}
70116
+ });
70117
+ }
70118
+ return { targets, problems };
70119
+ }
70120
+ function targetById(resolved, id) {
70121
+ if (id === void 0)
70122
+ return void 0;
70123
+ return resolved.targets.find((target) => target.id === id);
70124
+ }
70125
+
70126
+ // ../../packages/core/dist/s3/sync.js
70127
+ var DEFAULT_LIMIT2 = 500;
70128
+ async function syncFromS3(options) {
70129
+ const base = normalisePrefix(options.target.prefix);
70130
+ const where = normalisePrefix(`${base}${options.prefix ?? ""}`);
70131
+ const result = { written: [], unchanged: 0, failed: [] };
70132
+ const objects = await options.target.client.list(where, options.limit ?? DEFAULT_LIMIT2, options.signal);
70133
+ for (const object3 of objects) {
70134
+ const relative = object3.key.slice(where.length);
70135
+ if (relative === "" || relative.endsWith("/"))
70136
+ continue;
70137
+ if (!options.extensions.some((extension) => relative.toLowerCase().endsWith(extension)))
70138
+ continue;
70139
+ if (relative.split("/").includes("..")) {
70140
+ result.failed.push({ key: object3.key, problem: "The key would write outside the folder." });
70141
+ continue;
70142
+ }
70143
+ try {
70144
+ const bytes = await options.target.client.get(object3.key, options.signal);
70145
+ const localPath = join(options.localDir, relative);
70146
+ let existing;
70147
+ try {
70148
+ existing = await options.fs.readBytes(localPath);
70149
+ } catch {
70150
+ }
70151
+ if (existing !== void 0 && existing.equals(bytes)) {
70152
+ result.unchanged += 1;
70153
+ continue;
70154
+ }
70155
+ await options.fs.mkdir(dirname(localPath));
70156
+ await options.fs.writeBytes(localPath, bytes);
70157
+ result.written.push(relative);
70158
+ } catch (error51) {
70159
+ result.failed.push({
70160
+ key: object3.key,
70161
+ problem: error51 instanceof Error ? error51.message : String(error51)
70162
+ });
70163
+ }
70164
+ }
70165
+ return result;
70166
+ }
70167
+ async function uploadToS3(options) {
70168
+ if (options.target.readOnly === true) {
70169
+ throw new Error(`The connection "${options.target.label}" is read-only.`);
70170
+ }
70171
+ const base = normalisePrefix(options.target.prefix);
70172
+ const where = normalisePrefix(`${base}${options.prefix ?? ""}`);
70173
+ await options.target.client.put(`${where}${options.relative}`, options.contents, void 0, options.signal);
70174
+ }
70175
+ function join(dir, relative) {
70176
+ const left = dir.replace(/[\\/]+$/, "");
70177
+ return `${left}/${relative}`;
70178
+ }
70179
+ function dirname(filePath) {
70180
+ const cut = filePath.lastIndexOf("/");
70181
+ return cut === -1 ? filePath : filePath.slice(0, cut);
70182
+ }
70183
+
70184
+ // ../../packages/core/dist/s3/tools.js
70185
+ function pick2(targets, wanted) {
70186
+ if (wanted === void 0) {
70187
+ if (targets.length === 1)
70188
+ return targets[0];
70189
+ return `Several buckets are configured. Name one with "connection": ${targets.map((target) => target.label).join(", ")}.`;
70190
+ }
70191
+ const found = targets.find((target) => target.label.toLowerCase() === wanted.toLowerCase() || target.id === wanted);
70192
+ if (found !== void 0)
70193
+ return found;
70194
+ return `There is no S3 connection called "${wanted}". Configured: ${targets.map((target) => target.label).join(", ")}.`;
70195
+ }
70196
+ function looksBinary(bytes) {
70197
+ return bytes.subarray(0, 8e3).includes(0);
70198
+ }
70199
+ function describeSize(bytes) {
70200
+ if (bytes < 1024)
70201
+ return `${String(bytes)} B`;
70202
+ if (bytes < 1024 * 1024)
70203
+ return `${(bytes / 1024).toFixed(1)} KB`;
70204
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
70205
+ }
70206
+ var failed = (error51) => ({
70207
+ content: error51 instanceof Error ? error51.message : String(error51),
70208
+ isError: true
70209
+ });
70210
+ function whichBuckets(targets) {
70211
+ return targets.length === 1 ? `the S3 bucket "${targets[0]?.label ?? ""}"` : `an S3 bucket (${targets.map((target) => target.label).join(", ")})`;
70212
+ }
70213
+ var connectionField = external_exports.string().optional().describe("Which configured bucket to use. May be omitted when only one is set up.");
70214
+ var listSchema = external_exports.object({
70215
+ connection: connectionField,
70216
+ prefix: external_exports.string().optional().describe("Folder to list, relative to the connection\u2019s own prefix. Omit for everything."),
70217
+ limit: external_exports.number().int().min(1).max(1e3).optional().describe("How many to return. Default 100.")
70218
+ });
70219
+ function createS3ListTool(targets) {
70220
+ return {
70221
+ name: "s3_list_files",
70222
+ group: "read",
70223
+ description: `List files in ${whichBuckets(targets)}. Use it to find what is there before reading or downloading. Returns keys, sizes and dates, never contents.`,
70224
+ parametersSchema: listSchema,
70225
+ async execute(params, context) {
70226
+ const target = pick2(targets, params.connection);
70227
+ if (typeof target === "string")
70228
+ return { content: target, isError: true };
70229
+ const base = normalisePrefix(target.prefix);
70230
+ const where = params.prefix === void 0 ? base : normalisePrefix(`${base}${params.prefix}`);
70231
+ try {
70232
+ const found = await target.client.list(where, params.limit ?? 100, context.signal);
70233
+ if (found.length === 0)
70234
+ return { content: `No files under "${where === "" ? "/" : where}".` };
70235
+ const lines = found.map((object3) => `${displayKey(object3.key, target.prefix)} ${describeSize(object3.size)} ${object3.lastModified}`);
70236
+ return { content: [`${String(found.length)} file(s) in ${target.bucket}:`, ...lines].join("\n") };
70237
+ } catch (error51) {
70238
+ return failed(error51);
70239
+ }
70240
+ }
70241
+ };
70242
+ }
70243
+ var readSchema = external_exports.object({
70244
+ connection: connectionField,
70245
+ key: external_exports.string().min(1).describe("The file to read, as s3_list_files reports it.")
70246
+ });
70247
+ function createS3ReadTool(targets) {
70248
+ return {
70249
+ name: "s3_read_file",
70250
+ group: "read",
70251
+ description: `Read a file from ${whichBuckets(targets)} as text. For anything that is not text, use s3_download_file and open it locally.`,
70252
+ parametersSchema: readSchema,
70253
+ async execute(params, context) {
70254
+ const target = pick2(targets, params.connection);
70255
+ if (typeof target === "string")
70256
+ return { content: target, isError: true };
70257
+ const resolved = confineKey(params.key, target.prefix);
70258
+ if (!resolved.ok)
70259
+ return { content: resolved.message, isError: true };
70260
+ try {
70261
+ const bytes = await target.client.get(resolved.key, context.signal);
70262
+ if (looksBinary(bytes)) {
70263
+ return {
70264
+ content: `"${params.key}" is ${describeSize(bytes.length)} of binary data, not text. Use s3_download_file to copy it here and open it with something that understands it.`
70265
+ };
70266
+ }
70267
+ return { content: bytes.toString("utf8") };
70268
+ } catch (error51) {
70269
+ return failed(error51);
70270
+ }
70271
+ }
70272
+ };
70273
+ }
70274
+ var downloadSchema = external_exports.object({
70275
+ connection: connectionField,
70276
+ key: external_exports.string().min(1).describe("The file in the bucket."),
70277
+ to: external_exports.string().min(1).describe("Where to write it, relative to the workspace root.")
70278
+ });
70279
+ function createS3DownloadTool(targets) {
70280
+ return {
70281
+ name: "s3_download_file",
70282
+ group: "edit",
70283
+ description: `Copy a file out of ${whichBuckets(targets)} onto this machine.`,
70284
+ parametersSchema: downloadSchema,
70285
+ preview: async (params) => {
70286
+ const target = pick2(targets, params.connection);
70287
+ const where = typeof target === "string" ? "(unknown bucket)" : `s3://${target.bucket}/${params.key}`;
70288
+ return { kind: "text", text: `Copy ${where}
70289
+ to ${params.to}` };
70290
+ },
70291
+ async execute(params, context) {
70292
+ const target = pick2(targets, params.connection);
70293
+ if (typeof target === "string")
70294
+ return { content: target, isError: true };
70295
+ const resolved = confineKey(params.key, target.prefix);
70296
+ if (!resolved.ok)
70297
+ return { content: resolved.message, isError: true };
70298
+ const to = await resolveToolPath(context, params.to);
70299
+ if (!to.ok)
70300
+ return { content: to.message, isError: true };
70301
+ try {
70302
+ const bytes = await target.client.get(resolved.key, context.signal);
70303
+ await context.fs.writeBytes(to.realPath, bytes);
70304
+ return {
70305
+ content: `Wrote ${describeSize(bytes.length)} to ${params.to} from s3://${target.bucket}/${resolved.key}.`,
70306
+ path: to.realPath
70307
+ };
70308
+ } catch (error51) {
70309
+ return failed(error51);
70310
+ }
70311
+ }
70312
+ };
70313
+ }
70314
+ var uploadSchema = external_exports.object({
70315
+ connection: connectionField,
70316
+ from: external_exports.string().min(1).describe("The local file to upload, relative to the workspace root."),
70317
+ key: external_exports.string().min(1).describe("Where to put it in the bucket.")
70318
+ });
70319
+ function createS3UploadTool(targets) {
70320
+ return {
70321
+ name: "s3_upload_file",
70322
+ group: "edit",
70323
+ description: `Copy a file from this machine into ${whichBuckets(targets)}.`,
70324
+ parametersSchema: uploadSchema,
70325
+ /*
70326
+ * The preview names the destination in full, bucket included.
70327
+ *
70328
+ * Invariant 8: this is the one thing the person approving needs and cannot otherwise check.
70329
+ * A file sent to the wrong bucket is not recoverable by undoing anything here — it is on
70330
+ * somebody else's storage, possibly visible to people the user never intended.
70331
+ */
70332
+ preview: async (params) => {
70333
+ const target = pick2(targets, params.connection);
70334
+ const where = typeof target === "string" ? "(unknown bucket)" : `s3://${target.bucket}/${normalisePrefix(target.prefix)}${params.key}`;
70335
+ return { kind: "text", text: `Upload ${params.from}
70336
+ to ${where}` };
70337
+ },
70338
+ async execute(params, context) {
70339
+ const target = pick2(targets, params.connection);
70340
+ if (typeof target === "string")
70341
+ return { content: target, isError: true };
70342
+ if (target.readOnly === true) {
70343
+ return { content: `The connection "${target.label}" is read-only.`, isError: true };
70344
+ }
70345
+ const resolved = confineKey(params.key, target.prefix);
70346
+ if (!resolved.ok)
70347
+ return { content: resolved.message, isError: true };
70348
+ const from = await resolveToolPath(context, params.from);
70349
+ if (!from.ok)
70350
+ return { content: from.message, isError: true };
70351
+ try {
70352
+ const bytes = await context.fs.readBytes(from.realPath);
70353
+ await target.client.put(resolved.key, bytes, void 0, context.signal);
70354
+ return { content: `Uploaded ${describeSize(bytes.length)} to s3://${target.bucket}/${resolved.key}.` };
70355
+ } catch (error51) {
70356
+ return failed(error51);
70357
+ }
70358
+ }
70359
+ };
70360
+ }
70361
+ function createS3Tools(targets) {
70362
+ if (targets.length === 0)
70363
+ return [];
70364
+ return [
70365
+ createS3ListTool(targets),
70366
+ createS3ReadTool(targets),
70367
+ createS3DownloadTool(targets),
70368
+ createS3UploadTool(targets)
70369
+ ];
70370
+ }
70371
+
70372
+ // ../../packages/core/dist/s3/localFolder.js
70373
+ import { createHash as createHash5 } from "node:crypto";
70374
+ function mirrorFolder(options) {
70375
+ const connection = safeSegment(options.connectionId);
70376
+ const digest = createHash5("sha256").update((options.prefix ?? "").trim().toLowerCase()).digest("hex").slice(0, 8);
70377
+ return join2(options.storageDir, "s3", connection, `${options.kind}-${digest}`);
70378
+ }
70379
+ function safeSegment(id) {
70380
+ const cleaned = id.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/-+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 40);
70381
+ const suffix = createHash5("sha256").update(id).digest("hex").slice(0, 6);
70382
+ return `${cleaned === "" ? "connection" : cleaned}-${suffix}`;
70383
+ }
70384
+ function join2(...parts) {
70385
+ return parts.map((part, index) => index === 0 ? part.replace(/[\\/]+$/, "") : part).join("/");
70386
+ }
70387
+
69541
70388
  // src/reachableHosts.ts
69542
70389
  import os3 from "node:os";
69543
70390
  function reachableHosts(bindAddress, port, extra = []) {
@@ -69581,8 +70428,9 @@ function reachableOrigins(hosts, extra = []) {
69581
70428
  // src/identity.ts
69582
70429
  import crypto5 from "node:crypto";
69583
70430
  var SingleUserIdentity = class _SingleUserIdentity {
69584
- describe = "single user (local)";
70431
+ describe;
69585
70432
  static PRINCIPAL = { id: "local", displayName: "Local user" };
70433
+ principal;
69586
70434
  /** Long-lived, minted per server run, only ever sent in an `Authorization` header. */
69587
70435
  sessionToken = crypto5.randomBytes(32).toString("base64url");
69588
70436
  /**
@@ -69597,9 +70445,19 @@ var SingleUserIdentity = class _SingleUserIdentity {
69597
70445
  handoffToken = crypto5.randomBytes(32).toString("base64url");
69598
70446
  handoffExpiresAt;
69599
70447
  handoffSeconds;
69600
- constructor(handoffSeconds = 10) {
70448
+ /**
70449
+ * @param principal Who this server's storage is filed under. Defaults to the local user.
70450
+ *
70451
+ * Supplied when the platform named the account — `JUPYTERHUB_USER` and friends, see
70452
+ * `hostedUser.ts`. **It changes the name, not the gate.** The bearer token below still decides
70453
+ * who gets in, which is §14's rule that identity resolution must never become a way past the
70454
+ * door: knowing that a server was spawned for Ana says nothing about who is making this request.
70455
+ */
70456
+ constructor(handoffSeconds = 10, principal) {
69601
70457
  this.handoffSeconds = handoffSeconds;
69602
70458
  this.handoffExpiresAt = Date.now() + handoffSeconds * 1e3;
70459
+ this.principal = principal ?? _SingleUserIdentity.PRINCIPAL;
70460
+ this.describe = principal === void 0 ? "single user (local)" : `single user \u2014 ${principal.id}`;
69603
70461
  }
69604
70462
  get launchToken() {
69605
70463
  if (this.handoffToken === void 0) throw new Error("handoff token already consumed");
@@ -69646,7 +70504,7 @@ var SingleUserIdentity = class _SingleUserIdentity {
69646
70504
  async authenticate(request) {
69647
70505
  const header = request.headers.authorization;
69648
70506
  if (header === void 0 || !header.startsWith("Bearer ")) return void 0;
69649
- return timingSafeEquals(header.slice("Bearer ".length), this.sessionToken) ? _SingleUserIdentity.PRINCIPAL : void 0;
70507
+ return timingSafeEquals(header.slice("Bearer ".length), this.sessionToken) ? this.principal : void 0;
69650
70508
  }
69651
70509
  };
69652
70510
  function timingSafeEquals(a, b) {
@@ -70234,6 +71092,21 @@ function readVariablesFile(filePath) {
70234
71092
  }
70235
71093
  }
70236
71094
 
71095
+ // src/hostedUser.ts
71096
+ var SOURCES = [
71097
+ /** JupyterHub's own, set in every single-user server it spawns. */
71098
+ "JUPYTERHUB_USER",
71099
+ /** Set by some deployments that front an app without the hub's spawner. */
71100
+ "JUPYTER_USER"
71101
+ ];
71102
+ function hostedUser(env2 = process.env) {
71103
+ for (const source of SOURCES) {
71104
+ const value = env2[source]?.trim();
71105
+ if (value !== void 0 && value.length > 0) return { id: value, source };
71106
+ }
71107
+ return void 0;
71108
+ }
71109
+
70237
71110
  // src/session.ts
70238
71111
  import { watch as fsWatch } from "node:fs";
70239
71112
  import fs23 from "node:fs/promises";
@@ -70766,11 +71639,26 @@ var STREAM_PADDING = `: ${(() => {
70766
71639
  })()}
70767
71640
 
70768
71641
  `;
71642
+ function principalFromPlatform() {
71643
+ const found = hostedUser();
71644
+ return found === void 0 ? void 0 : { id: found.id, displayName: found.id };
71645
+ }
70769
71646
  async function startServer(options) {
70770
71647
  const log = options.logSink ?? ((line) => process.stderr.write(`${line}
70771
71648
  `));
70772
71649
  setFrameAncestors(options.allowFrameAncestors ?? []);
70773
- const identity = options.identity ?? (options.noToken === true ? new OpenIdentity() : new SingleUserIdentity(options.handoffSeconds));
71650
+ const identity = options.identity ?? (options.noToken === true ? new OpenIdentity() : (
71651
+ /*
71652
+ * Named by the platform when it says so, and still gated by the token either way.
71653
+ *
71654
+ * JupyterHub spawns a server per person and sets `JUPYTERHUB_USER` in it, so settings,
71655
+ * secrets and history are filed under that person rather than under "local" — which is
71656
+ * what somebody had otherwise to write a Python function to achieve. Read from this
71657
+ * process's environment, never from a request: see `hostedUser.ts` for why the URL
71658
+ * suffix carrying the same name is not the same fact.
71659
+ */
71660
+ new SingleUserIdentity(options.handoffSeconds, principalFromPlatform())
71661
+ ));
70774
71662
  const roles = options.roles ?? SINGLE_USER_POLICY;
70775
71663
  const sharedStore = options.sharedConfig;
70776
71664
  const sharedSecretStore = new FileSecretStore(path31.join(options.dataDir, "shared-secrets.json"));
@@ -70825,6 +71713,12 @@ async function startServer(options) {
70825
71713
  };
70826
71714
  const connection = {
70827
71715
  transport,
71716
+ /*
71717
+ * Replaced below, once the bridge that owns the state exists. A no-op rather than a missing
71718
+ * field so the object is a complete `Connection` from the moment it is built — a half-built
71719
+ * one handed to anything in between is how a route ends up calling something undefined.
71720
+ */
71721
+ resync: () => void 0,
70828
71722
  deliver: (message3) => {
70829
71723
  for (const listener of listeners) listener(message3);
70830
71724
  },
@@ -70932,6 +71826,9 @@ async function startServer(options) {
70932
71826
  originalDispose();
70933
71827
  session.dispose();
70934
71828
  };
71829
+ connection.resync = () => {
71830
+ session.resync();
71831
+ };
70935
71832
  return connection;
70936
71833
  }
70937
71834
  const server = createServer((request, response) => {
@@ -71024,6 +71921,7 @@ async function startServer(options) {
71024
71921
  if (viaAdminUrl) adminConnections.add(principal.id);
71025
71922
  else adminConnections.delete(principal.id);
71026
71923
  connection.attach(response);
71924
+ connection.resync();
71027
71925
  connection.transport.post({
71028
71926
  type: "hostRole",
71029
71927
  role: isAdminSession(principal) ? "admin" : "user",
@@ -71051,6 +71949,7 @@ async function startServer(options) {
71051
71949
  if (connection === void 0) {
71052
71950
  connection = await openConnection(principal);
71053
71951
  connections.set(principal.id, connection);
71952
+ connection.resync();
71054
71953
  }
71055
71954
  respondJson(response, 200, { messages: connection.drain() });
71056
71955
  return;