@homingbird/mcp 0.3.1 → 0.3.2

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.
@@ -8,7 +8,7 @@ var __export = (target2, all3) => {
8
8
  // src/stdio.ts
9
9
  import { spawn as spawn2 } from "node:child_process";
10
10
  import { randomBytes as randomBytes2, randomInt } from "node:crypto";
11
- import { homedir, hostname } from "node:os";
11
+ import { homedir } from "node:os";
12
12
 
13
13
  // ../kernel/src/data.ts
14
14
  var tagged = (tag) => () => {
@@ -1070,49 +1070,414 @@ var makeSemaphore = (permits) => {
1070
1070
  var makeMutex = () => makeSemaphore(1);
1071
1071
  var QueueClosed = tagged("QueueClosed")();
1072
1072
 
1073
+ // ../cli/src/antigravity.ts
1074
+ var antigravityInput = (prompt) => `${JSON.stringify({ event: "user", message: { role: "user", content: [{ type: "text", text: prompt }] } })}
1075
+ `;
1076
+ var antigravityOutput = (printed) => {
1077
+ let response = null;
1078
+ for (const line of printed.split(/\r?\n/)) {
1079
+ const value = parsedJson(line);
1080
+ const event2 = StreamEvent.read(value);
1081
+ if (event2._tag === "Err" || event2.value.event !== "result") continue;
1082
+ const result2 = ResultEvent.read(value);
1083
+ if (result2._tag === "Err") return result_exports.err("printed a result event without a status");
1084
+ const { status: status2, response: said2 } = result2.value.result;
1085
+ if (status2 !== "SUCCESS") return result_exports.err(`reported ${statusLabel(status2)} instead of a response`);
1086
+ if (said2 === void 0) return result_exports.err("printed a result event without a response");
1087
+ response = said2;
1088
+ }
1089
+ return response === null ? result_exports.err("printed no result event") : result_exports.ok(response);
1090
+ };
1091
+ var ANTIGRAVITY_PRINT = [
1092
+ ...["agy", "--print=", "--input-format=stream-json", "--output-format=stream-json", "--sandbox"]
1093
+ ];
1094
+ var ANTIGRAVITY_READER_SETTINGS = {
1095
+ toolPermission: "request-review",
1096
+ permissions: {
1097
+ deny: ["read_file(*)", "write_file(*)", "command(*)", "mcp(*)", "read_url(*)", "execute_url(*)"]
1098
+ }
1099
+ };
1100
+ var StreamEvent = schema_exports.struct({ event: schema_exports.string() });
1101
+ var ResultEvent = schema_exports.struct({
1102
+ result: schema_exports.struct({ status: schema_exports.string(), response: schema_exports.optional(schema_exports.string()) })
1103
+ });
1104
+ var statusLabel = (status2) => /^[A-Z_]{1,40}$/.test(status2) ? status2 : "a failure";
1105
+ var parsedJson = (line) => {
1106
+ try {
1107
+ return JSON.parse(line);
1108
+ } catch {
1109
+ return null;
1110
+ }
1111
+ };
1112
+
1073
1113
  // ../cli/src/agent-presets.ts
1074
- var presetReader = (preset, platform) => preset.reader === null || platform !== "win32" ? preset.reader : preset.reader.replace(/''/g, '""');
1114
+ var presetAgent = (preset, platform) => shellCommand(preset.agent.words, platform);
1115
+ var presetReader = (preset, platform) => preset.reader === null ? null : shellCommand(preset.reader.words, platform);
1116
+ var presetCommandOf = (command2, platform) => {
1117
+ for (const preset of AGENT_PRESETS)
1118
+ for (const role of ROLES) {
1119
+ const launch = preset[role];
1120
+ if (launch !== null && shellCommand(launch.words, platform) === command2.trim())
1121
+ return { preset, role, launch };
1122
+ }
1123
+ return null;
1124
+ };
1075
1125
  var isReaderWithSomeTools = (reader) => AGENT_PRESETS.some(
1076
- (preset) => preset.readerTools === "minimal" && ["linux", "win32"].some((platform) => presetReader(preset, platform) === reader.trim())
1126
+ (preset) => preset.readerTools === "minimal" && SHELLS.some((platform) => presetReader(preset, platform) === reader.trim())
1077
1127
  );
1128
+ var presetState = (preset) => {
1129
+ const state = preset.verifiedWith === null ? "not yet tested with the real CLI" : `verified with ${preset.verifiedWith}`;
1130
+ return preset.optionsSeenIn === null ? state : `${state}; options seen in ${preset.optionsSeenIn} --help`;
1131
+ };
1132
+ var shellCommand = (words, platform) => words.map((word) => shellWord(word, platform)).join(" ");
1078
1133
  var AGENT_PRESETS = [
1079
1134
  {
1080
1135
  name: "claude",
1081
1136
  program: "Claude Code",
1082
- agent: "claude -p",
1083
- reader: "claude -p --tools '' --strict-mcp-config",
1137
+ agent: {
1138
+ words: ["claude", "-p", "--permission-prompts", "none", "--settings", '{"disableAllHooks":true}'],
1139
+ probe: null,
1140
+ format: "text",
1141
+ withoutStrictMcp: null
1142
+ },
1143
+ reader: {
1144
+ words: [
1145
+ ...["claude", "-p", "--tools", "", "--strict-mcp-config"],
1146
+ ...["--permission-prompts", "none", "--settings", '{"disableAllHooks":true}']
1147
+ ],
1148
+ probe: null,
1149
+ format: "text",
1150
+ withoutStrictMcp: [
1151
+ ...["claude", "-p", "--tools", "", "--disallowedTools", "mcp__*"],
1152
+ ...["--permission-prompts", "none", "--settings", '{"disableAllHooks":true}']
1153
+ ]
1154
+ },
1084
1155
  readerTools: "none",
1085
- verifiedWith: "Claude Code 2.1.327"
1156
+ verifiedWith: "Claude Code 2.1.327",
1157
+ optionsSeenIn: "Claude Code 2.1.329",
1158
+ minimumVersion: "2.1.259",
1159
+ upgrade: "claude update",
1160
+ environment: {},
1161
+ signInCheck: null,
1162
+ mcpAttach: {
1163
+ words: (server) => [
1164
+ "--mcp-config",
1165
+ JSON.stringify({
1166
+ mcpServers: {
1167
+ homingbird: {
1168
+ type: "stdio",
1169
+ command: server.command,
1170
+ args: server.args,
1171
+ env: server.environment
1172
+ }
1173
+ }
1174
+ }),
1175
+ "--strict-mcp-config"
1176
+ ],
1177
+ verified: false
1178
+ }
1086
1179
  },
1087
1180
  {
1088
1181
  name: "codex",
1089
1182
  program: "Codex CLI",
1090
- agent: "codex exec --skip-git-repo-check --ephemeral --sandbox workspace-write -",
1091
- reader: [
1092
- "codex exec --skip-git-repo-check --ephemeral --ignore-user-config --ignore-rules",
1093
- "--sandbox read-only --disable shell_tool --disable unified_exec --disable view_image",
1094
- '-c web_search="disabled" -'
1095
- ].join(" "),
1183
+ agent: {
1184
+ words: ["codex", "exec", "--skip-git-repo-check", "--ephemeral", "--sandbox", "workspace-write", "-"],
1185
+ probe: null,
1186
+ format: "text",
1187
+ withoutStrictMcp: null
1188
+ },
1189
+ reader: {
1190
+ words: [
1191
+ ...[
1192
+ "codex",
1193
+ "exec",
1194
+ "--skip-git-repo-check",
1195
+ "--ephemeral",
1196
+ "--ignore-user-config",
1197
+ "--ignore-rules"
1198
+ ],
1199
+ ...["--sandbox", "read-only", "--disable", "shell_tool", "--disable", "unified_exec"],
1200
+ ...["--disable", "view_image", "-c", 'web_search="disabled"'],
1201
+ ...["-c", "features.plugins=false", "-c", "features.apps=false", "-"]
1202
+ ],
1203
+ probe: {
1204
+ args: [
1205
+ ...["--ignore-user-config", "-c", "features.plugins=false", "-c", "features.apps=false"],
1206
+ ...["mcp", "list", "--json"]
1207
+ ],
1208
+ timeoutMs: 15e3,
1209
+ wordsFrom: (printed) => codexServersSwitchedOff(printed)
1210
+ },
1211
+ format: "text",
1212
+ withoutStrictMcp: null
1213
+ },
1096
1214
  readerTools: "minimal",
1097
- verifiedWith: null
1215
+ verifiedWith: null,
1216
+ optionsSeenIn: null,
1217
+ minimumVersion: null,
1218
+ upgrade: "npm install -g @openai/codex@latest",
1219
+ environment: {},
1220
+ signInCheck: null,
1221
+ mcpAttach: {
1222
+ words: (server) => ["-c", `mcp_servers.homingbird=${codexServerTable(server)}`],
1223
+ verified: false
1224
+ }
1098
1225
  },
1099
1226
  {
1100
1227
  name: "antigravity",
1101
1228
  program: "Antigravity CLI (agy)",
1102
- agent: "agy -p --mode default --output-format text",
1103
- reader: null,
1104
- readerTools: null,
1105
- verifiedWith: null
1229
+ agent: { words: ANTIGRAVITY_PRINT, probe: null, format: "antigravity-stream", withoutStrictMcp: null },
1230
+ reader: {
1231
+ words: [...ANTIGRAVITY_PRINT, "--settings", JSON.stringify(ANTIGRAVITY_READER_SETTINGS)],
1232
+ probe: {
1233
+ args: ["--help"],
1234
+ timeoutMs: 1e4,
1235
+ wordsFrom: (printed) => antigravitySettingsOffered(printed)
1236
+ },
1237
+ format: "antigravity-stream",
1238
+ withoutStrictMcp: null
1239
+ },
1240
+ readerTools: "minimal",
1241
+ verifiedWith: null,
1242
+ optionsSeenIn: null,
1243
+ minimumVersion: "1.1.15",
1244
+ upgrade: "install the latest Antigravity CLI (agy)",
1245
+ environment: { AGY_CLI_DISABLE_AUTO_UPDATE: "true" },
1246
+ signInCheck: {
1247
+ args: ["-p", "/usage", "--output-format", "json", "--print-timeout", "15s"],
1248
+ timeoutMs: 2e4,
1249
+ problem: "Antigravity did not answer within 20 seconds, or is not signed in on this computer. Sign in first: run `agy` in a terminal, then start this again."
1250
+ },
1251
+ mcpAttach: null
1106
1252
  },
1107
1253
  {
1108
1254
  name: "gemini",
1109
1255
  program: "Gemini CLI, legacy: Code Assist Standard or Enterprise, or an API key",
1110
- agent: 'gemini -p "" --output-format text --approval-mode default',
1256
+ agent: {
1257
+ words: ["gemini", "-p", "", "--output-format", "text", "--approval-mode", "default"],
1258
+ probe: null,
1259
+ format: "text",
1260
+ withoutStrictMcp: null
1261
+ },
1111
1262
  reader: null,
1112
1263
  readerTools: null,
1113
- verifiedWith: null
1264
+ verifiedWith: null,
1265
+ optionsSeenIn: null,
1266
+ minimumVersion: null,
1267
+ upgrade: "npm install -g @google/gemini-cli@latest",
1268
+ environment: {},
1269
+ signInCheck: null,
1270
+ mcpAttach: null
1114
1271
  }
1115
1272
  ];
1273
+ var ROLES = ["agent", "reader"];
1274
+ var antigravitySettingsOffered = (printed) => printed.exitCode === 0 && /^\s*--settings(?:[= \t]|$)/m.test(printed.output) ? result_exports.ok([]) : result_exports.err("agy --help does not list --settings, which the reader needs to deny every tool");
1275
+ var SHELLS = ["linux", "win32"];
1276
+ var PLAIN_WORD = /^[\w@+=:,./-]+$/;
1277
+ var shellWord = (word, platform) => {
1278
+ if (PLAIN_WORD.test(word)) return word;
1279
+ if (platform === "win32") return `"${word.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`;
1280
+ return `'${word.replace(/'/g, `'\\''`)}'`;
1281
+ };
1282
+ var codexServersSwitchedOff = (printed) => {
1283
+ if (printed.exitCode !== 0)
1284
+ return result_exports.err(`codex mcp list exited with code ${printed.exitCode ?? "unknown"}`);
1285
+ const listed = CodexServers.read(jsonArrayIn(printed.output));
1286
+ if (listed._tag === "Err") return result_exports.err("codex mcp list --json printed no list of servers");
1287
+ return result_exports.ok(
1288
+ listed.value.flatMap((server) => ["-c", `mcp_servers.${JSON.stringify(server.name)}.enabled=false`])
1289
+ );
1290
+ };
1291
+ var codexServerTable = (server) => {
1292
+ const variables2 = Object.entries(server.environment).map(
1293
+ ([name, value]) => `${name}=${JSON.stringify(value)}`
1294
+ );
1295
+ return `{command=${JSON.stringify(server.command)},args=[${server.args.map((arg) => JSON.stringify(arg)).join(",")}],env={${variables2.join(",")}}}`;
1296
+ };
1297
+ var CodexServers = schema_exports.array(schema_exports.struct({ name: schema_exports.string({ minLength: 1 }) }));
1298
+ var jsonArrayIn = (output) => {
1299
+ const start = output.indexOf("[");
1300
+ const end = output.lastIndexOf("]");
1301
+ if (start === -1 || end < start) return null;
1302
+ try {
1303
+ return JSON.parse(output.slice(start, end + 1));
1304
+ } catch {
1305
+ return null;
1306
+ }
1307
+ };
1308
+
1309
+ // ../cli/src/agent-environment.ts
1310
+ var agentEnvironment = (variables2, secrets) => Object.fromEntries(
1311
+ Object.entries(variables2).flatMap(
1312
+ ([name, value]) => value === void 0 || isWithheld(name, value, secrets) ? [] : [[name, value]]
1313
+ )
1314
+ );
1315
+ var PERSON_CLAUDE_CODE_VARIABLES = /* @__PURE__ */ new Set([
1316
+ "CLAUDE_CODE_OAUTH_TOKEN",
1317
+ "CLAUDE_CODE_USE_BEDROCK",
1318
+ "CLAUDE_CODE_USE_VERTEX",
1319
+ "CLAUDE_CODE_GIT_BASH_PATH",
1320
+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
1321
+ "CLAUDE_CODE_SKIP_BEDROCK_AUTH",
1322
+ "CLAUDE_CODE_SKIP_VERTEX_AUTH"
1323
+ ]);
1324
+ var PARENT_SESSION_VARIABLES = /* @__PURE__ */ new Set([
1325
+ "CLAUDECODE",
1326
+ "CLAUDE_EFFORT",
1327
+ "CLAUDE_PID",
1328
+ "MCP_SERVER_CONNECTION_BATCH_SIZE",
1329
+ "CODEX_THREAD_ID",
1330
+ "CODEX_SESSION_ID",
1331
+ "CODEX_TOOL_CALL_ID",
1332
+ "CODEX_VERSION",
1333
+ "CODEX_CI",
1334
+ "CODEX_PERMISSION_PROFILE"
1335
+ ]);
1336
+ var PARENT_SESSION_PREFIXES = ["CLAUDE_CODE_", "CLAUDE_AGENT_SDK_", "CLAUDE_PREVIEW_"];
1337
+ var isParentSession = (name) => {
1338
+ const upper = name.toUpperCase();
1339
+ if (PARENT_SESSION_VARIABLES.has(upper)) return true;
1340
+ return PARENT_SESSION_PREFIXES.some((prefix) => upper.startsWith(prefix)) && !PERSON_CLAUDE_CODE_VARIABLES.has(upper);
1341
+ };
1342
+ var WITHHELD_NAME = /^(?:HOMINGBIRD|HB)_/i;
1343
+ var isWithheld = (name, value, secrets) => WITHHELD_NAME.test(name) || isParentSession(name) || secrets.some((secret) => secret !== "" && value.includes(secret));
1344
+
1345
+ // ../cli/src/agent-install-directories.ts
1346
+ var withAgentInstallDirectories = (variables2, platform) => {
1347
+ if (platform !== "win32") return variables2;
1348
+ const name = Object.keys(variables2).find((each) => each.toUpperCase() === "PATH");
1349
+ return name === void 0 ? variables2 : { ...variables2, [name]: agentSearchPath(variables2, platform) };
1350
+ };
1351
+ var agentSearchPath = (variables2, platform) => {
1352
+ const name = Object.keys(variables2).find((each) => each.toUpperCase() === "PATH");
1353
+ const path = name === void 0 ? void 0 : variables2[name];
1354
+ if (platform !== "win32" || path === void 0) return path;
1355
+ const listed = path.split(";").filter((directory2) => directory2 !== "");
1356
+ const added = installDirectories(variables2).filter(
1357
+ (directory2) => !listed.some((each) => each.toLowerCase() === directory2.toLowerCase())
1358
+ );
1359
+ return [...listed, ...added].join(";");
1360
+ };
1361
+ var installDirectories = (variables2) => {
1362
+ const profile = variables2.USERPROFILE;
1363
+ const local = variables2.LOCALAPPDATA ?? (profile === void 0 ? void 0 : `${profile}\\AppData\\Local`);
1364
+ const roaming = variables2.APPDATA ?? (profile === void 0 ? void 0 : `${profile}\\AppData\\Roaming`);
1365
+ return [
1366
+ ...profile === void 0 ? [] : [`${profile}\\.local\\bin`],
1367
+ ...local === void 0 ? [] : [`${local}\\Programs\\OpenAI\\Codex\\bin`, `${local}\\agy\\bin`],
1368
+ ...roaming === void 0 ? [] : [`${roaming}\\npm`]
1369
+ ];
1370
+ };
1371
+
1372
+ // ../cli/src/program-paths.ts
1373
+ var resolvedProgram = (command2, path) => task_exports.gen(function* () {
1374
+ const env = yield* task_exports.ask();
1375
+ const program = programWord(command2);
1376
+ if (program === null) return null;
1377
+ const pathExtensions = env.variables.PATHEXT ?? null;
1378
+ for (const candidate of candidatesFor(program, path, env.platform, pathExtensions, env.homeDirectory)) {
1379
+ if (yield* task_exports.promise(() => env.programs.isRunnable(candidate))) return yield* lastingPathOf(candidate);
1380
+ }
1381
+ return null;
1382
+ });
1383
+ var lastingPathOf = (path) => versionManagerOf(path)?.isTemporary === true ? realPathOf(path) : task_exports.succeed(path);
1384
+ var candidatesFor = (program, path, platform, pathExtensions, home = null) => {
1385
+ const isWindows = platform === "win32";
1386
+ const located = isWindows ? program : expandHome(program, home);
1387
+ const names = isWindows && !/\.[^.\\/]+$/.test(program) ? (pathExtensions ?? DEFAULT_PATHEXT).split(";").filter((extension) => extension !== "").map((extension) => `${located}${extension.toLowerCase()}`) : [located];
1388
+ if (/[\\/]/.test(located)) return isAbsolute(located, isWindows) ? names : [];
1389
+ return path.split(isWindows ? ";" : ":").map(
1390
+ (directory2) => isWindows ? directory2.trim().replace(/^"(.*)"$/, "$1") : expandHome(directory2, home)
1391
+ ).filter((directory2) => directory2 !== "").flatMap(
1392
+ (directory2) => names.map((name) => `${directory2.replace(/[\\/]+$/, "")}${isWindows ? "\\" : "/"}${name}`)
1393
+ );
1394
+ };
1395
+ var programWord = (command2) => {
1396
+ const first = command2.trim().split(/\s+/)[0] ?? "";
1397
+ return /^[A-Za-z0-9._+\-\\/:~]+$/.test(first) && !first.includes("=") ? first : null;
1398
+ };
1399
+ var versionManagerOf = (path) => VERSION_MANAGERS.find((manager) => manager.pattern.test(path)) ?? null;
1400
+ var VERSION_MANAGERS = [
1401
+ { name: "fnm", pattern: /[\\/]fnm_multishells[\\/]/i, isTemporary: true },
1402
+ { name: "fnm", pattern: /[\\/]\.?fnm[\\/]/i, isTemporary: false },
1403
+ { name: "nvm", pattern: /[\\/]\.?nvm[\\/]/i, isTemporary: false },
1404
+ { name: "Volta", pattern: /[\\/]\.?volta[\\/]/i, isTemporary: false },
1405
+ { name: "asdf", pattern: /[\\/]\.asdf[\\/]/i, isTemporary: false },
1406
+ { name: "mise", pattern: /[\\/]mise[\\/](installs|shims)[\\/]/i, isTemporary: false }
1407
+ ];
1408
+ var DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
1409
+ var expandHome = (path, home) => home !== null && (path === "~" || path.startsWith("~/")) ? `${home}${path.slice(1)}` : path;
1410
+ var isAbsolute = (program, isWindows) => isWindows ? /^([A-Za-z]:)?[\\/]/.test(program) : program.startsWith("/");
1411
+ var realPathOf = (path) => task_exports.gen(function* () {
1412
+ const env = yield* task_exports.ask();
1413
+ return (yield* task_exports.promise(() => env.programs.realPath(path))) ?? path;
1414
+ });
1415
+
1416
+ // ../cli/src/windows-shell.ts
1417
+ var cmdCommand = (systemRoot, command2) => [
1418
+ `${systemRoot}\\System32\\cmd.exe`,
1419
+ ["/d", "/v:off", "/s", "/c", `"${command2}"`]
1420
+ ];
1421
+
1422
+ // ../cli/src/agent-probe.ts
1423
+ var presetAsked = (preset, args, timeoutMs) => task_exports.gen(function* () {
1424
+ const env = yield* task_exports.ask();
1425
+ const variables2 = withAgentInstallDirectories(env.variables, env.platform);
1426
+ const environment = {
1427
+ ...agentEnvironment(variables2, [env.credentialsFile ?? ""]),
1428
+ ...preset.environment
1429
+ };
1430
+ const name = preset.agent.words[0];
1431
+ const path = agentSearchPath(env.variables, env.platform);
1432
+ const found = path === void 0 ? null : yield* resolvedProgram(name, path);
1433
+ const program = found ?? name;
1434
+ const [command2, words, verbatim] = env.platform === "win32" && /\.(?:cmd|bat)$/i.test(program) ? [
1435
+ ...cmdCommand(variables2.SystemRoot ?? "C:\\Windows", shellCommand([program, ...args], "win32")),
1436
+ true
1437
+ ] : [program, args, false];
1438
+ const finished = yield* task_exports.result(
1439
+ task_exports.tryPromise(
1440
+ (signal) => env.processes.run(command2, words, {
1441
+ environment,
1442
+ timeoutMs,
1443
+ signal,
1444
+ ...verbatim && { windowsVerbatimArguments: true }
1445
+ }),
1446
+ () => null
1447
+ )
1448
+ );
1449
+ return finished._tag === "Ok" ? finished.value : { exitCode: null, output: "" };
1450
+ });
1451
+
1452
+ // ../cli/src/agent-version.ts
1453
+ var presetVersion = (preset) => task_exports.gen(function* () {
1454
+ const asked = yield* presetAsked(preset, ["--version"], VERSION_TIMEOUT_MS);
1455
+ if (asked.exitCode === null) return { status: "missing", version: null };
1456
+ const version = asked.exitCode === 0 ? versionIn(asked.output) : null;
1457
+ if (version === null) return { status: "unknown", version: null };
1458
+ const minimum = preset.minimumVersion;
1459
+ return minimum !== null && isOlder(version, minimum) ? { status: "too_old", version } : { status: "supported", version };
1460
+ });
1461
+ var versionLine = (preset, check) => {
1462
+ const needs = preset.minimumVersion === null ? "" : `, needs ${preset.minimumVersion} or later`;
1463
+ switch (check.status) {
1464
+ case "missing":
1465
+ return `not found on this PATH${needs}`;
1466
+ case "unknown":
1467
+ return `installed, version not readable${needs}`;
1468
+ case "too_old":
1469
+ return `${check.version}, too old${needs}: ${preset.upgrade}`;
1470
+ case "supported":
1471
+ return `${check.version}${needs}`;
1472
+ }
1473
+ };
1474
+ var versionIn = (printed) => printed.match(/\b(\d+)\.(\d+)\.(\d+)\b/)?.[0] ?? null;
1475
+ var isOlder = (version, minimum) => {
1476
+ const [a, b] = [version, minimum].map((each) => each.split(".").map(Number));
1477
+ for (let index = 0; index < 3; index++) if (a[index] !== b[index]) return a[index] < b[index];
1478
+ return false;
1479
+ };
1480
+ var VERSION_TIMEOUT_MS = 5e3;
1116
1481
 
1117
1482
  // ../cli/src/failure.ts
1118
1483
  var CliFailure = tagged("CliFailure")();
@@ -1121,6 +1486,24 @@ var failed = (message) => CliFailure({ message, exitCode: EXIT.failed });
1121
1486
  var fromApiError = (error) => error._tag === "Unauthorized" ? CliFailure({ message: SIGNED_OUT_MESSAGE, exitCode: EXIT.signedOut }) : CliFailure({ message: error.message, exitCode: EXIT.failed });
1122
1487
  var SIGNED_OUT_MESSAGE = "Not signed in. Run `homingbird login --server <url>` first.";
1123
1488
 
1489
+ // ../cli/src/agent-launch.ts
1490
+ var launchesAsGiven = (settings, platform) => ({
1491
+ agent: unprobed(settings.agent, platform),
1492
+ reader: settings.split === null ? null : unprobed(settings.split.reader, platform),
1493
+ installed: []
1494
+ });
1495
+ var unprobed = (command2, platform) => {
1496
+ const match = presetCommandOf(command2, platform);
1497
+ if (match === null) return launchAsGiven(command2);
1498
+ return { ...launchAsGiven(command2), format: match.launch.format, environment: match.preset.environment };
1499
+ };
1500
+ var launchAsGiven = (command2) => ({
1501
+ command: command2,
1502
+ format: "text",
1503
+ environment: {},
1504
+ withoutStrictMcp: null
1505
+ });
1506
+
1124
1507
  // ../cli/src/arguments.ts
1125
1508
  var RUN_TIMEOUT_DEFAULT_SECONDS = 300;
1126
1509
 
@@ -2532,7 +2915,7 @@ var EventBody = schema_exports.openVariants(
2532
2915
  },
2533
2916
  UNKNOWN_EVENT
2534
2917
  );
2535
- var StreamEvent = schema_exports.struct({
2918
+ var StreamEvent2 = schema_exports.struct({
2536
2919
  seq: schema_exports.int({ min: 0 }),
2537
2920
  at: schema_exports.int({ min: 0 }),
2538
2921
  body: EventBody
@@ -2573,6 +2956,13 @@ var DeviceRequest = schema_exports.struct({
2573
2956
  client: schema_exports.string(),
2574
2957
  expiresAt: schema_exports.int({ min: 0 })
2575
2958
  });
2959
+ var JoinCode = schema_exports.struct({
2960
+ code: schema_exports.string(),
2961
+ serverUrl: schema_exports.string(),
2962
+ expiresAt: schema_exports.int({ min: 0 }),
2963
+ /** How long it still works, so a client counts down from its own clock, not the server's. */
2964
+ expiresInSeconds: schema_exports.optional(schema_exports.int({ min: 0 }))
2965
+ });
2576
2966
  var ConsentRequest = schema_exports.struct({
2577
2967
  id: schema_exports.string(),
2578
2968
  client: schema_exports.string(),
@@ -2866,7 +3256,9 @@ var WeekFigures = schema_exports.struct({
2866
3256
  notesSent: count,
2867
3257
  repliesReceived: count,
2868
3258
  /** The typical time from a colleague's new note to the person's first reply to it. */
2869
- medianReplyMs: schema_exports.nullable(count)
3259
+ medianReplyMs: schema_exports.nullable(count),
3260
+ /** Answers of channels' agents the person approved as a manager, never counted as notes they sent. */
3261
+ approvedForChannels: schema_exports.optional(count)
2870
3262
  });
2871
3263
  var YourWeek = schema_exports.struct({ days: schema_exports.int({ min: 1 }), current: WeekFigures, previous: WeekFigures });
2872
3264
  var AgentReport = schema_exports.struct({
@@ -2894,6 +3286,23 @@ var Delivery = schema_exports.struct({
2894
3286
  medianPickupMs: schema_exports.nullable(count),
2895
3287
  waitedWithoutAgent: count
2896
3288
  });
3289
+ var TeamTotals = schema_exports.struct({
3290
+ team: schema_exports.string({ minLength: 1, maxLength: 80 }),
3291
+ activeMembers: schema_exports.nullable(count),
3292
+ notesSent: schema_exports.nullable(count),
3293
+ sentAsWritten: schema_exports.nullable(count),
3294
+ sentAfterEdits: schema_exports.nullable(count),
3295
+ discarded: schema_exports.nullable(count),
3296
+ quickApprovals: schema_exports.nullable(count),
3297
+ medianDecisionMs: schema_exports.nullable(count),
3298
+ skipped: count
3299
+ });
3300
+ var ChannelAgentTotals = schema_exports.struct({
3301
+ written: count,
3302
+ sentAsWritten: count,
3303
+ sentAfterEdits: count,
3304
+ discarded: count
3305
+ });
2897
3306
  var OrganizationFigures = schema_exports.struct({
2898
3307
  activeMembers: count,
2899
3308
  notesSent: count,
@@ -2915,7 +3324,10 @@ var OrganizationFigures = schema_exports.struct({
2915
3324
  hiddenLabels: count,
2916
3325
  medianDecisionMs: schema_exports.optional(schema_exports.nullable(count)),
2917
3326
  authorship: schema_exports.optional(schema_exports.nullable(Authorship)),
2918
- delivery: schema_exports.optional(schema_exports.nullable(Delivery))
3327
+ delivery: schema_exports.optional(schema_exports.nullable(Delivery)),
3328
+ channelAgents: schema_exports.optional(schema_exports.nullable(ChannelAgentTotals)),
3329
+ teams: schema_exports.optional(schema_exports.array(TeamTotals)),
3330
+ hiddenTeams: schema_exports.optional(count)
2919
3331
  });
2920
3332
  var OrganizationPeriod = schema_exports.struct({
2921
3333
  days: schema_exports.int({ min: 1 }),
@@ -2936,6 +3348,34 @@ var OrganizationInsights = schema_exports.struct({
2936
3348
  weeks: schema_exports.optional(schema_exports.array(QuickWeek)),
2937
3349
  quickWarning: schema_exports.optional(schema_exports.boolean)
2938
3350
  });
3351
+ var ManagerApprovals = schema_exports.struct({
3352
+ memberId: MemberId,
3353
+ name: schema_exports.string({ maxLength: 200 }),
3354
+ approved: count
3355
+ });
3356
+ var ChannelAgentFigures = schema_exports.struct({
3357
+ written: count,
3358
+ sentAsWritten: count,
3359
+ sentAfterEdits: count,
3360
+ discarded: count,
3361
+ medianDecisionMs: schema_exports.nullable(count),
3362
+ quickApprovals: count,
3363
+ approvals: schema_exports.nullable(schema_exports.array(ManagerApprovals)),
3364
+ approvedByFormerManagers: schema_exports.optional(count)
3365
+ });
3366
+ var ChannelAgentPeriod = schema_exports.struct({
3367
+ days: schema_exports.int({ min: 1 }),
3368
+ current: ChannelAgentFigures,
3369
+ previous: ChannelAgentFigures
3370
+ });
3371
+ var ChannelAgentReport = schema_exports.struct({
3372
+ generatedAt: Timestamp,
3373
+ channel: ChannelSlug,
3374
+ quickApprovalSeconds: schema_exports.int({ min: 1 }),
3375
+ minimumGroupSize: schema_exports.int({ min: 1 }),
3376
+ waiting: count,
3377
+ periods: schema_exports.array(ChannelAgentPeriod)
3378
+ });
2939
3379
  var QUICK_PICKUP_MS = 5 * 6e4;
2940
3380
  var PICKUP_WAIT_MS = 24 * 60 * 6e4;
2941
3381
 
@@ -3082,6 +3522,40 @@ var AnalyticsBatch = schema_exports.struct({
3082
3522
  });
3083
3523
  var analyticsEvent = (name, properties, anonymousId, timestamp) => ({ event: name, properties, anonymousId, timestamp });
3084
3524
 
3525
+ // ../protocol/src/desk-wake.ts
3526
+ var DeskWake = schema_exports.struct({
3527
+ host: schema_exports.string({ maxLength: 253 }),
3528
+ headerNames: schema_exports.array(schema_exports.string({ maxLength: 64 }), { maxItems: 8 }),
3529
+ credentialId: CredentialId,
3530
+ enabled: schema_exports.boolean,
3531
+ lastWakeAt: schema_exports.nullable(Timestamp),
3532
+ lastStatus: schema_exports.tolerant(
3533
+ schema_exports.literal("never", "sent", "online", "not_online", "refused", "rate_limited", "unreachable"),
3534
+ UNKNOWN
3535
+ ),
3536
+ failures: schema_exports.int({ min: 0 }),
3537
+ stoppedBecause: schema_exports.nullable(
3538
+ schema_exports.tolerant(schema_exports.literal("refused", "failures", "credential_gone", "unreadable"), UNKNOWN)
3539
+ ),
3540
+ createdAt: Timestamp,
3541
+ updatedAt: Timestamp
3542
+ });
3543
+ var DESK_WAKE_HEADERS_MAX = 4;
3544
+ var DeskWakeHeader = schema_exports.struct({
3545
+ name: schema_exports.string({ pattern: /^[A-Za-z0-9-]{1,64}$/ }),
3546
+ value: schema_exports.string({ pattern: /^[!-~](?:[ -~]{0,3998}[!-~])?$/ })
3547
+ });
3548
+ var DeskWakeSetup = schema_exports.struct({
3549
+ url: schema_exports.string({ minLength: 9, maxLength: 2e3, pattern: /^https:\/\/\S+$/ }),
3550
+ headers: schema_exports.array(DeskWakeHeader, { maxItems: DESK_WAKE_HEADERS_MAX }),
3551
+ credentialId: CredentialId,
3552
+ enabled: schema_exports.boolean
3553
+ });
3554
+ var DeskWakeTest = schema_exports.struct({
3555
+ status: schema_exports.int({ min: 0, max: 599 }),
3556
+ outcome: DeskWake.fields.lastStatus
3557
+ });
3558
+
3085
3559
  // ../protocol/src/contract.ts
3086
3560
  var PushSubscription = schema_exports.struct({
3087
3561
  endpoint: schema_exports.string({ minLength: 1, maxLength: 2e3, pattern: /^https:\/\// }),
@@ -3122,6 +3596,27 @@ var contract = {
3122
3596
  body: schema_exports.struct({ notifications: schema_exports.literal(...NOTIFICATION_LEVELS) }),
3123
3597
  response: schema_exports.struct({ notifications: NotificationLevel })
3124
3598
  }),
3599
+ "me.deskWake.get": route({
3600
+ method: "GET",
3601
+ path: "/me/desk-wake",
3602
+ access: "human",
3603
+ response: schema_exports.struct({ wake: schema_exports.nullable(DeskWake) })
3604
+ }),
3605
+ "me.deskWake.set": route({
3606
+ method: "PUT",
3607
+ path: "/me/desk-wake",
3608
+ access: "human",
3609
+ body: DeskWakeSetup,
3610
+ response: DeskWake
3611
+ }),
3612
+ "me.deskWake.remove": route({ method: "DELETE", path: "/me/desk-wake", access: "human", response: Empty }),
3613
+ "me.deskWake.test": route({
3614
+ method: "POST",
3615
+ path: "/me/desk-wake/test",
3616
+ access: "human",
3617
+ body: Empty,
3618
+ response: DeskWakeTest
3619
+ }),
3125
3620
  "directory.list": route({
3126
3621
  method: "GET",
3127
3622
  path: "/directory",
@@ -3245,6 +3740,12 @@ var contract = {
3245
3740
  access: "human",
3246
3741
  response: ChannelAgent
3247
3742
  }),
3743
+ "channels.agent.figures": route({
3744
+ method: "GET",
3745
+ path: "/channels/:slug/agent/figures",
3746
+ access: "human",
3747
+ response: ChannelAgentReport
3748
+ }),
3248
3749
  "channels.askPrivately": route({
3249
3750
  method: "POST",
3250
3751
  path: "/channels/:slug/private-question",
@@ -3663,6 +4164,16 @@ var contract = {
3663
4164
  }),
3664
4165
  response: Empty
3665
4166
  }),
4167
+ "joinCodes.create": route({
4168
+ method: "POST",
4169
+ path: "/join-codes",
4170
+ access: "human",
4171
+ body: schema_exports.struct({
4172
+ /** Issues the credential to this channel's agent instead of the person creating the code. */
4173
+ channel: schema_exports.optional(ChannelSlug)
4174
+ }),
4175
+ response: JoinCode
4176
+ }),
3666
4177
  "consent.get": route({ method: "GET", path: "/consent/:id", access: "human", response: ConsentRequest }),
3667
4178
  "consent.decide": route({
3668
4179
  method: "POST",
@@ -3729,7 +4240,7 @@ var contract = {
3729
4240
  path: "/events/poll",
3730
4241
  access: "member",
3731
4242
  query: { after: schema_exports.optional(Digits), wait: schema_exports.optional(schema_exports.string({ pattern: /^[0-9]{1,2}$/ })) },
3732
- response: schema_exports.struct({ events: schema_exports.array(StreamEvent), cursor: schema_exports.int({ min: 0 }) })
4243
+ response: schema_exports.struct({ events: schema_exports.array(StreamEvent2), cursor: schema_exports.int({ min: 0 }) })
3733
4244
  }),
3734
4245
  "answeringFlow.get": route({
3735
4246
  method: "GET",
@@ -3877,16 +4388,29 @@ var FEATURES = {
3877
4388
  "channels.agent.rename",
3878
4389
  "channels.agent.retire",
3879
4390
  "channels.agent.credentials.revoke",
4391
+ "channels.agent.figures",
3880
4392
  "channels.askPrivately",
3881
4393
  "reviews.list",
3882
4394
  "reviews.get"
3883
4395
  ]
3884
4396
  },
4397
+ cloudDesk: {
4398
+ default: false,
4399
+ routes: ["me.deskWake.get", "me.deskWake.set", "me.deskWake.test"]
4400
+ },
4401
+ joinCodes: { default: true, routes: ["joinCodes.create"] },
3885
4402
  analytics: { default: false, routes: ["analytics.track"] }
3886
4403
  };
3887
4404
  var FEATURE_NAMES = Object.keys(FEATURES);
3888
4405
  var FeatureSwitches = schema_exports.record(schema_exports.boolean);
3889
4406
 
4407
+ // ../protocol/src/waking-events.ts
4408
+ var isWakingEvent = (body, viewerId) => {
4409
+ if (body.type === "note.sent") return body.note.authorId !== viewerId;
4410
+ if (body.type === "debate.changed") return viewerId !== null && body.participantIds.includes(viewerId);
4411
+ return body.type === "draft.requested" || body.type === "resync";
4412
+ };
4413
+
3890
4414
  // ../protocol/src/debate-rules.ts
3891
4415
  var turnsTakenBy = (room, memberId) => room.turns.filter((turn) => turn.memberId === memberId).length;
3892
4416
 
@@ -4030,15 +4554,16 @@ var AUDIT_EVENTS = {
4030
4554
  }),
4031
4555
  "credential.issued": event("security", "credential", {
4032
4556
  kind: CredentialKind,
4033
- grant: schema_exports.literal("browser", "device_code", "authorization_code"),
4557
+ grant: schema_exports.literal("browser", "device_code", "authorization_code", "join_code"),
4034
4558
  clientKind: CLIENT_KIND,
4035
4559
  channelAgent: schema_exports.optional(MemberId)
4036
4560
  }),
4037
4561
  "credential.renamed": event("security", "credential", {}),
4038
4562
  "credential.revoked": event("security", "credential", {
4039
- because: schema_exports.optional(schema_exports.literal("issuer_left", "agent_retired"))
4563
+ because: schema_exports.optional(schema_exports.literal("issuer_left", "agent_retired", "refresh_replayed"))
4040
4564
  }),
4041
4565
  "credential.device_decided": event("security", "none", { approved: schema_exports.boolean }),
4566
+ "credential.join_code_created": event("security", "member", { channel: schema_exports.optional(ChannelSlug) }),
4042
4567
  "credential.consent_decided": event("security", "auth_request", { approved: schema_exports.boolean }),
4043
4568
  "oauth.client_registered": event("security", "oauth_client", { redirectHosts: hostList() }),
4044
4569
  "oauth.client_resolved": event("security", "oauth_client", { redirectHosts: hostList() }),
@@ -4075,6 +4600,15 @@ var AUDIT_EVENTS = {
4075
4600
  removed: schema_exports.array(MemberId, { maxItems: GROUP_MEMBERS_MAX }),
4076
4601
  because: schema_exports.optional(schema_exports.literal("deactivated"))
4077
4602
  }),
4603
+ "desk_wake.registered": event("security", "member", { host: schema_exports.string({ maxLength: 253 }) }),
4604
+ "desk_wake.removed": event("security", "member", {
4605
+ host: schema_exports.string({ maxLength: 253 }),
4606
+ because: schema_exports.optional(schema_exports.literal("deactivated"))
4607
+ }),
4608
+ "desk_wake.stopped": event("security", "member", {
4609
+ host: schema_exports.string({ maxLength: 253 }),
4610
+ because: schema_exports.literal("refused", "failures", "credential_gone", "unreadable")
4611
+ }),
4078
4612
  "note.approved": event("full", "note", {
4079
4613
  conversationId: ConversationId,
4080
4614
  edited: schema_exports.boolean,
@@ -4168,6 +4702,10 @@ var ROUTE_AUDIT = {
4168
4702
  "me.character.set": { event: "character.set", target: "member" },
4169
4703
  "me.character.clear": { event: "character.cleared", target: "member" },
4170
4704
  "me.notifications.set": { event: "member.notifications_changed", target: "member" },
4705
+ "me.deskWake.get": read(),
4706
+ "me.deskWake.set": { event: "desk_wake.registered", target: "member" },
4707
+ "me.deskWake.remove": { event: "desk_wake.removed", target: "member" },
4708
+ "me.deskWake.test": { none: "A test wake keeps nothing; the operational log says how it went." },
4171
4709
  "directory.list": read(),
4172
4710
  "channels.list": read(),
4173
4711
  "channels.get": read(),
@@ -4182,6 +4720,7 @@ var ROUTE_AUDIT = {
4182
4720
  "channels.members.remove": { event: "channel.member_removed", target: "channel" },
4183
4721
  "channels.managers.addTeam": { event: "group.members_changed", target: "group" },
4184
4722
  "channels.agent.get": read(),
4723
+ "channels.agent.figures": read(),
4185
4724
  "channels.agent.create": { event: "channel.agent_created", target: "member" },
4186
4725
  "channels.agent.rename": { event: "channel.agent_renamed", target: "member" },
4187
4726
  "channels.agent.retire": { event: "channel.agent_retired", target: "member" },
@@ -4246,6 +4785,7 @@ var ROUTE_AUDIT = {
4246
4785
  "credentials.revoke": { event: "credential.revoked", target: "credential" },
4247
4786
  "device.get": read(),
4248
4787
  "device.decide": { event: "credential.device_decided", target: "none" },
4788
+ "joinCodes.create": { event: "credential.join_code_created", target: "member" },
4249
4789
  "consent.get": read(),
4250
4790
  "consent.decide": { event: "credential.consent_decided", target: "auth_request" },
4251
4791
  "push.key": read(),
@@ -4884,7 +5424,9 @@ var countUsage = (api, name, properties) => task_exports.catchAll(() => task_exp
4884
5424
  var ANALYTICS_NOTICE = "This Homingbird server counts anonymous usage, such as which agent preset a desk runs, never notes, names or email addresses. Turn it off with `homingbird analytics off` or DO_NOT_TRACK=1.";
4885
5425
  var isDoNotTrack = (variables2) => variables2.DO_NOT_TRACK !== void 0 && variables2.DO_NOT_TRACK !== "" && variables2.DO_NOT_TRACK !== "0";
4886
5426
  var presetLabel = (agent) => {
4887
- const name = AGENT_PRESETS.find((preset) => preset.agent === agent || preset.name === agent)?.name;
5427
+ const name = AGENT_PRESETS.find(
5428
+ (preset) => preset.name === agent || ["linux", "win32"].some((shell) => presetAgent(preset, shell) === agent)
5429
+ )?.name;
4888
5430
  return ANALYTICS_AGENT_PRESETS.find((known) => known === name) ?? "custom";
4889
5431
  };
4890
5432
  var AnalyticsSettings = schema_exports.struct({
@@ -5110,7 +5652,7 @@ var pollOnce = (options, cursor) => task_exports.gen(function* () {
5110
5652
  });
5111
5653
  var UNREADABLE_PROBLEM = "The server sent an event this client cannot read; it was skipped.";
5112
5654
  var arrivedFrom = (raw) => {
5113
- const event2 = StreamEvent.read(raw);
5655
+ const event2 = StreamEvent2.read(raw);
5114
5656
  if (event2._tag === "Ok") return { event: event2.value, seq: event2.value.seq };
5115
5657
  const seq = raw?.seq;
5116
5658
  return { event: null, seq: typeof seq === "number" && Number.isSafeInteger(seq) ? seq : null };
@@ -5185,6 +5727,9 @@ var post = (options, path, fields) => task_exports.gen(function* () {
5185
5727
  });
5186
5728
  var unreachable = () => DeviceFlowFailed({ reason: "unreachable", message: "The Homingbird server could not be reached." });
5187
5729
 
5730
+ // ../client/src/join-code.ts
5731
+ var JoinCodeRefused = tagged("JoinCodeRefused")();
5732
+
5188
5733
  // ../client/src/protocol-check.ts
5189
5734
  var requireReadableServer = (api) => task_exports.flatMap((info) => {
5190
5735
  const side = upgradeNeeded(info);
@@ -5522,7 +6067,10 @@ var summaryOf = (note) => ({
5522
6067
  });
5523
6068
 
5524
6069
  // ../cli/src/web-client.ts
5525
- var reviewLink = (serverUrl, slug) => `${serverUrl.replace(/\/+$/, "")}/#/channel/${encodeURIComponent(slug)}/agent`;
6070
+ var reviewLink = (serverUrl, slug, draftId = null) => {
6071
+ const page = `${serverUrl.replace(/\/+$/, "")}/#/channel/${encodeURIComponent(slug)}/agent`;
6072
+ return draftId === null ? page : `${page}?draft=${encodeURIComponent(draftId)}`;
6073
+ };
5526
6074
  var reviewChannelOf = (api, member) => member.kind !== "channel_agent" ? task_exports.succeed(null) : task_exports.catchAll(() => task_exports.succeed(null))(
5527
6075
  task_exports.map(
5528
6076
  (listed) => listed.channels.find((channel) => channel.agent?.id === member.id)?.slug ?? null
@@ -5633,6 +6181,46 @@ var overview = task_exports.gen(function* () {
5633
6181
  );
5634
6182
  });
5635
6183
 
6184
+ // ../cli/src/commands/presets.ts
6185
+ var presets = task_exports.gen(function* () {
6186
+ const env = yield* task_exports.ask();
6187
+ const { platform } = env;
6188
+ const installed = yield* task_exports.forEach(AGENT_PRESETS, presetVersion);
6189
+ return outcome(
6190
+ {
6191
+ presets: AGENT_PRESETS.map((preset, index) => ({
6192
+ name: preset.name,
6193
+ program: preset.program,
6194
+ agent: presetAgent(preset, platform),
6195
+ reader: presetReader(preset, platform),
6196
+ readerTools: preset.readerTools,
6197
+ verifiedWith: preset.verifiedWith,
6198
+ optionsSeenIn: preset.optionsSeenIn,
6199
+ minimumVersion: preset.minimumVersion,
6200
+ installed: installed[index],
6201
+ state: presetState(preset)
6202
+ }))
6203
+ },
6204
+ [
6205
+ "Agent presets for run and service install (--agent <name>):",
6206
+ ...AGENT_PRESETS.flatMap((preset, index) => [
6207
+ "",
6208
+ ` ${preset.name} ${preset.program}; ${presetState(preset)}`,
6209
+ ` here: ${versionLine(preset, installed[index])}`,
6210
+ ` agent: ${presetAgent(preset, platform)}`,
6211
+ ` reader: ${readerLine(preset, platform)}`
6212
+ ]),
6213
+ "",
6214
+ "Any other --agent value is run as the command it is."
6215
+ ].join("\n")
6216
+ );
6217
+ });
6218
+ var readerLine = (preset, platform) => {
6219
+ const reader = presetReader(preset, platform);
6220
+ if (reader === null) return "none known; with --split, give --reader yourself";
6221
+ return preset.readerTools === "minimal" ? `${reader} (minimal tools, not none)` : `${reader} (no tools)`;
6222
+ };
6223
+
5636
6224
  // ../cli/src/commands/requests.ts
5637
6225
  var requests = task_exports.gen(function* () {
5638
6226
  const session = yield* openSession;
@@ -5698,6 +6286,7 @@ var serviceVariables = (spec) => [
5698
6286
  var serviceLockPath = (configDirectory, server) => `${configDirectory}/desks/service-${serviceSlug(server)}.lock`;
5699
6287
  var serviceStopPath = (configDirectory, server) => `${configDirectory}/desks/service-${serviceSlug(server)}.stop`;
5700
6288
  var serviceMissingPath = (configDirectory, server) => `${configDirectory}/desks/service-${serviceSlug(server)}.missing`;
6289
+ var serviceAgentsPath = (configDirectory, server) => `${configDirectory}/desks/service-${serviceSlug(server)}.agents`;
5701
6290
  var serviceSlug = (server) => {
5702
6291
  const key = serverKey(server);
5703
6292
  const whole = key.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "");
@@ -5743,16 +6332,33 @@ var shortHash = (text) => {
5743
6332
  };
5744
6333
  var CREDENTIALS_FILE_VARIABLE = "HOMINGBIRD_CREDENTIALS_FILE";
5745
6334
 
5746
- // ../cli/src/agent-environment.ts
5747
- var agentEnvironment = (variables2, secrets) => Object.fromEntries(
5748
- Object.entries(variables2).flatMap(
5749
- ([name, value]) => value === void 0 || isWithheld(name, value, secrets) ? [] : [[name, value]]
5750
- )
5751
- );
5752
- var WITHHELD_NAME = /^(?:HOMINGBIRD|HB)_/i;
5753
- var isWithheld = (name, value, secrets) => WITHHELD_NAME.test(name) || secrets.some((secret) => secret !== "" && value.includes(secret));
6335
+ // ../cli/src/agent-errors.ts
6336
+ var firstErrorLine = (run3, secrets) => {
6337
+ const line = (run3.errors ?? "").split(/\r?\n/).map((each) => each.trim()).find((each) => each !== "");
6338
+ if (line === void 0) return null;
6339
+ const withheld = secrets.reduce(
6340
+ (text, secret) => secret === "" ? text : text.split(secret).join("[withheld]"),
6341
+ line
6342
+ );
6343
+ const clean = withheld.replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁦-⁩]/g, "");
6344
+ return clean.length <= ERROR_LINE_MAX ? clean : `${clean.slice(0, ERROR_LINE_MAX - 1)}\u2026`;
6345
+ };
6346
+ var isManagedMcpRefusal = (run3) => run3.exitCode !== 0 && MANAGED_MCP_REFUSAL.test(run3.errors ?? "");
6347
+ var MANAGED_MCP_REFUSAL = /cannot use --strict-mcp-config when an enterprise MCP config is present/i;
6348
+ var ERROR_LINE_MAX = 160;
5754
6349
 
5755
6350
  // ../cli/src/commands/run.ts
6351
+ var installedMcpServer = task_exports.gen(function* () {
6352
+ const env = yield* task_exports.ask();
6353
+ const [node, script] = env.program;
6354
+ if (node === void 0 || script === void 0) return null;
6355
+ const bundle = script.replace(
6356
+ /[\\/]cli[\\/]dist[\\/][^\\/]+$/,
6357
+ (found) => found.replace(/cli([\\/])dist\1[^\\/]+$/, "mcp$1dist$1homingbird-mcp.mjs")
6358
+ );
6359
+ if (bundle === script || !(yield* env.files.exists(bundle))) return null;
6360
+ return [node, bundle];
6361
+ });
5756
6362
  var runDesk = (session, settings, report) => task_exports.gen(function* () {
5757
6363
  const env = yield* task_exports.ask();
5758
6364
  const { agent, timeoutSeconds, split } = settings;
@@ -5779,6 +6385,9 @@ var runDesk = (session, settings, report) => task_exports.gen(function* () {
5779
6385
  member,
5780
6386
  agent,
5781
6387
  split,
6388
+ launches: settings.launches ?? launchesAsGiven(settings, env.platform ?? "linux"),
6389
+ credentialsFile: env.credentialsFile ?? "",
6390
+ platform: env.platform ?? "linux",
5782
6391
  isService: settings.isService === true,
5783
6392
  pause: deskPausePath(env, session.credential.serverUrl, member.id),
5784
6393
  timeoutMs: timeoutSeconds * 1e3,
@@ -5817,7 +6426,7 @@ Every draft waits for approval in the web client.${runner.isService ? "" : " Pre
5817
6426
  );
5818
6427
  yield* task_exports.ensuring(task_exports.sync(() => stopping.abort()))(
5819
6428
  stream_exports.forEach(
5820
- (event2) => isWaking(event2, member.id) ? answerWaitingOrStop(runner) : task_exports.unit
6429
+ (event2) => isWakingEvent(event2.body, member.id) ? answerWaitingOrStop(runner) : task_exports.unit
5821
6430
  )(events)
5822
6431
  );
5823
6432
  });
@@ -5850,13 +6459,6 @@ var MINIMAL_READER_WARNING = "Split mode: this preset reader runs with minimal t
5850
6459
  var MINIMAL_READER_REFUSED = "Split mode with --require-toolless-reader: this preset reader runs with minimal tools, not none. Give --reader a command that runs without tools.";
5851
6460
  var SAME_READER_REFUSED = "Split mode with --require-toolless-reader needs a --reader command different from --agent, one that runs without tools.";
5852
6461
  var STOPPING = [EXIT.signedOut];
5853
- var WAKING = [
5854
- "note.sent",
5855
- "draft.requested",
5856
- "debate.changed",
5857
- "resync"
5858
- ];
5859
- var isWaking = (event2, viewerId) => WAKING.includes(event2.body.type) && !(event2.body.type === "note.sent" && event2.body.note.authorId === viewerId) && !(event2.body.type === "debate.changed" && !event2.body.participantIds.includes(viewerId));
5860
6462
  var answerWaiting = (runner) => task_exports.gen(function* () {
5861
6463
  for (; ; ) {
5862
6464
  yield* untilResumed(runner);
@@ -5902,7 +6504,7 @@ var debateDeskOf = (runner) => ({
5902
6504
  tried: runner.triedDebates,
5903
6505
  told: runner.told,
5904
6506
  report: runner.report,
5905
- run: (role, prompt, what) => outputOf(runner, role === "agent" ? runner.agent : runner.split.reader, role, prompt, what),
6507
+ run: (role, prompt, what) => outputOf(runner, role, prompt, what),
5906
6508
  warn
5907
6509
  });
5908
6510
  var untilResumed = (runner) => task_exports.gen(function* () {
@@ -6000,7 +6602,7 @@ var withoutOptions = (words) => {
6000
6602
  };
6001
6603
  var LAUNCHERS = /* @__PURE__ */ new Set(["env", "npx", "bunx"]);
6002
6604
  var draftedBy = (runner, prompt, what) => task_exports.gen(function* () {
6003
- const output = yield* outputOf(runner, runner.agent, "agent", prompt, what);
6605
+ const output = yield* outputOf(runner, "agent", prompt, what);
6004
6606
  if (output === null) return null;
6005
6607
  const reply = runnerReplyIn(output);
6006
6608
  const problem = replyProblem(reply);
@@ -6010,7 +6612,7 @@ var draftedBy = (runner, prompt, what) => task_exports.gen(function* () {
6010
6612
  var extractedFrom = (runner, note, authors, what) => task_exports.gen(function* () {
6011
6613
  const env = yield* task_exports.ask();
6012
6614
  const prompt = readerPrompt(quotedNote(note, { authors, nonce: env.nonce }));
6013
- const output = yield* outputOf(runner, runner.split.reader, "reader", prompt, what);
6615
+ const output = yield* outputOf(runner, "reader", prompt, what);
6014
6616
  const extracted = output === null ? null : extractionIn(output);
6015
6617
  if (extracted === null) {
6016
6618
  if (output !== null)
@@ -6026,33 +6628,61 @@ var extractedOriginalOf = (runner, request, authors) => task_exports.gen(functio
6026
6628
  if (note._tag === "Err") return `(The note ${request.inReplyTo} could not be loaded.)`;
6027
6629
  return (yield* extractedFrom(runner, note.value, authors, `the note ${note.value.id}`)) ?? UNREADABLE;
6028
6630
  });
6029
- var outputOf = (runner, command2, role, prompt, what) => task_exports.gen(function* () {
6030
- const env = yield* task_exports.ask();
6031
- const environment = agentEnvironment(env.variables, [
6032
- runner.session.credential.token,
6033
- env.credentialsFile ?? ""
6034
- ]);
6631
+ var outputOf = (runner, role, prompt, what) => task_exports.gen(function* () {
6632
+ const launch = role === "agent" ? runner.launches.agent : runner.launches.reader;
6035
6633
  const finished = yield* task_exports.result(
6036
6634
  task_exports.timeout(runner.timeoutMs)(
6037
- task_exports.tryPromise(
6038
- (signal) => env.launcher.runAgent(command2, prompt, environment, signal),
6039
- (cause) => failed(cause instanceof Error ? cause.message : String(cause))
6040
- )
6635
+ task_exports.gen(function* () {
6636
+ const first = yield* launched(runner, launch, prompt);
6637
+ const fallback = launch.withoutStrictMcp;
6638
+ if (fallback === null || !isManagedMcpRefusal(first)) return first;
6639
+ yield* warn(role === "reader" ? MANAGED_MCP_WARNING : MANAGED_MCP_AGENT_WARNING);
6640
+ runner.launches = { ...runner.launches, [role]: fallback };
6641
+ return yield* launched(runner, fallback, prompt);
6642
+ })
6041
6643
  )
6042
6644
  );
6043
- const reason = finished._tag === "Ok" ? exitProblem(finished.value, command2) : finished.error._tag === "TimeoutError" ? `did not finish within ${runner.timeoutMs / 1e3} seconds` : `could not be started (${finished.error.message})`;
6044
- if (reason === null && finished._tag === "Ok") return finished.value.output;
6045
- return yield* task_exports.as(null)(warn(`The ${role} command ${reason}; nothing was drafted for ${what}.`));
6645
+ const reason = finished._tag === "Ok" ? exitProblem(finished.value, launch.command, secretsOf(runner), runner.platform) : finished.error._tag === "TimeoutError" ? `did not finish within ${runner.timeoutMs / 1e3} seconds` : `could not be started (${finished.error.message})`;
6646
+ if (reason !== null || finished._tag !== "Ok")
6647
+ return yield* task_exports.as(null)(warn(`The ${role} command ${reason}; nothing was drafted for ${what}.`));
6648
+ if (launch.format === "text") return finished.value.output;
6649
+ const denied = firstErrorLine(finished.value, secretsOf(runner));
6650
+ if (denied !== null)
6651
+ yield* warn(`The ${role} command finished but reported, perhaps a tool it was denied: ${denied}`);
6652
+ const reply = antigravityOutput(finished.value.output);
6653
+ if (reply._tag === "Ok") return reply.value;
6654
+ return yield* task_exports.as(null)(warn(`The ${role} command ${reply.error}; nothing was drafted for ${what}.`));
6655
+ });
6656
+ var MANAGED_MCP_AGENT_WARNING = "Claude Code refused --strict-mcp-config because your organization manages its MCP configuration: the agent now runs without the Homingbird MCP server.";
6657
+ var MANAGED_MCP_WARNING = "Claude Code refused --strict-mcp-config because your organization manages its MCP configuration: the reader now runs without it, with every MCP tool denied.";
6658
+ var launched = (runner, launch, prompt) => task_exports.gen(function* () {
6659
+ const env = yield* task_exports.ask();
6660
+ const environment = {
6661
+ ...agentEnvironment(env.variables, secretsOf(runner)),
6662
+ ...launch.environment
6663
+ };
6664
+ const input = launch.format === "antigravity-stream" ? antigravityInput(prompt) : prompt;
6665
+ return yield* task_exports.tryPromise(
6666
+ (signal) => env.launcher.runAgent(launch.command, input, environment, signal),
6667
+ (cause) => failed(cause instanceof Error ? cause.message : String(cause))
6668
+ );
6046
6669
  });
6047
- var exitProblem = (finished, command2) => {
6670
+ var secretsOf = (runner) => [
6671
+ runner.session.credential.token,
6672
+ runner.credentialsFile
6673
+ ];
6674
+ var exitProblem = (finished, command2, secrets, platform) => {
6048
6675
  if (finished.exitCode === 0) return null;
6049
- if (finished.exitCode === SHELL_COMMAND_NOT_FOUND) return notFound(command2);
6050
- return `exited with code ${finished.exitCode ?? "unknown"}`;
6676
+ if (SHELL_COMMAND_NOT_FOUND.includes(finished.exitCode ?? 0)) return notFound(command2, platform);
6677
+ const said2 = firstErrorLine(finished, secrets);
6678
+ return `exited with code ${finished.exitCode ?? "unknown"}${said2 === null ? "" : ` (${said2})`}`;
6051
6679
  };
6052
- var SHELL_COMMAND_NOT_FOUND = 127;
6053
- var notFound = (command2) => {
6680
+ var SHELL_COMMAND_NOT_FOUND = [127, 9009];
6681
+ var notFound = (command2, platform) => {
6054
6682
  const program = command2.trim().split(/\s+/)[0] ?? command2;
6055
- return `could not be found: "${program}" is not on the PATH this runs with; give its absolute path, such as /usr/local/bin/${program.replace(/^.*\//, "")}, or set PATH`;
6683
+ const name = program.replace(/^.*[\\/]/, "");
6684
+ const example = platform === "win32" ? `C:\\Users\\you\\AppData\\Roaming\\npm\\${name}.cmd` : `/usr/local/bin/${name}`;
6685
+ return `could not be found: "${program}" is not on the PATH this runs with; give its absolute path, such as ${example}, or set PATH`;
6056
6686
  };
6057
6687
  var labelsOf = (runner, reply) => ({
6058
6688
  client: runnerClient(runner.agent),
@@ -6170,7 +6800,12 @@ var runKeyService = {
6170
6800
  return result_exports.err(
6171
6801
  `A Windows service cannot hold a value with " or %: ${unsafe}. Give the agent command without them.`
6172
6802
  );
6173
- return result_exports.ok(commandLine(runnerCommand(paths.logPath, checked2)));
6803
+ const line = commandLine(runnerCommand(paths.logPath, checked2));
6804
+ if (line.length > COMMAND_LINE_MAX)
6805
+ return result_exports.err(
6806
+ `The service's command line would be ${line.length} characters, more than the ${COMMAND_LINE_MAX} Windows starts. Give shorter paths or a shorter agent command.`
6807
+ );
6808
+ return result_exports.ok(line);
6174
6809
  })(requirePrintable(spec)),
6175
6810
  install: (paths, definition, spec) => {
6176
6811
  const [program, ...args] = runnerCommand(paths.logPath, spec);
@@ -6198,6 +6833,7 @@ var runnerCommand = (logPath, spec) => [
6198
6833
  credentialsFile: spec.credentialsFile
6199
6834
  })
6200
6835
  ];
6836
+ var COMMAND_LINE_MAX = 32767;
6201
6837
  var commandLine = (words) => words.map(windowsArgument).join(" ");
6202
6838
  var isServiceAccount = (user) => {
6203
6839
  const name = user.split("\\").at(-1);
@@ -6294,6 +6930,7 @@ var serviceStatus = task_exports.gen(function* () {
6294
6930
  const running = manager.stopsThroughRunner ? yield* isClaimLive(paths.lockPath) : state?.running ?? false;
6295
6931
  const loaded = state?.loaded ?? false;
6296
6932
  const waitingFor = running ? yield* missingProgramOf(paths) : null;
6933
+ const agents = running && waitingFor === null ? yield* agentsOf(paths) : [];
6297
6934
  return outcome(
6298
6935
  {
6299
6936
  service: paths.name,
@@ -6304,6 +6941,7 @@ var serviceStatus = task_exports.gen(function* () {
6304
6941
  running,
6305
6942
  lastExit: state?.lastExit ?? null,
6306
6943
  waitingFor,
6944
+ agents,
6307
6945
  definition: paths.definitionPath,
6308
6946
  log: paths.logPath,
6309
6947
  signedIn: signInProblem === null
@@ -6314,6 +6952,7 @@ var serviceStatus = task_exports.gen(function* () {
6314
6952
  ...installed ? [
6315
6953
  `Running: ${running ? waitingFor === null ? "yes" : "yes, waiting for a missing program" : loaded ? "no" : "no, not loaded"}`,
6316
6954
  ...waitingFor === null ? [] : [`Waiting: ${waitingFor}`],
6955
+ ...agents.map((line) => `Agent: ${line}`),
6317
6956
  ...manager.stopsThroughRunner ? [] : [`Last exit: ${state?.lastExit ?? "none"}`]
6318
6957
  ] : [],
6319
6958
  `Log: ${paths.logPath}`,
@@ -6362,6 +7001,11 @@ var missingProgramOf = (paths) => task_exports.gen(function* () {
6362
7001
  const written = yield* env.files.read(serviceMissingPath(credentialDirectory(env), server));
6363
7002
  return written?.trim() || null;
6364
7003
  });
7004
+ var agentsOf = (paths) => task_exports.gen(function* () {
7005
+ const env = yield* task_exports.ask();
7006
+ const written = yield* env.files.read(serviceAgentsPath(credentialDirectory(env), paths.server));
7007
+ return (written ?? "").split("\n").filter((line) => line.trim() !== "");
7008
+ });
6365
7009
  var installedState = (manager, paths, needsState) => task_exports.gen(function* () {
6366
7010
  const env = yield* task_exports.ask();
6367
7011
  if (manager.writesFile) {
@@ -6508,7 +7152,7 @@ var PRIVATE_DIRECTORY_MODE = 448;
6508
7152
 
6509
7153
  // ../cli/src/node-launcher.ts
6510
7154
  import { spawn } from "node:child_process";
6511
- var nodeLauncher = (platform, start = spawn, kill = (pid, signal) => process.kill(pid, signal), agentErrors = "inherit", systemRoot = process.env.SystemRoot ?? "C:\\Windows") => ({
7155
+ var nodeLauncher = (platform, start = spawn, kill = (pid, signal) => process.kill(pid, signal), agentErrors = "inherit", systemRoot = process.env.SystemRoot ?? "C:\\Windows", writeError = (chunk) => void process.stderr.write(chunk)) => ({
6512
7156
  openInBrowser: (url) => {
6513
7157
  if (!isWebAddress(url)) return Promise.resolve(false);
6514
7158
  const [command2, ...args] = openerCommand(platform, url);
@@ -6523,14 +7167,17 @@ var nodeLauncher = (platform, start = spawn, kill = (pid, signal) => process.kil
6523
7167
  },
6524
7168
  runAgent: (command2, prompt, environment, signal) => new Promise((resolve, reject) => {
6525
7169
  const isWindows = platform === "win32";
6526
- const child = start(command2, [], {
6527
- stdio: ["pipe", "pipe", agentErrors],
6528
- shell: true,
7170
+ const [program, args] = isWindows ? cmdCommand(systemRoot, command2) : [command2, []];
7171
+ const child = start(program, args, {
7172
+ stdio: ["pipe", "pipe", "pipe"],
7173
+ shell: !isWindows,
6529
7174
  env: { ...environment },
6530
- ...isWindows ? { windowsHide: true } : { detached: true }
7175
+ ...isWindows ? { windowsHide: true, windowsVerbatimArguments: true } : { detached: true }
6531
7176
  });
6532
7177
  const chunks = [];
7178
+ const errorChunks = [];
6533
7179
  let size = 0;
7180
+ let errorSize = 0;
6534
7181
  const stopGroup = () => {
6535
7182
  if (isWindows) stopProcessTree(child.pid, start, systemRoot);
6536
7183
  else stopProcessGroup(child.pid, kill);
@@ -6543,15 +7190,28 @@ var nodeLauncher = (platform, start = spawn, kill = (pid, signal) => process.kil
6543
7190
  size += chunk.length;
6544
7191
  if (size <= AGENT_OUTPUT_MAX_BYTES) chunks.push(chunk);
6545
7192
  });
7193
+ child.stderr?.on("data", (chunk) => {
7194
+ if (agentErrors === "inherit") writeError(chunk);
7195
+ errorSize += chunk.length;
7196
+ if (errorSize <= AGENT_ERRORS_MAX_BYTES) errorChunks.push(chunk);
7197
+ });
6546
7198
  child.stdin?.on("error", () => {
6547
7199
  });
6548
7200
  child.once("error", reject);
6549
- child.once("close", (exitCode) => resolve({ exitCode, output: Buffer.concat(chunks).toString("utf8") }));
7201
+ child.once(
7202
+ "close",
7203
+ (exitCode) => resolve({
7204
+ exitCode,
7205
+ output: Buffer.concat(chunks).toString("utf8"),
7206
+ errors: Buffer.concat(errorChunks).toString("utf8")
7207
+ })
7208
+ );
6550
7209
  child.stdin?.end(prompt);
6551
7210
  })
6552
7211
  });
6553
7212
  var openerCommand = (platform, url) => platform === "darwin" ? ["open", url] : platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
6554
7213
  var AGENT_OUTPUT_MAX_BYTES = 1e6;
7214
+ var AGENT_ERRORS_MAX_BYTES = 64e3;
6555
7215
  var isWebAddress = (url) => URL.canParse(url) && ["http:", "https:"].includes(new URL(url).protocol);
6556
7216
  var taskkillCommand = (systemRoot, pid) => [
6557
7217
  `${systemRoot}\\System32\\taskkill.exe`,
@@ -6642,6 +7302,15 @@ var PERMISSION_BITS = 511;
6642
7302
  import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
6643
7303
  import { dirname as dirname2, join } from "node:path";
6644
7304
  var credentialFilePath = (environment, homeDirectory) => join(environment.XDG_CONFIG_HOME || join(homeDirectory, ".config"), "homingbird", "mcp-credentials.json");
7305
+ var readRunnerCredential = (path, serverUrl) => task_exports.catchAll(() => task_exports.succeed(null))(
7306
+ task_exports.gen(function* () {
7307
+ const text = yield* task_exports.tryPromise(() => readFile2(path, "utf8"), unreadable);
7308
+ const parsed3 = yield* task_exports.attempt(() => JSON.parse(text), unreadable);
7309
+ const decoded = RunnerCredential.decode(parsed3);
7310
+ if (decoded._tag === "Err") return null;
7311
+ return sameServer(decoded.value.serverUrl, serverUrl) ? decoded.value.token : null;
7312
+ })
7313
+ );
6645
7314
  var readCredential2 = (path, serverUrl) => task_exports.map((all3) => all3[serverUrl] ?? null)(readAll(path));
6646
7315
  var storeCredential = (path, serverUrl, credential) => task_exports.flatMap((all3) => writeAll(path, { ...all3, [serverUrl]: credential }))(readAll(path));
6647
7316
  var removeCredential2 = (path, serverUrl) => task_exports.flatMap((all3) => {
@@ -6664,6 +7333,11 @@ var readAll = (path) => task_exports.catchAll(() => task_exports.succeed({}))(
6664
7333
  })
6665
7334
  );
6666
7335
  var unreadable = () => "unreadable";
7336
+ var RunnerCredential = schema_exports.struct({
7337
+ serverUrl: schema_exports.string({ pattern: /^https?:\/\// }),
7338
+ token: schema_exports.string({ minLength: 1 })
7339
+ });
7340
+ var sameServer = (a, b) => a.replace(/\/+$/, "") === b.replace(/\/+$/, "");
6667
7341
 
6668
7342
  // src/browser-opener.ts
6669
7343
  var browserOpener = (launch, platform, serverUrl) => (url) => isWithin(serverUrl, url) ? task_exports.catchAll(() => task_exports.succeed(false))(
@@ -6705,11 +7379,6 @@ var waitingTriggers = (context, except = /* @__PURE__ */ new Set()) => task_expo
6705
7379
  var waitingNoteIds = (context) => task_exports.map(
6706
7380
  ({ items }) => new Set(items.map((item) => item.note.id))
6707
7381
  )(context.api["inbox.list"]({ query: {} }));
6708
- var WAKING_EVENTS = [
6709
- "note.sent",
6710
- "draft.requested",
6711
- "resync"
6712
- ];
6713
7382
  var announcedRequests = () => {
6714
7383
  const seen = /* @__PURE__ */ new Set();
6715
7384
  return { has: (id) => seen.has(id), add: (id) => void seen.add(id) };
@@ -6808,7 +7477,7 @@ var makeChannel = (context, write) => {
6808
7477
  isOpen = true;
6809
7478
  }),
6810
7479
  online: pushWhenOpen,
6811
- received: (event2) => WAKING_EVENTS.includes(event2.body.type) ? pushWhenOpen : task_exports.unit
7480
+ received: (event2) => isWakingEvent(event2.body, null) ? pushWhenOpen : task_exports.unit
6812
7481
  };
6813
7482
  };
6814
7483
  var channelNotification = (trigger) => ({
@@ -6951,6 +7620,8 @@ var BASIS_DESCRIPTION = 'What you read or relied on for this draft, such as "Rea
6951
7620
  var SIGN_IN_FIRST = "Not signed in to Homingbird. Call the login tool first.";
6952
7621
  var ANALYTICS_NOTICE2 = "This Homingbird server counts anonymous usage from the web client and the command line, never notes, names or email addresses; this MCP adapter sends none. People turn it off with `homingbird analytics off` or DO_NOT_TRACK=1.";
6953
7622
  var makeLocalSession = (options) => {
7623
+ const runnerCredential = options.runnerCredentialPath ?? null;
7624
+ if (runnerCredential !== null) return runnersSession(options, runnerCredential);
6954
7625
  const { serverUrl, credentialPath, scope, clock } = options;
6955
7626
  const fetching = options.fetch !== void 0 ? { fetch: options.fetch } : {};
6956
7627
  const flow = {
@@ -7082,6 +7753,37 @@ The code ${pending.userCode} is already filled in: one click there finishes it.
7082
7753
  })
7083
7754
  };
7084
7755
  };
7756
+ var runnersSession = (options, path) => {
7757
+ const { serverUrl } = options;
7758
+ const fetching = options.fetch !== void 0 ? { fetch: options.fetch } : {};
7759
+ let token = null;
7760
+ let refused2 = false;
7761
+ const signedOutText = () => `Not signed in to ${serverUrl}: ${refused2 ? "the server no longer accepts" : "this server could not read"} the runner\u2019s credential in ${path}. Sign in again with homingbird login.`;
7762
+ return {
7763
+ state: () => token === null ? { kind: "signed_out", note: null } : { kind: "signed_in" },
7764
+ token: () => token,
7765
+ protocolProblem: () => null,
7766
+ credentialWasRefused: () => {
7767
+ token = null;
7768
+ refused2 = true;
7769
+ },
7770
+ restore: task_exports.map((read2) => void (token = read2))(readRunnerCredential(path, serverUrl)),
7771
+ login: task_exports.succeed(RUNNERS_CREDENTIAL),
7772
+ logout: task_exports.succeed(RUNNERS_CREDENTIAL),
7773
+ status: task_exports.gen(function* () {
7774
+ if (token === null) return signedOutText();
7775
+ const me = yield* task_exports.result(httpApi({ serverUrl, token: () => token, ...fetching })["me.get"]({}));
7776
+ if (me._tag === "Ok")
7777
+ return `Signed in to ${serverUrl} as ${me.value.member.name} <${me.value.member.email}>, with the runner\u2019s credential "${me.value.credential.name}".`;
7778
+ if (me.error._tag !== "Unauthorized")
7779
+ return `Signed in to ${serverUrl}, but it cannot be reached right now.`;
7780
+ token = null;
7781
+ refused2 = true;
7782
+ return signedOutText();
7783
+ })
7784
+ };
7785
+ };
7786
+ var RUNNERS_CREDENTIAL = "This Homingbird server was started by homingbird run for one agent run, with the runner\u2019s own credential: there is nothing to sign in or out of here.";
7085
7787
  var REVOKED_AND_REMOVED = "Signed out of Homingbird. The server revoked the credential, and it was removed from this device.";
7086
7788
  var REMOVED_ONLY_HERE = "Signed out of Homingbird on this device only: the credential was removed here, but the server did not confirm that it revoked it, so it may still work. Revoke it in the web client's device list.";
7087
7789
  var EXPIRY_MARGIN_MS = 6e4;
@@ -7549,6 +8251,7 @@ var webClientLink2 = (webClientUrl, conversationId) => {
7549
8251
  const base2 = webClientUrl.replace(/\/+$/, "");
7550
8252
  return conversationId === null ? `${base2}/` : `${base2}/#/c/${conversationId}`;
7551
8253
  };
8254
+ var draftLink2 = (webClientUrl, draft2) => `${webClientUrl.replace(/\/+$/, "")}/#/c/${encodeURIComponent(draft2.conversationId)}?draft=${encodeURIComponent(draft2.id)}`;
7552
8255
 
7553
8256
  // src/tools.ts
7554
8257
  var WAIT_MAX_SECONDS = 50;
@@ -7837,13 +8540,13 @@ var TOOLS = [
7837
8540
  input: { conversationId: schema_exports.optional(ConversationId), draftId: schema_exports.optional(NoteId) },
7838
8541
  describe: {
7839
8542
  conversationId: "Open this conversation. Leave out to open the front page.",
7840
- draftId: "Open the conversation this draft is waiting in."
8543
+ draftId: "Open this draft\u2019s card in the conversation it is waiting in."
7841
8544
  },
7842
8545
  run: ({ conversationId, draftId }, context) => task_exports.gen(function* () {
7843
8546
  if (context.webClientUrl === null)
7844
8547
  return "The address of the Homingbird web client is not known here. Ask your human to open their Homingbird in a browser.";
7845
- const target2 = conversationId ?? (draftId === void 0 ? null : (yield* context.api["notes.get"]({ params: { id: draftId } })).conversationId);
7846
- const link = webClientLink2(context.webClientUrl, target2);
8548
+ const draft2 = conversationId === void 0 && draftId !== void 0 ? yield* context.api["notes.get"]({ params: { id: draftId } }) : null;
8549
+ const link = draft2 === null ? webClientLink2(context.webClientUrl, conversationId ?? null) : draft2.status === "draft" ? draftLink2(context.webClientUrl, draft2) : webClientLink2(context.webClientUrl, draft2.conversationId);
7847
8550
  const opened = context.openInBrowser === void 0 ? false : yield* context.openInBrowser(link);
7848
8551
  return opened ? `Opened ${link} in your human's browser. Tell them it is open, and show the link in case it did not come to the front.` : `Show this link to your human: ${link}
7849
8552
  They approve, edit or discard drafts there. Opening it sends nothing.`;
@@ -7944,7 +8647,7 @@ var arrived = (triggers) => [
7944
8647
  ...triggers.map((trigger) => trigger.text)
7945
8648
  ].join("\n\n");
7946
8649
  var awaitingApproval = (draft2, context) => {
7947
- const where = context.webClientUrl === null ? "" : ` at ${webClientLink2(context.webClientUrl, draft2.conversationId)}`;
8650
+ const where = context.webClientUrl === null ? "" : ` at ${draftLink2(context.webClientUrl, draft2)}`;
7948
8651
  return `Draft ${draft2.id} is saved in conversation ${draft2.conversationId}. It has NOT been sent. Your human has to approve it in the Homingbird web client${where}. Show them that link. ${APPROVAL_RULE}`;
7949
8652
  };
7950
8653
  var DESK_INBOX_ADVICE = "For each note, call draft_reply with its note id; for each request, call draft_note with its requestId.";
@@ -8018,12 +8721,16 @@ var METHODS = {
8018
8721
  "tools/list": (_, context) => task_exports.map((debates2) => ({
8019
8722
  tools: [
8020
8723
  ...(context.local?.tools ?? []).map(localDefinition),
8021
- ...toolDefinitions().filter((tool3) => debates2 || !DEBATE_TOOL_NAMES.includes(String(tool3.name)))
8724
+ ...toolDefinitions().filter(
8725
+ (tool3) => (debates2 || !DEBATE_TOOL_NAMES.includes(String(tool3.name))) && !(context.withheldTools ?? []).includes(String(tool3.name))
8726
+ )
8022
8727
  ]
8023
8728
  }))((context.local?.blockedBecause() ?? null) === null ? offersDebates(context.api) : task_exports.succeed(true)),
8024
8729
  "tools/call": (params, context) => {
8025
8730
  const local = context.local?.tools.find((each) => each.name === params.name);
8026
8731
  if (local !== void 0) return task_exports.map(said)(local.run);
8732
+ if ((context.withheldTools ?? []).includes(String(params.name)))
8733
+ return task_exports.fail(invalidParams(`Unknown tool: ${String(params.name)}`));
8027
8734
  const blocked = context.local?.blockedBecause() ?? null;
8028
8735
  if (blocked !== null) return task_exports.succeed(refused(blocked));
8029
8736
  return task_exports.map((result2) => {
@@ -8138,10 +8845,18 @@ var USAGE2 = [
8138
8845
  " the agent command by default. Also HOMINGBIRD_READER.",
8139
8846
  " --require-toolless-reader Refuse to start when the reader is the agent command itself.",
8140
8847
  "",
8848
+ "HOMINGBIRD_CREDENTIALS_FILE names the credential file of the runner that started this server for",
8849
+ "one agent run, as homingbird run --attach-mcp does; it then only reads that file.",
8850
+ "",
8141
8851
  "Signing in happens from the MCP client: ask your agent to log in."
8142
8852
  ].join("\n");
8853
+ var RUNNERS_SERVER_ONLY = "HOMINGBIRD_CREDENTIALS_FILE is set: this server answers one agent run of homingbird run, so it takes no --run-agent, --desk or --channel.";
8854
+ var RUNNER_WITHHELD_TOOLS = ["skip_note", "wait_for_notes"];
8143
8855
  var runStdioProgram = (program) => task_exports.gen(function* () {
8144
8856
  const options = yield* task_exports.fromResult(optionsFrom(program));
8857
+ const runnerCredentialPath = program.environment.HOMINGBIRD_CREDENTIALS_FILE?.trim() || null;
8858
+ if (runnerCredentialPath !== null && (options.agent !== null || options.isChannel))
8859
+ return yield* task_exports.fail(ProgramFailed({ message: RUNNERS_SERVER_ONLY }));
8145
8860
  const deskEnv = program.deskEnv;
8146
8861
  if (options.agent !== null && deskEnv === void 0)
8147
8862
  return yield* task_exports.fail(ProgramFailed({ message: "This build of homingbird-mcp cannot run a desk." }));
@@ -8168,6 +8883,7 @@ var runStdioProgram = (program) => task_exports.gen(function* () {
8168
8883
  serverUrl: options.serverUrl,
8169
8884
  clientName: options.clientName,
8170
8885
  credentialPath: program.credentialPath,
8886
+ runnerCredentialPath,
8171
8887
  scope,
8172
8888
  clock,
8173
8889
  ...fetching,
@@ -8186,6 +8902,7 @@ var runStdioProgram = (program) => task_exports.gen(function* () {
8186
8902
  local: localAdapterOf(session, desk2),
8187
8903
  desk: options.isDesk,
8188
8904
  announced,
8905
+ ...runnerCredentialPath !== null && { withheldTools: RUNNER_WITHHELD_TOOLS },
8189
8906
  ...opening,
8190
8907
  ...channel !== null && {
8191
8908
  channel: {
@@ -8233,7 +8950,7 @@ ${USAGE2}` })
8233
8950
  agent: agent === "" ? null : agent,
8234
8951
  split: isSplit ? { reader: reader === "" ? agent : reader, requireToollessReader } : null,
8235
8952
  serverUrl: serverUrl.replace(/\/+$/, ""),
8236
- clientName: flag("--name") ?? `MCP agent on ${program.hostName}`,
8953
+ clientName: flag("--name") ?? "MCP agent",
8237
8954
  isChannel: program.arguments.includes("--channel") || program.arguments.includes("--desk"),
8238
8955
  isDesk: program.arguments.includes("--desk")
8239
8956
  }) : err(ProgramFailed({ message: USAGE2 }));
@@ -8241,7 +8958,7 @@ ${USAGE2}` })
8241
8958
  var ProgramFailed = tagged("ProgramFailed")();
8242
8959
 
8243
8960
  // src/version.ts
8244
- var ADAPTER_VERSION = "0.3.1";
8961
+ var ADAPTER_VERSION = "0.3.2";
8245
8962
 
8246
8963
  // src/stdio.ts
8247
8964
  var NONCE_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
@@ -8252,7 +8969,6 @@ var exit2 = await task_exports.run(
8252
8969
  arguments: process.argv.slice(2),
8253
8970
  environment: process.env,
8254
8971
  credentialPath: credentialFilePath(process.env, homedir()),
8255
- hostName: hostname(),
8256
8972
  version: ADAPTER_VERSION,
8257
8973
  input: process.stdin,
8258
8974
  write: (line) => process.stdout.write(line),