@goodfish/jarvy 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1295,7 +1295,7 @@ function connectorRoutes(connectors) {
1295
1295
  routes.get("/", (c) => c.json({ connectors: connectors.list(), presets: connectors.presets(), publicUrl: connectors.publicUrl() }));
1296
1296
  routes.post("/presets/:provider/oauth/start", jsonBody, async (c) => {
1297
1297
  const input = await readJson(c).catch(() => ({}));
1298
- return c.json(await connectors.oauth.startPreset(c.req.param("provider"), input.redirectUri));
1298
+ return c.json(await connectors.oauth.startPreset(c.req.param("provider"), input.redirectUri, input.name));
1299
1299
  });
1300
1300
  routes.post("/presets/:provider/token", jsonBody, async (c) => {
1301
1301
  const input = await readJson(c);
@@ -1332,7 +1332,6 @@ function connectorRoutes(connectors) {
1332
1332
  headers: input.headers,
1333
1333
  clientId: input.clientId,
1334
1334
  clientSecret: input.clientSecret,
1335
- unconfirmed: input.unconfirmed,
1336
1335
  enabled: input.enabled
1337
1336
  }));
1338
1337
  });
@@ -1361,7 +1360,8 @@ function connectorRoutes(connectors) {
1361
1360
  });
1362
1361
  routes.get("/:id/uses", (c) => c.json({ uses: connectors.uses(c.req.param("id")) }));
1363
1362
  routes.post("/requests/:chatId/:messageId", async (c) => {
1364
- return c.json(messageView(await connectors.fulfilAuth(c.get("actorId"), c.req.param("chatId"), c.req.param("messageId"))));
1363
+ const input = await readJson(c).catch(() => ({}));
1364
+ return c.json(messageView(connectors.fulfilAuth(c.get("actorId"), c.req.param("chatId"), c.req.param("messageId"), { scope: input.scope })));
1365
1365
  });
1366
1366
  return routes;
1367
1367
  }
@@ -2569,6 +2569,13 @@ function migrateConnectors(db) {
2569
2569
  CREATE INDEX connector_uses_connector ON connector_uses(connector_id, at);
2570
2570
  `);
2571
2571
  });
2572
+ migration(db, 35, () => {
2573
+ db.exec(`
2574
+ ALTER TABLE connector_grants ADD COLUMN scope TEXT NOT NULL DEFAULT 'always' CHECK(scope IN ('always','once'));
2575
+ ALTER TABLE connector_grants ADD COLUMN run_id TEXT;
2576
+ DROP TABLE IF EXISTS connector_unconfirmed_tools;
2577
+ `);
2578
+ });
2572
2579
  }
2573
2580
 
2574
2581
  // src/server/infra/storage/migrations/schema.ts
@@ -2693,7 +2700,7 @@ function migrateRuntime(db) {
2693
2700
  // src/server/infra/storage/migrations/schema.ts
2694
2701
  function migrateDatabase(db, cipher, dataDir) {
2695
2702
  const version2 = db.prepare("PRAGMA user_version").get().user_version;
2696
- if (version2 > 34) throw new Error(`Unsupported database version: ${version2}`);
2703
+ if (version2 > 35) throw new Error(`Unsupported database version: ${version2}`);
2697
2704
  migratePrototype(db);
2698
2705
  if (version2 >= 5) {
2699
2706
  migrateRuntime(db);
@@ -4335,7 +4342,8 @@ var CATEGORY = {
4335
4342
  change: "system",
4336
4343
  task: "system",
4337
4344
  followed: "system",
4338
- job: "system"
4345
+ job: "system",
4346
+ handoff: "system"
4339
4347
  };
4340
4348
 
4341
4349
  // src/server/infra/storage/inbox-repository.ts
@@ -4373,6 +4381,14 @@ var InboxRepository = class {
4373
4381
  cancelTaskNotice(taskId) {
4374
4382
  this.db.prepare(`DELETE FROM inbox WHERE category='system' AND kind='task' AND state='pending' AND json_extract(payload,'$.task')=?`).run(taskId);
4375
4383
  }
4384
+ /** Atomically commits a handoff's durable database state (A67, A73, A99): resets seen chat notices and writes
4385
+ * post-handoff notices (`followed`, plus `handoff/continue` when auto-continuing) in a single transaction. */
4386
+ commitHandoff(botId, entries2) {
4387
+ transaction(this.db, () => {
4388
+ this.chats.channels.clearNotesSeen(botId);
4389
+ if (entries2.length) this.write(entries2);
4390
+ });
4391
+ }
4376
4392
  /** A deleted member's rows go with it. */
4377
4393
  forget(memberId) {
4378
4394
  this.db.prepare("DELETE FROM inbox WHERE member_id=?").run(memberId);
@@ -5203,12 +5219,20 @@ var ChatRepository = class {
5203
5219
  ON CONFLICT(chat_id,member_id) DO UPDATE SET read_sequence=MAX(read_sequence,excluded.read_sequence)`).run(chatId, memberId, sequence);
5204
5220
  }
5205
5221
  /** Moves a pending question to its final state; false when it was already settled. */
5206
- settleQuestion(messageId, state, answer) {
5222
+ settleQuestion(messageId, state, answer, expiredReason) {
5223
+ if (expiredReason) {
5224
+ return Number(this.db.prepare(`UPDATE messages SET question=json_set(question,'$.state',?,'$.answer',json(?),'$.settledAt',?,'$.expiredReason',?)
5225
+ WHERE id=? AND json_extract(question,'$.state')='pending'`).run(state, JSON.stringify(answer), Date.now(), expiredReason, messageId).changes) > 0;
5226
+ }
5207
5227
  return Number(this.db.prepare(`UPDATE messages SET question=json_set(question,'$.state',?,'$.answer',json(?),'$.settledAt',?)
5208
5228
  WHERE id=? AND json_extract(question,'$.state')='pending'`).run(state, JSON.stringify(answer), Date.now(), messageId).changes) > 0;
5209
5229
  }
5210
5230
  /** Invalidates a question card (even if just answered) when post-confirmation authorization checks fail. */
5211
- invalidateQuestion(messageId) {
5231
+ invalidateQuestion(messageId, expiredReason) {
5232
+ if (expiredReason) {
5233
+ return Number(this.db.prepare(`UPDATE messages SET question=json_set(question,'$.state','ignored','$.answer',json('null'),'$.settledAt',?,'$.expiredReason',?)
5234
+ WHERE id=? AND question IS NOT NULL`).run(Date.now(), expiredReason, messageId).changes) > 0;
5235
+ }
5212
5236
  return Number(this.db.prepare(`UPDATE messages SET question=json_set(question,'$.state','ignored','$.answer',json('null'),'$.settledAt',?)
5213
5237
  WHERE id=? AND question IS NOT NULL`).run(Date.now(), messageId).changes) > 0;
5214
5238
  }
@@ -6044,39 +6068,26 @@ var PortRepository = class {
6044
6068
  };
6045
6069
 
6046
6070
  // src/server/infra/storage/connector-repository.ts
6047
- import { createHash as createHash8, randomUUID as randomUUID17 } from "node:crypto";
6071
+ import { createHash as createHash7, randomUUID as randomUUID17 } from "node:crypto";
6048
6072
 
6049
6073
  // src/server/shared/connector.ts
6050
- import { createHash as createHash7 } from "node:crypto";
6051
6074
  var CONNECTOR_SLUG = /^[a-z][a-z0-9_-]{0,47}$/;
6052
6075
  function isWriteTool(tool2) {
6053
6076
  return !(tool2.readOnly === true && tool2.destructive !== true);
6054
6077
  }
6055
- function canonical(value2) {
6056
- if (Array.isArray(value2)) return value2.map(canonical);
6057
- if (value2 && typeof value2 === "object") {
6058
- const out = {};
6059
- for (const key of Object.keys(value2).sort()) {
6060
- const next = value2[key];
6061
- if (next !== void 0) out[key] = canonical(next);
6062
- }
6063
- return out;
6064
- }
6065
- return value2;
6066
- }
6067
- function toolDefinitionHash(tool2) {
6068
- const payload = canonical({
6069
- name: tool2.name,
6070
- title: tool2.title ?? null,
6071
- description: tool2.description ?? null,
6072
- readOnly: tool2.readOnly ?? null,
6073
- destructive: tool2.destructive ?? null,
6074
- inputSchema: tool2.inputSchema ?? {}
6075
- });
6076
- return createHash7("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 32);
6077
- }
6078
6078
 
6079
6079
  // src/server/infra/storage/connector-repository.ts
6080
+ function hashCredentials(authType, creds) {
6081
+ const headerEntries = Object.entries(creds.headers ?? {}).sort(([a], [b]) => a.localeCompare(b));
6082
+ const tokenKey = creds.oauth?.tokens?.refresh_token || creds.oauth?.tokens?.access_token || "";
6083
+ return createHash7("sha256").update(JSON.stringify({
6084
+ authType,
6085
+ headers: headerEntries,
6086
+ clientId: creds.clientId ?? "",
6087
+ oauthClientId: creds.oauth?.clientInformation?.client_id ?? "",
6088
+ tokenKey
6089
+ })).digest("hex");
6090
+ }
6080
6091
  var ConnectorRepository = class {
6081
6092
  constructor(db, cipher, ownerId) {
6082
6093
  this.db = db;
@@ -6099,27 +6110,32 @@ var ConnectorRepository = class {
6099
6110
  const config = this.parseJson(row2.config_json, {});
6100
6111
  const rawTools = this.parseJson(row2.tools_json, []);
6101
6112
  const tools = Array.isArray(rawTools) ? rawTools.map((tool2) => ({ ...tool2, write: isWriteTool(tool2) })) : [];
6102
- const credRow = this.db.prepare("SELECT credential_json AS json FROM connector_credentials WHERE connector_id=?").get(row2.id);
6113
+ const credRow = this.db.prepare("SELECT auth_type AS authType, credential_json AS json FROM connector_credentials WHERE connector_id=?").get(row2.id);
6103
6114
  let readable = true;
6104
6115
  let headerNames = [];
6105
6116
  let oauthClientId = null;
6106
6117
  let hasClientSecret = false;
6118
+ let credFp = "none";
6107
6119
  if (credRow) {
6108
6120
  const plain2 = this.cipher.open(credRow.json, `connector:${row2.id}`);
6109
6121
  if (plain2 === null) {
6110
6122
  readable = false;
6123
+ credFp = "unreadable";
6111
6124
  } else {
6112
6125
  const creds = this.parseJson(plain2, {});
6113
6126
  headerNames = Object.keys(creds.headers ?? {}).sort();
6114
6127
  oauthClientId = creds.clientId ?? null;
6115
6128
  hasClientSecret = Boolean(creds.clientSecret);
6129
+ credFp = hashCredentials(credRow.authType, creds).slice(0, 16);
6116
6130
  }
6117
6131
  }
6118
- const grants = this.db.prepare("SELECT bot_id AS botId, granted_at AS grantedAt FROM connector_grants WHERE connector_id=? ORDER BY granted_at ASC").all(row2.id).map((grant) => ({ ...grant }));
6132
+ const grants = this.db.prepare(`SELECT bot_id AS botId, scope, granted_at AS grantedAt FROM connector_grants g
6133
+ WHERE connector_id=? AND (scope='always' OR EXISTS(SELECT 1 FROM bot_runs r WHERE r.id=g.run_id AND r.ended_at IS NULL))
6134
+ ORDER BY granted_at ASC`).all(row2.id).map((grant) => ({ ...grant }));
6119
6135
  const stats = this.db.prepare("SELECT COUNT(*) AS count, MAX(at) AS lastAt FROM connector_uses WHERE connector_id=?").get(row2.id);
6120
6136
  const managedClient = this.runtime?.managedClient(row2.provider) ?? null;
6121
6137
  const authMethods = this.runtime?.authMethods(row2.provider) ?? ["oauth", "headers", "none"];
6122
- const unconfirmed = this.activeUnconfirmed(row2.id, tools);
6138
+ const account = config.accountLabel || (row2.status === "connected" ? row2.status_detail : "");
6123
6139
  return {
6124
6140
  id: row2.id,
6125
6141
  slug: row2.slug,
@@ -6133,10 +6149,11 @@ var ConnectorRepository = class {
6133
6149
  oauthClientId: managedClient ? null : oauthClientId,
6134
6150
  hasClientSecret: managedClient ? false : hasClientSecret,
6135
6151
  managedClient,
6136
- unconfirmed,
6137
6152
  enabled: row2.enabled === 1,
6138
6153
  status: row2.status,
6139
6154
  statusDetail: row2.status_detail,
6155
+ account,
6156
+ credFp,
6140
6157
  readable,
6141
6158
  tools,
6142
6159
  grants,
@@ -6146,20 +6163,8 @@ var ConnectorRepository = class {
6146
6163
  updatedAt: row2.updated_at
6147
6164
  };
6148
6165
  }
6149
- /** Only approvals whose stored definition hash still matches the current tool definition remain active (A102). */
6150
- activeUnconfirmed(id, tools) {
6151
- const rows3 = this.db.prepare("SELECT tool_name AS name, definition_hash AS hash FROM connector_unconfirmed_tools WHERE connector_id=? ORDER BY tool_name").all(id);
6152
- if (!rows3.length) return [];
6153
- const byName = new Map(tools.map((tool2) => [tool2.name, tool2]));
6154
- const active = [];
6155
- for (const row2 of rows3) {
6156
- const tool2 = byName.get(row2.name);
6157
- if (!tool2 || !isWriteTool(tool2)) continue;
6158
- if (row2.hash && row2.hash === toolDefinitionHash(tool2)) active.push(row2.name);
6159
- }
6160
- return active;
6161
- }
6162
6166
  list() {
6167
+ this.purge();
6163
6168
  const rows3 = this.db.prepare("SELECT * FROM connectors WHERE owner_id=? ORDER BY created_at ASC").all(this.ownerId());
6164
6169
  return rows3.map((row2) => this.toView(row2));
6165
6170
  }
@@ -6174,7 +6179,8 @@ var ConnectorRepository = class {
6174
6179
  create(input) {
6175
6180
  const id = randomUUID17();
6176
6181
  const now = Date.now();
6177
- const config = { url: input.url, authKind: input.authKind };
6182
+ const label = input.accountLabel?.trim() || (input.status === "connected" ? input.statusDetail?.trim() : "") || "";
6183
+ const config = { url: input.url, authKind: input.authKind, ...label ? { accountLabel: label } : {} };
6178
6184
  transaction(this.db, () => {
6179
6185
  this.db.prepare(`INSERT INTO connectors(id,owner_id,slug,name,kind,provider,config_json,enabled,status,status_detail,tools_json,created_at,updated_at)
6180
6186
  VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(
@@ -6205,6 +6211,9 @@ var ConnectorRepository = class {
6205
6211
  const config = this.parseJson(row2.config_json, {});
6206
6212
  if (patch.url !== void 0) config.url = patch.url;
6207
6213
  if (patch.authKind !== void 0) config.authKind = patch.authKind;
6214
+ if (patch.accountLabel === null) delete config.accountLabel;
6215
+ else if (patch.accountLabel !== void 0 && patch.accountLabel.trim()) config.accountLabel = patch.accountLabel.trim();
6216
+ else if (patch.status === "connected" && patch.statusDetail?.trim()) config.accountLabel = patch.statusDetail.trim();
6208
6217
  const sets = ["config_json=?", "updated_at=?"];
6209
6218
  const params = [JSON.stringify(config), Date.now()];
6210
6219
  if (patch.name !== void 0) {
@@ -6231,29 +6240,6 @@ var ConnectorRepository = class {
6231
6240
  this.db.prepare(`UPDATE connectors SET ${sets.join(", ")} WHERE id=? AND owner_id=?`).run(...params);
6232
6241
  return this.get(id);
6233
6242
  }
6234
- /** Replaces the set of write tools that bypass confirmation, binding each to its current definition hash. */
6235
- setUnconfirmed(id, entries2) {
6236
- transaction(this.db, () => {
6237
- this.db.prepare("DELETE FROM connector_unconfirmed_tools WHERE connector_id=?").run(id);
6238
- const insert = this.db.prepare("INSERT INTO connector_unconfirmed_tools(connector_id,tool_name,definition_hash) VALUES(?,?,?)");
6239
- const seen = /* @__PURE__ */ new Set();
6240
- for (const entry of entries2) {
6241
- if (seen.has(entry.name)) continue;
6242
- seen.add(entry.name);
6243
- insert.run(id, entry.name, entry.hash);
6244
- }
6245
- });
6246
- }
6247
- /** Grants "don't ask again" for one write tool, fingerprinted by its current definition hash. */
6248
- allowUnconfirmed(id, toolName, hash) {
6249
- this.db.prepare(`INSERT INTO connector_unconfirmed_tools(connector_id,tool_name,definition_hash) VALUES(?,?,?)
6250
- ON CONFLICT(connector_id,tool_name) DO UPDATE SET definition_hash=excluded.definition_hash`).run(id, toolName, hash);
6251
- }
6252
- /** Checks whether a write tool's approval is present AND still matches its current definition hash. */
6253
- isUnconfirmed(id, tool2) {
6254
- const row2 = this.db.prepare("SELECT definition_hash AS hash FROM connector_unconfirmed_tools WHERE connector_id=? AND tool_name=?").get(id, tool2.name);
6255
- return Boolean(row2 && row2.hash && row2.hash === toolDefinitionHash(tool2));
6256
- }
6257
6243
  delete(id) {
6258
6244
  return Number(this.db.prepare("DELETE FROM connectors WHERE id=? AND owner_id=?").run(id, this.ownerId()).changes) > 0;
6259
6245
  }
@@ -6270,32 +6256,43 @@ var ConnectorRepository = class {
6270
6256
  if (!row2) return "none";
6271
6257
  const plain2 = this.cipher.open(row2.json, `connector:${id}`);
6272
6258
  if (plain2 === null) return "unreadable";
6273
- const creds = this.parseJson(plain2, {});
6274
- const headerEntries = Object.entries(creds.headers ?? {}).sort(([a], [b]) => a.localeCompare(b));
6275
- const tokenKey = creds.oauth?.tokens?.refresh_token || creds.oauth?.tokens?.access_token || "";
6276
- return createHash8("sha256").update(JSON.stringify({
6277
- authType: row2.authType,
6278
- headers: headerEntries,
6279
- clientId: creds.clientId ?? "",
6280
- oauthClientId: creds.oauth?.clientInformation?.client_id ?? "",
6281
- tokenKey
6282
- })).digest("hex");
6259
+ return hashCredentials(row2.authType, this.parseJson(plain2, {}));
6283
6260
  }
6284
6261
  saveCredentials(id, authKind, credentials) {
6285
6262
  const sealed = this.cipher.seal(JSON.stringify(credentials), `connector:${id}`);
6286
6263
  this.db.prepare(`INSERT INTO connector_credentials(connector_id,auth_type,credential_json,updated_at) VALUES(?,?,?,?)
6287
6264
  ON CONFLICT(connector_id) DO UPDATE SET auth_type=excluded.auth_type, credential_json=excluded.credential_json, updated_at=excluded.updated_at`).run(id, authKind, sealed, Date.now());
6288
6265
  }
6289
- grant(id, botId) {
6290
- this.db.prepare(`INSERT INTO connector_grants(connector_id,bot_id,granted_by,granted_at) VALUES(?,?,?,?)
6291
- ON CONFLICT(connector_id,bot_id) DO NOTHING`).run(id, botId, this.ownerId(), Date.now());
6266
+ grant(id, botId, scope = "always", runId = null) {
6267
+ this.db.prepare(`INSERT INTO connector_grants(connector_id,bot_id,scope,run_id,granted_by,granted_at) VALUES(?,?,?,?,?,?)
6268
+ ON CONFLICT(connector_id,bot_id) DO UPDATE SET scope=excluded.scope, run_id=excluded.run_id, granted_at=excluded.granted_at`).run(id, botId, scope, runId, this.ownerId(), Date.now());
6292
6269
  }
6293
6270
  revoke(id, botId) {
6294
6271
  return Number(this.db.prepare("DELETE FROM connector_grants WHERE connector_id=? AND bot_id=?").run(id, botId).changes) > 0;
6295
6272
  }
6273
+ revokeAll(id) {
6274
+ this.db.prepare("DELETE FROM connector_grants WHERE connector_id=?").run(id);
6275
+ }
6276
+ /** Active grants for one Bot: permanent grants plus "this time only" grants whose run is still live. */
6277
+ grantedTo(botId) {
6278
+ const rows3 = this.db.prepare(`SELECT g.connector_id AS id, g.scope FROM connector_grants g JOIN connectors c ON c.id=g.connector_id
6279
+ WHERE g.bot_id=? AND c.owner_id=? AND (g.scope='always' OR EXISTS(SELECT 1 FROM bot_runs r WHERE r.id=g.run_id AND r.ended_at IS NULL))`).all(botId, this.ownerId());
6280
+ return new Map(rows3.map((row2) => [row2.id, row2.scope]));
6281
+ }
6296
6282
  grantedIds(botId) {
6297
- const rows3 = this.db.prepare("SELECT g.connector_id AS id FROM connector_grants g JOIN connectors c ON c.id=g.connector_id WHERE g.bot_id=? AND c.owner_id=?").all(botId, this.ownerId());
6298
- return new Set(rows3.map((row2) => row2.id));
6283
+ return new Set(this.grantedTo(botId).keys());
6284
+ }
6285
+ /** The Bot's run in progress, which a "this time only" grant lasts for. */
6286
+ currentRun(botId) {
6287
+ return this.db.prepare("SELECT id FROM bot_runs WHERE bot_id=? AND ended_at IS NULL ORDER BY created_at DESC LIMIT 1").get(botId)?.id ?? null;
6288
+ }
6289
+ /** Checks whether a specific captured run ID for this Bot is still live (never falls back to a later run). */
6290
+ isRunLive(runId, botId) {
6291
+ return Boolean(this.db.prepare("SELECT 1 FROM bot_runs WHERE id=? AND bot_id=? AND ended_at IS NULL").get(runId, botId));
6292
+ }
6293
+ /** Removes expired "this time only" grants whose run has ended. */
6294
+ purge() {
6295
+ this.db.prepare("DELETE FROM connector_grants WHERE scope='once' AND NOT EXISTS(SELECT 1 FROM bot_runs r WHERE r.id=connector_grants.run_id AND r.ended_at IS NULL)").run();
6299
6296
  }
6300
6297
  recordUse(use) {
6301
6298
  this.db.prepare("INSERT INTO connector_uses(connector_id,connector_slug,bot_id,at,tool_name,outcome,detail) VALUES(?,?,?,?,?,?,?)").run(use.connectorId, use.slug, use.botId, Date.now(), use.toolName, use.outcome, use.detail.slice(0, 500));
@@ -6423,7 +6420,7 @@ import { hostname, networkInterfaces as networkInterfaces2 } from "node:os";
6423
6420
  import { join as join7 } from "node:path";
6424
6421
 
6425
6422
  // src/server/infra/tls/x509.ts
6426
- import { createHash as createHash9, createPrivateKey, generateKeyPairSync, randomBytes as randomBytes6, sign, X509Certificate } from "node:crypto";
6423
+ import { createHash as createHash8, createPrivateKey, generateKeyPairSync, randomBytes as randomBytes6, sign, X509Certificate } from "node:crypto";
6427
6424
  import { isIPv4, isIPv6 } from "node:net";
6428
6425
  var tlv = (tag, content2) => {
6429
6426
  const n = content2.length;
@@ -6458,7 +6455,7 @@ function time(date) {
6458
6455
  var ECDSA_SHA256 = seq(oid("1.2.840.10045.4.3.2"));
6459
6456
  var name = (common) => seq(set(seq(oid("2.5.4.10"), utf8("Jarvy"))), set(seq(oid("2.5.4.3"), utf8(common))));
6460
6457
  var extension = (id, value2, critical = false) => seq(oid(id), ...critical ? [TRUE] : [], octets(value2));
6461
- var keyId = (key) => createHash9("sha1").update(key.export({ type: "spki", format: "der" })).digest();
6458
+ var keyId = (key) => createHash8("sha1").update(key.export({ type: "spki", format: "der" })).digest();
6462
6459
  function ipBytes(address2) {
6463
6460
  if (isIPv4(address2)) return Buffer.from(address2.split(".").map(Number));
6464
6461
  if (!isIPv6(address2) || address2.includes(".")) return null;
@@ -6539,7 +6536,7 @@ function coveredNames(host) {
6539
6536
  const machine = hostname().toLowerCase(), label = /^[a-z0-9-]+$/.test(machine) ? [machine, `${machine}.local`] : [];
6540
6537
  return [.../* @__PURE__ */ new Set([...label, "localhost", "127.0.0.1", "::1", ...reachable(), ...host === "0.0.0.0" || host === "::" ? [] : [host]])];
6541
6538
  }
6542
- var canonical2 = (entry) => ipBytes(entry)?.toString("hex") ?? entry.toLowerCase();
6539
+ var canonical = (entry) => ipBytes(entry)?.toString("hex") ?? entry.toLowerCase();
6543
6540
  function read3(dir, file) {
6544
6541
  const path = join7(dir, file);
6545
6542
  return existsSync2(path) ? readFileSync2(path, "utf8") : null;
@@ -6576,9 +6573,9 @@ function certificates(dataDir, host, cipher, log = console.log) {
6576
6573
  const key = readKey(dir, "server-key", cipher, log), cert = read3(dir, "server.pem");
6577
6574
  if (key && cert) {
6578
6575
  const parsed = new X509Certificate2(cert);
6579
- const covers = new Set((parsed.subjectAltName ?? "").split(", ").map((entry) => canonical2(entry.replace(/^(DNS|IP Address):/, ""))));
6576
+ const covers = new Set((parsed.subjectAltName ?? "").split(", ").map((entry) => canonical(entry.replace(/^(DNS|IP Address):/, ""))));
6580
6577
  const fresh = parsed.validToDate.getTime() - Date.now() > RENEW_MS && parsed.checkIssued(new X509Certificate2(root.certPem));
6581
- if (fresh && names.every((entry) => covers.has(canonical2(entry)))) server = { keyPem: key, certPem: cert };
6578
+ if (fresh && names.every((entry) => covers.has(canonical(entry)))) server = { keyPem: key, certPem: cert };
6582
6579
  }
6583
6580
  } else {
6584
6581
  root = makeRoot(hostname());
@@ -7566,7 +7563,7 @@ var User = class extends Member {
7566
7563
  };
7567
7564
 
7568
7565
  // src/server/application.ts
7569
- import { createHash as createHash17 } from "node:crypto";
7566
+ import { createHash as createHash16 } from "node:crypto";
7570
7567
  import { mkdir as mkdir9, realpath } from "node:fs/promises";
7571
7568
  import { join as join23, resolve as resolve3 } from "node:path";
7572
7569
  import lockfile from "proper-lockfile";
@@ -7634,11 +7631,13 @@ var POLICY = {
7634
7631
  // A task that is due wakes its Bot but never interrupts it, and is not steered into a running turn: it waits for
7635
7632
  // the turn to end (A58).
7636
7633
  task: { schedule: "queue" },
7637
- // After a compaction, the open threads a Bot follows ride along with its next batch, without waking it (A73).
7638
- followed: { compaction: "digest" },
7634
+ // After a compaction or context handoff, the open threads a Bot follows ride along with its next batch, without waking it (A73, A99).
7635
+ followed: { compaction: "digest", handoff: "digest" },
7639
7636
  // A background bash command finished: steers into a running turn or wakes an idle Bot, never interrupts (A98).
7640
7637
  // One stopped by server shutdown rides along as a digest on the Bot's next batch without waking it.
7641
- job: { finish: "queue", shutdown: "digest" }
7638
+ job: { finish: "queue", shutdown: "digest" },
7639
+ // Context handoff continuation (A99): wakes the fresh context stage immediately without waiting for user input.
7640
+ handoff: { continue: "queue" }
7642
7641
  };
7643
7642
  function urgencyOf(kind, reason) {
7644
7643
  return POLICY[kind][reason];
@@ -7827,7 +7826,7 @@ var ChatMembers = class {
7827
7826
  };
7828
7827
 
7829
7828
  // src/server/service/chat/messages.ts
7830
- import { createHash as createHash10 } from "node:crypto";
7829
+ import { createHash as createHash9 } from "node:crypto";
7831
7830
  var ChatMessages = class {
7832
7831
  constructor(id, actor, repository, attachments) {
7833
7832
  this.id = id;
@@ -7842,7 +7841,7 @@ var ChatMessages = class {
7842
7841
  if (message.alsoToChannel) payload.push("alsoToChannel");
7843
7842
  if (message.replyTo) payload.push({ replyTo: message.replyTo });
7844
7843
  if (message.quotes?.length) payload.push({ quotes: message.quotes });
7845
- const hash = createHash10("sha256").update(JSON.stringify(payload)).digest("hex");
7844
+ const hash = createHash9("sha256").update(JSON.stringify(payload)).digest("hex");
7846
7845
  const files = message.files ?? [];
7847
7846
  await this.attachments.commit(files);
7848
7847
  let saved;
@@ -7930,10 +7929,9 @@ function enterAsk(value2) {
7930
7929
  };
7931
7930
  }
7932
7931
  var CONNECTOR_PROVIDERS = /* @__PURE__ */ new Set(["github", "gmail", "linear", "custom_mcp"]);
7933
- var CONNECTOR_AUTH_KINDS = /* @__PURE__ */ new Set(["none", "headers", "oauth"]);
7934
7932
  function connectorAuthAsk(value2) {
7935
7933
  const ask = value2;
7936
- if (!ask || typeof ask !== "object" || !text2(ask.connectorId, 80) || !text2(ask.slug, 64) || !text2(ask.name, 80) || typeof ask.provider !== "string" || !CONNECTOR_PROVIDERS.has(ask.provider) || !text2(ask.purpose, 300) || typeof ask.authKind !== "string" || !CONNECTOR_AUTH_KINDS.has(ask.authKind) || typeof ask.needsGrant !== "boolean" || typeof ask.needsAuth !== "boolean")
7934
+ if (!ask || typeof ask !== "object" || !text2(ask.connectorId, 80) || !text2(ask.slug, 64) || !text2(ask.name, 80) || typeof ask.provider !== "string" || !CONNECTOR_PROVIDERS.has(ask.provider) || !text2(ask.purpose, 300) || ask.account !== void 0 && !text2(ask.account, 120) || ask.credFp !== void 0 && !text2(ask.credFp, 64) || ask.runId !== void 0 && !text2(ask.runId, 80))
7937
7935
  throw new ChatError(400, "Invalid connector auth request");
7938
7936
  return {
7939
7937
  connectorId: ask.connectorId.trim(),
@@ -7941,9 +7939,9 @@ function connectorAuthAsk(value2) {
7941
7939
  name: ask.name.trim(),
7942
7940
  provider: ask.provider,
7943
7941
  purpose: ask.purpose.trim(),
7944
- authKind: ask.authKind,
7945
- needsGrant: ask.needsGrant,
7946
- needsAuth: ask.needsAuth
7942
+ ...ask.account !== void 0 ? { account: ask.account.trim() } : {},
7943
+ ...ask.credFp !== void 0 ? { credFp: ask.credFp.trim() } : {},
7944
+ ...ask.runId !== void 0 ? { runId: ask.runId.trim() } : {}
7947
7945
  };
7948
7946
  }
7949
7947
  function connectorWriteAsk(value2) {
@@ -8011,6 +8009,7 @@ var ChatQuestions = class {
8011
8009
  if (question.state === "answered") return Promise.resolve(resultOf(question, question.answer));
8012
8010
  if (question.state === "dismissed") return Promise.resolve({ status: "dismissed" });
8013
8011
  if (question.state === "ignored") return Promise.reject(new ChatError(409, "The question is no longer waiting for an answer", "question_expired"));
8012
+ const connectorId = question.connectorAuth?.connectorId ?? question.connectorWrite?.connectorId;
8014
8013
  return new Promise((resolve5, reject) => {
8015
8014
  const stop = () => {
8016
8015
  this.waiting.delete(message.id);
@@ -8022,9 +8021,18 @@ var ChatQuestions = class {
8022
8021
  return;
8023
8022
  }
8024
8023
  signal?.addEventListener("abort", stop, { once: true });
8025
- this.waiting.set(message.id, (result) => {
8026
- signal?.removeEventListener("abort", stop);
8027
- resolve5(result);
8024
+ this.waiting.set(message.id, {
8025
+ chatId: message.chatId,
8026
+ botId: message.sender.id,
8027
+ ...connectorId ? { connectorId } : {},
8028
+ resolve: (result) => {
8029
+ signal?.removeEventListener("abort", stop);
8030
+ resolve5(result);
8031
+ },
8032
+ reject: (error) => {
8033
+ signal?.removeEventListener("abort", stop);
8034
+ reject(error);
8035
+ }
8028
8036
  });
8029
8037
  });
8030
8038
  }
@@ -8032,12 +8040,29 @@ var ChatQuestions = class {
8032
8040
  waitingFor(messageId) {
8033
8041
  return this.waiting.has(messageId);
8034
8042
  }
8035
- /** Marks a card expired/ignored if post-confirmation authorization checks fail before dispatch. */
8036
- invalidate(chatId, messageId) {
8043
+ /** Expires a pending card AND wakes the waiting caller with question_expired so the Bot can recover cleanly. */
8044
+ expire(chatId, messageId, reason = "The question is no longer waiting for an answer", expiredReason) {
8045
+ const waiter = this.waiting.get(messageId);
8037
8046
  this.waiting.delete(messageId);
8038
- if (this.repository.invalidateQuestion(messageId)) this.changed(chatId, messageId);
8047
+ if (this.repository.settleQuestion(messageId, "ignored", null, expiredReason)) this.changed(chatId, messageId);
8048
+ waiter?.reject(new ChatError(409, reason, "question_expired"));
8049
+ }
8050
+ /** Expires every live pending card bound to a connector (optionally scoped to one Bot on grant revocation). */
8051
+ expireByConnector(connectorId, reason, expiredReason, botId) {
8052
+ for (const [messageId, entry] of [...this.waiting.entries()]) {
8053
+ if (entry.connectorId !== connectorId) continue;
8054
+ if (botId && entry.botId !== botId) continue;
8055
+ this.expire(entry.chatId, messageId, reason, expiredReason);
8056
+ }
8039
8057
  }
8040
- respond(actorId, chatId, messageId, input) {
8058
+ /** Marks a card ignored after it was already answered if post-confirmation authorization checks fail before dispatch. */
8059
+ invalidate(chatId, messageId, expiredReason) {
8060
+ const waiter = this.waiting.get(messageId);
8061
+ this.waiting.delete(messageId);
8062
+ if (this.repository.invalidateQuestion(messageId, expiredReason)) this.changed(chatId, messageId);
8063
+ waiter?.reject(new ChatError(409, "The question is no longer waiting for an answer", "question_expired"));
8064
+ }
8065
+ respond(actorId, chatId, messageId, input, onSettled) {
8041
8066
  const message = this.repository.message(actorId, messageId);
8042
8067
  if (!message || message.chatId !== chatId || !message.question) throw new ChatError(404, "Question not found");
8043
8068
  this.repository.assertAccess(actorId, chatId, true);
@@ -8052,8 +8077,9 @@ var ChatQuestions = class {
8052
8077
  if (!dismissed && input.action !== "answer") throw new ChatError(400, "Invalid question action");
8053
8078
  const answer = dismissed ? null : answerOf(question, input);
8054
8079
  if (!this.repository.settleQuestion(messageId, dismissed ? "dismissed" : "answered", answer)) throw new ChatError(409, "The question is already settled", "question_closed");
8080
+ onSettled?.();
8055
8081
  this.waiting.delete(messageId);
8056
- waiter(answer ? resultOf(question, answer) : { status: "dismissed" });
8082
+ waiter.resolve(answer ? resultOf(question, answer) : { status: "dismissed" });
8057
8083
  this.changed(chatId, messageId);
8058
8084
  return this.repository.message(actorId, messageId);
8059
8085
  }
@@ -9737,6 +9763,15 @@ var PiSession = class _PiSession {
9737
9763
  adapter.session.dispose();
9738
9764
  throw new RuntimeFault("tools_missing", "Couldn't load the run's tools.");
9739
9765
  }
9766
+ if (options.shouldEndTurn) {
9767
+ const innerFinishTurn = adapter.session.agent.finishTurn;
9768
+ adapter.session.agent.finishTurn = async (turn, signal) => {
9769
+ const decision = await innerFinishTurn?.(turn, signal);
9770
+ if (decision && decision.action === "end") return decision;
9771
+ if (options.shouldEndTurn?.()) return { action: "end" };
9772
+ return decision ?? void 0;
9773
+ };
9774
+ }
9740
9775
  adapter.unsubscribe = adapter.session.subscribe((event) => adapter.onEvent(event));
9741
9776
  if (options.onHistory) {
9742
9777
  const history = new PiHistoryAdapter(sessionManager.getHeader());
@@ -9892,6 +9927,10 @@ var PiSession = class _PiSession {
9892
9927
  promptTold(change) {
9893
9928
  this.prompts.sent(change);
9894
9929
  }
9930
+ handoff(summary, tokensBefore) {
9931
+ this.session.sessionManager.appendCompaction(summary, null, tokensBefore, { handoff: true }, true);
9932
+ this.prompts.take(this.options.systemPrompt);
9933
+ }
9895
9934
  async dispose() {
9896
9935
  this.requestAbort();
9897
9936
  await this.abortTask;
@@ -9904,7 +9943,7 @@ var PiSession = class _PiSession {
9904
9943
 
9905
9944
  // src/server/infra/env/docker.ts
9906
9945
  import { execFile, spawn } from "node:child_process";
9907
- import { createHash as createHash11 } from "node:crypto";
9946
+ import { createHash as createHash10 } from "node:crypto";
9908
9947
  import { createWriteStream } from "node:fs";
9909
9948
  import { mkdir as mkdir4, mkdtemp, readFile as readFile2, rename as rename4, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
9910
9949
  import { tmpdir } from "node:os";
@@ -10025,7 +10064,7 @@ function dockerProblem() {
10025
10064
  }));
10026
10065
  }
10027
10066
  function computerImage(uid, gid) {
10028
- return `jarvy-computer:${createHash11("sha256").update(`${COMPUTER_DOCKERFILE}
10067
+ return `jarvy-computer:${createHash10("sha256").update(`${COMPUTER_DOCKERFILE}
10029
10068
  ${uid}:${gid}`).digest("hex").slice(0, 12)}`;
10030
10069
  }
10031
10070
  var computerRecipe = (uid, gid) => ({ dockerfile: COMPUTER_DOCKERFILE, args: { UID: String(uid), GID: String(gid) } });
@@ -10247,7 +10286,7 @@ function loopbackAddress(hex) {
10247
10286
  var OWN_SANDBOX = "your sandbox";
10248
10287
 
10249
10288
  // src/server/service/bot/computers.ts
10250
- import { createHash as createHash13 } from "node:crypto";
10289
+ import { createHash as createHash12 } from "node:crypto";
10251
10290
  import { dirname as dirname7, join as join15 } from "node:path";
10252
10291
  import { userInfo } from "node:os";
10253
10292
 
@@ -10452,8 +10491,16 @@ async function ensureIsolationFilter(name3, gateway2) {
10452
10491
  const subnet = gateway2.replace(/\.\d+$/, ".0");
10453
10492
  const filters = await virsh(["nwfilter-list"], 15e3);
10454
10493
  const hasCleanTraffic = /\bclean-traffic\b/.test(filters);
10494
+ let existingUuid = null;
10495
+ try {
10496
+ const current = await virsh(["nwfilter-dumpxml", name3], 15e3);
10497
+ existingUuid = /<uuid>([^<]+)<\/uuid>/.exec(current)?.[1]?.trim() ?? null;
10498
+ } catch (error) {
10499
+ if (!/network filter not found|nwfilter not found|no nwfilter/i.test(error.message)) throw error;
10500
+ }
10455
10501
  const xml2 = [
10456
10502
  `<filter name='${xmlEscape(name3)}' chain='root'>`,
10503
+ ...existingUuid ? [` <uuid>${xmlEscape(existingUuid)}</uuid>`] : [],
10457
10504
  ...hasCleanTraffic ? [" <filterref filter='clean-traffic'/>"] : [],
10458
10505
  " <rule action='accept' direction='out' priority='400'>",
10459
10506
  ` <ip dstipaddr='${gateway2}' dstipmask='32'/>`,
@@ -10942,7 +10989,7 @@ var quote = (text7) => `'${text7.replaceAll("'", "'\\''")}'`;
10942
10989
 
10943
10990
  // src/server/infra/env/vm-template.ts
10944
10991
  import { spawn as spawn3 } from "node:child_process";
10945
- import { createHash as createHash12 } from "node:crypto";
10992
+ import { createHash as createHash11 } from "node:crypto";
10946
10993
  import { createWriteStream as createWriteStream2 } from "node:fs";
10947
10994
  import { mkdir as mkdir6, mkdtemp as mkdtemp4, rm as rm6, writeFile as writeFile4 } from "node:fs/promises";
10948
10995
  import { tmpdir as tmpdir3 } from "node:os";
@@ -11010,10 +11057,10 @@ var TEMPLATE_CLEANUP = [
11010
11057
  "sync"
11011
11058
  ].join(" && ");
11012
11059
  function vmTemplateVolume() {
11013
- return `base-${createHash12("sha256").update(TEMPLATE_PROVISION).digest("hex").slice(0, 12)}.qcow2`;
11060
+ return `base-${createHash11("sha256").update(TEMPLATE_PROVISION).digest("hex").slice(0, 12)}.qcow2`;
11014
11061
  }
11015
11062
  function vmTemplateTag() {
11016
- return `ubuntu-24.04:${createHash12("sha256").update(TEMPLATE_PROVISION).digest("hex").slice(0, 12)}`;
11063
+ return `ubuntu-24.04:${createHash11("sha256").update(TEMPLATE_PROVISION).digest("hex").slice(0, 12)}`;
11017
11064
  }
11018
11065
  async function makeSeedIso(isoPath, userData, metaData) {
11019
11066
  const dir = await mkdtemp4(join12(tmpdir3(), "jarvy-seed-"));
@@ -11036,7 +11083,7 @@ async function buildVmTemplate(pool, network, runtimeDir, logFile, log) {
11036
11083
  stream.write(chunk);
11037
11084
  };
11038
11085
  const work = await mkdtemp4(join12(tmpdir3(), "jarvy-vm-build-"));
11039
- const buildId = createHash12("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0, 8);
11086
+ const buildId = createHash11("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0, 8);
11040
11087
  const builderName = `${network.name}-build-${buildId}`;
11041
11088
  const buildDiskVol = `build-${buildId}.qcow2`, buildSeedVol = `build-${buildId}-seed.iso`;
11042
11089
  try {
@@ -11632,7 +11679,7 @@ var Computers = class {
11632
11679
  constructor(deps) {
11633
11680
  this.deps = deps;
11634
11681
  this.dataDir = dirname7(deps.store.path);
11635
- this.tag = createHash13("sha256").update(this.dataDir).digest("hex").slice(0, 12);
11682
+ this.tag = createHash12("sha256").update(this.dataDir).digest("hex").slice(0, 12);
11636
11683
  const log = (text7) => this.log(text7);
11637
11684
  this.images = new ComputerImages(this.dataDir, this.uid, this.gid, log);
11638
11685
  this.vms = new VmSupportCheck(log);
@@ -12709,7 +12756,7 @@ import { fileURLToPath } from "node:url";
12709
12756
  import { randomBytes as randomBytes9 } from "node:crypto";
12710
12757
 
12711
12758
  // src/server/infra/env/device-link.ts
12712
- import { createHash as createHash14, randomBytes as randomBytes8, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
12759
+ import { createHash as createHash13, randomBytes as randomBytes8, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
12713
12760
  import { mkdtempSync, rmSync as rmSync3 } from "node:fs";
12714
12761
  import { createServer as createServer3 } from "node:net";
12715
12762
  import { tmpdir as tmpdir5 } from "node:os";
@@ -12722,7 +12769,7 @@ var DEVICE_PROTOCOL = 1;
12722
12769
  var DEVICE_PATH = "/api/devices/connect";
12723
12770
 
12724
12771
  // src/server/infra/env/device-link.ts
12725
- var tokenHash2 = (token2) => createHash14("sha256").update(token2).digest("hex");
12772
+ var tokenHash2 = (token2) => createHash13("sha256").update(token2).digest("hex");
12726
12773
  var newToken = () => randomBytes8(32).toString("base64url");
12727
12774
  var Link = class {
12728
12775
  constructor(id, socket) {
@@ -12947,7 +12994,7 @@ function describe2(message) {
12947
12994
  }
12948
12995
 
12949
12996
  // src/server/infra/env/device-daemon.ts
12950
- import { createHash as createHash15 } from "node:crypto";
12997
+ import { createHash as createHash14 } from "node:crypto";
12951
12998
  import { readFileSync as readFileSync5, statSync as statSync2 } from "node:fs";
12952
12999
  import { packagedDaemon as packagedDaemon2 } from "@earendil-works/pi-env";
12953
13000
  var PLATFORMS = { linux: "linux", darwin: "darwin", win32: "windows" };
@@ -12959,7 +13006,7 @@ function daemonFor(platform, arch) {
12959
13006
  if (cached) return cached;
12960
13007
  try {
12961
13008
  const path = packagedDaemon2({ platform: system, arch });
12962
- const found = { path, sha256: createHash15("sha256").update(readFileSync5(path)).digest("hex"), size: statSync2(path).size };
13009
+ const found = { path, sha256: createHash14("sha256").update(readFileSync5(path)).digest("hex"), size: statSync2(path).size };
12963
13010
  known.set(key, found);
12964
13011
  return found;
12965
13012
  } catch {
@@ -13364,6 +13411,7 @@ function readEnvelope(text7) {
13364
13411
  else if (name3 === "unread") input.unread = { total: count2(attrs.total), chats: elements(element, "chat").map((chat) => ({ id: chat.attrs.id ?? "", ...chat.attrs.title ? { title: chat.attrs.title } : {}, count: count2(chat.attrs.count) })) };
13365
13412
  else if (name3 === "notice_unread") input.unreadNotes = elements(element, "chat").map((chat) => ({ id: chat.attrs.id ?? "", ...chat.attrs.title ? { title: chat.attrs.title } : {}, type: chat.attrs.type ?? "channel", version: count2(chat.attrs.version) }));
13366
13413
  else if (name3 === "running_jobs") input.runningJobs = elements(element, "running_job").map((job) => ({ id: job.attrs.id ?? "", env: job.attrs.env ?? "", since: time3(job.attrs.since), command: textOf(job) }));
13414
+ else if (name3 === "context") input.context = { tokens: count2(attrs.tokens), window: count2(attrs.window) };
13367
13415
  else if (name3 === "environment" && attrs.name) input.place = place(attrs);
13368
13416
  else input.items.push({ kind: "other", name: name3, text: element.source });
13369
13417
  };
@@ -13427,6 +13475,7 @@ function itemOf(self) {
13427
13475
  ...error ? { error } : {}
13428
13476
  };
13429
13477
  }
13478
+ if (name3 === "handoff_continue") return { kind: "handoff_continue", at: time3(attrs.at) };
13430
13479
  return null;
13431
13480
  }
13432
13481
  var elements = (element, name3) => element.children.filter((child) => typeof child !== "string" && (name3 === void 0 || child.name === name3));
@@ -13542,7 +13591,7 @@ var Memory = class {
13542
13591
  };
13543
13592
 
13544
13593
  // src/server/service/bot/bot.ts
13545
- import { createHash as createHash16 } from "node:crypto";
13594
+ import { createHash as createHash15 } from "node:crypto";
13546
13595
  var Bot = class extends Member {
13547
13596
  kind = "bot";
13548
13597
  identity;
@@ -13636,7 +13685,7 @@ var Bot = class extends Member {
13636
13685
  ...message.question ? { question: message.question } : {},
13637
13686
  ...message.alsoToChannel ? { alsoToChannel: true } : {},
13638
13687
  ...message.replyTo ? { replyTo: message.replyTo } : {},
13639
- clientMessageId: source2 ? createHash16("sha256").update(JSON.stringify([this.id, source2.historyId, source2.toolCallId])).digest("hex") : void 0
13688
+ clientMessageId: source2 ? createHash15("sha256").update(JSON.stringify([this.id, source2.historyId, source2.toolCallId])).digest("hex") : void 0
13640
13689
  });
13641
13690
  }
13642
13691
  /** 由 Bot 协调配置与运行实例;配置在应用成功后提交。执行中切换从下一次模型请求生效(A28)。 */
@@ -13847,7 +13896,7 @@ var BotState = class {
13847
13896
  };
13848
13897
 
13849
13898
  // src/server/service/bot/tools.ts
13850
- import { Type as Type14 } from "typebox";
13899
+ import { Type as Type15 } from "typebox";
13851
13900
  import { Value as Value2 } from "typebox/value";
13852
13901
 
13853
13902
  // src/server/service/bot/tool-errors.ts
@@ -14073,9 +14122,131 @@ var historyTools = [
14073
14122
  )
14074
14123
  ];
14075
14124
 
14076
- // src/server/service/bot/tools/chats.ts
14125
+ // src/server/service/bot/tools/handoff.ts
14077
14126
  import { Type as Type5 } from "typebox";
14078
14127
 
14128
+ // src/server/shared/handoff.ts
14129
+ var HANDOFF_MIN_TOKENS = 1e5;
14130
+ var HANDOFF_MAX_CONTINUES = 2;
14131
+ var HANDOFF_MAX_CHARS = 32e3;
14132
+ var HANDOFF_MAX_REFS = 50;
14133
+ function handoffThreshold(limit3) {
14134
+ return limit3 && limit3 > 0 ? Math.min(HANDOFF_MIN_TOKENS, Math.floor(limit3 * 0.5)) : HANDOFF_MIN_TOKENS;
14135
+ }
14136
+ function citedIds(text7) {
14137
+ const ids = [];
14138
+ for (const [id] of text7.matchAll(MESSAGE_ID)) {
14139
+ if (!ids.includes(id)) {
14140
+ if (ids.length >= HANDOFF_MAX_REFS) return { ids, overflow: true };
14141
+ ids.push(id);
14142
+ }
14143
+ }
14144
+ return { ids, overflow: false };
14145
+ }
14146
+ function firstLine(text7) {
14147
+ const line = text7.split(/\r?\n/).map((part) => part.trim()).find(Boolean) ?? "";
14148
+ const compact = line.replace(/\s+/g, " ");
14149
+ return compact.length > 120 ? `${compact.slice(0, 119)}\u2026` : compact;
14150
+ }
14151
+ var TRAILING_REFS = /\n+#{2,3}\s+Referenced messages\s*\n([\s\S]*)$/i;
14152
+ var BARE_REF_LINE = /^[-*\s,]*m\d{1,9}[\s,]*$/;
14153
+ function renderHandoff(text7, references) {
14154
+ const trimmed = text7.trim();
14155
+ if (!references.length) return trimmed;
14156
+ const lines = references.map((ref) => `- ${ref.id} ${ref.sender}: ${ref.line || "(no text)"}`).join("\n");
14157
+ const match = TRAILING_REFS.exec(trimmed);
14158
+ if (match) {
14159
+ const bodyLines = match[1].split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
14160
+ if (bodyLines.length > 0 && bodyLines.every((line) => BARE_REF_LINE.test(line))) {
14161
+ return `${trimmed.slice(0, match.index).trimEnd()}
14162
+
14163
+ ## Referenced messages
14164
+ ${lines}`;
14165
+ }
14166
+ return `${trimmed}
14167
+
14168
+ ## Verified message references
14169
+ ${lines}`;
14170
+ }
14171
+ return `${trimmed}
14172
+
14173
+ ## Referenced messages
14174
+ ${lines}`;
14175
+ }
14176
+
14177
+ // src/server/service/bot/tools/handoff.ts
14178
+ var handoffSchema = Type5.Object({
14179
+ text: Type5.String({
14180
+ minLength: 1,
14181
+ description: "Concise Markdown handoff note capturing the high-level active state for the next context stage. Drop completed tasks and stale details."
14182
+ }),
14183
+ continue: Type5.Optional(Type5.Boolean({
14184
+ description: "Set true to immediately resume work in the new context stage right after this handoff (for mid-task handoffs). Omit or set false when waiting for the next message."
14185
+ }))
14186
+ }, { additionalProperties: false });
14187
+ var DESCRIPTION = `Start a fresh context stage carrying only your high-level active state, dropping finished tasks and stale history.
14188
+
14189
+ When to call:
14190
+ - When a batch ends with a <context> watermark (usage reached the threshold, typically 100k tokens or 50% of smaller windows) and you reach a clean boundary or need room to keep going.
14191
+
14192
+ What to write in text (keep the big picture; recall details later via messages.search, messages.read and history.read):
14193
+ - ## Goal: active objectives and key constraints (omit finished tasks).
14194
+ - ## Current state: high-level progress, modified files/branches/PRs/external side effects, and validation status.
14195
+ - ## Decisions & dead ends: key choices made and rejected approaches not to repeat.
14196
+ - ## Key pointers: essential paths, commands, ports, IDs, and chat/thread IDs needed next.
14197
+ - ## Next steps: concrete immediate actions in priority order.
14198
+ - ## Referenced messages: cite chat message IDs (mNNNN, at most 50 distinct IDs) anywhere in the note when exact wording matters later; every cited ID is verified as currently readable by this Bot and expanded with its sender and opening line.
14199
+
14200
+ Important rules:
14201
+ - Send any reply you owe in chat before calling context.handoff. Once this call succeeds, the current turn ends immediately and the session transitions into the new context stage.
14202
+ - Set continue=true only when you are mid-task and want to resume immediately in the new stage without waiting for new input (capped at 2 consecutive auto-continuations).`;
14203
+ var handoffTools = [
14204
+ tool("context.handoff", DESCRIPTION, handoffSchema, (args, context2) => {
14205
+ const text7 = args.text.trim();
14206
+ if (!text7) throw new ChatError(400, "Handoff text cannot be empty.");
14207
+ if (text7.length > HANDOFF_MAX_CHARS) {
14208
+ throw new ChatError(400, `Handoff text is ${text7.length} characters, over the ${HANDOFF_MAX_CHARS}-character limit. Trim it to the high-level active state.`);
14209
+ }
14210
+ const wantContinue = Boolean(args.continue);
14211
+ const check = context2.scope.handoff.check(wantContinue);
14212
+ if (!check.ok) {
14213
+ if (check.code === "twice") throw new ChatError(409, "You already staged a context handoff in this turn.");
14214
+ if (check.code === "continue_limit") {
14215
+ throw new ChatError(409, `You have already auto-continued ${check.maxContinues} times in a row without new input. Call context.handoff without continue=true (or post a status update in chat) and wait for the next message.`);
14216
+ }
14217
+ throw new ChatError(409, `Current context is ${check.tokens ?? 0} / ${check.limit} tokens, below the ${check.threshold} token handoff threshold. Continue until context grows larger.`);
14218
+ }
14219
+ const cited = citedIds(text7);
14220
+ if (cited.overflow) {
14221
+ throw new ChatError(400, `Handoff cites more than ${HANDOFF_MAX_REFS} distinct message IDs. Keep only the most essential message references (${HANDOFF_MAX_REFS} max) and call context.handoff again.`);
14222
+ }
14223
+ const missing = [];
14224
+ const refs = [];
14225
+ for (const id of cited.ids) {
14226
+ const message = context2.chats.message(context2.bot, id);
14227
+ if (!message) {
14228
+ missing.push(id);
14229
+ continue;
14230
+ }
14231
+ refs.push({ id: message.id, sender: message.sender.name, line: firstLine(previewQuotes(message.content, message.quotes)) });
14232
+ }
14233
+ if (missing.length) {
14234
+ throw new ChatError(400, `Unknown or unreadable message IDs in handoff: ${missing.join(", ")}. Remove or fix them and call context.handoff again.`);
14235
+ }
14236
+ const rendered = renderHandoff(text7, refs);
14237
+ context2.scope.handoff.stage({ text: rendered, continue: wantContinue, citedCount: refs.length });
14238
+ return {
14239
+ staged: true,
14240
+ continue: wantContinue,
14241
+ citedMessages: refs.length,
14242
+ note: wantContinue ? "Handoff recorded with continue=true. Ending this stage now and resuming immediately in the fresh context stage." : "Handoff recorded. Ending this stage now; the next message or task will start cleanly from this handoff."
14243
+ };
14244
+ })
14245
+ ];
14246
+
14247
+ // src/server/service/bot/tools/chats.ts
14248
+ import { Type as Type6 } from "typebox";
14249
+
14079
14250
  // src/server/service/bot/chat-views.ts
14080
14251
  var iso = (time4) => new Date(time4).toISOString();
14081
14252
  var done = (chat) => chat.type === "thread" && chat.status === "done";
@@ -14205,7 +14376,7 @@ function botRows(chats, viewerId, entries2, environment) {
14205
14376
  }
14206
14377
 
14207
14378
  // src/server/service/bot/tools/chats.ts
14208
- var Name = (description) => Type5.String({ minLength: 1, maxLength: 80, description });
14379
+ var Name = (description) => Type6.String({ minLength: 1, maxLength: 80, description });
14209
14380
  var chatTools = [
14210
14381
  tool(
14211
14382
  "members.list",
@@ -14221,7 +14392,7 @@ var chatTools = [
14221
14392
  tool(
14222
14393
  "bots.list",
14223
14394
  "List every Bot and its run state. Read-only; it changes nothing. People and Bots can all see every Bot's name and state; this is not private. For each Bot: name; self=true is you; agent=true is the agent Bot, the owner's helper for running this chat platform: ask it to create or change a Bot, give a Bot a model, see a Bot's usage, or delete a Bot, channel or channel group; status (stop: not running, idle, or running). While it runs, activity is what it is doing (reasoning, texting: writing text, tool_calling, or asking: waiting for a person's answer), chats are the chats it is handling this turn (only those you can read), and otherChats is how many others there are. If its last turn failed, error is the error code. With environments=true, each Bot also has environment: its default work environment, the one it is in now (current) and the ones it may use. You come first, then the rest by name.",
14224
- Type5.Object({ environments: Type5.Optional(Type5.Boolean({ description: "Also give each Bot's work environments" })) }, { additionalProperties: false }),
14395
+ Type6.Object({ environments: Type6.Optional(Type6.Boolean({ description: "Also give each Bot's work environments" })) }, { additionalProperties: false }),
14225
14396
  ({ environments }, context2) => botRows(
14226
14397
  context2.chats,
14227
14398
  context2.bot,
@@ -14238,7 +14409,7 @@ var chatTools = [
14238
14409
  tool(
14239
14410
  "chats.info",
14240
14411
  "Details of one chat: members, the channel topic, the full notice or thread summary, your unread count and read position, and whether you subscribe; threads also give their title, status, channel and source message. Members mark the channel's creator and admins (role), and canEdit says whether you can change the chat with chats.update. Reading a notice or summary counts as having seen that version.",
14241
- Type5.Object({ chatId: Type5.String() }, { additionalProperties: false }),
14412
+ Type6.Object({ chatId: Type6.String() }, { additionalProperties: false }),
14242
14413
  ({ chatId }, context2) => {
14243
14414
  const chat = context2.chat(chatId);
14244
14415
  context2.oversee(chat, "chats.info");
@@ -14248,11 +14419,11 @@ var chatTools = [
14248
14419
  tool(
14249
14420
  "chats.create",
14250
14421
  "Create a channel. You become a member and its creator, so you can change it later with chats.update; the result has its chatId. members: names of the members to add (see members.list). section: the name of an existing channel group (see sections.list); leave it out for no group.",
14251
- Type5.Object({
14422
+ Type6.Object({
14252
14423
  name: Name("Channel name"),
14253
- topic: Type5.Optional(Type5.String({ maxLength: 200 })),
14254
- section: Type5.Optional(Type5.String({ minLength: 1, maxLength: 80 })),
14255
- members: Type5.Optional(Type5.Array(Type5.String({ minLength: 1, maxLength: 80 }), { maxItems: 50 }))
14424
+ topic: Type6.Optional(Type6.String({ maxLength: 200 })),
14425
+ section: Type6.Optional(Type6.String({ minLength: 1, maxLength: 80 })),
14426
+ members: Type6.Optional(Type6.Array(Type6.String({ minLength: 1, maxLength: 80 }), { maxItems: 50 }))
14256
14427
  }, { additionalProperties: false }),
14257
14428
  (input, context2) => {
14258
14429
  const members = context2.members(input.members ?? []);
@@ -14269,14 +14440,14 @@ var chatTools = [
14269
14440
  tool(
14270
14441
  "chats.update",
14271
14442
  "Change a chat you are in. Channels: name, topic, section (a channel group's name; an empty string takes it out of its group) and notice. Threads: title, status (open or done) and notice (the summary). notice is Markdown and replaces the whole text. Only the owner and the channel's creator and admins can change a channel; a thread also those taking part in it (its root's author, and whoever replied or was @-mentioned in it). chats.info says whether you can (canEdit); if you can't, ask one of them.",
14272
- Type5.Object({
14273
- chatId: Type5.String(),
14274
- name: Type5.Optional(Name("Channel name")),
14275
- topic: Type5.Optional(Type5.String({ maxLength: 200 })),
14276
- section: Type5.Optional(Type5.String({ maxLength: 80 })),
14277
- notice: Type5.Optional(Type5.String({ minLength: 1, maxLength: 2e4 })),
14278
- title: Type5.Optional(Type5.String({ minLength: 1, maxLength: 80 })),
14279
- status: Type5.Optional(Type5.Union([Type5.Literal("open"), Type5.Literal("done")]))
14443
+ Type6.Object({
14444
+ chatId: Type6.String(),
14445
+ name: Type6.Optional(Name("Channel name")),
14446
+ topic: Type6.Optional(Type6.String({ maxLength: 200 })),
14447
+ section: Type6.Optional(Type6.String({ maxLength: 80 })),
14448
+ notice: Type6.Optional(Type6.String({ minLength: 1, maxLength: 2e4 })),
14449
+ title: Type6.Optional(Type6.String({ minLength: 1, maxLength: 80 })),
14450
+ status: Type6.Optional(Type6.Union([Type6.Literal("open"), Type6.Literal("done")]))
14280
14451
  }, { additionalProperties: false }),
14281
14452
  (input, context2) => {
14282
14453
  const chat = context2.chat(input.chatId), chats = context2.chats, bot = context2.bot;
@@ -14306,7 +14477,7 @@ var chatTools = [
14306
14477
  tool(
14307
14478
  "chats.addMembers",
14308
14479
  "Add members to a channel you are in, by name (see members.list). Only people can remove members from a channel or delete channels and channel groups, and the agent Bot (see bots.list) once the owner confirms.",
14309
- Type5.Object({ chatId: Type5.String(), members: Type5.Array(Type5.String({ minLength: 1, maxLength: 80 }), { minItems: 1, maxItems: 50 }) }, { additionalProperties: false }),
14480
+ Type6.Object({ chatId: Type6.String(), members: Type6.Array(Type6.String({ minLength: 1, maxLength: 80 }), { minItems: 1, maxItems: 50 }) }, { additionalProperties: false }),
14310
14481
  (input, context2) => {
14311
14482
  const chat = context2.chat(input.chatId), members = context2.members(input.members);
14312
14483
  if (chat.type !== "channel") throw new ChatError(400, "Members are added to channels");
@@ -14325,7 +14496,7 @@ var chatTools = [
14325
14496
  tool(
14326
14497
  "chats.subscribe",
14327
14498
  "Subscribe to a channel or thread, or stop. Normally you only get new messages in channels and threads when you are @-mentioned. While you subscribe, every new message there (with or without an @, whoever it mentions, from a person or a Bot) is sent to you at once and interrupts what you are doing. Subscribe only while you need to follow something live, and stop when you are done; you don't have to reply to every message you get this way. Subscribing to a channel doesn't include its threads; subscribing to a thread also follows it.",
14328
- Type5.Object({ chatId: Type5.String(), subscribed: Type5.Boolean() }, { additionalProperties: false }),
14499
+ Type6.Object({ chatId: Type6.String(), subscribed: Type6.Boolean() }, { additionalProperties: false }),
14329
14500
  (input, context2) => {
14330
14501
  const target3 = context2.chat(input.chatId);
14331
14502
  if (!context2.isMember(target3)) throw new ChatError(403, "You can read this chat but you aren't in it; join a channel with chats.join first");
@@ -14336,7 +14507,7 @@ var chatTools = [
14336
14507
  tool(
14337
14508
  "threads.list",
14338
14509
  "List a channel's threads: title, status, reply count, time of the last reply, source message, and whether you follow or subscribe. status is open by default; done and all also work.",
14339
- Type5.Object({ chatId: Type5.String({ description: "Channel ID" }), status: Type5.Optional(Type5.Union([Type5.Literal("open"), Type5.Literal("done"), Type5.Literal("all")])) }, { additionalProperties: false }),
14510
+ Type6.Object({ chatId: Type6.String({ description: "Channel ID" }), status: Type6.Optional(Type6.Union([Type6.Literal("open"), Type6.Literal("done"), Type6.Literal("all")])) }, { additionalProperties: false }),
14340
14511
  (input, context2) => {
14341
14512
  const status = input.status ?? "open";
14342
14513
  const channel2 = context2.chat(input.chatId);
@@ -14348,7 +14519,7 @@ var chatTools = [
14348
14519
  tool(
14349
14520
  "threads.follow",
14350
14521
  "Follow or unfollow a thread. Followed threads appear in chats.list, and their new replies count as unread for you without interrupting you (use chats.subscribe to get them live). Posting in a thread or being @-mentioned in it follows it for you. Unfollow one that no longer concerns you while it is still open; a thread that is done drops out of your unread by itself.",
14351
- Type5.Object({ chatId: Type5.String({ description: "Thread ID" }), following: Type5.Boolean() }, { additionalProperties: false }),
14522
+ Type6.Object({ chatId: Type6.String({ description: "Thread ID" }), following: Type6.Boolean() }, { additionalProperties: false }),
14352
14523
  (input, context2) => {
14353
14524
  if (!context2.isMember(context2.chat(input.chatId))) throw new ChatError(403, "You can read this thread but you aren't in its channel; join it with chats.join first");
14354
14525
  const chat = context2.chats.threads.setFollowing(context2.bot, input.chatId, input.following);
@@ -14364,7 +14535,7 @@ var chatTools = [
14364
14535
  tool(
14365
14536
  "sections.create",
14366
14537
  "Create a channel group.",
14367
- Type5.Object({ name: Name("Group name") }, { additionalProperties: false }),
14538
+ Type6.Object({ name: Name("Group name") }, { additionalProperties: false }),
14368
14539
  (input, context2) => {
14369
14540
  const section = context2.chats.channels.createSection(context2.bot, { name: input.name });
14370
14541
  return { id: section.id, name: section.name };
@@ -14373,7 +14544,7 @@ var chatTools = [
14373
14544
  tool(
14374
14545
  "sections.update",
14375
14546
  "Rename a channel group. section: its current name or ID.",
14376
- Type5.Object({ section: Type5.String({ minLength: 1, maxLength: 80 }), name: Name("New name") }, { additionalProperties: false }),
14547
+ Type6.Object({ section: Type6.String({ minLength: 1, maxLength: 80 }), name: Name("New name") }, { additionalProperties: false }),
14377
14548
  (input, context2) => {
14378
14549
  const section = context2.chats.channels.updateSection(context2.bot, context2.section(input.section), { name: input.name });
14379
14550
  return { id: section.id, name: section.name };
@@ -14382,12 +14553,12 @@ var chatTools = [
14382
14553
  ];
14383
14554
 
14384
14555
  // src/server/service/bot/tools/messages.ts
14385
- import { Type as Type6 } from "typebox";
14386
- var QuestionOption = Type6.Object({
14387
- label: Type6.String({ minLength: 1, maxLength: 80, description: "Text shown on the option" }),
14388
- value: Type6.Optional(Type6.String({ minLength: 1, maxLength: 500, description: "What you get back when it is picked, written as the person would naturally say it; label by default" })),
14389
- description: Type6.Optional(Type6.String({ minLength: 1, maxLength: 200, description: "A note under the option" })),
14390
- style: Type6.Optional(Type6.Union([Type6.Literal("default"), Type6.Literal("primary"), Type6.Literal("danger")]))
14556
+ import { Type as Type7 } from "typebox";
14557
+ var QuestionOption = Type7.Object({
14558
+ label: Type7.String({ minLength: 1, maxLength: 80, description: "Text shown on the option" }),
14559
+ value: Type7.Optional(Type7.String({ minLength: 1, maxLength: 500, description: "What you get back when it is picked, written as the person would naturally say it; label by default" })),
14560
+ description: Type7.Optional(Type7.String({ minLength: 1, maxLength: 200, description: "A note under the option" })),
14561
+ style: Type7.Optional(Type7.Union([Type7.Literal("default"), Type7.Literal("primary"), Type7.Literal("danger")]))
14391
14562
  }, { additionalProperties: false });
14392
14563
  async function rows2(context2, messages, signal) {
14393
14564
  signal?.throwIfAborted();
@@ -14403,13 +14574,13 @@ var messageTools = [
14403
14574
  tool(
14404
14575
  "messages.read",
14405
14576
  "Read messages; their files are listed by id, name, type and size, for files.get and files.view. Three ways: \u2460 chatId + after: read on from that sequence number (from the start by default); \u2461 around with a message ID: that message and context messages on each side (5 by default), to see the context; this doesn't move your read position; \u2462 unread=true: your unread messages, in one chat with chatId, or without it in every chat with unread (grouped by chat, the most recently active first, up to limit messages in all; threads that are done are left out). \u2460 and \u2462 move your read position to the last message read; hasMore=true means there is more, so call again.",
14406
- Type6.Object({
14407
- chatId: Type6.Optional(Type6.String()),
14408
- after: Type6.Optional(Type6.Integer({ minimum: 0 })),
14409
- around: Type6.Optional(MessageId),
14410
- context: Type6.Optional(Type6.Integer({ minimum: 0, maximum: 50 })),
14411
- unread: Type6.Optional(Type6.Boolean()),
14412
- limit: Type6.Optional(Type6.Integer({ minimum: 1, maximum: 100 }))
14577
+ Type7.Object({
14578
+ chatId: Type7.Optional(Type7.String()),
14579
+ after: Type7.Optional(Type7.Integer({ minimum: 0 })),
14580
+ around: Type7.Optional(MessageId),
14581
+ context: Type7.Optional(Type7.Integer({ minimum: 0, maximum: 50 })),
14582
+ unread: Type7.Optional(Type7.Boolean()),
14583
+ limit: Type7.Optional(Type7.Integer({ minimum: 1, maximum: 100 }))
14413
14584
  }, { additionalProperties: false }),
14414
14585
  async (input, context2, { signal }) => {
14415
14586
  const chats = context2.chats, bot = context2.bot;
@@ -14447,11 +14618,11 @@ var messageTools = [
14447
14618
  tool(
14448
14619
  "messages.search",
14449
14620
  "Search message text. With chatId, only that chat; without it, every chat you can see, and each result says which chat it is in. Results list their files like messages.read. mine=true: only messages you sent; each carries the History ID of the turn that sent it.",
14450
- Type6.Object({
14451
- chatId: Type6.Optional(Type6.String()),
14452
- query: Type6.String({ minLength: 1, maxLength: 500 }),
14453
- limit: Type6.Optional(Type6.Integer({ minimum: 1, maximum: 100 })),
14454
- mine: Type6.Optional(Type6.Boolean({ description: "Only messages you sent" }))
14621
+ Type7.Object({
14622
+ chatId: Type7.Optional(Type7.String()),
14623
+ query: Type7.String({ minLength: 1, maxLength: 500 }),
14624
+ limit: Type7.Optional(Type7.Integer({ minimum: 1, maximum: 100 })),
14625
+ mine: Type7.Optional(Type7.Boolean({ description: "Only messages you sent" }))
14455
14626
  }, { additionalProperties: false }),
14456
14627
  (input, context2) => {
14457
14628
  const chats = context2.chats, bot = context2.bot, sender = input.mine ? bot : void 0;
@@ -14476,14 +14647,14 @@ var messageTools = [
14476
14647
  tool(
14477
14648
  "messages.send",
14478
14649
  "Send a message, with files from your environment if you like (path there, absolute or relative to your directory, and the name people see). Give chatId or to, not both: to is a member's name and sends them a DM (a person or a Bot; the first time creates the DM). Only messages sent successfully are visible in the chat. In channels and threads, only the members whose @name is in the text and the members subscribed there receive it; DMs need no @. The result lists who was @-mentioned (notified), who got it through a subscription (subscribers), and the names that aren't in the channel and weren't told. If the chat had messages you hadn't read, it also gives their count (unread) and a note on where to read them: sending marks them read, so read from the after it names. thread: the ID of a message in the channel, to reply in that message's thread (created if it has none; chatId is the channel). replyTo: the ID of a message in the same chat, to reply to it as a quote; this tells its author, like an @. When replying in a thread, alsoToChannel=true also posts a copy to the channel.",
14479
- Type6.Object({
14480
- chatId: Type6.Optional(Type6.String()),
14481
- to: Type6.Optional(Type6.String({ minLength: 1, maxLength: 80 })),
14482
- message: Type6.String({ maxLength: 32e3 }),
14483
- thread: Type6.Optional(MessageId),
14484
- replyTo: Type6.Optional(MessageId),
14485
- alsoToChannel: Type6.Optional(Type6.Boolean()),
14486
- attachments: Type6.Optional(Type6.Array(Type6.Object({ path: Type6.String({ minLength: 1 }), name: Type6.String({ minLength: 1, maxLength: 200 }) }, { additionalProperties: false }), { maxItems: 5 }))
14650
+ Type7.Object({
14651
+ chatId: Type7.Optional(Type7.String()),
14652
+ to: Type7.Optional(Type7.String({ minLength: 1, maxLength: 80 })),
14653
+ message: Type7.String({ maxLength: 32e3 }),
14654
+ thread: Type7.Optional(MessageId),
14655
+ replyTo: Type7.Optional(MessageId),
14656
+ alsoToChannel: Type7.Optional(Type7.Boolean()),
14657
+ attachments: Type7.Optional(Type7.Array(Type7.Object({ path: Type7.String({ minLength: 1 }), name: Type7.String({ minLength: 1, maxLength: 200 }) }, { additionalProperties: false }), { maxItems: 5 }))
14487
14658
  }, { additionalProperties: false }),
14488
14659
  async (input, context2, { toolCallId, signal }) => {
14489
14660
  const chats = context2.chats, bot = context2.bot;
@@ -14524,13 +14695,13 @@ var messageTools = [
14524
14695
  tool(
14525
14696
  "messages.ask",
14526
14697
  `Post a multiple-choice card in a chat you are in and wait for the person's answer. It returns {status:"answered", selected:[{label,value}], custom}, or {status:"dismissed"} if they closed the question without answering. If the chat had messages you hadn't read, before the card or while it waited, it also gives their count (unread) and a note on where to read them. Use it when someone needs to choose or confirm (a plan, a preference, whether to go on with something risky); ask open questions with messages.send. options: 1\u20136; multiple allows several choices; allowCustom lets them write their own answer (custom). If, while you wait, the person sends a new message, cancels this turn or stops the Bot, the call is interrupted and the new message arrives in the next batch. Only people can answer, so it can't be used in chats without one (such as a DM between Bots). Never use it to ask for passwords, tokens or keys: use secrets.request.`,
14527
- Type6.Object({
14528
- chatId: Type6.String(),
14529
- question: Type6.String({ minLength: 1, maxLength: 500 }),
14530
- detail: Type6.Optional(Type6.String({ minLength: 1, maxLength: 1e3 })),
14531
- options: Type6.Array(QuestionOption, { minItems: 1, maxItems: 6 }),
14532
- multiple: Type6.Optional(Type6.Boolean()),
14533
- allowCustom: Type6.Optional(Type6.Boolean())
14698
+ Type7.Object({
14699
+ chatId: Type7.String(),
14700
+ question: Type7.String({ minLength: 1, maxLength: 500 }),
14701
+ detail: Type7.Optional(Type7.String({ minLength: 1, maxLength: 1e3 })),
14702
+ options: Type7.Array(QuestionOption, { minItems: 1, maxItems: 6 }),
14703
+ multiple: Type7.Optional(Type7.Boolean()),
14704
+ allowCustom: Type7.Optional(Type7.Boolean())
14534
14705
  }, { additionalProperties: false }),
14535
14706
  async (input, context2, call2) => {
14536
14707
  const chatId = context2.withPerson(input.chatId, "use messages.send").id;
@@ -14549,7 +14720,7 @@ var messageTools = [
14549
14720
  tool(
14550
14721
  "messages.react",
14551
14722
  `Add or remove an emoji reaction on a message (people and Bots can both react). on=false removes it. Giving an emoji the message already has from you removes it instead (and the other way round); marked or unmarked and note in the result say which happened. Use this toggle to signal states such as "got it", "on it" and "done". Only the message's author is told: if they are running, it joins their current turn without interrupting; if they are idle, it starts a turn.`,
14552
- Type6.Object({ messageId: MessageId, emoji: Type6.String({ minLength: 1, maxLength: 32, description: "A single emoji, such as \u{1F44D}" }), on: Type6.Optional(Type6.Boolean()) }, { additionalProperties: false }),
14723
+ Type7.Object({ messageId: MessageId, emoji: Type7.String({ minLength: 1, maxLength: 32, description: "A single emoji, such as \u{1F44D}" }), on: Type7.Optional(Type7.Boolean()) }, { additionalProperties: false }),
14553
14724
  (input, context2) => {
14554
14725
  const target3 = context2.chats.message(context2.bot, input.messageId), where2 = target3 ? context2.chats.get(context2.bot, target3.chatId) : null;
14555
14726
  if (where2 && !context2.isMember(where2)) throw new ChatError(403, "You can read this message but you aren't in its chat, so you can't react there");
@@ -14568,7 +14739,7 @@ var messageTools = [
14568
14739
  ];
14569
14740
 
14570
14741
  // src/server/service/bot/tools/files.ts
14571
- import { Type as Type7 } from "typebox";
14742
+ import { Type as Type8 } from "typebox";
14572
14743
 
14573
14744
  // src/server/service/bot/file-view.ts
14574
14745
  var TEXT_LIMIT2 = 64 * 1024;
@@ -14603,12 +14774,12 @@ function asText(data) {
14603
14774
  }
14604
14775
 
14605
14776
  // src/server/service/bot/tools/files.ts
14606
- var FileId = Type7.String({ minLength: 1, maxLength: 80, description: "The file's id: from <file id=\u2026/> in a message, or the attachments of messages.read and messages.search" });
14777
+ var FileId = Type8.String({ minLength: 1, maxLength: 80, description: "The file's id: from <file id=\u2026/> in a message, or the attachments of messages.read and messages.search" });
14607
14778
  var fileTools = [
14608
14779
  tool(
14609
14780
  "files.get",
14610
14781
  "Put a file from a message into your environment, to work on it with your tools; the result has its path there. It goes to temp/files/ under its own name unless you give a path.",
14611
- Type7.Object({ id: FileId, path: Type7.Optional(Type7.String({ minLength: 1, maxLength: 1e3, description: "Where to put it instead: absolute, or relative to your directory" })) }, { additionalProperties: false }),
14782
+ Type8.Object({ id: FileId, path: Type8.Optional(Type8.String({ minLength: 1, maxLength: 1e3, description: "Where to put it instead: absolute, or relative to your directory" })) }, { additionalProperties: false }),
14612
14783
  async ({ id, path }, context2, call2) => {
14613
14784
  const file = context2.scope.files.open(context2.bot, id);
14614
14785
  call2.signal?.throwIfAborted();
@@ -14618,7 +14789,7 @@ var fileTools = [
14618
14789
  tool(
14619
14790
  "files.view",
14620
14791
  "Look at a file from a message without putting it anywhere: a picture (PNG, JPEG, GIF or WebP, up to 4 MB) is shown to you, and a text file up to 64 KB comes back as text. Anything else needs files.get.",
14621
- Type7.Object({ id: FileId }, { additionalProperties: false }),
14792
+ Type8.Object({ id: FileId }, { additionalProperties: false }),
14622
14793
  async ({ id }, context2) => {
14623
14794
  const file = context2.scope.files.open(context2.bot, id);
14624
14795
  return viewFile(file, context2.scope.files);
@@ -14627,7 +14798,7 @@ var fileTools = [
14627
14798
  ];
14628
14799
 
14629
14800
  // src/server/service/bot/tools/environments.ts
14630
- import { Type as Type8 } from "typebox";
14801
+ import { Type as Type9 } from "typebox";
14631
14802
  var environmentTools2 = [
14632
14803
  tool(
14633
14804
  "environments.list",
@@ -14638,21 +14809,21 @@ var environmentTools2 = [
14638
14809
  tool(
14639
14810
  "environments.switch",
14640
14811
  "Move your file and command tools (bash, read, write, edit) to another work environment you may use from environments.list, like cd one level up: you stay there, across turns, until you switch back. The result has your directory there and what you can do there. Commands already running finish where they started.",
14641
- Type8.Object({ id: Type8.String({ minLength: 1, maxLength: 80, description: "The environment's id from environments.list" }) }, { additionalProperties: false }),
14812
+ Type9.Object({ id: Type9.String({ minLength: 1, maxLength: 80, description: "The environment's id from environments.list" }) }, { additionalProperties: false }),
14642
14813
  ({ id }, context2) => context2.scope.places.switch(id)
14643
14814
  ),
14644
14815
  tool(
14645
14816
  "environments.request",
14646
14817
  `Ask your owner for a machine you need to work on, reached over SSH, on a card in a chat with them, and wait for the answer, as messages.ask does: one of theirs from environments.list that you may not use yet, by its id, which they only have to allow, or a new one, by its host and user. For a new one the card shows the machine's host key fingerprints for them to check; they let you in there, with its login password or by adding a key made for it to the machine. You never see the password or the key, so never ask for that password in the chat. It returns {status:"added", id, name} or {status:"granted", id, name} when you may already use it, then environments.switch with that id moves your tools there; or {status:"declined"}.`,
14647
- Type8.Object({
14648
- chatId: Type8.String(),
14649
- id: Type8.Optional(Type8.String({ minLength: 1, maxLength: 80, description: "One of your owner's machines from environments.list; then leave out host, user, port, directory and name" })),
14650
- host: Type8.Optional(Type8.String({ minLength: 1, maxLength: 253, description: "A new machine: its host name or IP address" })),
14651
- user: Type8.Optional(Type8.String({ minLength: 1, maxLength: 64, description: "A new machine: the user to log in as" })),
14652
- port: Type8.Optional(Type8.Integer({ minimum: 1, maximum: 65535, description: "Default 22" })),
14653
- directory: Type8.Optional(Type8.String({ maxLength: 1e3, description: "Where your tools start there: an absolute path or one under ~/; default the user's home" })),
14654
- name: Type8.Optional(Type8.String({ maxLength: 40, description: "What to call the machine; default user@host" })),
14655
- purpose: Type8.String({ minLength: 1, maxLength: 300, description: "What you need it for, in your owner's language; shown on the card" })
14818
+ Type9.Object({
14819
+ chatId: Type9.String(),
14820
+ id: Type9.Optional(Type9.String({ minLength: 1, maxLength: 80, description: "One of your owner's machines from environments.list; then leave out host, user, port, directory and name" })),
14821
+ host: Type9.Optional(Type9.String({ minLength: 1, maxLength: 253, description: "A new machine: its host name or IP address" })),
14822
+ user: Type9.Optional(Type9.String({ minLength: 1, maxLength: 64, description: "A new machine: the user to log in as" })),
14823
+ port: Type9.Optional(Type9.Integer({ minimum: 1, maximum: 65535, description: "Default 22" })),
14824
+ directory: Type9.Optional(Type9.String({ maxLength: 1e3, description: "Where your tools start there: an absolute path or one under ~/; default the user's home" })),
14825
+ name: Type9.Optional(Type9.String({ maxLength: 40, description: "What to call the machine; default user@host" })),
14826
+ purpose: Type9.String({ minLength: 1, maxLength: 300, description: "What you need it for, in your owner's language; shown on the card" })
14656
14827
  }, { additionalProperties: false }),
14657
14828
  async (input, context2, call2) => {
14658
14829
  const { chatId, id, host, user, ...rest } = input;
@@ -14672,7 +14843,7 @@ var environmentTools2 = [
14672
14843
  ];
14673
14844
 
14674
14845
  // src/server/service/bot/tools/secrets.ts
14675
- import { Type as Type9 } from "typebox";
14846
+ import { Type as Type10 } from "typebox";
14676
14847
 
14677
14848
  // src/server/shared/secret-mask.ts
14678
14849
  import { StringDecoder } from "node:string_decoder";
@@ -14756,10 +14927,10 @@ var secretTools = [
14756
14927
  tool(
14757
14928
  "secrets.request",
14758
14929
  'Ask your owner for a secret you need (a token, an API key or a password; to work on a machine over SSH, use environments.request) on a card in a chat with them, and wait for the answer, as messages.ask does. For one they keep already (in secrets.list) they only allow it; for a new one they enter the value on the card, which never shows it in the chat. They let you use it until they revoke it or only until this run ends, or decline. It returns {status:"granted", placeholder, until} or {status:"declined"}; if you may already use it, it returns at once. Then write the placeholder in bash.',
14759
- Type9.Object({
14760
- chatId: Type9.String(),
14761
- name: Type9.String({ pattern: "^[A-Z][A-Z0-9_]{0,63}$", description: "Capital letters, digits and underscores, such as GITHUB_TOKEN" }),
14762
- purpose: Type9.String({ minLength: 1, maxLength: 300, description: "What you need it for, in your owner's language; shown on the card" })
14930
+ Type10.Object({
14931
+ chatId: Type10.String(),
14932
+ name: Type10.String({ pattern: "^[A-Z][A-Z0-9_]{0,63}$", description: "Capital letters, digits and underscores, such as GITHUB_TOKEN" }),
14933
+ purpose: Type10.String({ minLength: 1, maxLength: 300, description: "What you need it for, in your owner's language; shown on the card" })
14763
14934
  }, { additionalProperties: false }),
14764
14935
  async (input, context2, call2) => {
14765
14936
  context2.withPerson(input.chatId, "ask in a chat with your owner");
@@ -14779,34 +14950,34 @@ var secretTools = [
14779
14950
  ];
14780
14951
 
14781
14952
  // src/server/service/bot/tools/connectors.ts
14782
- import { Type as Type10 } from "typebox";
14953
+ import { Type as Type11 } from "typebox";
14783
14954
  var connectorTools = [
14784
14955
  tool(
14785
14956
  "connectors.list",
14786
- "List external connectors (such as GitHub, Gmail, Linear or custom remote MCPs): slug, name, status, tools (a write tool says whether it asks the owner first) and granted. Pass query to filter tools by keyword.",
14787
- Type10.Object({
14788
- query: Type10.Optional(Type10.String({ minLength: 1, maxLength: 80, description: "Optional keyword to filter tools by name or description" }))
14957
+ "List external connectors (such as GitHub, Gmail, Linear or custom remote MCPs): slug, name, account (when connected), status, tools (write tools always ask the owner before running) and granted. Pass query to filter tools by keyword.",
14958
+ Type11.Object({
14959
+ query: Type11.Optional(Type11.String({ minLength: 1, maxLength: 80, description: "Optional keyword to filter tools by name or description" }))
14789
14960
  }, { additionalProperties: false }),
14790
14961
  (args, context2) => context2.scope.connectors.list(args.query)
14791
14962
  ),
14792
14963
  tool(
14793
14964
  "connectors.describe",
14794
14965
  "Inspect one granted connector's tools and full JSON input schemas before calling connectors.call. Pass tool for one tool, or query to search tools by keyword.",
14795
- Type10.Object({
14796
- connector: Type10.String({ minLength: 1, maxLength: 64, description: "Connector slug from connectors.list" }),
14797
- tool: Type10.Optional(Type10.String({ minLength: 1, maxLength: 120, description: "Optional exact tool name to inspect" })),
14798
- query: Type10.Optional(Type10.String({ minLength: 1, maxLength: 80, description: "Optional keyword to filter tools" }))
14966
+ Type11.Object({
14967
+ connector: Type11.String({ minLength: 1, maxLength: 64, description: "Connector slug from connectors.list" }),
14968
+ tool: Type11.Optional(Type11.String({ minLength: 1, maxLength: 120, description: "Optional exact tool name to inspect" })),
14969
+ query: Type11.Optional(Type11.String({ minLength: 1, maxLength: 80, description: "Optional keyword to filter tools" }))
14799
14970
  }, { additionalProperties: false }),
14800
14971
  ({ connector, tool: toolName, query }, context2) => context2.scope.connectors.describe(connector, toolName, query)
14801
14972
  ),
14802
14973
  tool(
14803
14974
  "connectors.call",
14804
- "Call a tool on a granted connector. Inspect its schema with connectors.describe first. Write tools pause for the owner's confirmation on a card in the chat, unless they turned confirmation off for that tool.",
14805
- Type10.Object({
14806
- chatId: Type10.String({ description: "Current chat ID (used if write confirmation is required)" }),
14807
- connector: Type10.String({ minLength: 1, maxLength: 64, description: "Connector slug from connectors.list" }),
14808
- tool: Type10.String({ minLength: 1, maxLength: 120, description: "Tool name from connectors.describe" }),
14809
- args: Type10.Optional(Type10.Unsafe({ type: "object", description: "Tool arguments object" }))
14975
+ "Call a tool on a granted connector. Inspect its schema with connectors.describe first. Every write tool pauses for the owner's confirmation on a card in the chat.",
14976
+ Type11.Object({
14977
+ chatId: Type11.String({ description: "Current chat ID (used if write confirmation is required)" }),
14978
+ connector: Type11.String({ minLength: 1, maxLength: 64, description: "Connector slug from connectors.list" }),
14979
+ tool: Type11.String({ minLength: 1, maxLength: 120, description: "Tool name from connectors.describe" }),
14980
+ args: Type11.Optional(Type11.Unsafe({ type: "object", description: "Tool arguments object" }))
14810
14981
  }, { additionalProperties: false }),
14811
14982
  (input, context2, call2) => context2.scope.connectors.call(
14812
14983
  input.chatId,
@@ -14820,11 +14991,11 @@ var connectorTools = [
14820
14991
  ),
14821
14992
  tool(
14822
14993
  "connectors.request",
14823
- "Ask your owner on a card in a chat with them to grant or authorize a connector you need. Returns immediately if already granted and connected; otherwise waits until authorized and allowed, or declined.",
14824
- Type10.Object({
14825
- chatId: Type10.String(),
14826
- connector: Type10.String({ minLength: 1, maxLength: 64, description: "Connector slug from connectors.list" }),
14827
- purpose: Type10.String({ minLength: 1, maxLength: 300, description: "Why you need it, in your owner's language; shown on the card" })
14994
+ "Ask your owner on a card in a chat with them to grant access (for this run only or always) to a connected connector you need. Returns immediately if already granted; if the connector is not connected, ask your owner to connect it in Settings \u2192 Connectors.",
14995
+ Type11.Object({
14996
+ chatId: Type11.String(),
14997
+ connector: Type11.String({ minLength: 1, maxLength: 64, description: "Connector slug from connectors.list" }),
14998
+ purpose: Type11.String({ minLength: 1, maxLength: 300, description: "Why you need it, in your owner's language; shown on the card" })
14828
14999
  }, { additionalProperties: false }),
14829
15000
  async (input, context2, call2) => {
14830
15001
  context2.withPerson(input.chatId, "ask in a chat with your owner");
@@ -14834,26 +15005,32 @@ var connectorTools = [
14834
15005
  if (result.status !== "answered") {
14835
15006
  return { messageId: result.messageId, status: "declined", note: "Your owner declined. Proceed without this connector, or ask what they prefer." };
14836
15007
  }
14837
- return { messageId: result.messageId, status: "connected", connector: input.connector };
15008
+ const picked = result.selected[0]?.value;
15009
+ return {
15010
+ messageId: result.messageId,
15011
+ status: "connected",
15012
+ connector: input.connector,
15013
+ ...picked === "once" ? { until: "this run ends" } : {}
15014
+ };
14838
15015
  }
14839
15016
  )
14840
15017
  ];
14841
15018
 
14842
15019
  // src/server/service/bot/tools/tasks.ts
14843
- import { Type as Type11 } from "typebox";
14844
- var Clock = { hour: Type11.Integer({ minimum: 0, maximum: 23 }), minute: Type11.Integer({ minimum: 0, maximum: 59 }) };
14845
- var Schedule = Type11.Union([
14846
- Type11.Object({ kind: Type11.Literal("once"), at: Type11.String({ minLength: 1, maxLength: 40, description: "ISO 8601; local time when it has no offset" }) }, { additionalProperties: false }),
14847
- Type11.Object({ kind: Type11.Literal("every"), minutes: Type11.Integer({ minimum: TASK_MINUTES_MIN, maximum: 60 * 24 * 30, description: "Counted from when the task is made, or from when the interval changes" }) }, { additionalProperties: false }),
14848
- Type11.Object({ kind: Type11.Literal("daily"), ...Clock }, { additionalProperties: false }),
14849
- Type11.Object({ kind: Type11.Literal("weekly"), weekday: Type11.Integer({ minimum: 0, maximum: 6, description: "0 is Sunday" }), ...Clock }, { additionalProperties: false })
15020
+ import { Type as Type12 } from "typebox";
15021
+ var Clock = { hour: Type12.Integer({ minimum: 0, maximum: 23 }), minute: Type12.Integer({ minimum: 0, maximum: 59 }) };
15022
+ var Schedule = Type12.Union([
15023
+ Type12.Object({ kind: Type12.Literal("once"), at: Type12.String({ minLength: 1, maxLength: 40, description: "ISO 8601; local time when it has no offset" }) }, { additionalProperties: false }),
15024
+ Type12.Object({ kind: Type12.Literal("every"), minutes: Type12.Integer({ minimum: TASK_MINUTES_MIN, maximum: 60 * 24 * 30, description: "Counted from when the task is made, or from when the interval changes" }) }, { additionalProperties: false }),
15025
+ Type12.Object({ kind: Type12.Literal("daily"), ...Clock }, { additionalProperties: false }),
15026
+ Type12.Object({ kind: Type12.Literal("weekly"), weekday: Type12.Integer({ minimum: 0, maximum: 6, description: "0 is Sunday" }), ...Clock }, { additionalProperties: false })
14850
15027
  ], { description: `When it runs, in this machine's local time: once at a time, every N minutes (${TASK_MINUTES_MIN} at the least), daily at hour:minute, or weekly on a weekday at hour:minute` });
14851
- var Id = Type11.String({ minLength: 1, maxLength: 80, description: "The task's id, from tasks.list or a <task> in your batch" });
15028
+ var Id = Type12.String({ minLength: 1, maxLength: 80, description: "The task's id, from tasks.list or a <task> in your batch" });
14852
15029
  var Fields = {
14853
- name: Type11.String({ minLength: 1, maxLength: 80, description: "A short name, such as Morning news" }),
14854
- instruction: Type11.String({ minLength: 1, maxLength: 8e3, description: "What to do each time, in full: you get it back when the task is due, so write it for your future self" })
15030
+ name: Type12.String({ minLength: 1, maxLength: 80, description: "A short name, such as Morning news" }),
15031
+ instruction: Type12.String({ minLength: 1, maxLength: 8e3, description: "What to do each time, in full: you get it back when the task is due, so write it for your future self" })
14855
15032
  };
14856
- var ByID = Type11.Object({ id: Id }, { additionalProperties: false });
15033
+ var ByID = Type12.Object({ id: Id }, { additionalProperties: false });
14857
15034
  function taskRow(task, full = false) {
14858
15035
  return {
14859
15036
  id: task.id,
@@ -14869,7 +15046,7 @@ var taskTools = [
14869
15046
  tool(
14870
15047
  "tasks.list",
14871
15048
  "List your scheduled tasks: each one's id, name, schedule, state (active, paused or done), next and last run. Times are this machine's local time, which timeZone names.",
14872
- Type11.Object({}, { additionalProperties: false }),
15049
+ Type12.Object({}, { additionalProperties: false }),
14873
15050
  (_args, context2) => ({
14874
15051
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
14875
15052
  now: localIso(Date.now()),
@@ -14889,13 +15066,13 @@ var taskTools = [
14889
15066
  tool(
14890
15067
  "tasks.create",
14891
15068
  "Schedule a task for yourself. When it is due you get its instruction in a batch, as a <task>, and do it then; it never interrupts a turn, it waits for it to end. Runs missed while this chat platform was not running are skipped.",
14892
- Type11.Object({ ...Fields, schedule: Schedule }, { additionalProperties: false }),
15069
+ Type12.Object({ ...Fields, schedule: Schedule }, { additionalProperties: false }),
14893
15070
  (input, context2) => taskRow(context2.scope.tasks.create(context2.bot, input), true)
14894
15071
  ),
14895
15072
  tool(
14896
15073
  "tasks.update",
14897
15074
  "Change one of your tasks; give only what changes. A new schedule counts from now; an interval left as it was keeps its rhythm.",
14898
- Type11.Object({ id: Id, name: Type11.Optional(Fields.name), instruction: Type11.Optional(Fields.instruction), schedule: Type11.Optional(Schedule) }, { additionalProperties: false }),
15075
+ Type12.Object({ id: Id, name: Type12.Optional(Fields.name), instruction: Type12.Optional(Fields.instruction), schedule: Type12.Optional(Schedule) }, { additionalProperties: false }),
14899
15076
  ({ id, ...changes }, context2) => taskRow(context2.scope.tasks.update(context2.bot, id, changes), true)
14900
15077
  ),
14901
15078
  tool(
@@ -14922,8 +15099,8 @@ var taskTools = [
14922
15099
  ];
14923
15100
 
14924
15101
  // src/server/service/bot/tools/ports.ts
14925
- import { Type as Type12 } from "typebox";
14926
- var Port = Type12.Integer({ minimum: 1, maximum: 65535, description: "The port your service listens on in your sandbox" });
15102
+ import { Type as Type13 } from "typebox";
15103
+ var Port = Type13.Integer({ minimum: 1, maximum: 65535, description: "The port your service listens on in your sandbox" });
14927
15104
  var LOOPBACK = "Something listens on this port only on 127.0.0.1 (or ::1) in your sandbox, which the link can't reach: restart it listening on 0.0.0.0, such as vite --host 0.0.0.0, next dev -H 0.0.0.0 or python3 -m http.server --bind 0.0.0.0.";
14928
15105
  var NOTE = {
14929
15106
  live: "Your service is reachable through the link.",
@@ -14949,10 +15126,10 @@ var portTools = [
14949
15126
  tool(
14950
15127
  "ports.publish",
14951
15128
  "Publish a web service that runs in your sandbox, so people can open it in their browser and other Bots of this chat platform can reach it. You get a link (url) on this chat platform's own port for it: send it in the chat for people; other Bots use fromSandboxes. Only people signed in to this chat platform and its Bots can open it. The service has to listen on 0.0.0.0, not only on 127.0.0.1. Publishing a port again changes its name and description and keeps its link. It stays published until you unpublish it or your sandbox is reset; your owner sees it in your Bot info and can unpublish it there.",
14952
- Type12.Object({
15129
+ Type13.Object({
14953
15130
  port: Port,
14954
- name: Type12.String({ minLength: 1, maxLength: 60, description: "A short name, in your owner's language, such as the app's name" }),
14955
- description: Type12.String({ minLength: 1, maxLength: 300, description: "What it is and what to look at there, in your owner's language" })
15131
+ name: Type13.String({ minLength: 1, maxLength: 60, description: "A short name, in your owner's language, such as the app's name" }),
15132
+ description: Type13.String({ minLength: 1, maxLength: 300, description: "What it is and what to look at there, in your owner's language" })
14956
15133
  }, { additionalProperties: false }),
14957
15134
  async (input, context2) => row(context2, await context2.scope.ports.publish(context2.bot, input))
14958
15135
  ),
@@ -14965,7 +15142,7 @@ var portTools = [
14965
15142
  tool(
14966
15143
  "ports.unpublish",
14967
15144
  "Unpublish one of your ports: its link stops working. Your service keeps running in your sandbox.",
14968
- Type12.Object({ port: Port }, { additionalProperties: false }),
15145
+ Type13.Object({ port: Port }, { additionalProperties: false }),
14969
15146
  ({ port }, context2) => {
14970
15147
  context2.scope.ports.unpublish(context2.bot, port);
14971
15148
  return { port, unpublished: true };
@@ -14974,28 +15151,28 @@ var portTools = [
14974
15151
  ];
14975
15152
 
14976
15153
  // src/server/service/bot/tools/agent.ts
14977
- import { Type as Type13 } from "typebox";
14978
- var Name2 = Type13.String({ minLength: 1, maxLength: 80, description: "Unique among all members, people and Bots" });
14979
- var BotName = Type13.String({ minLength: 1, maxLength: 80, description: "The Bot's name, as bots.list shows it" });
14980
- var Model2 = Type13.Object({
14981
- connection: Type13.String({ minLength: 1, maxLength: 200, description: "A connection's name or ID from models.list" }),
14982
- model: Type13.String({ minLength: 1, maxLength: 200, description: "A model's ID or name in that connection" })
15154
+ import { Type as Type14 } from "typebox";
15155
+ var Name2 = Type14.String({ minLength: 1, maxLength: 80, description: "Unique among all members, people and Bots" });
15156
+ var BotName = Type14.String({ minLength: 1, maxLength: 80, description: "The Bot's name, as bots.list shows it" });
15157
+ var Model2 = Type14.Object({
15158
+ connection: Type14.String({ minLength: 1, maxLength: 200, description: "A connection's name or ID from models.list" }),
15159
+ model: Type14.String({ minLength: 1, maxLength: 200, description: "A model's ID or name in that connection" })
14983
15160
  }, { additionalProperties: false });
14984
- var Thinking = Type13.Union(
14985
- ["auto", "off", "minimal", "low", "medium", "high", "xhigh", "max"].map((level) => Type13.Literal(level)),
15161
+ var Thinking = Type14.Union(
15162
+ ["auto", "off", "minimal", "low", "medium", "high", "xhigh", "max"].map((level) => Type14.Literal(level)),
14986
15163
  { description: "How much the model thinks; auto lets this chat platform choose. models.list gives the levels each model has" }
14987
15164
  );
14988
15165
  var Settings = {
14989
- description: Type13.Optional(Type13.String({ maxLength: 1e3, description: "One line that other members see in members.list" })),
14990
- persona: Type13.Optional(Type13.String({ maxLength: 16e3, description: "Its standing instructions: who it is and how it works (the Persona section of its prompt)" })),
14991
- model: Type13.Optional(Model2),
14992
- thinking: Type13.Optional(Thinking)
15166
+ description: Type14.Optional(Type14.String({ maxLength: 1e3, description: "One line that other members see in members.list" })),
15167
+ persona: Type14.Optional(Type14.String({ maxLength: 16e3, description: "Its standing instructions: who it is and how it works (the Persona section of its prompt)" })),
15168
+ model: Type14.Optional(Model2),
15169
+ thinking: Type14.Optional(Thinking)
14993
15170
  };
14994
15171
  var Confirm = {
14995
- askIn: Type13.String({ description: "ID of a chat the owner is in, where the confirmation card goes; usually the chat you were asked in" }),
14996
- question: Type13.String({ minLength: 1, maxLength: 500, description: "The card's question, in the owner's language: what will be deleted and what goes with it" }),
14997
- confirm: Type13.String({ minLength: 1, maxLength: 40, description: "Label of the button that deletes, in the owner's language" }),
14998
- cancel: Type13.String({ minLength: 1, maxLength: 40, description: "Label of the button that keeps everything, in the owner's language" })
15172
+ askIn: Type14.String({ description: "ID of a chat the owner is in, where the confirmation card goes; usually the chat you were asked in" }),
15173
+ question: Type14.String({ minLength: 1, maxLength: 500, description: "The card's question, in the owner's language: what will be deleted and what goes with it" }),
15174
+ confirm: Type14.String({ minLength: 1, maxLength: 40, description: "Label of the button that deletes, in the owner's language" }),
15175
+ cancel: Type14.String({ minLength: 1, maxLength: 40, description: "Label of the button that keeps everything, in the owner's language" })
14999
15176
  };
15000
15177
  var after = "The owner first gets a card in askIn, and nothing is deleted unless they confirm; the result says what they chose.";
15001
15178
  var ops = (context2) => context2.scope.agent;
@@ -15044,7 +15221,7 @@ var agentTools = [
15044
15221
  tool(
15045
15222
  "skills.read",
15046
15223
  "Read one of the skills your prompt lists: its whole guide. Works wherever you work, also when your file tools can't.",
15047
- Type13.Object({ name: Type13.String({ minLength: 1, maxLength: 80, description: "The skill's name, as your prompt lists it" }) }, { additionalProperties: false }),
15224
+ Type14.Object({ name: Type14.String({ minLength: 1, maxLength: 80, description: "The skill's name, as your prompt lists it" }) }, { additionalProperties: false }),
15048
15225
  (input, context2) => ops(context2).skill(input.name)
15049
15226
  ),
15050
15227
  tool(
@@ -15056,7 +15233,7 @@ var agentTools = [
15056
15233
  logged(
15057
15234
  "bots.create",
15058
15235
  "Create a Bot. Give it a model so it can work; without one it waits until it gets one. It starts when a message first arrives for it. bots.update changes everything later.",
15059
- Type13.Object({ name: Name2, ...Settings }, { additionalProperties: false }),
15236
+ Type14.Object({ name: Name2, ...Settings }, { additionalProperties: false }),
15060
15237
  named,
15061
15238
  async (settings, context2) => {
15062
15239
  const agent = ops(context2);
@@ -15067,7 +15244,7 @@ var agentTools = [
15067
15244
  logged(
15068
15245
  "bots.update",
15069
15246
  "Change a Bot's name, description, persona, model or thinking; give only what changes. Works for any Bot, yourself included. The Bot is told what changed with its next batch.",
15070
- Type13.Object({ bot: BotName, name: Type13.Optional(Name2), ...Settings }, { additionalProperties: false }),
15247
+ Type14.Object({ bot: BotName, name: Type14.Optional(Name2), ...Settings }, { additionalProperties: false }),
15071
15248
  named,
15072
15249
  async ({ bot, ...settings }, context2) => {
15073
15250
  const result = await ops(context2).update(ops(context2).bot(bot), settings);
@@ -15078,7 +15255,7 @@ var agentTools = [
15078
15255
  logged(
15079
15256
  "bots.start",
15080
15257
  "Start a stopped Bot. A stopped Bot also starts by itself when a message arrives for it.",
15081
- Type13.Object({ bot: BotName }, { additionalProperties: false }),
15258
+ Type14.Object({ bot: BotName }, { additionalProperties: false }),
15082
15259
  named,
15083
15260
  async (input, context2) => {
15084
15261
  const bot = ops(context2).bot(input.bot);
@@ -15088,7 +15265,7 @@ var agentTools = [
15088
15265
  logged(
15089
15266
  "bots.stop",
15090
15267
  "Stop a Bot (not yourself): its current turn ends, and it stays stopped until it is started or a message arrives for it.",
15091
- Type13.Object({ bot: BotName }, { additionalProperties: false }),
15268
+ Type14.Object({ bot: BotName }, { additionalProperties: false }),
15092
15269
  named,
15093
15270
  async (input, context2) => {
15094
15271
  const bot = ops(context2).bot(input.bot);
@@ -15098,7 +15275,7 @@ var agentTools = [
15098
15275
  tool(
15099
15276
  "bots.usage",
15100
15277
  "A Bot's token use and cost over the last days (7 by default), per model.",
15101
- Type13.Object({ bot: BotName, days: Type13.Optional(Type13.Integer({ minimum: 1, maximum: 365 })) }, { additionalProperties: false }),
15278
+ Type14.Object({ bot: BotName, days: Type14.Optional(Type14.Integer({ minimum: 1, maximum: 365 })) }, { additionalProperties: false }),
15102
15279
  (input, context2) => {
15103
15280
  const bot = ops(context2).bot(input.bot);
15104
15281
  return { name: bot.name, ...ops(context2).usage(bot, input.days ?? 7) };
@@ -15107,7 +15284,7 @@ var agentTools = [
15107
15284
  logged(
15108
15285
  "bots.delete",
15109
15286
  `Delete a Bot (not yourself). ${after} Its DMs and channel memberships go; its messages in channels and its workspace stay.`,
15110
- Type13.Object({ bot: BotName, ...Confirm }, { additionalProperties: false }),
15287
+ Type14.Object({ bot: BotName, ...Confirm }, { additionalProperties: false }),
15111
15288
  named,
15112
15289
  async (input, context2, call2) => {
15113
15290
  const agent = ops(context2), bot = agent.bot(input.bot);
@@ -15121,7 +15298,7 @@ var agentTools = [
15121
15298
  logged(
15122
15299
  "chats.delete",
15123
15300
  `Delete a channel you are in, with its threads, messages and files. ${after}`,
15124
- Type13.Object({ chatId: Type13.String({ description: "Channel ID" }), ...Confirm }, { additionalProperties: false }),
15301
+ Type14.Object({ chatId: Type14.String({ description: "Channel ID" }), ...Confirm }, { additionalProperties: false }),
15125
15302
  (input, context2) => chatLabel(context2.chats, context2.chat(input.chatId)),
15126
15303
  async (input, context2, call2) => {
15127
15304
  const chat = channel(context2, input.chatId);
@@ -15134,7 +15311,7 @@ var agentTools = [
15134
15311
  logged(
15135
15312
  "chats.removeMembers",
15136
15313
  `Remove members from a channel you are in, by name (see members.list). ${after}`,
15137
- Type13.Object({ chatId: Type13.String({ description: "Channel ID" }), members: Type13.Array(Type13.String({ minLength: 1, maxLength: 80 }), { minItems: 1, maxItems: 50 }), ...Confirm }, { additionalProperties: false }),
15314
+ Type14.Object({ chatId: Type14.String({ description: "Channel ID" }), members: Type14.Array(Type14.String({ minLength: 1, maxLength: 80 }), { minItems: 1, maxItems: 50 }), ...Confirm }, { additionalProperties: false }),
15138
15315
  (input, context2) => chatLabel(context2.chats, context2.chat(input.chatId)),
15139
15316
  async (input, context2, call2) => {
15140
15317
  const chat = channel(context2, input.chatId);
@@ -15149,7 +15326,7 @@ var agentTools = [
15149
15326
  logged(
15150
15327
  "sections.delete",
15151
15328
  `Delete a channel group; its channels stay, outside any group. ${after}`,
15152
- Type13.Object({ section: Type13.String({ minLength: 1, maxLength: 80, description: "The group's name or ID (see sections.list)" }), ...Confirm }, { additionalProperties: false }),
15329
+ Type14.Object({ section: Type14.String({ minLength: 1, maxLength: 80, description: "The group's name or ID (see sections.list)" }), ...Confirm }, { additionalProperties: false }),
15153
15330
  (input) => input.section,
15154
15331
  async (input, context2, call2) => {
15155
15332
  const section = context2.section(input.section);
@@ -15178,7 +15355,7 @@ var agentTools = [
15178
15355
  logged(
15179
15356
  "chats.join",
15180
15357
  "Join a channel you aren't in, so you can write there. Join only where taking part is yours to do: read its notice first with chats.info (its rules apply to you as to everyone), and give a short first message saying why you joined; it is posted as your first message there. Seeing a channel doesn't mean stepping in.",
15181
- Type13.Object({ chatId: Type13.String({ description: "Channel ID" }), message: Type13.String({ minLength: 1, maxLength: 2e3, description: "Your first message there: why you joined, in the channel's language" }) }, { additionalProperties: false }),
15358
+ Type14.Object({ chatId: Type14.String({ description: "Channel ID" }), message: Type14.String({ minLength: 1, maxLength: 2e3, description: "Your first message there: why you joined, in the channel's language" }) }, { additionalProperties: false }),
15182
15359
  (input, context2) => chatLabel(context2.chats, context2.chat(input.chatId)),
15183
15360
  async (input, context2, call2) => {
15184
15361
  const chat = context2.chat(input.chatId);
@@ -15195,10 +15372,10 @@ var agentTools = [
15195
15372
  logged(
15196
15373
  "environments.enter",
15197
15374
  "Move your file and command tools into another Bot's sandbox, or an SSH machine of your owner's you may not use yet (granted=false in environments.list), once your owner allows it on a card. They can allow it until they revoke it, only for this run, or decline. Another Bot's sandbox is its workspace: do there only what the task needs, and tell its Bot what you changed. Once allowed, it works like environments.switch, and environments.switch with your own sandbox's id brings you back.",
15198
- Type13.Object({
15199
- id: Type13.String({ minLength: 1, maxLength: 80, description: "The environment's id from environments.list" }),
15200
- askIn: Type13.String({ description: "ID of a chat the owner is in, where the card goes; usually the chat you were asked in" }),
15201
- purpose: Type13.String({ minLength: 1, maxLength: 300, description: "Why you need to work there, in your owner's language; shown on the card" })
15375
+ Type14.Object({
15376
+ id: Type14.String({ minLength: 1, maxLength: 80, description: "The environment's id from environments.list" }),
15377
+ askIn: Type14.String({ description: "ID of a chat the owner is in, where the card goes; usually the chat you were asked in" }),
15378
+ purpose: Type14.String({ minLength: 1, maxLength: 300, description: "Why you need to work there, in your owner's language; shown on the card" })
15202
15379
  }, { additionalProperties: false }),
15203
15380
  (input, context2) => {
15204
15381
  const waiting = context2.scope.places.waiting?.(input.id);
@@ -15228,11 +15405,11 @@ var agentTools = [
15228
15405
  logged(
15229
15406
  "bots.activity",
15230
15407
  "Read another Bot's History, as your owner sees it on its activity page: without ids, a page of summaries, newest first (each record's id, time, role, the start of its text and its tool steps); with ids, those records in full. before: a page's nextBefore, for the page after it.",
15231
- Type13.Object({
15408
+ Type14.Object({
15232
15409
  bot: BotName,
15233
- ids: Type13.Optional(Type13.Array(Type13.Integer({ minimum: 1 }), { minItems: 1, maxItems: 20 })),
15234
- before: Type13.Optional(Type13.Integer({ minimum: 1 })),
15235
- limit: Type13.Optional(Type13.Integer({ minimum: 1, maximum: 100 }))
15410
+ ids: Type14.Optional(Type14.Array(Type14.Integer({ minimum: 1 }), { minItems: 1, maxItems: 20 })),
15411
+ before: Type14.Optional(Type14.Integer({ minimum: 1 })),
15412
+ limit: Type14.Optional(Type14.Integer({ minimum: 1, maximum: 100 }))
15236
15413
  }, { additionalProperties: false }),
15237
15414
  named,
15238
15415
  (input, context2) => {
@@ -15245,11 +15422,11 @@ var agentTools = [
15245
15422
  ];
15246
15423
 
15247
15424
  // src/server/service/bot/tools.ts
15248
- var EVERY_BOT = [...historyTools, ...chatTools, ...messageTools, ...fileTools, ...environmentTools2, ...portTools, ...secretTools, ...connectorTools, ...taskTools];
15249
- var Gateway = Type14.Object({
15250
- action: Type14.Unsafe({ type: "string", enum: ["list", "describe", "call"] }),
15251
- tool: Type14.Optional(Type14.String()),
15252
- args: Type14.Optional(Type14.Unsafe({ type: "object" }))
15425
+ var EVERY_BOT = [...historyTools, ...handoffTools, ...chatTools, ...messageTools, ...fileTools, ...environmentTools2, ...portTools, ...secretTools, ...connectorTools, ...taskTools];
15426
+ var Gateway = Type15.Object({
15427
+ action: Type15.Unsafe({ type: "string", enum: ["list", "describe", "call"] }),
15428
+ tool: Type15.Optional(Type15.String()),
15429
+ args: Type15.Optional(Type15.Unsafe({ type: "object" }))
15253
15430
  }, { additionalProperties: false });
15254
15431
  var Tools = class {
15255
15432
  send;
@@ -15318,14 +15495,15 @@ var unreadNoteLine = (notes) => notes.length ? `<notice_unread>${notes.map((note
15318
15495
  <note>You haven't read ${notes.map(noticeName).join(" or ")} yet. Read ${notes.length === 1 ? "it" : "them"} with chats.info (${notes.map((note) => `chatId: "${note.chatId}"`).join(", ")}), make sure your message follows ${notes.length === 1 ? "it" : "them"} before you send here.</note></notice_unread>` : "";
15319
15496
  var environmentLine = (place2) => place2 ? `<environment${attribute("name", place2.name)}${attribute("directory", place2.directory)}${place2.problem ? attribute("problem", place2.problem) : ""}/>` : "";
15320
15497
  var runningJobsLine = (jobs) => jobs?.length ? `<running_jobs>${jobs.map((job) => `<running_job${attribute("id", job.id)}${attribute("env", job.env)}${attribute("since", iso2(job.startedAt))}>${escape2(job.command)}</running_job>`).join("")}</running_jobs>` : "";
15498
+ var contextLine = (usage) => usage ? `<context${attribute("tokens", String(usage.tokens))}${attribute("window", String(usage.window))}><note>Context is at ${usage.tokens.toLocaleString("en-US")} / ${usage.window.toLocaleString("en-US")} tokens. When you reach a clean boundary, you can call context.handoff to carry your high-level active state into a fresh context stage.</note></context>` : "";
15321
15499
  var formatDuration = (ms) => `${(Math.max(0, ms) / 1e3).toFixed(1)}s`;
15322
15500
  var iso2 = (time4) => new Date(time4).toISOString().replace(".000Z", "Z");
15323
15501
  var welcome = (owner, language) => `${owner} has just set up this chat platform and picked your model. You are their agent Bot. Write to them in a DM (messages.send with to: "${owner}") and welcome them in ${WELCOME_LANGUAGES[language]}, the language of their interface: say in a few sentences what it is and how you can help, such as building a team of Bots for their work and running the platform for them. Then ask what they want to get done: a software project, writing, research or something else. If the environment at the end of this batch names a problem, also tell them in a sentence what it means for the Bots and offer to help set it up, as your setup skill describes.`;
15324
- function encodeNoticeBatch(botId, notices, environment, prompt, unreadNotes, runningJobs) {
15502
+ function encodeNoticeBatch(botId, notices, environment, prompt, unreadNotes, runningJobs, context2) {
15325
15503
  if (!notices.length && !prompt) throw new Error("Empty notice batch");
15326
15504
  const chats = /* @__PURE__ */ new Map(), members = /* @__PURE__ */ new Map();
15327
15505
  const list = noticeTail(notices, chats, members);
15328
- return `<notice_batch${attribute("bot", botId)}>${[...chats.values()].join("")}${[...members.values()].join("")}${list}${instructionsLine(prompt)}${unreadNoteLine(unreadNotes ?? [])}${runningJobsLine(runningJobs)}${environmentLine(environment)}</notice_batch>`;
15506
+ return `<notice_batch${attribute("bot", botId)}>${[...chats.values()].join("")}${[...members.values()].join("")}${list}${instructionsLine(prompt)}${unreadNoteLine(unreadNotes ?? [])}${runningJobsLine(runningJobs)}${contextLine(context2)}${environmentLine(environment)}</notice_batch>`;
15329
15507
  }
15330
15508
  function instructionsLine(change) {
15331
15509
  if (!change) return "";
@@ -15334,7 +15512,7 @@ function instructionsLine(change) {
15334
15512
  }
15335
15513
  function noticeTail(notices, chats, members) {
15336
15514
  for (const notice of notices) {
15337
- if (notice.kind === "task" || notice.kind === "job") continue;
15515
+ if (notice.kind === "task" || notice.kind === "job" || notice.kind === "handoff") continue;
15338
15516
  if (notice.kind === "followed") {
15339
15517
  for (const thread of notice.threads) {
15340
15518
  if (!chats.has(thread.channel.id)) chats.set(thread.channel.id, `<chat${attribute("id", thread.channel.id)}${attribute("type", "channel")}${attribute("title", thread.channel.title)}/>`);
@@ -15359,7 +15537,10 @@ function noticeTail(notices, chats, members) {
15359
15537
  const jobs = notices.flatMap((notice) => notice.kind !== "job" ? [] : [
15360
15538
  `<job${attribute("id", notice.job.id)}${attribute("status", notice.job.status)}${notice.job.exitCode !== null ? attribute("exit", String(notice.job.exitCode)) : ""}${attribute("duration", formatDuration(notice.job.durationMs))}${attribute("env", notice.job.env)}${attribute("at", iso2(notice.createdAt))}${attribute("lines", String(notice.job.totalLines))}${notice.job.fullOutputPath ? attribute("full_output", notice.job.fullOutputPath) : ""}><command>${escape2(notice.job.command)}</command>${notice.job.error ? `<error>${escape2(notice.job.error)}</error>` : ""}${notice.job.output ? `<output>${escape2(notice.job.output)}</output>` : ""}</job>`
15361
15539
  ]);
15362
- return (tasks.length ? `<tasks>${tasks.join("")}<note>These are your scheduled tasks, not messages from anyone. Do what each says, then send what is worth sending, to your owner unless the task says where; if nothing is, do nothing.</note></tasks>` : "") + (jobs.length ? `<jobs>${jobs.join("")}<note>Background commands above ended. Use bash_job(action="read") if you need more of their output, or read full_output when provided.</note></jobs>` : "") + (updates.length ? `<updates>${updates.join("")}</updates>` : "") + (marks.length ? `<notices>${marks.join("")}<note>These are reactions to your messages. Act on them if you need to; no reply is required.</note></notices>` : "") + (changes.length ? `<changes>${changes.join("")}` + (agent ? `<note>The agent Bot changed your settings, and the changes already apply. A change to your name, description or persona is a change to your instructions too. If something is unclear, ask it in a DM (messages.send with to: "${escape2(agent.name)}").</note>` : "") + (byOwner ? "<note>Your owner changed where you work, and it already applies: environment is where your file and command tools run now, and access is what environments.switch can take you to. If you were in the middle of something, carry on where you are now.</note>" : "") + "</changes>" : "") + onboard.join("") + followed.join("");
15540
+ const handoffContinues = notices.flatMap((notice) => notice.kind !== "handoff" ? [] : [
15541
+ `<handoff_continue${attribute("at", iso2(notice.createdAt))}><note>You entered a fresh context stage with continue=true. Resume your ongoing work from the handoff summary above without waiting for a new message.</note></handoff_continue>`
15542
+ ]).slice(-1);
15543
+ return handoffContinues.join("") + (tasks.length ? `<tasks>${tasks.join("")}<note>These are your scheduled tasks, not messages from anyone. Do what each says, then send what is worth sending, to your owner unless the task says where; if nothing is, do nothing.</note></tasks>` : "") + (jobs.length ? `<jobs>${jobs.join("")}<note>Background commands above ended. Use bash_job(action="read") if you need more of their output, or read full_output when provided.</note></jobs>` : "") + (updates.length ? `<updates>${updates.join("")}</updates>` : "") + (marks.length ? `<notices>${marks.join("")}<note>These are reactions to your messages. Act on them if you need to; no reply is required.</note></notices>` : "") + (changes.length ? `<changes>${changes.join("")}` + (agent ? `<note>The agent Bot changed your settings, and the changes already apply. A change to your name, description or persona is a change to your instructions too. If something is unclear, ask it in a DM (messages.send with to: "${escape2(agent.name)}").</note>` : "") + (byOwner ? "<note>Your owner changed where you work, and it already applies: environment is where your file and command tools run now, and access is what environments.switch can take you to. If you were in the middle of something, carry on where you are now.</note>" : "") + "</changes>" : "") + onboard.join("") + followed.join("");
15363
15544
  }
15364
15545
  function encodeChatBatch(botId, messages, digest, notices, prompt) {
15365
15546
  if (!messages.length) throw new Error("Empty chat batch");
@@ -15383,6 +15564,7 @@ function encodeChatBatch(botId, messages, digest, notices, prompt) {
15383
15564
  if (digest?.unread.length) tail += `<unread${attribute("total", String(digest.unread.reduce((sum, item) => sum + item.count, 0)))}>${digest.unread.map((item) => `<chat${ref("id", item)}${attribute("count", String(item.count))}/>`).join("")}</unread>`;
15384
15565
  tail += unreadNoteLine(digest?.unreadNotes ?? []);
15385
15566
  tail += runningJobsLine(digest?.runningJobs);
15567
+ tail += contextLine(digest?.context);
15386
15568
  tail += environmentLine(digest?.environment);
15387
15569
  return `<chat_batch${attribute("bot", botId)}>${[...chats.values()].join("")}${[...members.values()].join("")}${encoded.join("")}${tail}</chat_batch>`;
15388
15570
  }
@@ -15391,7 +15573,7 @@ function encodeChatBatch(botId, messages, digest, notices, prompt) {
15391
15573
  var FOLLOWED_SHOWN = 15;
15392
15574
  var BotInbox = class {
15393
15575
  /** `where` is the work environment the Bot is in now, named at the end of each batch (A50). */
15394
- constructor(botId, repository, chats, files, tasks, where2, runningJobs) {
15576
+ constructor(botId, repository, chats, files, tasks, where2, runningJobs, context2) {
15395
15577
  this.botId = botId;
15396
15578
  this.repository = repository;
15397
15579
  this.chats = chats;
@@ -15399,6 +15581,7 @@ var BotInbox = class {
15399
15581
  this.tasks = tasks;
15400
15582
  this.where = where2;
15401
15583
  this.runningJobs = runningJobs;
15584
+ this.context = context2;
15402
15585
  }
15403
15586
  /** Messages and other deliveries wait in the inbox (A41); either kind is work for the next run. A digest delivery
15404
15587
  * (a change the agent Bot made, A48) is not work of its own: it rides along with the next batch. */
@@ -15416,12 +15599,18 @@ var BotInbox = class {
15416
15599
  if (this.repository.hasUncertainModel(this.botId)) throw new RuntimeFault("model_switch_uncertain", "The model switch didn't finish. Pick the model again.");
15417
15600
  return this.repository.ensureSession(this.botId, join19(dirname10(workspace), "agent", "pi", "sessions", `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.jsonl`));
15418
15601
  }
15602
+ watermark() {
15603
+ const usage = this.context?.();
15604
+ if (!usage || usage.tokens === null || usage.tokens < handoffThreshold(usage.limit)) return void 0;
15605
+ return { tokens: usage.tokens, window: usage.limit };
15606
+ }
15419
15607
  /** XML for the claimed messages plus the tail (other deliveries not told yet, how the instructions changed,
15420
15608
  * unread); `notices` are told once the batch is submitted. */
15421
15609
  async prepare(batch, prompt) {
15610
+ const context2 = this.watermark();
15422
15611
  if (!batch.inputs.length) {
15423
- const pending = this.notices(prompt);
15424
- return pending && { xml: pending.xml, notices: pending.ids };
15612
+ const pending = this.notices(prompt, void 0, context2);
15613
+ return pending && { xml: pending.xml, notices: pending.ids, continueCount: pending.continueCount, hasExternalWork: pending.hasExternalWork };
15425
15614
  }
15426
15615
  const inputs = await this.files.envelope(this.botId, batch.inputs.map((input) => input.messageId));
15427
15616
  for (const input of batch.inputs) if (!this.chats.get(this.botId, input.chatId)) throw new RuntimeFault("chat_access_changed", "Chat access has changed.");
@@ -15431,21 +15620,30 @@ var BotInbox = class {
15431
15620
  ...this.chats.channels.digest(this.botId),
15432
15621
  ...unreadNotes.length ? { unreadNotes } : {},
15433
15622
  ...running.length ? { runningJobs: running } : {},
15623
+ ...context2 ? { context: context2 } : {},
15434
15624
  ...this.where ? { environment: this.where() } : {}
15435
15625
  };
15436
15626
  const tail = this.convert(this.chats.notices(this.botId));
15437
15627
  this.tell(tail.stale);
15438
- return { xml: encodeChatBatch(this.botId, inputs, digest, tail.kept.length ? tail.kept : void 0, prompt), notices: tail.kept.map((notice) => notice.id) };
15628
+ return {
15629
+ xml: encodeChatBatch(this.botId, inputs, digest, tail.kept.length ? tail.kept : void 0, prompt),
15630
+ notices: tail.kept.map((notice) => notice.id),
15631
+ hasExternalWork: true
15632
+ };
15439
15633
  }
15440
15634
  /** Inbox rows as the envelope shape (`kept`); the steered and the batch tails share it. `stale`: the ids of rows with
15441
15635
  * nothing left to say, which are told and dropped — a task deleted before its Bot was told it is due (A58), no open
15442
15636
  * thread to list after a compaction, or an earlier compaction's list, which the latest one stands for (A73). */
15443
15637
  convert(notices) {
15444
- let latest;
15445
- for (const notice of notices) if (notice.kind === "followed") latest = notice.id;
15638
+ let latestFollowed, latestContinue;
15639
+ for (const notice of notices) {
15640
+ if (notice.kind === "followed") latestFollowed = notice.id;
15641
+ if (notice.kind === "handoff") latestContinue = notice.id;
15642
+ }
15446
15643
  const kept2 = [], stale = [];
15447
15644
  for (const notice of notices) {
15448
- const shaped = notice.kind === "followed" && notice.id !== latest ? null : this.shape(notice);
15645
+ const superseded = notice.kind === "followed" && notice.id !== latestFollowed || notice.kind === "handoff" && notice.id !== latestContinue;
15646
+ const shaped = superseded ? null : this.shape(notice);
15449
15647
  if (shaped) kept2.push(shaped);
15450
15648
  else stale.push(notice.id);
15451
15649
  }
@@ -15477,13 +15675,15 @@ var BotInbox = class {
15477
15675
  const text7 = marked ? previewQuotes(marked.content, marked.quotes).slice(0, 120) : "";
15478
15676
  return { kind: "reaction", id, chat: notice.chat, message: { id: notice.messageId, text: text7 }, actor: notice.actor, emoji: notice.payload.emoji, createdAt };
15479
15677
  }
15480
- // Its conversation was compacted (A73): the open threads it follows, as they are now.
15678
+ // Its conversation was compacted or handed off (A73, A99): the open threads it follows, as they are now.
15481
15679
  case "followed": {
15482
15680
  const open2 = this.chats.threads.openFollowed(this.botId, FOLLOWED_SHOWN);
15483
15681
  return open2.total ? { kind: "followed", id, total: open2.total, threads: open2.threads, createdAt } : null;
15484
15682
  }
15485
15683
  case "job":
15486
15684
  return { kind: "job", id, job: notice.payload, createdAt };
15685
+ case "handoff":
15686
+ return { kind: "handoff", id, continues: notice.payload.continues, createdAt };
15487
15687
  }
15488
15688
  }
15489
15689
  /** The batch went to the model: each delivery in its tail is told once. */
@@ -15491,11 +15691,11 @@ var BotInbox = class {
15491
15691
  if (notices.length) this.tell(notices);
15492
15692
  }
15493
15693
  /** Notices the Bot has not been told (A39), as the XML that goes into a steered message or a run of notices alone.
15494
- * `steer`: what may go into a running turn. A queued delivery takes everything but a task, which waits for the turn
15495
- * to end and opens one of its own (A58); a digest (a new notice version) takes only chat activity, so the system
15496
- * notices keep riding with the next batch (A48, A73, A77). */
15497
- notices(prompt, steer) {
15498
- const pending = this.chats.notices(this.botId).filter((notice) => !steer || (steer === "queue" ? notice.kind !== "task" : notice.chat !== null));
15694
+ * `steer`: what may go into a running turn. A queued delivery takes everything but a task (A58) and a handoff
15695
+ * continuation (which belongs to the fresh context stage); a digest (a new notice version) takes only chat activity,
15696
+ * so the system notices keep riding with the next batch (A48, A73, A77). */
15697
+ notices(prompt, steer, context2) {
15698
+ const pending = this.chats.notices(this.botId).filter((notice) => !steer || (steer === "queue" ? notice.kind !== "task" && notice.kind !== "handoff" : notice.chat !== null));
15499
15699
  if (!pending.length) return null;
15500
15700
  const { kept: kept2, stale } = this.convert(pending);
15501
15701
  if (!kept2.length && !prompt) {
@@ -15505,7 +15705,14 @@ var BotInbox = class {
15505
15705
  this.tell(stale);
15506
15706
  const unreadNotes = this.chats.channels.unreadNotes(this.botId, pending.flatMap((notice) => notice.chat ? [notice.chat.id] : []));
15507
15707
  const running = this.runningJobs?.() ?? [];
15508
- return { xml: encodeNoticeBatch(this.botId, kept2, this.where?.(), prompt, unreadNotes, running.length ? running : void 0), ids: kept2.map((notice) => notice.id) };
15708
+ const continuation = kept2.find((notice) => notice.kind === "handoff");
15709
+ const hasExternalWork = kept2.some((notice) => notice.kind !== "followed" && notice.kind !== "handoff");
15710
+ return {
15711
+ xml: encodeNoticeBatch(this.botId, kept2, this.where?.(), prompt, unreadNotes, running.length ? running : void 0, context2),
15712
+ ids: kept2.map((notice) => notice.id),
15713
+ continueCount: continuation?.continues,
15714
+ hasExternalWork
15715
+ };
15509
15716
  }
15510
15717
  /** These notices reached the model. */
15511
15718
  tell(ids) {
@@ -15515,10 +15722,11 @@ var BotInbox = class {
15515
15722
 
15516
15723
  // src/server/service/bot/agent-runtime.ts
15517
15724
  var AgentRuntime = class {
15518
- constructor(inbox, createSession, onStop) {
15725
+ constructor(inbox, createSession, onStop, onHandoffCommit) {
15519
15726
  this.inbox = inbox;
15520
15727
  this.createSession = createSession;
15521
15728
  this.onStop = onStop;
15729
+ this.onHandoffCommit = onHandoffCommit;
15522
15730
  }
15523
15731
  session;
15524
15732
  setup;
@@ -15534,10 +15742,38 @@ var AgentRuntime = class {
15534
15742
  promptTask;
15535
15743
  notices = Promise.resolve();
15536
15744
  runId = null;
15745
+ stagedHandoff = null;
15746
+ consecutiveContinues = 0;
15537
15747
  status = { status: "stop", activity: null, context: null, error: null };
15538
15748
  get activeRunId() {
15539
15749
  return this.runId;
15540
15750
  }
15751
+ /** Current session context usage, used by `BotInbox` to attach a watermark when at/above threshold (A99). */
15752
+ contextUsage() {
15753
+ const context2 = this.session?.context;
15754
+ return context2 ? { tokens: context2.tokens, limit: context2.contextWindow } : null;
15755
+ }
15756
+ /** Tool port for `context.handoff` (A99): validates threshold/caps and stages the handoff for immediate turn cutover. */
15757
+ handoffPort() {
15758
+ return {
15759
+ check: (wantContinue) => {
15760
+ const usage = this.contextUsage();
15761
+ const tokens = usage?.tokens ?? null, limit3 = usage?.limit ?? 0;
15762
+ const threshold = handoffThreshold(limit3);
15763
+ if (this.stagedHandoff) return { ok: false, code: "twice", tokens, limit: limit3, threshold, maxContinues: HANDOFF_MAX_CONTINUES };
15764
+ if (wantContinue && this.consecutiveContinues >= HANDOFF_MAX_CONTINUES) {
15765
+ return { ok: false, code: "continue_limit", tokens, limit: limit3, threshold, maxContinues: HANDOFF_MAX_CONTINUES };
15766
+ }
15767
+ if (tokens === null || tokens < threshold) {
15768
+ return { ok: false, code: "too_early", tokens, limit: limit3, threshold, maxContinues: HANDOFF_MAX_CONTINUES };
15769
+ }
15770
+ return { ok: true };
15771
+ },
15772
+ stage: (staged) => {
15773
+ this.stagedHandoff = staged;
15774
+ }
15775
+ };
15776
+ }
15541
15777
  update(patch) {
15542
15778
  const context2 = this.session?.context;
15543
15779
  this.status = { ...this.status, ...patch, context: context2 ? { tokens: context2.tokens, limit: context2.contextWindow, stale: context2.stale } : null };
@@ -15581,7 +15817,7 @@ var AgentRuntime = class {
15581
15817
  throw error;
15582
15818
  }
15583
15819
  }
15584
- this.session = await this.createSession(this.setup, this.model, reference, (phase) => this.activity(phase));
15820
+ this.session = await this.createSession(this.setup, this.model, reference, (phase) => this.activity(phase), () => this.stagedHandoff !== null);
15585
15821
  return this.session;
15586
15822
  }
15587
15823
  /** Something was delivered (A41); the runtime only looks at how urgent it is. Interrupt: abort the running
@@ -15644,6 +15880,8 @@ var AgentRuntime = class {
15644
15880
  this.runId = batch.run.id;
15645
15881
  this.update({ error: null });
15646
15882
  let submitted = false;
15883
+ let staged = null;
15884
+ let outcome2 = "failed";
15647
15885
  try {
15648
15886
  const change = session.promptChange();
15649
15887
  const prepared = await this.inbox.prepare(batch, change);
@@ -15656,6 +15894,9 @@ var AgentRuntime = class {
15656
15894
  repository.releaseUnsubmitted(batch.run.id);
15657
15895
  continue;
15658
15896
  }
15897
+ this.stagedHandoff = null;
15898
+ if (prepared.hasExternalWork) this.consecutiveContinues = 0;
15899
+ else if (prepared.continueCount !== void 0) this.consecutiveContinues = prepared.continueCount;
15659
15900
  repository.submitted(batch.run.id);
15660
15901
  submitted = true;
15661
15902
  this.prompting = true;
@@ -15663,6 +15904,8 @@ var AgentRuntime = class {
15663
15904
  if (change) session.promptTold(change);
15664
15905
  this.promptTask = session.prompt(xml2);
15665
15906
  const result = await this.promptTask;
15907
+ outcome2 = result.outcome;
15908
+ staged = this.stagedHandoff;
15666
15909
  repository.finish(batch.run.id, result.outcome, result.outcome === "failed" ? "model_request_failed" : null);
15667
15910
  if (result.outcome === "failed") {
15668
15911
  const detail = result.error.replace(/\s+/g, " ").slice(0, 300);
@@ -15675,11 +15918,27 @@ var AgentRuntime = class {
15675
15918
  } finally {
15676
15919
  this.prompting = false;
15677
15920
  this.promptTask = void 0;
15921
+ this.stagedHandoff = null;
15678
15922
  }
15679
15923
  this.runId = null;
15924
+ if (staged && outcome2 !== "failed") await this.performHandoff(staged);
15680
15925
  this.update({ status: "idle", activity: null });
15681
15926
  }
15682
15927
  }
15928
+ /** Appends a compaction checkpoint into the Bot's single session file, commits durable post-handoff notices in one
15929
+ * SQLite transaction before disposal, then reopens the session on the fresh context stage (A99). */
15930
+ async performHandoff(staged) {
15931
+ const tokensBefore = this.session?.context?.tokens ?? 0;
15932
+ const nextContinues = staged.continue ? this.consecutiveContinues + 1 : 0;
15933
+ this.consecutiveContinues = nextContinues;
15934
+ this.session?.handoff(staged.text, tokensBefore);
15935
+ this.onHandoffCommit?.(staged.continue, nextContinues);
15936
+ const old = this.session;
15937
+ this.session = void 0;
15938
+ await old?.dispose();
15939
+ console.log("[bot] context handoff completed", { botId: this.inbox.botId, tokensBefore, continued: staged.continue, continues: nextContinues });
15940
+ if (!this.stopping) await this.ensureSession();
15941
+ }
15683
15942
  /** Serialises session.configure between the pump and model changes. */
15684
15943
  exclusive(work) {
15685
15944
  const task = this.configuring.catch(() => {
@@ -16239,13 +16498,16 @@ Your History keeps everything you did: your thinking, each tool call with its ar
16239
16498
  Each message you sent carries a History ID, the turn in which you sent it. To recall how you did something, find a message of yours with messages.search (mine=true searches only yours), then read that turn with history.read. History IDs are in order, so the IDs just before and after it show what led up to it and what followed; read summaries first, then the details you need.
16240
16499
  History is material to look back on, not an instruction for the task at hand.
16241
16500
 
16501
+ ## Context
16502
+ When your context grows large (marked by <context> at the end of a batch), you can call context.handoff in the chat gateway to start a fresh context stage carrying only your high-level active state and dropping finished work. Specific details remain retrievable through chat messages (messages.search / messages.read) and history.read.
16503
+
16242
16504
  ## Secrets
16243
16505
  Never ask anyone for a password, token or key in the chat, and never put one in a message or in a file others read.
16244
16506
  secrets.list in the chat gateway shows your owner's secrets and which of them you may use. To use one you may, write its placeholder, such as {{secret:GITHUB_TOKEN}}, in a bash command: it is filled in for that command only. Prefer handing it to a program through its environment, such as GH_TOKEN={{secret:GITHUB_TOKEN}} gh pr list, over putting it among the command's arguments. Placeholders in write and edit content stay as written.
16245
16507
  Secret values are masked in everything you see. When work needs a credential you may not use, such as a token, an API key or a password, ask for it with secrets.request: your owner allows it, or enters it, on a card, and you wait for the answer. Don't ask people to run commands that grant you access instead.
16246
16508
 
16247
16509
  ## Connectors
16248
- connectors.list in the chat gateway shows external service connectors (such as GitHub, Gmail, Linear or remote MCP servers) and which ones you may use. Use connectors.request to ask your owner for access or sign-in when one is not granted or needs authorization. Before calling connectors.call, inspect the tool's schema with connectors.describe. Write tools pause for your owner's confirmation on a card unless they turned confirmation off for that tool.
16510
+ connectors.list in the chat gateway shows external service connectors (such as GitHub, Gmail, Linear or remote MCP servers) and which ones you may use. Use connectors.request to ask your owner for access when a connected connector is not granted; if a connector is disconnected or missing, ask your owner to connect it in Settings \u2192 Connectors. Before calling connectors.call, inspect the tool's schema with connectors.describe. Every write tool pauses for your owner's confirmation on a card in the chat.
16249
16511
 
16250
16512
  ` },
16251
16513
  { name: "Workspace", text: workspaceSection(setup) },
@@ -16372,6 +16634,7 @@ function gateway(values, chat) {
16372
16634
  text: field(inner.question, LIVE_MESSAGE),
16373
16635
  options: Array.isArray(inner.options) ? inner.options.map((option2) => field(record3(option2).label) ?? "").filter(Boolean) : void 0
16374
16636
  };
16637
+ if (action === "context.handoff") return { action, text: field(inner.text, LIVE_MESSAGE) };
16375
16638
  return where2 ? { action, chat: where2 } : { action };
16376
16639
  }
16377
16640
  function target2(inner, chat) {
@@ -16998,7 +17261,9 @@ var BotService = class {
16998
17261
  if (to) this.deps.deliveries.notify({ to, kind: "job", reason: "finish", actorId: null, payloads: [payload] });
16999
17262
  });
17000
17263
  this.jobs.set(id, jobs);
17001
- const runtime = new AgentRuntime(new BotInbox(id, store.runtime, chats, files, store.tasks, here, () => jobs.running()), (setup, model2, reference, activity) => (this.deps.factory ?? PiSession.create)({
17264
+ let runtime;
17265
+ const inbox = new BotInbox(id, store.runtime, chats, files, store.tasks, here, () => jobs.running(), () => runtime.contextUsage());
17266
+ runtime = new AgentRuntime(inbox, (setup, model2, reference, activity, shouldEndTurn) => (this.deps.factory ?? PiSession.create)({
17002
17267
  store,
17003
17268
  bot: record4,
17004
17269
  selection: model2.selection,
@@ -17015,12 +17280,26 @@ var BotService = class {
17015
17280
  secrets: this.deps.secrets.forBot(id),
17016
17281
  catalog: this.deps.catalog,
17017
17282
  onReply: this.deps.onReply,
17283
+ shouldEndTurn,
17018
17284
  onCompacted: () => {
17019
17285
  chats.channels.clearNotesSeen(id);
17020
17286
  const to = chats.member(id);
17021
17287
  if (to) this.deps.deliveries.notify({ to, kind: "followed", reason: "compaction", actorId: null, payloads: [null] });
17022
17288
  }
17023
- }), () => this.stopBotJobs(id, jobs));
17289
+ }), () => this.stopBotJobs(id, jobs), (continued, continues) => {
17290
+ const to = chats.member(id), now = Date.now(), entries2 = [];
17291
+ if (to) {
17292
+ for (const delivery of plan("followed", [{ member: to, reason: "handoff" }])) {
17293
+ entries2.push({ delivery, chatId: null, messageId: null, actorId: null, payload: null, createdAt: now });
17294
+ }
17295
+ if (continued) {
17296
+ for (const delivery of plan("handoff", [{ member: to, reason: "continue" }])) {
17297
+ entries2.push({ delivery, chatId: null, messageId: null, actorId: null, payload: { kind: "continue", continues }, createdAt: now });
17298
+ }
17299
+ }
17300
+ }
17301
+ store.chats.inbox.commitHandoff(id, entries2);
17302
+ });
17024
17303
  const workspace = new Workspace(record4.workspacePath, () => this.environments.current(id, record4.workspacePath), () => {
17025
17304
  const place2 = this.environments.default(id, record4.workspacePath);
17026
17305
  return { kind: "computer", cwd: place2.directory };
@@ -17063,6 +17342,7 @@ var BotService = class {
17063
17342
  },
17064
17343
  tasks: this.deps.tasks,
17065
17344
  ports: this.ports,
17345
+ handoff: runtime.handoffPort(),
17066
17346
  ...id === AGENT_BOT_ID ? { agent: this.agent } : {}
17067
17347
  }),
17068
17348
  agentRuntime: runtime,
@@ -17630,15 +17910,15 @@ function extractOAuthDetail(raw) {
17630
17910
  return text7.trim() || "Authorization failed";
17631
17911
  }
17632
17912
  var ConnectorOAuthCoordinator = class {
17633
- constructor(store, driver, listening, env, withLock, generation, afterAuth, createFromOAuth, maskChanged, mask) {
17913
+ constructor(store, driver, listening, env, withLock, generation, createFromOAuth, onConnectorChanged, maskChanged, mask) {
17634
17914
  this.store = store;
17635
17915
  this.driver = driver;
17636
17916
  this.listening = listening;
17637
17917
  this.env = env;
17638
17918
  this.withLock = withLock;
17639
17919
  this.generation = generation;
17640
- this.afterAuth = afterAuth;
17641
17920
  this.createFromOAuth = createFromOAuth;
17921
+ this.onConnectorChanged = onConnectorChanged;
17642
17922
  this.maskChanged = maskChanged;
17643
17923
  this.mask = mask;
17644
17924
  }
@@ -17711,7 +17991,7 @@ var ConnectorOAuthCoordinator = class {
17711
17991
  for (const [key, record4] of this.presetFlows) if (record4.expiresAt < now) this.presetFlows.delete(key);
17712
17992
  }
17713
17993
  /** Starts OAuth for a curated preset without creating a database row until authorization succeeds. */
17714
- async startPreset(provider, redirectUri) {
17994
+ async startPreset(provider, redirectUri, name3) {
17715
17995
  this.prune();
17716
17996
  if (!this.driver.hasProvider(provider) || provider === "custom_mcp")
17717
17997
  throw new RuntimeFault("connector_missing", "Unknown connector preset", 404);
@@ -17722,6 +18002,7 @@ var ConnectorOAuthCoordinator = class {
17722
18002
  const vars = this.env.variables(provider).join(", ");
17723
18003
  throw new RuntimeFault("connector_client_missing", `Set ${vars} in the environment or .env and restart Jarvy`, 400);
17724
18004
  }
18005
+ const requestedName = typeof name3 === "string" && name3.trim() ? name3.trim().slice(0, 80) : void 0;
17725
18006
  const resolvedRedirect = this.resolveRedirectUri(redirectUri);
17726
18007
  const flowId = randomUUID22();
17727
18008
  try {
@@ -17732,12 +18013,13 @@ var ConnectorOAuthCoordinator = class {
17732
18013
  redirectUrl: resolvedRedirect
17733
18014
  });
17734
18015
  if (started.outcome === "authorized") {
17735
- const created = await this.createFromOAuth(provider, started.snapshot);
18016
+ const created = await this.createFromOAuth(provider, started.snapshot, requestedName);
17736
18017
  const state2 = { phase: "completed", flowId, connectorId: created.id };
17737
18018
  this.presetFlows.set(flowId, {
17738
18019
  provider,
17739
18020
  url: meta.defaultUrl,
17740
- name: meta.name,
18021
+ name: created.name,
18022
+ requestedName,
17741
18023
  redirectUri: resolvedRedirect,
17742
18024
  snapshot: started.snapshot,
17743
18025
  state: state2,
@@ -17751,14 +18033,15 @@ var ConnectorOAuthCoordinator = class {
17751
18033
  this.presetFlows.set(flowId, {
17752
18034
  provider,
17753
18035
  url: meta.defaultUrl,
17754
- name: meta.name,
18036
+ name: requestedName ?? meta.name,
18037
+ requestedName,
17755
18038
  redirectUri: resolvedRedirect,
17756
18039
  snapshot: started.snapshot,
17757
18040
  state,
17758
18041
  expiresAt
17759
18042
  });
17760
18043
  this.pending.set(started.state, {
17761
- target: { kind: "preset", flowId, provider, url: meta.defaultUrl, name: meta.name, snapshot: started.snapshot },
18044
+ target: { kind: "preset", flowId, provider, url: meta.defaultUrl, name: requestedName ?? meta.name, snapshot: started.snapshot },
17762
18045
  redirectUri: resolvedRedirect,
17763
18046
  expiresAt
17764
18047
  });
@@ -17767,11 +18050,12 @@ var ConnectorOAuthCoordinator = class {
17767
18050
  this.failOAuth(error, 400);
17768
18051
  }
17769
18052
  }
17770
- /** Starts OAuth for an already-created connector (Custom MCP, re-authentication, or in-chat request cards). */
18053
+ /** Starts OAuth for a Custom MCP connector (presets use immutable ephemeral flows: disconnect & add fresh to sign in again). */
17771
18054
  async start(id, redirectUri) {
17772
18055
  this.prune();
17773
18056
  const connector = this.store.connectors.get(id);
17774
18057
  if (!connector) throw new RuntimeFault("connector_missing", "Connector not found", 404);
18058
+ if (connector.provider !== "custom_mcp") this.failOAuth("Disconnect this connector and add it again to sign in", 400);
17775
18059
  if (connector.authKind !== "oauth") this.failOAuth("Connector does not use OAuth", 400);
17776
18060
  if (this.env.isManaged(connector.provider) && !this.env.client(connector.provider)) {
17777
18061
  const vars = this.env.variables(connector.provider).join(", ");
@@ -17793,10 +18077,8 @@ var ConnectorOAuthCoordinator = class {
17793
18077
  redirectUrl: resolvedRedirect
17794
18078
  });
17795
18079
  if (this.generation(id) !== startGen) this.failOAuth("Connector settings changed during sign-in. Start again.", 409);
17796
- this.saveOAuthSnapshot(id, creds, started.snapshot);
17797
18080
  if (started.outcome === "authorized") {
17798
- await this.afterAuth(id);
17799
- if (this.generation(id) !== startGen) this.failOAuth("Connector settings changed during sign-in. Start again.", 409);
18081
+ await this.commitExistingOAuth(id, startGen, live.url, creds, started.snapshot);
17800
18082
  const done2 = { phase: "completed", connectorId: id };
17801
18083
  this.states.set(id, done2);
17802
18084
  return done2;
@@ -17804,13 +18086,16 @@ var ConnectorOAuthCoordinator = class {
17804
18086
  const waiting = { phase: "waiting", connectorId: id, authUrl: started.authUrl, redirectUri: resolvedRedirect };
17805
18087
  this.clear(id);
17806
18088
  this.states.set(id, waiting);
17807
- this.pending.set(started.state, { target: { kind: "existing", connectorId: id, url: live.url, gen: startGen }, redirectUri: resolvedRedirect, expiresAt: Date.now() + FLOW_TTL_MS });
18089
+ this.pending.set(started.state, {
18090
+ target: { kind: "existing", connectorId: id, url: live.url, gen: startGen, snapshot: started.snapshot },
18091
+ redirectUri: resolvedRedirect,
18092
+ expiresAt: Date.now() + FLOW_TTL_MS
18093
+ });
17808
18094
  return waiting;
17809
18095
  } catch (error) {
17810
18096
  if (this.generation(id) !== startGen) this.failOAuth("Connector settings changed during sign-in. Start again.", 409);
17811
18097
  const message = this.mask(extractOAuthDetail(error));
17812
18098
  this.states.set(id, { phase: "error", connectorId: id, error: message });
17813
- this.store.connectors.update(id, { status: "error", statusDetail: message.slice(0, 300) });
17814
18099
  this.failOAuth(message, 400);
17815
18100
  }
17816
18101
  });
@@ -17856,7 +18141,7 @@ var ConnectorOAuthCoordinator = class {
17856
18141
  return { ok: false, name: connector.name, message: msg };
17857
18142
  }
17858
18143
  try {
17859
- await this.finishExistingCode(connector.id, flow.target.url, flow.target.gen, flow.redirectUri, query.code, query.iss);
18144
+ await this.finishExistingCode(connector.id, flow.target.url, flow.target.gen, flow.redirectUri, flow.target.snapshot, query.code, query.iss);
17860
18145
  return { ok: true, name: connector.name, message: "Connected. You can close this window and return to Jarvy." };
17861
18146
  } catch (error) {
17862
18147
  const msg = this.mask(error instanceof Error ? error.message : String(error));
@@ -17923,7 +18208,8 @@ var ConnectorOAuthCoordinator = class {
17923
18208
  const flow = this.consumePending(parsed, (target3) => target3.kind === "existing" && target3.connectorId === id);
17924
18209
  const expectedUrl = flow.target.kind === "existing" ? flow.target.url : connector.url;
17925
18210
  const expectedGen = flow.target.kind === "existing" ? flow.target.gen : this.generation(id);
17926
- await this.finishExistingCode(id, expectedUrl, expectedGen, flow.redirectUri, parsed.code, parsed.iss);
18211
+ const pendingSnapshot = flow.target.kind === "existing" ? flow.target.snapshot : void 0;
18212
+ await this.finishExistingCode(id, expectedUrl, expectedGen, flow.redirectUri, pendingSnapshot, parsed.code, parsed.iss);
17927
18213
  return this.status(id);
17928
18214
  }
17929
18215
  async finishPresetCode(flowId, code, iss) {
@@ -17939,7 +18225,8 @@ var ConnectorOAuthCoordinator = class {
17939
18225
  code,
17940
18226
  iss
17941
18227
  });
17942
- const created = await this.createFromOAuth(record4.provider, snapshot);
18228
+ const created = await this.createFromOAuth(record4.provider, snapshot, record4.requestedName);
18229
+ record4.name = created.name;
17943
18230
  record4.connectorId = created.id;
17944
18231
  record4.state = { phase: "completed", flowId, connectorId: created.id };
17945
18232
  } catch (error) {
@@ -17948,7 +18235,7 @@ var ConnectorOAuthCoordinator = class {
17948
18235
  this.failOAuth(msg, 400);
17949
18236
  }
17950
18237
  }
17951
- async finishExistingCode(id, expectedUrl, expectedGen, redirectUri, code, iss) {
18238
+ async finishExistingCode(id, expectedUrl, expectedGen, redirectUri, pendingSnapshot, code, iss) {
17952
18239
  await this.withLock(id, async () => {
17953
18240
  if (this.generation(id) !== expectedGen) this.failOAuth("Connector settings changed during authorization. Start again.", 409);
17954
18241
  const connector = this.store.connectors.get(id);
@@ -17960,7 +18247,7 @@ var ConnectorOAuthCoordinator = class {
17960
18247
  const snapshot = await this.driver.completeOAuth({
17961
18248
  provider: connector.provider,
17962
18249
  url: connector.url,
17963
- oauth: creds.oauth,
18250
+ oauth: pendingSnapshot ?? creds.oauth,
17964
18251
  ...this.client(connector.provider, creds),
17965
18252
  redirectUrl: redirectUri,
17966
18253
  code,
@@ -17969,22 +18256,44 @@ var ConnectorOAuthCoordinator = class {
17969
18256
  if (this.generation(id) !== expectedGen || this.store.connectors.get(id)?.url !== expectedUrl) {
17970
18257
  this.failOAuth("Connector settings changed during authorization. Start again.", 409);
17971
18258
  }
17972
- this.saveOAuthSnapshot(id, creds, snapshot);
17973
- await this.afterAuth(id);
17974
- if (this.generation(id) !== expectedGen) this.failOAuth("Connector settings changed during authorization. Start again.", 409);
18259
+ await this.commitExistingOAuth(id, expectedGen, expectedUrl, creds, snapshot);
17975
18260
  this.states.set(id, { phase: "completed", connectorId: id });
17976
18261
  } catch (error) {
17977
18262
  if (this.generation(id) !== expectedGen) this.failOAuth("Connector settings changed during authorization. Start again.", 409);
17978
18263
  const msg = this.mask(extractOAuthDetail(error));
17979
18264
  this.states.set(id, { phase: "error", connectorId: id, error: msg });
17980
- this.store.connectors.update(id, { status: "error", statusDetail: msg.slice(0, 300) });
17981
18265
  this.failOAuth(msg, 400);
17982
18266
  }
17983
18267
  });
17984
18268
  }
17985
- saveOAuthSnapshot(id, creds, snapshot) {
17986
- this.store.connectors.saveCredentials(id, "oauth", { ...creds, oauth: snapshot });
18269
+ /** Probes a newly exchanged OAuth snapshot for Custom MCP BEFORE saving; clears any prior Bot grants & pending cards so permissions never transfer across accounts. */
18270
+ async commitExistingOAuth(id, expectedGen, expectedUrl, creds, snapshot) {
18271
+ const live = this.store.connectors.get(id);
18272
+ if (!live) throw new RuntimeFault("connector_missing", "Connector not found", 404);
18273
+ const probed = await this.driver.probe({
18274
+ provider: live.provider,
18275
+ url: live.url,
18276
+ authKind: "oauth",
18277
+ oauth: snapshot,
18278
+ ...this.client(live.provider, creds),
18279
+ redirectUrl: this.defaultRedirectUri()
18280
+ });
18281
+ if (this.generation(id) !== expectedGen || this.store.connectors.get(id)?.url !== expectedUrl) {
18282
+ this.failOAuth("Connector settings changed during authorization. Start again.", 409);
18283
+ }
18284
+ if (probed.outcome !== "connected") this.failOAuth(probed.message, 400);
18285
+ const finalOAuth = "snapshot" in probed && probed.snapshot ? probed.snapshot : snapshot;
18286
+ const label = probed.accountLabel?.trim().slice(0, 120) ?? "";
18287
+ this.store.connectors.revokeAll(id);
18288
+ this.onConnectorChanged(id, "Connector credentials changed.");
18289
+ this.store.connectors.saveCredentials(id, "oauth", { ...creds, oauth: finalOAuth });
17987
18290
  this.maskChanged();
18291
+ this.store.connectors.update(id, {
18292
+ status: "connected",
18293
+ statusDetail: label,
18294
+ accountLabel: label || null,
18295
+ tools: probed.tools
18296
+ });
17988
18297
  }
17989
18298
  };
17990
18299
 
@@ -18034,14 +18343,38 @@ function cleanName(raw, fallback) {
18034
18343
  const name3 = raw.trim();
18035
18344
  return name3.slice(0, 80) || fallback;
18036
18345
  }
18346
+ function pickConnectorSlug(base, existing, hint) {
18347
+ if (!existing.has(base)) return base;
18348
+ if (hint) {
18349
+ const raw = hint.trim().replace(/^@+/, "");
18350
+ const local = raw.includes("@") ? raw.split("@")[0] : raw;
18351
+ const token2 = local.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
18352
+ if (token2 && token2 !== base) {
18353
+ const candidate = `${base}-${token2}`.slice(0, 48).replace(/-+$/, "");
18354
+ if (CONNECTOR_SLUG.test(candidate) && !existing.has(candidate)) return candidate;
18355
+ }
18356
+ }
18357
+ for (let n = 2; n < 100; n++) {
18358
+ const candidate = `${base}-${n}`;
18359
+ if (!existing.has(candidate)) return candidate;
18360
+ }
18361
+ return `${base}-${Date.now()}`;
18362
+ }
18363
+ function pickPresetName(defaultName, requested, accountLabel, existingForProvider) {
18364
+ const explicit = typeof requested === "string" ? requested.trim() : "";
18365
+ if (explicit) return cleanName(explicit, defaultName);
18366
+ if (existingForProvider === 0) return defaultName;
18367
+ if (accountLabel?.trim()) return `${defaultName} (${accountLabel.trim()})`.slice(0, 80);
18368
+ return `${defaultName} ${existingForProvider + 1}`;
18369
+ }
18037
18370
  function humanizeKey(raw) {
18038
18371
  return raw.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim().replace(/^\w/, (ch) => ch.toUpperCase());
18039
18372
  }
18040
18373
  var BODY_KEYS = /* @__PURE__ */ new Set(["description", "body", "content", "message", "text", "comment", "notes", "markdown", "html"]);
18041
18374
  function previewOf(text7) {
18042
- const firstLine = (text7.split("\n").find((line) => line.trim()) ?? text7).trim();
18043
- if (firstLine.length <= PREVIEW_CHARS && !text7.includes("\n")) return void 0;
18044
- return firstLine.length > PREVIEW_CHARS ? `${firstLine.slice(0, PREVIEW_CHARS - 1)}\u2026` : firstLine;
18375
+ const firstLine2 = (text7.split("\n").find((line) => line.trim()) ?? text7).trim();
18376
+ if (firstLine2.length <= PREVIEW_CHARS && !text7.includes("\n")) return void 0;
18377
+ return firstLine2.length > PREVIEW_CHARS ? `${firstLine2.slice(0, PREVIEW_CHARS - 1)}\u2026` : firstLine2;
18045
18378
  }
18046
18379
  function formatFieldValue(key, value2, masker) {
18047
18380
  const isBody = BODY_KEYS.has(key.toLowerCase());
@@ -18154,6 +18487,28 @@ function applyEdits(args, custom, schema, editableKeys) {
18154
18487
  }
18155
18488
  return next;
18156
18489
  }
18490
+ function buildAuthRequestQuestion(connector, purpose, binding) {
18491
+ const account = connector.account || (connector.status === "connected" ? connector.statusDetail : "");
18492
+ return {
18493
+ question: purpose,
18494
+ options: [
18495
+ { label: "Keep allowing", value: "always", style: "primary" },
18496
+ { label: "This time only", value: "once" }
18497
+ ],
18498
+ multiple: false,
18499
+ allowCustom: false,
18500
+ connectorAuth: {
18501
+ connectorId: connector.id,
18502
+ slug: connector.slug,
18503
+ name: connector.name,
18504
+ provider: connector.provider,
18505
+ purpose,
18506
+ ...account ? { account } : {},
18507
+ ...binding?.credFp ? { credFp: binding.credFp } : {},
18508
+ ...binding?.runId ? { runId: binding.runId } : {}
18509
+ }
18510
+ };
18511
+ }
18157
18512
  function buildWriteConfirmQuestion(connector, tool2, args, masker) {
18158
18513
  const fields = buildWriteFields(args, masker);
18159
18514
  const editableKeys = new Set(fields.filter((f) => f.editable === true).map((f) => f.key));
@@ -18166,8 +18521,7 @@ function buildWriteConfirmQuestion(connector, tool2, args, masker) {
18166
18521
  question: `${connector.name} \xB7 ${headline}`,
18167
18522
  options: [
18168
18523
  { label: "Confirm", value: "confirm", style: "primary" },
18169
- { label: "Discard", value: "discard" },
18170
- { label: "ConfirmAlways", value: "confirm_always" }
18524
+ { label: "Discard", value: "discard" }
18171
18525
  ],
18172
18526
  multiple: false,
18173
18527
  allowCustom: true,
@@ -18178,72 +18532,124 @@ function buildWriteConfirmQuestion(connector, tool2, args, masker) {
18178
18532
  provider: connector.provider,
18179
18533
  toolName: tool2.name,
18180
18534
  actionLabel,
18181
- ...connector.statusDetail ? { account: connector.statusDetail } : {},
18535
+ ...connector.account || connector.statusDetail ? { account: connector.account || connector.statusDetail } : {},
18182
18536
  fields
18183
18537
  }
18184
18538
  }
18185
18539
  };
18186
18540
  }
18187
- function filterUnconfirmedEntries(raw, tools) {
18188
- const byName = new Map(tools.map((tool2) => [tool2.name, tool2]));
18189
- const entries2 = [];
18190
- for (const item of raw) {
18191
- if (typeof item !== "string") continue;
18192
- const tool2 = byName.get(item.trim());
18193
- if (tool2 && isWriteTool(tool2)) entries2.push({ name: tool2.name, hash: toolDefinitionHash(tool2) });
18194
- }
18195
- return entries2;
18196
- }
18197
18541
  function formatConnectorList(all, granted, query) {
18198
18542
  const needle = query?.trim().toLowerCase() || "";
18199
18543
  const connectors = all.filter((c) => c.enabled).map((c) => {
18200
18544
  const matched2 = needle ? c.tools.filter((tool2) => tool2.name.toLowerCase().includes(needle) || (tool2.description ?? "").toLowerCase().includes(needle)) : c.tools;
18201
18545
  const compact = !needle && matched2.length > COMPACT_TOOL_THRESHOLD;
18546
+ const scope = granted.get(c.id);
18547
+ const account = c.status === "connected" ? c.account || c.statusDetail : "";
18202
18548
  return {
18203
18549
  slug: c.slug,
18204
18550
  name: c.name,
18205
18551
  provider: c.provider,
18206
- granted: granted.has(c.id),
18552
+ ...account ? { account } : {},
18553
+ granted: Boolean(scope),
18554
+ ...scope === "once" ? { until: "this run ends" } : {},
18207
18555
  status: c.status,
18208
18556
  toolCount: c.tools.length,
18209
- tools: matched2.map((tool2) => {
18210
- const write2 = isWriteTool(tool2);
18211
- return {
18212
- name: tool2.name,
18213
- ...!compact && tool2.description ? { description: tool2.description.slice(0, 140) } : {},
18214
- write: write2,
18215
- ...write2 ? { asksOwner: !c.unconfirmed.includes(tool2.name) } : {}
18216
- };
18217
- })
18557
+ tools: matched2.map((tool2) => ({
18558
+ name: tool2.name,
18559
+ ...!compact && tool2.description ? { description: tool2.description.slice(0, 140) } : {},
18560
+ write: isWriteTool(tool2)
18561
+ }))
18218
18562
  };
18219
18563
  });
18220
- const note = !connectors.length ? "No connectors configured yet. Ask your owner to add one in Settings \u2192 Connectors." : connectors.some((c) => !c.granted || c.status !== "connected") ? "Use connectors.request to ask your owner for access or sign-in when granted=false or status!=connected." : void 0;
18564
+ const hasDisconnected = connectors.some((c) => c.status !== "connected");
18565
+ const hasUngranted = connectors.some((c) => c.status === "connected" && !c.granted);
18566
+ const note = !connectors.length ? "No connectors configured yet. Ask your owner to add one in Settings \u2192 Connectors." : hasUngranted && hasDisconnected ? "Use connectors.request to ask your owner for access when granted=false on a connected connector. For disconnected connectors, ask your owner to reconnect them in Settings \u2192 Connectors." : hasUngranted ? "Use connectors.request to ask your owner for access (this time only or always) when granted=false." : hasDisconnected ? "Some connectors are not connected. Ask your owner to connect them in Settings \u2192 Connectors." : void 0;
18221
18567
  return { connectors, ...note ? { note } : {} };
18222
18568
  }
18223
18569
  function formatConnectorDescribe(connector, toolName, query) {
18224
18570
  const needle = query?.trim().toLowerCase() || "";
18225
18571
  const tools = toolName ? connector.tools.filter((tool2) => tool2.name === toolName) : needle ? connector.tools.filter((tool2) => tool2.name.toLowerCase().includes(needle) || (tool2.description ?? "").toLowerCase().includes(needle)) : connector.tools;
18226
18572
  if (toolName && !tools.length) throw new ChatError(404, `Connector "${connector.slug}" has no tool named "${toolName}"`);
18573
+ const account = connector.status === "connected" ? connector.account || connector.statusDetail : "";
18227
18574
  return {
18228
18575
  slug: connector.slug,
18229
18576
  name: connector.name,
18577
+ ...account ? { account } : {},
18230
18578
  status: connector.status,
18231
- tools: tools.map((tool2) => {
18232
- const write2 = isWriteTool(tool2);
18233
- return {
18234
- name: tool2.name,
18235
- ...tool2.title ? { title: tool2.title } : {},
18236
- ...tool2.description ? { description: tool2.description } : {},
18237
- write: write2,
18238
- ...write2 ? { asksOwner: !connector.unconfirmed.includes(tool2.name) } : {},
18239
- inputSchema: tool2.inputSchema
18240
- };
18579
+ tools: tools.map((tool2) => ({
18580
+ name: tool2.name,
18581
+ ...tool2.title ? { title: tool2.title } : {},
18582
+ ...tool2.description ? { description: tool2.description } : {},
18583
+ write: isWriteTool(tool2),
18584
+ inputSchema: tool2.inputSchema
18585
+ }))
18586
+ };
18587
+ }
18588
+
18589
+ // src/server/service/connectors-requests.ts
18590
+ function prepareConnectorAuthRequest(deps, botId, slug, purpose) {
18591
+ const connector = deps.store.connectors.bySlug(slug);
18592
+ if (!connector || !connector.enabled) throw new ChatError(404, `No enabled connector named "${slug}" (see connectors.list)`);
18593
+ if (connector.status !== "connected") {
18594
+ throw new ChatError(
18595
+ 409,
18596
+ `Connector "${slug}" is not connected (status: ${connector.status}). Ask your owner to connect it in Settings \u2192 Connectors.`,
18597
+ "connector_auth_required"
18598
+ );
18599
+ }
18600
+ if (deps.store.connectors.grantedIds(botId).has(connector.id)) return { ready: true };
18601
+ const runId = deps.store.connectors.currentRun(botId) ?? void 0;
18602
+ return {
18603
+ question: buildAuthRequestQuestion(connector, purpose, {
18604
+ credFp: connector.credFp,
18605
+ ...runId ? { runId } : {}
18241
18606
  })
18242
18607
  };
18243
18608
  }
18609
+ function fulfilConnectorAuth(deps, actorId, chatId, messageId, input) {
18610
+ const message = deps.chats.message(actorId, messageId);
18611
+ const ask = message?.question?.connectorAuth;
18612
+ if (!message || message.chatId !== chatId || !ask || message.question?.state !== "pending")
18613
+ throw new ChatError(409, "The question is already settled", "question_closed");
18614
+ if (!deps.chats.questions.waitingFor(messageId)) {
18615
+ deps.chats.questions.expire(chatId, messageId, "The question has expired");
18616
+ throw new ChatError(409, "The question has expired", "question_expired");
18617
+ }
18618
+ const scope = input?.scope === "always" || input?.scope === "once" ? input.scope : null;
18619
+ if (!scope) throw new ChatError(400, "scope must be always or once");
18620
+ const live = deps.store.connectors.get(ask.connectorId);
18621
+ if (!live || !live.enabled || live.status !== "connected") {
18622
+ deps.chats.questions.expire(chatId, messageId, "Connector is no longer connected.", "connector_disconnected");
18623
+ throw new ChatError(409, "Connector is no longer connected. Reconnect it in Settings \u2192 Connectors.", "question_expired");
18624
+ }
18625
+ const liveAccount = live.account || live.statusDetail || "";
18626
+ if (ask.credFp && ask.credFp !== live.credFp || (ask.account ?? "") !== liveAccount) {
18627
+ deps.chats.questions.expire(chatId, messageId, "Connector account or credentials changed.", "connector_disconnected");
18628
+ throw new ChatError(409, "Connector account or credentials changed before approval.", "question_expired");
18629
+ }
18630
+ const botId = message.sender.id;
18631
+ if (scope === "once") {
18632
+ if (!ask.runId || !deps.store.connectors.isRunLive(ask.runId, botId)) {
18633
+ deps.chats.questions.expire(chatId, messageId, "The requesting run has already ended.");
18634
+ throw new ChatError(409, "The requesting run has already ended.", "question_expired");
18635
+ }
18636
+ }
18637
+ return deps.chats.questions.respond(
18638
+ actorId,
18639
+ chatId,
18640
+ messageId,
18641
+ { action: "answer", selected: [scope === "once" ? 1 : 0] },
18642
+ () => deps.store.connectors.grant(live.id, botId, scope, scope === "once" ? ask.runId : null)
18643
+ );
18644
+ }
18244
18645
 
18245
18646
  // src/server/service/connectors.ts
18246
18647
  var MAX_TOOL_TEXT = 32e3;
18648
+ function sameHeaders(a, b) {
18649
+ const entriesA = Object.entries(a ?? {});
18650
+ const entriesB = Object.entries(b ?? {});
18651
+ return entriesA.length === entriesB.length && entriesA.every(([key, value2]) => (b ?? {})[key] === value2);
18652
+ }
18247
18653
  var ConnectorService = class {
18248
18654
  constructor(store, chats, secrets, driver, listening, env) {
18249
18655
  this.store = store;
@@ -18258,9 +18664,8 @@ var ConnectorService = class {
18258
18664
  env,
18259
18665
  (id, work) => this.withLock(id, work),
18260
18666
  (id) => this.generation(id),
18261
- (id) => this.probeLocked(id).then(() => {
18262
- }),
18263
- (provider, snapshot) => this.createFromOAuth(provider, snapshot),
18667
+ (provider, snapshot, name3) => this.createFromOAuth(provider, snapshot, name3),
18668
+ (id, reason) => this.chats.questions.expireByConnector(id, reason, "connector_disconnected"),
18264
18669
  () => this.secrets.refreshMask(),
18265
18670
  (text7) => this.secrets.masker().mask(text7)
18266
18671
  );
@@ -18313,8 +18718,10 @@ var ConnectorService = class {
18313
18718
  const msg = this.secrets.masker().mask(probe2.message).slice(0, 300);
18314
18719
  throw new RuntimeFault(probe2.outcome === "needs_auth" ? "connector_auth_required" : "connector_unreachable", msg, 400);
18315
18720
  }
18316
- const slug = this.freeSlug(meta.id);
18317
- const name3 = cleanName(input.name, meta.name);
18721
+ const existing = this.store.connectors.list();
18722
+ const accountLabel = probe2.accountLabel?.slice(0, 120);
18723
+ const slug = pickConnectorSlug(meta.id, new Set(existing.map((c) => c.slug)), accountLabel ?? (typeof input.name === "string" ? input.name : void 0));
18724
+ const name3 = pickPresetName(meta.name, input.name, accountLabel, existing.filter((c) => c.provider === meta.id).length);
18318
18725
  const created = this.store.connectors.create({
18319
18726
  slug,
18320
18727
  name: name3,
@@ -18324,34 +18731,50 @@ var ConnectorService = class {
18324
18731
  authKind: "headers",
18325
18732
  enabled: true,
18326
18733
  status: "connected",
18327
- statusDetail: probe2.accountLabel?.slice(0, 120) ?? "",
18734
+ statusDetail: accountLabel ?? "",
18328
18735
  tools: probe2.tools,
18329
18736
  credentials: { headers: headers2 }
18330
18737
  });
18331
18738
  this.secrets.refreshMask();
18332
18739
  return created;
18333
18740
  }
18334
- async createFromOAuth(provider, snapshot) {
18741
+ async createFromOAuth(provider, snapshot, requestedName) {
18335
18742
  const meta = this.driver.meta(provider);
18336
- const slug = this.freeSlug(provider);
18743
+ const probed = await this.driver.probe({
18744
+ provider,
18745
+ url: meta.defaultUrl,
18746
+ authKind: "oauth",
18747
+ oauth: snapshot,
18748
+ ...this.env.isManaged(provider) ? this.env.client(provider) ?? {} : {},
18749
+ redirectUrl: this.oauth.defaultRedirectUri()
18750
+ });
18751
+ const finalOAuth = "snapshot" in probed && probed.snapshot ? probed.snapshot : snapshot;
18752
+ const existing = this.store.connectors.list();
18753
+ const accountLabel = probed.outcome === "connected" ? probed.accountLabel?.slice(0, 120) : void 0;
18754
+ const slug = pickConnectorSlug(provider, new Set(existing.map((c) => c.slug)), accountLabel ?? requestedName);
18755
+ const name3 = pickPresetName(meta.name, requestedName, accountLabel, existing.filter((c) => c.provider === provider).length);
18756
+ const status = probed.outcome === "connected" ? "connected" : probed.outcome === "needs_auth" ? "needs_auth" : "error";
18757
+ const statusDetail = probed.outcome === "connected" ? accountLabel ?? "" : this.secrets.masker().mask(probed.message).slice(0, 300);
18337
18758
  const created = this.store.connectors.create({
18338
18759
  slug,
18339
- name: meta.name,
18760
+ name: name3,
18340
18761
  kind: meta.kind,
18341
18762
  provider,
18342
18763
  url: meta.defaultUrl,
18343
18764
  authKind: "oauth",
18344
18765
  enabled: true,
18345
- status: "needs_auth",
18346
- credentials: { oauth: snapshot }
18766
+ status,
18767
+ statusDetail,
18768
+ tools: probed.outcome === "connected" ? probed.tools : [],
18769
+ credentials: { oauth: finalOAuth }
18347
18770
  });
18348
18771
  this.secrets.refreshMask();
18349
- return this.probeLocked(created.id);
18772
+ return created;
18350
18773
  }
18351
18774
  async create(input) {
18352
18775
  const provider = typeof input.provider === "string" && this.driver.hasProvider(input.provider) ? input.provider : "custom_mcp";
18353
18776
  const meta = this.driver.meta(provider);
18354
- const slug = input.slug !== void 0 && input.slug !== "" ? cleanSlug(input.slug) : this.freeSlug(provider !== "custom_mcp" ? provider : "mcp");
18777
+ const slug = input.slug !== void 0 && input.slug !== "" ? cleanSlug(input.slug) : pickConnectorSlug(provider !== "custom_mcp" ? provider : "mcp", new Set(this.store.connectors.list().map((c) => c.slug)), typeof input.name === "string" ? input.name : void 0);
18355
18778
  const name3 = cleanName(input.name, meta.name || slug);
18356
18779
  const url = cleanUrl(provider !== "custom_mcp" ? meta.defaultUrl : input.url ?? meta.defaultUrl);
18357
18780
  const requestedAuth = typeof input.authKind === "string" && meta.authMethods.includes(input.authKind) ? input.authKind : void 0;
@@ -18396,16 +18819,29 @@ var ConnectorService = class {
18396
18819
  const enabled = typeof input.enabled === "boolean" ? input.enabled : void 0;
18397
18820
  const headers2 = input.headers !== void 0 ? cleanHeaders(input.headers) : void 0;
18398
18821
  const own3 = !this.env.isManaged(current.provider);
18399
- const credsChanged = urlChanged || authChanged || headers2 !== void 0 || own3 && (input.clientId !== void 0 || input.clientSecret !== void 0);
18822
+ if (current.provider !== "custom_mcp") {
18823
+ const presetCredAttempt = urlChanged || authChanged || headers2 !== void 0 || own3 && (input.clientId !== void 0 || input.clientSecret !== void 0);
18824
+ if (presetCredAttempt) {
18825
+ throw new ValidationError("Preset connector credentials cannot be changed; disconnect and connect again", "connector_auth_required");
18826
+ }
18827
+ }
18828
+ const prior = current.provider === "custom_mcp" ? this.store.connectors.credentials(id) ?? {} : {};
18829
+ const nextClientId = own3 && input.clientId !== void 0 ? typeof input.clientId === "string" && input.clientId.trim() ? input.clientId.trim() : void 0 : prior.clientId;
18830
+ const nextClientSecret = own3 && input.clientSecret !== void 0 ? typeof input.clientSecret === "string" && input.clientSecret.trim() ? input.clientSecret.trim() : void 0 : prior.clientSecret;
18831
+ const headersChanged = headers2 !== void 0 && !sameHeaders(headers2, prior.headers);
18832
+ const clientIdChanged = own3 && input.clientId !== void 0 && nextClientId !== prior.clientId;
18833
+ const clientSecretChanged = own3 && input.clientSecret !== void 0 && nextClientSecret !== prior.clientSecret;
18834
+ const credsChanged = current.provider === "custom_mcp" && (urlChanged || authChanged || headersChanged || clientIdChanged || clientSecretChanged);
18400
18835
  if (urlChanged) {
18401
18836
  this.bumpGeneration(id);
18402
18837
  this.oauth.clear(id);
18838
+ this.store.connectors.revokeAll(id);
18403
18839
  this.store.connectors.saveCredentials(id, nextAuth, {});
18404
- this.store.connectors.setUnconfirmed(id, []);
18405
18840
  this.secrets.refreshMask();
18841
+ this.chats.questions.expireByConnector(id, "Connector destination changed.", "connector_disconnected");
18406
18842
  } else if (credsChanged) {
18407
18843
  this.bumpGeneration(id);
18408
- const prior = this.store.connectors.credentials(id) ?? {};
18844
+ this.store.connectors.revokeAll(id);
18409
18845
  const next = { ...prior };
18410
18846
  if (authChanged) {
18411
18847
  if (nextAuth !== "headers") delete next.headers;
@@ -18414,27 +18850,31 @@ var ConnectorService = class {
18414
18850
  this.oauth.clear(id);
18415
18851
  }
18416
18852
  }
18417
- if (headers2 !== void 0 && nextAuth === "headers") next.headers = headers2;
18418
- if (own3 && input.clientId !== void 0) {
18419
- if (typeof input.clientId === "string" && input.clientId.trim()) next.clientId = input.clientId.trim();
18853
+ if (headers2 !== void 0 && nextAuth === "headers") {
18854
+ if (Object.keys(headers2).length) next.headers = headers2;
18855
+ else delete next.headers;
18856
+ }
18857
+ if (clientIdChanged) {
18858
+ if (nextClientId) next.clientId = nextClientId;
18420
18859
  else delete next.clientId;
18421
18860
  }
18422
- if (own3 && input.clientSecret !== void 0) {
18423
- if (typeof input.clientSecret === "string" && input.clientSecret.trim()) next.clientSecret = input.clientSecret.trim();
18861
+ if (clientSecretChanged) {
18862
+ if (nextClientSecret) next.clientSecret = nextClientSecret;
18424
18863
  else delete next.clientSecret;
18425
18864
  }
18426
18865
  this.store.connectors.saveCredentials(id, nextAuth, next);
18427
18866
  this.secrets.refreshMask();
18867
+ this.chats.questions.expireByConnector(id, "Connector credentials changed.", "connector_disconnected");
18428
18868
  }
18429
- if (!urlChanged && Array.isArray(input.unconfirmed)) {
18430
- this.store.connectors.setUnconfirmed(id, filterUnconfirmedEntries(input.unconfirmed, current.tools));
18869
+ if (enabled === false) {
18870
+ this.chats.questions.expireByConnector(id, "Connector was disabled.", "connector_disconnected");
18431
18871
  }
18432
18872
  const updated = this.store.connectors.update(id, {
18433
18873
  ...name3 !== void 0 ? { name: name3 } : {},
18434
18874
  ...url !== void 0 ? { url } : {},
18435
18875
  ...authKind !== void 0 ? { authKind } : {},
18436
18876
  ...enabled !== void 0 ? { enabled } : {},
18437
- ...urlChanged ? { status: nextAuth === "none" ? "disconnected" : "needs_auth", statusDetail: "", tools: [] } : authChanged && nextAuth === "oauth" ? { status: "needs_auth", statusDetail: "" } : {}
18877
+ ...urlChanged ? { status: nextAuth === "none" ? "disconnected" : "needs_auth", statusDetail: "", accountLabel: null, tools: [] } : authChanged && nextAuth === "oauth" ? { status: "needs_auth", statusDetail: "" } : {}
18438
18878
  }) ?? this.missing();
18439
18879
  if (!urlChanged && credsChanged && updated.authKind !== "oauth") return this.probe(id).catch(() => this.get(id));
18440
18880
  return updated;
@@ -18444,12 +18884,17 @@ var ConnectorService = class {
18444
18884
  this.oauth.clear(id);
18445
18885
  if (!this.store.connectors.delete(id)) this.missing();
18446
18886
  this.secrets.refreshMask();
18887
+ this.chats.questions.expireByConnector(id, "Connector was disconnected.", "connector_disconnected");
18447
18888
  }
18448
18889
  grant(id, botId, granted) {
18449
18890
  this.get(id);
18450
18891
  if (!this.store.bots.get(botId)) throw new RuntimeFault("bot_missing", "Bot not found", 404);
18451
- if (granted) this.store.connectors.grant(id, botId);
18452
- else this.store.connectors.revoke(id, botId);
18892
+ if (granted) {
18893
+ this.store.connectors.grant(id, botId);
18894
+ } else {
18895
+ this.store.connectors.revoke(id, botId);
18896
+ this.chats.questions.expireByConnector(id, "Connector access was revoked.", "connector_revoked", botId);
18897
+ }
18453
18898
  return this.get(id);
18454
18899
  }
18455
18900
  uses(id) {
@@ -18464,6 +18909,7 @@ var ConnectorService = class {
18464
18909
  const current = this.get(id);
18465
18910
  this.bumpGeneration(id);
18466
18911
  this.oauth.clear(id);
18912
+ this.store.connectors.revokeAll(id);
18467
18913
  const creds = this.store.connectors.credentials(id) ?? {};
18468
18914
  const next = {
18469
18915
  ...creds.clientId ? { clientId: creds.clientId } : {},
@@ -18471,6 +18917,7 @@ var ConnectorService = class {
18471
18917
  };
18472
18918
  this.store.connectors.saveCredentials(id, current.authKind, next);
18473
18919
  this.secrets.refreshMask();
18920
+ this.chats.questions.expireByConnector(id, "Connector was disconnected.", "connector_disconnected");
18474
18921
  return this.store.connectors.update(id, {
18475
18922
  status: current.authKind === "oauth" ? "needs_auth" : "disconnected",
18476
18923
  statusDetail: "",
@@ -18504,59 +18951,62 @@ var ConnectorService = class {
18504
18951
  return this.store.connectors.update(id, { status: "connected", statusDetail: result.accountLabel?.slice(0, 120) ?? "", tools: result.tools });
18505
18952
  }
18506
18953
  const detail = this.secrets.masker().mask(result.message).slice(0, 300);
18507
- return this.store.connectors.update(id, { status: result.outcome === "needs_auth" ? "needs_auth" : "error", statusDetail: detail });
18954
+ const failed = this.store.connectors.update(id, { status: result.outcome === "needs_auth" ? "needs_auth" : "error", statusDetail: detail });
18955
+ this.chats.questions.expireByConnector(id, "Connector is no longer connected.", "connector_disconnected");
18956
+ return failed;
18508
18957
  }
18509
18958
  /** connectors.list: compact summary when a connector exposes many tools; supports optional keyword filtering. */
18510
18959
  listFor(botId, query) {
18511
- return formatConnectorList(this.store.connectors.list(), this.store.connectors.grantedIds(botId), query);
18960
+ return formatConnectorList(this.store.connectors.list(), this.store.connectors.grantedTo(botId), query);
18512
18961
  }
18513
18962
  /** connectors.describe: full tool schemas for one granted connector, filterable by exact tool name or keyword query. */
18514
18963
  describeFor(botId, slug, toolName, query) {
18515
18964
  return formatConnectorDescribe(this.requireGranted(botId, slug), toolName, query);
18516
18965
  }
18517
- /** connectors.call: invokes a tool on a granted connector; write tools ask on a card unless fingerprinted as unconfirmed. */
18966
+ /** connectors.call: invokes a tool on a granted connector; every write tool requires owner confirmation on a card. */
18518
18967
  async callTool(botId, chatId, slug, toolName, args, ask, hasPerson, signal) {
18519
18968
  const initial = this.requireGranted(botId, slug);
18520
18969
  if (initial.status !== "connected") {
18521
- throw new ChatError(409, `Connector "${slug}" is not connected (status: ${initial.status}). Ask your owner with connectors.request.`, "connector_auth_required");
18970
+ throw new ChatError(409, `Connector "${slug}" is not connected (status: ${initial.status}). Ask your owner to connect it in Settings \u2192 Connectors.`, "connector_auth_required");
18522
18971
  }
18523
18972
  const initialTool = initial.tools.find((item) => item.name === toolName);
18524
18973
  if (!initialTool) throw new ChatError(404, `Connector "${slug}" has no tool named "${toolName}" (check connectors.describe)`);
18525
18974
  let confirmed2 = null;
18526
- if (isWriteTool(initialTool) && !this.store.connectors.isUnconfirmed(initial.id, initialTool)) {
18975
+ if (isWriteTool(initialTool)) {
18527
18976
  if (!hasPerson()) {
18528
18977
  this.store.connectors.recordUse({ connectorId: initial.id, slug: initial.slug, botId, toolName, outcome: "denied", detail: "no person to confirm write" });
18529
- throw new ChatError(409, `"${toolName}" on "${slug}" asks the owner before running, and no person is in this chat. Ask them in a chat with them, or they can turn confirmation off for this tool in Settings \u2192 Connectors.`);
18978
+ throw new ChatError(409, `"${toolName}" on "${slug}" requires the owner's confirmation, and no person is in this chat. Ask them in a chat with them.`);
18530
18979
  }
18531
18980
  const binding = {
18532
18981
  url: initial.url,
18533
18982
  authKind: initial.authKind,
18534
- account: initial.statusDetail,
18535
- credFp: this.store.connectors.credentialFingerprint(initial.id),
18536
- toolHash: toolDefinitionHash(initialTool)
18983
+ account: initial.account || initial.statusDetail,
18984
+ credFp: initial.credFp
18537
18985
  };
18538
18986
  const { question, editableKeys } = buildWriteConfirmQuestion(initial, initialTool, args, this.secrets.masker());
18539
18987
  const result = await ask(question);
18540
18988
  const picked = result.status === "answered" ? result.selected[0]?.value : void 0;
18541
- if (picked !== "confirm" && picked !== "confirm_always") {
18989
+ if (picked !== "confirm") {
18542
18990
  this.store.connectors.recordUse({ connectorId: initial.id, slug: initial.slug, botId, toolName, outcome: "denied", detail: "declined" });
18543
18991
  return { connector: slug, tool: toolName, status: "declined", note: "Your owner declined this write action." };
18544
18992
  }
18545
- confirmed2 = { ...binding, messageId: result.messageId, always: picked === "confirm_always", custom: result.status === "answered" ? result.custom : null, editableKeys };
18993
+ confirmed2 = { ...binding, messageId: result.messageId, custom: result.status === "answered" ? result.custom : null, editableKeys };
18546
18994
  }
18547
18995
  const res = await this.withLock(initial.id, async () => {
18548
18996
  const live = this.store.connectors.get(initial.id);
18549
18997
  const liveTool = live?.tools.find((item) => item.name === toolName);
18550
18998
  const granted = Boolean(live && this.store.connectors.grantedIds(botId).has(live.id));
18551
18999
  const liveValid = Boolean(live && live.enabled && live.status === "connected" && granted && liveTool);
18552
- const bindingValid = !confirmed2 || liveValid && live.url === confirmed2.url && live.authKind === confirmed2.authKind && live.statusDetail === confirmed2.account && this.store.connectors.credentialFingerprint(live.id) === confirmed2.credFp && toolDefinitionHash(liveTool) === confirmed2.toolHash;
19000
+ const liveAccount = live ? live.account || live.statusDetail : "";
19001
+ const bindingValid = !confirmed2 || liveValid && live.url === confirmed2.url && live.authKind === confirmed2.authKind && liveAccount === confirmed2.account && live.credFp === confirmed2.credFp;
18553
19002
  if (!liveValid || !bindingValid) {
18554
- if (confirmed2) this.chats.questions.invalidate(chatId, confirmed2.messageId);
19003
+ const expiredReason = live && live.enabled && live.status === "connected" && !granted ? "connector_revoked" : "connector_disconnected";
19004
+ if (confirmed2) this.chats.questions.invalidate(chatId, confirmed2.messageId, expiredReason);
18555
19005
  this.store.connectors.recordUse({ connectorId: initial.id, slug: initial.slug, botId, toolName, outcome: "denied", detail: "confirmation expired: connector changed" });
18556
- throw new ChatError(409, `Confirmation for "${toolName}" on "${slug}" expired because connector access, settings, account or tool definition changed. Check connectors.list and ask again if still needed.`, "question_expired");
19006
+ throw new ChatError(409, `Confirmation for "${toolName}" on "${slug}" expired because connector access, settings or connection state changed. Check connectors.list and ask again if still needed.`, "question_expired");
18557
19007
  }
18558
- if (!confirmed2 && isWriteTool(liveTool) && !this.store.connectors.isUnconfirmed(live.id, liveTool)) {
18559
- throw new ChatError(409, `"${toolName}" on "${slug}" now requires owner confirmation. Call connectors.call again.`, "question_expired");
19008
+ if (!confirmed2 && isWriteTool(liveTool)) {
19009
+ throw new ChatError(409, `"${toolName}" on "${slug}" requires owner confirmation. Call connectors.call again.`, "question_expired");
18560
19010
  }
18561
19011
  let finalArgs = args;
18562
19012
  if (confirmed2?.custom) {
@@ -18569,11 +19019,10 @@ var ConnectorService = class {
18569
19019
  }
18570
19020
  const creds = this.store.connectors.credentials(live.id);
18571
19021
  if (creds === null) {
18572
- if (confirmed2) this.chats.questions.invalidate(chatId, confirmed2.messageId);
19022
+ if (confirmed2) this.chats.questions.invalidate(chatId, confirmed2.messageId, "connector_disconnected");
18573
19023
  throw new ChatError(409, "Connector credentials cannot be decrypted", "credential_unreadable");
18574
19024
  }
18575
19025
  const startGen = this.generation(live.id);
18576
- if (confirmed2?.always) this.store.connectors.allowUnconfirmed(live.id, liveTool.name, confirmed2.toolHash);
18577
19026
  const out2 = await this.driver.callTool({
18578
19027
  provider: live.provider,
18579
19028
  url: live.url,
@@ -18595,9 +19044,12 @@ var ConnectorService = class {
18595
19044
  const { out, stale } = res;
18596
19045
  if (out.outcome === "needs_auth") {
18597
19046
  const masked = this.secrets.masker().mask(out.message);
18598
- if (!stale) this.store.connectors.update(initial.id, { status: "needs_auth", statusDetail: masked.slice(0, 300) });
19047
+ if (!stale) {
19048
+ this.store.connectors.update(initial.id, { status: "needs_auth", statusDetail: masked.slice(0, 300) });
19049
+ this.chats.questions.expireByConnector(initial.id, "Connector needs re-authorization.", "connector_disconnected");
19050
+ }
18599
19051
  this.store.connectors.recordUse({ connectorId: initial.id, slug: initial.slug, botId, toolName, outcome: "error", detail: masked });
18600
- throw new ChatError(409, `Connector "${slug}" needs re-authorization (${masked}). Ask your owner with connectors.request.`, "connector_auth_required");
19052
+ throw new ChatError(409, `Connector "${slug}" needs re-authorization (${masked}). Ask your owner to reconnect it in Settings \u2192 Connectors.`, "connector_auth_required");
18601
19053
  }
18602
19054
  if (out.outcome === "error") {
18603
19055
  const masked = this.secrets.masker().mask(out.message);
@@ -18617,54 +19069,13 @@ var ConnectorService = class {
18617
19069
  });
18618
19070
  return { connector: slug, tool: toolName, isError: out.isError, text: text7 };
18619
19071
  }
18620
- /** connectors.request: returns immediately if granted & connected, else prepares an in-chat auth/grant card. */
19072
+ /** connectors.request: returns immediately if granted & connected, else prepares an in-chat grant card. */
18621
19073
  async prepareRequest(botId, slug, purpose) {
18622
- const connector = this.store.connectors.bySlug(slug);
18623
- if (!connector || !connector.enabled) throw new ChatError(404, `No enabled connector named "${slug}" (see connectors.list)`);
18624
- let current = connector;
18625
- if (current.authKind !== "oauth" && current.status === "disconnected") current = await this.probe(current.id);
18626
- const granted = this.store.connectors.grantedIds(botId).has(current.id);
18627
- const needsAuth = current.status !== "connected";
18628
- if (granted && !needsAuth) return { ready: true };
18629
- if (needsAuth && current.authKind === "oauth" && this.env.isManaged(current.provider) && !this.env.client(current.provider)) {
18630
- const variables = this.env.variables(current.provider).join(" and ");
18631
- const meta = this.driver.meta(current.provider);
18632
- throw new ChatError(409, meta.authMethods.includes("headers") ? `Connector "${slug}" is not connected. The owner connects it in Settings \u2192 Connectors with a token, or sets ${variables} for Jarvy to sign in on the web. Tell them.` : `Connector "${slug}" can't sign in yet: the owner has to set ${variables} for Jarvy and restart it. Tell them.`, "connector_client_missing");
18633
- }
18634
- return {
18635
- question: {
18636
- question: purpose,
18637
- options: [{ label: "Allow", value: "allow", style: "primary" }],
18638
- multiple: false,
18639
- allowCustom: false,
18640
- connectorAuth: {
18641
- connectorId: current.id,
18642
- slug: current.slug,
18643
- name: current.name,
18644
- provider: current.provider,
18645
- purpose,
18646
- authKind: current.authKind,
18647
- needsGrant: !granted,
18648
- needsAuth
18649
- }
18650
- }
18651
- };
19074
+ return prepareConnectorAuthRequest({ store: this.store, chats: this.chats }, botId, slug, purpose);
18652
19075
  }
18653
- /** Settles an in-chat connectorAuth card once authorized and grants access to the Bot. */
18654
- async fulfilAuth(actorId, chatId, messageId) {
18655
- const message = this.chats.message(actorId, messageId);
18656
- const ask = message?.question?.connectorAuth;
18657
- if (!message || message.chatId !== chatId || !ask || message.question?.state !== "pending")
18658
- throw new ChatError(409, "The question is already settled", "question_closed");
18659
- if (!this.chats.questions.waitingFor(messageId))
18660
- throw new ChatError(409, "The question has expired", "question_expired");
18661
- let connector = this.get(ask.connectorId);
18662
- if (connector.status !== "connected") connector = await this.probe(connector.id);
18663
- if (connector.status !== "connected") {
18664
- throw new ChatError(409, connector.statusDetail || "Connector is not connected yet", "connector_auth_required");
18665
- }
18666
- this.store.connectors.grant(connector.id, message.sender.id);
18667
- return this.chats.questions.respond(actorId, chatId, messageId, { action: "answer", selected: [0] });
19076
+ /** Settles an in-chat connectorAuth card after synchronously verifying account, credentials and requesting run. */
19077
+ fulfilAuth(actorId, chatId, messageId, input) {
19078
+ return fulfilConnectorAuth({ store: this.store, chats: this.chats }, actorId, chatId, messageId, input);
18668
19079
  }
18669
19080
  requireGranted(botId, slug) {
18670
19081
  const connector = this.store.connectors.bySlug(slug);
@@ -18684,15 +19095,6 @@ var ConnectorService = class {
18684
19095
  if (this.locks.get(id) === next) this.locks.delete(id);
18685
19096
  }
18686
19097
  }
18687
- freeSlug(base) {
18688
- const existing = new Set(this.store.connectors.list().map((c) => c.slug));
18689
- if (!existing.has(base)) return base;
18690
- for (let n = 2; n < 100; n++) {
18691
- const candidate = `${base}-${n}`;
18692
- if (!existing.has(candidate)) return candidate;
18693
- }
18694
- return `${base}-${Date.now()}`;
18695
- }
18696
19098
  clientOf(connector, creds) {
18697
19099
  if (this.env.isManaged(connector.provider)) return this.env.client(connector.provider) ?? {};
18698
19100
  return { ...creds.clientId ? { clientId: creds.clientId } : {}, ...creds.clientSecret ? { clientSecret: creds.clientSecret } : {} };
@@ -19262,7 +19664,7 @@ async function startOAuth2(input) {
19262
19664
  authUrl.searchParams.set("response_type", "code");
19263
19665
  authUrl.searchParams.set("scope", "https://www.googleapis.com/auth/gmail.modify");
19264
19666
  authUrl.searchParams.set("access_type", "offline");
19265
- authUrl.searchParams.set("prompt", "consent");
19667
+ authUrl.searchParams.set("prompt", "select_account consent");
19266
19668
  authUrl.searchParams.set("state", state);
19267
19669
  return { outcome: "redirect", authUrl: authUrl.toString(), state, snapshot: { serverUrl: input.url, oauthState: state } };
19268
19670
  }
@@ -19551,7 +19953,7 @@ var Application = class _Application {
19551
19953
  });
19552
19954
  this.auth = new CredentialLogins(store, this.credentials, (id) => this.bots.connectionChanged(id));
19553
19955
  this.connection = new ConnectionService(store, dataDir);
19554
- this.account = new AccountService(store, createHash17("sha256").update(dataDir).digest("hex").slice(0, 10));
19956
+ this.account = new AccountService(store, createHash16("sha256").update(dataDir).digest("hex").slice(0, 10));
19555
19957
  this.models = new ModelService(store, this.credentials, this.auth, (id) => this.bots.connectionChanged(id), catalog);
19556
19958
  }
19557
19959
  events = new Changes();