@moxt-ai/mobius 0.0.47 → 0.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/acp/session-manager.d.ts +2 -1
  2. package/dist/acp/session-manager.d.ts.map +1 -1
  3. package/dist/acp/session-manager.js +38 -23
  4. package/dist/acp/session-manager.js.map +1 -1
  5. package/dist/agent-catalog/agent-specification.d.ts +0 -1
  6. package/dist/agent-catalog/agent-specification.d.ts.map +1 -1
  7. package/dist/agent-catalog/agent-specification.js +0 -2
  8. package/dist/agent-catalog/agent-specification.js.map +1 -1
  9. package/dist/agent-catalog/agents/pi-agent.d.ts +0 -1
  10. package/dist/agent-catalog/agents/pi-agent.d.ts.map +1 -1
  11. package/dist/agent-catalog/agents/pi-agent.js +0 -2
  12. package/dist/agent-catalog/agents/pi-agent.js.map +1 -1
  13. package/dist/agent-catalog/discover-agent.d.ts.map +1 -1
  14. package/dist/agent-catalog/discover-agent.js +2 -2
  15. package/dist/agent-catalog/discover-agent.js.map +1 -1
  16. package/dist/agent-catalog/local-agent.d.ts +1 -2
  17. package/dist/agent-catalog/local-agent.d.ts.map +1 -1
  18. package/dist/agent-catalog/local-agent.js +2 -7
  19. package/dist/agent-catalog/local-agent.js.map +1 -1
  20. package/dist/agent-catalog/publish-agent-catalog.d.ts.map +1 -1
  21. package/dist/agent-catalog/publish-agent-catalog.js +0 -1
  22. package/dist/agent-catalog/publish-agent-catalog.js.map +1 -1
  23. package/dist/artifacts/local-file-streamer.d.ts +3 -0
  24. package/dist/artifacts/local-file-streamer.d.ts.map +1 -0
  25. package/dist/artifacts/local-file-streamer.js +82 -0
  26. package/dist/artifacts/local-file-streamer.js.map +1 -0
  27. package/dist/authorization/local-raster.d.ts +4 -3
  28. package/dist/authorization/local-raster.d.ts.map +1 -1
  29. package/dist/authorization/local-raster.js +22 -12
  30. package/dist/authorization/local-raster.js.map +1 -1
  31. package/dist/cli.js +624 -1673
  32. package/dist/cli.js.map +4 -4
  33. package/dist/index.d.ts +0 -3
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +664 -1704
  36. package/dist/index.js.map +4 -4
  37. package/dist/native-sessions/history-images.js +1 -1
  38. package/dist/native-sessions/history-images.js.map +1 -1
  39. package/dist/pairing/pair-local-machine.d.ts.map +1 -1
  40. package/dist/pairing/pair-local-machine.js +0 -1
  41. package/dist/pairing/pair-local-machine.js.map +1 -1
  42. package/dist/run-daemon.d.ts.map +1 -1
  43. package/dist/run-daemon.js +99 -285
  44. package/dist/run-daemon.js.map +1 -1
  45. package/dist/runtime.js +512 -1388
  46. package/dist/runtime.js.map +4 -4
  47. package/package.json +1 -1
  48. package/dist/bots/bot-context-applicator.d.ts +0 -14
  49. package/dist/bots/bot-context-applicator.d.ts.map +0 -1
  50. package/dist/bots/bot-context-applicator.js +0 -32
  51. package/dist/bots/bot-context-applicator.js.map +0 -1
  52. package/dist/bots/bot-execution-context.d.ts +0 -20
  53. package/dist/bots/bot-execution-context.d.ts.map +0 -1
  54. package/dist/bots/bot-execution-context.js +0 -82
  55. package/dist/bots/bot-execution-context.js.map +0 -1
  56. package/dist/bots/bot-message-command.d.ts +0 -6
  57. package/dist/bots/bot-message-command.d.ts.map +0 -1
  58. package/dist/bots/bot-message-command.js +0 -140
  59. package/dist/bots/bot-message-command.js.map +0 -1
  60. package/dist/bots/bot-outbound-ipc.d.ts +0 -12
  61. package/dist/bots/bot-outbound-ipc.d.ts.map +0 -1
  62. package/dist/bots/bot-outbound-ipc.js +0 -245
  63. package/dist/bots/bot-outbound-ipc.js.map +0 -1
  64. package/dist/bots/local-bot-execution-authorizer.d.ts +0 -23
  65. package/dist/bots/local-bot-execution-authorizer.d.ts.map +0 -1
  66. package/dist/bots/local-bot-execution-authorizer.js +0 -62
  67. package/dist/bots/local-bot-execution-authorizer.js.map +0 -1
package/dist/cli.js CHANGED
@@ -6,12 +6,12 @@ var __export = (target, all2) => {
6
6
  };
7
7
 
8
8
  // src/cli.ts
9
- import { mkdir as mkdir5 } from "node:fs/promises";
9
+ import { mkdir as mkdir4 } from "node:fs/promises";
10
10
 
11
11
  // package.json
12
12
  var package_default = {
13
13
  name: "@moxt-ai/mobius",
14
- version: "0.0.47",
14
+ version: "0.0.49",
15
15
  description: "Mobius CLI for pairing and running local AI agent services.",
16
16
  type: "module",
17
17
  bin: {
@@ -145,12 +145,12 @@ var ExecutableIdentity = class {
145
145
  realPath;
146
146
  requestedPath;
147
147
  size;
148
- constructor(requestedPath, realPath_, device, inode, size, changedAtMilliseconds) {
148
+ constructor(requestedPath2, realPath_, device, inode, size, changedAtMilliseconds) {
149
149
  this.changedAtMilliseconds = changedAtMilliseconds;
150
150
  this.device = device;
151
151
  this.inode = inode;
152
152
  this.realPath = realPath_;
153
- this.requestedPath = requestedPath;
153
+ this.requestedPath = requestedPath2;
154
154
  this.size = size;
155
155
  }
156
156
  matches = (candidate) => this.requestedPath === candidate.requestedPath && this.realPath === candidate.realPath && this.device === candidate.device && this.inode === candidate.inode && this.size === candidate.size && this.changedAtMilliseconds === candidate.changedAtMilliseconds;
@@ -190,8 +190,8 @@ function executableExtensions(executableName, environment, platform) {
190
190
  const extensions = configured.split(";").map((extension2) => extension2.trim()).filter((extension2) => extension2.length > 0).map((extension2) => extension2.startsWith(".") ? extension2 : `.${extension2}`);
191
191
  return extensions.length > 0 ? extensions : [".EXE"];
192
192
  }
193
- async function resolveExecutablePath(requestedPath, platform = process.platform) {
194
- const absoluteRequestedPath = resolve(requestedPath);
193
+ async function resolveExecutablePath(requestedPath2, platform = process.platform) {
194
+ const absoluteRequestedPath = resolve(requestedPath2);
195
195
  try {
196
196
  const resolvedPath = await realpath(absoluteRequestedPath);
197
197
  const metadata = await stat(resolvedPath);
@@ -224,8 +224,8 @@ async function findExecutableOnPath(executableName, environment, platform = proc
224
224
  continue;
225
225
  }
226
226
  for (const extension2 of extensions) {
227
- const requestedPath = resolve(join(entry, `${executableName}${extension2}`));
228
- const executable = await resolveExecutablePath(requestedPath, platform);
227
+ const requestedPath2 = resolve(join(entry, `${executableName}${extension2}`));
228
+ const executable = await resolveExecutablePath(requestedPath2, platform);
229
229
  if (executable !== null) {
230
230
  return executable;
231
231
  }
@@ -4334,7 +4334,7 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
4334
4334
  defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
4335
4335
  defineLazyInternal(inst, "values", (zod) => {
4336
4336
  if (zod.def.options.every((o) => o._zod.values)) {
4337
- return new Set(zod.def.options.flatMap((option2) => Array.from(option2._zod.values)));
4337
+ return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));
4338
4338
  }
4339
4339
  return void 0;
4340
4340
  });
@@ -4352,8 +4352,8 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
4352
4352
  }
4353
4353
  let async = false;
4354
4354
  const results = [];
4355
- for (const option2 of def.options) {
4356
- const result = option2._zod.run({
4355
+ for (const option of def.options) {
4356
+ const result = option._zod.run({
4357
4357
  value: payload.value,
4358
4358
  issues: []
4359
4359
  }, ctx);
@@ -4412,8 +4412,8 @@ var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
4412
4412
  }
4413
4413
  let async = false;
4414
4414
  const results = [];
4415
- for (const option2 of def.options) {
4416
- const result = option2._zod.run({
4415
+ for (const option of def.options) {
4416
+ const result = option._zod.run({
4417
4417
  value: payload.value,
4418
4418
  issues: []
4419
4419
  }, ctx);
@@ -4438,24 +4438,24 @@ function getDiscriminatedOption(union2, value) {
4438
4438
  map2 = discriminatorMap(internals.def);
4439
4439
  internals.bag.optionsMap = map2;
4440
4440
  }
4441
- const option2 = map2.get(value);
4442
- if (option2 === null)
4441
+ const option = map2.get(value);
4442
+ if (option === null)
4443
4443
  throw new Error(`Ambiguous discriminator value "${String(value)}"`);
4444
- return option2;
4444
+ return option;
4445
4445
  }
4446
4446
  function discriminatorMap(def) {
4447
4447
  const map2 = /* @__PURE__ */ new Map();
4448
- for (const option2 of def.options) {
4449
- const values = option2._zod.propValues?.[def.discriminator];
4448
+ for (const option of def.options) {
4449
+ const values = option._zod.propValues?.[def.discriminator];
4450
4450
  if (!values || values.size === 0)
4451
- throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option2)}"`);
4451
+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
4452
4452
  for (const value of values) {
4453
4453
  if (map2.has(value)) {
4454
4454
  if (value !== void 0)
4455
4455
  throw new Error(`Duplicate discriminator value "${String(value)}"`);
4456
4456
  map2.set(value, null);
4457
4457
  } else {
4458
- map2.set(value, option2);
4458
+ map2.set(value, option);
4459
4459
  }
4460
4460
  }
4461
4461
  }
@@ -4468,10 +4468,10 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
4468
4468
  defineLazyInternal(inst, "propValues", (zod) => {
4469
4469
  const propValues = {};
4470
4470
  let undefinedCount = 0;
4471
- for (const option2 of zod.def.options) {
4472
- const pv = option2._zod.propValues;
4471
+ for (const option of zod.def.options) {
4472
+ const pv = option._zod.propValues;
4473
4473
  if (!pv || Object.keys(pv).length === 0)
4474
- throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option2)}"`);
4474
+ throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);
4475
4475
  if (pv[zod.def.discriminator]?.has(void 0))
4476
4476
  undefinedCount++;
4477
4477
  for (const [k, v] of Object.entries(pv)) {
@@ -4487,8 +4487,8 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
4487
4487
  propValues[zod.def.discriminator]?.delete(void 0);
4488
4488
  return propValues;
4489
4489
  });
4490
- def.options.forEach((option2, i) => {
4491
- const propShape = rawShape(option2._zod.def);
4490
+ def.options.forEach((option, i) => {
4491
+ const propShape = rawShape(option._zod.def);
4492
4492
  if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {
4493
4493
  throw new Error(`Invalid discriminated union option at index "${i}"`);
4494
4494
  }
@@ -14788,8 +14788,8 @@ function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) {
14788
14788
  doc.write(`let ${outputVar};`);
14789
14789
  let firstBranch = true;
14790
14790
  const claimed = /* @__PURE__ */ new Set();
14791
- for (const option2 of def.options) {
14792
- const values = option2._zod.propValues?.[def.discriminator];
14791
+ for (const option of def.options) {
14792
+ const values = option._zod.propValues?.[def.discriminator];
14793
14793
  if (!values || values.size === 0) {
14794
14794
  throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values");
14795
14795
  }
@@ -14803,7 +14803,7 @@ function generateDiscriminatedUnionCheck(doc, ctx, def, accessor) {
14803
14803
  const prefix = firstBranch ? "if" : "else if";
14804
14804
  doc.write(`${prefix} (${conditions.join(" || ")}) {`);
14805
14805
  doc.indented((d) => {
14806
- const branchOutput = generateCheck(d, ctx, option2, accessor);
14806
+ const branchOutput = generateCheck(d, ctx, option, accessor);
14807
14807
  d.write(`${outputVar} = ${branchOutput};`);
14808
14808
  });
14809
14809
  doc.write(`}`);
@@ -16385,14 +16385,14 @@ function compactTypeUnion(schema) {
16385
16385
  if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0)
16386
16386
  return;
16387
16387
  const types = [];
16388
- for (const option2 of options) {
16389
- if (!option2 || typeof option2 !== "object")
16388
+ for (const option of options) {
16389
+ if (!option || typeof option !== "object")
16390
16390
  return;
16391
- compactTypeUnion(option2);
16392
- const keys = Object.keys(option2);
16391
+ compactTypeUnion(option);
16392
+ const keys = Object.keys(option);
16393
16393
  if (keys.length !== 1 || keys[0] !== "type")
16394
16394
  return;
16395
- const type = option2.type;
16395
+ const type = option.type;
16396
16396
  for (const member of Array.isArray(type) ? type : [type]) {
16397
16397
  if (typeof member !== "string")
16398
16398
  return;
@@ -16682,8 +16682,8 @@ function isTransforming(_schema, _ctx) {
16682
16682
  return false;
16683
16683
  }
16684
16684
  if (def.type === "union") {
16685
- for (const option2 of def.options) {
16686
- if (isTransforming(option2, ctx))
16685
+ for (const option of def.options) {
16686
+ if (isTransforming(option, ctx))
16687
16687
  return true;
16688
16688
  }
16689
16689
  return false;
@@ -20431,6 +20431,11 @@ var AGENT_INSTALL_CANCELLED_KIND = "agent.integration.install.cancelled";
20431
20431
  var AGENT_SETTINGS_DISCOVER_KIND = "agent.settings.discover";
20432
20432
  var AGENT_SETTINGS_DISCOVERED_KIND = "agent.settings.discovered";
20433
20433
  var AGENT_SETTINGS_DISCOVERY_FAILED_KIND = "agent.settings.discovery.failed";
20434
+ var FILE_READ_KIND = "file.read";
20435
+ var FILE_BEGIN_KIND = "file.begin";
20436
+ var FILE_CHUNK_KIND = "file.chunk";
20437
+ var FILE_END_KIND = "file.end";
20438
+ var FILE_FAILED_KIND = "file.failed";
20434
20439
  var IDENTIFIER_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
20435
20440
  var DIRECTORY_IDENTIFIER_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
20436
20441
  var IDENTIFIER = external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN);
@@ -20441,6 +20446,41 @@ var workspaceEntrySchema = external_exports.strictObject({
20441
20446
  directoryId: DIRECTORY_IDENTIFIER,
20442
20447
  name: external_exports.string().min(1).max(255)
20443
20448
  }).readonly();
20449
+ var fileReadCommandSchema = external_exports.strictObject({
20450
+ kind: external_exports.literal(FILE_READ_KIND),
20451
+ maxBytes: external_exports.number().int().positive().max(128 * 1024 * 1024),
20452
+ requestId: IDENTIFIER,
20453
+ sessionId: IDENTIFIER,
20454
+ path: external_exports.string().min(1).max(4096)
20455
+ }).readonly();
20456
+ var fileBeginEventSchema = external_exports.strictObject({
20457
+ byteLength: external_exports.number().int().positive().max(128 * 1024 * 1024),
20458
+ kind: external_exports.literal(FILE_BEGIN_KIND),
20459
+ mediaType: external_exports.string().min(1).max(255),
20460
+ modifiedAt: external_exports.iso.datetime({ offset: true }),
20461
+ name: external_exports.string().min(1).max(500),
20462
+ requestId: IDENTIFIER,
20463
+ sessionId: IDENTIFIER
20464
+ }).readonly();
20465
+ var fileChunkEventSchema = external_exports.strictObject({
20466
+ data: external_exports.string().min(1).max(4e5),
20467
+ kind: external_exports.literal(FILE_CHUNK_KIND),
20468
+ requestId: IDENTIFIER,
20469
+ sequence: external_exports.number().int().nonnegative().max(1024),
20470
+ sessionId: IDENTIFIER
20471
+ }).readonly();
20472
+ var fileEndEventSchema = external_exports.strictObject({
20473
+ kind: external_exports.literal(FILE_END_KIND),
20474
+ requestId: IDENTIFIER,
20475
+ sessionId: IDENTIFIER
20476
+ }).readonly();
20477
+ var fileFailedEventSchema = external_exports.strictObject({
20478
+ code: IDENTIFIER,
20479
+ kind: external_exports.literal(FILE_FAILED_KIND),
20480
+ message: external_exports.string().min(1).max(500),
20481
+ requestId: IDENTIFIER,
20482
+ sessionId: IDENTIFIER
20483
+ }).readonly();
20444
20484
  var configValueSchema = external_exports.strictObject({
20445
20485
  description: SHORT_TEXT,
20446
20486
  groupId: external_exports.string().max(128),
@@ -20657,7 +20697,7 @@ var sessionPrepareCommandSchema = external_exports.strictObject({
20657
20697
  kind: external_exports.literal(SESSION_PREPARE_KIND),
20658
20698
  requestId: IDENTIFIER,
20659
20699
  sessionState: external_exports.literal("provisioned").optional(),
20660
- /** @deprecated Reserved for the legacy Bot Agent-configuration endpoint. */
20700
+ /** Marks an inspection-only Session preparation. */
20661
20701
  transient: external_exports.boolean().optional()
20662
20702
  }).superRefine((command, context) => {
20663
20703
  if (command.transient === true && command.sessionState === "provisioned") {
@@ -20878,11 +20918,15 @@ var decodeRecordedAgentContentValue = (value) => decodeValue(value, recordedDisp
20878
20918
  var decodePromptImagesValue = (value) => decodeValue(value, external_exports.array(promptImageSchema).max(8).readonly());
20879
20919
  var decodePromptResourcesValue = (value) => decodeValue(value, external_exports.array(promptResourceSchema).max(16).readonly());
20880
20920
  var decodeSessionConfigurationSelections = (value) => decodeValue(value, sessionConfigurationSelectionsSchema);
20881
- var decodeAgentExecutionConfiguration = (value) => decodeValue(value, agentExecutionConfigurationSchema);
20882
20921
  var encode3 = (message, schema) => JSON.stringify(decodeValue(message, schema));
20883
20922
  var decodeAgentSettingsDiscoverCommand = (encoded) => decode3(encoded, agentSettingsDiscoverCommandSchema);
20884
20923
  var encodeAgentSettingsDiscoveredEvent = (message) => encode3(message, agentSettingsDiscoveredEventSchema);
20885
20924
  var encodeAgentSettingsDiscoveryFailedEvent = (message) => encode3(message, agentSettingsDiscoveryFailedEventSchema);
20925
+ var decodeFileReadCommand = (encoded) => decode3(encoded, fileReadCommandSchema);
20926
+ var encodeFileBeginEvent = (message) => encode3(message, fileBeginEventSchema);
20927
+ var encodeFileChunkEvent = (message) => encode3(message, fileChunkEventSchema);
20928
+ var encodeFileEndEvent = (message) => encode3(message, fileEndEventSchema);
20929
+ var encodeFileFailedEvent = (message) => encode3(message, fileFailedEventSchema);
20886
20930
  var decodeWorkspaceListCommand = (encoded) => decode3(encoded, workspaceListCommandSchema);
20887
20931
  var encodeWorkspaceEntriesEvent = (message) => encode3(message, workspaceEntriesEventSchema);
20888
20932
  var decodeSessionPrepareCommand = (encoded) => decode3(encoded, sessionPrepareCommandSchema);
@@ -21362,325 +21406,6 @@ function encodeSessionFailedEvent(message) {
21362
21406
  return JSON.stringify(decodeSessionFailedEvent(JSON.stringify(message)));
21363
21407
  }
21364
21408
 
21365
- // ../protocol/src/bot.ts
21366
- var BOT_SESSION_PROMPT_KIND = "bot.session.prompt";
21367
- var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
21368
- var DIRECTORY_IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
21369
- var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
21370
- var SHA256_PATTERN = /^[a-f0-9]{64}$/;
21371
- var MAX_INSTRUCTIONS_LENGTH = 1e5;
21372
- var BotDeliveryTargetReference = class {
21373
- alias;
21374
- deliveryTargetId;
21375
- constructor(alias, deliveryTargetId) {
21376
- this.alias = alias;
21377
- this.deliveryTargetId = deliveryTargetId;
21378
- }
21379
- };
21380
- var BotReplyRoute = class {
21381
- };
21382
- var OwnerBotReplyRoute = class extends BotReplyRoute {
21383
- kind = "owner";
21384
- };
21385
- var BotConnectionReplyRoute = class extends BotReplyRoute {
21386
- connectionId;
21387
- deliveryTargetId;
21388
- kind = "connection";
21389
- constructor(connectionId, deliveryTargetId) {
21390
- super();
21391
- this.connectionId = connectionId;
21392
- this.deliveryTargetId = deliveryTargetId;
21393
- }
21394
- };
21395
- var BotSessionPromptCommand = class {
21396
- additionalDirectoryIds;
21397
- agentId;
21398
- allowedDeliveryTargets;
21399
- behaviorDigest;
21400
- behaviorInstructions;
21401
- behaviorRevisionId;
21402
- bindingId;
21403
- bindingRevision;
21404
- botId;
21405
- commandId;
21406
- conversationId;
21407
- directoryId;
21408
- disposition;
21409
- executionCapabilityId;
21410
- executionCapabilitySecret;
21411
- executionDeadlineAt;
21412
- executionId;
21413
- executionConfiguration;
21414
- images;
21415
- kind = BOT_SESSION_PROMPT_KIND;
21416
- prompt;
21417
- replyRoute;
21418
- resources;
21419
- sessionConfigurations;
21420
- sessionId;
21421
- targetCommandId;
21422
- turnId;
21423
- constructor(sessionId, commandId, agentId, bindingId, directoryId2, additionalDirectoryIds, images, resources, prompt, executionId, executionCapabilityId, executionCapabilitySecret, executionDeadlineAt, botId, conversationId, turnId, behaviorRevisionId, bindingRevision, behaviorInstructions, behaviorDigest, allowedDeliveryTargets, replyRoute, executionConfiguration, sessionConfigurations = [], disposition = SessionPromptDisposition.Reject, targetCommandId = "") {
21424
- this.sessionId = sessionId;
21425
- this.commandId = commandId;
21426
- this.agentId = agentId;
21427
- this.bindingId = bindingId;
21428
- this.directoryId = directoryId2;
21429
- this.disposition = disposition;
21430
- this.additionalDirectoryIds = Object.freeze([...additionalDirectoryIds]);
21431
- this.images = Object.freeze([...images]);
21432
- this.resources = Object.freeze([...resources]);
21433
- this.prompt = prompt;
21434
- this.executionId = executionId;
21435
- this.executionCapabilityId = executionCapabilityId;
21436
- this.executionCapabilitySecret = executionCapabilitySecret;
21437
- this.executionDeadlineAt = executionDeadlineAt;
21438
- this.botId = botId;
21439
- this.conversationId = conversationId;
21440
- this.turnId = turnId;
21441
- this.behaviorRevisionId = behaviorRevisionId;
21442
- this.bindingRevision = bindingRevision;
21443
- this.behaviorInstructions = behaviorInstructions;
21444
- this.behaviorDigest = behaviorDigest;
21445
- this.allowedDeliveryTargets = Object.freeze(
21446
- allowedDeliveryTargets.map(
21447
- (target) => new BotDeliveryTargetReference(target.alias, target.deliveryTargetId)
21448
- )
21449
- );
21450
- this.replyRoute = replyRoute;
21451
- this.executionConfiguration = decodeAgentExecutionConfiguration(executionConfiguration);
21452
- this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
21453
- this.targetCommandId = targetCommandId;
21454
- }
21455
- toJSON() {
21456
- const { disposition, sessionConfigurations, targetCommandId, ...command } = this;
21457
- return {
21458
- ...command,
21459
- ...sessionConfigurations.length === 0 ? {} : { sessionConfigurations },
21460
- ...disposition === SessionPromptDisposition.Reject ? {} : { disposition, targetCommandId }
21461
- };
21462
- }
21463
- };
21464
- function isRecord3(value) {
21465
- return typeof value === "object" && value !== null && !Array.isArray(value);
21466
- }
21467
- function parseJson3(encoded) {
21468
- let value;
21469
- try {
21470
- value = JSON.parse(encoded);
21471
- } catch (cause) {
21472
- throw new ProtocolMessageError("Message is not valid JSON", { cause });
21473
- }
21474
- if (!isRecord3(value)) {
21475
- throw new ProtocolMessageError("Message must be a JSON object");
21476
- }
21477
- return value;
21478
- }
21479
- function assertExactKeys2(value, expected) {
21480
- const keys = Object.keys(value);
21481
- if (keys.length !== expected.length || keys.some((key) => !expected.includes(key))) {
21482
- throw new ProtocolMessageError("Message fields do not match the Bot protocol");
21483
- }
21484
- }
21485
- function assertKeysWithOptional(value, expected, optional2) {
21486
- const keys = Object.keys(value);
21487
- if (keys.length < expected.length || keys.length > expected.length + optional2.length || expected.some((key) => !Object.hasOwn(value, key)) || keys.some((key) => !expected.includes(key) && !optional2.includes(key))) {
21488
- throw new ProtocolMessageError("Message fields do not match the Bot protocol");
21489
- }
21490
- }
21491
- function readText2(value, key, maximumLength, allowEmpty) {
21492
- const field = value[key];
21493
- if (typeof field !== "string" || field.length > maximumLength || !allowEmpty && field.length === 0) {
21494
- throw new ProtocolMessageError(`Invalid Bot protocol field: ${key}`);
21495
- }
21496
- return field;
21497
- }
21498
- function readIdentifier2(value, key) {
21499
- const field = readText2(value, key, 128, false);
21500
- if (!IDENTIFIER_PATTERN3.test(field)) {
21501
- throw new ProtocolMessageError(`Invalid Bot identifier field: ${key}`);
21502
- }
21503
- return field;
21504
- }
21505
- function readDirectoryIdentifier2(value, key) {
21506
- const field = readText2(value, key, 2048, false);
21507
- if (!DIRECTORY_IDENTIFIER_PATTERN3.test(field)) {
21508
- throw new ProtocolMessageError(`Invalid Bot directory field: ${key}`);
21509
- }
21510
- return field;
21511
- }
21512
- function readInteger(value, key) {
21513
- const field = value[key];
21514
- if (typeof field !== "number" || !Number.isSafeInteger(field) || field < 1) {
21515
- throw new ProtocolMessageError(`Invalid Bot integer field: ${key}`);
21516
- }
21517
- return field;
21518
- }
21519
- function readTimestamp(value, key) {
21520
- const field = readText2(value, key, 64, false);
21521
- if (Number.isNaN(Date.parse(field))) {
21522
- throw new ProtocolMessageError(`Invalid Bot timestamp field: ${key}`);
21523
- }
21524
- return field;
21525
- }
21526
- function readDigest(value, key) {
21527
- const field = readText2(value, key, 64, false);
21528
- if (!SHA256_PATTERN.test(field)) {
21529
- throw new ProtocolMessageError(`Invalid Bot digest field: ${key}`);
21530
- }
21531
- return field;
21532
- }
21533
- function readToken(value, key) {
21534
- const field = readText2(value, key, 256, false);
21535
- if (!TOKEN_PATTERN.test(field)) {
21536
- throw new ProtocolMessageError(`Invalid Bot token field: ${key}`);
21537
- }
21538
- return field;
21539
- }
21540
- function readIdentifiers(value, key, maximumCount) {
21541
- const field = value[key];
21542
- if (!Array.isArray(field) || field.length > maximumCount) {
21543
- throw new ProtocolMessageError(`Invalid Bot identifier list: ${key}`);
21544
- }
21545
- const identifiers = [];
21546
- const unique = /* @__PURE__ */ new Set();
21547
- for (const candidate of field) {
21548
- if (typeof candidate !== "string" || !IDENTIFIER_PATTERN3.test(candidate) || unique.has(candidate)) {
21549
- throw new ProtocolMessageError(`Invalid Bot identifier list: ${key}`);
21550
- }
21551
- unique.add(candidate);
21552
- identifiers.push(candidate);
21553
- }
21554
- return Object.freeze(identifiers);
21555
- }
21556
- function readTargets(value, key) {
21557
- const field = value[key];
21558
- if (!Array.isArray(field) || field.length > 64) {
21559
- throw new ProtocolMessageError(`Invalid Bot delivery targets: ${key}`);
21560
- }
21561
- const targets = [];
21562
- const identifiers = /* @__PURE__ */ new Set();
21563
- const aliases = /* @__PURE__ */ new Set();
21564
- for (const candidate of field) {
21565
- if (!isRecord3(candidate)) {
21566
- throw new ProtocolMessageError(`Invalid Bot delivery targets: ${key}`);
21567
- }
21568
- assertExactKeys2(candidate, ["alias", "deliveryTargetId"]);
21569
- const alias = readIdentifier2(candidate, "alias");
21570
- const deliveryTargetId = readIdentifier2(candidate, "deliveryTargetId");
21571
- if (aliases.has(alias) || identifiers.has(deliveryTargetId)) {
21572
- throw new ProtocolMessageError(`Duplicate Bot delivery target: ${key}`);
21573
- }
21574
- aliases.add(alias);
21575
- identifiers.add(deliveryTargetId);
21576
- targets.push(new BotDeliveryTargetReference(alias, deliveryTargetId));
21577
- }
21578
- return Object.freeze(targets);
21579
- }
21580
- function readSessionConfigurations(value) {
21581
- if (!Object.hasOwn(value, "sessionConfigurations")) {
21582
- return [];
21583
- }
21584
- return decodeSessionConfigurationSelections(value["sessionConfigurations"]);
21585
- }
21586
- function readReplyRoute(value) {
21587
- if (!isRecord3(value)) {
21588
- throw new ProtocolMessageError("Invalid Bot reply route");
21589
- }
21590
- const kind = readText2(value, "kind", 32, false);
21591
- if (kind === "owner") {
21592
- assertExactKeys2(value, ["kind"]);
21593
- return new OwnerBotReplyRoute();
21594
- }
21595
- if (kind === "connection") {
21596
- assertExactKeys2(value, ["connectionId", "deliveryTargetId", "kind"]);
21597
- return new BotConnectionReplyRoute(
21598
- readIdentifier2(value, "connectionId"),
21599
- readIdentifier2(value, "deliveryTargetId")
21600
- );
21601
- }
21602
- throw new ProtocolMessageError("Invalid Bot reply route");
21603
- }
21604
- function decodeBotSessionPromptCommand(encoded) {
21605
- const value = parseJson3(encoded);
21606
- assertKeysWithOptional(
21607
- value,
21608
- [
21609
- "additionalDirectoryIds",
21610
- "agentId",
21611
- "allowedDeliveryTargets",
21612
- "behaviorDigest",
21613
- "behaviorInstructions",
21614
- "behaviorRevisionId",
21615
- "bindingId",
21616
- "bindingRevision",
21617
- "botId",
21618
- "commandId",
21619
- "conversationId",
21620
- "directoryId",
21621
- "executionCapabilityId",
21622
- "executionCapabilitySecret",
21623
- "executionDeadlineAt",
21624
- "executionId",
21625
- "executionConfiguration",
21626
- "images",
21627
- "kind",
21628
- "prompt",
21629
- "replyRoute",
21630
- "resources",
21631
- "sessionId",
21632
- "turnId"
21633
- ],
21634
- ["disposition", "sessionConfigurations", "targetCommandId"]
21635
- );
21636
- if (value["kind"] !== BOT_SESSION_PROMPT_KIND) {
21637
- throw new ProtocolMessageError("Invalid Bot Session prompt kind");
21638
- }
21639
- const rawDisposition = value["disposition"];
21640
- let disposition;
21641
- if (rawDisposition === void 0 || rawDisposition === SessionPromptDisposition.Reject) {
21642
- disposition = SessionPromptDisposition.Reject;
21643
- } else if (rawDisposition === SessionPromptDisposition.Queue) {
21644
- disposition = SessionPromptDisposition.Queue;
21645
- } else if (rawDisposition === SessionPromptDisposition.Steer) {
21646
- disposition = SessionPromptDisposition.Steer;
21647
- } else {
21648
- throw new ProtocolMessageError("Invalid Bot Session prompt disposition");
21649
- }
21650
- const targetCommandId = value["targetCommandId"] === void 0 ? "" : readText2(value, "targetCommandId", 128, false);
21651
- if (disposition === SessionPromptDisposition.Reject && targetCommandId.length > 0 || disposition !== SessionPromptDisposition.Reject && !IDENTIFIER_PATTERN3.test(targetCommandId)) {
21652
- throw new ProtocolMessageError("Bot Session prompt disposition has an invalid target command");
21653
- }
21654
- return new BotSessionPromptCommand(
21655
- readIdentifier2(value, "sessionId"),
21656
- readIdentifier2(value, "commandId"),
21657
- readIdentifier2(value, "agentId"),
21658
- readIdentifier2(value, "bindingId"),
21659
- readDirectoryIdentifier2(value, "directoryId"),
21660
- readIdentifiers(value, "additionalDirectoryIds", 16),
21661
- decodePromptImagesValue(value["images"]),
21662
- decodePromptResourcesValue(value["resources"]),
21663
- readText2(value, "prompt", 1e4, false),
21664
- readIdentifier2(value, "executionId"),
21665
- readIdentifier2(value, "executionCapabilityId"),
21666
- readToken(value, "executionCapabilitySecret"),
21667
- readTimestamp(value, "executionDeadlineAt"),
21668
- readIdentifier2(value, "botId"),
21669
- readIdentifier2(value, "conversationId"),
21670
- readIdentifier2(value, "turnId"),
21671
- readIdentifier2(value, "behaviorRevisionId"),
21672
- readInteger(value, "bindingRevision"),
21673
- readText2(value, "behaviorInstructions", MAX_INSTRUCTIONS_LENGTH, true),
21674
- readDigest(value, "behaviorDigest"),
21675
- readTargets(value, "allowedDeliveryTargets"),
21676
- readReplyRoute(value["replyRoute"]),
21677
- decodeAgentExecutionConfiguration(value["executionConfiguration"]),
21678
- readSessionConfigurations(value),
21679
- disposition,
21680
- targetCommandId
21681
- );
21682
- }
21683
-
21684
21409
  // ../protocol/src/mobius-api.ts
21685
21410
  var MOBIUS_API_PREFIX = "/mobius/api";
21686
21411
  var API_PREFIX_PATTERN = /^\/[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*$/;
@@ -21893,13 +21618,13 @@ var SessionEventRejectionCode = {
21893
21618
  SessionNotFound: "session_not_found",
21894
21619
  SessionRejected: "session_rejected"
21895
21620
  };
21896
- var IDENTIFIER_PATTERN4 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
21621
+ var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
21897
21622
  var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
21898
21623
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
21899
21624
  var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
21900
21625
  var eventSourceSchema = external_exports.discriminatedUnion("kind", [
21901
21626
  external_exports.strictObject({
21902
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21627
+ attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21903
21628
  kind: external_exports.literal("attempt"),
21904
21629
  sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
21905
21630
  }).readonly(),
@@ -21909,41 +21634,41 @@ var eventSourceSchema = external_exports.discriminatedUnion("kind", [
21909
21634
  }).readonly()
21910
21635
  ]);
21911
21636
  var eventEnvelopeSchema = external_exports.strictObject({
21912
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21637
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21913
21638
  kind: external_exports.literal(SESSION_EVENT_KIND),
21914
21639
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21915
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21640
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21916
21641
  source: eventSourceSchema
21917
21642
  }).readonly();
21918
21643
  var committedEventSchema = external_exports.strictObject({
21919
21644
  cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
21920
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21645
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21921
21646
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
21922
21647
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21923
21648
  recordedAt: external_exports.string().datetime({ offset: true }),
21924
21649
  sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
21925
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21650
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21926
21651
  source: eventSourceSchema
21927
21652
  }).readonly();
21928
21653
  var eventAcknowledgementSchema = external_exports.strictObject({
21929
21654
  cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
21930
21655
  duplicate: external_exports.boolean(),
21931
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21656
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21932
21657
  kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
21933
21658
  sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
21934
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4)
21659
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21935
21660
  }).readonly();
21936
21661
  var eventDeferredSchema = external_exports.strictObject({
21937
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21662
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21938
21663
  kind: external_exports.literal(SESSION_EVENT_DEFERRED_KIND),
21939
21664
  retryAfterMilliseconds: external_exports.number().int().min(100).max(6e4),
21940
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4)
21665
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21941
21666
  }).readonly();
21942
21667
  var eventRejectionSchema = external_exports.strictObject({
21943
21668
  code: external_exports.enum(SessionEventRejectionCode),
21944
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21669
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21945
21670
  kind: external_exports.literal(SESSION_EVENT_REJECTED_KIND),
21946
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4)
21671
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21947
21672
  }).readonly();
21948
21673
  function decode5(encoded, schema) {
21949
21674
  let value;
@@ -22194,11 +21919,7 @@ var LocalAgentDefinition = class _LocalAgentDefinition {
22194
21919
  id;
22195
21920
  label;
22196
21921
  permissionProfile;
22197
- promptTimeoutMilliseconds;
22198
- constructor(id, label, command, arguments_, environment = {}, adapterVersion = "", agentVersion = "", adapterIdentity = readTrustedIdentity(command), agentIdentity = adapterIdentity, promptTimeoutMilliseconds = 30 * 60 * 1e3, capabilities = unsupportedSessionCapabilities(), permissionProfile = permissionProfileForAgent(id)) {
22199
- if (!Number.isSafeInteger(promptTimeoutMilliseconds) || promptTimeoutMilliseconds < 1) {
22200
- throw new Error("The local Agent prompt deadline is invalid");
22201
- }
21922
+ constructor(id, label, command, arguments_, environment = {}, adapterVersion = "", agentVersion = "", adapterIdentity = readTrustedIdentity(command), agentIdentity = adapterIdentity, capabilities = unsupportedSessionCapabilities(), permissionProfile = permissionProfileForAgent(id)) {
22202
21923
  this.adapterIdentity = adapterIdentity;
22203
21924
  this.adapterPath = adapterIdentity.realPath;
22204
21925
  this.adapterVersion = adapterVersion;
@@ -22208,7 +21929,6 @@ var LocalAgentDefinition = class _LocalAgentDefinition {
22208
21929
  this.id = id;
22209
21930
  this.label = label;
22210
21931
  this.permissionProfile = permissionProfile;
22211
- this.promptTimeoutMilliseconds = promptTimeoutMilliseconds;
22212
21932
  this.command = adapterIdentity.realPath;
22213
21933
  this.arguments = Object.freeze([...arguments_]);
22214
21934
  this.environment = permissionProfile.apply(environment, permissionProfile.currentMode(environment));
@@ -22227,7 +21947,6 @@ var LocalAgentDefinition = class _LocalAgentDefinition {
22227
21947
  this.agentVersion,
22228
21948
  this.adapterIdentity,
22229
21949
  this.agentIdentity,
22230
- this.promptTimeoutMilliseconds,
22231
21950
  this.capabilities,
22232
21951
  this.permissionProfile
22233
21952
  );
@@ -22529,7 +22248,7 @@ var ManagedNpmPackageError = class extends Error {
22529
22248
  this.name = "ManagedNpmPackageError";
22530
22249
  }
22531
22250
  };
22532
- function isRecord4(value) {
22251
+ function isRecord3(value) {
22533
22252
  return typeof value === "object" && value !== null && !Array.isArray(value);
22534
22253
  }
22535
22254
  function packagePath(root, packageName) {
@@ -22551,7 +22270,7 @@ async function readJsonRecord(path2, maximumBytes) {
22551
22270
  );
22552
22271
  }
22553
22272
  const value = JSON.parse(await handle.readFile({ encoding: "utf8" }));
22554
- if (!isRecord4(value)) {
22273
+ if (!isRecord3(value)) {
22555
22274
  throw new ManagedNpmPackageError(
22556
22275
  "managed_package_verification_failed",
22557
22276
  "The managed npm package metadata is invalid"
@@ -22577,7 +22296,7 @@ function readBinPath(packageMetadata, executableName) {
22577
22296
  if (typeof bin === "string") {
22578
22297
  return bin;
22579
22298
  }
22580
- if (isRecord4(bin) && typeof bin[executableName] === "string") {
22299
+ if (isRecord3(bin) && typeof bin[executableName] === "string") {
22581
22300
  return bin[executableName];
22582
22301
  }
22583
22302
  throw new ManagedNpmPackageError(
@@ -22593,7 +22312,7 @@ function verifyPackageLockEntry(lock, definition2, verifyDependencyClosure) {
22593
22312
  );
22594
22313
  }
22595
22314
  const packages = lock["packages"];
22596
- if (!isRecord4(packages)) {
22315
+ if (!isRecord3(packages)) {
22597
22316
  throw new ManagedNpmPackageError(
22598
22317
  "managed_package_verification_failed",
22599
22318
  "The managed npm package lockfile is invalid"
@@ -22607,7 +22326,7 @@ function verifyPackageLockEntry(lock, definition2, verifyDependencyClosure) {
22607
22326
  if (verifyDependencyClosure && normalizedKey.length > 0) {
22608
22327
  let resolved;
22609
22328
  try {
22610
- if (!normalizedKey.split("/").includes("node_modules") || !isRecord4(candidate) || typeof candidate["version"] !== "string" || candidate["version"].length === 0 || typeof candidate["integrity"] !== "string" || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(candidate["integrity"]) || typeof candidate["resolved"] !== "string") {
22329
+ if (!normalizedKey.split("/").includes("node_modules") || !isRecord3(candidate) || typeof candidate["version"] !== "string" || candidate["version"].length === 0 || typeof candidate["integrity"] !== "string" || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(candidate["integrity"]) || typeof candidate["resolved"] !== "string") {
22611
22330
  throw new Error("Invalid locked dependency");
22612
22331
  }
22613
22332
  resolved = new URL(candidate["resolved"]);
@@ -22630,7 +22349,7 @@ function verifyPackageLockEntry(lock, definition2, verifyDependencyClosure) {
22630
22349
  matches += 1;
22631
22350
  }
22632
22351
  }
22633
- if (matches !== 1 || !isRecord4(entry) || entry["integrity"] !== definition2.integrity || entry["resolved"] !== definition2.tarballUrl || entry["version"] !== definition2.version) {
22352
+ if (matches !== 1 || !isRecord3(entry) || entry["integrity"] !== definition2.integrity || entry["resolved"] !== definition2.tarballUrl || entry["version"] !== definition2.version) {
22634
22353
  throw new ManagedNpmPackageError(
22635
22354
  "managed_package_verification_failed",
22636
22355
  "The managed npm package lockfile does not match the pinned artifact"
@@ -22811,7 +22530,6 @@ function normalizeVersionOutput(output2) {
22811
22530
  // src/agent-catalog/agent-specification.ts
22812
22531
  var VERSION_PROBE_TIMEOUT_MILLISECONDS = 3e3;
22813
22532
  var ACP_PROBE_TIMEOUT_MILLISECONDS = 5e3;
22814
- var DEFAULT_PROMPT_TIMEOUT_MILLISECONDS = 30 * 60 * 1e3;
22815
22533
  var LocalAgentSpecification = class {
22816
22534
  acpProbeTimeoutMilliseconds = ACP_PROBE_TIMEOUT_MILLISECONDS;
22817
22535
  authenticationCommand = () => "";
@@ -22819,7 +22537,6 @@ var LocalAgentSpecification = class {
22819
22537
  agentVersionArguments = ["--version"];
22820
22538
  normalizeAdapterVersion = normalizeVersionOutput;
22821
22539
  normalizeAgentVersion = normalizeVersionOutput;
22822
- promptTimeoutMilliseconds = DEFAULT_PROMPT_TIMEOUT_MILLISECONDS;
22823
22540
  versionProbeTimeoutMilliseconds = VERSION_PROBE_TIMEOUT_MILLISECONDS;
22824
22541
  resolveManagedAgent = async (stateDirectory, platform, signal) => {
22825
22542
  signal.throwIfAborted();
@@ -23443,7 +23160,7 @@ var ManagedAgentArchiveError = class extends Error {
23443
23160
  this.name = "ManagedAgentArchiveError";
23444
23161
  }
23445
23162
  };
23446
- function isRecord5(value) {
23163
+ function isRecord4(value) {
23447
23164
  return typeof value === "object" && value !== null && !Array.isArray(value);
23448
23165
  }
23449
23166
  function isContainedPath3(root, candidate) {
@@ -23500,7 +23217,7 @@ async function readManifest(path2) {
23500
23217
  );
23501
23218
  }
23502
23219
  const parsed = JSON.parse(await handle.readFile({ encoding: "utf8" }));
23503
- if (!isRecord5(parsed)) {
23220
+ if (!isRecord4(parsed)) {
23504
23221
  throw new ManagedAgentArchiveError(
23505
23222
  "managed_archive_verification_failed",
23506
23223
  "The managed Agent archive manifest is invalid"
@@ -23671,7 +23388,6 @@ var PI_AGENT_PACKAGE = new SriManagedNpmPackageDefinition(
23671
23388
 
23672
23389
  // src/agent-catalog/agents/pi-agent.ts
23673
23390
  var ACP_PROBE_TIMEOUT_MILLISECONDS2 = 3e4;
23674
- var PROMPT_TIMEOUT_MILLISECONDS = 5 * 60 * 1e3;
23675
23391
  var PiAgentSpecification = class extends BridgedAcpAgentDefinition {
23676
23392
  acpProbeTimeoutMilliseconds = ACP_PROBE_TIMEOUT_MILLISECONDS2;
23677
23393
  adapterEnvironmentVariable = "PI_ACP_PI_COMMAND";
@@ -23703,7 +23419,6 @@ var PiAgentSpecification = class extends BridgedAcpAgentDefinition {
23703
23419
  "bundle",
23704
23420
  "cli.js"
23705
23421
  ];
23706
- promptTimeoutMilliseconds = PROMPT_TIMEOUT_MILLISECONDS;
23707
23422
  resolveManagedAgent = async (stateDirectory, _platform, signal) => {
23708
23423
  signal.throwIfAborted();
23709
23424
  const executable = await validateManagedNpmPackage(
@@ -23815,8 +23530,8 @@ var WorkBuddyAgentSpecification = class extends DirectAcpAgentDefinition {
23815
23530
  requestedPaths.unshift(join11(homeDirectory, "Applications", ...WORKBUDDY_MACOS_EXECUTABLE_PATH));
23816
23531
  }
23817
23532
  const executables = [];
23818
- for (const requestedPath of requestedPaths) {
23819
- const executable = await resolveExecutablePath(requestedPath, "darwin");
23533
+ for (const requestedPath2 of requestedPaths) {
23534
+ const executable = await resolveExecutablePath(requestedPath2, "darwin");
23820
23535
  context.signal.throwIfAborted();
23821
23536
  if (executable !== null) {
23822
23537
  executables.push(executable);
@@ -23904,41 +23619,41 @@ var DiscoveryAcpHandler = class {
23904
23619
  };
23905
23620
  function readableAcpStream(input2) {
23906
23621
  let byteLength = 0;
23907
- let open5 = true;
23622
+ let open6 = true;
23908
23623
  return new ReadableStream({
23909
23624
  start(controller) {
23910
23625
  input2.on("data", (chunk) => {
23911
- if (!open5) {
23626
+ if (!open6) {
23912
23627
  return;
23913
23628
  }
23914
23629
  if (!(chunk instanceof Uint8Array)) {
23915
- open5 = false;
23630
+ open6 = false;
23916
23631
  controller.error(new Error("ACP adapter produced invalid output"));
23917
23632
  return;
23918
23633
  }
23919
23634
  byteLength += chunk.byteLength;
23920
23635
  if (byteLength > ACP_OUTPUT_LIMIT_BYTES) {
23921
- open5 = false;
23636
+ open6 = false;
23922
23637
  controller.error(new Error("ACP adapter output limit exceeded"));
23923
23638
  return;
23924
23639
  }
23925
23640
  controller.enqueue(new Uint8Array(chunk));
23926
23641
  });
23927
23642
  input2.once("end", () => {
23928
- if (open5) {
23929
- open5 = false;
23643
+ if (open6) {
23644
+ open6 = false;
23930
23645
  controller.close();
23931
23646
  }
23932
23647
  });
23933
23648
  input2.once("error", (error62) => {
23934
- if (open5) {
23935
- open5 = false;
23649
+ if (open6) {
23650
+ open6 = false;
23936
23651
  controller.error(error62);
23937
23652
  }
23938
23653
  });
23939
23654
  },
23940
23655
  cancel() {
23941
- open5 = false;
23656
+ open6 = false;
23942
23657
  }
23943
23658
  });
23944
23659
  }
@@ -24209,7 +23924,7 @@ async function resolveAdapterExecutable(specification, context) {
24209
23924
  const executables = await resolveAdapterExecutables(specification, context);
24210
23925
  return executables[0] ?? null;
24211
23926
  }
24212
- async function probeVersion(executable, arguments_, environment, defaultWorkspace, signal, timeoutMilliseconds, normalize4 = normalizeVersionOutput) {
23927
+ async function probeVersion(executable, arguments_, environment, defaultWorkspace, signal, timeoutMilliseconds, normalize5 = normalizeVersionOutput) {
24213
23928
  const result = await runBoundedProcess({
24214
23929
  arguments: arguments_,
24215
23930
  command: executable.path,
@@ -24218,7 +23933,7 @@ async function probeVersion(executable, arguments_, environment, defaultWorkspac
24218
23933
  signal,
24219
23934
  timeoutMilliseconds
24220
23935
  });
24221
- const version2 = normalize4(result.stdout || result.stderr);
23936
+ const version2 = normalize5(result.stdout || result.stderr);
24222
23937
  if (version2.length === 0) {
24223
23938
  throw new ProcessExecutionError("process_exit_failed", "The executable did not report a version");
24224
23939
  }
@@ -24355,8 +24070,7 @@ async function discoverAgent(specification, context) {
24355
24070
  adapterVersion,
24356
24071
  agentVersion,
24357
24072
  adapter.identity,
24358
- agent.identity,
24359
- specification.promptTimeoutMilliseconds
24073
+ agent.identity
24360
24074
  );
24361
24075
  try {
24362
24076
  const readiness = await probeAcpReadiness(
@@ -24382,7 +24096,6 @@ async function discoverAgent(specification, context) {
24382
24096
  agentVersion,
24383
24097
  adapter.identity,
24384
24098
  agent.identity,
24385
- specification.promptTimeoutMilliseconds,
24386
24099
  readiness.capabilities
24387
24100
  )
24388
24101
  );
@@ -24410,164 +24123,6 @@ async function discoverLocalAgentInventory(options) {
24410
24123
  return new LocalAgentInventory(discoveries);
24411
24124
  }
24412
24125
 
24413
- // src/bots/bot-message-command.ts
24414
- import { randomUUID } from "node:crypto";
24415
- import { createConnection } from "node:net";
24416
- var BOT_IPC_RESPONSE_LIMIT = 64 * 1024;
24417
- var BOT_IPC_TIMEOUT_MILLISECONDS = 2e4;
24418
- var BotMessageCommandError = class extends Error {
24419
- code;
24420
- constructor(code, message, options = {}) {
24421
- super(message, options);
24422
- this.code = code;
24423
- this.name = "BotMessageCommandError";
24424
- }
24425
- };
24426
- function isRecord6(value) {
24427
- return typeof value === "object" && value !== null && !Array.isArray(value);
24428
- }
24429
- function requiredEnvironment(environment, name) {
24430
- const value = environment[name]?.trim();
24431
- if (value === void 0 || value.length === 0) {
24432
- throw new BotMessageCommandError(
24433
- "execution_context_required",
24434
- "This command is available only inside an active Mobius Bot execution"
24435
- );
24436
- }
24437
- return value;
24438
- }
24439
- function option(arguments_, name) {
24440
- const index2 = arguments_.indexOf(name);
24441
- if (index2 < 0 || index2 + 1 >= arguments_.length || arguments_[index2 + 1]?.startsWith("--") === true) {
24442
- throw new BotMessageCommandError(
24443
- "invalid_request",
24444
- "Usage: mobius bot message send --target <current|alias> --text <message>"
24445
- );
24446
- }
24447
- const value = arguments_[index2 + 1];
24448
- if (value === void 0) {
24449
- throw new BotMessageCommandError("invalid_request", "The Bot message option is missing");
24450
- }
24451
- return value;
24452
- }
24453
- function validateArguments(arguments_) {
24454
- if (arguments_.length !== 4) {
24455
- throw new BotMessageCommandError(
24456
- "invalid_request",
24457
- "Usage: mobius bot message send --target <current|alias> --text <message>"
24458
- );
24459
- }
24460
- const names = [arguments_[0], arguments_[2]];
24461
- if (!names.includes("--target") || !names.includes("--text") || names[0] === names[1]) {
24462
- throw new BotMessageCommandError(
24463
- "invalid_request",
24464
- "Usage: mobius bot message send --target <current|alias> --text <message>"
24465
- );
24466
- }
24467
- }
24468
- function decodeResponse(encoded) {
24469
- let value;
24470
- try {
24471
- value = JSON.parse(encoded);
24472
- } catch (cause) {
24473
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data", {
24474
- cause
24475
- });
24476
- }
24477
- if (!isRecord6(value) || typeof value["ok"] !== "boolean") {
24478
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data");
24479
- }
24480
- if (value["ok"] === true && typeof value["outboundMessageId"] === "string") {
24481
- return value["outboundMessageId"];
24482
- }
24483
- const error62 = value["error"];
24484
- if (value["ok"] === false && isRecord6(error62) && typeof error62["code"] === "string" && typeof error62["message"] === "string") {
24485
- throw new BotMessageCommandError(error62["code"], error62["message"]);
24486
- }
24487
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data");
24488
- }
24489
- async function requestLocalBotService(socketPath, payload, signal) {
24490
- signal.throwIfAborted();
24491
- return await new Promise((resolve5, reject) => {
24492
- const socket = createConnection(socketPath);
24493
- const chunks = [];
24494
- let length = 0;
24495
- let finished = false;
24496
- const finish = () => {
24497
- socket.removeAllListeners();
24498
- socket.destroy();
24499
- };
24500
- const fail = (error62) => {
24501
- if (finished) {
24502
- return;
24503
- }
24504
- finished = true;
24505
- finish();
24506
- if (error62 instanceof BotMessageCommandError) {
24507
- reject(error62);
24508
- return;
24509
- }
24510
- reject(
24511
- new BotMessageCommandError(
24512
- "execution_context_required",
24513
- "The active Mobius Bot execution is unavailable",
24514
- { cause: error62 }
24515
- )
24516
- );
24517
- };
24518
- const abort = () => fail(signal.reason);
24519
- socket.setTimeout(BOT_IPC_TIMEOUT_MILLISECONDS, () => {
24520
- fail(new BotMessageCommandError("bot_service_unavailable", "The local Bot service timed out"));
24521
- });
24522
- socket.once("error", fail);
24523
- socket.once("connect", () => socket.end(`${payload}
24524
- `));
24525
- socket.on("data", (chunk) => {
24526
- length += chunk.byteLength;
24527
- if (length > BOT_IPC_RESPONSE_LIMIT) {
24528
- fail(new BotMessageCommandError("bot_service_unavailable", "The local Bot response is too large"));
24529
- return;
24530
- }
24531
- chunks.push(chunk);
24532
- });
24533
- socket.once("end", () => {
24534
- if (finished) {
24535
- return;
24536
- }
24537
- finished = true;
24538
- signal.removeEventListener("abort", abort);
24539
- try {
24540
- resolve5(decodeResponse(Buffer.concat(chunks).toString("utf8")));
24541
- } catch (error62) {
24542
- reject(error62);
24543
- } finally {
24544
- finish();
24545
- }
24546
- });
24547
- signal.addEventListener("abort", abort, { once: true });
24548
- });
24549
- }
24550
- async function executeBotMessageCommand(arguments_, environment, signal) {
24551
- validateArguments(arguments_);
24552
- const contextHandle = requiredEnvironment(environment, "MOBIUS_BOT_CONTEXT");
24553
- const socketPath = requiredEnvironment(environment, "MOBIUS_BOT_SOCKET");
24554
- const target = option(arguments_, "--target");
24555
- const text3 = option(arguments_, "--text");
24556
- if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(target) || text3.trim().length === 0 || text3.length > 1e4) {
24557
- throw new BotMessageCommandError("invalid_request", "The Bot outbound message is invalid");
24558
- }
24559
- return await requestLocalBotService(
24560
- socketPath,
24561
- JSON.stringify({
24562
- contextHandle,
24563
- idempotencyKey: `cli_${randomUUID()}`,
24564
- target,
24565
- text: text3
24566
- }),
24567
- signal
24568
- );
24569
- }
24570
-
24571
24126
  // src/config.ts
24572
24127
  import { join as join14 } from "node:path";
24573
24128
  function loadDefaultWorkspace(environment = process.env) {
@@ -24588,15 +24143,15 @@ function createDaemonConfig(connection, agents = [], installableAgents = []) {
24588
24143
  }
24589
24144
 
24590
24145
  // src/pairing/pair-local-machine.ts
24591
- import { randomUUID as randomUUID2 } from "node:crypto";
24146
+ import { randomUUID } from "node:crypto";
24592
24147
  import { mkdir as mkdir3, open as open4, realpath as realpath6, rename as rename3, stat as stat5, writeFile as writeFile2 } from "node:fs/promises";
24593
24148
  import { hostname as hostname3 } from "node:os";
24594
24149
  import { basename, join as join15, resolve as resolve3 } from "node:path";
24595
24150
  import { fetch as fetch2 } from "undici";
24596
24151
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
24597
24152
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
24598
- var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
24599
- var TOKEN_PATTERN2 = /^[a-zA-Z0-9_-]{32,256}$/;
24153
+ var IDENTIFIER_PATTERN4 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
24154
+ var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
24600
24155
  var MAX_CONNECTION_FILE_LENGTH = 16 * 1024;
24601
24156
  var CLAIM_RESPONSE_KEYS = ["channelId", "daemonToken", "runtimeId"];
24602
24157
  var REDEEM_RESPONSE_KEYS = ["channelId", "runtimeCredential", "runtimeId"];
@@ -24610,36 +24165,36 @@ var PairingClientError = class extends Error {
24610
24165
  this.name = "PairingClientError";
24611
24166
  }
24612
24167
  };
24613
- function isRecord7(value) {
24168
+ function isRecord5(value) {
24614
24169
  return typeof value === "object" && value !== null && !Array.isArray(value);
24615
24170
  }
24616
24171
  function hasExactKeys(value, expectedKeys) {
24617
24172
  const keys = Object.keys(value);
24618
24173
  return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
24619
24174
  }
24620
- function readSingleOption(arguments_, option2) {
24175
+ function readSingleOption(arguments_, option) {
24621
24176
  const values = [];
24622
24177
  for (let index2 = 0; index2 < arguments_.length; index2 += 1) {
24623
- if (arguments_[index2] !== option2) {
24178
+ if (arguments_[index2] !== option) {
24624
24179
  continue;
24625
24180
  }
24626
24181
  const value = arguments_[index2 + 1];
24627
24182
  if (value === void 0 || value.startsWith("--")) {
24628
- throw new PairingClientError("invalid_arguments", `${option2} requires a value`);
24183
+ throw new PairingClientError("invalid_arguments", `${option} requires a value`);
24629
24184
  }
24630
24185
  values.push(value);
24631
24186
  index2 += 1;
24632
24187
  }
24633
24188
  if (values.length !== 1) {
24634
- throw new PairingClientError("invalid_arguments", `${option2} must be provided exactly once`);
24189
+ throw new PairingClientError("invalid_arguments", `${option} must be provided exactly once`);
24635
24190
  }
24636
24191
  return values[0] ?? "";
24637
24192
  }
24638
24193
  function assertKnownArguments(arguments_) {
24639
24194
  for (let index2 = 0; index2 < arguments_.length; index2 += 2) {
24640
- const option2 = arguments_[index2];
24641
- if (option2 !== "--url" && option2 !== "--code" && option2 !== "--pairing" && option2 !== "--workspace") {
24642
- throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option2 ?? "missing option"}`);
24195
+ const option = arguments_[index2];
24196
+ if (option !== "--url" && option !== "--code" && option !== "--pairing" && option !== "--workspace") {
24197
+ throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option ?? "missing option"}`);
24643
24198
  }
24644
24199
  }
24645
24200
  }
@@ -24684,7 +24239,7 @@ function parsePairCommand(arguments_) {
24684
24239
  };
24685
24240
  }
24686
24241
  function validatePairingId(value) {
24687
- if (!IDENTIFIER_PATTERN5.test(value)) {
24242
+ if (!IDENTIFIER_PATTERN4.test(value)) {
24688
24243
  throw new PairingClientError("invalid_pairing_id", "The Runtime pairing ID is invalid");
24689
24244
  }
24690
24245
  return value;
@@ -24694,7 +24249,7 @@ function parseChannelArgument(arguments_) {
24694
24249
  throw new PairingClientError("invalid_arguments", "Usage: mobius start --channel <channel-id>");
24695
24250
  }
24696
24251
  const channelId = arguments_[1] ?? "";
24697
- if (!IDENTIFIER_PATTERN5.test(channelId)) {
24252
+ if (!IDENTIFIER_PATTERN4.test(channelId)) {
24698
24253
  throw new PairingClientError("invalid_channel_id", "The saved channel ID is invalid");
24699
24254
  }
24700
24255
  return channelId;
@@ -24733,9 +24288,9 @@ async function readJsonResponse(response) {
24733
24288
  }
24734
24289
  }
24735
24290
  function readRelayError(value) {
24736
- if (isRecord7(value)) {
24291
+ if (isRecord5(value)) {
24737
24292
  const error62 = value["error"];
24738
- if (isRecord7(error62)) {
24293
+ if (isRecord5(error62)) {
24739
24294
  const code = error62["code"];
24740
24295
  const message = error62["message"];
24741
24296
  if (typeof code === "string" && typeof message === "string") {
@@ -24746,13 +24301,13 @@ function readRelayError(value) {
24746
24301
  return new PairingClientError("pairing_failed", "The relay could not pair this machine");
24747
24302
  }
24748
24303
  function decodePairingResponse(value, credentialField, expectedKeys) {
24749
- if (!isRecord7(value) || !hasExactKeys(value, expectedKeys)) {
24304
+ if (!isRecord5(value) || !hasExactKeys(value, expectedKeys)) {
24750
24305
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
24751
24306
  }
24752
24307
  const channelId = value["channelId"];
24753
24308
  const runtimeCredential2 = value[credentialField];
24754
24309
  const runtimeId = value["runtimeId"];
24755
- if (typeof channelId !== "string" || !IDENTIFIER_PATTERN5.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN2.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN5.test(runtimeId)) {
24310
+ if (typeof channelId !== "string" || !IDENTIFIER_PATTERN4.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN4.test(runtimeId)) {
24756
24311
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
24757
24312
  }
24758
24313
  return { channelId, runtimeCredential: runtimeCredential2, runtimeId };
@@ -24762,7 +24317,6 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
24762
24317
  agentPath: agent.agentIdentity.requestedPath,
24763
24318
  agentVersion: agent.agentVersion,
24764
24319
  agentSettingsDiscovery: true,
24765
- botSessionConfiguration: true,
24766
24320
  capabilities: agent.capabilities,
24767
24321
  id: agent.id,
24768
24322
  label: agent.label,
@@ -24797,7 +24351,7 @@ async function persistConnection(channelId, relayOrigin, runtimeCredential2, def
24797
24351
  const connectionsDirectory = join15(readStateDirectory(environment), "connections");
24798
24352
  await mkdir3(connectionsDirectory, { mode: 448, recursive: true });
24799
24353
  const connectionPath = join15(connectionsDirectory, `${channelId}.json`);
24800
- const temporaryPath = join15(connectionsDirectory, `.${channelId}.${randomUUID2()}.tmp`);
24354
+ const temporaryPath = join15(connectionsDirectory, `.${channelId}.${randomUUID()}.tmp`);
24801
24355
  await writeFile2(
24802
24356
  temporaryPath,
24803
24357
  `${JSON.stringify(
@@ -24817,14 +24371,14 @@ async function persistConnection(channelId, relayOrigin, runtimeCredential2, def
24817
24371
  return connectionPath;
24818
24372
  }
24819
24373
  function decodeSavedConnection(value, expectedChannelId) {
24820
- if (!isRecord7(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24374
+ if (!isRecord5(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24821
24375
  throw new PairingClientError("invalid_connection", "The saved connection is invalid");
24822
24376
  }
24823
24377
  const defaultWorkspace = value["defaultWorkspace"];
24824
24378
  const channelId = value["channelId"];
24825
24379
  const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
24826
24380
  const relayOrigin = value["relayOrigin"];
24827
- if (typeof defaultWorkspace !== "string" || typeof channelId !== "string" || channelId !== expectedChannelId || !IDENTIFIER_PATTERN5.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN2.test(runtimeCredential2) || typeof relayOrigin !== "string") {
24381
+ if (typeof defaultWorkspace !== "string" || typeof channelId !== "string" || channelId !== expectedChannelId || !IDENTIFIER_PATTERN4.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof relayOrigin !== "string") {
24828
24382
  throw new PairingClientError("invalid_connection", "The saved connection is invalid");
24829
24383
  }
24830
24384
  return {
@@ -24983,10 +24537,10 @@ var AuditStore = class {
24983
24537
  };
24984
24538
 
24985
24539
  // src/run-daemon.ts
24986
- import { randomUUID as randomUUID5 } from "node:crypto";
24987
- import { basename as basename6, join as join17 } from "node:path";
24540
+ import { randomUUID as randomUUID4 } from "node:crypto";
24541
+ import { basename as basename7 } from "node:path";
24988
24542
  import { styleText } from "node:util";
24989
- import { fetch as fetch7, WebSocket as WebSocket2 } from "undici";
24543
+ import { fetch as fetch6, WebSocket as WebSocket2 } from "undici";
24990
24544
 
24991
24545
  // src/acp/session-manager.ts
24992
24546
  import { spawn as spawn3 } from "node:child_process";
@@ -24998,10 +24552,11 @@ import {
24998
24552
  } from "@agentclientprotocol/sdk";
24999
24553
 
25000
24554
  // src/authorization/local-raster.ts
25001
- import { readFile as readFile2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
24555
+ import { open as open5, readFile as readFile2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
25002
24556
  import { basename as basename2, isAbsolute as isAbsolute8, normalize as normalize2 } from "node:path";
25003
24557
  import { fileURLToPath } from "node:url";
25004
- var MAX_LOCAL_RASTER_BYTES = 3e6;
24558
+ var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
24559
+ var MAX_INLINE_RASTER_BYTES = 3e6;
25005
24560
  var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
25006
24561
  var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
25007
24562
  var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
@@ -25012,12 +24567,17 @@ var LocalRasterImage = class {
25012
24567
  bytes;
25013
24568
  mimeType;
25014
24569
  name;
25015
- constructor(name, mimeType, bytes) {
24570
+ sourceUri;
24571
+ constructor(name, mimeType, bytes, sourceUri = "") {
25016
24572
  this.bytes = bytes;
25017
24573
  this.mimeType = mimeType;
25018
24574
  this.name = name;
24575
+ this.sourceUri = sourceUri;
25019
24576
  }
25020
- base64 = () => Buffer.from(this.bytes).toString("base64");
24577
+ base64 = async () => {
24578
+ const bytes = this.bytes ?? new Uint8Array(await readFile2(this.sourceUri));
24579
+ return Buffer.from(bytes).toString("base64");
24580
+ };
25021
24581
  };
25022
24582
  function startsWith(bytes, signature, offset = 0) {
25023
24583
  if (bytes.byteLength < offset + signature.byteLength) {
@@ -25041,14 +24601,14 @@ function sniffRasterMime(bytes) {
25041
24601
  return null;
25042
24602
  }
25043
24603
  function readInlineRaster(data, name = "Image") {
25044
- if (data.length === 0 || data.length > Math.ceil(MAX_LOCAL_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
24604
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
25045
24605
  return null;
25046
24606
  }
25047
24607
  if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
25048
24608
  return null;
25049
24609
  }
25050
24610
  const bytes = new Uint8Array(Buffer.from(data, "base64"));
25051
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_LOCAL_RASTER_BYTES) {
24611
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_RASTER_BYTES) {
25052
24612
  return null;
25053
24613
  }
25054
24614
  const mimeType = sniffRasterMime(bytes);
@@ -25116,16 +24676,19 @@ async function readLocalRaster(uri, signal) {
25116
24676
  if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
25117
24677
  return null;
25118
24678
  }
25119
- const bytes = new Uint8Array(await readFile2(target));
25120
- signal.throwIfAborted();
25121
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_LOCAL_RASTER_BYTES) {
25122
- return null;
24679
+ const handle = await open5(target, "r");
24680
+ const header = new Uint8Array(12);
24681
+ try {
24682
+ await handle.read(header, 0, header.byteLength, 0);
24683
+ } finally {
24684
+ await handle.close();
25123
24685
  }
25124
- const mimeType = sniffRasterMime(bytes);
24686
+ signal.throwIfAborted();
24687
+ const mimeType = sniffRasterMime(header);
25125
24688
  if (mimeType === null) {
25126
24689
  return null;
25127
24690
  }
25128
- return new LocalRasterImage(basename2(target) || "Image", mimeType, bytes);
24691
+ return new LocalRasterImage(basename2(target) || "Image", mimeType, null, target);
25129
24692
  }
25130
24693
 
25131
24694
  // src/authorization/local-video.ts
@@ -25251,7 +24814,7 @@ async function resolveMessageImages(message, usedCharacters, signal) {
25251
24814
  if (local === null) {
25252
24815
  return "[Image unavailable]";
25253
24816
  }
25254
- const data = local.base64();
24817
+ const data = await local.base64();
25255
24818
  if (usedCharacters + imageCharacters + data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
25256
24819
  return "[Image unavailable]";
25257
24820
  }
@@ -25287,7 +24850,7 @@ async function replaceImageMarkers(text3, replace) {
25287
24850
 
25288
24851
  // src/acp/activity.ts
25289
24852
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
25290
- function isRecord8(value) {
24853
+ function isRecord6(value) {
25291
24854
  return typeof value === "object" && value !== null && !Array.isArray(value);
25292
24855
  }
25293
24856
  var AcpActivity = class _AcpActivity {
@@ -25521,16 +25084,16 @@ async function normalizeToolContent(content3, prepareContent) {
25521
25084
  return normalized;
25522
25085
  }
25523
25086
  function rawMcpToolContent(rawOutput) {
25524
- if (!isRecord8(rawOutput)) {
25087
+ if (!isRecord6(rawOutput)) {
25525
25088
  return [];
25526
25089
  }
25527
- const result = isRecord8(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
25090
+ const result = isRecord6(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
25528
25091
  const content3 = result["content"];
25529
25092
  if (!Array.isArray(content3)) {
25530
25093
  return [];
25531
25094
  }
25532
25095
  return content3.flatMap((item) => {
25533
- if (!isRecord8(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
25096
+ if (!isRecord6(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
25534
25097
  return [];
25535
25098
  }
25536
25099
  const uri = item["uri"];
@@ -25607,7 +25170,7 @@ function contentPhase(content3) {
25607
25170
  return "";
25608
25171
  }
25609
25172
  const codex = metadata["codex"];
25610
- if (!isRecord8(codex)) {
25173
+ if (!isRecord6(codex)) {
25611
25174
  return "";
25612
25175
  }
25613
25176
  const phase = codex["phase"];
@@ -28411,7 +27974,7 @@ var attention = {
28411
27974
  };
28412
27975
  function resolveAllAttention(events, context) {
28413
27976
  let index2 = -1;
28414
- let open5;
27977
+ let open6;
28415
27978
  let group;
28416
27979
  let text3;
28417
27980
  let openingSequence;
@@ -28421,16 +27984,16 @@ function resolveAllAttention(events, context) {
28421
27984
  let offset;
28422
27985
  while (++index2 < events.length) {
28423
27986
  if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
28424
- open5 = index2;
28425
- while (open5--) {
28426
- if (events[open5][0] === "exit" && events[open5][1].type === "attentionSequence" && events[open5][1]._open && // If the markers are the same:
28427
- context.sliceSerialize(events[open5][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
28428
- if ((events[open5][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open5][1].end.offset - events[open5][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
27987
+ open6 = index2;
27988
+ while (open6--) {
27989
+ if (events[open6][0] === "exit" && events[open6][1].type === "attentionSequence" && events[open6][1]._open && // If the markers are the same:
27990
+ context.sliceSerialize(events[open6][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
27991
+ if ((events[open6][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open6][1].end.offset - events[open6][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
28429
27992
  continue;
28430
27993
  }
28431
- use = events[open5][1].end.offset - events[open5][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
27994
+ use = events[open6][1].end.offset - events[open6][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
28432
27995
  const start = {
28433
- ...events[open5][1].end
27996
+ ...events[open6][1].end
28434
27997
  };
28435
27998
  const end = {
28436
27999
  ...events[index2][1].start
@@ -28441,7 +28004,7 @@ function resolveAllAttention(events, context) {
28441
28004
  type: use > 1 ? "strongSequence" : "emphasisSequence",
28442
28005
  start,
28443
28006
  end: {
28444
- ...events[open5][1].end
28007
+ ...events[open6][1].end
28445
28008
  }
28446
28009
  };
28447
28010
  closingSequence = {
@@ -28454,7 +28017,7 @@ function resolveAllAttention(events, context) {
28454
28017
  text3 = {
28455
28018
  type: use > 1 ? "strongText" : "emphasisText",
28456
28019
  start: {
28457
- ...events[open5][1].end
28020
+ ...events[open6][1].end
28458
28021
  },
28459
28022
  end: {
28460
28023
  ...events[index2][1].start
@@ -28469,18 +28032,18 @@ function resolveAllAttention(events, context) {
28469
28032
  ...closingSequence.end
28470
28033
  }
28471
28034
  };
28472
- events[open5][1].end = {
28035
+ events[open6][1].end = {
28473
28036
  ...openingSequence.start
28474
28037
  };
28475
28038
  events[index2][1].start = {
28476
28039
  ...closingSequence.end
28477
28040
  };
28478
28041
  nextEvents = [];
28479
- if (events[open5][1].end.offset - events[open5][1].start.offset) {
28480
- nextEvents = push(nextEvents, [["enter", events[open5][1], context], ["exit", events[open5][1], context]]);
28042
+ if (events[open6][1].end.offset - events[open6][1].start.offset) {
28043
+ nextEvents = push(nextEvents, [["enter", events[open6][1], context], ["exit", events[open6][1], context]]);
28481
28044
  }
28482
28045
  nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text3, context]]);
28483
- nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open5 + 1, index2), context));
28046
+ nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open6 + 1, index2), context));
28484
28047
  nextEvents = push(nextEvents, [["exit", text3, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
28485
28048
  if (events[index2][1].end.offset - events[index2][1].start.offset) {
28486
28049
  offset = 2;
@@ -28488,8 +28051,8 @@ function resolveAllAttention(events, context) {
28488
28051
  } else {
28489
28052
  offset = 0;
28490
28053
  }
28491
- splice(events, open5 - 1, index2 - open5 + 3, nextEvents);
28492
- index2 = open5 + nextEvents.length - offset - 2;
28054
+ splice(events, open6 - 1, index2 - open6 + 3, nextEvents);
28055
+ index2 = open6 + nextEvents.length - offset - 2;
28493
28056
  break;
28494
28057
  }
28495
28058
  }
@@ -28521,10 +28084,10 @@ function tokenizeAttention(effects, ok2) {
28521
28084
  }
28522
28085
  const token = effects.exit("attentionSequence");
28523
28086
  const after = classifyCharacter(code);
28524
- const open5 = !after || after === 2 && before || attentionMarkers2.includes(code);
28087
+ const open6 = !after || after === 2 && before || attentionMarkers2.includes(code);
28525
28088
  const close = !before || before === 2 && after || attentionMarkers2.includes(previous2);
28526
- token._open = Boolean(marker === 42 ? open5 : open5 && (before || !close));
28527
- token._close = Boolean(marker === 42 ? close : close && (after || !open5));
28089
+ token._open = Boolean(marker === 42 ? open6 : open6 && (before || !close));
28090
+ token._close = Boolean(marker === 42 ? close : close && (after || !open6));
28528
28091
  return ok2(code);
28529
28092
  }
28530
28093
  }
@@ -28548,9 +28111,9 @@ function tokenizeAutolink(effects, ok2, nok) {
28548
28111
  effects.consume(code);
28549
28112
  effects.exit("autolinkMarker");
28550
28113
  effects.enter("autolinkProtocol");
28551
- return open5;
28114
+ return open6;
28552
28115
  }
28553
- function open5(code) {
28116
+ function open6(code) {
28554
28117
  if (asciiAlpha(code)) {
28555
28118
  effects.consume(code);
28556
28119
  return schemeOrEmailAtext;
@@ -28750,9 +28313,9 @@ function tokenizeCharacterReference(effects, ok2, nok) {
28750
28313
  effects.enter("characterReferenceMarker");
28751
28314
  effects.consume(code);
28752
28315
  effects.exit("characterReferenceMarker");
28753
- return open5;
28316
+ return open6;
28754
28317
  }
28755
- function open5(code) {
28318
+ function open6(code) {
28756
28319
  if (code === 35) {
28757
28320
  effects.enter("characterReferenceMarkerNumeric");
28758
28321
  effects.consume(code);
@@ -30121,9 +29684,9 @@ function tokenizeHtmlFlow(effects, ok2, nok) {
30121
29684
  effects.enter("htmlFlow");
30122
29685
  effects.enter("htmlFlowData");
30123
29686
  effects.consume(code);
30124
- return open5;
29687
+ return open6;
30125
29688
  }
30126
- function open5(code) {
29689
+ function open6(code) {
30127
29690
  if (code === 33) {
30128
29691
  effects.consume(code);
30129
29692
  return declarationOpen;
@@ -30471,9 +30034,9 @@ function tokenizeHtmlText(effects, ok2, nok) {
30471
30034
  effects.enter("htmlText");
30472
30035
  effects.enter("htmlTextData");
30473
30036
  effects.consume(code);
30474
- return open5;
30037
+ return open6;
30475
30038
  }
30476
- function open5(code) {
30039
+ function open6(code) {
30477
30040
  if (code === 33) {
30478
30041
  effects.consume(code);
30479
30042
  return declarationOpen;
@@ -30799,12 +30362,12 @@ function resolveToLabelEnd(events, context) {
30799
30362
  let index2 = events.length;
30800
30363
  let offset = 0;
30801
30364
  let token;
30802
- let open5;
30365
+ let open6;
30803
30366
  let close;
30804
30367
  let media;
30805
30368
  while (index2--) {
30806
30369
  token = events[index2][1];
30807
- if (open5) {
30370
+ if (open6) {
30808
30371
  if (token.type === "link" || token.type === "labelLink" && token._inactive) {
30809
30372
  break;
30810
30373
  }
@@ -30813,7 +30376,7 @@ function resolveToLabelEnd(events, context) {
30813
30376
  }
30814
30377
  } else if (close) {
30815
30378
  if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) {
30816
- open5 = index2;
30379
+ open6 = index2;
30817
30380
  if (token.type !== "labelLink") {
30818
30381
  offset = 2;
30819
30382
  break;
@@ -30824,9 +30387,9 @@ function resolveToLabelEnd(events, context) {
30824
30387
  }
30825
30388
  }
30826
30389
  const group = {
30827
- type: events[open5][1].type === "labelLink" ? "link" : "image",
30390
+ type: events[open6][1].type === "labelLink" ? "link" : "image",
30828
30391
  start: {
30829
- ...events[open5][1].start
30392
+ ...events[open6][1].start
30830
30393
  },
30831
30394
  end: {
30832
30395
  ...events[events.length - 1][1].end
@@ -30835,7 +30398,7 @@ function resolveToLabelEnd(events, context) {
30835
30398
  const label = {
30836
30399
  type: "label",
30837
30400
  start: {
30838
- ...events[open5][1].start
30401
+ ...events[open6][1].start
30839
30402
  },
30840
30403
  end: {
30841
30404
  ...events[close][1].end
@@ -30844,20 +30407,20 @@ function resolveToLabelEnd(events, context) {
30844
30407
  const text3 = {
30845
30408
  type: "labelText",
30846
30409
  start: {
30847
- ...events[open5 + offset + 2][1].end
30410
+ ...events[open6 + offset + 2][1].end
30848
30411
  },
30849
30412
  end: {
30850
30413
  ...events[close - 2][1].start
30851
30414
  }
30852
30415
  };
30853
30416
  media = [["enter", group, context], ["enter", label, context]];
30854
- media = push(media, events.slice(open5 + 1, open5 + offset + 3));
30417
+ media = push(media, events.slice(open6 + 1, open6 + offset + 3));
30855
30418
  media = push(media, [["enter", text3, context]]);
30856
- media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open5 + offset + 4, close - 3), context));
30419
+ media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open6 + offset + 4, close - 3), context));
30857
30420
  media = push(media, [["exit", text3, context], events[close - 2], events[close - 1], ["exit", label, context]]);
30858
30421
  media = push(media, events.slice(close + 1));
30859
30422
  media = push(media, [["exit", group, context]]);
30860
- splice(events, open5, events.length, media);
30423
+ splice(events, open6, events.length, media);
30861
30424
  return events;
30862
30425
  }
30863
30426
  function tokenizeLabelEnd(effects, ok2, nok) {
@@ -31002,9 +30565,9 @@ function tokenizeLabelStartImage(effects, ok2, nok) {
31002
30565
  effects.enter("labelImageMarker");
31003
30566
  effects.consume(code);
31004
30567
  effects.exit("labelImageMarker");
31005
- return open5;
30568
+ return open6;
31006
30569
  }
31007
- function open5(code) {
30570
+ function open6(code) {
31008
30571
  if (code === 91) {
31009
30572
  effects.enter("labelMarker");
31010
30573
  effects.consume(code);
@@ -32308,8 +31871,8 @@ function compiler(options) {
32308
31871
  return length;
32309
31872
  }
32310
31873
  function opener(create, and) {
32311
- return open5;
32312
- function open5(token) {
31874
+ return open6;
31875
+ function open6(token) {
32313
31876
  enter.call(this, create(token), token);
32314
31877
  if (and) and.call(this, token);
32315
31878
  }
@@ -32341,18 +31904,18 @@ function compiler(options) {
32341
31904
  }
32342
31905
  function exit2(token, onExitError) {
32343
31906
  const node3 = this.stack.pop();
32344
- const open5 = this.tokenStack.pop();
32345
- if (!open5) {
31907
+ const open6 = this.tokenStack.pop();
31908
+ if (!open6) {
32346
31909
  throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({
32347
31910
  start: token.start,
32348
31911
  end: token.end
32349
31912
  }) + "): it\u2019s not open");
32350
- } else if (open5[0].type !== token.type) {
31913
+ } else if (open6[0].type !== token.type) {
32351
31914
  if (onExitError) {
32352
- onExitError.call(this, token, open5[0]);
31915
+ onExitError.call(this, token, open6[0]);
32353
31916
  } else {
32354
- const handler = open5[1] || defaultOnError;
32355
- handler.call(this, token, open5[0]);
31917
+ const handler = open6[1] || defaultOnError;
31918
+ handler.call(this, token, open6[0]);
32356
31919
  }
32357
31920
  }
32358
31921
  node3.position.end = point2(token.end);
@@ -33036,7 +32599,7 @@ var SessionConfigProtocolError = class extends Error {
33036
32599
  this.name = "SessionConfigProtocolError";
33037
32600
  }
33038
32601
  };
33039
- function isRecord9(value) {
32602
+ function isRecord7(value) {
33040
32603
  return typeof value === "object" && value !== null && !Array.isArray(value);
33041
32604
  }
33042
32605
  function readString2(value, fallback = "") {
@@ -33048,13 +32611,13 @@ function truncate2(value, maximum) {
33048
32611
  function readBoolean(value, fallback = false) {
33049
32612
  return typeof value === "boolean" ? value : fallback;
33050
32613
  }
33051
- function normalizeConfigValue(option2, groupId = "", groupName = "") {
32614
+ function normalizeConfigValue(option, groupId = "", groupName = "") {
33052
32615
  return {
33053
- description: truncate2(readString2(option2["description"]), 500),
32616
+ description: truncate2(readString2(option["description"]), 500),
33054
32617
  groupId: truncate2(groupId, 128),
33055
32618
  groupName: truncate2(groupName, 255),
33056
- name: truncate2(readString2(option2["name"], readString2(option2["value"])), 255),
33057
- value: truncate2(readString2(option2["value"]), 500)
32619
+ name: truncate2(readString2(option["name"], readString2(option["value"])), 255),
32620
+ value: truncate2(readString2(option["value"]), 500)
33058
32621
  };
33059
32622
  }
33060
32623
  function normalizeConfigValues(value) {
@@ -33063,7 +32626,7 @@ function normalizeConfigValues(value) {
33063
32626
  }
33064
32627
  const normalized = [];
33065
32628
  for (const entry of value) {
33066
- if (!isRecord9(entry)) {
32629
+ if (!isRecord7(entry)) {
33067
32630
  continue;
33068
32631
  }
33069
32632
  const groupedOptions = entry["options"];
@@ -33071,7 +32634,7 @@ function normalizeConfigValues(value) {
33071
32634
  const groupId = readString2(entry["group"]);
33072
32635
  const groupName = readString2(entry["name"]);
33073
32636
  for (const groupedOption of groupedOptions) {
33074
- if (isRecord9(groupedOption)) {
32637
+ if (isRecord7(groupedOption)) {
33075
32638
  normalized.push(normalizeConfigValue(groupedOption, groupId, groupName));
33076
32639
  }
33077
32640
  }
@@ -33084,21 +32647,21 @@ function normalizeConfigValues(value) {
33084
32647
  function normalizeConfigOptions(value, modes) {
33085
32648
  const normalized = [];
33086
32649
  if (Array.isArray(value)) {
33087
- for (const option2 of value) {
33088
- if (!isRecord9(option2)) {
32650
+ for (const option of value) {
32651
+ if (!isRecord7(option)) {
33089
32652
  continue;
33090
32653
  }
33091
- const id = truncate2(readString2(option2["id"]), 128);
33092
- const name = truncate2(readString2(option2["name"], id), 255);
32654
+ const id = truncate2(readString2(option["id"]), 128);
32655
+ const name = truncate2(readString2(option["name"], id), 255);
33093
32656
  if (id.length === 0 || name.length === 0) {
33094
32657
  continue;
33095
32658
  }
33096
- if (option2["type"] === "boolean") {
32659
+ if (option["type"] === "boolean") {
33097
32660
  normalized.push({
33098
- booleanValue: readBoolean(option2["currentValue"]),
33099
- category: truncate2(readString2(option2["category"]), 128),
32661
+ booleanValue: readBoolean(option["currentValue"]),
32662
+ category: truncate2(readString2(option["category"]), 128),
33100
32663
  currentValue: "",
33101
- description: truncate2(readString2(option2["description"]), 500),
32664
+ description: truncate2(readString2(option["description"]), 500),
33102
32665
  id,
33103
32666
  name,
33104
32667
  type: "boolean",
@@ -33106,15 +32669,15 @@ function normalizeConfigOptions(value, modes) {
33106
32669
  });
33107
32670
  continue;
33108
32671
  }
33109
- if (option2["type"] === "select") {
33110
- const values = normalizeConfigValues(option2["options"]);
33111
- const currentValue = truncate2(readString2(option2["currentValue"]), 500);
32672
+ if (option["type"] === "select") {
32673
+ const values = normalizeConfigValues(option["options"]);
32674
+ const currentValue = truncate2(readString2(option["currentValue"]), 500);
33112
32675
  if (currentValue.length > 0 && values.some((entry) => entry.value === currentValue)) {
33113
32676
  normalized.push({
33114
32677
  booleanValue: false,
33115
- category: truncate2(readString2(option2["category"]), 128),
32678
+ category: truncate2(readString2(option["category"]), 128),
33116
32679
  currentValue,
33117
- description: truncate2(readString2(option2["description"]), 500),
32680
+ description: truncate2(readString2(option["description"]), 500),
33118
32681
  id,
33119
32682
  name,
33120
32683
  type: "select",
@@ -33124,12 +32687,12 @@ function normalizeConfigOptions(value, modes) {
33124
32687
  }
33125
32688
  }
33126
32689
  }
33127
- if (isRecord9(modes)) {
32690
+ if (isRecord7(modes)) {
33128
32691
  const values = [];
33129
32692
  const availableModes = modes["availableModes"];
33130
32693
  if (Array.isArray(availableModes)) {
33131
32694
  for (const mode of availableModes) {
33132
- if (!isRecord9(mode)) {
32695
+ if (!isRecord7(mode)) {
33133
32696
  continue;
33134
32697
  }
33135
32698
  const id = truncate2(readString2(mode["id"]), 500);
@@ -33162,14 +32725,14 @@ function normalizeConfigOptions(value, modes) {
33162
32725
  return normalized.slice(0, 100);
33163
32726
  }
33164
32727
  function insertRequiredOption(current, required2, afterCategory = "") {
33165
- if (current.some((option2) => option2.id === required2.id || option2.category === required2.category)) {
32728
+ if (current.some((option) => option.id === required2.id || option.category === required2.category)) {
33166
32729
  return current;
33167
32730
  }
33168
32731
  if (current.length < MAXIMUM_CONFIG_OPTIONS) {
33169
32732
  if (afterCategory.length === 0) {
33170
32733
  return [required2, ...current];
33171
32734
  }
33172
- const index3 = current.findIndex((option2) => option2.category === afterCategory);
32735
+ const index3 = current.findIndex((option) => option.category === afterCategory);
33173
32736
  if (index3 < 0) {
33174
32737
  return [...current, required2];
33175
32738
  }
@@ -33178,7 +32741,7 @@ function insertRequiredOption(current, required2, afterCategory = "") {
33178
32741
  if (afterCategory.length === 0) {
33179
32742
  return [required2, ...current.slice(0, MAXIMUM_CONFIG_OPTIONS - 1)];
33180
32743
  }
33181
- const index2 = current.findIndex((option2) => option2.category === afterCategory);
32744
+ const index2 = current.findIndex((option) => option.category === afterCategory);
33182
32745
  if (index2 < 0) {
33183
32746
  return [...current.slice(0, MAXIMUM_CONFIG_OPTIONS - 1), required2];
33184
32747
  }
@@ -33191,11 +32754,11 @@ function insertRequiredOption(current, required2, afterCategory = "") {
33191
32754
  }
33192
32755
  return [...current.slice(0, MAXIMUM_CONFIG_OPTIONS - 2), anchor2, required2];
33193
32756
  }
33194
- function validRequiredSelect(option2) {
33195
- return option2.type === "select" && option2.currentValue.length > 0 && option2.values.some((value) => value.value === option2.currentValue);
32757
+ function validRequiredSelect(option) {
32758
+ return option.type === "select" && option.currentValue.length > 0 && option.values.some((value) => value.value === option.currentValue);
33196
32759
  }
33197
32760
  function ensureModelOption(current) {
33198
- const existing = current.find((option2) => option2.id === "model" || option2.category === "model");
32761
+ const existing = current.find((option) => option.id === "model" || option.category === "model");
33199
32762
  if (existing !== void 0 && validRequiredSelect(existing)) {
33200
32763
  return current;
33201
32764
  }
@@ -33218,12 +32781,12 @@ function ensureModelOption(current) {
33218
32781
  ]
33219
32782
  };
33220
32783
  return insertRequiredOption(
33221
- current.filter((option2) => option2.id !== "model" && option2.category !== "model"),
32784
+ current.filter((option) => option.id !== "model" && option.category !== "model"),
33222
32785
  unavailable
33223
32786
  );
33224
32787
  }
33225
32788
  function ensureReasoningEffortOption(current) {
33226
- const existing = current.find((option2) => option2.id === "reasoning_effort" || option2.category === "thought_level");
32789
+ const existing = current.find((option) => option.id === "reasoning_effort" || option.category === "thought_level");
33227
32790
  if (existing !== void 0 && validRequiredSelect(existing)) {
33228
32791
  return current;
33229
32792
  }
@@ -33246,7 +32809,7 @@ function ensureReasoningEffortOption(current) {
33246
32809
  ]
33247
32810
  };
33248
32811
  return insertRequiredOption(
33249
- current.filter((option2) => option2.id !== "reasoning_effort" && option2.category !== "thought_level"),
32812
+ current.filter((option) => option.id !== "reasoning_effort" && option.category !== "thought_level"),
33250
32813
  unavailable,
33251
32814
  "model"
33252
32815
  );
@@ -33254,34 +32817,34 @@ function ensureReasoningEffortOption(current) {
33254
32817
  function ensureRequiredExecutionOptions(current, permission) {
33255
32818
  const normalized = ensureReasoningEffortOption(ensureModelOption(current));
33256
32819
  const model = normalized.find(
33257
- (option2) => (option2.id === "model" || option2.category === "model") && validRequiredSelect(option2)
32820
+ (option) => (option.id === "model" || option.category === "model") && validRequiredSelect(option)
33258
32821
  );
33259
32822
  const reasoningEffort = normalized.find(
33260
- (option2) => (option2.id === "reasoning_effort" || option2.category === "thought_level") && validRequiredSelect(option2)
32823
+ (option) => (option.id === "reasoning_effort" || option.category === "thought_level") && validRequiredSelect(option)
33261
32824
  );
33262
32825
  if (model === void 0 || reasoningEffort === void 0) {
33263
32826
  throw new SessionConfigProtocolError("The required Agent execution settings are unavailable");
33264
32827
  }
33265
32828
  const optional2 = normalized.filter(
33266
- (option2) => option2.id !== permission.id && option2.category !== permission.category && option2.id !== "model" && option2.category !== "model" && option2.id !== "reasoning_effort" && option2.category !== "thought_level"
32829
+ (option) => option.id !== permission.id && option.category !== permission.category && option.id !== "model" && option.category !== "model" && option.id !== "reasoning_effort" && option.category !== "thought_level"
33267
32830
  );
33268
32831
  return [permission, model, reasoningEffort, ...optional2].slice(0, MAXIMUM_CONFIG_OPTIONS);
33269
32832
  }
33270
32833
  function normalizeStandardLifecycle(response) {
33271
- const lifecycle = isRecord9(response) ? response : {};
32834
+ const lifecycle = isRecord7(response) ? response : {};
33272
32835
  return ensureReasoningEffortOption(normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]));
33273
32836
  }
33274
32837
  function replaceStandardConfigOptions(current, value) {
33275
32838
  const next = normalizeConfigOptions(value, void 0);
33276
- const withMode = next.some((option2) => option2.category === "mode") ? next : [...current.filter((option2) => option2.category === "mode"), ...next].slice(0, 100);
32839
+ const withMode = next.some((option) => option.category === "mode") ? next : [...current.filter((option) => option.category === "mode"), ...next].slice(0, 100);
33277
32840
  return ensureReasoningEffortOption(withMode);
33278
32841
  }
33279
32842
  function updateCurrentValue(current, configId, value) {
33280
- return current.map((option2) => option2.id === configId ? { ...option2, currentValue: value } : option2);
32843
+ return current.map((option) => option.id === configId ? { ...option, currentValue: value } : option);
33281
32844
  }
33282
32845
  var StandardSessionConfigProtocol = class {
33283
32846
  configure = async (current, change, nativeSessionId, transport) => {
33284
- const existing = current.find((option2) => option2.id === change.configId);
32847
+ const existing = current.find((option) => option.id === change.configId);
33285
32848
  if (existing === void 0) {
33286
32849
  return current;
33287
32850
  }
@@ -33310,7 +32873,7 @@ var StandardSessionConfigProtocol = class {
33310
32873
  "ACP agent exited while changing session configuration",
33311
32874
  change.signal
33312
32875
  );
33313
- if (!isRecord9(response) || !Array.isArray(response["configOptions"])) {
32876
+ if (!isRecord7(response) || !Array.isArray(response["configOptions"])) {
33314
32877
  throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
33315
32878
  }
33316
32879
  return replaceStandardConfigOptions(current, response["configOptions"]);
@@ -33324,31 +32887,31 @@ var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
33324
32887
  var LEGACY_MODEL_CONFIG_ID = "grok_build_legacy_model";
33325
32888
  var LEGACY_REASONING_EFFORT_CONFIG_ID = "grok_build_legacy_reasoning_effort";
33326
32889
  function legacyOptions(response) {
33327
- if (!isRecord9(response)) {
32890
+ if (!isRecord7(response)) {
33328
32891
  return [];
33329
32892
  }
33330
32893
  const metadata = response["_meta"];
33331
- if (!isRecord9(metadata)) {
32894
+ if (!isRecord7(metadata)) {
33332
32895
  return [];
33333
32896
  }
33334
32897
  const sessionConfig = metadata["x.ai/sessionConfig"];
33335
- if (!isRecord9(sessionConfig) || !Array.isArray(sessionConfig["options"])) {
32898
+ if (!isRecord7(sessionConfig) || !Array.isArray(sessionConfig["options"])) {
33336
32899
  return [];
33337
32900
  }
33338
- return sessionConfig["options"].slice(0, 500).filter(isRecord9);
32901
+ return sessionConfig["options"].slice(0, 500).filter(isRecord7);
33339
32902
  }
33340
- function legacyValue(option2) {
33341
- const value = readString2(option2["id"]);
32903
+ function legacyValue(option) {
32904
+ const value = readString2(option["id"]);
33342
32905
  return {
33343
- description: readString2(option2["description"]).slice(0, 500),
32906
+ description: readString2(option["description"]).slice(0, 500),
33344
32907
  groupId: "",
33345
32908
  groupName: "",
33346
- name: readString2(option2["label"], value).slice(0, 255),
32909
+ name: readString2(option["label"], value).slice(0, 255),
33347
32910
  value: value.slice(0, 500)
33348
32911
  };
33349
32912
  }
33350
32913
  function modelsRecord(response) {
33351
- if (!isRecord9(response) || !isRecord9(response["models"])) {
32914
+ if (!isRecord7(response) || !isRecord7(response["models"])) {
33352
32915
  return {};
33353
32916
  }
33354
32917
  return response["models"];
@@ -33357,9 +32920,9 @@ function legacyModelOptions(response) {
33357
32920
  const options = legacyOptions(response);
33358
32921
  const models = modelsRecord(response);
33359
32922
  const values = [];
33360
- for (const option2 of options) {
33361
- if (option2["category"] === "model") {
33362
- const value = legacyValue(option2);
32923
+ for (const option of options) {
32924
+ if (option["category"] === "model") {
32925
+ const value = legacyValue(option);
33363
32926
  if (value.value.length > 0 && !values.some((existing) => existing.value === value.value)) {
33364
32927
  values.push(value);
33365
32928
  }
@@ -33367,7 +32930,7 @@ function legacyModelOptions(response) {
33367
32930
  }
33368
32931
  if (values.length === 0 && Array.isArray(models["availableModels"])) {
33369
32932
  for (const model of models["availableModels"]) {
33370
- if (!isRecord9(model)) {
32933
+ if (!isRecord7(model)) {
33371
32934
  continue;
33372
32935
  }
33373
32936
  const value = readString2(model["modelId"]).slice(0, 500);
@@ -33385,7 +32948,7 @@ function legacyModelOptions(response) {
33385
32948
  }
33386
32949
  }
33387
32950
  }
33388
- const selected = options.find((option2) => option2["category"] === "model" && option2["selected"] === true);
32951
+ const selected = options.find((option) => option["category"] === "model" && option["selected"] === true);
33389
32952
  const currentValue = readString2(
33390
32953
  models["currentModelId"],
33391
32954
  selected === void 0 ? "" : readString2(selected["id"])
@@ -33408,11 +32971,11 @@ function legacyModelOptions(response) {
33408
32971
  function legacyReasoningEffortOptions(response) {
33409
32972
  const options = legacyOptions(response);
33410
32973
  const values = [];
33411
- for (const option2 of options) {
33412
- if (option2["category"] !== "mode") {
32974
+ for (const option of options) {
32975
+ if (option["category"] !== "mode") {
33413
32976
  continue;
33414
32977
  }
33415
- const value = legacyValue(option2);
32978
+ const value = legacyValue(option);
33416
32979
  if (value.value.length > 0 && !values.some((existing) => existing.value === value.value)) {
33417
32980
  values.push(value);
33418
32981
  }
@@ -33420,7 +32983,7 @@ function legacyReasoningEffortOptions(response) {
33420
32983
  if (values.length === 0) {
33421
32984
  return [];
33422
32985
  }
33423
- const selected = options.find((option2) => option2["category"] === "mode" && option2["selected"] === true);
32986
+ const selected = options.find((option) => option["category"] === "mode" && option["selected"] === true);
33424
32987
  if (selected === void 0) {
33425
32988
  values.unshift({
33426
32989
  description: "Use the selected model's default reasoning effort",
@@ -33447,41 +33010,41 @@ function legacyReasoningEffortOptions(response) {
33447
33010
  return [result];
33448
33011
  }
33449
33012
  function normalizeGrokLifecycle(response) {
33450
- const lifecycle = isRecord9(response) ? response : {};
33013
+ const lifecycle = isRecord7(response) ? response : {};
33451
33014
  const standard = normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
33452
33015
  const normalized = [...standard];
33453
- if (!normalized.some((option2) => option2.category === "model")) {
33016
+ if (!normalized.some((option) => option.category === "model")) {
33454
33017
  normalized.push(...legacyModelOptions(response));
33455
33018
  }
33456
- if (!normalized.some((option2) => option2.category === "thought_level")) {
33019
+ if (!normalized.some((option) => option.category === "thought_level")) {
33457
33020
  const efforts = legacyReasoningEffortOptions(response);
33458
33021
  if (efforts.length > 0) {
33459
- const modelIndex = normalized.findIndex((option2) => option2.category === "model");
33022
+ const modelIndex = normalized.findIndex((option) => option.category === "model");
33460
33023
  normalized.splice(modelIndex < 0 ? normalized.length : modelIndex + 1, 0, ...efforts);
33461
33024
  }
33462
33025
  }
33463
33026
  return ensureReasoningEffortOption(normalized.slice(0, 100));
33464
33027
  }
33465
33028
  function updateCurrentValue2(current, category, value) {
33466
- return current.map((option2) => option2.category === category ? { ...option2, currentValue: value } : option2);
33029
+ return current.map((option) => option.category === category ? { ...option, currentValue: value } : option);
33467
33030
  }
33468
33031
  function validateGrokResponse(response, modelId) {
33469
- if (!isRecord9(response) || !isRecord9(response["_meta"])) {
33032
+ if (!isRecord7(response) || !isRecord7(response["_meta"])) {
33470
33033
  throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
33471
33034
  }
33472
33035
  const model = response["_meta"]["model"];
33473
- const appliedModel = isRecord9(model) ? model["Ok"] : model;
33036
+ const appliedModel = isRecord7(model) ? model["Ok"] : model;
33474
33037
  if (appliedModel !== modelId) {
33475
33038
  throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
33476
33039
  }
33477
33040
  }
33478
33041
  var GrokBuildSessionConfigProtocol = class {
33479
33042
  configure = async (current, change, nativeSessionId, transport) => {
33480
- const existing = current.find((option2) => option2.id === change.configId);
33043
+ const existing = current.find((option) => option.id === change.configId);
33481
33044
  if (existing === void 0 || existing.id !== LEGACY_MODEL_CONFIG_ID && existing.id !== LEGACY_REASONING_EFFORT_CONFIG_ID) {
33482
33045
  return await standardSessionConfigProtocol.configure(current, change, nativeSessionId, transport);
33483
33046
  }
33484
- const model = current.find((option2) => option2.category === "model");
33047
+ const model = current.find((option) => option.category === "model");
33485
33048
  if (model === void 0) {
33486
33049
  return current;
33487
33050
  }
@@ -33507,10 +33070,10 @@ var GrokBuildSessionConfigProtocol = class {
33507
33070
  validateGrokResponse(response, modelId);
33508
33071
  const updated = updateCurrentValue2(current, existing.category, change.value);
33509
33072
  return existing.category === "thought_level" ? updated.map(
33510
- (option2) => option2.category === "thought_level" ? {
33511
- ...option2,
33512
- values: option2.values.filter((value) => value.value !== AGENT_DEFAULT_REASONING_EFFORT)
33513
- } : option2
33073
+ (option) => option.category === "thought_level" ? {
33074
+ ...option,
33075
+ values: option.values.filter((value) => value.value !== AGENT_DEFAULT_REASONING_EFFORT)
33076
+ } : option
33514
33077
  ) : updated;
33515
33078
  };
33516
33079
  normalizeLifecycle = (response) => normalizeGrokLifecycle(response);
@@ -33784,6 +33347,7 @@ var MAX_ACP_PROCESSES = 10;
33784
33347
  var MAX_PRE_SESSION_UPDATES = 100;
33785
33348
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
33786
33349
  var SESSION_CONTROL_COMMAND_ID = "session-control";
33350
+ var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
33787
33351
  var NullAcpSessionObserver = class {
33788
33352
  importLocalArtifact = (_sessionId, _artifact, signal) => {
33789
33353
  signal.throwIfAborted();
@@ -34002,7 +33566,7 @@ function createWritableAcpStream(output2) {
34002
33566
  function truncate3(value, maximumLength) {
34003
33567
  return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
34004
33568
  }
34005
- function isRecord10(value) {
33569
+ function isRecord8(value) {
34006
33570
  return typeof value === "object" && value !== null && !Array.isArray(value);
34007
33571
  }
34008
33572
  function readString4(value, fallback = "") {
@@ -34035,12 +33599,12 @@ function normalizeElicitationOptions(schema) {
34035
33599
  const normalized = [];
34036
33600
  const oneOf = schema["oneOf"];
34037
33601
  if (Array.isArray(oneOf)) {
34038
- for (const option2 of oneOf) {
34039
- if (isRecord10(option2) && typeof option2["const"] === "string") {
33602
+ for (const option of oneOf) {
33603
+ if (isRecord8(option) && typeof option["const"] === "string") {
34040
33604
  normalized.push({
34041
- description: truncate3(readString4(option2["description"]), 500),
34042
- label: truncate3(readString4(option2["title"], option2["const"]), 255),
34043
- value: truncate3(option2["const"], 500)
33605
+ description: truncate3(readString4(option["description"]), 500),
33606
+ label: truncate3(readString4(option["title"], option["const"]), 255),
33607
+ value: truncate3(option["const"], 500)
34044
33608
  });
34045
33609
  }
34046
33610
  }
@@ -34056,7 +33620,7 @@ function normalizeElicitationOptions(schema) {
34056
33620
  return normalized.slice(0, 200);
34057
33621
  }
34058
33622
  const items = schema["items"];
34059
- if (!isRecord10(items)) {
33623
+ if (!isRecord8(items)) {
34060
33624
  return normalized;
34061
33625
  }
34062
33626
  const anyOf = items["anyOf"];
@@ -34069,7 +33633,7 @@ function numericString(value) {
34069
33633
  return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
34070
33634
  }
34071
33635
  function normalizeElicitationFields(requestedSchema) {
34072
- if (!isRecord10(requestedSchema) || !isRecord10(requestedSchema["properties"])) {
33636
+ if (!isRecord8(requestedSchema) || !isRecord8(requestedSchema["properties"])) {
34073
33637
  return [];
34074
33638
  }
34075
33639
  const properties2 = requestedSchema["properties"];
@@ -34079,7 +33643,7 @@ function normalizeElicitationFields(requestedSchema) {
34079
33643
  );
34080
33644
  const normalized = [];
34081
33645
  for (const [name, property] of Object.entries(properties2)) {
34082
- if (!isRecord10(property)) {
33646
+ if (!isRecord8(property)) {
34083
33647
  continue;
34084
33648
  }
34085
33649
  const type = elicitationFieldType(property["type"]);
@@ -34170,7 +33734,7 @@ function validateElicitationContent(encoded, requestedSchema) {
34170
33734
  "invalid_elicitation_response"
34171
33735
  );
34172
33736
  }
34173
- if (!isRecord10(decoded) || !isRecord10(requestedSchema) || !isRecord10(requestedSchema["properties"])) {
33737
+ if (!isRecord8(decoded) || !isRecord8(requestedSchema) || !isRecord8(requestedSchema["properties"])) {
34174
33738
  throw new AcpExecutionError(
34175
33739
  "Elicitation response does not match the requested form",
34176
33740
  {},
@@ -34190,7 +33754,7 @@ function validateElicitationContent(encoded, requestedSchema) {
34190
33754
  const validated = {};
34191
33755
  for (const [name, value] of Object.entries(decoded)) {
34192
33756
  const property = properties2[name];
34193
- if (!isRecord10(property)) {
33757
+ if (!isRecord8(property)) {
34194
33758
  throw new AcpExecutionError(
34195
33759
  `Elicitation field ${name} was not requested`,
34196
33760
  {},
@@ -34227,7 +33791,7 @@ function validateElicitationContent(encoded, requestedSchema) {
34227
33791
  );
34228
33792
  }
34229
33793
  const allowed = normalizeElicitationOptions(property);
34230
- if (allowed.length > 0 && value.some((entry) => !allowed.some((option2) => option2.value === entry))) {
33794
+ if (allowed.length > 0 && value.some((entry) => !allowed.some((option) => option.value === entry))) {
34231
33795
  throw new AcpExecutionError(
34232
33796
  `Elicitation field ${name} contains an invalid selection`,
34233
33797
  {},
@@ -34343,6 +33907,7 @@ var AcpProcessSession = class _AcpProcessSession {
34343
33907
  #permissionProfile;
34344
33908
  #sessionConfigProtocol;
34345
33909
  #store;
33910
+ #emittedToolImages = /* @__PURE__ */ new Set();
34346
33911
  #verifiedAgentVersion;
34347
33912
  #preSessionUpdateBytes = 0;
34348
33913
  #agentName = "";
@@ -34563,19 +34128,19 @@ var AcpProcessSession = class _AcpProcessSession {
34563
34128
  }
34564
34129
  };
34565
34130
  prepareAgentContent = async (content3) => {
34566
- if (content3.type === "image" && content3.data.length > 0) {
34567
- const raster = readInlineRaster(content3.data, content3.name);
34568
- if (raster !== null) {
34569
- return await this.importRaster(raster, AbortSignal.timeout(2e4));
34570
- }
34571
- }
34572
- if (content3.type === "image" && content3.data.length === 0 && content3.uri.length > 0) {
34131
+ if (content3.type === "image" && content3.uri.length > 0) {
34573
34132
  const signal = AbortSignal.timeout(2e4);
34574
34133
  const raster = await readLocalRaster(content3.uri, signal);
34575
34134
  if (raster !== null) {
34576
34135
  return await this.importRaster(raster, signal);
34577
34136
  }
34578
34137
  }
34138
+ if (content3.type === "image" && content3.data.length > 0) {
34139
+ const raster = readInlineRaster(content3.data, content3.name);
34140
+ if (raster !== null) {
34141
+ return await this.importRaster(raster, AbortSignal.timeout(2e4));
34142
+ }
34143
+ }
34579
34144
  if (content3.type === "video" && content3.data.length > 0) {
34580
34145
  const video = readInlineVideo(content3.data, content3.mimeType, content3.name);
34581
34146
  if (video === null) {
@@ -34596,6 +34161,22 @@ var AcpProcessSession = class _AcpProcessSession {
34596
34161
  sessionId: this.#mobiusSessionId
34597
34162
  });
34598
34163
  };
34164
+ emitToolImages = async (update) => {
34165
+ if (update.status !== "completed") {
34166
+ return;
34167
+ }
34168
+ for (const [index2, item] of (update.content ?? []).entries()) {
34169
+ if (item.type !== "content" || item.content.type !== "image") {
34170
+ continue;
34171
+ }
34172
+ const key = `${update.toolCallId}:${index2.toString()}`;
34173
+ if (this.#emittedToolImages.has(key)) {
34174
+ continue;
34175
+ }
34176
+ this.#emittedToolImages.add(key);
34177
+ await this.emitAgentContent(normalizeContentBlock(item.content), `tool-${key}`);
34178
+ }
34179
+ };
34599
34180
  emitRaster = async (raster, messageId, signal) => {
34600
34181
  const content3 = await this.importRaster(raster, signal);
34601
34182
  await this.#getObserver().onContent({
@@ -34607,14 +34188,14 @@ var AcpProcessSession = class _AcpProcessSession {
34607
34188
  sessionId: this.#mobiusSessionId
34608
34189
  });
34609
34190
  };
34610
- importRaster = async (raster, signal) => {
34611
- const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, raster, signal);
34612
- return imageDisplayContent(
34613
- raster.mimeType,
34614
- raster.name,
34615
- artifactId.length > 0 ? "" : raster.base64(),
34616
- artifactId
34617
- );
34191
+ importRaster = async (raster, _signal) => {
34192
+ if (raster.sourceUri.length > 0) {
34193
+ return {
34194
+ ...imageDisplayContent(raster.mimeType, raster.name, "", ""),
34195
+ uri: raster.sourceUri
34196
+ };
34197
+ }
34198
+ return imageDisplayContent(raster.mimeType, raster.name, await raster.base64(), "");
34618
34199
  };
34619
34200
  importVideo = async (video, signal) => {
34620
34201
  const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, video, signal);
@@ -34901,7 +34482,7 @@ var AcpProcessSession = class _AcpProcessSession {
34901
34482
  };
34902
34483
  nativeSessionId = () => this.#nativeSessionId;
34903
34484
  configure = async (options) => {
34904
- const existing = this.#configOptions.find((option2) => option2.id === options.configId);
34485
+ const existing = this.#configOptions.find((option) => option.id === options.configId);
34905
34486
  if (existing === void 0 || existing.type !== options.valueType) {
34906
34487
  throw new AcpExecutionError(
34907
34488
  "The requested ACP configuration option is unavailable",
@@ -35098,7 +34679,7 @@ var AcpProcessSession = class _AcpProcessSession {
35098
34679
  "ACP agent exited during steering",
35099
34680
  options.signal
35100
34681
  );
35101
- if (!isRecord10(response)) {
34682
+ if (!isRecord8(response)) {
35102
34683
  throw new AcpExecutionError(
35103
34684
  "ACP agent returned an invalid steering response",
35104
34685
  {},
@@ -35213,10 +34794,10 @@ var AcpProcessSession = class _AcpProcessSession {
35213
34794
  onPermission = async (request, signal) => {
35214
34795
  this.assertNativeSession(request.sessionId);
35215
34796
  const interactionId = `permission-${crypto.randomUUID()}`;
35216
- const options = request.options.slice(0, 20).map((option2) => ({
35217
- kind: option2.kind,
35218
- name: truncate3(option2.name, 255),
35219
- optionId: truncate3(option2.optionId, 255)
34797
+ const options = request.options.slice(0, 20).map((option) => ({
34798
+ kind: option.kind,
34799
+ name: truncate3(option.name, 255),
34800
+ optionId: truncate3(option.optionId, 255)
35220
34801
  }));
35221
34802
  if (options.length === 0) {
35222
34803
  throw new AcpExecutionError(
@@ -35225,7 +34806,7 @@ var AcpProcessSession = class _AcpProcessSession {
35225
34806
  "invalid_agent_permission_request"
35226
34807
  );
35227
34808
  }
35228
- const pending = new PendingPermission(interactionId, new Set(options.map((option2) => option2.optionId)));
34809
+ const pending = new PendingPermission(interactionId, new Set(options.map((option) => option.optionId)));
35229
34810
  this.#pendingPermissions.set(interactionId, pending);
35230
34811
  const abort = () => {
35231
34812
  void this.cancelPermission(interactionId);
@@ -35394,6 +34975,7 @@ var AcpProcessSession = class _AcpProcessSession {
35394
34975
  }
35395
34976
  if (update.sessionUpdate === "tool_call_update") {
35396
34977
  await this.#turn.activities.recordToolCallUpdate(update);
34978
+ await this.emitToolImages(update);
35397
34979
  return;
35398
34980
  }
35399
34981
  if (update.sessionUpdate === "plan") {
@@ -35433,7 +35015,7 @@ var AcpProcessSession = class _AcpProcessSession {
35433
35015
  }
35434
35016
  if (update.sessionUpdate === "current_mode_update") {
35435
35017
  this.#configOptions = this.#configOptions.map(
35436
- (option2) => option2.category === "mode" ? { ...option2, currentValue: update.currentModeId } : option2
35018
+ (option) => option.category === "mode" ? { ...option, currentValue: update.currentModeId } : option
35437
35019
  );
35438
35020
  this.#configRevision += 1;
35439
35021
  await this.emitConfigUpdate();
@@ -35966,7 +35548,7 @@ var AcpSessionManager = class {
35966
35548
  if (desired.id === PERMISSION_MODE_CONFIG_ID) {
35967
35549
  continue;
35968
35550
  }
35969
- const current = runtime.prepared().configOptions.find((option2) => option2.id === desired.id);
35551
+ const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
35970
35552
  if (current === void 0 || current.type !== desired.type) {
35971
35553
  continue;
35972
35554
  }
@@ -36072,7 +35654,7 @@ var AcpSessionManager = class {
36072
35654
  async (runtime) => await runtime.close()
36073
35655
  );
36074
35656
  /**
36075
- * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
35657
+ * Retained for Agents that expose a separate persisted configuration channel.
36076
35658
  * Use inspectAgentSettings for Agent-scoped settings discovery.
36077
35659
  */
36078
35660
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
@@ -36234,7 +35816,7 @@ var AcpSessionManager = class {
36234
35816
  () => deadlineController.abort(
36235
35817
  new AcpExecutionError("The steering request exceeded its deadline", {}, "steering_timeout")
36236
35818
  ),
36237
- options.agent.promptTimeoutMilliseconds
35819
+ SESSION_CONTROL_TIMEOUT_MILLISECONDS
36238
35820
  );
36239
35821
  deadline.unref();
36240
35822
  try {
@@ -36259,28 +35841,13 @@ var AcpSessionManager = class {
36259
35841
  if (this.#activeSessionIds.has(options.sessionId)) {
36260
35842
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
36261
35843
  }
36262
- const deadlineController = new AbortController();
36263
- const deadlineError = new AcpExecutionError(
36264
- "The local Agent prompt exceeded its deadline",
36265
- {},
36266
- "prompt_timeout"
36267
- );
36268
- const deadline = setTimeout(
36269
- () => deadlineController.abort(deadlineError),
36270
- options.agent.promptTimeoutMilliseconds
36271
- );
36272
- deadline.unref();
36273
- const boundedOptions = {
36274
- ...options,
36275
- signal: AbortSignal.any([options.signal, deadlineController.signal])
36276
- };
36277
35844
  this.#activeSessionIds.add(options.sessionId);
36278
35845
  this.#activeCommandIds.set(options.sessionId, options.commandId);
36279
35846
  try {
36280
35847
  if (this.#cancellationRequests.has(options.sessionId)) {
36281
35848
  return { stopReason: "cancelled" };
36282
35849
  }
36283
- const runtime = await this.ensureSession(boundedOptions);
35850
+ const runtime = await this.ensureSession(options);
36284
35851
  if (this.#nativeOperations.has(`${options.agent.id}:${runtime.nativeSessionId()}`)) {
36285
35852
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
36286
35853
  }
@@ -36288,7 +35855,7 @@ var AcpSessionManager = class {
36288
35855
  return { stopReason: "cancelled" };
36289
35856
  }
36290
35857
  try {
36291
- const result = await runtime.prompt(boundedOptions);
35858
+ const result = await runtime.prompt(options);
36292
35859
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
36293
35860
  } catch (error62) {
36294
35861
  if (this.#cancellationRequests.has(options.sessionId)) {
@@ -36316,7 +35883,6 @@ var AcpSessionManager = class {
36316
35883
  cause: error62
36317
35884
  });
36318
35885
  } finally {
36319
- clearTimeout(deadline);
36320
35886
  try {
36321
35887
  await this.#cancellationRequests.get(options.sessionId);
36322
35888
  } finally {
@@ -36682,7 +36248,6 @@ async function publishAgentCatalog(config2, signal) {
36682
36248
  agentPath: agent.agentIdentity.requestedPath,
36683
36249
  agentVersion: agent.agentVersion,
36684
36250
  agentSettingsDiscovery: true,
36685
- botSessionConfiguration: true,
36686
36251
  capabilities: agent.capabilities,
36687
36252
  id: agent.id,
36688
36253
  label: agent.label,
@@ -37169,6 +36734,91 @@ var FixedInstallationExecutor = class {
37169
36734
  };
37170
36735
  };
37171
36736
 
36737
+ // src/artifacts/local-file-streamer.ts
36738
+ import { createReadStream as createReadStream2 } from "node:fs";
36739
+ import { realpath as realpath8, stat as stat7 } from "node:fs/promises";
36740
+ import { basename as basename4, isAbsolute as isAbsolute9, normalize as normalize3 } from "node:path";
36741
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
36742
+ var CHUNK_BYTES = 192 * 1024;
36743
+ function requestedPath(value) {
36744
+ if (value.includes("\0")) {
36745
+ return null;
36746
+ }
36747
+ if (value.startsWith("file:")) {
36748
+ try {
36749
+ const url2 = new URL(value);
36750
+ return url2.protocol === "file:" && url2.host.length === 0 ? fileURLToPath2(url2) : null;
36751
+ } catch {
36752
+ return null;
36753
+ }
36754
+ }
36755
+ return value;
36756
+ }
36757
+ async function resolveFile(value, signal) {
36758
+ const requested = requestedPath(value);
36759
+ if (requested === null || !isAbsolute9(requested) || normalize3(requested) !== requested) {
36760
+ return null;
36761
+ }
36762
+ try {
36763
+ const target = await realpath8(requested);
36764
+ signal.throwIfAborted();
36765
+ return isAbsolute9(target) && normalize3(target) === target ? target : null;
36766
+ } catch {
36767
+ signal.throwIfAborted();
36768
+ return null;
36769
+ }
36770
+ }
36771
+ async function streamLocalFile(command, send2, signal) {
36772
+ const target = await resolveFile(command.path, signal);
36773
+ if (target === null) {
36774
+ throw new Error("The local file is unavailable");
36775
+ }
36776
+ const before = await stat7(target);
36777
+ signal.throwIfAborted();
36778
+ if (!before.isFile() || before.size < 1 || before.size > command.maxBytes) {
36779
+ throw new Error("The local file is too large to read");
36780
+ }
36781
+ const raster = await readLocalRaster(target, signal);
36782
+ send2(
36783
+ encodeFileBeginEvent({
36784
+ byteLength: before.size,
36785
+ kind: FILE_BEGIN_KIND,
36786
+ mediaType: raster?.mimeType ?? "application/octet-stream",
36787
+ modifiedAt: before.mtime.toISOString(),
36788
+ name: basename4(target) || "file",
36789
+ requestId: command.requestId,
36790
+ sessionId: command.sessionId
36791
+ })
36792
+ );
36793
+ let sequence = 0;
36794
+ const stream = createReadStream2(target, { highWaterMark: CHUNK_BYTES, signal });
36795
+ for await (const value of stream) {
36796
+ const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
36797
+ send2(
36798
+ encodeFileChunkEvent({
36799
+ data: Buffer.from(bytes).toString("base64"),
36800
+ kind: FILE_CHUNK_KIND,
36801
+ requestId: command.requestId,
36802
+ sequence,
36803
+ sessionId: command.sessionId
36804
+ })
36805
+ );
36806
+ sequence += 1;
36807
+ }
36808
+ const after = await stat7(target);
36809
+ signal.throwIfAborted();
36810
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) {
36811
+ throw new Error("The local file changed during transfer");
36812
+ }
36813
+ send2(
36814
+ encodeFileEndEvent({
36815
+ kind: FILE_END_KIND,
36816
+ requestId: command.requestId,
36817
+ sessionId: command.sessionId
36818
+ })
36819
+ );
36820
+ }
36821
+
37172
36822
  // src/artifacts/runtime-artifact-uploader.ts
37173
36823
  import { createHash as createHash2 } from "node:crypto";
37174
36824
 
@@ -37195,15 +36845,15 @@ var MobiusValidationError = class extends MobiusError {
37195
36845
  };
37196
36846
 
37197
36847
  // ../mobius-sdk/src/resources.ts
37198
- var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
36848
+ var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
37199
36849
  function invalidResponse(message) {
37200
36850
  return new MobiusProtocolError(message);
37201
36851
  }
37202
- function isRecord11(value) {
36852
+ function isRecord9(value) {
37203
36853
  return typeof value === "object" && value !== null && !Array.isArray(value);
37204
36854
  }
37205
36855
  function record3(value, name) {
37206
- if (!isRecord11(value)) {
36856
+ if (!isRecord9(value)) {
37207
36857
  throw invalidResponse(`The service returned an invalid ${name}`);
37208
36858
  }
37209
36859
  return value;
@@ -37217,7 +36867,7 @@ function stringField(value, field, maximumLength = 85e5) {
37217
36867
  }
37218
36868
  function identifierField(value, field) {
37219
36869
  const candidate = stringField(value, field, 128);
37220
- if (!IDENTIFIER_PATTERN6.test(candidate)) {
36870
+ if (!IDENTIFIER_PATTERN5.test(candidate)) {
37221
36871
  throw invalidResponse(`The service returned an invalid ${field}`);
37222
36872
  }
37223
36873
  return candidate;
@@ -37564,9 +37214,9 @@ var LocalAuthorizationError = class extends Error {
37564
37214
  };
37565
37215
 
37566
37216
  // src/authorization/workspace-directory.ts
37567
- import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
37217
+ import { readdir as readdir2, realpath as realpath9, stat as stat8 } from "node:fs/promises";
37568
37218
  import { homedir as homedir2 } from "node:os";
37569
- import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute9, join as join16, normalize as normalize3, relative as relative4 } from "node:path";
37219
+ import { basename as basename5, dirname as dirname5, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
37570
37220
  var WorkspaceDirectoryListing = class {
37571
37221
  directoryId;
37572
37222
  directoryLabel;
@@ -37592,7 +37242,7 @@ function decodePath(value, prefix) {
37592
37242
  throw new LocalAuthorizationError("The directory identifier is invalid");
37593
37243
  }
37594
37244
  const decoded = Buffer.from(encoded, "base64url").toString("utf8");
37595
- if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize3(decoded) !== decoded) {
37245
+ if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize4(decoded) !== decoded) {
37596
37246
  throw new LocalAuthorizationError("The directory identifier is invalid");
37597
37247
  }
37598
37248
  return decoded;
@@ -37618,7 +37268,7 @@ var WorkspaceDirectoryService = class {
37618
37268
  }
37619
37269
  if (id.startsWith("path-")) {
37620
37270
  const path2 = decodePath(id, "path-");
37621
- if (isAbsolute9(path2)) {
37271
+ if (isAbsolute10(path2)) {
37622
37272
  return path2;
37623
37273
  }
37624
37274
  }
@@ -37626,15 +37276,15 @@ var WorkspaceDirectoryService = class {
37626
37276
  };
37627
37277
  resolvePath = async (requested, signal) => {
37628
37278
  signal.throwIfAborted();
37629
- if (!isAbsolute9(requested) || requested.includes("\0") || normalize3(requested) !== requested) {
37279
+ if (!isAbsolute10(requested) || requested.includes("\0") || normalize4(requested) !== requested) {
37630
37280
  throw new LocalAuthorizationError("The local directory path is invalid");
37631
37281
  }
37632
37282
  try {
37633
- const target = await realpath8(requested);
37283
+ const target = await realpath9(requested);
37634
37284
  signal.throwIfAborted();
37635
- const metadata = await stat7(target);
37285
+ const metadata = await stat8(target);
37636
37286
  signal.throwIfAborted();
37637
- if (!isAbsolute9(target) || normalize3(target) !== target || !metadata.isDirectory()) {
37287
+ if (!isAbsolute10(target) || normalize4(target) !== target || !metadata.isDirectory()) {
37638
37288
  throw new LocalAuthorizationError("The selected location is not a directory");
37639
37289
  }
37640
37290
  return target;
@@ -37650,15 +37300,15 @@ var WorkspaceDirectoryService = class {
37650
37300
  };
37651
37301
  label = (path2) => {
37652
37302
  const suffix = relative4(homedir2(), path2);
37653
- return suffix === "" ? "~" : !isAbsolute9(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
37303
+ return suffix === "" ? "~" : !isAbsolute10(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
37654
37304
  };
37655
- identify = async (bindingId, requestedPath, signal) => {
37305
+ identify = async (bindingId, requestedPath2, signal) => {
37656
37306
  this.authorizeMachine(bindingId);
37657
- const path2 = await this.resolvePath(requestedPath, signal);
37307
+ const path2 = await this.resolvePath(requestedPath2, signal);
37658
37308
  return {
37659
37309
  path: path2,
37660
37310
  directoryId: encodePath(path2),
37661
- name: basename4(path2) || path2,
37311
+ name: basename5(path2) || path2,
37662
37312
  label: this.label(path2)
37663
37313
  };
37664
37314
  };
@@ -37714,446 +37364,9 @@ var WorkspaceDirectoryService = class {
37714
37364
  };
37715
37365
  };
37716
37366
 
37717
- // src/bots/local-bot-execution-authorizer.ts
37718
- var LocalBotAuthorizationError = class extends Error {
37719
- code;
37720
- constructor(code, message, options = {}) {
37721
- super(message, options);
37722
- this.code = code;
37723
- this.name = "LocalBotAuthorizationError";
37724
- }
37725
- };
37726
- var AuthorizedLocalBotExecution = class {
37727
- agent;
37728
- behaviorDigest;
37729
- behaviorRevisionId;
37730
- bindingId;
37731
- bindingRevision;
37732
- botId;
37733
- executionConfiguration;
37734
- workspacePath;
37735
- workspaceRef;
37736
- constructor(command, agent, workspacePath) {
37737
- this.agent = agent;
37738
- this.behaviorDigest = command.behaviorDigest;
37739
- this.behaviorRevisionId = command.behaviorRevisionId;
37740
- this.bindingId = command.bindingId;
37741
- this.bindingRevision = command.bindingRevision;
37742
- this.botId = command.botId;
37743
- this.executionConfiguration = command.executionConfiguration;
37744
- this.workspacePath = workspacePath;
37745
- this.workspaceRef = command.directoryId;
37746
- }
37747
- };
37748
- var LocalBotExecutionAuthorizer = class {
37749
- authorize = async (command, catalog, directories, bindingAuthorityId, signal) => {
37750
- signal.throwIfAborted();
37751
- let agent;
37752
- try {
37753
- agent = catalog.find(command.agentId).withPermissionMode(command.executionConfiguration.permissionMode);
37754
- } catch (cause) {
37755
- if (cause instanceof AgentPermissionConfigurationError) {
37756
- throw new LocalBotAuthorizationError("binding_incompatible", cause.message, { cause });
37757
- }
37758
- throw cause;
37759
- }
37760
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
37761
- revalidateExecutable(agent.adapterIdentity),
37762
- revalidateExecutable(agent.agentIdentity)
37763
- ]);
37764
- signal.throwIfAborted();
37765
- if (!adapterUnchanged || !agentUnchanged) {
37766
- throw new LocalBotAuthorizationError(
37767
- "binding_incompatible",
37768
- "The local Agent executable changed while the Runtime is active; restart the Runtime"
37769
- );
37770
- }
37771
- if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
37772
- throw new LocalBotAuthorizationError(
37773
- "binding_incompatible",
37774
- "The local Agent cannot apply the Bot behavior"
37775
- );
37776
- }
37777
- const workspacePath = await directories.resolve(bindingAuthorityId, command.directoryId, signal);
37778
- signal.throwIfAborted();
37779
- return new AuthorizedLocalBotExecution(command, agent, workspacePath);
37780
- };
37781
- };
37782
-
37783
- // src/bots/bot-context-applicator.ts
37784
- var AppliedBotContext = class {
37785
- resources;
37786
- constructor(resources) {
37787
- this.resources = Object.freeze([...resources]);
37788
- }
37789
- };
37790
- var EmbeddedBotContextApplicator = class {
37791
- apply = async (command, execution, resources, signal) => {
37792
- signal.throwIfAborted();
37793
- if (execution.botId !== command.botId || execution.behaviorRevisionId !== command.behaviorRevisionId || execution.behaviorDigest !== command.behaviorDigest) {
37794
- throw new LocalBotAuthorizationError(
37795
- "binding_incompatible",
37796
- "The Bot behavior does not match the execution target"
37797
- );
37798
- }
37799
- if (command.behaviorInstructions.length === 0) {
37800
- return new AppliedBotContext(resources);
37801
- }
37802
- if (!execution.agent.capabilities.embeddedContextPrompt) {
37803
- throw new LocalBotAuthorizationError(
37804
- "binding_incompatible",
37805
- "The local Agent cannot enforce the Bot behavior context"
37806
- );
37807
- }
37808
- const trustedContext = {
37809
- mimeType: "text/markdown",
37810
- name: "Mobius Bot behavior",
37811
- text: command.behaviorInstructions,
37812
- type: "embedded",
37813
- uri: `mobius://bots/${encodeURIComponent(command.botId)}/behavior-revisions/${encodeURIComponent(command.behaviorRevisionId)}?sha256=${command.behaviorDigest}`
37814
- };
37815
- return new AppliedBotContext([trustedContext, ...resources]);
37816
- };
37817
- };
37818
-
37819
- // src/bots/bot-execution-context.ts
37820
- import { randomBytes } from "node:crypto";
37821
- var ActiveBotExecutionContext = class {
37822
- command;
37823
- contextHandle;
37824
- constructor(contextHandle, command) {
37825
- this.contextHandle = contextHandle;
37826
- this.command = command;
37827
- }
37828
- resolveTarget = (target) => {
37829
- if (target === "current") {
37830
- if (!(this.command.replyRoute instanceof BotConnectionReplyRoute)) {
37831
- throw new LocalBotAuthorizationError(
37832
- "delivery_target_not_allowed",
37833
- "This Bot conversation has no external reply target"
37834
- );
37835
- }
37836
- return this.command.replyRoute.deliveryTargetId;
37837
- }
37838
- const resolved = this.command.allowedDeliveryTargets.find((candidate) => candidate.alias === target);
37839
- if (resolved === void 0) {
37840
- throw new LocalBotAuthorizationError(
37841
- "delivery_target_not_allowed",
37842
- "The named Bot delivery target is not approved"
37843
- );
37844
- }
37845
- return resolved.deliveryTargetId;
37846
- };
37847
- };
37848
- var BotExecutionContextLease = class {
37849
- context;
37850
- #release;
37851
- #released = false;
37852
- constructor(context, release) {
37853
- this.context = context;
37854
- this.#release = release;
37855
- }
37856
- release = () => {
37857
- if (this.#released) {
37858
- return;
37859
- }
37860
- this.#released = true;
37861
- this.#release();
37862
- };
37863
- };
37864
- var BotExecutionContextRegistry = class {
37865
- #activeByHandle = /* @__PURE__ */ new Map();
37866
- #handlesBySession = /* @__PURE__ */ new Map();
37867
- #inactiveHandles = /* @__PURE__ */ new Set();
37868
- #now;
37869
- constructor(now = Date.now) {
37870
- this.#now = now;
37871
- }
37872
- activate = (command) => {
37873
- let handle = this.#handlesBySession.get(command.sessionId);
37874
- if (handle === void 0) {
37875
- handle = `ctx_${Buffer.from(randomBytes(32)).toString("base64url")}`;
37876
- this.#handlesBySession.set(command.sessionId, handle);
37877
- }
37878
- if (this.#activeByHandle.has(handle)) {
37879
- throw new LocalBotAuthorizationError("session_busy", "The Bot execution context is already active");
37880
- }
37881
- const context = new ActiveBotExecutionContext(handle, command);
37882
- this.#inactiveHandles.delete(handle);
37883
- this.#activeByHandle.set(handle, context);
37884
- return new BotExecutionContextLease(context, () => {
37885
- if (this.#activeByHandle.get(handle) === context) {
37886
- this.#activeByHandle.delete(handle);
37887
- this.#inactiveHandles.add(handle);
37888
- }
37889
- });
37890
- };
37891
- read = (handle) => {
37892
- const context = this.#activeByHandle.get(handle);
37893
- if (context === void 0) {
37894
- if (this.#inactiveHandles.has(handle)) {
37895
- throw new LocalBotAuthorizationError(
37896
- "execution_capability_expired",
37897
- "The Bot execution capability has expired"
37898
- );
37899
- }
37900
- throw new LocalBotAuthorizationError(
37901
- "execution_context_required",
37902
- "An active Bot execution context is required"
37903
- );
37904
- }
37905
- if (Date.parse(context.command.executionDeadlineAt) <= this.#now()) {
37906
- throw new LocalBotAuthorizationError(
37907
- "execution_capability_expired",
37908
- "The Bot execution capability has expired"
37909
- );
37910
- }
37911
- return context;
37912
- };
37913
- };
37914
-
37915
- // src/bots/bot-outbound-ipc.ts
37916
- import { chmod as chmod2, mkdir as mkdir4, unlink } from "node:fs/promises";
37917
- import { createServer } from "node:net";
37918
- import { dirname as dirname6, isAbsolute as isAbsolute10 } from "node:path";
37919
- import { fetch as fetch5 } from "undici";
37920
- var BOT_IPC_REQUEST_LIMIT = 32 * 1024;
37921
- var BOT_IPC_TIMEOUT_MILLISECONDS2 = 2e4;
37922
- var BOT_RELAY_TIMEOUT_MILLISECONDS = 2e4;
37923
- var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
37924
- var WINDOWS_NAMED_PIPE_PREFIX = "\\\\.\\pipe\\";
37925
- var BotOutboundIpcRequest = class {
37926
- contextHandle;
37927
- idempotencyKey;
37928
- target;
37929
- text;
37930
- constructor(contextHandle, idempotencyKey, target, text3) {
37931
- this.contextHandle = contextHandle;
37932
- this.idempotencyKey = idempotencyKey;
37933
- this.target = target;
37934
- this.text = text3;
37935
- }
37936
- };
37937
- function isRecord12(value) {
37938
- return typeof value === "object" && value !== null && !Array.isArray(value);
37939
- }
37940
- function decodeRequest(encoded) {
37941
- let value;
37942
- try {
37943
- value = JSON.parse(encoded);
37944
- } catch (cause) {
37945
- throw new LocalBotAuthorizationError("invalid_request", "The local Bot request is invalid", { cause });
37946
- }
37947
- if (!isRecord12(value)) {
37948
- throw new LocalBotAuthorizationError("invalid_request", "The local Bot request is invalid");
37949
- }
37950
- const keys = Object.keys(value);
37951
- if (keys.length !== 4 || !keys.every((key) => ["contextHandle", "idempotencyKey", "target", "text"].includes(key))) {
37952
- throw new LocalBotAuthorizationError("invalid_request", "The local Bot request fields are invalid");
37953
- }
37954
- const contextHandle = value["contextHandle"];
37955
- const idempotencyKey = value["idempotencyKey"];
37956
- const target = value["target"];
37957
- const text3 = value["text"];
37958
- if (typeof contextHandle !== "string" || !/^ctx_[a-zA-Z0-9_-]{43}$/.test(contextHandle) || typeof idempotencyKey !== "string" || !IDENTIFIER_PATTERN7.test(idempotencyKey) || typeof target !== "string" || !IDENTIFIER_PATTERN7.test(target) || typeof text3 !== "string" || text3.trim().length === 0 || text3.length > 1e4) {
37959
- throw new LocalBotAuthorizationError("invalid_request", "The local Bot request is invalid");
37960
- }
37961
- return new BotOutboundIpcRequest(contextHandle, idempotencyKey, target, text3);
37962
- }
37963
- function relayEndpoint(relayUrl, context, target) {
37964
- const endpoint = new URL(relayUrl);
37965
- if (endpoint.protocol !== "ws:" && endpoint.protocol !== "wss:") {
37966
- throw new LocalBotAuthorizationError("bot_service_unavailable", "The Mobius Relay URL is invalid");
37967
- }
37968
- endpoint.protocol = endpoint.protocol === "wss:" ? "https:" : "http:";
37969
- endpoint.search = "";
37970
- const execution = encodeURIComponent(context.command.executionId);
37971
- if (target === "current") {
37972
- context.resolveTarget(target);
37973
- endpoint.pathname = `${MOBIUS_API_PREFIX}/v1/bot-executions/${execution}/reply-messages`;
37974
- return endpoint;
37975
- }
37976
- const deliveryTargetId = context.resolveTarget(target);
37977
- endpoint.pathname = `${MOBIUS_API_PREFIX}/v1/bot-executions/${execution}/delivery-targets/${encodeURIComponent(deliveryTargetId)}/messages`;
37978
- return endpoint;
37979
- }
37980
- function daemonToken(relayUrl) {
37981
- const token = relayUrl.searchParams.get("token") ?? "";
37982
- if (!/^[a-zA-Z0-9_-]{32,256}$/.test(token)) {
37983
- throw new LocalBotAuthorizationError("bot_service_unavailable", "The Runtime credential is unavailable");
37984
- }
37985
- return token;
37986
- }
37987
- async function decodeRelayResponse(response) {
37988
- const encoded = await response.text();
37989
- let value;
37990
- try {
37991
- value = JSON.parse(encoded);
37992
- } catch (cause) {
37993
- throw new LocalBotAuthorizationError("bot_service_unavailable", "The Mobius Relay returned invalid data", {
37994
- cause
37995
- });
37996
- }
37997
- if (response.status === 202 && isRecord12(value) && typeof value["outboundMessageId"] === "string") {
37998
- return value["outboundMessageId"];
37999
- }
38000
- if (isRecord12(value) && isRecord12(value["error"])) {
38001
- const error62 = value["error"];
38002
- if (typeof error62["code"] === "string" && typeof error62["message"] === "string") {
38003
- throw new LocalBotAuthorizationError(error62["code"], error62["message"]);
38004
- }
38005
- }
38006
- throw new LocalBotAuthorizationError("bot_service_unavailable", "The Mobius Relay rejected the Bot action");
38007
- }
38008
- var BotOutboundIpcServer = class {
38009
- #registry;
38010
- #relayUrl;
38011
- #server;
38012
- #socketPath;
38013
- #usesFilesystemSocket;
38014
- constructor(socketPath, relayUrl, registry2) {
38015
- const usesFilesystemSocket = !socketPath.startsWith(WINDOWS_NAMED_PIPE_PREFIX);
38016
- if (usesFilesystemSocket && !isAbsolute10(socketPath)) {
38017
- throw new Error("The Bot IPC path must be absolute");
38018
- }
38019
- this.#registry = registry2;
38020
- this.#relayUrl = new URL(relayUrl);
38021
- this.#server = createServer({ allowHalfOpen: true }, (socket) => this.accept(socket));
38022
- this.#socketPath = socketPath;
38023
- this.#usesFilesystemSocket = usesFilesystemSocket;
38024
- }
38025
- get socketPath() {
38026
- return this.#socketPath;
38027
- }
38028
- listen = async (signal) => {
38029
- signal.throwIfAborted();
38030
- if (this.#usesFilesystemSocket) {
38031
- await mkdir4(dirname6(this.#socketPath), { mode: 448, recursive: true });
38032
- await unlink(this.#socketPath).catch((error62) => {
38033
- if (!isRecord12(error62) || error62["code"] !== "ENOENT") {
38034
- throw error62;
38035
- }
38036
- });
38037
- }
38038
- await new Promise((resolve5, reject) => {
38039
- const fail = (error62) => reject(error62);
38040
- this.#server.once("error", fail);
38041
- this.#server.listen(this.#socketPath, () => {
38042
- this.#server.removeListener("error", fail);
38043
- resolve5();
38044
- });
38045
- });
38046
- if (this.#usesFilesystemSocket) {
38047
- await chmod2(this.#socketPath, 384);
38048
- }
38049
- signal.addEventListener("abort", this.abort, { once: true });
38050
- if (signal.aborted) {
38051
- this.abort();
38052
- }
38053
- };
38054
- close = async () => {
38055
- if (this.#server.listening) {
38056
- await new Promise((resolve5, reject) => {
38057
- this.#server.close((error62) => {
38058
- if (error62 === void 0) {
38059
- resolve5();
38060
- return;
38061
- }
38062
- reject(error62);
38063
- });
38064
- });
38065
- }
38066
- if (this.#usesFilesystemSocket) {
38067
- await unlink(this.#socketPath).catch((error62) => {
38068
- if (!isRecord12(error62) || error62["code"] !== "ENOENT") {
38069
- throw error62;
38070
- }
38071
- });
38072
- }
38073
- };
38074
- #abort = () => {
38075
- this.#server.close();
38076
- };
38077
- abort = () => this.#abort();
38078
- accept = (socket) => {
38079
- const chunks = [];
38080
- let length = 0;
38081
- let rejected = false;
38082
- const controller = new AbortController();
38083
- socket.setTimeout(BOT_IPC_TIMEOUT_MILLISECONDS2, () => {
38084
- controller.abort(new Error("Bot IPC request timed out"));
38085
- socket.destroy();
38086
- });
38087
- socket.on("data", (chunk) => {
38088
- length += chunk.byteLength;
38089
- if (length > BOT_IPC_REQUEST_LIMIT) {
38090
- rejected = true;
38091
- controller.abort(new Error("Bot IPC request is too large"));
38092
- socket.end(
38093
- JSON.stringify({
38094
- error: { code: "invalid_request", message: "The local Bot request is too large" },
38095
- ok: false
38096
- })
38097
- );
38098
- return;
38099
- }
38100
- chunks.push(chunk);
38101
- });
38102
- socket.once("error", () => controller.abort());
38103
- socket.once("close", () => controller.abort());
38104
- socket.once("end", () => {
38105
- if (rejected) {
38106
- return;
38107
- }
38108
- void this.handle(Buffer.concat(chunks).toString("utf8").trim(), controller.signal).then(
38109
- (outboundMessageId) => {
38110
- if (!socket.destroyed) {
38111
- socket.end(JSON.stringify({ ok: true, outboundMessageId }));
38112
- }
38113
- },
38114
- (error62) => {
38115
- if (socket.destroyed) {
38116
- return;
38117
- }
38118
- const code = error62 instanceof LocalBotAuthorizationError ? error62.code : "bot_service_unavailable";
38119
- const message = error62 instanceof LocalBotAuthorizationError ? error62.message : "The local Bot action could not be completed";
38120
- socket.end(JSON.stringify({ error: { code, message }, ok: false }));
38121
- }
38122
- );
38123
- });
38124
- };
38125
- handle = async (encoded, signal) => {
38126
- const request = decodeRequest(encoded);
38127
- const context = this.#registry.read(request.contextHandle);
38128
- const timeout = AbortSignal.timeout(BOT_RELAY_TIMEOUT_MILLISECONDS);
38129
- const requestSignal = AbortSignal.any([signal, timeout]);
38130
- let response;
38131
- try {
38132
- response = await fetch5(relayEndpoint(this.#relayUrl, context, request.target), {
38133
- body: JSON.stringify({ idempotencyKey: request.idempotencyKey, text: request.text }),
38134
- headers: {
38135
- authorization: `Bearer ${daemonToken(this.#relayUrl)}`,
38136
- "content-type": "application/json",
38137
- "x-mobius-bot-execution-capability": context.command.executionCapabilitySecret
38138
- },
38139
- method: "POST",
38140
- signal: requestSignal
38141
- });
38142
- } catch (cause) {
38143
- signal.throwIfAborted();
38144
- throw new LocalBotAuthorizationError(
38145
- timeout.aborted ? "bot_service_timeout" : "bot_service_unavailable",
38146
- timeout.aborted ? "The Mobius Bot action timed out" : "The Mobius Relay is unavailable",
38147
- { cause }
38148
- );
38149
- }
38150
- return await decodeRelayResponse(response);
38151
- };
38152
- };
38153
-
38154
37367
  // src/native-sessions/service.ts
38155
- import { randomUUID as randomUUID3 } from "node:crypto";
38156
- import { basename as basename5 } from "node:path";
37368
+ import { randomUUID as randomUUID2 } from "node:crypto";
37369
+ import { basename as basename6 } from "node:path";
38157
37370
 
38158
37371
  // src/native-sessions/codex-history.ts
38159
37372
  import { spawn as spawn4 } from "node:child_process";
@@ -38447,7 +37660,7 @@ var NativeSessionService = class {
38447
37660
  if (authorized === null) {
38448
37661
  return null;
38449
37662
  }
38450
- const entryId = randomUUID3();
37663
+ const entryId = randomUUID2();
38451
37664
  if (this.#entries.size >= 5e3) {
38452
37665
  this.#entries.clear();
38453
37666
  }
@@ -38501,7 +37714,7 @@ var NativeSessionService = class {
38501
37714
  "invalid_native_session_response"
38502
37715
  );
38503
37716
  }
38504
- nextCursor = randomUUID3();
37717
+ nextCursor = randomUUID2();
38505
37718
  if (this.#cursors.size >= 500) {
38506
37719
  this.#cursors.clear();
38507
37720
  }
@@ -38662,7 +37875,7 @@ var NativeSessionService = class {
38662
37875
  }
38663
37876
  resolvedPaths.add(path2);
38664
37877
  additionalDirectories.push(path2);
38665
- additionalEntries.push({ directoryId: directoryId2, name: basename5(path2) });
37878
+ additionalEntries.push({ directoryId: directoryId2, name: basename6(path2) });
38666
37879
  }
38667
37880
  const listing = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
38668
37881
  const opened = await this.#sessions.forkSessionAtTurn(
@@ -38820,12 +38033,12 @@ var NativeSessionService = class {
38820
38033
 
38821
38034
  // src/prompt-artifact-resolver.ts
38822
38035
  import { createHash as createHash3 } from "node:crypto";
38823
- import { fetch as fetch6 } from "undici";
38036
+ import { fetch as fetch5 } from "undici";
38824
38037
  var ARTIFACT_SCHEME = "mobius-artifact:";
38825
38038
  var ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS = 2e4;
38826
38039
  var MAX_AGENT_IMAGE_BASE64_LENGTH = 4e6;
38827
38040
  var MAX_AGENT_RESOURCE_BYTE_LENGTH = 1e6;
38828
- var IDENTIFIER_PATTERN8 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
38041
+ var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
38829
38042
  var PromptArtifactError = class extends Error {
38830
38043
  code;
38831
38044
  constructor(code, message, options = {}) {
@@ -38868,7 +38081,7 @@ function parseReference(resource) {
38868
38081
  const encodedByteLength2 = url2.searchParams.get("byteLength") ?? "";
38869
38082
  const sha256 = url2.searchParams.get("sha256") ?? "";
38870
38083
  const byteLength = Number(encodedByteLength2);
38871
- if (url2.protocol !== ARTIFACT_SCHEME || url2.hash.length > 0 || resource.type !== "link" || resource.text.length > 0 || !IDENTIFIER_PATTERN8.test(artifactId) || keys.length !== 2 || keys[0] !== "byteLength" || keys[1] !== "sha256" || !/^[1-9][0-9]*$/.test(encodedByteLength2) || !Number.isSafeInteger(byteLength) || !/^[a-f0-9]{64}$/.test(sha256)) {
38084
+ if (url2.protocol !== ARTIFACT_SCHEME || url2.hash.length > 0 || resource.type !== "link" || resource.text.length > 0 || !IDENTIFIER_PATTERN6.test(artifactId) || keys.length !== 2 || keys[0] !== "byteLength" || keys[1] !== "sha256" || !/^[1-9][0-9]*$/.test(encodedByteLength2) || !Number.isSafeInteger(byteLength) || !/^[a-f0-9]{64}$/.test(sha256)) {
38872
38085
  throw new PromptArtifactError("artifact_reference_invalid", "The prompt artifact reference is invalid");
38873
38086
  }
38874
38087
  return new PromptArtifactReference(artifactId, byteLength, sha256, resource);
@@ -38934,7 +38147,7 @@ async function download(config2, command, reference, signal) {
38934
38147
  const requestSignal = AbortSignal.any([signal, timeoutSignal]);
38935
38148
  let response;
38936
38149
  try {
38937
- response = await fetch6(downloadUrl(config2, command, reference), {
38150
+ response = await fetch5(downloadUrl(config2, command, reference), {
38938
38151
  dispatcher: environmentProxyDispatcher,
38939
38152
  headers: {
38940
38153
  accept: reference.resource.mimeType,
@@ -39267,7 +38480,7 @@ var RelayConnectionDiagnostics = class {
39267
38480
  };
39268
38481
 
39269
38482
  // src/relay-connection/liveness.ts
39270
- import { randomUUID as randomUUID4 } from "node:crypto";
38483
+ import { randomUUID as randomUUID3 } from "node:crypto";
39271
38484
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
39272
38485
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
39273
38486
  var RelayLivenessState = class {
@@ -39356,7 +38569,7 @@ var RelayConnectionLiveness = class {
39356
38569
  }
39357
38570
  throw new Error("Heartbeat was scheduled in an invalid state");
39358
38571
  }
39359
- const heartbeatId = randomUUID4();
38572
+ const heartbeatId = randomUUID3();
39360
38573
  this.#state = new AwaitingHeartbeatAckState(
39361
38574
  heartbeatId,
39362
38575
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -39372,7 +38585,7 @@ var RelayConnectionLiveness = class {
39372
38585
 
39373
38586
  // src/relay-connection/session-event-outbox.ts
39374
38587
  import { mkdirSync as mkdirSync3 } from "node:fs";
39375
- import { dirname as dirname7 } from "node:path";
38588
+ import { dirname as dirname6 } from "node:path";
39376
38589
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
39377
38590
  var DEFAULT_OUTBOX_LIMITS = {
39378
38591
  criticalEventBytes: 136 * 1024 * 1024,
@@ -39438,7 +38651,7 @@ var SessionEventOutbox = class {
39438
38651
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
39439
38652
  validateLimits(limits);
39440
38653
  this.#limits = limits;
39441
- mkdirSync3(dirname7(path2), { recursive: true });
38654
+ mkdirSync3(dirname6(path2), { recursive: true });
39442
38655
  this.#database = new DatabaseSync3(path2);
39443
38656
  this.#database.exec(`
39444
38657
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -39971,12 +39184,6 @@ var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
39971
39184
  var AGENT_ACTIVITY_COALESCING_MILLISECONDS = 100;
39972
39185
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
39973
39186
  var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
39974
- function botIpcSocketPath() {
39975
- if (process.platform === "win32") {
39976
- return `\\\\.\\pipe\\mobius-bot-${randomUUID5()}`;
39977
- }
39978
- return join17("/tmp", `mobius-bot-${randomUUID5()}.sock`);
39979
- }
39980
39187
  var DaemonAcpObserver = class {
39981
39188
  #config;
39982
39189
  #record;
@@ -40194,7 +39401,7 @@ async function reconcileActiveTurn(config2, turn, signal) {
40194
39401
  const requestSignal = AbortSignal.any([signal, timeoutSignal]);
40195
39402
  let response;
40196
39403
  try {
40197
- response = await fetch7(activeTurnReconciliationEndpoint(config2, turn), {
39404
+ response = await fetch6(activeTurnReconciliationEndpoint(config2, turn), {
40198
39405
  body: JSON.stringify({ outcome: { kind: "running" } }),
40199
39406
  dispatcher: environmentProxyDispatcher,
40200
39407
  headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
@@ -40506,13 +39713,13 @@ function reportFailure(publisher, command, code, message, attemptId) {
40506
39713
  );
40507
39714
  }
40508
39715
  function operationErrorCode(error62) {
40509
- if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof LocalBotAuthorizationError || error62 instanceof PromptArtifactError) {
39716
+ if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
40510
39717
  return error62.code;
40511
39718
  }
40512
39719
  return "session_operation_failed";
40513
39720
  }
40514
39721
  function operationErrorMessage(error62) {
40515
- if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof LocalBotAuthorizationError || error62 instanceof PromptArtifactError) {
39722
+ if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
40516
39723
  return error62.message;
40517
39724
  }
40518
39725
  return "The local agent operation could not be completed";
@@ -40547,7 +39754,7 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
40547
39754
  additionalDirectories.push(directory);
40548
39755
  additionalDirectoryEntries.push({
40549
39756
  directoryId: additionalDirectoryId,
40550
- name: basename6(directory)
39757
+ name: basename7(directory)
40551
39758
  });
40552
39759
  }
40553
39760
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
@@ -40777,11 +39984,13 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
40777
39984
  } else {
40778
39985
  await applyCompleteSessionConfiguration(
40779
39986
  sessions,
39987
+ audit,
40780
39988
  prepared.configOptions,
40781
39989
  command.sessionConfigurations,
40782
39990
  agent,
40783
39991
  resolved.cwd,
40784
39992
  resolved.additionalDirectories,
39993
+ command.commandId,
40785
39994
  command.sessionId,
40786
39995
  signal
40787
39996
  );
@@ -40890,11 +40099,11 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
40890
40099
  function invalidSessionConfiguration(message) {
40891
40100
  return new AcpExecutionError(message, {}, "invalid_session_configuration");
40892
40101
  }
40893
- function validateSessionConfigurationSelection(option2, selection) {
40894
- if (option2.type !== selection.valueType) {
40102
+ function validateSessionConfigurationSelection(option, selection) {
40103
+ if (option.type !== selection.valueType) {
40895
40104
  throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
40896
40105
  }
40897
- if (option2.type === "boolean") {
40106
+ if (option.type === "boolean") {
40898
40107
  if (selection.value.length > 0) {
40899
40108
  throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
40900
40109
  }
@@ -40903,7 +40112,7 @@ function validateSessionConfigurationSelection(option2, selection) {
40903
40112
  if (selection.booleanValue) {
40904
40113
  throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
40905
40114
  }
40906
- if (!option2.values.some((value) => value.value === selection.value)) {
40115
+ if (!option.values.some((value) => value.value === selection.value)) {
40907
40116
  throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an unavailable value`);
40908
40117
  }
40909
40118
  }
@@ -40915,29 +40124,49 @@ function assertSessionConfigurationSchema(options, selections) {
40915
40124
  if (selectionsById.size !== selections.length) {
40916
40125
  throw invalidSessionConfiguration("The Turn configuration contains duplicate Agent settings");
40917
40126
  }
40918
- for (const option2 of options) {
40919
- const selection = selectionsById.get(option2.id);
40920
- if (selection === void 0 || selection.valueType !== option2.type || option2.type === "boolean" && selection.value.length > 0 || option2.type === "select" && selection.booleanValue) {
40921
- throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option2.id}`);
40127
+ for (const option of options) {
40128
+ const selection = selectionsById.get(option.id);
40129
+ if (selection === void 0 || selection.valueType !== option.type || option.type === "boolean" && selection.value.length > 0 || option.type === "select" && selection.booleanValue) {
40130
+ throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
40922
40131
  }
40923
40132
  }
40924
40133
  }
40925
- function sessionConfigurationMatches(option2, selection) {
40926
- validateSessionConfigurationSelection(option2, selection);
40927
- return option2.type === "boolean" ? option2.booleanValue === selection.booleanValue : option2.currentValue === selection.value;
40134
+ function assertSessionConfigurationCoverage(options, selections) {
40135
+ const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
40136
+ if (selectionsById.size !== selections.length) {
40137
+ throw invalidSessionConfiguration("The Turn configuration contains duplicate Agent settings");
40138
+ }
40139
+ for (const option of options) {
40140
+ if (!selectionsById.has(option.id)) {
40141
+ throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
40142
+ }
40143
+ }
40144
+ }
40145
+ function sessionConfigurationSelectionIsAvailable(option, selection) {
40146
+ if (option.type !== selection.valueType) {
40147
+ return false;
40148
+ }
40149
+ if (option.type === "boolean") {
40150
+ return selection.value.length === 0;
40151
+ }
40152
+ return !selection.booleanValue && option.values.some((value) => value.value === selection.value);
40153
+ }
40154
+ function sessionConfigurationMatches(option, selection) {
40155
+ validateSessionConfigurationSelection(option, selection);
40156
+ return option.type === "boolean" ? option.booleanValue === selection.booleanValue : option.currentValue === selection.value;
40928
40157
  }
40929
40158
  function sessionConfigurationPriority(selection, options) {
40930
40159
  if (selection.configId === "permission_mode") {
40931
40160
  return 0;
40932
40161
  }
40933
- const option2 = options.find((candidate) => candidate.id === selection.configId);
40934
- if (selection.configId === "model" || option2?.category === "model") {
40162
+ const option = options.find((candidate) => candidate.id === selection.configId);
40163
+ if (selection.configId === "model" || option?.category === "model") {
40935
40164
  return 1;
40936
40165
  }
40937
- if (selection.configId === "reasoning_effort" || option2?.category === "thought_level") {
40166
+ if (selection.configId === "reasoning_effort" || option?.category === "thought_level") {
40938
40167
  return 2;
40939
40168
  }
40940
- if (option2?.category === "model_config") {
40169
+ if (option?.category === "model_config") {
40941
40170
  return 3;
40942
40171
  }
40943
40172
  return 4;
@@ -40945,19 +40174,100 @@ function sessionConfigurationPriority(selection, options) {
40945
40174
  function assertCompleteSessionConfiguration(options, selections) {
40946
40175
  assertSessionConfigurationSchema(options, selections);
40947
40176
  const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
40948
- for (const option2 of options) {
40949
- const selection = selectionsById.get(option2.id);
40950
- if (selection === void 0 || !sessionConfigurationMatches(option2, selection)) {
40951
- throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option2.id}`);
40177
+ for (const option of options) {
40178
+ const selection = selectionsById.get(option.id);
40179
+ if (selection === void 0 || !sessionConfigurationMatches(option, selection)) {
40180
+ throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
40952
40181
  }
40953
40182
  }
40954
40183
  }
40955
- async function applySessionConfigurationSelection(sessions, options, selection, agent, cwd, additionalDirectories, sessionId, signal) {
40956
- const option2 = options.find((candidate) => candidate.id === selection.configId);
40957
- if (option2 === void 0) {
40184
+ function assertAppliedSessionConfiguration(options, selections) {
40185
+ const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
40186
+ for (const option of options) {
40187
+ const selection = selectionsById.get(option.id);
40188
+ if (option.id === AGENT_PERMISSION_MODE_CONFIG_ID) {
40189
+ if (selection === void 0 || !sessionConfigurationMatches(option, selection)) {
40190
+ throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
40191
+ }
40192
+ continue;
40193
+ }
40194
+ if (selection === void 0 || !sessionConfigurationSelectionIsAvailable(option, selection)) {
40195
+ continue;
40196
+ }
40197
+ if (!sessionConfigurationMatches(option, selection)) {
40198
+ throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
40199
+ }
40200
+ }
40201
+ }
40202
+ function unavailableSessionConfigurationCategory(selection) {
40203
+ if (selection.configId === "model") {
40204
+ return "model";
40205
+ }
40206
+ if (selection.configId === "reasoning_effort") {
40207
+ return "thought_level";
40208
+ }
40209
+ return "unknown";
40210
+ }
40211
+ async function applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
40212
+ const option = options.find((candidate) => candidate.id === selection.configId);
40213
+ if (option === void 0) {
40214
+ if (selection.configId !== AGENT_PERMISSION_MODE_CONFIG_ID) {
40215
+ warnIgnoredSetting(
40216
+ audit,
40217
+ "session_configuration_setting_ignored",
40218
+ commandId,
40219
+ sessionId,
40220
+ agent.id,
40221
+ selection,
40222
+ unavailableSessionConfigurationCategory(selection),
40223
+ "setting_unavailable"
40224
+ );
40225
+ return options;
40226
+ }
40958
40227
  throw invalidSessionConfiguration(`The Agent setting ${selection.configId} is unavailable`);
40959
40228
  }
40960
- if (sessionConfigurationMatches(option2, selection)) {
40229
+ if (selection.configId !== AGENT_PERMISSION_MODE_CONFIG_ID) {
40230
+ if (option.type !== selection.valueType) {
40231
+ warnIgnoredSetting(
40232
+ audit,
40233
+ "session_configuration_setting_ignored",
40234
+ commandId,
40235
+ sessionId,
40236
+ agent.id,
40237
+ selection,
40238
+ option.category,
40239
+ "setting_schema_mismatch"
40240
+ );
40241
+ return options;
40242
+ }
40243
+ if (option.type === "boolean" && selection.value.length > 0 || option.type === "select" && selection.booleanValue) {
40244
+ warnIgnoredSetting(
40245
+ audit,
40246
+ "session_configuration_setting_ignored",
40247
+ commandId,
40248
+ sessionId,
40249
+ agent.id,
40250
+ selection,
40251
+ option.category,
40252
+ "selection_schema_mismatch"
40253
+ );
40254
+ return options;
40255
+ }
40256
+ if (option.type === "select" && !option.values.some((value) => value.value === selection.value)) {
40257
+ warnIgnoredSetting(
40258
+ audit,
40259
+ "session_configuration_setting_ignored",
40260
+ commandId,
40261
+ sessionId,
40262
+ agent.id,
40263
+ selection,
40264
+ option.category,
40265
+ "value_unavailable"
40266
+ );
40267
+ return options;
40268
+ }
40269
+ }
40270
+ if (sessionConfigurationMatches(option, selection)) {
40961
40271
  return options;
40962
40272
  }
40963
40273
  return await sessions.configureSession({
@@ -40966,15 +40276,15 @@ async function applySessionConfigurationSelection(sessions, options, selection,
40966
40276
  booleanValue: selection.booleanValue,
40967
40277
  configId: selection.configId,
40968
40278
  cwd,
40969
- requestId: `cfg_${randomUUID5()}`,
40279
+ requestId: `cfg_${randomUUID4()}`,
40970
40280
  sessionId,
40971
40281
  signal,
40972
40282
  value: selection.value,
40973
40283
  valueType: selection.valueType
40974
40284
  });
40975
40285
  }
40976
- async function applyCompleteSessionConfiguration(sessions, initialOptions, selections, agent, cwd, additionalDirectories, sessionId, signal) {
40977
- assertSessionConfigurationSchema(initialOptions, selections);
40286
+ async function applyCompleteSessionConfiguration(sessions, audit, initialOptions, selections, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
40287
+ assertSessionConfigurationCoverage(initialOptions, selections);
40978
40288
  let options = initialOptions;
40979
40289
  const orderedSelections = selections.toSorted((left, right) => {
40980
40290
  const priority = sessionConfigurationPriority(left, initialOptions) - sessionConfigurationPriority(right, initialOptions);
@@ -40983,50 +40293,20 @@ async function applyCompleteSessionConfiguration(sessions, initialOptions, selec
40983
40293
  for (const selection of orderedSelections) {
40984
40294
  options = await applySessionConfigurationSelection(
40985
40295
  sessions,
40296
+ audit,
40986
40297
  options,
40987
40298
  selection,
40988
40299
  agent,
40989
40300
  cwd,
40990
40301
  additionalDirectories,
40302
+ commandId,
40991
40303
  sessionId,
40992
40304
  signal
40993
40305
  );
40994
40306
  }
40995
- assertCompleteSessionConfiguration(options, selections);
40996
- }
40997
- function botExecutionAgent(agent, contextHandle, socketPath) {
40998
- return new LocalAgentDefinition(
40999
- agent.id,
41000
- agent.label,
41001
- agent.command,
41002
- agent.arguments,
41003
- {
41004
- ...agent.environment,
41005
- MOBIUS_BOT_CONTEXT: contextHandle,
41006
- MOBIUS_BOT_SOCKET: socketPath,
41007
- MOBIUS_RELAY_TOKEN: "",
41008
- MOBIUS_RELAY_URL: ""
41009
- },
41010
- agent.adapterVersion,
41011
- agent.agentVersion,
41012
- agent.adapterIdentity,
41013
- agent.agentIdentity,
41014
- agent.promptTimeoutMilliseconds,
41015
- agent.capabilities,
41016
- agent.permissionProfile
41017
- );
41018
- }
41019
- function assertPreparedPermission(configOptions, permissionMode) {
41020
- const permission = configOptions.find((option2) => option2.id === "permission_mode");
41021
- if (permission === void 0 || permission.type !== "select" || permissionMode !== AGENT_DEFAULT_EXECUTION_SETTING && permission.currentValue !== permissionMode) {
41022
- throw new AcpExecutionError(
41023
- "The required Agent permission mode is unavailable",
41024
- {},
41025
- "invalid_session_configuration"
41026
- );
41027
- }
40307
+ assertAppliedSessionConfiguration(options, selections);
41028
40308
  }
41029
- function warnIgnoredExecutionSetting(audit, commandId, sessionId, agentId, selection, category, reason) {
40309
+ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
41030
40310
  const details = {
41031
40311
  agentId,
41032
40312
  category,
@@ -41034,264 +40314,10 @@ function warnIgnoredExecutionSetting(audit, commandId, sessionId, agentId, selec
41034
40314
  reason,
41035
40315
  requestedValue: selection.value
41036
40316
  };
41037
- const event = "bot_execution_setting_ignored";
41038
40317
  audit.record({ commandId, details, event, sessionId });
41039
40318
  process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}
41040
40319
  `);
41041
40320
  }
41042
- async function applySupportedExecutionSelection(sessions, audit, configOptions, selection, category, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
41043
- if (selection.value === AGENT_DEFAULT_EXECUTION_SETTING) {
41044
- return configOptions;
41045
- }
41046
- const option2 = configOptions.find((candidate) => candidate.id === selection.configId);
41047
- if (option2 === void 0) {
41048
- warnIgnoredExecutionSetting(audit, commandId, sessionId, agent.id, selection, category, "setting_unavailable");
41049
- return configOptions;
41050
- }
41051
- if (option2.type !== "select" || option2.category !== category) {
41052
- warnIgnoredExecutionSetting(
41053
- audit,
41054
- commandId,
41055
- sessionId,
41056
- agent.id,
41057
- selection,
41058
- category,
41059
- "setting_schema_mismatch"
41060
- );
41061
- return configOptions;
41062
- }
41063
- if (selection.valueType !== "select" || selection.booleanValue) {
41064
- warnIgnoredExecutionSetting(
41065
- audit,
41066
- commandId,
41067
- sessionId,
41068
- agent.id,
41069
- selection,
41070
- category,
41071
- "selection_schema_mismatch"
41072
- );
41073
- return configOptions;
41074
- }
41075
- if (!option2.values.some((value) => value.value === selection.value)) {
41076
- warnIgnoredExecutionSetting(audit, commandId, sessionId, agent.id, selection, category, "value_unavailable");
41077
- return configOptions;
41078
- }
41079
- if (option2.currentValue === selection.value) {
41080
- return configOptions;
41081
- }
41082
- return await sessions.configureSession({
41083
- additionalDirectories,
41084
- agent,
41085
- booleanValue: false,
41086
- configId: selection.configId,
41087
- cwd,
41088
- requestId: `cfg_${randomUUID5()}`,
41089
- sessionId,
41090
- signal,
41091
- value: selection.value,
41092
- valueType: "select"
41093
- });
41094
- }
41095
- async function executeBotPrompt(outbox, publisher, command, config2, directories, audit, sessions, authorizer, contexts, applicator, ipc, attemptId, activateAttempt, timer, signal) {
41096
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity) => {
41097
- publisher.recordAttempt(command.sessionId, encodeDaemonActivity(command, activity), attemptId);
41098
- });
41099
- try {
41100
- const deadline = Date.parse(command.executionDeadlineAt);
41101
- const remaining = deadline - Date.now();
41102
- if (!Number.isSafeInteger(deadline) || remaining <= 0) {
41103
- throw new LocalBotAuthorizationError("turn_expired", "The Bot execution deadline has expired");
41104
- }
41105
- const execution = await authorizer.authorize(command, config2.catalog, directories, config2.bindingId, signal);
41106
- const resolved = await resolveSessionDirectories(
41107
- directories,
41108
- config2.bindingId,
41109
- command.directoryId,
41110
- command.additionalDirectoryIds,
41111
- signal
41112
- );
41113
- const attachments = await resolvePromptArtifacts(config2, command, signal);
41114
- const applied = await applicator.apply(command, execution, attachments.resources, signal);
41115
- const deadlineSignal = AbortSignal.timeout(remaining);
41116
- const executionSignal = AbortSignal.any([signal, deadlineSignal]);
41117
- const startExecution = () => {
41118
- audit.record({
41119
- commandId: command.commandId,
41120
- details: {
41121
- behaviorRevisionId: command.behaviorRevisionId,
41122
- bindingId: command.bindingId,
41123
- botId: command.botId,
41124
- executionId: command.executionId
41125
- },
41126
- event: "bot_session_authorized",
41127
- sessionId: command.sessionId
41128
- });
41129
- outbox.transitionExecution(command.commandId, "running");
41130
- publisher.recordAttempt(
41131
- command.sessionId,
41132
- encodeSessionStartedEvent({
41133
- attemptId,
41134
- commandId: command.commandId,
41135
- kind: SESSION_STARTED_KIND,
41136
- sessionId: command.sessionId
41137
- }),
41138
- attemptId
41139
- );
41140
- activateAttempt();
41141
- };
41142
- let stopReason = "steered";
41143
- if (command.disposition === SessionPromptDisposition.Steer) {
41144
- startExecution();
41145
- await sessions.steerPrompt({
41146
- additionalDirectories: resolved.additionalDirectories,
41147
- agent: execution.agent,
41148
- commandId: command.commandId,
41149
- cwd: resolved.cwd,
41150
- images: attachments.images,
41151
- prompt: command.prompt,
41152
- resources: applied.resources,
41153
- sessionId: command.sessionId,
41154
- signal: executionSignal,
41155
- targetCommandId: command.targetCommandId
41156
- });
41157
- } else {
41158
- if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
41159
- throw new AcpExecutionError(
41160
- "The queued Bot prompt target is unavailable",
41161
- {},
41162
- "prompt_queue_target_unavailable"
41163
- );
41164
- }
41165
- const lease = contexts.activate(command);
41166
- try {
41167
- const agent = botExecutionAgent(execution.agent, lease.context.contextHandle, ipc.socketPath);
41168
- const prepared = await sessions.prepareExecutionSession({
41169
- additionalDirectories: resolved.additionalDirectories,
41170
- agent,
41171
- cwd: resolved.cwd,
41172
- sessionId: command.sessionId,
41173
- signal: executionSignal
41174
- });
41175
- assertPreparedPermission(prepared.configOptions, execution.executionConfiguration.permissionMode);
41176
- let configOptions = await applySupportedExecutionSelection(
41177
- sessions,
41178
- audit,
41179
- prepared.configOptions,
41180
- execution.executionConfiguration.model,
41181
- "model",
41182
- agent,
41183
- resolved.cwd,
41184
- resolved.additionalDirectories,
41185
- command.commandId,
41186
- command.sessionId,
41187
- executionSignal
41188
- );
41189
- configOptions = await applySupportedExecutionSelection(
41190
- sessions,
41191
- audit,
41192
- configOptions,
41193
- execution.executionConfiguration.reasoningEffort,
41194
- "thought_level",
41195
- agent,
41196
- resolved.cwd,
41197
- resolved.additionalDirectories,
41198
- command.commandId,
41199
- command.sessionId,
41200
- executionSignal
41201
- );
41202
- for (const selection of command.sessionConfigurations) {
41203
- await sessions.configureSession({
41204
- additionalDirectories: resolved.additionalDirectories,
41205
- agent,
41206
- booleanValue: selection.booleanValue,
41207
- configId: selection.configId,
41208
- cwd: resolved.cwd,
41209
- requestId: `cfg_${randomUUID5()}`,
41210
- sessionId: command.sessionId,
41211
- signal: executionSignal,
41212
- value: selection.value,
41213
- valueType: selection.valueType
41214
- });
41215
- }
41216
- startExecution();
41217
- const result = await sessions.runPrompt({
41218
- additionalDirectories: resolved.additionalDirectories,
41219
- agent,
41220
- commandId: command.commandId,
41221
- cwd: resolved.cwd,
41222
- disposition: command.disposition,
41223
- images: attachments.images,
41224
- onActivity: activities.record,
41225
- onText: (text3, messageId) => {
41226
- publisher.recordAttempt(
41227
- command.sessionId,
41228
- encodeAgentMessageDeltaEvent({
41229
- commandId: command.commandId,
41230
- kind: AGENT_MESSAGE_DELTA_KIND,
41231
- messageId,
41232
- sessionId: command.sessionId,
41233
- text: text3
41234
- }),
41235
- attemptId
41236
- );
41237
- return Promise.resolve();
41238
- },
41239
- prompt: command.prompt,
41240
- resources: applied.resources,
41241
- sessionId: command.sessionId,
41242
- signal: executionSignal,
41243
- targetCommandId: command.targetCommandId
41244
- });
41245
- stopReason = result.stopReason;
41246
- } finally {
41247
- lease.release();
41248
- }
41249
- }
41250
- activities.flush();
41251
- publisher.recordAttempt(
41252
- command.sessionId,
41253
- encodeSessionCompletedEvent({
41254
- commandId: command.commandId,
41255
- kind: SESSION_COMPLETED_KIND,
41256
- sessionId: command.sessionId,
41257
- stopReason
41258
- }),
41259
- attemptId
41260
- );
41261
- outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
41262
- audit.record({
41263
- commandId: command.commandId,
41264
- details: { botId: command.botId, executionId: command.executionId },
41265
- event: stopReason === "cancelled" ? "bot_session_cancelled" : "bot_session_completed",
41266
- sessionId: command.sessionId
41267
- });
41268
- } catch (error62) {
41269
- activities.flush();
41270
- const failure2 = Date.parse(command.executionDeadlineAt) <= Date.now() ? new LocalBotAuthorizationError("turn_expired", "The Bot execution deadline has expired", {
41271
- cause: error62
41272
- }) : error62;
41273
- audit.record({
41274
- commandId: command.commandId,
41275
- details: {
41276
- botId: command.botId,
41277
- code: operationErrorCode(failure2),
41278
- executionId: command.executionId
41279
- },
41280
- event: "bot_session_failed",
41281
- sessionId: command.sessionId
41282
- });
41283
- const code = operationErrorCode(failure2);
41284
- reportFailure(
41285
- publisher,
41286
- command,
41287
- code === "session_operation_failed" ? "agent_execution_failed" : code,
41288
- code === "session_operation_failed" ? "The local agent could not complete the Bot request" : operationErrorMessage(failure2),
41289
- attemptId
41290
- );
41291
- outbox.transitionExecution(command.commandId, "failed");
41292
- console.error("Mobius daemon Bot command failed", failure2);
41293
- }
41294
- }
41295
40321
  function waitForRelayRetry(signal, timer) {
41296
40322
  if (signal.aborted) {
41297
40323
  return Promise.resolve();
@@ -41338,13 +40364,13 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
41338
40364
  {
41339
40365
  agentId: agent.id,
41340
40366
  kind: AGENT_INSTALL_REQUEST_KIND,
41341
- requestId: `automatic-integration-${randomUUID5()}`
40367
+ requestId: `automatic-integration-${randomUUID4()}`
41342
40368
  },
41343
40369
  signal
41344
40370
  );
41345
40371
  }
41346
40372
  }
41347
- async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, authorizer, contexts, applicator, ipc, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer) {
40373
+ async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer) {
41348
40374
  const relayUrl = new URL(config2.relayUrl);
41349
40375
  relayUrl.searchParams.set("deliveryReceipts", "1");
41350
40376
  relayUrl.searchParams.set("liveness", "1");
@@ -41510,32 +40536,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41510
40536
  }
41511
40537
  return;
41512
40538
  }
41513
- if (kind === BOT_SESSION_PROMPT_KIND) {
41514
- const command = decodeBotSessionPromptCommand(delivery.payload);
41515
- await processDeliveredPrompt(
41516
- delivery,
41517
- command,
41518
- command.disposition !== SessionPromptDisposition.Steer,
41519
- (attemptId, activateAttempt, executionSignal) => executeBotPrompt(
41520
- outbox,
41521
- publisher,
41522
- command,
41523
- config2,
41524
- directories,
41525
- audit,
41526
- sessions,
41527
- authorizer,
41528
- contexts,
41529
- applicator,
41530
- ipc,
41531
- attemptId,
41532
- activateAttempt,
41533
- timer,
41534
- executionSignal
41535
- )
41536
- );
41537
- return;
41538
- }
41539
40539
  if (kind === SESSION_PROMPT_KIND) {
41540
40540
  const command = decodeSessionPromptCommand(delivery.payload);
41541
40541
  await processDeliveredPrompt(
@@ -41593,8 +40593,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41593
40593
  payloadSessionId = decodeSessionElicitationRespondCommand(delivery.payload).sessionId;
41594
40594
  } else if (payloadKind === SESSION_PROMPT_KIND) {
41595
40595
  payloadSessionId = decodeSessionPromptCommand(delivery.payload).sessionId;
41596
- } else if (payloadKind === BOT_SESSION_PROMPT_KIND) {
41597
- payloadSessionId = decodeBotSessionPromptCommand(delivery.payload).sessionId;
41598
40596
  } else {
41599
40597
  throw new Error("Runtime delivery contains an unsupported protocol message");
41600
40598
  }
@@ -41987,6 +40985,29 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41987
40985
  connectionLiveness.acknowledge(decodeRuntimeHeartbeatAckEvent(encoded));
41988
40986
  return;
41989
40987
  }
40988
+ if (kind === FILE_READ_KIND) {
40989
+ const command2 = decodeFileReadCommand(encoded);
40990
+ void streamLocalFile(
40991
+ command2,
40992
+ (message) => send(socket, message),
40993
+ connectionController.signal
40994
+ ).catch((error62) => {
40995
+ if (socket.readyState !== WebSocket2.OPEN || connectionController.signal.aborted) {
40996
+ return;
40997
+ }
40998
+ send(
40999
+ socket,
41000
+ encodeFileFailedEvent({
41001
+ code: "file_unavailable",
41002
+ kind: FILE_FAILED_KIND,
41003
+ message: error62 instanceof Error ? error62.message : "The local file is unavailable",
41004
+ requestId: command2.requestId,
41005
+ sessionId: command2.sessionId
41006
+ })
41007
+ );
41008
+ });
41009
+ return;
41010
+ }
41990
41011
  if (kind === SESSION_CANCEL_KIND) {
41991
41012
  const cancellation = decodeSessionCancelCommand(encoded);
41992
41013
  const turn2 = activeTurns.get(cancellation.commandId);
@@ -42080,48 +41101,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42080
41101
  });
42081
41102
  return;
42082
41103
  }
42083
- if (kind === BOT_SESSION_PROMPT_KIND) {
42084
- const command2 = decodeBotSessionPromptCommand(encoded);
42085
- if (activeTurns.has(command2.commandId)) {
42086
- return;
42087
- }
42088
- const receipt2 = outbox.claimExecution(command2.commandId, command2.sessionId, encoded);
42089
- if (receipt2.kind === "duplicate") {
42090
- return;
42091
- }
42092
- const turn2 = new ActiveDaemonTurn(command2, receipt2.attemptId);
42093
- activeTurns.set(command2.commandId, turn2);
42094
- void executeBotPrompt(
42095
- outbox,
42096
- publisher,
42097
- command2,
42098
- config2,
42099
- directories,
42100
- audit,
42101
- sessions,
42102
- authorizer,
42103
- contexts,
42104
- applicator,
42105
- ipc,
42106
- receipt2.attemptId,
42107
- () => {
42108
- if (command2.disposition !== SessionPromptDisposition.Steer) {
42109
- activeAttemptIds.set(command2.sessionId, receipt2.attemptId);
42110
- }
42111
- },
42112
- timer,
42113
- turn2.signal
42114
- ).catch((error62) => {
42115
- console.error("Mobius daemon Bot turn failed", error62);
42116
- }).finally(() => {
42117
- activeTurns.delete(command2.commandId);
42118
- if (activeAttemptIds.get(command2.sessionId) === receipt2.attemptId) {
42119
- activeAttemptIds.delete(command2.sessionId);
42120
- }
42121
- turn2.finish();
42122
- });
42123
- return;
42124
- }
42125
41104
  if (kind !== SESSION_PROMPT_KIND) {
42126
41105
  throw new Error("Unsupported protocol message");
42127
41106
  }
@@ -42225,10 +41204,6 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
42225
41204
  const sessionStore = new SqliteAcpSessionStore(config2.auditDatabasePath);
42226
41205
  const outbox = new SessionEventOutbox(config2.auditDatabasePath);
42227
41206
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
42228
- const authorizer = new LocalBotExecutionAuthorizer();
42229
- const contexts = new BotExecutionContextRegistry();
42230
- const applicator = new EmbeddedBotContextApplicator();
42231
- const ipc = new BotOutboundIpcServer(botIpcSocketPath(), config2.relayUrl, contexts);
42232
41207
  const activeTurns = /* @__PURE__ */ new Map();
42233
41208
  const activeAttemptIds = /* @__PURE__ */ new Map();
42234
41209
  const recordSessionEvent = (sessionId, payload) => {
@@ -42302,7 +41277,6 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
42302
41277
  startAutomaticIntegrationProvisioning();
42303
41278
  });
42304
41279
  try {
42305
- await ipc.listen(signal);
42306
41280
  while (!signal.aborted) {
42307
41281
  connectionEpoch += 1;
42308
41282
  try {
@@ -42316,10 +41290,6 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
42316
41290
  nativeSessions,
42317
41291
  outbox,
42318
41292
  publisher,
42319
- authorizer,
42320
- contexts,
42321
- applicator,
42322
- ipc,
42323
41293
  activeTurns,
42324
41294
  activeAttemptIds,
42325
41295
  connectionEpoch,
@@ -42352,19 +41322,15 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
42352
41322
  await installations.close();
42353
41323
  } finally {
42354
41324
  try {
42355
- await ipc.close();
41325
+ await sessions.close();
42356
41326
  } finally {
42357
41327
  try {
42358
- await sessions.close();
41328
+ sessionStore.close();
42359
41329
  } finally {
42360
41330
  try {
42361
- sessionStore.close();
41331
+ publisher.close();
42362
41332
  } finally {
42363
- try {
42364
- publisher.close();
42365
- } finally {
42366
- outbox.close();
42367
- }
41333
+ outbox.close();
42368
41334
  }
42369
41335
  }
42370
41336
  }
@@ -42440,14 +41406,12 @@ Usage:
42440
41406
  mobius pair --url <relay-url> --pairing <runtime-pairing-id> --code <pairing-code> [--workspace <directory>]
42441
41407
  mobius start --channel <channel-id>
42442
41408
  mobius agents [--json]
42443
- mobius bot message send --target <current|alias> --text <message>
42444
41409
 
42445
41410
  Commands:
42446
41411
  --version Print the installed Mobius CLI version
42447
41412
  pair Pair this machine and start its local daemon
42448
41413
  start Start the local daemon for a saved channel
42449
41414
  agents Show detected, missing, and integration-ready Agents
42450
- bot Send a message from an active execution
42451
41415
 
42452
41416
  Pairing grants this browser access to the machine with your user account's permissions.
42453
41417
  New conversations default to ~/.mobius/workspace; choose other directories in the browser.
@@ -42468,7 +41432,7 @@ async function main() {
42468
41432
  if (arguments_.length > 1 || arguments_.length === 1 && arguments_[0] !== "--json") {
42469
41433
  throw new Error("Usage: mobius agents [--json]");
42470
41434
  }
42471
- await mkdir5(loadDefaultWorkspace(), { recursive: true, mode: 448 });
41435
+ await mkdir4(loadDefaultWorkspace(), { recursive: true, mode: 448 });
42472
41436
  const inventory = await discoverLocalAgentInventory({
42473
41437
  defaultWorkspace: loadDefaultWorkspace(),
42474
41438
  environment: process.env,
@@ -42477,18 +41441,6 @@ async function main() {
42477
41441
  process.stdout.write(formatAgentDiagnostics(inventory, arguments_[0] === "--json"));
42478
41442
  return;
42479
41443
  }
42480
- if (command === "bot") {
42481
- if (process.argv[3] !== "message" || process.argv[4] !== "send") {
42482
- throw new BotMessageCommandError(
42483
- "invalid_request",
42484
- "Usage: mobius bot message send --target <current|alias> --text <message>"
42485
- );
42486
- }
42487
- const outboundMessageId = await executeBotMessageCommand(process.argv.slice(5), process.env, shutdown.signal);
42488
- process.stdout.write(`${JSON.stringify({ outboundMessageId })}
42489
- `);
42490
- return;
42491
- }
42492
41444
  let config2;
42493
41445
  if (command === "pair") {
42494
41446
  process.stdout.write(`mobius version: ${package_default.version}
@@ -42523,8 +41475,7 @@ try {
42523
41475
  } catch (error62) {
42524
41476
  if (!shutdown.signal.aborted) {
42525
41477
  const message = error62 instanceof Error ? error62.message : "Unknown failure";
42526
- const code = error62 instanceof BotMessageCommandError ? `${error62.code}: ` : "";
42527
- process.stderr.write(`Mobius daemon failed: ${code}${message}
41478
+ process.stderr.write(`Mobius daemon failed: ${message}
42528
41479
  `);
42529
41480
  process.exitCode = 1;
42530
41481
  }