@moxt-ai/mobius 0.0.43 → 0.0.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -20732,9 +20732,6 @@ function encodeSessionFailedEvent(message) {
20732
20732
  }
20733
20733
 
20734
20734
  // ../protocol/src/bot.ts
20735
- var BOT_BINDING_APPROVAL_REQUEST_KIND = "bot.binding.approval.request";
20736
- var BOT_BINDING_APPROVED_KIND = "bot.binding.approved";
20737
- var BOT_BINDING_UNAVAILABLE_KIND = "bot.binding.unavailable";
20738
20735
  var BOT_SESSION_PROMPT_KIND = "bot.session.prompt";
20739
20736
  var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
20740
20737
  var DIRECTORY_IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
@@ -20749,21 +20746,6 @@ var BotDeliveryTargetReference = class {
20749
20746
  this.deliveryTargetId = deliveryTargetId;
20750
20747
  }
20751
20748
  };
20752
- var BotCompletionDeliveryPolicy = class {
20753
- };
20754
- var NoBotCompletionDeliveryPolicy = class extends BotCompletionDeliveryPolicy {
20755
- kind = "none";
20756
- };
20757
- var RequiredBotCompletionDeliveryPolicy = class extends BotCompletionDeliveryPolicy {
20758
- deliveryTargetId;
20759
- kind = "required";
20760
- messageTemplate;
20761
- constructor(deliveryTargetId, messageTemplate) {
20762
- super();
20763
- this.deliveryTargetId = deliveryTargetId;
20764
- this.messageTemplate = messageTemplate;
20765
- }
20766
- };
20767
20749
  var BotReplyRoute = class {
20768
20750
  };
20769
20751
  var OwnerBotReplyRoute = class extends BotReplyRoute {
@@ -20779,94 +20761,6 @@ var BotConnectionReplyRoute = class extends BotReplyRoute {
20779
20761
  this.deliveryTargetId = deliveryTargetId;
20780
20762
  }
20781
20763
  };
20782
- var BotExecutionBindingApprovalRequest = class {
20783
- agentConfigRevision;
20784
- agentRef;
20785
- allowedDeliveryTargets;
20786
- behaviorDigest;
20787
- behaviorInstructions;
20788
- behaviorRevisionId;
20789
- bindingId;
20790
- bindingRevision;
20791
- botId;
20792
- completionPolicy;
20793
- executionConfiguration;
20794
- kind = BOT_BINDING_APPROVAL_REQUEST_KIND;
20795
- requestId;
20796
- requiredCapabilities;
20797
- runtimeId;
20798
- sessionConfigurations;
20799
- workspaceRef;
20800
- constructor(requestId, botId, behaviorRevisionId, bindingId, bindingRevision, runtimeId, agentRef, workspaceRef, agentConfigRevision, behaviorInstructions, behaviorDigest, requiredCapabilities, allowedDeliveryTargets, completionPolicy, executionConfiguration, sessionConfigurations = []) {
20801
- this.requestId = requestId;
20802
- this.botId = botId;
20803
- this.behaviorRevisionId = behaviorRevisionId;
20804
- this.bindingId = bindingId;
20805
- this.bindingRevision = bindingRevision;
20806
- this.runtimeId = runtimeId;
20807
- this.agentRef = agentRef;
20808
- this.workspaceRef = workspaceRef;
20809
- this.agentConfigRevision = agentConfigRevision;
20810
- this.behaviorInstructions = behaviorInstructions;
20811
- this.behaviorDigest = behaviorDigest;
20812
- this.requiredCapabilities = Object.freeze([...requiredCapabilities]);
20813
- this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
20814
- this.allowedDeliveryTargets = Object.freeze(
20815
- allowedDeliveryTargets.map(
20816
- (target) => new BotDeliveryTargetReference(target.alias, target.deliveryTargetId)
20817
- )
20818
- );
20819
- this.completionPolicy = completionPolicy;
20820
- this.executionConfiguration = decodeAgentExecutionConfiguration(executionConfiguration);
20821
- }
20822
- toJSON() {
20823
- const { sessionConfigurations, ...request } = this;
20824
- return {
20825
- ...request,
20826
- ...sessionConfigurations.length === 0 ? {} : { sessionConfigurations }
20827
- };
20828
- }
20829
- };
20830
- var BotExecutionBindingApprovedEvent = class {
20831
- agentIdentityDigest;
20832
- behaviorRevisionId;
20833
- bindingId;
20834
- bindingRevision;
20835
- botId;
20836
- kind = BOT_BINDING_APPROVED_KIND;
20837
- localGrantId;
20838
- requestId;
20839
- workspaceIdentityDigest;
20840
- constructor(requestId, botId, behaviorRevisionId, bindingId, bindingRevision, localGrantId, agentIdentityDigest, workspaceIdentityDigest) {
20841
- this.requestId = requestId;
20842
- this.botId = botId;
20843
- this.behaviorRevisionId = behaviorRevisionId;
20844
- this.bindingId = bindingId;
20845
- this.bindingRevision = bindingRevision;
20846
- this.localGrantId = localGrantId;
20847
- this.agentIdentityDigest = agentIdentityDigest;
20848
- this.workspaceIdentityDigest = workspaceIdentityDigest;
20849
- }
20850
- };
20851
- var BotExecutionBindingUnavailableEvent = class {
20852
- behaviorRevisionId;
20853
- bindingId;
20854
- bindingRevision;
20855
- botId;
20856
- code;
20857
- kind = BOT_BINDING_UNAVAILABLE_KIND;
20858
- message;
20859
- requestId;
20860
- constructor(requestId, botId, behaviorRevisionId, bindingId, bindingRevision, code, message) {
20861
- this.requestId = requestId;
20862
- this.botId = botId;
20863
- this.behaviorRevisionId = behaviorRevisionId;
20864
- this.bindingId = bindingId;
20865
- this.bindingRevision = bindingRevision;
20866
- this.code = code;
20867
- this.message = message;
20868
- }
20869
- };
20870
20764
  var BotSessionPromptCommand = class {
20871
20765
  additionalDirectoryIds;
20872
20766
  agentId;
@@ -20888,7 +20782,6 @@ var BotSessionPromptCommand = class {
20888
20782
  executionConfiguration;
20889
20783
  images;
20890
20784
  kind = BOT_SESSION_PROMPT_KIND;
20891
- localGrantId;
20892
20785
  prompt;
20893
20786
  replyRoute;
20894
20787
  resources;
@@ -20896,7 +20789,7 @@ var BotSessionPromptCommand = class {
20896
20789
  sessionId;
20897
20790
  targetCommandId;
20898
20791
  turnId;
20899
- constructor(sessionId, commandId, agentId, bindingId, directoryId2, additionalDirectoryIds, images, resources, prompt, executionId, executionCapabilityId, executionCapabilitySecret, executionDeadlineAt, botId, conversationId, turnId, behaviorRevisionId, bindingRevision, localGrantId, behaviorInstructions, behaviorDigest, allowedDeliveryTargets, replyRoute, executionConfiguration, sessionConfigurations = [], disposition = SessionPromptDisposition.Reject, targetCommandId = "") {
20792
+ 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 = "") {
20900
20793
  this.sessionId = sessionId;
20901
20794
  this.commandId = commandId;
20902
20795
  this.agentId = agentId;
@@ -20916,7 +20809,6 @@ var BotSessionPromptCommand = class {
20916
20809
  this.turnId = turnId;
20917
20810
  this.behaviorRevisionId = behaviorRevisionId;
20918
20811
  this.bindingRevision = bindingRevision;
20919
- this.localGrantId = localGrantId;
20920
20812
  this.behaviorInstructions = behaviorInstructions;
20921
20813
  this.behaviorDigest = behaviorDigest;
20922
20814
  this.allowedDeliveryTargets = Object.freeze(
@@ -21060,24 +20952,6 @@ function readSessionConfigurations(value) {
21060
20952
  }
21061
20953
  return decodeSessionConfigurationSelections(value["sessionConfigurations"]);
21062
20954
  }
21063
- function readCompletionPolicy(value) {
21064
- if (!isRecord2(value)) {
21065
- throw new ProtocolMessageError("Invalid Bot completion policy");
21066
- }
21067
- const kind = readText2(value, "kind", 32, false);
21068
- if (kind === "none") {
21069
- assertExactKeys2(value, ["kind"]);
21070
- return new NoBotCompletionDeliveryPolicy();
21071
- }
21072
- if (kind === "required") {
21073
- assertExactKeys2(value, ["deliveryTargetId", "kind", "messageTemplate"]);
21074
- return new RequiredBotCompletionDeliveryPolicy(
21075
- readIdentifier2(value, "deliveryTargetId"),
21076
- readText2(value, "messageTemplate", 1e4, false)
21077
- );
21078
- }
21079
- throw new ProtocolMessageError("Invalid Bot completion policy");
21080
- }
21081
20955
  function readReplyRoute(value) {
21082
20956
  if (!isRecord2(value)) {
21083
20957
  throw new ProtocolMessageError("Invalid Bot reply route");
@@ -21096,110 +20970,6 @@ function readReplyRoute(value) {
21096
20970
  }
21097
20971
  throw new ProtocolMessageError("Invalid Bot reply route");
21098
20972
  }
21099
- function decodeBotExecutionBindingApprovalRequest(encoded) {
21100
- const value = parseJson3(encoded);
21101
- assertKeysWithOptional(
21102
- value,
21103
- [
21104
- "agentConfigRevision",
21105
- "agentRef",
21106
- "allowedDeliveryTargets",
21107
- "behaviorDigest",
21108
- "behaviorInstructions",
21109
- "behaviorRevisionId",
21110
- "bindingId",
21111
- "bindingRevision",
21112
- "botId",
21113
- "completionPolicy",
21114
- "executionConfiguration",
21115
- "kind",
21116
- "requestId",
21117
- "requiredCapabilities",
21118
- "runtimeId",
21119
- "workspaceRef"
21120
- ],
21121
- ["sessionConfigurations"]
21122
- );
21123
- if (value["kind"] !== BOT_BINDING_APPROVAL_REQUEST_KIND) {
21124
- throw new ProtocolMessageError("Invalid Bot binding approval request kind");
21125
- }
21126
- return new BotExecutionBindingApprovalRequest(
21127
- readIdentifier2(value, "requestId"),
21128
- readIdentifier2(value, "botId"),
21129
- readIdentifier2(value, "behaviorRevisionId"),
21130
- readIdentifier2(value, "bindingId"),
21131
- readInteger(value, "bindingRevision"),
21132
- readIdentifier2(value, "runtimeId"),
21133
- readIdentifier2(value, "agentRef"),
21134
- readDirectoryIdentifier2(value, "workspaceRef"),
21135
- readInteger(value, "agentConfigRevision"),
21136
- readText2(value, "behaviorInstructions", MAX_INSTRUCTIONS_LENGTH, true),
21137
- readDigest(value, "behaviorDigest"),
21138
- readIdentifiers(value, "requiredCapabilities", 32),
21139
- readTargets(value, "allowedDeliveryTargets"),
21140
- readCompletionPolicy(value["completionPolicy"]),
21141
- decodeAgentExecutionConfiguration(value["executionConfiguration"]),
21142
- readSessionConfigurations(value)
21143
- );
21144
- }
21145
- function decodeBotExecutionBindingApprovedEvent(encoded) {
21146
- const value = parseJson3(encoded);
21147
- assertExactKeys2(value, [
21148
- "agentIdentityDigest",
21149
- "behaviorRevisionId",
21150
- "bindingId",
21151
- "bindingRevision",
21152
- "botId",
21153
- "kind",
21154
- "localGrantId",
21155
- "requestId",
21156
- "workspaceIdentityDigest"
21157
- ]);
21158
- if (value["kind"] !== BOT_BINDING_APPROVED_KIND) {
21159
- throw new ProtocolMessageError("Invalid Bot binding approval event kind");
21160
- }
21161
- return new BotExecutionBindingApprovedEvent(
21162
- readIdentifier2(value, "requestId"),
21163
- readIdentifier2(value, "botId"),
21164
- readIdentifier2(value, "behaviorRevisionId"),
21165
- readIdentifier2(value, "bindingId"),
21166
- readInteger(value, "bindingRevision"),
21167
- readIdentifier2(value, "localGrantId"),
21168
- readDigest(value, "agentIdentityDigest"),
21169
- readDigest(value, "workspaceIdentityDigest")
21170
- );
21171
- }
21172
- function encodeBotExecutionBindingApprovedEvent(event) {
21173
- return JSON.stringify(decodeBotExecutionBindingApprovedEvent(JSON.stringify(event)));
21174
- }
21175
- function decodeBotExecutionBindingUnavailableEvent(encoded) {
21176
- const value = parseJson3(encoded);
21177
- assertExactKeys2(value, [
21178
- "behaviorRevisionId",
21179
- "bindingId",
21180
- "bindingRevision",
21181
- "botId",
21182
- "code",
21183
- "kind",
21184
- "message",
21185
- "requestId"
21186
- ]);
21187
- if (value["kind"] !== BOT_BINDING_UNAVAILABLE_KIND) {
21188
- throw new ProtocolMessageError("Invalid Bot binding unavailable event kind");
21189
- }
21190
- return new BotExecutionBindingUnavailableEvent(
21191
- readIdentifier2(value, "requestId"),
21192
- readIdentifier2(value, "botId"),
21193
- readIdentifier2(value, "behaviorRevisionId"),
21194
- readIdentifier2(value, "bindingId"),
21195
- readInteger(value, "bindingRevision"),
21196
- readIdentifier2(value, "code"),
21197
- readText2(value, "message", 500, false)
21198
- );
21199
- }
21200
- function encodeBotExecutionBindingUnavailableEvent(event) {
21201
- return JSON.stringify(decodeBotExecutionBindingUnavailableEvent(JSON.stringify(event)));
21202
- }
21203
20973
  function decodeBotSessionPromptCommand(encoded) {
21204
20974
  const value = parseJson3(encoded);
21205
20975
  assertKeysWithOptional(
@@ -21224,7 +20994,6 @@ function decodeBotSessionPromptCommand(encoded) {
21224
20994
  "executionConfiguration",
21225
20995
  "images",
21226
20996
  "kind",
21227
- "localGrantId",
21228
20997
  "prompt",
21229
20998
  "replyRoute",
21230
20999
  "resources",
@@ -21270,7 +21039,6 @@ function decodeBotSessionPromptCommand(encoded) {
21270
21039
  readIdentifier2(value, "turnId"),
21271
21040
  readIdentifier2(value, "behaviorRevisionId"),
21272
21041
  readInteger(value, "bindingRevision"),
21273
- readIdentifier2(value, "localGrantId"),
21274
21042
  readText2(value, "behaviorInstructions", MAX_INSTRUCTIONS_LENGTH, true),
21275
21043
  readDigest(value, "behaviorDigest"),
21276
21044
  readTargets(value, "allowedDeliveryTargets"),
@@ -34250,10 +34018,7 @@ var LocalAuthorizationError = class extends Error {
34250
34018
  // src/bots/bot-execution-context.ts
34251
34019
  import { randomBytes } from "node:crypto";
34252
34020
 
34253
- // src/bots/local-bot-grant-store.ts
34254
- import { createHash, randomUUID } from "node:crypto";
34255
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
34256
- var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
34021
+ // src/bots/local-bot-execution-authorizer.ts
34257
34022
  var LocalBotAuthorizationError = class extends Error {
34258
34023
  code;
34259
34024
  constructor(code, message, options = {}) {
@@ -34262,325 +34027,40 @@ var LocalBotAuthorizationError = class extends Error {
34262
34027
  this.name = "LocalBotAuthorizationError";
34263
34028
  }
34264
34029
  };
34265
- var LocalBotGrant = class {
34030
+ var AuthorizedLocalBotExecution = class {
34266
34031
  agent;
34267
- agentIdentityDigest;
34268
- allowedDeliveryTargetIds;
34269
34032
  behaviorDigest;
34270
34033
  behaviorRevisionId;
34271
34034
  bindingId;
34272
34035
  bindingRevision;
34273
34036
  botId;
34274
- expiresAt;
34275
34037
  executionConfiguration;
34276
- localGrantId;
34277
- revocationEpoch;
34278
- workspaceIdentityDigest;
34279
34038
  workspacePath;
34280
34039
  workspaceRef;
34281
- constructor(localGrantId, botId, behaviorRevisionId, behaviorDigest, bindingId, bindingRevision, agent, agentIdentityDigest, workspaceRef, workspacePath, workspaceIdentityDigest, allowedDeliveryTargetIds, executionConfiguration, expiresAt, revocationEpoch) {
34282
- this.localGrantId = localGrantId;
34283
- this.botId = botId;
34284
- this.behaviorRevisionId = behaviorRevisionId;
34285
- this.behaviorDigest = behaviorDigest;
34286
- this.bindingId = bindingId;
34287
- this.bindingRevision = bindingRevision;
34040
+ constructor(command, agent, workspacePath) {
34288
34041
  this.agent = agent;
34289
- this.agentIdentityDigest = agentIdentityDigest;
34290
- this.workspaceRef = workspaceRef;
34042
+ this.behaviorDigest = command.behaviorDigest;
34043
+ this.behaviorRevisionId = command.behaviorRevisionId;
34044
+ this.bindingId = command.bindingId;
34045
+ this.bindingRevision = command.bindingRevision;
34046
+ this.botId = command.botId;
34047
+ this.executionConfiguration = command.executionConfiguration;
34291
34048
  this.workspacePath = workspacePath;
34292
- this.workspaceIdentityDigest = workspaceIdentityDigest;
34293
- this.allowedDeliveryTargetIds = Object.freeze([...allowedDeliveryTargetIds]);
34294
- this.executionConfiguration = executionConfiguration;
34295
- this.expiresAt = expiresAt;
34296
- this.revocationEpoch = revocationEpoch;
34049
+ this.workspaceRef = command.directoryId;
34297
34050
  }
34298
34051
  };
34299
- function digest(value) {
34300
- return createHash("sha256").update(value, "utf8").digest("hex");
34301
- }
34302
- function agentDigest(agent) {
34303
- return digest(
34304
- JSON.stringify({
34305
- adapter: agent.adapterIdentity,
34306
- agent: agent.agentIdentity,
34307
- agentVersion: agent.agentVersion,
34308
- arguments: agent.arguments,
34309
- id: agent.id
34310
- })
34311
- );
34312
- }
34313
- function configurePermission(agent, permissionMode) {
34314
- try {
34315
- return agent.withPermissionMode(permissionMode);
34316
- } catch (cause) {
34317
- if (cause instanceof AgentPermissionConfigurationError) {
34318
- throw new LocalBotAuthorizationError("binding_incompatible", cause.message, { cause });
34319
- }
34320
- throw cause;
34321
- }
34322
- }
34323
- function workspaceDigest(path2) {
34324
- return digest(path2);
34325
- }
34326
- function exactTargets(left, right) {
34327
- if (left.length !== right.length) {
34328
- return false;
34329
- }
34330
- const expected = [...left].sort();
34331
- const actual = [...right].sort();
34332
- return expected.every((target, index2) => target === actual[index2]);
34333
- }
34334
- function exactSessionConfigurations(left, right) {
34335
- if (left.length !== right.length) {
34336
- return false;
34337
- }
34338
- const expected = new Map(left.map((selection) => [selection.configId, selection]));
34339
- return right.every((selection) => {
34340
- const approved = expected.get(selection.configId);
34341
- return approved !== void 0 && approved.booleanValue === selection.booleanValue && approved.value === selection.value && approved.valueType === selection.valueType;
34342
- });
34343
- }
34344
- function exactExecutionConfiguration(left, right) {
34345
- return left.permissionMode === right.permissionMode && exactSessionConfigurations([left.model, left.reasoningEffort], [right.model, right.reasoningEffort]);
34346
- }
34347
- function rowString(row, key) {
34348
- const value = Reflect.get(row, key);
34349
- if (typeof value !== "string") {
34350
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
34351
- }
34352
- return value;
34353
- }
34354
- function rowInteger(row, key) {
34355
- const value = Reflect.get(row, key);
34356
- if (typeof value !== "number" || !Number.isSafeInteger(value)) {
34357
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
34358
- }
34359
- return value;
34360
- }
34361
- function rowHasInteger(row, key) {
34362
- const value = Reflect.get(row, key);
34363
- if (value === null) {
34364
- return false;
34365
- }
34366
- if (typeof value !== "number" || !Number.isSafeInteger(value)) {
34367
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
34368
- }
34369
- return true;
34370
- }
34371
- function parseTargets(encoded) {
34372
- let value;
34373
- try {
34374
- value = JSON.parse(encoded);
34375
- } catch (cause) {
34376
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
34377
- }
34378
- if (!Array.isArray(value) || value.some((target) => typeof target !== "string")) {
34379
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
34380
- }
34381
- return value.filter((target) => typeof target === "string");
34382
- }
34383
- function parseSessionConfigurations(encoded) {
34384
- let value;
34385
- try {
34386
- value = JSON.parse(encoded);
34387
- return decodeSessionConfigurationSelections(value);
34388
- } catch (cause) {
34389
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
34390
- }
34391
- }
34392
- function parseExecutionConfiguration(encoded) {
34393
- let value;
34394
- try {
34395
- value = JSON.parse(encoded);
34396
- return decodeAgentExecutionConfiguration(value);
34397
- } catch (cause) {
34398
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
34399
- }
34400
- }
34401
- var LocalBotGrantStore = class {
34402
- #database;
34403
- constructor(path2) {
34404
- this.#database = new DatabaseSync3(path2);
34405
- this.#database.exec(`
34406
- CREATE TABLE IF NOT EXISTS local_bot_grants (
34407
- local_grant_id TEXT PRIMARY KEY,
34408
- bot_id TEXT NOT NULL,
34409
- behavior_revision_id TEXT NOT NULL,
34410
- behavior_digest TEXT NOT NULL,
34411
- binding_id TEXT NOT NULL UNIQUE,
34412
- binding_revision INTEGER NOT NULL,
34413
- agent_ref TEXT NOT NULL,
34414
- agent_identity_digest TEXT NOT NULL,
34415
- workspace_ref TEXT NOT NULL,
34416
- workspace_path TEXT NOT NULL,
34417
- workspace_identity_digest TEXT NOT NULL,
34418
- allowed_delivery_target_ids_json TEXT NOT NULL,
34419
- unattended_policy_json TEXT NOT NULL,
34420
- created_at INTEGER NOT NULL,
34421
- expires_at INTEGER NOT NULL,
34422
- revocation_epoch INTEGER NOT NULL DEFAULT 0,
34423
- revoked_at INTEGER
34424
- ) STRICT;
34425
- CREATE TABLE IF NOT EXISTS local_bot_binding_resolutions (
34426
- request_id TEXT PRIMARY KEY,
34427
- binding_id TEXT NOT NULL,
34428
- local_grant_id TEXT NOT NULL,
34429
- resolved_at INTEGER NOT NULL,
34430
- result TEXT NOT NULL CHECK (result IN ('approved', 'unavailable')),
34431
- error_code TEXT,
34432
- error_message TEXT
34433
- ) STRICT;
34434
- CREATE TABLE IF NOT EXISTS local_bot_grant_configurations (
34435
- local_grant_id TEXT PRIMARY KEY,
34436
- session_configurations_json TEXT NOT NULL
34437
- ) STRICT;
34438
- CREATE TABLE IF NOT EXISTS local_bot_grant_execution_configurations (
34439
- local_grant_id TEXT PRIMARY KEY,
34440
- execution_configuration_json TEXT NOT NULL
34441
- ) STRICT;
34442
- `);
34443
- }
34444
- approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
34052
+ var LocalBotExecutionAuthorizer = class {
34053
+ authorize = async (command, catalog, directories, bindingAuthorityId, signal) => {
34445
34054
  signal.throwIfAborted();
34446
- const existing = this.#database.prepare(
34447
- `SELECT grants.* FROM local_bot_binding_resolutions AS resolutions
34448
- INNER JOIN local_bot_grants AS grants
34449
- ON grants.local_grant_id = resolutions.local_grant_id
34450
- WHERE resolutions.request_id = ? AND resolutions.binding_id = ?
34451
- AND resolutions.result = 'approved'`
34452
- ).get(request.requestId, request.bindingId);
34453
- if (existing !== void 0) {
34454
- return new BotExecutionBindingApprovedEvent(
34455
- request.requestId,
34456
- request.botId,
34457
- request.behaviorRevisionId,
34458
- request.bindingId,
34459
- request.bindingRevision,
34460
- rowString(existing, "local_grant_id"),
34461
- rowString(existing, "agent_identity_digest"),
34462
- rowString(existing, "workspace_identity_digest")
34463
- );
34464
- }
34465
- const resolved = await this.resolveProposal(request, catalog, directories, bindingAuthorityId, signal);
34466
- const localGrantId = `lbg_${randomUUID()}`;
34467
- const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
34468
- this.#database.exec("BEGIN IMMEDIATE");
34055
+ let agent;
34469
34056
  try {
34470
- this.#database.prepare(
34471
- `INSERT INTO local_bot_grants (
34472
- local_grant_id, bot_id, behavior_revision_id, behavior_digest,
34473
- binding_id, binding_revision, agent_ref,
34474
- agent_identity_digest, workspace_ref, workspace_path,
34475
- workspace_identity_digest, allowed_delivery_target_ids_json,
34476
- unattended_policy_json, created_at, expires_at
34477
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
34478
- ).run(
34479
- localGrantId,
34480
- request.botId,
34481
- request.behaviorRevisionId,
34482
- request.behaviorDigest,
34483
- request.bindingId,
34484
- request.bindingRevision,
34485
- request.agentRef,
34486
- resolved.agentIdentityDigest,
34487
- request.workspaceRef,
34488
- resolved.workspacePath,
34489
- resolved.workspaceIdentityDigest,
34490
- JSON.stringify(request.allowedDeliveryTargets.map((target) => target.deliveryTargetId)),
34491
- JSON.stringify({ localSideEffects: "owner-approval-required" }),
34492
- now,
34493
- expiresAt
34494
- );
34495
- this.#database.prepare(
34496
- `INSERT INTO local_bot_grant_configurations (
34497
- local_grant_id, session_configurations_json
34498
- ) VALUES (?, ?)`
34499
- ).run(localGrantId, JSON.stringify(request.sessionConfigurations));
34500
- this.#database.prepare(
34501
- `INSERT INTO local_bot_grant_execution_configurations (
34502
- local_grant_id, execution_configuration_json
34503
- ) VALUES (?, ?)`
34504
- ).run(localGrantId, JSON.stringify(request.executionConfiguration));
34505
- this.#database.prepare(
34506
- `INSERT INTO local_bot_binding_resolutions (
34507
- request_id, binding_id, local_grant_id, resolved_at, result
34508
- ) VALUES (?, ?, ?, ?, 'approved')`
34509
- ).run(request.requestId, request.bindingId, localGrantId, now);
34510
- this.#database.exec("COMMIT");
34057
+ agent = catalog.find(command.agentId).withPermissionMode(command.executionConfiguration.permissionMode);
34511
34058
  } catch (cause) {
34512
- this.#database.exec("ROLLBACK");
34059
+ if (cause instanceof AgentPermissionConfigurationError) {
34060
+ throw new LocalBotAuthorizationError("binding_incompatible", cause.message, { cause });
34061
+ }
34513
34062
  throw cause;
34514
34063
  }
34515
- signal.throwIfAborted();
34516
- return new BotExecutionBindingApprovedEvent(
34517
- request.requestId,
34518
- request.botId,
34519
- request.behaviorRevisionId,
34520
- request.bindingId,
34521
- request.bindingRevision,
34522
- localGrantId,
34523
- resolved.agentIdentityDigest,
34524
- resolved.workspaceIdentityDigest
34525
- );
34526
- };
34527
- resolveExecution = async (command, catalog, directories, bindingAuthorityId, now, signal) => {
34528
- signal.throwIfAborted();
34529
- const row = this.#database.prepare(
34530
- `SELECT grants.*, COALESCE(configurations.session_configurations_json, '[]')
34531
- AS session_configurations_json,
34532
- COALESCE(execution.execution_configuration_json, ?)
34533
- AS execution_configuration_json
34534
- FROM local_bot_grants AS grants
34535
- LEFT JOIN local_bot_grant_configurations AS configurations
34536
- ON configurations.local_grant_id = grants.local_grant_id
34537
- LEFT JOIN local_bot_grant_execution_configurations AS execution
34538
- ON execution.local_grant_id = grants.local_grant_id
34539
- WHERE grants.local_grant_id = ? AND grants.bot_id = ?
34540
- AND behavior_revision_id = ? AND behavior_digest = ?
34541
- AND binding_id = ? AND binding_revision = ?
34542
- AND agent_ref = ?`
34543
- ).get(
34544
- JSON.stringify(DEFAULT_AGENT_EXECUTION_CONFIGURATION),
34545
- command.localGrantId,
34546
- command.botId,
34547
- command.behaviorRevisionId,
34548
- command.behaviorDigest,
34549
- command.bindingId,
34550
- command.bindingRevision,
34551
- command.agentId
34552
- );
34553
- if (row === void 0) {
34554
- throw new LocalBotAuthorizationError(
34555
- "binding_not_approved",
34556
- "The Bot execution binding is not locally approved"
34557
- );
34558
- }
34559
- const approvedTargets = parseTargets(rowString(row, "allowed_delivery_target_ids_json"));
34560
- const requestedTargets = command.allowedDeliveryTargets.map((target) => target.deliveryTargetId);
34561
- if (!exactTargets(approvedTargets, requestedTargets)) {
34562
- throw new LocalBotAuthorizationError(
34563
- "binding_not_approved",
34564
- "The Bot execution target policy differs from its binding"
34565
- );
34566
- }
34567
- const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
34568
- if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
34569
- throw new LocalBotAuthorizationError(
34570
- "binding_not_approved",
34571
- "The Bot Agent configuration differs from its binding"
34572
- );
34573
- }
34574
- const approvedExecutionConfiguration = parseExecutionConfiguration(
34575
- rowString(row, "execution_configuration_json")
34576
- );
34577
- if (!exactExecutionConfiguration(approvedExecutionConfiguration, command.executionConfiguration)) {
34578
- throw new LocalBotAuthorizationError(
34579
- "binding_not_approved",
34580
- "The Bot execution configuration differs from its binding"
34581
- );
34582
- }
34583
- const agent = configurePermission(catalog.find(command.agentId), command.executionConfiguration.permissionMode);
34584
34064
  const [adapterUnchanged, agentUnchanged] = await Promise.all([
34585
34065
  revalidateExecutable(agent.adapterIdentity),
34586
34066
  revalidateExecutable(agent.agentIdentity)
@@ -34592,150 +34072,15 @@ var LocalBotGrantStore = class {
34592
34072
  "The local Agent executable changed while the Runtime is active; restart the Runtime"
34593
34073
  );
34594
34074
  }
34595
- const workspaceRef = rowString(row, "workspace_ref");
34596
- const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
34597
- const currentAgentDigest = agentDigest(agent);
34598
- const currentWorkspaceDigest = workspaceDigest(workspacePath);
34599
- signal.throwIfAborted();
34600
- let expiresAt = rowInteger(row, "expires_at");
34601
- let revocationEpoch = rowInteger(row, "revocation_epoch");
34602
- if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
34603
- const refreshed = this.refreshTarget(
34604
- rowString(row, "local_grant_id"),
34605
- currentAgentDigest,
34606
- currentWorkspaceDigest,
34607
- workspacePath,
34608
- now
34609
- );
34610
- expiresAt = refreshed.expiresAt;
34611
- revocationEpoch = refreshed.revocationEpoch;
34612
- }
34613
34075
  if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
34614
34076
  throw new LocalBotAuthorizationError(
34615
34077
  "binding_incompatible",
34616
- "The local Agent cannot apply the approved Bot behavior"
34617
- );
34618
- }
34619
- return new LocalBotGrant(
34620
- rowString(row, "local_grant_id"),
34621
- command.botId,
34622
- command.behaviorRevisionId,
34623
- command.behaviorDigest,
34624
- command.bindingId,
34625
- command.bindingRevision,
34626
- agent,
34627
- currentAgentDigest,
34628
- workspaceRef,
34629
- workspacePath,
34630
- currentWorkspaceDigest,
34631
- approvedTargets,
34632
- approvedExecutionConfiguration,
34633
- expiresAt,
34634
- revocationEpoch
34635
- );
34636
- };
34637
- recordUnavailable = (request, code, message, now) => {
34638
- this.#database.prepare(
34639
- `INSERT OR IGNORE INTO local_bot_binding_resolutions (
34640
- request_id, binding_id, local_grant_id, resolved_at,
34641
- result, error_code, error_message
34642
- ) VALUES (?, ?, '', ?, 'unavailable', ?, ?)`
34643
- ).run(request.requestId, request.bindingId, now, code, message);
34644
- };
34645
- close = () => {
34646
- this.#database.close();
34647
- };
34648
- resolveProposal = async (request, catalog, directories, bindingAuthorityId, signal) => {
34649
- const agent = configurePermission(
34650
- catalog.find(request.agentRef),
34651
- request.executionConfiguration.permissionMode
34652
- );
34653
- if (request.requiredCapabilities.includes("embedded-context") && !agent.capabilities.embeddedContextPrompt) {
34654
- throw new LocalBotAuthorizationError(
34655
- "binding_incompatible",
34656
- "The local Agent cannot apply embedded Bot context"
34657
- );
34658
- }
34659
- if (request.requiredCapabilities.some((capability) => capability !== "embedded-context")) {
34660
- throw new LocalBotAuthorizationError(
34661
- "binding_incompatible",
34662
- "The Bot requires an unsupported local Agent capability"
34078
+ "The local Agent cannot apply the Bot behavior"
34663
34079
  );
34664
34080
  }
34665
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
34666
- revalidateExecutable(agent.adapterIdentity),
34667
- revalidateExecutable(agent.agentIdentity)
34668
- ]);
34081
+ const workspacePath = await directories.resolve(bindingAuthorityId, command.directoryId, signal);
34669
34082
  signal.throwIfAborted();
34670
- if (!adapterUnchanged || !agentUnchanged) {
34671
- throw new LocalBotAuthorizationError(
34672
- "binding_incompatible",
34673
- "The local Agent executable changed before approval"
34674
- );
34675
- }
34676
- const workspacePath = await directories.resolve(bindingAuthorityId, request.workspaceRef, signal);
34677
- return {
34678
- agent,
34679
- agentIdentityDigest: agentDigest(agent),
34680
- workspaceIdentityDigest: workspaceDigest(workspacePath),
34681
- workspacePath
34682
- };
34683
- };
34684
- refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
34685
- const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
34686
- this.#database.exec("BEGIN IMMEDIATE");
34687
- try {
34688
- const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
34689
- if (current === void 0) {
34690
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
34691
- }
34692
- const currentExpiresAt = rowInteger(current, "expires_at");
34693
- const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
34694
- if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
34695
- this.#database.exec("COMMIT");
34696
- return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
34697
- }
34698
- const result = this.#database.prepare(
34699
- `UPDATE local_bot_grants
34700
- SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
34701
- expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
34702
- WHERE local_grant_id = ? AND revocation_epoch = ?`
34703
- ).run(
34704
- agentIdentityDigest,
34705
- workspaceIdentityDigest,
34706
- workspacePath,
34707
- expiresAt,
34708
- localGrantId,
34709
- currentRevocationEpoch
34710
- );
34711
- if (result.changes !== 1) {
34712
- throw new LocalBotAuthorizationError(
34713
- "local_grant_invalid",
34714
- "The local Bot grant target could not be refreshed"
34715
- );
34716
- }
34717
- this.#database.prepare(
34718
- `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
34719
- VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
34720
- ).run(
34721
- new Date(now).toISOString(),
34722
- rowString(current, "binding_id"),
34723
- JSON.stringify({
34724
- agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
34725
- bindingId: rowString(current, "binding_id"),
34726
- botId: rowString(current, "bot_id"),
34727
- expired: currentExpiresAt <= now,
34728
- revived: rowHasInteger(current, "revoked_at"),
34729
- workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
34730
- workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
34731
- })
34732
- );
34733
- this.#database.exec("COMMIT");
34734
- return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
34735
- } catch (cause) {
34736
- this.#database.exec("ROLLBACK");
34737
- throw cause;
34738
- }
34083
+ return new AuthorizedLocalBotExecution(command, agent, workspacePath);
34739
34084
  };
34740
34085
  };
34741
34086
 
@@ -34835,7 +34180,7 @@ var BotExecutionContextRegistry = class {
34835
34180
  };
34836
34181
 
34837
34182
  // src/bots/bot-message-command.ts
34838
- import { randomUUID as randomUUID2 } from "node:crypto";
34183
+ import { randomUUID } from "node:crypto";
34839
34184
  import { createConnection } from "node:net";
34840
34185
  var BOT_IPC_RESPONSE_LIMIT = 64 * 1024;
34841
34186
  var BOT_IPC_TIMEOUT_MILLISECONDS = 2e4;
@@ -34984,7 +34329,7 @@ async function executeBotMessageCommand(arguments_, environment, signal) {
34984
34329
  socketPath,
34985
34330
  JSON.stringify({
34986
34331
  contextHandle,
34987
- idempotencyKey: `cli_${randomUUID2()}`,
34332
+ idempotencyKey: `cli_${randomUUID()}`,
34988
34333
  target,
34989
34334
  text: text3
34990
34335
  }),
@@ -35232,7 +34577,7 @@ var BotOutboundIpcServer = class {
35232
34577
  };
35233
34578
 
35234
34579
  // src/pairing/pair-local-machine.ts
35235
- import { randomUUID as randomUUID3 } from "node:crypto";
34580
+ import { randomUUID as randomUUID2 } from "node:crypto";
35236
34581
  import { mkdir as mkdir4, open as open4, realpath as realpath7, rename as rename3, stat as stat6, writeFile as writeFile2 } from "node:fs/promises";
35237
34582
  import { hostname as hostname3 } from "node:os";
35238
34583
  import { basename as basename3, join as join15, resolve as resolve3 } from "node:path";
@@ -36192,7 +35537,7 @@ var HermesAgentSpecification = class extends DirectAcpAgentDefinition {
36192
35537
  import { join as join10 } from "node:path";
36193
35538
 
36194
35539
  // src/agent-installation/managed-agent-archive.ts
36195
- import { createHash as createHash2 } from "node:crypto";
35540
+ import { createHash } from "node:crypto";
36196
35541
  import { createReadStream } from "node:fs";
36197
35542
  import { chmod as chmod2, copyFile, mkdir as mkdir3, mkdtemp as mkdtemp2, open as open3, realpath as realpath6, rename as rename2, rm as rm2, stat as stat5, writeFile } from "node:fs/promises";
36198
35543
  import { delimiter as delimiter2, dirname as dirname5, isAbsolute as isAbsolute7, join as join9, relative as relative4, sep as sep4 } from "node:path";
@@ -36305,7 +35650,7 @@ function isContainedPath3(root, candidate) {
36305
35650
  }
36306
35651
  async function hashFile(path2, signal) {
36307
35652
  signal.throwIfAborted();
36308
- const digest2 = createHash2("sha256");
35653
+ const digest = createHash("sha256");
36309
35654
  const stream = createReadStream(path2, { signal });
36310
35655
  try {
36311
35656
  for await (const chunk of stream) {
@@ -36316,9 +35661,9 @@ async function hashFile(path2, signal) {
36316
35661
  "The managed Agent archive produced invalid bytes"
36317
35662
  );
36318
35663
  }
36319
- digest2.update(chunk);
35664
+ digest.update(chunk);
36320
35665
  }
36321
- return digest2.digest("hex");
35666
+ return digest.digest("hex");
36322
35667
  } catch (error62) {
36323
35668
  if (signal.aborted) {
36324
35669
  signal.throwIfAborted();
@@ -37438,7 +36783,7 @@ async function persistConnection(channelId, relayOrigin, runtimeCredential2, def
37438
36783
  const connectionsDirectory = join15(readStateDirectory(environment), "connections");
37439
36784
  await mkdir4(connectionsDirectory, { mode: 448, recursive: true });
37440
36785
  const connectionPath = join15(connectionsDirectory, `${channelId}.json`);
37441
- const temporaryPath = join15(connectionsDirectory, `.${channelId}.${randomUUID3()}.tmp`);
36786
+ const temporaryPath = join15(connectionsDirectory, `.${channelId}.${randomUUID2()}.tmp`);
37442
36787
  await writeFile2(
37443
36788
  temporaryPath,
37444
36789
  `${JSON.stringify(
@@ -37588,7 +36933,7 @@ async function resumeLocalMachine(arguments_, signal = new AbortController().sig
37588
36933
  }
37589
36934
 
37590
36935
  // src/run-daemon.ts
37591
- import { randomUUID as randomUUID6 } from "node:crypto";
36936
+ import { randomUUID as randomUUID5 } from "node:crypto";
37592
36937
  import { basename as basename6, join as join17 } from "node:path";
37593
36938
  import { styleText } from "node:util";
37594
36939
  import { fetch as fetch7, WebSocket as WebSocket2 } from "undici";
@@ -38133,7 +37478,7 @@ var FixedInstallationExecutor = class {
38133
37478
  };
38134
37479
 
38135
37480
  // src/artifacts/runtime-artifact-uploader.ts
38136
- import { createHash as createHash3 } from "node:crypto";
37481
+ import { createHash as createHash2 } from "node:crypto";
38137
37482
 
38138
37483
  // ../mobius-sdk/src/errors.ts
38139
37484
  var MobiusError = class extends Error {
@@ -38460,7 +37805,7 @@ async function uploadRuntimeArtifact(config2, sessionId, artifact, signal) {
38460
37805
  artifact.name,
38461
37806
  artifact.mimeType,
38462
37807
  artifact.bytes.byteLength,
38463
- createHash3("sha256").update(artifact.bytes).digest("hex")
37808
+ createHash2("sha256").update(artifact.bytes).digest("hex")
38464
37809
  );
38465
37810
  } catch (cause) {
38466
37811
  translateSdkError(cause);
@@ -38687,18 +38032,18 @@ var AppliedBotContext = class {
38687
38032
  }
38688
38033
  };
38689
38034
  var EmbeddedBotContextApplicator = class {
38690
- apply = async (command, grant, resources, signal) => {
38035
+ apply = async (command, execution, resources, signal) => {
38691
38036
  signal.throwIfAborted();
38692
- if (grant.botId !== command.botId || grant.behaviorRevisionId !== command.behaviorRevisionId || grant.behaviorDigest !== command.behaviorDigest) {
38037
+ if (execution.botId !== command.botId || execution.behaviorRevisionId !== command.behaviorRevisionId || execution.behaviorDigest !== command.behaviorDigest) {
38693
38038
  throw new LocalBotAuthorizationError(
38694
- "binding_not_approved",
38695
- "The Bot behavior does not match its local authorization"
38039
+ "binding_incompatible",
38040
+ "The Bot behavior does not match the execution target"
38696
38041
  );
38697
38042
  }
38698
38043
  if (command.behaviorInstructions.length === 0) {
38699
38044
  return new AppliedBotContext(resources);
38700
38045
  }
38701
- if (!grant.agent.capabilities.embeddedContextPrompt) {
38046
+ if (!execution.agent.capabilities.embeddedContextPrompt) {
38702
38047
  throw new LocalBotAuthorizationError(
38703
38048
  "binding_incompatible",
38704
38049
  "The local Agent cannot enforce the Bot behavior context"
@@ -38716,7 +38061,7 @@ var EmbeddedBotContextApplicator = class {
38716
38061
  };
38717
38062
 
38718
38063
  // src/native-sessions/service.ts
38719
- import { randomUUID as randomUUID4 } from "node:crypto";
38064
+ import { randomUUID as randomUUID3 } from "node:crypto";
38720
38065
  import { basename as basename5 } from "node:path";
38721
38066
 
38722
38067
  // src/native-sessions/codex-history.ts
@@ -39011,7 +38356,7 @@ var NativeSessionService = class {
39011
38356
  if (authorized === null) {
39012
38357
  return null;
39013
38358
  }
39014
- const entryId = randomUUID4();
38359
+ const entryId = randomUUID3();
39015
38360
  if (this.#entries.size >= 5e3) {
39016
38361
  this.#entries.clear();
39017
38362
  }
@@ -39065,7 +38410,7 @@ var NativeSessionService = class {
39065
38410
  "invalid_native_session_response"
39066
38411
  );
39067
38412
  }
39068
- nextCursor = randomUUID4();
38413
+ nextCursor = randomUUID3();
39069
38414
  if (this.#cursors.size >= 500) {
39070
38415
  this.#cursors.clear();
39071
38416
  }
@@ -39383,7 +38728,7 @@ var NativeSessionService = class {
39383
38728
  };
39384
38729
 
39385
38730
  // src/prompt-artifact-resolver.ts
39386
- import { createHash as createHash4 } from "node:crypto";
38731
+ import { createHash as createHash3 } from "node:crypto";
39387
38732
  import { fetch as fetch6 } from "undici";
39388
38733
  var ARTIFACT_SCHEME = "mobius-artifact:";
39389
38734
  var ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS = 2e4;
@@ -39522,7 +38867,7 @@ async function download(config2, command, reference, signal) {
39522
38867
  );
39523
38868
  }
39524
38869
  const bytes = await responseBytes(response, reference.byteLength, requestSignal);
39525
- if (createHash4("sha256").update(bytes).digest("hex") !== reference.sha256) {
38870
+ if (createHash3("sha256").update(bytes).digest("hex") !== reference.sha256) {
39526
38871
  throw new PromptArtifactError(
39527
38872
  "artifact_integrity_failed",
39528
38873
  "The prompt artifact failed integrity validation"
@@ -39831,7 +39176,7 @@ var RelayConnectionDiagnostics = class {
39831
39176
  };
39832
39177
 
39833
39178
  // src/relay-connection/liveness.ts
39834
- import { randomUUID as randomUUID5 } from "node:crypto";
39179
+ import { randomUUID as randomUUID4 } from "node:crypto";
39835
39180
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
39836
39181
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
39837
39182
  var RelayLivenessState = class {
@@ -39920,7 +39265,7 @@ var RelayConnectionLiveness = class {
39920
39265
  }
39921
39266
  throw new Error("Heartbeat was scheduled in an invalid state");
39922
39267
  }
39923
- const heartbeatId = randomUUID5();
39268
+ const heartbeatId = randomUUID4();
39924
39269
  this.#state = new AwaitingHeartbeatAckState(
39925
39270
  heartbeatId,
39926
39271
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -39937,7 +39282,7 @@ var RelayConnectionLiveness = class {
39937
39282
  // src/relay-connection/session-event-outbox.ts
39938
39283
  import { mkdirSync as mkdirSync3 } from "node:fs";
39939
39284
  import { dirname as dirname7 } from "node:path";
39940
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
39285
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
39941
39286
  var DEFAULT_OUTBOX_LIMITS = {
39942
39287
  criticalEventBytes: 136 * 1024 * 1024,
39943
39288
  runtimeDeliveryBytes: 64 * 1024 * 1024,
@@ -39989,7 +39334,7 @@ function rowNumber(row, field) {
39989
39334
  }
39990
39335
  return value;
39991
39336
  }
39992
- function rowString2(row, field) {
39337
+ function rowString(row, field) {
39993
39338
  const value = typeof row === "object" && row !== null ? Reflect.get(row, field) : void 0;
39994
39339
  if (typeof value !== "string" || value.length === 0) {
39995
39340
  throw new Error(`SQLite returned an invalid ${field} value`);
@@ -40003,7 +39348,7 @@ var SessionEventOutbox = class {
40003
39348
  validateLimits(limits);
40004
39349
  this.#limits = limits;
40005
39350
  mkdirSync3(dirname7(path2), { recursive: true });
40006
- this.#database = new DatabaseSync4(path2);
39351
+ this.#database = new DatabaseSync3(path2);
40007
39352
  this.#database.exec(`
40008
39353
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
40009
39354
  ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -40238,8 +39583,8 @@ var SessionEventOutbox = class {
40238
39583
  WHERE delivery_id = ?`
40239
39584
  ).get(delivery.deliveryId);
40240
39585
  if (existing !== void 0) {
40241
- const sessionId = rowString2(existing, "session_id");
40242
- const payload = rowString2(existing, "payload_json");
39586
+ const sessionId = rowString(existing, "session_id");
39587
+ const payload = rowString(existing, "payload_json");
40243
39588
  const state = runtimeDeliveryState(existing);
40244
39589
  if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
40245
39590
  throw new Error("The Runtime delivery identity conflicts with its durable receipt");
@@ -40327,9 +39672,9 @@ var SessionEventOutbox = class {
40327
39672
  ORDER BY received_at, delivery_id`
40328
39673
  ).all().map(
40329
39674
  (row) => new StoredRuntimeDelivery(
40330
- rowString2(row, "delivery_id"),
40331
- rowString2(row, "session_id"),
40332
- rowString2(row, "payload_json"),
39675
+ rowString(row, "delivery_id"),
39676
+ rowString(row, "session_id"),
39677
+ rowString(row, "payload_json"),
40333
39678
  runtimeDeliveryState(row),
40334
39679
  true
40335
39680
  )
@@ -40511,7 +39856,7 @@ function validateLimits(limits) {
40511
39856
  }
40512
39857
  }
40513
39858
  function runtimeDeliveryState(row) {
40514
- const state = rowString2(row, "state");
39859
+ const state = rowString(row, "state");
40515
39860
  if (state !== "received" && state !== "relay_committed" && state !== "processed") {
40516
39861
  throw new Error("SQLite returned an invalid Runtime delivery state");
40517
39862
  }
@@ -40537,9 +39882,9 @@ var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
40537
39882
  var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
40538
39883
  function botIpcSocketPath() {
40539
39884
  if (process.platform === "win32") {
40540
- return `\\\\.\\pipe\\mobius-bot-${randomUUID6()}`;
39885
+ return `\\\\.\\pipe\\mobius-bot-${randomUUID5()}`;
40541
39886
  }
40542
- return join17("/tmp", `mobius-bot-${randomUUID6()}.sock`);
39887
+ return join17("/tmp", `mobius-bot-${randomUUID5()}.sock`);
40543
39888
  }
40544
39889
  var DaemonAcpObserver = class {
40545
39890
  #config;
@@ -41498,14 +40843,14 @@ async function applyRequiredExecutionSelection(sessions, configOptions, selectio
41498
40843
  booleanValue: false,
41499
40844
  configId: selection.configId,
41500
40845
  cwd,
41501
- requestId: `cfg_${randomUUID6()}`,
40846
+ requestId: `cfg_${randomUUID5()}`,
41502
40847
  sessionId,
41503
40848
  signal,
41504
40849
  value: selection.value,
41505
40850
  valueType: "select"
41506
40851
  });
41507
40852
  }
41508
- async function executeBotPrompt(outbox, publisher, command, config2, directories, audit, sessions, grants, contexts, applicator, ipc, attemptId, activateAttempt, timer, signal) {
40853
+ async function executeBotPrompt(outbox, publisher, command, config2, directories, audit, sessions, authorizer, contexts, applicator, ipc, attemptId, activateAttempt, timer, signal) {
41509
40854
  const activities = new CoalescingDaemonActivityPublisher(timer, (activity) => {
41510
40855
  publisher.recordAttempt(command.sessionId, encodeDaemonActivity(command, activity), attemptId);
41511
40856
  });
@@ -41515,21 +40860,7 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
41515
40860
  if (!Number.isSafeInteger(deadline) || remaining <= 0) {
41516
40861
  throw new LocalBotAuthorizationError("turn_expired", "The Bot execution deadline has expired");
41517
40862
  }
41518
- const grant = await grants.resolveExecution(
41519
- command,
41520
- config2.catalog,
41521
- directories,
41522
- config2.bindingId,
41523
- Date.now(),
41524
- signal
41525
- );
41526
- const requestedExecutionTargetOverridden = command.directoryId !== grant.workspaceRef || command.additionalDirectoryIds.length > 0;
41527
- if (requestedExecutionTargetOverridden && !(command.replyRoute instanceof OwnerBotReplyRoute)) {
41528
- throw new LocalBotAuthorizationError(
41529
- "binding_not_approved",
41530
- "Only a paired owner conversation can override the approved Bot workspace"
41531
- );
41532
- }
40863
+ const execution = await authorizer.authorize(command, config2.catalog, directories, config2.bindingId, signal);
41533
40864
  const resolved = await resolveSessionDirectories(
41534
40865
  directories,
41535
40866
  config2.bindingId,
@@ -41537,20 +40868,8 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
41537
40868
  command.additionalDirectoryIds,
41538
40869
  signal
41539
40870
  );
41540
- const executionTargetOverridden = resolved.cwd !== grant.workspacePath || resolved.additionalDirectories.length > 0;
41541
- if (executionTargetOverridden && !sessions.hasPreparedSession(
41542
- command.sessionId,
41543
- grant.agent.id,
41544
- resolved.cwd,
41545
- resolved.additionalDirectories
41546
- )) {
41547
- throw new LocalBotAuthorizationError(
41548
- "local_approval_required",
41549
- "Open this Bot conversation in the paired local Web app before using the selected workspace"
41550
- );
41551
- }
41552
40871
  const attachments = await resolvePromptArtifacts(config2, command, signal);
41553
- const applied = await applicator.apply(command, grant, attachments.resources, signal);
40872
+ const applied = await applicator.apply(command, execution, attachments.resources, signal);
41554
40873
  const deadlineSignal = AbortSignal.timeout(remaining);
41555
40874
  const executionSignal = AbortSignal.any([signal, deadlineSignal]);
41556
40875
  const startExecution = () => {
@@ -41560,8 +40879,7 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
41560
40879
  behaviorRevisionId: command.behaviorRevisionId,
41561
40880
  bindingId: command.bindingId,
41562
40881
  botId: command.botId,
41563
- executionId: command.executionId,
41564
- localGrantId: command.localGrantId
40882
+ executionId: command.executionId
41565
40883
  },
41566
40884
  event: "bot_session_authorized",
41567
40885
  sessionId: command.sessionId
@@ -41584,7 +40902,7 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
41584
40902
  startExecution();
41585
40903
  await sessions.steerPrompt({
41586
40904
  additionalDirectories: resolved.additionalDirectories,
41587
- agent: grant.agent,
40905
+ agent: execution.agent,
41588
40906
  commandId: command.commandId,
41589
40907
  cwd: resolved.cwd,
41590
40908
  images: attachments.images,
@@ -41604,7 +40922,7 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
41604
40922
  }
41605
40923
  const lease = contexts.activate(command);
41606
40924
  try {
41607
- const agent = botExecutionAgent(grant.agent, lease.context.contextHandle, ipc.socketPath);
40925
+ const agent = botExecutionAgent(execution.agent, lease.context.contextHandle, ipc.socketPath);
41608
40926
  const prepared = await sessions.prepareExecutionSession({
41609
40927
  additionalDirectories: resolved.additionalDirectories,
41610
40928
  agent,
@@ -41612,11 +40930,11 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
41612
40930
  sessionId: command.sessionId,
41613
40931
  signal: executionSignal
41614
40932
  });
41615
- assertPreparedPermission(prepared.configOptions, grant.executionConfiguration.permissionMode);
40933
+ assertPreparedPermission(prepared.configOptions, execution.executionConfiguration.permissionMode);
41616
40934
  let configOptions = await applyRequiredExecutionSelection(
41617
40935
  sessions,
41618
40936
  prepared.configOptions,
41619
- grant.executionConfiguration.model,
40937
+ execution.executionConfiguration.model,
41620
40938
  "model",
41621
40939
  agent,
41622
40940
  resolved.cwd,
@@ -41627,7 +40945,7 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
41627
40945
  configOptions = await applyRequiredExecutionSelection(
41628
40946
  sessions,
41629
40947
  configOptions,
41630
- grant.executionConfiguration.reasoningEffort,
40948
+ execution.executionConfiguration.reasoningEffort,
41631
40949
  "thought_level",
41632
40950
  agent,
41633
40951
  resolved.cwd,
@@ -41642,7 +40960,7 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
41642
40960
  booleanValue: selection.booleanValue,
41643
40961
  configId: selection.configId,
41644
40962
  cwd: resolved.cwd,
41645
- requestId: `cfg_${randomUUID6()}`,
40963
+ requestId: `cfg_${randomUUID5()}`,
41646
40964
  sessionId: command.sessionId,
41647
40965
  signal: executionSignal,
41648
40966
  value: selection.value,
@@ -41774,13 +41092,13 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
41774
41092
  {
41775
41093
  agentId: agent.id,
41776
41094
  kind: AGENT_INSTALL_REQUEST_KIND,
41777
- requestId: `automatic-integration-${randomUUID6()}`
41095
+ requestId: `automatic-integration-${randomUUID5()}`
41778
41096
  },
41779
41097
  signal
41780
41098
  );
41781
41099
  }
41782
41100
  }
41783
- async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, grants, contexts, applicator, ipc, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer) {
41101
+ async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, authorizer, contexts, applicator, ipc, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer) {
41784
41102
  const relayUrl = new URL(config2.relayUrl);
41785
41103
  relayUrl.searchParams.set("deliveryReceipts", "1");
41786
41104
  relayUrl.searchParams.set("liveness", "1");
@@ -41960,7 +41278,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41960
41278
  directories,
41961
41279
  audit,
41962
41280
  sessions,
41963
- grants,
41281
+ authorizer,
41964
41282
  contexts,
41965
41283
  applicator,
41966
41284
  ipc,
@@ -42140,70 +41458,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42140
41458
  }
42141
41459
  return;
42142
41460
  }
42143
- if (kind === BOT_BINDING_APPROVED_KIND) {
42144
- decodeBotExecutionBindingApprovedEvent(encoded);
42145
- return;
42146
- }
42147
- if (kind === BOT_BINDING_UNAVAILABLE_KIND) {
42148
- decodeBotExecutionBindingUnavailableEvent(encoded);
42149
- return;
42150
- }
42151
- if (kind === BOT_BINDING_APPROVAL_REQUEST_KIND) {
42152
- const request = decodeBotExecutionBindingApprovalRequest(encoded);
42153
- void grants.approve(
42154
- request,
42155
- config2.catalog,
42156
- directories,
42157
- config2.bindingId,
42158
- Date.now(),
42159
- connectionController.signal
42160
- ).then((approved) => {
42161
- audit.record({
42162
- commandId: request.requestId,
42163
- details: {
42164
- behaviorRevisionId: request.behaviorRevisionId,
42165
- bindingId: request.bindingId,
42166
- botId: request.botId,
42167
- localGrantId: approved.localGrantId
42168
- },
42169
- event: "bot_binding_approved",
42170
- sessionId: `bot-binding:${request.bindingId}`
42171
- });
42172
- if (socket.readyState === WebSocket2.OPEN) {
42173
- send(socket, encodeBotExecutionBindingApprovedEvent(approved));
42174
- }
42175
- }).catch((error62) => {
42176
- if (connectionController.signal.aborted) {
42177
- return;
42178
- }
42179
- const code = error62 instanceof LocalBotAuthorizationError ? error62.code : "binding_incompatible";
42180
- const message = error62 instanceof LocalBotAuthorizationError ? error62.message : "The local execution target is incompatible";
42181
- grants.recordUnavailable(request, code, message, Date.now());
42182
- audit.record({
42183
- commandId: request.requestId,
42184
- details: { bindingId: request.bindingId, botId: request.botId, code },
42185
- event: "bot_binding_unavailable",
42186
- sessionId: `bot-binding:${request.bindingId}`
42187
- });
42188
- if (socket.readyState === WebSocket2.OPEN) {
42189
- send(
42190
- socket,
42191
- encodeBotExecutionBindingUnavailableEvent(
42192
- new BotExecutionBindingUnavailableEvent(
42193
- request.requestId,
42194
- request.botId,
42195
- request.behaviorRevisionId,
42196
- request.bindingId,
42197
- request.bindingRevision,
42198
- code,
42199
- message
42200
- )
42201
- )
42202
- );
42203
- }
42204
- });
42205
- return;
42206
- }
42207
41461
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
42208
41462
  const command2 = decodeNativeSessionCancel(encoded);
42209
41463
  const pending = nativeRequests.get(command2.requestId);
@@ -42599,7 +41853,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42599
41853
  directories,
42600
41854
  audit,
42601
41855
  sessions,
42602
- grants,
41856
+ authorizer,
42603
41857
  contexts,
42604
41858
  applicator,
42605
41859
  ipc,
@@ -42725,7 +41979,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
42725
41979
  const sessionStore = new SqliteAcpSessionStore(config2.auditDatabasePath);
42726
41980
  const outbox = new SessionEventOutbox(config2.auditDatabasePath);
42727
41981
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
42728
- const grants = new LocalBotGrantStore(config2.auditDatabasePath);
41982
+ const authorizer = new LocalBotExecutionAuthorizer();
42729
41983
  const contexts = new BotExecutionContextRegistry();
42730
41984
  const applicator = new EmbeddedBotContextApplicator();
42731
41985
  const ipc = new BotOutboundIpcServer(botIpcSocketPath(), config2.relayUrl, contexts);
@@ -42816,7 +42070,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
42816
42070
  nativeSessions,
42817
42071
  outbox,
42818
42072
  publisher,
42819
- grants,
42073
+ authorizer,
42820
42074
  contexts,
42821
42075
  applicator,
42822
42076
  ipc,
@@ -42861,13 +42115,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
42861
42115
  sessionStore.close();
42862
42116
  } finally {
42863
42117
  try {
42864
- grants.close();
42118
+ publisher.close();
42865
42119
  } finally {
42866
- try {
42867
- publisher.close();
42868
- } finally {
42869
- outbox.close();
42870
- }
42120
+ outbox.close();
42871
42121
  }
42872
42122
  }
42873
42123
  }