@chosengeneration/light-code 0.70.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/cli.js CHANGED
@@ -24631,6 +24631,8 @@ var FetchHttpClient = class {
24631
24631
  init.headers = options.headers;
24632
24632
  if (options.body !== void 0)
24633
24633
  init.body = options.body;
24634
+ if (options.bodyBytes !== void 0)
24635
+ init.body = options.bodyBytes;
24634
24636
  if (options.signal !== void 0)
24635
24637
  init.signal = options.signal;
24636
24638
  let target;
@@ -40320,6 +40322,55 @@ var mailIndexConfigSchema = external_exports.object({
40320
40322
  /** Characters of body kept per message, for showing a hit without reopening Outlook. */
40321
40323
  previewChars: external_exports.number().int().min(0).max(2e3)
40322
40324
  }).partial();
40325
+ var s3ConnectionSchema = external_exports.object({
40326
+ id: external_exports.string().min(1),
40327
+ label: external_exports.string().min(1),
40328
+ bucket: external_exports.string().min(1),
40329
+ region: external_exports.string().min(1),
40330
+ accessKeyId: external_exports.string().min(1),
40331
+ secretAccessKeyRef: external_exports.string().min(1),
40332
+ /** Only for temporary credentials. */
40333
+ sessionTokenRef: external_exports.string().optional(),
40334
+ /** Absent means the ordinary AWS endpoint for the region. */
40335
+ endpoint: external_exports.string().url().optional(),
40336
+ /** `host/bucket/key` instead of `bucket.host/key`, which internal deployments usually need. */
40337
+ pathStyle: external_exports.boolean().optional(),
40338
+ /**
40339
+ * Everything is confined to this prefix, when one is set.
40340
+ *
40341
+ * Not a convenience. It is the only thing bounding what the tools can reach in a bucket that may
40342
+ * hold far more than this project, and it is enforced on every key rather than trusted to the
40343
+ * model — `confine()`'s argument applied to a bucket instead of a disk.
40344
+ */
40345
+ prefix: external_exports.string().optional(),
40346
+ /** Refuses every write, so a bucket can be attached for reading with nothing to go wrong. */
40347
+ readOnly: external_exports.boolean().optional()
40348
+ });
40349
+ var s3MirrorSchema = external_exports.object({
40350
+ connectionId: external_exports.string().min(1),
40351
+ prefix: external_exports.string().optional(),
40352
+ /** Off by default: reading a bucket on every panel open is somebody's money and latency. */
40353
+ enabled: external_exports.boolean().optional()
40354
+ });
40355
+ var s3ConfigSchema = external_exports.object({
40356
+ connections: external_exports.array(s3ConnectionSchema).max(20).optional(),
40357
+ /**
40358
+ * Where skills are kept, when they live in a bucket rather than on this disk.
40359
+ *
40360
+ * Only the *files* move. They are still loaded, watched and indexed exactly as local ones are —
40361
+ * indexing stays as configured — so this names a sync, not a second kind of skill.
40362
+ */
40363
+ skills: s3MirrorSchema.optional(),
40364
+ /**
40365
+ * The same for Python tools, with one difference that is not a detail.
40366
+ *
40367
+ * A mirrored `.py` is **not** loaded on arrival. The hash-pinned registry (§13) refuses any tool
40368
+ * that was not approved with its source shown, so a bucket is how a tool *reaches* a machine,
40369
+ * and approval still happens on each one. Anybody with write access to the bucket would
40370
+ * otherwise be running code as this user on every machine that syncs.
40371
+ */
40372
+ tools: s3MirrorSchema.optional()
40373
+ });
40323
40374
  var configSchema = external_exports.object({
40324
40375
  profiles: external_exports.array(providerProfileSchema),
40325
40376
  /**
@@ -40341,6 +40392,8 @@ var configSchema = external_exports.object({
40341
40392
  * embedder would exfiltrate whatever gets indexed — sharper than the existing entries,
40342
40393
  * because the payload is source code.
40343
40394
  */
40395
+ /** User-scope only (invariant 5): it holds a bucket and a key that can write to it. */
40396
+ s3: s3ConfigSchema,
40344
40397
  vectorStores: external_exports.record(external_exports.string(), vectorStoreSchema),
40345
40398
  activeVectorStoreId: external_exports.string(),
40346
40399
  embedder: embedderConfigSchema,
@@ -40988,6 +41041,15 @@ var USER_SCOPE_ONLY_KEYS = [
40988
41041
  // Per-project settings live here, keyed by path. Same reasoning as `approvals` exactly: a repo
40989
41042
  // that could write its own entry would choose its own vector store and model for itself.
40990
41043
  "workspaces",
41044
+ /*
41045
+ * Holds a bucket, an endpoint and the reference to a key that can read and write it.
41046
+ *
41047
+ * The sharpest kind of entry on this list: a repository able to set it would point the upload
41048
+ * tool at a bucket of its choosing, and everything copied "into S3" would go to somebody else —
41049
+ * with the user watching a tool succeed. Same shape as `embedder`, with whatever the user
41050
+ * uploads as the payload.
41051
+ */
41052
+ "s3",
40991
41053
  // `expert.path` names an executable. A workspace able to set it would run a program of
40992
41054
  // its choosing as soon as the panel opened — the same threat as `python.uvPath`.
40993
41055
  // `expert.enabled` is here too, so a repo cannot switch on paid API calls by itself.
@@ -47023,6 +47085,14 @@ function merge2(single, many) {
47023
47085
  }
47024
47086
  return out;
47025
47087
  }
47088
+ function aliasFields(names) {
47089
+ const cleaned = merge2(void 0, names);
47090
+ const [primary, ...rest] = cleaned;
47091
+ return {
47092
+ primary,
47093
+ rest: rest.length > 0 ? rest : void 0
47094
+ };
47095
+ }
47026
47096
 
47027
47097
  // ../../packages/core/dist/tools/searchCodebase.js
47028
47098
  var paramsSchema6 = external_exports.object({
@@ -47198,16 +47268,44 @@ function toHit(match, self) {
47198
47268
  }
47199
47269
  async function searchTeamSkills(options, query, size = 5, signal) {
47200
47270
  const vector = await options.embedder.embed(query);
47201
- const matches = await options.searcher.searchByVector(options.collection, vector, {
47202
- size,
47203
- ...signal !== void 0 ? { signal } : {}
47204
- });
47205
- return matches.map((match) => toHit(match, options.owner));
47271
+ const tried = [];
47272
+ let firstError;
47273
+ for (const collection of options.collections) {
47274
+ tried.push(collection);
47275
+ let matches;
47276
+ try {
47277
+ matches = await options.searcher.searchByVector(collection, vector, {
47278
+ size,
47279
+ ...signal !== void 0 ? { signal } : {}
47280
+ });
47281
+ } catch (error51) {
47282
+ firstError ??= error51 instanceof Error ? error51 : new Error(String(error51));
47283
+ continue;
47284
+ }
47285
+ if (matches.length > 0) {
47286
+ return { hits: matches.map((match) => toHit(match, options.owner)), collection, tried };
47287
+ }
47288
+ }
47289
+ if (firstError !== void 0)
47290
+ throw firstError;
47291
+ return { hits: [], collection: void 0, tried };
47206
47292
  }
47207
47293
  async function findTeamSkillsNamed(options, name, signal) {
47208
- const candidates = await searchTeamSkills(options, name, 25, signal);
47209
47294
  const wanted = name.trim().toLowerCase();
47210
- return candidates.filter((hit) => hit.name.trim().toLowerCase() === wanted);
47295
+ const found = /* @__PURE__ */ new Map();
47296
+ for (const collection of options.collections) {
47297
+ let result;
47298
+ try {
47299
+ result = await searchTeamSkills({ ...options, collections: [collection] }, name, 25, signal);
47300
+ } catch {
47301
+ continue;
47302
+ }
47303
+ for (const hit of result.hits) {
47304
+ if (hit.name.trim().toLowerCase() === wanted)
47305
+ found.set(`${hit.owner ?? "?"}/${hit.name}`, hit);
47306
+ }
47307
+ }
47308
+ return [...found.values()];
47211
47309
  }
47212
47310
  function describeTeamSkillCollision(name, hits) {
47213
47311
  const others = hits.filter((hit) => !hit.isMine);
@@ -47223,11 +47321,13 @@ function describeTeamSkillCollision(name, hits) {
47223
47321
  " name and does not overwrite theirs."
47224
47322
  ].join("\n");
47225
47323
  }
47226
- function renderTeamSkillHits(hits, query) {
47324
+ function renderTeamSkillHits(found, query) {
47325
+ const { hits, collection, tried } = found;
47227
47326
  if (hits.length === 0) {
47228
47327
  return `No team skills match: ${query}
47229
- Either nobody has written one, or the shared skills index has not been built yet (Settings \u2192 Skills). This does not mean the subject is undocumented.`;
47328
+ ` + (tried.length > 0 ? "Looked in " + tried.join(", ") + ". " : "") + "Either nobody has written one, or the shared skills index has not been built yet (Settings \u2192 Skills). This does not mean the subject is undocumented.";
47230
47329
  }
47330
+ const widened = collection !== void 0 && tried.length > 1 && tried[0] !== collection ? "Nothing in " + tried.slice(0, tried.indexOf(collection)).join(", ") + "; these are from " + collection + "." : void 0;
47231
47331
  const rendered = hits.map((hit, position) => {
47232
47332
  const who = hit.isMine ? "yours" : hit.owner ?? "unknown owner";
47233
47333
  const where = hit.project === void 0 ? who : `${who} / ${hit.project}`;
@@ -47236,6 +47336,7 @@ ${hit.text}`;
47236
47336
  }).join("\n\n---\n\n");
47237
47337
  return [
47238
47338
  `${hits.length} team skill(s) matching: ${query}`,
47339
+ ...widened !== void 0 ? [widened] : [],
47239
47340
  'Anything not marked "yours" is a colleague\u2019s and has no file on this machine \u2014 the text',
47240
47341
  "above is the whole of it, so do not try to read_file it. To keep one, write your own copy",
47241
47342
  "with write_skill; that stores it under your name and leaves theirs alone.",
@@ -47278,24 +47379,27 @@ function createSearchTeamSkillsTool(options) {
47278
47379
  async execute(params) {
47279
47380
  const startedAt = Date.now();
47280
47381
  try {
47281
- const hits = await searchTeamSkills(options, params.query, params.size ?? 5);
47382
+ const found = await searchTeamSkills(options, params.query, params.size ?? 5);
47282
47383
  options.observer?.record({
47283
47384
  at: startedAt,
47284
47385
  source: "search_team_skills",
47386
+ // The one that answered, not the one that was asked first — the log is evidence about
47387
+ // what happened, and a widened search is exactly what somebody would want to see.
47388
+ collection: found.collection ?? found.tried.join(" \u2192 "),
47285
47389
  query: params.query,
47286
- collection: options.collection,
47287
- hits: hits.length,
47390
+ hits: found.hits.length,
47288
47391
  elapsedMs: Date.now() - startedAt,
47289
47392
  via: "index"
47290
47393
  });
47291
- return { content: renderTeamSkillHits(hits, params.query) };
47394
+ return { content: renderTeamSkillHits(found, params.query) };
47292
47395
  } catch (error51) {
47293
47396
  const message3 = error51 instanceof Error ? error51.message : String(error51);
47294
47397
  options.observer?.record({
47295
47398
  at: startedAt,
47296
47399
  source: "search_team_skills",
47297
47400
  query: params.query,
47298
- collection: options.collection,
47401
+ // Every name that would have been tried: the search failed before one could answer.
47402
+ collection: options.collections.join(" \u2192 "),
47299
47403
  hits: 0,
47300
47404
  elapsedMs: Date.now() - startedAt,
47301
47405
  error: message3
@@ -48586,26 +48690,26 @@ Each appears in its own window. Nothing is changed or sent.`
48586
48690
  async execute(params) {
48587
48691
  const ids = idsOf(params);
48588
48692
  const opened = [];
48589
- const failed = [];
48693
+ const failed2 = [];
48590
48694
  for (const id of ids) {
48591
48695
  try {
48592
48696
  opened.push((await options.display(id)).subject);
48593
48697
  } catch (error51) {
48594
- failed.push(`${id}: ${error51 instanceof Error ? error51.message : String(error51)}`);
48698
+ failed2.push(`${id}: ${error51 instanceof Error ? error51.message : String(error51)}`);
48595
48699
  }
48596
48700
  }
48597
48701
  if (opened.length === 0) {
48598
48702
  return { content: `Could not open any of them.
48599
- ${failed.join("\n")}`, isError: true };
48703
+ ${failed2.join("\n")}`, isError: true };
48600
48704
  }
48601
48705
  return {
48602
48706
  content: [
48603
48707
  `Opened ${String(opened.length)} message(s) in Outlook:`,
48604
48708
  ...opened.map((subject) => ` "${subject}"`),
48605
- ...failed.length === 0 ? [] : [
48709
+ ...failed2.length === 0 ? [] : [
48606
48710
  "",
48607
- `${String(failed.length)} could not be opened - moved or deleted since indexing:`,
48608
- ...failed.map((line) => ` ${line}`)
48711
+ `${String(failed2.length)} could not be opened - moved or deleted since indexing:`,
48712
+ ...failed2.map((line) => ` ${line}`)
48609
48713
  ]
48610
48714
  ].join("\n")
48611
48715
  };
@@ -56275,6 +56379,7 @@ var McpConnection = class {
56275
56379
  if (transport instanceof StdioClientTransport) {
56276
56380
  this.attachStderr(transport);
56277
56381
  }
56382
+ this.onLog(await describeMcpRequest(this.config, this.secrets));
56278
56383
  try {
56279
56384
  await client.connect(transport);
56280
56385
  } catch (error51) {
@@ -56358,6 +56463,20 @@ function renderToolResult(result) {
56358
56463
  function describeError(error51) {
56359
56464
  return error51 instanceof Error ? error51.message : String(error51);
56360
56465
  }
56466
+ async function describeMcpRequest(config2, secrets) {
56467
+ if (isStdioServer(config2))
56468
+ return `Starting ${config2.command}`;
56469
+ const kind = config2.type ?? "streamable-http (no type set; SSE is the fallback)";
56470
+ let names;
56471
+ try {
56472
+ const resolved = await interpolateSecrets(config2.headers, secrets);
56473
+ names = Object.entries(resolved).map(([name, value]) => value.trim().length === 0 ? `${name} (EMPTY)` : name);
56474
+ } catch (error51) {
56475
+ return `Connecting to ${config2.url} as ${kind}; headers unresolved: ${describeError(error51)}`;
56476
+ }
56477
+ const headers = names.length === 0 ? "no headers configured" : `headers: ${names.join(", ")}`;
56478
+ return `Connecting to ${config2.url} as ${kind}; ${headers}`;
56479
+ }
56361
56480
 
56362
56481
  // ../../packages/core/dist/mcp/registry.js
56363
56482
  function adaptTool(serverName, toolName, description, inputSchema, call) {
@@ -57159,10 +57278,20 @@ function createWriteSkillTool(context) {
57159
57278
  }
57160
57279
  await fs10.writeFile(filePath, rendered, "utf8");
57161
57280
  await context.onChanged();
57281
+ let publishProblem;
57282
+ if (context.onSaved !== void 0) {
57283
+ try {
57284
+ await context.onSaved(params.name, rendered);
57285
+ } catch (error51) {
57286
+ publishProblem = error51 instanceof Error ? error51.message : String(error51);
57287
+ }
57288
+ }
57162
57289
  const collision = existed ? void 0 : await collisionWarning(params.name);
57163
57290
  return {
57164
57291
  content: `${existed ? "Updated" : "Recorded"} the skill "${params.name}" at ${filePath}.
57165
- Its summary will appear in your context from the next message onward.` + (collision === void 0 ? "" : `
57292
+ Its summary will appear in your context from the next message onward.` + (publishProblem === void 0 ? "" : `
57293
+
57294
+ Saved here, but NOT copied to the bucket: ${publishProblem}`) + (collision === void 0 ? "" : `
57166
57295
 
57167
57296
  ${collision}`),
57168
57297
  path: filePath
@@ -58469,6 +58598,8 @@ async function truncateToolResult(content, store, maxChars = DEFAULT_MAX_CHARS)
58469
58598
  var DEFAULT_MAX_ITERATIONS = 25;
58470
58599
  var BOOKKEEPING_TOOLS = /* @__PURE__ */ new Set(["plan_progress"]);
58471
58600
  var MAX_REFUNDED_STEPS = 20;
58601
+ var FORM_DISMISSED = "The user dismissed the form without answering.";
58602
+ var MAX_FORM_RESETS = 5;
58472
58603
  var MAX_CONSECUTIVE_MISTAKES = 3;
58473
58604
  async function prepareModelMessages(conversation, provider, tools, options, events) {
58474
58605
  const contextWindow = options.contextWindow ?? 0;
@@ -58651,6 +58782,7 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
58651
58782
  conversation.addUserMessage(userMessage, options.images);
58652
58783
  const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
58653
58784
  let refunded = 0;
58785
+ let formResets = 0;
58654
58786
  const mistakeCounts = /* @__PURE__ */ new Map();
58655
58787
  let continueNudges = 0;
58656
58788
  const mode = options.mode ?? CODE_MODE;
@@ -58724,6 +58856,10 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
58724
58856
  conversation.addUserMessage(message3);
58725
58857
  events.onQueuedMessageConsumed?.(message3);
58726
58858
  }
58859
+ if (queued.length > 0) {
58860
+ iteration = -1;
58861
+ refunded = 0;
58862
+ }
58727
58863
  if (toolCall.name === "attempt_completion" || toolCall.name === "ask_followup_question") {
58728
58864
  events.onDone();
58729
58865
  return;
@@ -58732,6 +58868,11 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
58732
58868
  refunded += 1;
58733
58869
  iteration -= 1;
58734
58870
  }
58871
+ if (toolCall.name === "ask_user_form" && result.isError !== true && !result.content.startsWith(FORM_DISMISSED) && formResets < MAX_FORM_RESETS) {
58872
+ formResets += 1;
58873
+ iteration = -1;
58874
+ refunded = 0;
58875
+ }
58735
58876
  if (result.path !== void 0) {
58736
58877
  if (result.isError === true) {
58737
58878
  const count = (mistakeCounts.get(result.path) ?? 0) + 1;
@@ -58745,7 +58886,7 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
58745
58886
  }
58746
58887
  }
58747
58888
  }
58748
- events.onError(`Stopped after ${maxIterations} steps in one turn. Nothing is lost \u2014 send another message (for example "continue") to carry on from here. Raise the limit in Settings \u2192 Approvals if this task legitimately needs more.`);
58889
+ events.onError(`Stopped after ${maxIterations} steps since your last message. Nothing is lost \u2014 send another message (for example "continue") to carry on from here. Raise the limit in Settings \u2192 Approvals if this task legitimately needs more.`);
58749
58890
  }
58750
58891
 
58751
58892
  // ../../packages/core/dist/host/bridge.js
@@ -61715,6 +61856,10 @@ var NodeFileSystem = class {
61715
61856
  async writeFile(path36, contents) {
61716
61857
  await fs16.writeFile(path36, contents, "utf8");
61717
61858
  }
61859
+ /** The counterpart of `readBytes`, and deliberately as bare as `writeFile` beside it. */
61860
+ async writeBytes(path36, contents) {
61861
+ await fs16.writeFile(path36, contents);
61862
+ }
61718
61863
  async stat(path36) {
61719
61864
  const stat = await fs16.lstat(path36);
61720
61865
  return {
@@ -62133,6 +62278,10 @@ ${preview.text}` } : {}
62133
62278
  const defaultSkillsDir = workspaceRoot !== void 0 ? path24.join(workspaceRoot, ".lightcode", "skills") : void 0;
62134
62279
  let skillsDir = defaultSkillsDir;
62135
62280
  let extraSkillDirs = [];
62281
+ let mirroredSkillsDir;
62282
+ let mirroredToolsDir;
62283
+ let cachedSkillMirror;
62284
+ let lastSync = {};
62136
62285
  function resolveSkillDir(entry) {
62137
62286
  const trimmed = entry.trim();
62138
62287
  if (trimmed.length === 0)
@@ -62687,6 +62836,7 @@ ${preview.text}` } : {}
62687
62836
  let cachedOffice = {};
62688
62837
  let cachedMail = {};
62689
62838
  let cachedDatasets = [];
62839
+ let cachedS3 = { targets: [], problems: [] };
62690
62840
  let datasetSummaryForPrompt = [];
62691
62841
  let cachedPythonEnabled = false;
62692
62842
  const mailStore = new MailStore(storageDir);
@@ -62735,6 +62885,22 @@ ${preview.text}` } : {}
62735
62885
  cachedOffice = config2.office ?? {};
62736
62886
  cachedMail = config2.mail ?? {};
62737
62887
  cachedDatasets = config2.datasets ?? [];
62888
+ cachedS3 = await resolveS3({
62889
+ config: config2.s3,
62890
+ http: httpClient,
62891
+ secrets,
62892
+ /*
62893
+ * Through the one global resolver, so a corporate root certificate reaches S3 exactly as it
62894
+ * reaches the gateway and the vector store. §10: do not add another place to configure a CA.
62895
+ */
62896
+ tls: await resolveConnectionTls({
62897
+ ...config2.tls !== void 0 ? { global: config2.tls } : {},
62898
+ ...config2.certDir !== void 0 ? { certDir: config2.certDir } : {},
62899
+ onPaths: (paths) => {
62900
+ void Promise.all(paths.map((certPath) => denylist.add(certPath))).catch(() => void 0);
62901
+ }
62902
+ })
62903
+ });
62738
62904
  cachedPythonEnabled = config2.python?.dynamicTools === "on";
62739
62905
  datasetSummaryForPrompt = await Promise.all(cachedDatasets.map(async (dataset) => ({
62740
62906
  name: dataset.name,
@@ -62768,6 +62934,20 @@ ${preview.text}` } : {}
62768
62934
  cachedReadRoots = (config2.filesystem?.readRoots ?? []).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
62769
62935
  skillsDir = (config2.skills?.dir !== void 0 ? resolveSkillDir(config2.skills.dir) : void 0) ?? defaultSkillsDir;
62770
62936
  extraSkillDirs = (config2.skills?.paths ?? []).map(resolveSkillDir).filter((dir) => dir !== void 0);
62937
+ const skillMirror = config2.s3?.skills;
62938
+ cachedSkillMirror = skillMirror;
62939
+ if (skillMirror?.enabled === true) {
62940
+ mirroredSkillsDir = mirrorFolder({
62941
+ storageDir,
62942
+ connectionId: skillMirror.connectionId,
62943
+ kind: "skills",
62944
+ ...skillMirror.prefix !== void 0 ? { prefix: skillMirror.prefix } : {}
62945
+ });
62946
+ if (mirroredSkillsDir !== void 0)
62947
+ extraSkillDirs.push(mirroredSkillsDir);
62948
+ } else {
62949
+ mirroredSkillsDir = void 0;
62950
+ }
62771
62951
  return config2;
62772
62952
  }
62773
62953
  function announceConfigRecovery() {
@@ -62937,7 +63117,21 @@ ${preview.text}` } : {}
62937
63117
  submitForReview: (request) => services.submitForReview?.({ kind: "skill", ...request }) ?? Promise.resolve("")
62938
63118
  } : {}
62939
63119
  };
62940
- combined.register(createWriteSkillTool(context));
63120
+ const skillTarget = cachedSkillMirror?.enabled === true ? targetById(cachedS3, cachedSkillMirror.connectionId) : void 0;
63121
+ const mirrorPrefix = cachedSkillMirror?.prefix;
63122
+ combined.register(createWriteSkillTool({
63123
+ ...context,
63124
+ ...skillTarget !== void 0 && skillTarget.readOnly !== true ? {
63125
+ onSaved: async (name, content) => {
63126
+ await uploadToS3({
63127
+ target: skillTarget,
63128
+ ...mirrorPrefix !== void 0 ? { prefix: mirrorPrefix } : {},
63129
+ relative: `${name}.md`,
63130
+ contents: Buffer.from(content, "utf8")
63131
+ });
63132
+ }
63133
+ } : {}
63134
+ }));
62941
63135
  combined.register(createDeleteSkillTool(context));
62942
63136
  }
62943
63137
  if (workspaceRoot !== void 0) {
@@ -62972,6 +63166,8 @@ ${preview.text}` } : {}
62972
63166
  if (codebase !== void 0) {
62973
63167
  combined.register(createSearchCodebaseTool({ ...codebase, observer: searchLog }));
62974
63168
  }
63169
+ for (const tool of createS3Tools(cachedS3.targets))
63170
+ combined.register(tool);
62975
63171
  if (cachedDatasets.length > 0) {
62976
63172
  combined.register(createSearchDataTool({
62977
63173
  load: async () => Promise.all(cachedDatasets.map(async (dataset) => ({
@@ -63466,8 +63662,12 @@ ${direction}` : attachMentions(text, mentions);
63466
63662
  skillAliases(config2).length > 0 && search !== void 0 && embedder !== void 0 ? {
63467
63663
  searcher: search.searcher,
63468
63664
  embedder,
63469
- // The first is the default circle, exactly as it is for the codebase index.
63470
- collection: skillAliases(config2)[0],
63665
+ /*
63666
+ * All of them, in order — the first is the ordinary circle and the rest are what a
63667
+ * search widens into when it holds nothing. Handing over only the first is what
63668
+ * made the extra names typed in the panel do nothing at all for skills.
63669
+ */
63670
+ collections: skillAliases(config2),
63471
63671
  ...indexOwner(config2) !== void 0 ? { owner: indexOwner(config2) } : {}
63472
63672
  } : void 0,
63473
63673
  /*
@@ -65097,15 +65297,168 @@ ${direction}` : attachMentions(text, mentions);
65097
65297
  const digest = createHash3("sha256").update(path24.resolve(workspaceRoot).toLowerCase()).digest("hex").slice(0, 16);
65098
65298
  return `${config2?.embedder?.indexPrefix ?? DEFAULT_INDEX_PREFIX}-${digest}`;
65099
65299
  }
65100
- async function handleSaveSkillsAlias(alias) {
65300
+ async function postS3() {
65301
+ const { config: config2 } = await configManager.load();
65302
+ const connections = await Promise.all((config2.s3?.connections ?? []).map(async (connection) => ({
65303
+ id: connection.id,
65304
+ label: connection.label,
65305
+ bucket: connection.bucket,
65306
+ region: connection.region,
65307
+ accessKeyId: connection.accessKeyId,
65308
+ /*
65309
+ * Asked of the secret store rather than inferred from config holding a reference.
65310
+ *
65311
+ * Config and the store are two stores that can diverge, and letting one assert what only
65312
+ * the other knows is what made a vanished API key keep reading as "Set" for three
65313
+ * releases (section 19).
65314
+ */
65315
+ hasSecret: await secrets.get(connection.secretAccessKeyRef) !== void 0,
65316
+ ...connection.endpoint !== void 0 ? { endpoint: connection.endpoint } : {},
65317
+ ...connection.pathStyle !== void 0 ? { pathStyle: connection.pathStyle } : {},
65318
+ ...connection.prefix !== void 0 ? { prefix: connection.prefix } : {},
65319
+ ...connection.readOnly !== void 0 ? { readOnly: connection.readOnly } : {}
65320
+ })));
65321
+ post({
65322
+ type: "s3",
65323
+ connections,
65324
+ problems: cachedS3.problems,
65325
+ ...config2.s3?.skills !== void 0 ? { skills: config2.s3.skills } : {},
65326
+ ...config2.s3?.tools !== void 0 ? { tools: config2.s3.tools } : {},
65327
+ ...mirroredSkillsDir !== void 0 ? { skillsFolder: mirroredSkillsDir } : {},
65328
+ ...mirroredToolsDir !== void 0 ? { toolsFolder: mirroredToolsDir } : {},
65329
+ ...lastSync.skills !== void 0 ? { lastSkillsSync: lastSync.skills } : {},
65330
+ ...lastSync.tools !== void 0 ? { lastToolsSync: lastSync.tools } : {}
65331
+ });
65332
+ }
65333
+ const s3SecretRef = (id) => `s3:${id}:secret`;
65334
+ const s3TokenRef = (id) => `s3:${id}:sessionToken`;
65335
+ async function handleSaveS3Connection(input, secret, sessionToken) {
65336
+ const { config: config2 } = await configManager.load();
65337
+ const id = input.id ?? `s3-${Date.now().toString(36)}`;
65338
+ const existing = (config2.s3?.connections ?? []).find((connection) => connection.id === id);
65339
+ if (secret !== void 0 && secret.trim().length > 0) {
65340
+ await secrets.set(s3SecretRef(id), secret.trim());
65341
+ }
65342
+ if (sessionToken !== void 0 && sessionToken.trim().length > 0) {
65343
+ await secrets.set(s3TokenRef(id), sessionToken.trim());
65344
+ }
65345
+ const saved = {
65346
+ id,
65347
+ label: input.label.trim(),
65348
+ bucket: input.bucket.trim(),
65349
+ region: input.region.trim(),
65350
+ accessKeyId: input.accessKeyId.trim(),
65351
+ secretAccessKeyRef: s3SecretRef(id),
65352
+ ...existing?.sessionTokenRef !== void 0 || (sessionToken ?? "").trim().length > 0 ? { sessionTokenRef: s3TokenRef(id) } : {},
65353
+ ...input.endpoint !== void 0 && input.endpoint.trim().length > 0 ? { endpoint: input.endpoint.trim() } : {},
65354
+ ...input.pathStyle === true ? { pathStyle: true } : {},
65355
+ ...input.prefix !== void 0 && input.prefix.trim().length > 0 ? { prefix: input.prefix.trim() } : {},
65356
+ ...input.readOnly === true ? { readOnly: true } : {}
65357
+ };
65358
+ const others = (config2.s3?.connections ?? []).filter((connection) => connection.id !== id);
65359
+ await configManager.save("user", {
65360
+ s3: { ...config2.s3 ?? {}, connections: [...others, saved] }
65361
+ });
65362
+ await loadSettings();
65363
+ await postS3();
65364
+ }
65365
+ async function handleDeleteS3Connection(id) {
65366
+ const { config: config2 } = await configManager.load();
65367
+ await secrets.delete(s3SecretRef(id)).catch(() => void 0);
65368
+ await secrets.delete(s3TokenRef(id)).catch(() => void 0);
65369
+ const s3 = { ...config2.s3 ?? {} };
65370
+ s3.connections = (s3.connections ?? []).filter((connection) => connection.id !== id);
65371
+ if (s3.skills?.connectionId === id)
65372
+ delete s3.skills;
65373
+ if (s3.tools?.connectionId === id)
65374
+ delete s3.tools;
65375
+ await configManager.save("user", { s3 });
65376
+ await loadSettings();
65377
+ await postS3();
65378
+ }
65379
+ async function handleSaveS3Mirror(kind, connectionId, prefix, enabled) {
65380
+ const { config: config2 } = await configManager.load();
65381
+ const s3 = { ...config2.s3 ?? {} };
65382
+ if (connectionId.trim().length === 0)
65383
+ delete s3[kind];
65384
+ else {
65385
+ s3[kind] = {
65386
+ connectionId: connectionId.trim(),
65387
+ ...prefix !== void 0 && prefix.trim().length > 0 ? { prefix: prefix.trim() } : {},
65388
+ enabled
65389
+ };
65390
+ }
65391
+ await configManager.save("user", { s3 });
65392
+ await loadSettings();
65393
+ if (enabled && connectionId.trim().length > 0)
65394
+ await handleSyncS3(kind);
65395
+ else
65396
+ await postS3();
65397
+ }
65398
+ async function handleSyncS3(kind) {
65399
+ const { config: config2 } = await configManager.load();
65400
+ const mirror = config2.s3?.[kind];
65401
+ if (mirror === void 0) {
65402
+ lastSync = { ...lastSync, [kind]: "No bucket folder is configured." };
65403
+ await postS3();
65404
+ return;
65405
+ }
65406
+ const target = targetById(cachedS3, mirror.connectionId);
65407
+ if (target === void 0) {
65408
+ lastSync = {
65409
+ ...lastSync,
65410
+ [kind]: "That connection is not usable - check its key in the list above."
65411
+ };
65412
+ await postS3();
65413
+ return;
65414
+ }
65415
+ const localDir = mirrorFolder({
65416
+ storageDir,
65417
+ connectionId: mirror.connectionId,
65418
+ kind,
65419
+ ...mirror.prefix !== void 0 ? { prefix: mirror.prefix } : {}
65420
+ });
65421
+ if (kind === "tools")
65422
+ mirroredToolsDir = localDir;
65423
+ try {
65424
+ const result = await syncFromS3({
65425
+ target,
65426
+ ...mirror.prefix !== void 0 ? { prefix: mirror.prefix } : {},
65427
+ localDir,
65428
+ fs: new NodeFileSystem(),
65429
+ extensions: kind === "skills" ? [".md"] : [".py"]
65430
+ });
65431
+ const parts = [
65432
+ `${String(result.written.length)} updated`,
65433
+ `${String(result.unchanged)} unchanged`
65434
+ ];
65435
+ if (result.failed.length > 0)
65436
+ parts.push(`${String(result.failed.length)} failed`);
65437
+ lastSync = { ...lastSync, [kind]: `${(/* @__PURE__ */ new Date()).toLocaleTimeString()} - ${parts.join(", ")}` };
65438
+ for (const failure of result.failed)
65439
+ logger.warn(`s3 ${kind}: ${failure.key}`, failure.problem);
65440
+ if (kind === "skills") {
65441
+ await refreshSkills();
65442
+ postSkills();
65443
+ }
65444
+ } catch (error51) {
65445
+ lastSync = { ...lastSync, [kind]: error51 instanceof Error ? error51.message : String(error51) };
65446
+ }
65447
+ await postS3();
65448
+ }
65449
+ async function handleSaveSkillsAlias(aliases) {
65101
65450
  try {
65102
65451
  const { config: config2 } = await configManager.load();
65103
- const trimmed = alias.trim();
65104
65452
  const embedder = { ...config2.embedder ?? {} };
65105
- if (trimmed.length > 0)
65106
- embedder.skillsAlias = trimmed;
65453
+ const { primary, rest } = aliasFields(aliases);
65454
+ if (primary !== void 0)
65455
+ embedder.skillsAlias = primary;
65107
65456
  else
65108
65457
  delete embedder.skillsAlias;
65458
+ if (rest !== void 0)
65459
+ embedder.skillsAliases = rest;
65460
+ else
65461
+ delete embedder.skillsAliases;
65109
65462
  await configManager.save("user", { embedder });
65110
65463
  const { config: next } = await configManager.load();
65111
65464
  await postEmbedder(next);
@@ -65827,26 +66180,50 @@ ${direction}` : attachMentions(text, mentions);
65827
66180
  // rather than replacing a blank with the default and looking like it was set.
65828
66181
  ...config2.embedder?.indexPrefix !== void 0 ? { indexPrefix: config2.embedder.indexPrefix } : {},
65829
66182
  ...config2.embedder?.indexAlias !== void 0 ? { indexAlias: config2.embedder.indexAlias } : {},
66183
+ /*
66184
+ * Both spellings of both, because the panel shows the merged list and cannot merge what it
66185
+ * was never sent. The singular halves stay for older configs and older builds; the panel
66186
+ * runs them through `codebaseAliases`/`skillAliases`, which is the one place that knows how
66187
+ * the two fit together.
66188
+ */
66189
+ ...config2.embedder?.indexAliases !== void 0 ? { indexAliases: config2.embedder.indexAliases } : {},
66190
+ ...config2.embedder?.skillsAliases !== void 0 ? { skillsAliases: config2.embedder.skillsAliases } : {},
65830
66191
  ...config2.embedder?.skillsAlias !== void 0 ? { skillsAlias: config2.embedder.skillsAlias } : {},
65831
66192
  defaultIndexPrefix: DEFAULT_INDEX_PREFIX,
65832
66193
  indexedFiles
65833
66194
  });
65834
66195
  }
65835
- async function handleSaveEmbedder(profileId, model, dimensions, indexName, indexPrefix, indexAlias) {
66196
+ async function handleSaveEmbedder(profileId, model, dimensions, indexName, indexPrefix, indexAliases) {
65836
66197
  try {
65837
- await configManager.save("user", {
65838
- embedder: {
65839
- profileId,
65840
- model,
65841
- dimensions,
65842
- ...indexName !== void 0 && indexName.trim().length > 0 ? { indexName: indexName.trim() } : {},
65843
- // Absent rather than empty when cleared, so the default applies instead of a name
65844
- // beginning with a stray dash.
65845
- ...indexPrefix !== void 0 && indexPrefix.trim().length > 0 ? { indexPrefix: indexPrefix.trim() } : {},
65846
- // Same treatment: cleared means absent, which is what turns team scope back off.
65847
- ...indexAlias !== void 0 && indexAlias.trim().length > 0 ? { indexAlias: indexAlias.trim() } : {}
65848
- }
65849
- });
66198
+ const { config: current } = await configManager.load();
66199
+ const embedder = {
66200
+ ...current.embedder ?? {},
66201
+ profileId,
66202
+ model,
66203
+ dimensions
66204
+ };
66205
+ const put = (key, value) => {
66206
+ if (value === void 0)
66207
+ return;
66208
+ if (value.trim().length > 0)
66209
+ embedder[key] = value.trim();
66210
+ else
66211
+ delete embedder[key];
66212
+ };
66213
+ put("indexName", indexName);
66214
+ put("indexPrefix", indexPrefix);
66215
+ if (indexAliases !== void 0) {
66216
+ const { primary, rest } = aliasFields(indexAliases);
66217
+ if (primary !== void 0)
66218
+ embedder["indexAlias"] = primary;
66219
+ else
66220
+ delete embedder["indexAlias"];
66221
+ if (rest !== void 0)
66222
+ embedder["indexAliases"] = rest;
66223
+ else
66224
+ delete embedder["indexAliases"];
66225
+ }
66226
+ await configManager.save("user", { embedder });
65850
66227
  const { config: config2 } = await configManager.load();
65851
66228
  await postEmbedder(config2);
65852
66229
  scheduleDocsReindex("index prefix changed");
@@ -66635,6 +67012,13 @@ ${direction}` : attachMentions(text, mentions);
66635
67012
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
66636
67013
  }
66637
67014
  }
67015
+ function reportFailure(operation, work) {
67016
+ work.catch((error51) => {
67017
+ const reason = error51 instanceof Error ? error51.message : String(error51);
67018
+ logger.warn(`${operation} failed`, reason);
67019
+ post({ type: "error", message: `${operation} failed: ${reason}` });
67020
+ });
67021
+ }
66638
67022
  const unsubscribe = transport.onMessage((raw) => {
66639
67023
  const message3 = raw;
66640
67024
  if (message3.type === "sendMessage") {
@@ -66655,7 +67039,7 @@ ${direction}` : attachMentions(text, mentions);
66655
67039
  }
66656
67040
  })();
66657
67041
  } else if (message3.type === "requestMentionCandidates") {
66658
- void handleMentionCandidates(message3.query);
67042
+ reportFailure("handleMentionCandidates", handleMentionCandidates(message3.query));
66659
67043
  } else if (message3.type === "queueMessage") {
66660
67044
  queuedMessages.push(message3.text);
66661
67045
  postQueued();
@@ -66678,21 +67062,21 @@ ${direction}` : attachMentions(text, mentions);
66678
67062
  pendingFormFields.delete(message3.id);
66679
67063
  }
66680
67064
  } else if (message3.type === "approvalResponseAlways") {
66681
- void handleAlwaysAllow(message3.id, message3.scope);
67065
+ reportFailure("handleAlwaysAllow", handleAlwaysAllow(message3.id, message3.scope));
66682
67066
  } else if (message3.type === "rollback") {
66683
- void handleRollback();
67067
+ reportFailure("handleRollback", handleRollback());
66684
67068
  } else if (message3.type === "requestSettings") {
66685
- void postSettings();
67069
+ reportFailure("postSettings", postSettings());
66686
67070
  } else if (message3.type === "requestTasks") {
66687
- void postTasks();
67071
+ reportFailure("postTasks", postTasks());
66688
67072
  } else if (message3.type === "openTask") {
66689
- void openTask(message3.id);
67073
+ reportFailure("openTask", openTask(message3.id));
66690
67074
  } else if (message3.type === "deleteTask") {
66691
- void deleteTask(message3.id);
67075
+ reportFailure("deleteTask", deleteTask(message3.id));
66692
67076
  } else if (message3.type === "newTask") {
66693
- void startNewTask();
67077
+ reportFailure("startNewTask", startNewTask());
66694
67078
  } else if (message3.type === "setMode") {
66695
- void handleSetMode(message3.modeId);
67079
+ reportFailure("handleSetMode", handleSetMode(message3.modeId));
66696
67080
  } else if (message3.type === "setMaxIterations") {
66697
67081
  void configManager.save("user", { maxIterations: message3.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
66698
67082
  } else if (message3.type === "setProgrammingProfile") {
@@ -66720,7 +67104,7 @@ ${direction}` : attachMentions(text, mentions);
66720
67104
  }
66721
67105
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
66722
67106
  } else if (message3.type === "setToolTimeoutFor") {
66723
- void handleSetToolTimeoutFor(message3.name, message3.seconds);
67107
+ reportFailure("handleSetToolTimeoutFor", handleSetToolTimeoutFor(message3.name, message3.seconds));
66724
67108
  } else if (message3.type === "setToolTimeout") {
66725
67109
  void configManager.save("user", {
66726
67110
  tools: message3.seconds === void 0 ? {} : { timeoutSeconds: message3.seconds }
@@ -66742,73 +67126,73 @@ ${direction}` : attachMentions(text, mentions);
66742
67126
  }
66743
67127
  }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
66744
67128
  } else if (message3.type === "setAutoApprove") {
66745
- void handleSetAutoApprove(message3.group, message3.enabled);
67129
+ reportFailure("handleSetAutoApprove", handleSetAutoApprove(message3.group, message3.enabled));
66746
67130
  } else if (message3.type === "revokeAllowedTool") {
66747
- void saveApprovals({
67131
+ reportFailure("saveApprovals", saveApprovals({
66748
67132
  ...cachedApprovals,
66749
67133
  allowedTools: removeFromAllowlist(message3.toolName, cachedApprovals.allowedTools ?? [])
66750
- });
67134
+ }));
66751
67135
  } else if (message3.type === "revokeAllowedCommand") {
66752
- void saveApprovals({
67136
+ reportFailure("saveApprovals", saveApprovals({
66753
67137
  ...cachedApprovals,
66754
67138
  allowedCommands: removeFromAllowlist(message3.command, cachedApprovals.allowedCommands ?? [])
66755
- });
67139
+ }));
66756
67140
  } else if (message3.type === "requestMcp") {
66757
- void handleRequestMcp();
67141
+ reportFailure("handleRequestMcp", handleRequestMcp());
66758
67142
  } else if (message3.type === "saveMcpServers") {
66759
- void handleSaveMcpServers(message3.json);
67143
+ reportFailure("handleSaveMcpServers", handleSaveMcpServers(message3.json));
66760
67144
  } else if (message3.type === "saveMcpServer") {
66761
- void handleSaveMcpServer(message3.name, message3.previousName, message3.config);
67145
+ reportFailure("handleSaveMcpServer", handleSaveMcpServer(message3.name, message3.previousName, message3.config));
66762
67146
  } else if (message3.type === "duplicateMcpServer") {
66763
- void handleDuplicateMcpServer(message3.name);
67147
+ reportFailure("handleDuplicateMcpServer", handleDuplicateMcpServer(message3.name));
66764
67148
  } else if (message3.type === "deleteMcpServer") {
66765
- void handleDeleteMcpServer(message3.name);
67149
+ reportFailure("handleDeleteMcpServer", handleDeleteMcpServer(message3.name));
66766
67150
  } else if (message3.type === "browseForPath") {
66767
- void handleBrowseForPath(message3.purpose, message3.kind, message3.extensions);
67151
+ reportFailure("handleBrowseForPath", handleBrowseForPath(message3.purpose, message3.kind, message3.extensions));
66768
67152
  } else if (message3.type === "probePythonEnv") {
66769
- void handleProbePythonEnv(message3.venvDir, message3.script);
67153
+ reportFailure("handleProbePythonEnv", handleProbePythonEnv(message3.venvDir, message3.script));
66770
67154
  } else if (message3.type === "connectMcpServer") {
66771
67155
  void mcp.connectServer(message3.name);
66772
67156
  } else if (message3.type === "restartMcpServer") {
66773
67157
  void mcp.restart(message3.name);
66774
67158
  } else if (message3.type === "setMcpServerEnabled") {
66775
- void updateMcpServer(message3.name, (entry) => ({
67159
+ reportFailure("updateMcpServer", updateMcpServer(message3.name, (entry) => ({
66776
67160
  ...entry,
66777
67161
  disabled: !message3.enabled
66778
- })).then(() => postMcp());
67162
+ })).then(() => postMcp()));
66779
67163
  } else if (message3.type === "setMcpToolTimeout") {
66780
- void handleSetToolTimeout(message3.server, message3.tool, message3.seconds);
67164
+ reportFailure("handleSetToolTimeout", handleSetToolTimeout(message3.server, message3.tool, message3.seconds));
66781
67165
  } else if (message3.type === "setMcpToolPermission") {
66782
- void handleSetToolPermission(message3.server, message3.tool, message3.permission);
67166
+ reportFailure("handleSetToolPermission", handleSetToolPermission(message3.server, message3.tool, message3.permission));
66783
67167
  } else if (message3.type === "requestSearch") {
66784
- void postSearch();
66785
- void postDispatcher();
67168
+ reportFailure("postSearch", postSearch());
67169
+ reportFailure("postDispatcher", postDispatcher());
66786
67170
  post({ type: "searchLog", entries: [...searchLog.list()] });
66787
67171
  } else if (message3.type === "saveSearchConnection") {
66788
- void handleSaveSearchConnection(message3.connection);
67172
+ reportFailure("handleSaveSearchConnection", handleSaveSearchConnection(message3.connection));
66789
67173
  } else if (message3.type === "deleteSearchConnection") {
66790
- void handleDeleteSearchConnection(message3.id);
67174
+ reportFailure("handleDeleteSearchConnection", handleDeleteSearchConnection(message3.id));
66791
67175
  } else if (message3.type === "setActiveSearchConnection") {
66792
67176
  void (message3.forProject === true ? configManager.saveForWorkspace({ activeVectorStoreId: message3.id }) : configManager.save("user", { activeVectorStoreId: message3.id })).then(async () => {
66793
67177
  await postSearch();
66794
67178
  await postProjectSettings();
66795
67179
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66796
67180
  } else if (message3.type === "requestProjectSettings") {
66797
- void postProjectSettings();
67181
+ reportFailure("postProjectSettings", postProjectSettings());
66798
67182
  } else if (message3.type === "clearProjectSettings") {
66799
- void handleClearProjectSettings();
67183
+ reportFailure("handleClearProjectSettings", handleClearProjectSettings());
66800
67184
  } else if (message3.type === "requestSearchIndexes") {
66801
- void handleRequestSearchIndexes(message3.connection);
67185
+ reportFailure("handleRequestSearchIndexes", handleRequestSearchIndexes(message3.connection));
66802
67186
  } else if (message3.type === "testSearchConnection") {
66803
- void handleTestSearchConnection(message3.connection);
67187
+ reportFailure("handleTestSearchConnection", handleTestSearchConnection(message3.connection));
66804
67188
  } else if (message3.type === "syncVectorStore") {
66805
- void handleSyncVectorStore(message3.fromId);
67189
+ reportFailure("handleSyncVectorStore", handleSyncVectorStore(message3.fromId));
66806
67190
  } else if (message3.type === "clearDocsIndex") {
66807
- void handleClearDocsIndex(message3.kind);
67191
+ reportFailure("handleClearDocsIndex", handleClearDocsIndex(message3.kind));
66808
67192
  } else if (message3.type === "clearCodebaseIndex") {
66809
- void handleClearCodebaseIndex();
67193
+ reportFailure("handleClearCodebaseIndex", handleClearCodebaseIndex());
66810
67194
  } else if (message3.type === "openStandingSkill") {
66811
- void handleOpenStandingSkill();
67195
+ reportFailure("handleOpenStandingSkill", handleOpenStandingSkill());
66812
67196
  } else if (message3.type === "setOffice") {
66813
67197
  void configManager.load().then(async () => {
66814
67198
  await configManager.save("user", {
@@ -66822,70 +67206,80 @@ ${direction}` : attachMentions(text, mentions);
66822
67206
  }
66823
67207
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66824
67208
  } else if (message3.type === "indexDocs") {
66825
- void handleIndexDocs(message3.kind);
67209
+ reportFailure("handleIndexDocs", handleIndexDocs(message3.kind));
66826
67210
  } else if (message3.type === "runSearchProbe") {
66827
- void handleSearchProbe(message3.query, message3.target);
67211
+ reportFailure("handleSearchProbe", handleSearchProbe(message3.query, message3.target));
66828
67212
  } else if (message3.type === "clearSearchLog") {
66829
67213
  searchLog.clear();
66830
67214
  } else if (message3.type === "setDispatcher") {
66831
- void saveRetrieval({ dispatcher: message3.enabled }).then(() => {
66832
- void postDispatcher();
67215
+ reportFailure("saveRetrieval", saveRetrieval({ dispatcher: message3.enabled }).then(() => {
67216
+ reportFailure("postDispatcher", postDispatcher());
66833
67217
  if (message3.enabled)
66834
67218
  scheduleDocsReindex("dispatcher enabled");
66835
- }).catch((error51) => post({ type: "error", message: String(error51) }));
67219
+ }));
66836
67220
  } else if (message3.type === "setSkillRetrieval") {
66837
- void saveRetrieval({ skills: message3.enabled }).then(() => {
66838
- void postDispatcher();
67221
+ reportFailure("saveRetrieval", saveRetrieval({ skills: message3.enabled }).then(() => {
67222
+ reportFailure("postDispatcher", postDispatcher());
66839
67223
  if (message3.enabled)
66840
67224
  scheduleDocsReindex("skill retrieval enabled");
66841
- }).catch((error51) => post({ type: "error", message: String(error51) }));
67225
+ }));
66842
67226
  } else if (message3.type === "startIndexing") {
66843
- void handleStartIndexing();
67227
+ reportFailure("handleStartIndexing", handleStartIndexing());
66844
67228
  } else if (message3.type === "attachTeamAlias") {
66845
- void handleAttachTeamAlias();
67229
+ reportFailure("handleAttachTeamAlias", handleAttachTeamAlias());
66846
67230
  } else if (message3.type === "publishTeamSkills") {
66847
- void handlePublishTeamSkills();
67231
+ reportFailure("handlePublishTeamSkills", handlePublishTeamSkills());
66848
67232
  } else if (message3.type === "syncMail") {
66849
- void runMailSync("requested");
67233
+ reportFailure("runMailSync", runMailSync("requested"));
66850
67234
  } else if (message3.type === "pruneMail") {
66851
- void handlePruneMail();
67235
+ reportFailure("handlePruneMail", handlePruneMail());
66852
67236
  } else if (message3.type === "requestOutlookFolders") {
66853
- void handleRequestOutlookFolders(message3.depth, message3.force === true);
67237
+ reportFailure("handleRequestOutlookFolders", handleRequestOutlookFolders(message3.depth, message3.force === true));
66854
67238
  } else if (message3.type === "validateMailFolder") {
66855
- void handleValidateMailFolder(message3.path);
67239
+ reportFailure("handleValidateMailFolder", handleValidateMailFolder(message3.path));
66856
67240
  } else if (message3.type === "requestMailStatus") {
66857
- void loadSettings().then((config2) => {
67241
+ reportFailure("loadSettings", loadSettings().then((config2) => {
66858
67242
  reconcileMailTimer(config2);
66859
67243
  reconcileDatasetTimers(config2);
66860
67244
  return postMailStatus();
66861
- });
67245
+ }));
66862
67246
  } else if (message3.type === "saveMailSettings") {
66863
- void handleSaveMailSettings({
67247
+ reportFailure("handleSaveMailSettings", handleSaveMailSettings({
66864
67248
  enabled: message3.enabled,
66865
67249
  folders: message3.folders,
66866
67250
  includeSubfolders: message3.includeSubfolders,
66867
67251
  syncMinutes: message3.syncMinutes,
66868
67252
  retentionMonths: message3.retentionMonths,
66869
67253
  ...message3.storeId !== void 0 ? { storeId: message3.storeId } : {}
66870
- });
67254
+ }));
66871
67255
  } else if (message3.type === "clearTeamSkills") {
66872
- void handleClearTeamSkills();
67256
+ reportFailure("handleClearTeamSkills", handleClearTeamSkills());
66873
67257
  } else if (message3.type === "refreshMail") {
66874
- void handleRefreshMail(message3.days);
67258
+ reportFailure("handleRefreshMail", handleRefreshMail(message3.days));
66875
67259
  } else if (message3.type === "requestDatasetStatus") {
66876
- void postDatasetStatus();
67260
+ reportFailure("postDatasetStatus", postDatasetStatus());
66877
67261
  } else if (message3.type === "saveDataset") {
66878
- void handleSaveDataset(message3.dataset);
67262
+ reportFailure("handleSaveDataset", handleSaveDataset(message3.dataset));
66879
67263
  } else if (message3.type === "deleteDataset") {
66880
- void handleDeleteDataset(message3.id);
67264
+ reportFailure("handleDeleteDataset", handleDeleteDataset(message3.id));
66881
67265
  } else if (message3.type === "syncDataset") {
66882
- void runDatasetSync(message3.id, "manual");
67266
+ reportFailure("runDatasetSync", runDatasetSync(message3.id, "manual"));
66883
67267
  } else if (message3.type === "clearDataset") {
66884
- void handleClearDataset(message3.id, message3.resync === true);
67268
+ reportFailure("handleClearDataset", handleClearDataset(message3.id, message3.resync === true));
66885
67269
  } else if (message3.type === "clearMailIndex") {
66886
- void handleClearMailIndex(message3.resync === true);
67270
+ reportFailure("handleClearMailIndex", handleClearMailIndex(message3.resync === true));
67271
+ } else if (message3.type === "requestS3") {
67272
+ reportFailure("postS3", postS3());
67273
+ } else if (message3.type === "saveS3Connection") {
67274
+ reportFailure("handleSaveS3Connection", handleSaveS3Connection(message3.connection, message3.secret, message3.sessionToken));
67275
+ } else if (message3.type === "deleteS3Connection") {
67276
+ reportFailure("handleDeleteS3Connection", handleDeleteS3Connection(message3.id));
67277
+ } else if (message3.type === "saveS3Mirror") {
67278
+ reportFailure("handleSaveS3Mirror", handleSaveS3Mirror(message3.kind, message3.connectionId, message3.prefix, message3.enabled));
67279
+ } else if (message3.type === "syncS3") {
67280
+ reportFailure("handleSyncS3", handleSyncS3(message3.kind));
66887
67281
  } else if (message3.type === "saveSkillsAlias") {
66888
- void handleSaveSkillsAlias(message3.alias);
67282
+ reportFailure("handleSaveSkillsAlias", handleSaveSkillsAlias(message3.aliases));
66889
67283
  } else if (message3.type === "cancelIndexing") {
66890
67284
  if (message3.kind === void 0) {
66891
67285
  indexingAbort?.abort();
@@ -66897,23 +67291,23 @@ ${direction}` : attachMentions(text, mentions);
66897
67291
  indexingAborts.get(message3.kind)?.abort();
66898
67292
  }
66899
67293
  } else if (message3.type === "saveEmbedder") {
66900
- void handleSaveEmbedder(message3.profileId, message3.model, message3.dimensions, message3.indexName, message3.indexPrefix, message3.indexAlias);
67294
+ reportFailure("handleSaveEmbedder", handleSaveEmbedder(message3.profileId, message3.model, message3.dimensions, message3.indexName, message3.indexPrefix, message3.indexAliases));
66901
67295
  } else if (message3.type === "requestEmbedderModels") {
66902
- void handleRequestEmbedderModels(message3.profileId);
67296
+ reportFailure("handleRequestEmbedderModels", handleRequestEmbedderModels(message3.profileId));
66903
67297
  } else if (message3.type === "openWalkthrough") {
66904
67298
  void ui.openWalkthrough?.();
66905
67299
  } else if (message3.type === "requestTools") {
66906
- void postTools();
67300
+ reportFailure("postTools", postTools());
66907
67301
  } else if (message3.type === "requestSchedules") {
66908
- void postSchedules();
67302
+ reportFailure("postSchedules", postSchedules());
66909
67303
  } else if (message3.type === "saveSchedule") {
66910
- void handleSaveSchedule(message3.schedule);
67304
+ reportFailure("handleSaveSchedule", handleSaveSchedule(message3.schedule));
66911
67305
  } else if (message3.type === "duplicateSchedule") {
66912
- void handleDuplicateSchedule(message3.id);
67306
+ reportFailure("handleDuplicateSchedule", handleDuplicateSchedule(message3.id));
66913
67307
  } else if (message3.type === "deleteSchedule") {
66914
- void handleDeleteSchedule(message3.id);
67308
+ reportFailure("handleDeleteSchedule", handleDeleteSchedule(message3.id));
66915
67309
  } else if (message3.type === "setScheduleEnabled") {
66916
- void handleSetScheduleEnabled(message3.id, message3.enabled);
67310
+ reportFailure("handleSetScheduleEnabled", handleSetScheduleEnabled(message3.id, message3.enabled));
66917
67311
  } else if (message3.type === "setTaskExpertLimits") {
66918
67312
  const next = message3.maxSpendUsd === void 0 && message3.maxConsultations === void 0 ? void 0 : {
66919
67313
  ...message3.maxSpendUsd !== void 0 ? { maxSpendUsd: message3.maxSpendUsd } : {},
@@ -66943,7 +67337,7 @@ ${direction}` : attachMentions(text, mentions);
66943
67337
  await postExpert({ redetect: false });
66944
67338
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66945
67339
  } else if (message3.type === "measureExpertCost") {
66946
- void handleMeasureExpertCost();
67340
+ reportFailure("handleMeasureExpertCost", handleMeasureExpertCost());
66947
67341
  } else if (message3.type === "clearExpertPricing") {
66948
67342
  void configManager.load().then(async ({ config: config2 }) => {
66949
67343
  const expert = { ...config2.expert };
@@ -66953,23 +67347,23 @@ ${direction}` : attachMentions(text, mentions);
66953
67347
  await postExpert({ redetect: false });
66954
67348
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66955
67349
  } else if (message3.type === "assessJunior") {
66956
- void handleAssessJunior(message3.profileId);
67350
+ reportFailure("handleAssessJunior", handleAssessJunior(message3.profileId));
66957
67351
  } else if (message3.type === "clearAssessment") {
66958
- void handleClearAssessment(message3.model, message3.profileLabel);
67352
+ reportFailure("handleClearAssessment", handleClearAssessment(message3.model, message3.profileLabel));
66959
67353
  } else if (message3.type === "restartScheduler") {
66960
67354
  restartScheduleTimer();
66961
67355
  logger.info("schedule timer restarted by the user");
66962
- void postSchedules();
67356
+ reportFailure("postSchedules", postSchedules());
66963
67357
  } else if (message3.type === "deleteScheduleRun") {
66964
- void handleDeleteScheduleRun(message3.id, message3.at);
67358
+ reportFailure("handleDeleteScheduleRun", handleDeleteScheduleRun(message3.id, message3.at));
66965
67359
  } else if (message3.type === "clearScheduleRuns") {
66966
- void handleClearScheduleRuns(message3.id);
67360
+ reportFailure("handleClearScheduleRuns", handleClearScheduleRuns(message3.id));
66967
67361
  } else if (message3.type === "openScheduleRun") {
66968
- void openRunTranscript(message3.taskId, message3.title);
67362
+ reportFailure("openRunTranscript", openRunTranscript(message3.taskId, message3.title));
66969
67363
  } else if (message3.type === "runScheduleNow") {
66970
- void runSchedule(message3.id, "manual");
67364
+ reportFailure("runSchedule", runSchedule(message3.id, "manual"));
66971
67365
  } else if (message3.type === "requestSkills") {
66972
- void postSkills();
67366
+ reportFailure("postSkills", postSkills());
66973
67367
  } else if (message3.type === "saveSkillDirs") {
66974
67368
  void configManager.save("user", {
66975
67369
  skills: {
@@ -66978,32 +67372,32 @@ ${direction}` : attachMentions(text, mentions);
66978
67372
  }
66979
67373
  }).then(() => postSkills()).catch((error51) => post({ type: "error", message: String(error51) }));
66980
67374
  } else if (message3.type === "openManagedFile") {
66981
- void handleOpenManagedFile(message3.path);
67375
+ reportFailure("handleOpenManagedFile", handleOpenManagedFile(message3.path));
66982
67376
  } else if (message3.type === "deletePythonTool") {
66983
- void handleDeletePythonTool(message3.name);
67377
+ reportFailure("handleDeletePythonTool", handleDeletePythonTool(message3.name));
66984
67378
  } else if (message3.type === "approvePythonTool") {
66985
- void handleApprovePythonTool(message3.name);
67379
+ reportFailure("handleApprovePythonTool", handleApprovePythonTool(message3.name));
66986
67380
  } else if (message3.type === "deleteSkillFile") {
66987
- void handleDeleteSkillFile(message3.name);
67381
+ reportFailure("handleDeleteSkillFile", handleDeleteSkillFile(message3.name));
66988
67382
  } else if (message3.type === "requestPython") {
66989
- void postPython();
67383
+ reportFailure("postPython", postPython());
66990
67384
  } else if (message3.type === "setPython") {
66991
- void handleSetPython(message3);
67385
+ reportFailure("handleSetPython", handleSetPython(message3));
66992
67386
  } else if (message3.type === "requestNetwork") {
66993
- void postNetwork();
67387
+ reportFailure("postNetwork", postNetwork());
66994
67388
  } else if (message3.type === "saveNetwork") {
66995
- void handleSaveNetwork(message3.settings);
67389
+ reportFailure("handleSaveNetwork", handleSaveNetwork(message3.settings));
66996
67390
  } else if (message3.type === "requestExpert") {
66997
- void postExpert();
67391
+ reportFailure("postExpert", postExpert());
66998
67392
  } else if (message3.type === "setPlan") {
66999
- void applyPlan(message3.plan);
67393
+ reportFailure("applyPlan", applyPlan(message3.plan));
67000
67394
  } else if (message3.type === "requestPlan") {
67001
67395
  post({ type: "plan", plan: activePlan ?? "" });
67002
67396
  postPlanProgress();
67003
67397
  } else if (message3.type === "requestPlanProgress") {
67004
67398
  postPlanProgress();
67005
67399
  } else if (message3.type === "requestAgents") {
67006
- void postAgents();
67400
+ reportFailure("postAgents", postAgents());
67007
67401
  } else if (message3.type === "setAgentRole") {
67008
67402
  const assignment = message3.assignment;
67009
67403
  const role = message3.role;
@@ -67011,7 +67405,7 @@ ${direction}` : attachMentions(text, mentions);
67011
67405
  post({ type: "error", message: `There is no "${role}" role.` });
67012
67406
  return;
67013
67407
  }
67014
- void saveAgents((current) => {
67408
+ reportFailure("saveAgents", saveAgents((current) => {
67015
67409
  const roles = { ...current.roles ?? {} };
67016
67410
  if (assignment === void 0)
67017
67411
  delete roles[role];
@@ -67023,7 +67417,7 @@ ${direction}` : attachMentions(text, mentions);
67023
67417
  };
67024
67418
  }
67025
67419
  return { ...current, roles };
67026
- });
67420
+ }));
67027
67421
  } else if (message3.type === "setAgentPrompt") {
67028
67422
  const role = message3.role;
67029
67423
  const prompt = message3.prompt;
@@ -67031,7 +67425,7 @@ ${direction}` : attachMentions(text, mentions);
67031
67425
  post({ type: "error", message: `There is no "${role}" role.` });
67032
67426
  return;
67033
67427
  }
67034
- void saveAgents((current) => {
67428
+ reportFailure("saveAgents", saveAgents((current) => {
67035
67429
  const roles = { ...current.roles ?? {} };
67036
67430
  const existing = roles[role];
67037
67431
  if (prompt === void 0 || prompt === defaultPromptFor(role)) {
@@ -67044,31 +67438,31 @@ ${direction}` : attachMentions(text, mentions);
67044
67438
  roles[role] = { ...existing ?? { kind: "profile" }, prompt };
67045
67439
  }
67046
67440
  return { ...current, roles };
67047
- });
67441
+ }));
67048
67442
  } else if (message3.type === "setAgentBudget") {
67049
67443
  const matters = message3.matters;
67050
- void saveAgents((current) => ({ ...current, budgetMatters: matters }));
67444
+ reportFailure("saveAgents", saveAgents((current) => ({ ...current, budgetMatters: matters })));
67051
67445
  } else if (message3.type === "setTeamGuidance") {
67052
67446
  const guidance = message3.guidance;
67053
- void saveAgents((current) => {
67447
+ reportFailure("saveAgents", saveAgents((current) => {
67054
67448
  if (guidance === void 0 || guidance.trim().length === 0 || guidance === DEFAULT_TEAM_GUIDANCE) {
67055
67449
  const rest = { ...current };
67056
67450
  delete rest.teamGuidance;
67057
67451
  return rest;
67058
67452
  }
67059
67453
  return { ...current, teamGuidance: guidance };
67060
- });
67454
+ }));
67061
67455
  } else if (message3.type === "saveCustomRole") {
67062
- void handleSaveCustomRole(message3);
67456
+ reportFailure("handleSaveCustomRole", handleSaveCustomRole(message3));
67063
67457
  } else if (message3.type === "deleteCustomRole") {
67064
- void handleDeleteCustomRole(message3.id);
67458
+ reportFailure("handleDeleteCustomRole", handleDeleteCustomRole(message3.id));
67065
67459
  } else if (message3.type === "setRoleThinking") {
67066
67460
  const role = message3.role;
67067
67461
  if (!isAgentRole(role, cachedAgentDefinitions)) {
67068
67462
  post({ type: "error", message: `There is no "${role}" role.` });
67069
67463
  return;
67070
67464
  }
67071
- void saveAgents((current) => {
67465
+ reportFailure("saveAgents", saveAgents((current) => {
67072
67466
  const roles = { ...current.roles ?? {} };
67073
67467
  const existing = roles[role] ?? { kind: "profile" };
67074
67468
  if (message3.level === void 0) {
@@ -67079,43 +67473,43 @@ ${direction}` : attachMentions(text, mentions);
67079
67473
  roles[role] = { ...existing, thinking: message3.level };
67080
67474
  }
67081
67475
  return { ...current, roles };
67082
- });
67476
+ }));
67083
67477
  } else if (message3.type === "setRoleEnabled") {
67084
67478
  const role = message3.role;
67085
67479
  if (!isAgentRole(role, cachedAgentDefinitions)) {
67086
67480
  post({ type: "error", message: `There is no "${role}" role.` });
67087
67481
  return;
67088
67482
  }
67089
- void saveAgents((current) => {
67483
+ reportFailure("saveAgents", saveAgents((current) => {
67090
67484
  const roles = { ...current.roles ?? {} };
67091
67485
  roles[role] = {
67092
67486
  ...roles[role] ?? { kind: "profile" },
67093
67487
  enabled: message3.enabled
67094
67488
  };
67095
67489
  return { ...current, roles };
67096
- });
67490
+ }));
67097
67491
  } else if (message3.type === "setRoleWrite") {
67098
67492
  const role = message3.role;
67099
67493
  if (!isAgentRole(role, cachedAgentDefinitions)) {
67100
67494
  post({ type: "error", message: `There is no "${role}" role.` });
67101
67495
  return;
67102
67496
  }
67103
- void saveAgents((current) => {
67497
+ reportFailure("saveAgents", saveAgents((current) => {
67104
67498
  const roles = { ...current.roles ?? {} };
67105
67499
  roles[role] = { ...roles[role] ?? { kind: "profile" }, write: message3.canWrite };
67106
67500
  return { ...current, roles };
67107
- });
67501
+ }));
67108
67502
  } else if (message3.type === "setRoleTools") {
67109
67503
  const role = message3.role;
67110
67504
  if (!isAgentRole(role, cachedAgentDefinitions)) {
67111
67505
  post({ type: "error", message: `There is no "${role}" role.` });
67112
67506
  return;
67113
67507
  }
67114
- void saveAgents((current) => {
67508
+ reportFailure("saveAgents", saveAgents((current) => {
67115
67509
  const roles = { ...current.roles ?? {} };
67116
67510
  roles[role] = { ...roles[role] ?? { kind: "profile" }, tools: message3.usesTools };
67117
67511
  return { ...current, roles };
67118
- });
67512
+ }));
67119
67513
  } else if (message3.type === "setAgentColor") {
67120
67514
  const role = message3.role;
67121
67515
  const color = message3.color;
@@ -67123,35 +67517,35 @@ ${direction}` : attachMentions(text, mentions);
67123
67517
  post({ type: "error", message: `There is no "${role}" role.` });
67124
67518
  return;
67125
67519
  }
67126
- void saveAgents((current) => ({
67520
+ reportFailure("saveAgents", saveAgents((current) => ({
67127
67521
  ...current,
67128
67522
  colors: { ...current.colors ?? {}, [role]: color }
67129
- }));
67523
+ })));
67130
67524
  } else if (message3.type === "setExpert") {
67131
- void handleSetExpert(message3.enabled, message3.path, message3.model, {
67525
+ reportFailure("handleSetExpert", handleSetExpert(message3.enabled, message3.path, message3.model, {
67132
67526
  ...message3.maxSpendUsd !== void 0 ? { maxSpendUsd: message3.maxSpendUsd } : {},
67133
67527
  ...message3.maxConsultations !== void 0 ? { maxConsultations: message3.maxConsultations } : {},
67134
67528
  ...message3.profileId !== void 0 ? { profileId: message3.profileId } : {}
67135
- });
67529
+ }));
67136
67530
  } else if (message3.type === "requestProfiles") {
67137
- void postProfiles();
67138
- void postCapabilities();
67531
+ reportFailure("postProfiles", postProfiles());
67532
+ reportFailure("postCapabilities", postCapabilities());
67139
67533
  } else if (message3.type === "saveProfile") {
67140
- void handleSaveProfile(message3.profile);
67534
+ reportFailure("handleSaveProfile", handleSaveProfile(message3.profile));
67141
67535
  } else if (message3.type === "requestModels") {
67142
- void handleRequestModels(message3.profile);
67536
+ reportFailure("handleRequestModels", handleRequestModels(message3.profile));
67143
67537
  } else if (message3.type === "testConnection") {
67144
- void handleTestConnection(message3.profile);
67538
+ reportFailure("handleTestConnection", handleTestConnection(message3.profile));
67145
67539
  } else if (message3.type === "duplicateProfile") {
67146
- void handleDuplicateProfile(message3.id);
67540
+ reportFailure("handleDuplicateProfile", handleDuplicateProfile(message3.id));
67147
67541
  } else if (message3.type === "deleteProfile") {
67148
- void handleDeleteProfile(message3.id);
67542
+ reportFailure("handleDeleteProfile", handleDeleteProfile(message3.id));
67149
67543
  } else if (message3.type === "setActiveProfile") {
67150
- void handleSetActiveProfile(message3.id, message3.forProject);
67544
+ reportFailure("handleSetActiveProfile", handleSetActiveProfile(message3.id, message3.forProject));
67151
67545
  } else if (message3.type === "exportConfig") {
67152
- void handleExportConfig();
67546
+ reportFailure("handleExportConfig", handleExportConfig());
67153
67547
  } else if (message3.type === "importConfig") {
67154
- void handleImportConfig();
67548
+ reportFailure("handleImportConfig", handleImportConfig());
67155
67549
  }
67156
67550
  });
67157
67551
  void (async () => {
@@ -67666,6 +68060,8 @@ ${contents}
67666
68060
  }
67667
68061
  await postTasks();
67668
68062
  await postSettings();
68063
+ await postProfiles();
68064
+ await postS3();
67669
68065
  await postSchedules();
67670
68066
  } catch (error51) {
67671
68067
  logger.warn(`Could not resync the view: ${error51 instanceof Error ? error51.message : String(error51)}`);
@@ -69579,6 +69975,558 @@ That is a fault in the tool itself, or the source is unreachable from here. Fix
69579
69975
  };
69580
69976
  }
69581
69977
 
69978
+ // ../../packages/core/dist/s3/sigv4.js
69979
+ import { createHash as createHash4, createHmac } from "node:crypto";
69980
+ var EMPTY_PAYLOAD_SHA256 = createHash4("sha256").update("").digest("hex");
69981
+ function encodeSegment(segment) {
69982
+ return encodeURIComponent(segment).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
69983
+ }
69984
+ function canonicalPath(pathname) {
69985
+ if (pathname === "" || pathname === "/")
69986
+ return "/";
69987
+ return pathname.split("/").map((segment) => {
69988
+ let raw = segment;
69989
+ try {
69990
+ raw = decodeURIComponent(segment);
69991
+ } catch {
69992
+ }
69993
+ return encodeSegment(raw);
69994
+ }).join("/");
69995
+ }
69996
+ function canonicalQuery(search) {
69997
+ 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]));
69998
+ return parameters.map(([name, value]) => `${name}=${value}`).join("&");
69999
+ }
70000
+ function amzDate(now) {
70001
+ return `${now.toISOString().replace(/[-:]/g, "").slice(0, 15)}Z`;
70002
+ }
70003
+ function signingKey(secretAccessKey, date5, region, service) {
70004
+ const dateKey = createHmac("sha256", `AWS4${secretAccessKey}`).update(date5).digest();
70005
+ const regionKey = createHmac("sha256", dateKey).update(region).digest();
70006
+ const serviceKey = createHmac("sha256", regionKey).update(service).digest();
70007
+ return createHmac("sha256", serviceKey).update("aws4_request").digest();
70008
+ }
70009
+ function signRequest(input) {
70010
+ const service = input.service ?? "s3";
70011
+ const now = input.now ?? /* @__PURE__ */ new Date();
70012
+ const timestamp = amzDate(now);
70013
+ const date5 = timestamp.slice(0, 8);
70014
+ const url2 = new URL(input.url);
70015
+ const body = input.body ?? Buffer.alloc(0);
70016
+ const payloadHash = createHash4("sha256").update(body).digest("hex");
70017
+ const headers = {
70018
+ ...input.headers,
70019
+ host: url2.host,
70020
+ "x-amz-content-sha256": payloadHash,
70021
+ "x-amz-date": timestamp,
70022
+ ...input.sessionToken !== void 0 ? { "x-amz-security-token": input.sessionToken } : {}
70023
+ };
70024
+ const canonicalHeaderEntries = Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value.trim().replace(/\s+/g, " ")]).sort((a, b) => a[0].localeCompare(b[0]));
70025
+ const signedHeaders = canonicalHeaderEntries.map(([name]) => name).join(";");
70026
+ const canonicalRequest = [
70027
+ input.method.toUpperCase(),
70028
+ canonicalPath(url2.pathname),
70029
+ canonicalQuery(url2.search),
70030
+ `${canonicalHeaderEntries.map(([name, value]) => `${name}:${value}`).join("\n")}
70031
+ `,
70032
+ signedHeaders,
70033
+ payloadHash
70034
+ ].join("\n");
70035
+ const scope = `${date5}/${input.region}/${service}/aws4_request`;
70036
+ const stringToSign = [
70037
+ "AWS4-HMAC-SHA256",
70038
+ timestamp,
70039
+ scope,
70040
+ createHash4("sha256").update(canonicalRequest).digest("hex")
70041
+ ].join("\n");
70042
+ const signature = createHmac("sha256", signingKey(input.secretAccessKey, date5, input.region, service)).update(stringToSign).digest("hex");
70043
+ return {
70044
+ headers: {
70045
+ ...headers,
70046
+ Authorization: `AWS4-HMAC-SHA256 Credential=${input.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
70047
+ },
70048
+ canonicalRequest,
70049
+ stringToSign,
70050
+ signature
70051
+ };
70052
+ }
70053
+
70054
+ // ../../packages/core/dist/s3/client.js
70055
+ var S3Client = class {
70056
+ http;
70057
+ connection;
70058
+ tls;
70059
+ constructor(http, connection, tls2) {
70060
+ this.http = http;
70061
+ this.connection = connection;
70062
+ this.tls = tls2;
70063
+ }
70064
+ url(call) {
70065
+ const { bucket, region, endpoint, pathStyle } = this.connection;
70066
+ const origin = new URL(endpoint ?? `https://s3.${region}.amazonaws.com`);
70067
+ const key = call.key ?? "";
70068
+ const host = pathStyle === true ? origin.host : `${bucket}.${origin.host}`;
70069
+ const prefix = pathStyle === true ? `/${bucket}` : "";
70070
+ const path36 = key === "" ? "" : `/${key.split("/").map((part) => encodeURIComponent(part)).join("/")}`;
70071
+ const url2 = new URL(`${origin.protocol}//${host}${prefix}${path36}`);
70072
+ for (const [name, value] of Object.entries(call.query ?? {}))
70073
+ url2.searchParams.set(name, value);
70074
+ return url2.toString();
70075
+ }
70076
+ async send(call) {
70077
+ const url2 = this.url(call);
70078
+ const signed = signRequest({
70079
+ method: call.method,
70080
+ url: url2,
70081
+ headers: call.headers ?? {},
70082
+ ...call.bodyBytes !== void 0 ? { body: Buffer.from(call.bodyBytes) } : {},
70083
+ region: this.connection.region,
70084
+ accessKeyId: this.connection.accessKeyId,
70085
+ secretAccessKey: this.connection.secretAccessKey,
70086
+ ...this.connection.sessionToken !== void 0 ? { sessionToken: this.connection.sessionToken } : {}
70087
+ });
70088
+ const response = await this.http.request(url2, {
70089
+ method: call.method,
70090
+ headers: signed.headers,
70091
+ ...call.bodyBytes !== void 0 ? { bodyBytes: call.bodyBytes } : {},
70092
+ ...call.signal !== void 0 ? { signal: call.signal } : {},
70093
+ ...this.tls !== void 0 ? { tls: this.tls } : {}
70094
+ });
70095
+ const bytes = await readAll(response);
70096
+ return { status: response.status, text: bytes.toString("utf8"), bytes };
70097
+ }
70098
+ /**
70099
+ * Objects under a prefix.
70100
+ *
70101
+ * Follows the continuation token rather than stopping at the first page: a folder of 1,200 files
70102
+ * silently reported as 1,000 is the kind of wrong answer nobody thinks to check.
70103
+ */
70104
+ async list(prefix, limit = 1e3, signal) {
70105
+ const found = [];
70106
+ let token;
70107
+ while (found.length < limit) {
70108
+ const query = {
70109
+ "list-type": "2",
70110
+ "max-keys": String(Math.min(1e3, limit - found.length))
70111
+ };
70112
+ if (prefix !== "")
70113
+ query["prefix"] = prefix;
70114
+ if (token !== void 0)
70115
+ query["continuation-token"] = token;
70116
+ const result = await this.send({
70117
+ method: "GET",
70118
+ query,
70119
+ ...signal !== void 0 ? { signal } : {}
70120
+ });
70121
+ if (result.status !== 200)
70122
+ throw new Error(describeFailure(result.status, result.text));
70123
+ found.push(...parseListing(result.text));
70124
+ token = matchTag(result.text, "NextContinuationToken");
70125
+ if (token === void 0)
70126
+ break;
70127
+ }
70128
+ return found.slice(0, limit);
70129
+ }
70130
+ async get(key, signal) {
70131
+ const result = await this.send({
70132
+ method: "GET",
70133
+ key,
70134
+ ...signal !== void 0 ? { signal } : {}
70135
+ });
70136
+ if (result.status !== 200)
70137
+ throw new Error(describeFailure(result.status, result.text, key));
70138
+ return result.bytes;
70139
+ }
70140
+ async put(key, bytes, contentType2, signal) {
70141
+ const result = await this.send({
70142
+ method: "PUT",
70143
+ key,
70144
+ bodyBytes: bytes,
70145
+ ...contentType2 !== void 0 ? { headers: { "content-type": contentType2 } } : {},
70146
+ ...signal !== void 0 ? { signal } : {}
70147
+ });
70148
+ if (result.status !== 200 && result.status !== 204) {
70149
+ throw new Error(describeFailure(result.status, result.text, key));
70150
+ }
70151
+ }
70152
+ };
70153
+ async function readAll(response) {
70154
+ if (response.body === null)
70155
+ return Buffer.from(await response.text(), "utf8");
70156
+ const reader = response.body.getReader();
70157
+ const chunks = [];
70158
+ for (; ; ) {
70159
+ const { done, value } = await reader.read();
70160
+ if (done)
70161
+ break;
70162
+ if (value !== void 0)
70163
+ chunks.push(value);
70164
+ }
70165
+ return Buffer.concat(chunks);
70166
+ }
70167
+ function describeFailure(status, body, key) {
70168
+ const code = matchTag(body, "Code");
70169
+ const message3 = matchTag(body, "Message");
70170
+ const what = key === void 0 ? "" : ` for "${key}"`;
70171
+ if (code === void 0)
70172
+ return `S3 request failed${what} with status ${String(status)}.`;
70173
+ return `S3 ${code}${what}: ${message3 ?? `status ${String(status)}`}`;
70174
+ }
70175
+ function matchTag(xml, tag) {
70176
+ const match = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(xml);
70177
+ return match?.[1];
70178
+ }
70179
+ function parseListing(xml) {
70180
+ const objects = [];
70181
+ for (const block of xml.split("<Contents>").slice(1)) {
70182
+ const key = matchTag(block, "Key");
70183
+ if (key === void 0)
70184
+ continue;
70185
+ objects.push({
70186
+ key: decodeEntities3(key),
70187
+ size: Number(matchTag(block, "Size") ?? "0"),
70188
+ lastModified: matchTag(block, "LastModified") ?? ""
70189
+ });
70190
+ }
70191
+ return objects;
70192
+ }
70193
+ function decodeEntities3(value) {
70194
+ return value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&#39;", String.fromCharCode(39)).replaceAll("&amp;", "&");
70195
+ }
70196
+
70197
+ // ../../packages/core/dist/s3/keys.js
70198
+ function normalisePrefix(prefix) {
70199
+ const trimmed = (prefix ?? "").trim().replace(/^\/+/, "");
70200
+ if (trimmed === "")
70201
+ return "";
70202
+ return trimmed.endsWith("/") ? trimmed : `${trimmed}/`;
70203
+ }
70204
+ function confineKey(requested, prefix) {
70205
+ const clean = requested.trim().replace(/^\/+/, "");
70206
+ if (clean === "")
70207
+ return { ok: false, message: "No key was given." };
70208
+ if (clean.split("/").includes("..")) {
70209
+ return {
70210
+ ok: false,
70211
+ 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.`
70212
+ };
70213
+ }
70214
+ const base = normalisePrefix(prefix);
70215
+ if (base === "")
70216
+ return { ok: true, key: clean };
70217
+ const key = clean.startsWith(base) ? clean : `${base}${clean}`;
70218
+ if (!key.startsWith(base)) {
70219
+ return { ok: false, message: `"${requested}" is outside "${base}", which this connection is limited to.` };
70220
+ }
70221
+ return { ok: true, key };
70222
+ }
70223
+ function displayKey(key, prefix) {
70224
+ const base = normalisePrefix(prefix);
70225
+ return base !== "" && key.startsWith(base) ? key.slice(base.length) : key;
70226
+ }
70227
+
70228
+ // ../../packages/core/dist/s3/resolve.js
70229
+ async function resolveS3(options) {
70230
+ const targets = [];
70231
+ const problems = [];
70232
+ for (const connection of options.config?.connections ?? []) {
70233
+ const secret = await options.secrets.get(connection.secretAccessKeyRef);
70234
+ if (secret === void 0 || secret.trim().length === 0) {
70235
+ problems.push({
70236
+ label: connection.label,
70237
+ 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."
70238
+ });
70239
+ continue;
70240
+ }
70241
+ const sessionToken = connection.sessionTokenRef === void 0 ? void 0 : await options.secrets.get(connection.sessionTokenRef);
70242
+ const client = new S3Client(options.http, {
70243
+ bucket: connection.bucket,
70244
+ region: connection.region,
70245
+ accessKeyId: connection.accessKeyId,
70246
+ secretAccessKey: secret,
70247
+ ...sessionToken !== void 0 ? { sessionToken } : {},
70248
+ ...connection.endpoint !== void 0 ? { endpoint: connection.endpoint } : {},
70249
+ ...connection.pathStyle !== void 0 ? { pathStyle: connection.pathStyle } : {}
70250
+ }, options.tls);
70251
+ targets.push({
70252
+ id: connection.id,
70253
+ label: connection.label,
70254
+ bucket: connection.bucket,
70255
+ client,
70256
+ ...connection.prefix !== void 0 ? { prefix: connection.prefix } : {},
70257
+ ...connection.readOnly !== void 0 ? { readOnly: connection.readOnly } : {}
70258
+ });
70259
+ }
70260
+ return { targets, problems };
70261
+ }
70262
+ function targetById(resolved, id) {
70263
+ if (id === void 0)
70264
+ return void 0;
70265
+ return resolved.targets.find((target) => target.id === id);
70266
+ }
70267
+
70268
+ // ../../packages/core/dist/s3/sync.js
70269
+ var DEFAULT_LIMIT2 = 500;
70270
+ async function syncFromS3(options) {
70271
+ const base = normalisePrefix(options.target.prefix);
70272
+ const where = normalisePrefix(`${base}${options.prefix ?? ""}`);
70273
+ const result = { written: [], unchanged: 0, failed: [] };
70274
+ const objects = await options.target.client.list(where, options.limit ?? DEFAULT_LIMIT2, options.signal);
70275
+ for (const object3 of objects) {
70276
+ const relative = object3.key.slice(where.length);
70277
+ if (relative === "" || relative.endsWith("/"))
70278
+ continue;
70279
+ if (!options.extensions.some((extension) => relative.toLowerCase().endsWith(extension)))
70280
+ continue;
70281
+ if (relative.split("/").includes("..")) {
70282
+ result.failed.push({ key: object3.key, problem: "The key would write outside the folder." });
70283
+ continue;
70284
+ }
70285
+ try {
70286
+ const bytes = await options.target.client.get(object3.key, options.signal);
70287
+ const localPath = join(options.localDir, relative);
70288
+ let existing;
70289
+ try {
70290
+ existing = await options.fs.readBytes(localPath);
70291
+ } catch {
70292
+ }
70293
+ if (existing !== void 0 && existing.equals(bytes)) {
70294
+ result.unchanged += 1;
70295
+ continue;
70296
+ }
70297
+ await options.fs.mkdir(dirname(localPath));
70298
+ await options.fs.writeBytes(localPath, bytes);
70299
+ result.written.push(relative);
70300
+ } catch (error51) {
70301
+ result.failed.push({
70302
+ key: object3.key,
70303
+ problem: error51 instanceof Error ? error51.message : String(error51)
70304
+ });
70305
+ }
70306
+ }
70307
+ return result;
70308
+ }
70309
+ async function uploadToS3(options) {
70310
+ if (options.target.readOnly === true) {
70311
+ throw new Error(`The connection "${options.target.label}" is read-only.`);
70312
+ }
70313
+ const base = normalisePrefix(options.target.prefix);
70314
+ const where = normalisePrefix(`${base}${options.prefix ?? ""}`);
70315
+ await options.target.client.put(`${where}${options.relative}`, options.contents, void 0, options.signal);
70316
+ }
70317
+ function join(dir, relative) {
70318
+ const left = dir.replace(/[\\/]+$/, "");
70319
+ return `${left}/${relative}`;
70320
+ }
70321
+ function dirname(filePath) {
70322
+ const cut = filePath.lastIndexOf("/");
70323
+ return cut === -1 ? filePath : filePath.slice(0, cut);
70324
+ }
70325
+
70326
+ // ../../packages/core/dist/s3/tools.js
70327
+ function pick2(targets, wanted) {
70328
+ if (wanted === void 0) {
70329
+ if (targets.length === 1)
70330
+ return targets[0];
70331
+ return `Several buckets are configured. Name one with "connection": ${targets.map((target) => target.label).join(", ")}.`;
70332
+ }
70333
+ const found = targets.find((target) => target.label.toLowerCase() === wanted.toLowerCase() || target.id === wanted);
70334
+ if (found !== void 0)
70335
+ return found;
70336
+ return `There is no S3 connection called "${wanted}". Configured: ${targets.map((target) => target.label).join(", ")}.`;
70337
+ }
70338
+ function looksBinary(bytes) {
70339
+ return bytes.subarray(0, 8e3).includes(0);
70340
+ }
70341
+ function describeSize(bytes) {
70342
+ if (bytes < 1024)
70343
+ return `${String(bytes)} B`;
70344
+ if (bytes < 1024 * 1024)
70345
+ return `${(bytes / 1024).toFixed(1)} KB`;
70346
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
70347
+ }
70348
+ var failed = (error51) => ({
70349
+ content: error51 instanceof Error ? error51.message : String(error51),
70350
+ isError: true
70351
+ });
70352
+ function whichBuckets(targets) {
70353
+ return targets.length === 1 ? `the S3 bucket "${targets[0]?.label ?? ""}"` : `an S3 bucket (${targets.map((target) => target.label).join(", ")})`;
70354
+ }
70355
+ var connectionField = external_exports.string().optional().describe("Which configured bucket to use. May be omitted when only one is set up.");
70356
+ var listSchema = external_exports.object({
70357
+ connection: connectionField,
70358
+ prefix: external_exports.string().optional().describe("Folder to list, relative to the connection\u2019s own prefix. Omit for everything."),
70359
+ limit: external_exports.number().int().min(1).max(1e3).optional().describe("How many to return. Default 100.")
70360
+ });
70361
+ function createS3ListTool(targets) {
70362
+ return {
70363
+ name: "s3_list_files",
70364
+ group: "read",
70365
+ description: `List files in ${whichBuckets(targets)}. Use it to find what is there before reading or downloading. Returns keys, sizes and dates, never contents.`,
70366
+ parametersSchema: listSchema,
70367
+ async execute(params, context) {
70368
+ const target = pick2(targets, params.connection);
70369
+ if (typeof target === "string")
70370
+ return { content: target, isError: true };
70371
+ const base = normalisePrefix(target.prefix);
70372
+ const where = params.prefix === void 0 ? base : normalisePrefix(`${base}${params.prefix}`);
70373
+ try {
70374
+ const found = await target.client.list(where, params.limit ?? 100, context.signal);
70375
+ if (found.length === 0)
70376
+ return { content: `No files under "${where === "" ? "/" : where}".` };
70377
+ const lines = found.map((object3) => `${displayKey(object3.key, target.prefix)} ${describeSize(object3.size)} ${object3.lastModified}`);
70378
+ return { content: [`${String(found.length)} file(s) in ${target.bucket}:`, ...lines].join("\n") };
70379
+ } catch (error51) {
70380
+ return failed(error51);
70381
+ }
70382
+ }
70383
+ };
70384
+ }
70385
+ var readSchema = external_exports.object({
70386
+ connection: connectionField,
70387
+ key: external_exports.string().min(1).describe("The file to read, as s3_list_files reports it.")
70388
+ });
70389
+ function createS3ReadTool(targets) {
70390
+ return {
70391
+ name: "s3_read_file",
70392
+ group: "read",
70393
+ description: `Read a file from ${whichBuckets(targets)} as text. For anything that is not text, use s3_download_file and open it locally.`,
70394
+ parametersSchema: readSchema,
70395
+ async execute(params, context) {
70396
+ const target = pick2(targets, params.connection);
70397
+ if (typeof target === "string")
70398
+ return { content: target, isError: true };
70399
+ const resolved = confineKey(params.key, target.prefix);
70400
+ if (!resolved.ok)
70401
+ return { content: resolved.message, isError: true };
70402
+ try {
70403
+ const bytes = await target.client.get(resolved.key, context.signal);
70404
+ if (looksBinary(bytes)) {
70405
+ return {
70406
+ 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.`
70407
+ };
70408
+ }
70409
+ return { content: bytes.toString("utf8") };
70410
+ } catch (error51) {
70411
+ return failed(error51);
70412
+ }
70413
+ }
70414
+ };
70415
+ }
70416
+ var downloadSchema = external_exports.object({
70417
+ connection: connectionField,
70418
+ key: external_exports.string().min(1).describe("The file in the bucket."),
70419
+ to: external_exports.string().min(1).describe("Where to write it, relative to the workspace root.")
70420
+ });
70421
+ function createS3DownloadTool(targets) {
70422
+ return {
70423
+ name: "s3_download_file",
70424
+ group: "edit",
70425
+ description: `Copy a file out of ${whichBuckets(targets)} onto this machine.`,
70426
+ parametersSchema: downloadSchema,
70427
+ preview: async (params) => {
70428
+ const target = pick2(targets, params.connection);
70429
+ const where = typeof target === "string" ? "(unknown bucket)" : `s3://${target.bucket}/${params.key}`;
70430
+ return { kind: "text", text: `Copy ${where}
70431
+ to ${params.to}` };
70432
+ },
70433
+ async execute(params, context) {
70434
+ const target = pick2(targets, params.connection);
70435
+ if (typeof target === "string")
70436
+ return { content: target, isError: true };
70437
+ const resolved = confineKey(params.key, target.prefix);
70438
+ if (!resolved.ok)
70439
+ return { content: resolved.message, isError: true };
70440
+ const to = await resolveToolPath(context, params.to);
70441
+ if (!to.ok)
70442
+ return { content: to.message, isError: true };
70443
+ try {
70444
+ const bytes = await target.client.get(resolved.key, context.signal);
70445
+ await context.fs.writeBytes(to.realPath, bytes);
70446
+ return {
70447
+ content: `Wrote ${describeSize(bytes.length)} to ${params.to} from s3://${target.bucket}/${resolved.key}.`,
70448
+ path: to.realPath
70449
+ };
70450
+ } catch (error51) {
70451
+ return failed(error51);
70452
+ }
70453
+ }
70454
+ };
70455
+ }
70456
+ var uploadSchema = external_exports.object({
70457
+ connection: connectionField,
70458
+ from: external_exports.string().min(1).describe("The local file to upload, relative to the workspace root."),
70459
+ key: external_exports.string().min(1).describe("Where to put it in the bucket.")
70460
+ });
70461
+ function createS3UploadTool(targets) {
70462
+ return {
70463
+ name: "s3_upload_file",
70464
+ group: "edit",
70465
+ description: `Copy a file from this machine into ${whichBuckets(targets)}.`,
70466
+ parametersSchema: uploadSchema,
70467
+ /*
70468
+ * The preview names the destination in full, bucket included.
70469
+ *
70470
+ * Invariant 8: this is the one thing the person approving needs and cannot otherwise check.
70471
+ * A file sent to the wrong bucket is not recoverable by undoing anything here — it is on
70472
+ * somebody else's storage, possibly visible to people the user never intended.
70473
+ */
70474
+ preview: async (params) => {
70475
+ const target = pick2(targets, params.connection);
70476
+ const where = typeof target === "string" ? "(unknown bucket)" : `s3://${target.bucket}/${normalisePrefix(target.prefix)}${params.key}`;
70477
+ return { kind: "text", text: `Upload ${params.from}
70478
+ to ${where}` };
70479
+ },
70480
+ async execute(params, context) {
70481
+ const target = pick2(targets, params.connection);
70482
+ if (typeof target === "string")
70483
+ return { content: target, isError: true };
70484
+ if (target.readOnly === true) {
70485
+ return { content: `The connection "${target.label}" is read-only.`, isError: true };
70486
+ }
70487
+ const resolved = confineKey(params.key, target.prefix);
70488
+ if (!resolved.ok)
70489
+ return { content: resolved.message, isError: true };
70490
+ const from = await resolveToolPath(context, params.from);
70491
+ if (!from.ok)
70492
+ return { content: from.message, isError: true };
70493
+ try {
70494
+ const bytes = await context.fs.readBytes(from.realPath);
70495
+ await target.client.put(resolved.key, bytes, void 0, context.signal);
70496
+ return { content: `Uploaded ${describeSize(bytes.length)} to s3://${target.bucket}/${resolved.key}.` };
70497
+ } catch (error51) {
70498
+ return failed(error51);
70499
+ }
70500
+ }
70501
+ };
70502
+ }
70503
+ function createS3Tools(targets) {
70504
+ if (targets.length === 0)
70505
+ return [];
70506
+ return [
70507
+ createS3ListTool(targets),
70508
+ createS3ReadTool(targets),
70509
+ createS3DownloadTool(targets),
70510
+ createS3UploadTool(targets)
70511
+ ];
70512
+ }
70513
+
70514
+ // ../../packages/core/dist/s3/localFolder.js
70515
+ import { createHash as createHash5 } from "node:crypto";
70516
+ function mirrorFolder(options) {
70517
+ const connection = safeSegment(options.connectionId);
70518
+ const digest = createHash5("sha256").update((options.prefix ?? "").trim().toLowerCase()).digest("hex").slice(0, 8);
70519
+ return join2(options.storageDir, "s3", connection, `${options.kind}-${digest}`);
70520
+ }
70521
+ function safeSegment(id) {
70522
+ const cleaned = id.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/-+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 40);
70523
+ const suffix = createHash5("sha256").update(id).digest("hex").slice(0, 6);
70524
+ return `${cleaned === "" ? "connection" : cleaned}-${suffix}`;
70525
+ }
70526
+ function join2(...parts) {
70527
+ return parts.map((part, index) => index === 0 ? part.replace(/[\\/]+$/, "") : part).join("/");
70528
+ }
70529
+
69582
70530
  // src/identityTool.ts
69583
70531
  import { spawn as spawn7 } from "node:child_process";
69584
70532
  import path27 from "node:path";
@@ -70169,8 +71117,9 @@ function reachableOrigins(hosts, extra = []) {
70169
71117
  // src/identity.ts
70170
71118
  import crypto5 from "node:crypto";
70171
71119
  var SingleUserIdentity = class _SingleUserIdentity {
70172
- describe = "single user (local)";
71120
+ describe;
70173
71121
  static PRINCIPAL = { id: "local", displayName: "Local user" };
71122
+ principal;
70174
71123
  /** Long-lived, minted per server run, only ever sent in an `Authorization` header. */
70175
71124
  sessionToken = crypto5.randomBytes(32).toString("base64url");
70176
71125
  /**
@@ -70185,9 +71134,19 @@ var SingleUserIdentity = class _SingleUserIdentity {
70185
71134
  handoffToken = crypto5.randomBytes(32).toString("base64url");
70186
71135
  handoffExpiresAt;
70187
71136
  handoffSeconds;
70188
- constructor(handoffSeconds = 10) {
71137
+ /**
71138
+ * @param principal Who this server's storage is filed under. Defaults to the local user.
71139
+ *
71140
+ * Supplied when the platform named the account — `JUPYTERHUB_USER` and friends, see
71141
+ * `hostedUser.ts`. **It changes the name, not the gate.** The bearer token below still decides
71142
+ * who gets in, which is §14's rule that identity resolution must never become a way past the
71143
+ * door: knowing that a server was spawned for Ana says nothing about who is making this request.
71144
+ */
71145
+ constructor(handoffSeconds = 10, principal) {
70189
71146
  this.handoffSeconds = handoffSeconds;
70190
71147
  this.handoffExpiresAt = Date.now() + handoffSeconds * 1e3;
71148
+ this.principal = principal ?? _SingleUserIdentity.PRINCIPAL;
71149
+ this.describe = principal === void 0 ? "single user (local)" : `single user \u2014 ${principal.id}`;
70191
71150
  }
70192
71151
  get launchToken() {
70193
71152
  if (this.handoffToken === void 0) throw new Error("handoff token already consumed");
@@ -70234,7 +71193,7 @@ var SingleUserIdentity = class _SingleUserIdentity {
70234
71193
  async authenticate(request) {
70235
71194
  const header = request.headers.authorization;
70236
71195
  if (header === void 0 || !header.startsWith("Bearer ")) return void 0;
70237
- return timingSafeEquals(header.slice("Bearer ".length), this.sessionToken) ? _SingleUserIdentity.PRINCIPAL : void 0;
71196
+ return timingSafeEquals(header.slice("Bearer ".length), this.sessionToken) ? this.principal : void 0;
70238
71197
  }
70239
71198
  };
70240
71199
  function timingSafeEquals(a, b) {
@@ -70693,6 +71652,21 @@ function readVariablesFile(filePath) {
70693
71652
  }
70694
71653
  }
70695
71654
 
71655
+ // src/hostedUser.ts
71656
+ var SOURCES = [
71657
+ /** JupyterHub's own, set in every single-user server it spawns. */
71658
+ "JUPYTERHUB_USER",
71659
+ /** Set by some deployments that front an app without the hub's spawner. */
71660
+ "JUPYTER_USER"
71661
+ ];
71662
+ function hostedUser(env2 = process.env) {
71663
+ for (const source of SOURCES) {
71664
+ const value = env2[source]?.trim();
71665
+ if (value !== void 0 && value.length > 0) return { id: value, source };
71666
+ }
71667
+ return void 0;
71668
+ }
71669
+
70696
71670
  // src/session.ts
70697
71671
  import { watch as fsWatch } from "node:fs";
70698
71672
  import fs24 from "node:fs/promises";
@@ -71225,11 +72199,26 @@ var STREAM_PADDING = `: ${(() => {
71225
72199
  })()}
71226
72200
 
71227
72201
  `;
72202
+ function principalFromPlatform() {
72203
+ const found = hostedUser();
72204
+ return found === void 0 ? void 0 : { id: found.id, displayName: found.id };
72205
+ }
71228
72206
  async function startServer(options) {
71229
72207
  const log = options.logSink ?? ((line) => process.stderr.write(`${line}
71230
72208
  `));
71231
72209
  setFrameAncestors(options.allowFrameAncestors ?? []);
71232
- const identity = options.identity ?? (options.noToken === true ? new OpenIdentity() : new SingleUserIdentity(options.handoffSeconds));
72210
+ const identity = options.identity ?? (options.noToken === true ? new OpenIdentity() : (
72211
+ /*
72212
+ * Named by the platform when it says so, and still gated by the token either way.
72213
+ *
72214
+ * JupyterHub spawns a server per person and sets `JUPYTERHUB_USER` in it, so settings,
72215
+ * secrets and history are filed under that person rather than under "local" — which is
72216
+ * what somebody had otherwise to write a Python function to achieve. Read from this
72217
+ * process's environment, never from a request: see `hostedUser.ts` for why the URL
72218
+ * suffix carrying the same name is not the same fact.
72219
+ */
72220
+ new SingleUserIdentity(options.handoffSeconds, principalFromPlatform())
72221
+ ));
71233
72222
  const roles = options.roles ?? SINGLE_USER_POLICY;
71234
72223
  const sharedStore = options.sharedConfig;
71235
72224
  const sharedSecretStore = new FileSecretStore(path34.join(options.dataDir, "shared-secrets.json"));
@@ -71284,6 +72273,12 @@ async function startServer(options) {
71284
72273
  };
71285
72274
  const connection = {
71286
72275
  transport,
72276
+ /*
72277
+ * Replaced below, once the bridge that owns the state exists. A no-op rather than a missing
72278
+ * field so the object is a complete `Connection` from the moment it is built — a half-built
72279
+ * one handed to anything in between is how a route ends up calling something undefined.
72280
+ */
72281
+ resync: () => void 0,
71287
72282
  deliver: (message3) => {
71288
72283
  for (const listener of listeners) listener(message3);
71289
72284
  },
@@ -71391,6 +72386,9 @@ async function startServer(options) {
71391
72386
  originalDispose();
71392
72387
  session.dispose();
71393
72388
  };
72389
+ connection.resync = () => {
72390
+ session.resync();
72391
+ };
71394
72392
  return connection;
71395
72393
  }
71396
72394
  const server = createServer((request, response) => {
@@ -71483,6 +72481,7 @@ async function startServer(options) {
71483
72481
  if (viaAdminUrl) adminConnections.add(principal.id);
71484
72482
  else adminConnections.delete(principal.id);
71485
72483
  connection.attach(response);
72484
+ connection.resync();
71486
72485
  connection.transport.post({
71487
72486
  type: "hostRole",
71488
72487
  role: isAdminSession(principal) ? "admin" : "user",
@@ -71510,6 +72509,7 @@ async function startServer(options) {
71510
72509
  if (connection === void 0) {
71511
72510
  connection = await openConnection(principal);
71512
72511
  connections.set(principal.id, connection);
72512
+ connection.resync();
71513
72513
  }
71514
72514
  respondJson(response, 200, { messages: connection.drain() });
71515
72515
  return;
@@ -71733,7 +72733,7 @@ function respondJson(response, status, body) {
71733
72733
  }
71734
72734
 
71735
72735
  // src/cli.ts
71736
- var VERSION = true ? "0.70.0" : "unknown (not a packaged build)";
72736
+ var VERSION = true ? "0.77.0" : "unknown (not a packaged build)";
71737
72737
  var compat = installNodeCompat();
71738
72738
  function lastMeaningfulLine(problem) {
71739
72739
  const lines = problem.split(String.fromCharCode(10)).map((line) => line.trim()).filter((line) => line.length > 0 && !line.endsWith(":"));