@botiverse/raft-daemon 0.69.0 → 0.70.1

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.
@@ -31,6 +31,9 @@ import fs5 from "fs";
31
31
  import os4 from "os";
32
32
  import path8 from "path";
33
33
  import fs6 from "fs";
34
+ import os5 from "os";
35
+ import path9 from "path";
36
+ import fs7 from "fs";
34
37
  var require2 = __raftCreateRequire(import.meta.url);
35
38
  var __create = Object.create;
36
39
  var __defProp = Object.defineProperty;
@@ -1013,8 +1016,8 @@ var require_command = __commonJS({
1013
1016
  init_esm_shims();
1014
1017
  var EventEmitter = __require("events").EventEmitter;
1015
1018
  var childProcess = __require("child_process");
1016
- var path9 = __require("path");
1017
- var fs7 = __require("fs");
1019
+ var path10 = __require("path");
1020
+ var fs8 = __require("fs");
1018
1021
  var process3 = __require("process");
1019
1022
  var { Argument: Argument2, humanReadableArgName } = require_argument();
1020
1023
  var { CommanderError: CommanderError2 } = require_error();
@@ -1946,11 +1949,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
1946
1949
  let launchWithNode = false;
1947
1950
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1948
1951
  function findFile(baseDir, baseName) {
1949
- const localBin = path9.resolve(baseDir, baseName);
1950
- if (fs7.existsSync(localBin)) return localBin;
1951
- if (sourceExt.includes(path9.extname(baseName))) return void 0;
1952
+ const localBin = path10.resolve(baseDir, baseName);
1953
+ if (fs8.existsSync(localBin)) return localBin;
1954
+ if (sourceExt.includes(path10.extname(baseName))) return void 0;
1952
1955
  const foundExt = sourceExt.find(
1953
- (ext) => fs7.existsSync(`${localBin}${ext}`)
1956
+ (ext) => fs8.existsSync(`${localBin}${ext}`)
1954
1957
  );
1955
1958
  if (foundExt) return `${localBin}${foundExt}`;
1956
1959
  return void 0;
@@ -1962,21 +1965,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
1962
1965
  if (this._scriptPath) {
1963
1966
  let resolvedScriptPath;
1964
1967
  try {
1965
- resolvedScriptPath = fs7.realpathSync(this._scriptPath);
1968
+ resolvedScriptPath = fs8.realpathSync(this._scriptPath);
1966
1969
  } catch (err) {
1967
1970
  resolvedScriptPath = this._scriptPath;
1968
1971
  }
1969
- executableDir = path9.resolve(
1970
- path9.dirname(resolvedScriptPath),
1972
+ executableDir = path10.resolve(
1973
+ path10.dirname(resolvedScriptPath),
1971
1974
  executableDir
1972
1975
  );
1973
1976
  }
1974
1977
  if (executableDir) {
1975
1978
  let localFile = findFile(executableDir, executableFile);
1976
1979
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
1977
- const legacyName = path9.basename(
1980
+ const legacyName = path10.basename(
1978
1981
  this._scriptPath,
1979
- path9.extname(this._scriptPath)
1982
+ path10.extname(this._scriptPath)
1980
1983
  );
1981
1984
  if (legacyName !== this._name) {
1982
1985
  localFile = findFile(
@@ -1987,7 +1990,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1987
1990
  }
1988
1991
  executableFile = localFile || executableFile;
1989
1992
  }
1990
- launchWithNode = sourceExt.includes(path9.extname(executableFile));
1993
+ launchWithNode = sourceExt.includes(path10.extname(executableFile));
1991
1994
  let proc;
1992
1995
  if (process3.platform !== "win32") {
1993
1996
  if (launchWithNode) {
@@ -2827,7 +2830,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2827
2830
  * @return {Command}
2828
2831
  */
2829
2832
  nameFromFilename(filename) {
2830
- this._name = path9.basename(filename, path9.extname(filename));
2833
+ this._name = path10.basename(filename, path10.extname(filename));
2831
2834
  return this;
2832
2835
  }
2833
2836
  /**
@@ -2841,9 +2844,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2841
2844
  * @param {string} [path]
2842
2845
  * @return {(string|null|Command)}
2843
2846
  */
2844
- executableDir(path10) {
2845
- if (path10 === void 0) return this._executableDir;
2846
- this._executableDir = path10;
2847
+ executableDir(path11) {
2848
+ if (path11 === void 0) return this._executableDir;
2849
+ this._executableDir = path11;
2847
2850
  return this;
2848
2851
  }
2849
2852
  /**
@@ -4175,14 +4178,14 @@ var require_util = __commonJS({
4175
4178
  }
4176
4179
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
4177
4180
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
4178
- let path9 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
4181
+ let path10 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
4179
4182
  if (origin[origin.length - 1] === "/") {
4180
4183
  origin = origin.slice(0, origin.length - 1);
4181
4184
  }
4182
- if (path9 && path9[0] !== "/") {
4183
- path9 = `/${path9}`;
4185
+ if (path10 && path10[0] !== "/") {
4186
+ path10 = `/${path10}`;
4184
4187
  }
4185
- return new URL(`${origin}${path9}`);
4188
+ return new URL(`${origin}${path10}`);
4186
4189
  }
4187
4190
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
4188
4191
  throw new InvalidArgumentError2("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -5001,9 +5004,9 @@ var require_diagnostics = __commonJS({
5001
5004
  "undici:client:sendHeaders",
5002
5005
  (evt) => {
5003
5006
  const {
5004
- request: { method, path: path9, origin }
5007
+ request: { method, path: path10, origin }
5005
5008
  } = evt;
5006
- debugLog("sending request to %s %s%s", method, origin, path9);
5009
+ debugLog("sending request to %s %s%s", method, origin, path10);
5007
5010
  }
5008
5011
  );
5009
5012
  }
@@ -5021,14 +5024,14 @@ var require_diagnostics = __commonJS({
5021
5024
  "undici:request:headers",
5022
5025
  (evt) => {
5023
5026
  const {
5024
- request: { method, path: path9, origin },
5027
+ request: { method, path: path10, origin },
5025
5028
  response: { statusCode }
5026
5029
  } = evt;
5027
5030
  debugLog(
5028
5031
  "received response to %s %s%s - HTTP %d",
5029
5032
  method,
5030
5033
  origin,
5031
- path9,
5034
+ path10,
5032
5035
  statusCode
5033
5036
  );
5034
5037
  }
@@ -5037,23 +5040,23 @@ var require_diagnostics = __commonJS({
5037
5040
  "undici:request:trailers",
5038
5041
  (evt) => {
5039
5042
  const {
5040
- request: { method, path: path9, origin }
5043
+ request: { method, path: path10, origin }
5041
5044
  } = evt;
5042
- debugLog("trailers received from %s %s%s", method, origin, path9);
5045
+ debugLog("trailers received from %s %s%s", method, origin, path10);
5043
5046
  }
5044
5047
  );
5045
5048
  diagnosticsChannel.subscribe(
5046
5049
  "undici:request:error",
5047
5050
  (evt) => {
5048
5051
  const {
5049
- request: { method, path: path9, origin },
5052
+ request: { method, path: path10, origin },
5050
5053
  error: error48
5051
5054
  } = evt;
5052
5055
  debugLog(
5053
5056
  "request to %s %s%s errored - %s",
5054
5057
  method,
5055
5058
  origin,
5056
- path9,
5059
+ path10,
5057
5060
  error48.message
5058
5061
  );
5059
5062
  }
@@ -5155,7 +5158,7 @@ var require_request = __commonJS({
5155
5158
  var kHandler = /* @__PURE__ */ Symbol("handler");
5156
5159
  var Request = class {
5157
5160
  constructor(origin, {
5158
- path: path9,
5161
+ path: path10,
5159
5162
  method,
5160
5163
  body,
5161
5164
  headers,
@@ -5172,11 +5175,11 @@ var require_request = __commonJS({
5172
5175
  maxRedirections,
5173
5176
  typeOfService
5174
5177
  }, handler) {
5175
- if (typeof path9 !== "string") {
5178
+ if (typeof path10 !== "string") {
5176
5179
  throw new InvalidArgumentError2("path must be a string");
5177
- } else if (path9[0] !== "/" && !(path9.startsWith("http://") || path9.startsWith("https://")) && method !== "CONNECT") {
5180
+ } else if (path10[0] !== "/" && !(path10.startsWith("http://") || path10.startsWith("https://")) && method !== "CONNECT") {
5178
5181
  throw new InvalidArgumentError2("path must be an absolute URL or start with a slash");
5179
- } else if (invalidPathRegex.test(path9)) {
5182
+ } else if (invalidPathRegex.test(path10)) {
5180
5183
  throw new InvalidArgumentError2("invalid request path");
5181
5184
  }
5182
5185
  if (typeof method !== "string") {
@@ -5251,7 +5254,7 @@ var require_request = __commonJS({
5251
5254
  this.completed = false;
5252
5255
  this.aborted = false;
5253
5256
  this.upgrade = upgrade || null;
5254
- this.path = query ? serializePathWithQuery(path9, query) : path9;
5257
+ this.path = query ? serializePathWithQuery(path10, query) : path10;
5255
5258
  this.origin = origin;
5256
5259
  this.protocol = getProtocolFromUrlString(origin);
5257
5260
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -10268,7 +10271,7 @@ var require_client_h1 = __commonJS({
10268
10271
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
10269
10272
  }
10270
10273
  function writeH1(client, request) {
10271
- const { method, path: path9, host, upgrade, blocking, reset } = request;
10274
+ const { method, path: path10, host, upgrade, blocking, reset } = request;
10272
10275
  let { body, headers, contentLength } = request;
10273
10276
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
10274
10277
  if (util.isFormDataLike(body)) {
@@ -10337,7 +10340,7 @@ var require_client_h1 = __commonJS({
10337
10340
  if (socket.setTypeOfService) {
10338
10341
  socket.setTypeOfService(request.typeOfService);
10339
10342
  }
10340
- let header = `${method} ${path9} HTTP/1.1\r
10343
+ let header = `${method} ${path10} HTTP/1.1\r
10341
10344
  `;
10342
10345
  if (typeof host === "string") {
10343
10346
  header += `host: ${host}\r
@@ -10989,7 +10992,7 @@ var require_client_h2 = __commonJS({
10989
10992
  function writeH2(client, request) {
10990
10993
  const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout];
10991
10994
  const session = client[kHTTP2Session];
10992
- const { method, path: path9, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
10995
+ const { method, path: path10, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
10993
10996
  let { body } = request;
10994
10997
  if (upgrade != null && upgrade !== "websocket") {
10995
10998
  util.errorRequest(client, request, new InvalidArgumentError2(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -11057,7 +11060,7 @@ var require_client_h2 = __commonJS({
11057
11060
  }
11058
11061
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
11059
11062
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
11060
- headers[HTTP2_HEADER_PATH] = path9;
11063
+ headers[HTTP2_HEADER_PATH] = path10;
11061
11064
  if (protocol === "ws:" || protocol === "wss:") {
11062
11065
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
11063
11066
  } else {
@@ -11098,7 +11101,7 @@ var require_client_h2 = __commonJS({
11098
11101
  stream.setTimeout(requestTimeout);
11099
11102
  return true;
11100
11103
  }
11101
- headers[HTTP2_HEADER_PATH] = path9;
11104
+ headers[HTTP2_HEADER_PATH] = path10;
11102
11105
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
11103
11106
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
11104
11107
  if (body && typeof body.read === "function") {
@@ -13389,10 +13392,10 @@ var require_proxy_agent = __commonJS({
13389
13392
  };
13390
13393
  const {
13391
13394
  origin,
13392
- path: path9 = "/",
13395
+ path: path10 = "/",
13393
13396
  headers = {}
13394
13397
  } = opts;
13395
- opts.path = origin + path9;
13398
+ opts.path = origin + path10;
13396
13399
  if (!("host" in headers) && !("Host" in headers)) {
13397
13400
  const { host } = new URL(origin);
13398
13401
  headers.host = host;
@@ -15440,20 +15443,20 @@ var require_mock_utils = __commonJS({
15440
15443
  }
15441
15444
  return normalizedQp;
15442
15445
  }
15443
- function safeUrl2(path9) {
15444
- if (typeof path9 !== "string") {
15445
- return path9;
15446
+ function safeUrl3(path10) {
15447
+ if (typeof path10 !== "string") {
15448
+ return path10;
15446
15449
  }
15447
- const pathSegments = path9.split("?", 3);
15450
+ const pathSegments = path10.split("?", 3);
15448
15451
  if (pathSegments.length !== 2) {
15449
- return path9;
15452
+ return path10;
15450
15453
  }
15451
15454
  const qp = new URLSearchParams(pathSegments.pop());
15452
15455
  qp.sort();
15453
15456
  return [...pathSegments, qp.toString()].join("?");
15454
15457
  }
15455
- function matchKey(mockDispatch2, { path: path9, method, body, headers }) {
15456
- const pathMatch = matchValue(mockDispatch2.path, path9);
15458
+ function matchKey(mockDispatch2, { path: path10, method, body, headers }) {
15459
+ const pathMatch = matchValue(mockDispatch2.path, path10);
15457
15460
  const methodMatch = matchValue(mockDispatch2.method, method);
15458
15461
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
15459
15462
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -15476,10 +15479,10 @@ var require_mock_utils = __commonJS({
15476
15479
  }
15477
15480
  function getMockDispatch(mockDispatches, key) {
15478
15481
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
15479
- const resolvedPath = typeof basePath === "string" ? safeUrl2(basePath) : basePath;
15482
+ const resolvedPath = typeof basePath === "string" ? safeUrl3(basePath) : basePath;
15480
15483
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
15481
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path9, ignoreTrailingSlash }) => {
15482
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl2(path9)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl2(path9), resolvedPath);
15484
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path10, ignoreTrailingSlash }) => {
15485
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl3(path10)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl3(path10), resolvedPath);
15483
15486
  });
15484
15487
  if (matchedMockDispatches.length === 0) {
15485
15488
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -15518,19 +15521,19 @@ var require_mock_utils = __commonJS({
15518
15521
  mockDispatches.splice(index, 1);
15519
15522
  }
15520
15523
  }
15521
- function removeTrailingSlash(path9) {
15522
- while (path9.endsWith("/")) {
15523
- path9 = path9.slice(0, -1);
15524
+ function removeTrailingSlash(path10) {
15525
+ while (path10.endsWith("/")) {
15526
+ path10 = path10.slice(0, -1);
15524
15527
  }
15525
- if (path9.length === 0) {
15526
- path9 = "/";
15528
+ if (path10.length === 0) {
15529
+ path10 = "/";
15527
15530
  }
15528
- return path9;
15531
+ return path10;
15529
15532
  }
15530
15533
  function buildKey(opts) {
15531
- const { path: path9, method, body, headers, query } = opts;
15534
+ const { path: path10, method, body, headers, query } = opts;
15532
15535
  return {
15533
- path: path9,
15536
+ path: path10,
15534
15537
  method,
15535
15538
  body,
15536
15539
  headers,
@@ -16215,10 +16218,10 @@ var require_pending_interceptors_formatter = __commonJS({
16215
16218
  }
16216
16219
  format(pendingInterceptors) {
16217
16220
  const withPrettyHeaders = pendingInterceptors.map(
16218
- ({ method, path: path9, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
16221
+ ({ method, path: path10, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
16219
16222
  Method: method,
16220
16223
  Origin: origin,
16221
- Path: path9,
16224
+ Path: path10,
16222
16225
  "Status code": statusCode,
16223
16226
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
16224
16227
  Invocations: timesInvoked,
@@ -16299,9 +16302,9 @@ var require_mock_agent = __commonJS({
16299
16302
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
16300
16303
  const dispatchOpts = { ...opts };
16301
16304
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
16302
- const [path9, searchParams] = dispatchOpts.path.split("?");
16305
+ const [path10, searchParams] = dispatchOpts.path.split("?");
16303
16306
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
16304
- dispatchOpts.path = `${path9}?${normalizedSearchParams}`;
16307
+ dispatchOpts.path = `${path10}?${normalizedSearchParams}`;
16305
16308
  }
16306
16309
  return this[kAgent].dispatch(dispatchOpts, handler);
16307
16310
  }
@@ -16700,12 +16703,12 @@ var require_snapshot_recorder = __commonJS({
16700
16703
  * @return {Promise<void>} - Resolves when snapshots are loaded
16701
16704
  */
16702
16705
  async loadSnapshots(filePath) {
16703
- const path9 = filePath || this.#snapshotPath;
16704
- if (!path9) {
16706
+ const path10 = filePath || this.#snapshotPath;
16707
+ if (!path10) {
16705
16708
  throw new InvalidArgumentError2("Snapshot path is required");
16706
16709
  }
16707
16710
  try {
16708
- const data = await readFile2(resolve(path9), "utf8");
16711
+ const data = await readFile2(resolve(path10), "utf8");
16709
16712
  const parsed = JSON.parse(data);
16710
16713
  if (Array.isArray(parsed)) {
16711
16714
  this.#snapshots.clear();
@@ -16719,7 +16722,7 @@ var require_snapshot_recorder = __commonJS({
16719
16722
  if (error48.code === "ENOENT") {
16720
16723
  this.#snapshots.clear();
16721
16724
  } else {
16722
- throw new UndiciError(`Failed to load snapshots from ${path9}`, { cause: error48 });
16725
+ throw new UndiciError(`Failed to load snapshots from ${path10}`, { cause: error48 });
16723
16726
  }
16724
16727
  }
16725
16728
  }
@@ -16730,11 +16733,11 @@ var require_snapshot_recorder = __commonJS({
16730
16733
  * @returns {Promise<void>} - Resolves when snapshots are saved
16731
16734
  */
16732
16735
  async saveSnapshots(filePath) {
16733
- const path9 = filePath || this.#snapshotPath;
16734
- if (!path9) {
16736
+ const path10 = filePath || this.#snapshotPath;
16737
+ if (!path10) {
16735
16738
  throw new InvalidArgumentError2("Snapshot path is required");
16736
16739
  }
16737
- const resolvedPath = resolve(path9);
16740
+ const resolvedPath = resolve(path10);
16738
16741
  await mkdir2(dirname(resolvedPath), { recursive: true });
16739
16742
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
16740
16743
  hash: hash2,
@@ -17355,15 +17358,15 @@ var require_redirect_handler = __commonJS({
17355
17358
  return;
17356
17359
  }
17357
17360
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
17358
- const path9 = search ? `${pathname}${search}` : pathname;
17359
- const redirectUrlString = `${origin}${path9}`;
17361
+ const path10 = search ? `${pathname}${search}` : pathname;
17362
+ const redirectUrlString = `${origin}${path10}`;
17360
17363
  for (const historyUrl of this.history) {
17361
17364
  if (historyUrl.toString() === redirectUrlString) {
17362
17365
  throw new InvalidArgumentError2(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
17363
17366
  }
17364
17367
  }
17365
17368
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
17366
- this.opts.path = path9;
17369
+ this.opts.path = path10;
17367
17370
  this.opts.origin = origin;
17368
17371
  this.opts.query = null;
17369
17372
  }
@@ -23550,11 +23553,11 @@ var require_fetch = __commonJS({
23550
23553
  function dispatch({ body }) {
23551
23554
  const url2 = requestCurrentURL(request);
23552
23555
  const agent = fetchParams.controller.dispatcher;
23553
- const path9 = url2.pathname + url2.search;
23556
+ const path10 = url2.pathname + url2.search;
23554
23557
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
23555
23558
  return new Promise((resolve, reject) => agent.dispatch(
23556
23559
  {
23557
- path: hasTrailingQuestionMark ? `${path9}?` : path9,
23560
+ path: hasTrailingQuestionMark ? `${path10}?` : path10,
23558
23561
  origin: url2.origin,
23559
23562
  method: request.method,
23560
23563
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
@@ -24496,9 +24499,9 @@ var require_util4 = __commonJS({
24496
24499
  }
24497
24500
  }
24498
24501
  }
24499
- function validateCookiePath(path9) {
24500
- for (let i = 0; i < path9.length; ++i) {
24501
- const code = path9.charCodeAt(i);
24502
+ function validateCookiePath(path10) {
24503
+ for (let i = 0; i < path10.length; ++i) {
24504
+ const code = path10.charCodeAt(i);
24502
24505
  if (code < 32 || // exclude CTLs (0-31)
24503
24506
  code === 127 || // DEL
24504
24507
  code === 59) {
@@ -27651,11 +27654,11 @@ var require_undici = __commonJS({
27651
27654
  if (typeof opts.path !== "string") {
27652
27655
  throw new InvalidArgumentError2("invalid opts.path");
27653
27656
  }
27654
- let path9 = opts.path;
27657
+ let path10 = opts.path;
27655
27658
  if (!opts.path.startsWith("/")) {
27656
- path9 = `/${path9}`;
27659
+ path10 = `/${path10}`;
27657
27660
  }
27658
- url2 = new URL(util.parseOrigin(url2).origin + path9);
27661
+ url2 = new URL(util.parseOrigin(url2).origin + path10);
27659
27662
  } else {
27660
27663
  if (!opts) {
27661
27664
  opts = typeof url2 === "object" ? url2 : {};
@@ -28506,6 +28509,123 @@ function randomHex(length) {
28506
28509
  return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
28507
28510
  }
28508
28511
  init_esm_shims();
28512
+ var PROMOTED_IDENTITY_ATTRS = [
28513
+ "server_id",
28514
+ "machine_id",
28515
+ "agent_id",
28516
+ "launch_id",
28517
+ "session_id",
28518
+ "request_id",
28519
+ "route_pattern",
28520
+ "caller_kind"
28521
+ ];
28522
+ var PROMOTED_CLOSED_ATTRS = [
28523
+ "outcome",
28524
+ "reason",
28525
+ "event_kind",
28526
+ "source",
28527
+ "authority",
28528
+ "activity_write_site",
28529
+ "activity_source",
28530
+ "hint_source",
28531
+ "resolved_activity",
28532
+ "previous_activity",
28533
+ "next_activity",
28534
+ "repair_kind",
28535
+ "action",
28536
+ "error_class",
28537
+ "status_bucket",
28538
+ "shadow_agent_id",
28539
+ "shadow_signal_site",
28540
+ "shadow_observation_class",
28541
+ "shadow_prior_projection",
28542
+ "shadow_projection",
28543
+ "shadow_legacy_outcome",
28544
+ "shadow_action",
28545
+ "shadow_reason",
28546
+ "shadow_direction",
28547
+ "shadow_plan_kind"
28548
+ ];
28549
+ var TRACE_EVENT_ROW_PROMOTED_ATTRS = [
28550
+ ...PROMOTED_IDENTITY_ATTRS,
28551
+ ...PROMOTED_CLOSED_ATTRS
28552
+ ];
28553
+ init_esm_shims();
28554
+ function defineTraceFields(definitions) {
28555
+ for (const definition of definitions) {
28556
+ if (definition.fieldClass === "content_safety" && !definition.contentRule) {
28557
+ throw new Error(`Trace content-safety field "${definition.key}" must define a contentRule`);
28558
+ }
28559
+ if ((definition.fieldClass === "query_axis" || definition.fieldClass === "family_query_axis") && definition.valueKind === "content") {
28560
+ throw new Error(`Trace query-axis field "${definition.key}" cannot be content`);
28561
+ }
28562
+ if (definition.fieldClass === "family_query_axis" && !definition.scope) {
28563
+ throw new Error(`Trace family query-axis field "${definition.key}" must define a family scope`);
28564
+ }
28565
+ }
28566
+ return definitions;
28567
+ }
28568
+ var TRACE_B0_FIELD_DEFINITIONS = defineTraceFields([
28569
+ { key: "row_kind", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "stable" },
28570
+ { key: "trace_id", fieldClass: "query_axis", placement: "span", valueKind: "identity", highCardinality: true },
28571
+ { key: "span_id", fieldClass: "query_axis", placement: "span", valueKind: "identity", highCardinality: true },
28572
+ { key: "parent_span_id", fieldClass: "query_axis", placement: "span", valueKind: "identity", highCardinality: true },
28573
+ { key: "span_name", fieldClass: "query_axis", placement: "span", valueKind: "closed_enum", enumBinding: "pending_457" },
28574
+ { key: "span_surface", fieldClass: "query_axis", placement: "span", valueKind: "closed_enum", enumBinding: "stable" },
28575
+ { key: "span_kind", fieldClass: "query_axis", placement: "span", valueKind: "closed_enum", enumBinding: "stable" },
28576
+ { key: "span_status", fieldClass: "query_axis", placement: "span", valueKind: "closed_enum", enumBinding: "stable" },
28577
+ { key: "event_name", fieldClass: "query_axis", placement: "event", valueKind: "closed_enum", enumBinding: "pending_457" },
28578
+ { key: "event_kind", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28579
+ { key: "event_index", fieldClass: "query_axis", placement: "event", valueKind: "identity" },
28580
+ { key: "event_time", fieldClass: "query_axis", placement: "event", valueKind: "timestamp" },
28581
+ { key: "event_time_ms", fieldClass: "query_axis", placement: "event", valueKind: "numeric" },
28582
+ { key: "lifecycle_observed_at_ms", fieldClass: "query_axis", placement: "span_or_event", valueKind: "numeric" },
28583
+ { key: "activity_observed_at_ms", fieldClass: "query_axis", placement: "span_or_event", valueKind: "numeric" },
28584
+ { key: "advances_observed_clock", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28585
+ { key: "duration_ms", fieldClass: "query_axis", placement: "span_or_event", valueKind: "numeric" },
28586
+ { key: "request_id", fieldClass: "query_axis", placement: "span", valueKind: "identity", highCardinality: true },
28587
+ { key: "route_pattern", fieldClass: "query_axis", placement: "span", valueKind: "route" },
28588
+ { key: "caller_kind", fieldClass: "query_axis", placement: "span", valueKind: "closed_enum", enumBinding: "stable" },
28589
+ { key: "server_id", fieldClass: "query_axis", placement: "span", valueKind: "identity", highCardinality: true },
28590
+ { key: "machine_id", fieldClass: "query_axis", placement: "span", valueKind: "identity", highCardinality: true },
28591
+ { key: "agent_id", fieldClass: "query_axis", placement: "span_or_event", valueKind: "identity", highCardinality: true },
28592
+ { key: "launch_id", fieldClass: "query_axis", placement: "span", valueKind: "identity", highCardinality: true },
28593
+ { key: "session_id", fieldClass: "query_axis", placement: "span", valueKind: "identity", highCardinality: true },
28594
+ { key: "observation_class", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28595
+ { key: "action", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28596
+ { key: "source", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28597
+ { key: "served_from", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28598
+ { key: "authority", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28599
+ { key: "decided_by", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28600
+ { key: "error_class", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28601
+ { key: "query_name", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "query_registry" },
28602
+ { key: "phase", fieldClass: "query_axis", placement: "span_or_event", valueKind: "closed_enum", enumBinding: "pending_457" },
28603
+ { key: "hint_source", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:activity" },
28604
+ { key: "resolved_activity", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:activity" },
28605
+ { key: "previous_activity", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:activity" },
28606
+ { key: "next_activity", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:activity" },
28607
+ { key: "repair_kind", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:activity" },
28608
+ { key: "activity_write_site", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:activity" },
28609
+ { key: "activity_source", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:activity" },
28610
+ { key: "status_bucket", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:activity" },
28611
+ { key: "shadow_agent_id", fieldClass: "family_query_axis", placement: "event", valueKind: "identity", scope: "family:lifecycle_shadow", highCardinality: true },
28612
+ { key: "shadow_signal_site", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28613
+ { key: "shadow_observation_class", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28614
+ { key: "shadow_prior_projection", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28615
+ { key: "shadow_projection", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28616
+ { key: "shadow_legacy_outcome", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28617
+ { key: "shadow_action", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28618
+ { key: "shadow_reason", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28619
+ { key: "shadow_direction", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28620
+ { key: "shadow_plan_kind", fieldClass: "family_query_axis", placement: "event", valueKind: "closed_enum", scope: "family:lifecycle_shadow", enumBinding: "pending_457" },
28621
+ { key: "row_count", fieldClass: "detail", placement: "span_or_event", valueKind: "detail" },
28622
+ { key: "retry_count", fieldClass: "detail", placement: "span_or_event", valueKind: "detail" },
28623
+ { key: "error_message", fieldClass: "detail", placement: "span_or_event", valueKind: "detail", contentRule: "scrub_and_short_retention" },
28624
+ { key: "query_text", fieldClass: "content_safety", placement: "span_or_event", valueKind: "content", contentRule: "scrub_and_short_retention" },
28625
+ { key: "raw_payload", fieldClass: "content_safety", placement: "span_or_event", valueKind: "content", contentRule: "drop" },
28626
+ { key: "token", fieldClass: "content_safety", placement: "span_or_event", valueKind: "content", contentRule: "drop" }
28627
+ ]);
28628
+ init_esm_shims();
28509
28629
  init_esm_shims();
28510
28630
  init_esm_shims();
28511
28631
  init_esm_shims();
@@ -29281,10 +29401,10 @@ function mergeDefs(...defs) {
29281
29401
  function cloneDef(schema) {
29282
29402
  return mergeDefs(schema._zod.def);
29283
29403
  }
29284
- function getElementAtPath(obj, path9) {
29285
- if (!path9)
29404
+ function getElementAtPath(obj, path10) {
29405
+ if (!path10)
29286
29406
  return obj;
29287
- return path9.reduce((acc, key) => acc?.[key], obj);
29407
+ return path10.reduce((acc, key) => acc?.[key], obj);
29288
29408
  }
29289
29409
  function promiseAllObject(promisesObj) {
29290
29410
  const keys = Object.keys(promisesObj);
@@ -29667,11 +29787,11 @@ function aborted(x, startIndex = 0) {
29667
29787
  }
29668
29788
  return false;
29669
29789
  }
29670
- function prefixIssues(path9, issues) {
29790
+ function prefixIssues(path10, issues) {
29671
29791
  return issues.map((iss) => {
29672
29792
  var _a2;
29673
29793
  (_a2 = iss).path ?? (_a2.path = []);
29674
- iss.path.unshift(path9);
29794
+ iss.path.unshift(path10);
29675
29795
  return iss;
29676
29796
  });
29677
29797
  }
@@ -29852,7 +29972,7 @@ function formatError(error48, mapper = (issue2) => issue2.message) {
29852
29972
  }
29853
29973
  function treeifyError(error48, mapper = (issue2) => issue2.message) {
29854
29974
  const result2 = { errors: [] };
29855
- const processError = (error49, path9 = []) => {
29975
+ const processError = (error49, path10 = []) => {
29856
29976
  var _a2, _b;
29857
29977
  for (const issue2 of error49.issues) {
29858
29978
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -29862,7 +29982,7 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
29862
29982
  } else if (issue2.code === "invalid_element") {
29863
29983
  processError({ issues: issue2.issues }, issue2.path);
29864
29984
  } else {
29865
- const fullpath = [...path9, ...issue2.path];
29985
+ const fullpath = [...path10, ...issue2.path];
29866
29986
  if (fullpath.length === 0) {
29867
29987
  result2.errors.push(mapper(issue2));
29868
29988
  continue;
@@ -29894,8 +30014,8 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
29894
30014
  }
29895
30015
  function toDotPath(_path) {
29896
30016
  const segs = [];
29897
- const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
29898
- for (const seg of path9) {
30017
+ const path10 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
30018
+ for (const seg of path10) {
29899
30019
  if (typeof seg === "number")
29900
30020
  segs.push(`[${seg}]`);
29901
30021
  else if (typeof seg === "symbol")
@@ -41800,13 +41920,13 @@ function resolveRef(ref, ctx) {
41800
41920
  if (!ref.startsWith("#")) {
41801
41921
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
41802
41922
  }
41803
- const path9 = ref.slice(1).split("/").filter(Boolean);
41804
- if (path9.length === 0) {
41923
+ const path10 = ref.slice(1).split("/").filter(Boolean);
41924
+ if (path10.length === 0) {
41805
41925
  return ctx.rootSchema;
41806
41926
  }
41807
41927
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
41808
- if (path9[0] === defsKey) {
41809
- const key = path9[1];
41928
+ if (path10[0] === defsKey) {
41929
+ const key = path10[1];
41810
41930
  if (!key || !ctx.defs[key]) {
41811
41931
  throw new Error(`Reference not found: ${ref}`);
41812
41932
  }
@@ -42462,7 +42582,8 @@ var agentApiResolveChannelResponseSchema = passthroughObject({
42462
42582
  channelId: external_exports.string().trim().min(1)
42463
42583
  });
42464
42584
  var agentApiThreadUnfollowBodySchema = passthroughObject({
42465
- thread: external_exports.string().trim().min(1)
42585
+ thread: external_exports.string().trim().min(1),
42586
+ reason: external_exports.string().trim().min(1).max(200).optional()
42466
42587
  });
42467
42588
  var agentApiTaskClaimBodySchema = passthroughObject({
42468
42589
  channel: external_exports.string().trim().min(1),
@@ -42701,7 +42822,12 @@ var agentApiIntegrationLoginResponseSchema = passthroughObject({
42701
42822
  status: external_exports.enum(["logged_in", "already_logged_in", "approval_required"]),
42702
42823
  service: agentApiIntegrationServiceSchema,
42703
42824
  scopes: external_exports.array(external_exports.string()),
42704
- requestId: external_exports.string(),
42825
+ requestId: external_exports.string().optional(),
42826
+ session: passthroughObject({
42827
+ status: external_exports.literal("stored"),
42828
+ source: external_exports.enum(["cache", "fresh"]),
42829
+ path: nullableStringSchema
42830
+ }).optional(),
42705
42831
  approval: passthroughObject({
42706
42832
  requestId: external_exports.string(),
42707
42833
  target: nullableStringSchema,
@@ -43457,11 +43583,11 @@ function isAgentApiRawFailure(value) {
43457
43583
  );
43458
43584
  }
43459
43585
  function buildAgentApiRawRoutePath(routeKey, options = {}) {
43460
- let path9;
43586
+ let path10;
43461
43587
  try {
43462
43588
  const encodedPath = encodePathParams(routeKey, options.params);
43463
43589
  if (typeof encodedPath !== "string") return encodedPath;
43464
- path9 = encodedPath;
43590
+ path10 = encodedPath;
43465
43591
  } catch (cause) {
43466
43592
  if (cause instanceof MissingPathParamError) {
43467
43593
  return failure(routeKey, "missing_path_param", cause.message, { cause });
@@ -43471,12 +43597,12 @@ function buildAgentApiRawRoutePath(routeKey, options = {}) {
43471
43597
  const query = encodeQuery(routeKey, options.query);
43472
43598
  if (query && !(query instanceof URLSearchParams)) return query;
43473
43599
  const suffix = query && query.size > 0 ? `?${query.toString()}` : "";
43474
- return `${options.pathPrefix ?? AGENT_API_BASE_PATH}${path9}${suffix}`;
43600
+ return `${options.pathPrefix ?? AGENT_API_BASE_PATH}${path10}${suffix}`;
43475
43601
  }
43476
43602
  async function requestAgentApiRawRoute(transport, routeKey, options = {}) {
43477
43603
  const route3 = agentApiContract[routeKey];
43478
- const path9 = buildAgentApiRawRoutePath(routeKey, options);
43479
- if (typeof path9 !== "string") return path9;
43604
+ const path10 = buildAgentApiRawRoutePath(routeKey, options);
43605
+ if (typeof path10 !== "string") return path10;
43480
43606
  const body = parseBody(routeKey, options.body);
43481
43607
  if (isAgentApiRawFailure(body)) return body;
43482
43608
  let response;
@@ -43484,7 +43610,7 @@ async function requestAgentApiRawRoute(transport, routeKey, options = {}) {
43484
43610
  response = await transport.request({
43485
43611
  routeKey,
43486
43612
  method: route3.method,
43487
- path: path9,
43613
+ path: path10,
43488
43614
  body
43489
43615
  });
43490
43616
  } catch (cause) {
@@ -43870,8 +43996,8 @@ function buildDaemonApiRawRoutePath(routeKey, options = {}) {
43870
43996
  }
43871
43997
  async function requestDaemonApiRawRoute(transport, routeKey, options = {}) {
43872
43998
  const route3 = daemonApiContract[routeKey];
43873
- const path9 = buildDaemonApiRawRoutePath(routeKey, options);
43874
- if (typeof path9 !== "string") return path9;
43999
+ const path10 = buildDaemonApiRawRoutePath(routeKey, options);
44000
+ if (typeof path10 !== "string") return path10;
43875
44001
  const body = parseBody2(routeKey, options.body);
43876
44002
  if (isDaemonApiRawFailure(body)) return body;
43877
44003
  let response;
@@ -43879,7 +44005,7 @@ async function requestDaemonApiRawRoute(transport, routeKey, options = {}) {
43879
44005
  response = await transport.request({
43880
44006
  routeKey,
43881
44007
  method: route3.method,
43882
- path: path9,
44008
+ path: path10,
43883
44009
  body
43884
44010
  });
43885
44011
  } catch (cause) {
@@ -44281,6 +44407,54 @@ init_esm_shims();
44281
44407
  init_esm_shims();
44282
44408
  init_esm_shims();
44283
44409
  init_esm_shims();
44410
+ var RAFT_OAUTH_SCOPE_CATALOG = {
44411
+ openid: {
44412
+ phase: "identity",
44413
+ defaultAllowed: true,
44414
+ publicDiscovery: true,
44415
+ requiresResource: false,
44416
+ label: "OpenID identity"
44417
+ },
44418
+ profile: {
44419
+ phase: "identity",
44420
+ defaultAllowed: true,
44421
+ publicDiscovery: true,
44422
+ requiresResource: false,
44423
+ label: "Basic profile"
44424
+ },
44425
+ identity: {
44426
+ phase: "identity",
44427
+ defaultAllowed: true,
44428
+ publicDiscovery: true,
44429
+ requiresResource: false,
44430
+ label: "Raft identity card"
44431
+ },
44432
+ "agent:event:write": {
44433
+ phase: "agent_inbound",
44434
+ defaultAllowed: false,
44435
+ publicDiscovery: true,
44436
+ requiresResource: true,
44437
+ label: "Send structured events to an agent"
44438
+ },
44439
+ "agent:notification:write": {
44440
+ phase: "agent_inbound",
44441
+ defaultAllowed: false,
44442
+ publicDiscovery: true,
44443
+ requiresResource: true,
44444
+ label: "Send notifications to an agent"
44445
+ },
44446
+ "agent:action_request:write": {
44447
+ phase: "agent_inbound",
44448
+ defaultAllowed: false,
44449
+ publicDiscovery: false,
44450
+ requiresResource: true,
44451
+ label: "Request agent action"
44452
+ }
44453
+ };
44454
+ var RAFT_OAUTH_SCOPES_SUPPORTED = Object.keys(RAFT_OAUTH_SCOPE_CATALOG);
44455
+ var RAFT_OAUTH_DEFAULT_ALLOWED_SCOPES = RAFT_OAUTH_SCOPES_SUPPORTED.filter((scope) => RAFT_OAUTH_SCOPE_CATALOG[scope].defaultAllowed);
44456
+ var RAFT_OAUTH_PUBLIC_DISCOVERY_SCOPES = RAFT_OAUTH_SCOPES_SUPPORTED.filter((scope) => RAFT_OAUTH_SCOPE_CATALOG[scope].publicDiscovery);
44457
+ init_esm_shims();
44284
44458
  var NoopFailpointRegistry = class {
44285
44459
  get enabled() {
44286
44460
  return false;
@@ -44615,13 +44789,15 @@ var DISPLAY_PLAN_CONFIG = {
44615
44789
  }
44616
44790
  };
44617
44791
  var FREE_MONTHLY_FILE_UPLOAD_LIMIT_BYTES = 100 * 1024 * 1024;
44792
+ var FREE_SINGLE_FILE_UPLOAD_LIMIT_BYTES = 50 * 1024 * 1024;
44793
+ var PRO_SINGLE_FILE_UPLOAD_LIMIT_BYTES = 200 * 1024 * 1024;
44618
44794
  var TRIAL_START_DATE = /* @__PURE__ */ new Date("2026-04-18T00:00:00Z");
44619
44795
  var TRIAL_END_DATE = /* @__PURE__ */ new Date("2026-06-23T12:00:00Z");
44620
44796
  var TRIAL_DURATION_DAYS = (TRIAL_END_DATE.getTime() - TRIAL_START_DATE.getTime()) / (24 * 60 * 60 * 1e3);
44621
44797
  function buildAgentApiRoutePath(routeKey, pathParams, query) {
44622
- const path9 = buildAgentApiRawRoutePath(routeKey, { params: pathParams, query });
44623
- if (typeof path9 === "string") return path9;
44624
- throw cliErrorFromRawFailure(path9);
44798
+ const path10 = buildAgentApiRawRoutePath(routeKey, { params: pathParams, query });
44799
+ if (typeof path10 === "string") return path10;
44800
+ throw cliErrorFromRawFailure(path10);
44625
44801
  }
44626
44802
  function buildAgentApiEventsPath(query) {
44627
44803
  return buildAgentApiRoutePath("events", void 0, query);
@@ -45386,7 +45562,7 @@ function loadAgentContext(env = process.env) {
45386
45562
  const shadowed = RAW_AGENT_ENV_KEYS.filter((k) => env[k]);
45387
45563
  if (shadowed.length > 0) {
45388
45564
  process.stderr.write(
45389
- `slock: RAFT_PROFILE=${profileSlug} active; ignoring ${shadowed.join(", ")} from env.
45565
+ `raft: RAFT_PROFILE=${profileSlug} active; ignoring ${shadowed.join(", ")} from env.
45390
45566
  `
45391
45567
  );
45392
45568
  }
@@ -45464,17 +45640,17 @@ function bootstrapSuggestedNextAction(code) {
45464
45640
  case "MISSING_AGENT_ID":
45465
45641
  case "MISSING_SERVER_URL":
45466
45642
  case "MISSING_TOKEN":
45467
- return "Use a Slock profile with `raft --profile <slug> ...`; create one with `raft agent login --server <server-url> --agent <agent-id> --profile-slug <slug>`.";
45643
+ return "Use a Raft profile with `raft --profile <slug> ...`; create one with `raft agent login --server <server-url> --agent <agent-id> --profile-slug <slug>`.";
45468
45644
  case "PROFILE_FILE_UNREADABLE":
45469
45645
  case "PROFILE_FILE_INVALID":
45470
- return "Check the selected Slock profile, or recreate it with `raft agent login --server <server-url> --agent <agent-id> --profile-slug <slug>`.";
45646
+ return "Check the selected Raft profile, or recreate it with `raft agent login --server <server-url> --agent <agent-id> --profile-slug <slug>`.";
45471
45647
  case "TOKEN_FILE_UNREADABLE":
45472
45648
  case "TOKEN_FILE_EMPTY":
45473
- return "Check the daemon-injected token file, or restart the Slock daemon so it can inject a fresh credential.";
45649
+ return "Check the daemon-injected token file, or restart the Raft daemon so it can inject a fresh credential.";
45474
45650
  case "MISSING_AGENT_PROXY_URL":
45475
45651
  case "MISSING_AGENT_PROXY_TOKEN":
45476
45652
  case "MULTIPLE_AGENT_PROXY_TOKENS":
45477
- return "Restart the Slock daemon so it can inject a complete local proxy environment, or remove the partial proxy env vars before retrying.";
45653
+ return "Restart the Raft daemon so it can inject a complete local proxy environment, or remove the partial proxy env vars before retrying.";
45478
45654
  default:
45479
45655
  return void 0;
45480
45656
  }
@@ -45588,7 +45764,7 @@ var DeviceCodeLoginError = class extends Error {
45588
45764
  }
45589
45765
  };
45590
45766
  var ACTIONABLE_ERROR_MESSAGES = {
45591
- device_login_disabled: "Device login is not enabled on this Slock server. Ask an admin to set SLOCK_DEVICE_LOGIN_ENABLED=true.",
45767
+ device_login_disabled: "Device login is not enabled on this Raft server. Ask an admin to set SLOCK_DEVICE_LOGIN_ENABLED=true.",
45592
45768
  device_code_required: "Internal CLI bug: device_code was missing from the poll request.",
45593
45769
  user_code_required: "Internal CLI bug: user_code was missing from the approve request.",
45594
45770
  authorization_pending: "Still waiting for you to approve the login on the web page.",
@@ -45772,9 +45948,9 @@ function describeListResult(reason, serverUrl) {
45772
45948
  var agentListCommand = defineCommand(
45773
45949
  {
45774
45950
  name: "list",
45775
- description: "List Slock agents the user can mint credentials for (after a device-code login).",
45951
+ description: "List Raft agents the user can mint credentials for (after a device-code login).",
45776
45952
  options: [
45777
- { flags: "--server <url>", description: "Slock server base URL, e.g. https://slock.example.com" },
45953
+ { flags: "--server <url>", description: "Raft server base URL, e.g. https://app.raft.build" },
45778
45954
  { flags: "--client-name <label>", description: "Human-readable label shown on the web approval page" }
45779
45955
  ]
45780
45956
  },
@@ -45856,7 +46032,7 @@ var import_undici4 = __toESM(require_undici(), 1);
45856
46032
  var WAIT_MAX_POLL_MS = 15 * 60 * 1e3;
45857
46033
  var SERVER_OPTION = {
45858
46034
  flags: "--server <url>",
45859
- description: "Slock server base URL, e.g. https://slock.example.com"
46035
+ description: "Raft server base URL, e.g. https://app.raft.build"
45860
46036
  };
45861
46037
  var AGENT_OPTION = {
45862
46038
  flags: "--agent <agentId>",
@@ -45872,7 +46048,7 @@ var PROFILE_SLUG_OPTION = {
45872
46048
  };
45873
46049
  var PROFILE_DIR_OPTION = {
45874
46050
  flags: "--profile-dir <path>",
45875
- description: "Override the profile directory root (default resolution: SLOCK_HOME/profiles/<slug> when SLOCK_HOME is set, else ~/.slock/profiles/<slug>)"
46051
+ description: "Override the profile directory root (default resolution uses the managed Raft home when present, otherwise the local profile store)"
45876
46052
  };
45877
46053
  var DEVICE_CODE_OPTION = {
45878
46054
  flags: "--device-code <code>",
@@ -45887,7 +46063,7 @@ function mergeParentLoginOpts(options, command) {
45887
46063
  var agentLoginCommand = defineCommand(
45888
46064
  {
45889
46065
  name: "login",
45890
- description: "Sign this CLI in as a specific Slock agent via the device-code login grant.",
46066
+ description: "Sign this CLI in as a specific Raft agent via the device-code login grant.",
45891
46067
  options: [
45892
46068
  SERVER_OPTION,
45893
46069
  AGENT_OPTION,
@@ -47098,7 +47274,7 @@ function createRaftChannelWakeAdapter(options = {}) {
47098
47274
  if (!options.endpointUrl) {
47099
47275
  return buildRaftChannelWakeFailedEvent(input, {
47100
47276
  failureClass: "no_session",
47101
- reason: "Claude Code Slock channel plugin endpoint is not configured; start Claude Code with the Slock channel plugin and pass its localhost wake endpoint to the bridge."
47277
+ reason: "Claude Code Raft channel plugin endpoint is not configured; start Claude Code with the Raft channel plugin and pass its localhost wake endpoint to the bridge."
47102
47278
  });
47103
47279
  }
47104
47280
  const request = options.fetchImpl ?? fetch;
@@ -47125,14 +47301,14 @@ function createRaftChannelWakeAdapter(options = {}) {
47125
47301
  } catch (err) {
47126
47302
  return buildRaftChannelWakeFailedEvent(input, {
47127
47303
  failureClass: "no_session",
47128
- reason: err instanceof Error && err.message ? `Claude Code Slock channel plugin endpoint is unreachable: ${err.message}` : "Claude Code Slock channel plugin endpoint is unreachable"
47304
+ reason: err instanceof Error && err.message ? `Claude Code Raft channel plugin endpoint is unreachable: ${err.message}` : "Claude Code Raft channel plugin endpoint is unreachable"
47129
47305
  });
47130
47306
  }
47131
47307
  const body = await parseWakeResponse(response);
47132
47308
  if (!response.ok || body.ok === false) {
47133
47309
  return buildRaftChannelWakeFailedEvent(input, {
47134
47310
  failureClass: body.failureClass ?? statusFailureClass(response.status),
47135
- reason: body.reason ?? `Claude Code Slock channel plugin rejected wake attempt with HTTP ${response.status}`,
47311
+ reason: body.reason ?? `Claude Code Raft channel plugin rejected wake attempt with HTTP ${response.status}`,
47136
47312
  ...typeof body.retryAfterMs === "number" ? { retryAfterMs: body.retryAfterMs } : {}
47137
47313
  });
47138
47314
  }
@@ -47140,7 +47316,7 @@ function createRaftChannelWakeAdapter(options = {}) {
47140
47316
  if (!runtimeSession) {
47141
47317
  return buildRaftChannelWakeFailedEvent(input, {
47142
47318
  failureClass: "protocol_mismatch",
47143
- reason: "Claude Code Slock channel plugin accepted wake but did not return runtimeSession"
47319
+ reason: "Claude Code Raft channel plugin accepted wake but did not return runtimeSession"
47144
47320
  });
47145
47321
  }
47146
47322
  return buildRaftChannelWakeInjectedEvent({
@@ -47648,7 +47824,7 @@ function sleep(ms) {
47648
47824
  return new Promise((resolve) => setTimeout(resolve, ms));
47649
47825
  }
47650
47826
  init_esm_shims();
47651
- var ACTION_HEREDOC_DELIMITER = "SLOCKACTION";
47827
+ var ACTION_HEREDOC_DELIMITER = "RAFTACTION";
47652
47828
  var PrepareActionInputError = class extends Error {
47653
47829
  constructor(code, message) {
47654
47830
  super(message);
@@ -47667,8 +47843,8 @@ async function readStream(stream) {
47667
47843
  function missingActionMessage() {
47668
47844
  return [
47669
47845
  "No action JSON received on stdin.",
47670
- "Pipe a JSON ActionCardAction object (channel:create / agent:create / channel:add_member) into slock action prepare:",
47671
- ` slock action prepare --target "#channel" <<'${ACTION_HEREDOC_DELIMITER}'`,
47846
+ "Pipe a JSON ActionCardAction object (channel:create / agent:create / channel:add_member) into raft action prepare:",
47847
+ ` raft action prepare --target "#channel" <<'${ACTION_HEREDOC_DELIMITER}'`,
47672
47848
  ' {"type":"channel:create","name":"demo","visibility":"public"}',
47673
47849
  ` ${ACTION_HEREDOC_DELIMITER}`
47674
47850
  ].join("\n");
@@ -47823,7 +47999,7 @@ function formatServerInfo(data) {
47823
47999
  text += " (none)\n";
47824
48000
  }
47825
48001
  text += "\n### Humans\n";
47826
- text += `To start a new DM: raft message send --target "dm:@name" <<'SLOCKMSG' followed by the message body and SLOCKMSG. To reply in an existing DM: reuse the target from received messages.
48002
+ text += `To start a new DM: raft message send --target "dm:@name" <<'RAFTMSG' followed by the message body and RAFTMSG. To reply in an existing DM: reuse the target from received messages.
47827
48003
  `;
47828
48004
  text += "Role labels show server-level owner/admin authority; no role label means ordinary member.\n";
47829
48005
  if (humans.length > 0) {
@@ -48388,10 +48564,24 @@ function makeChannelMuteCommand(action) {
48388
48564
  {
48389
48565
  name: action,
48390
48566
  description: action === "mute" ? "Mute ordinary Activity delivery for a regular channel" : "Unmute ordinary Activity delivery for a regular channel",
48391
- arguments: ["<target>"]
48567
+ arguments: ["[target]"],
48568
+ options: [
48569
+ {
48570
+ flags: "--target <target>",
48571
+ description: `Regular channel to ${action}, e.g. '#engineering'`
48572
+ }
48573
+ ]
48392
48574
  },
48393
- async (ctx, targetArg) => {
48394
- const target = String(targetArg ?? "");
48575
+ async (ctx, targetArg, opts = {}) => {
48576
+ const positionalTarget = targetArg?.trim();
48577
+ const flagTarget = opts.target?.trim();
48578
+ if (positionalTarget && flagTarget && positionalTarget !== flagTarget) {
48579
+ throw new CliError({
48580
+ code: "INVALID_ARG",
48581
+ message: "Positional target and --target must refer to the same channel when both are provided"
48582
+ });
48583
+ }
48584
+ const target = flagTarget || positionalTarget || "";
48395
48585
  const channelName = parseRegularChannelTarget(target);
48396
48586
  if (!channelName) {
48397
48587
  throw new CliError({
@@ -48813,7 +49003,7 @@ function toKnowledgeErrorCode(errorCode2, status) {
48813
49003
  var knowledgeGetCommand = defineCommand(
48814
49004
  {
48815
49005
  name: "get",
48816
- description: "Fetch a Slock Manual for Agents topic from the current server",
49006
+ description: "Fetch a Raft Manual for Agents topic from the current server",
48817
49007
  arguments: ["<topic>"],
48818
49008
  options: [
48819
49009
  {
@@ -48872,7 +49062,7 @@ var inboxCheckCommand = defineCommand(
48872
49062
  if (agentContext.clientMode !== "managed-runner") {
48873
49063
  throw new CliError({
48874
49064
  code: "INBOX_CHECK_FAILED",
48875
- message: "`slock inbox check` is only available inside managed daemon runners.",
49065
+ message: "`raft inbox check` is only available inside managed daemon runners.",
48876
49066
  suggestedNextAction: "Use `raft message check` to drain messages."
48877
49067
  });
48878
49068
  }
@@ -48924,6 +49114,10 @@ var threadUnfollowCommand = defineCommand(
48924
49114
  {
48925
49115
  flags: "--target <target>",
48926
49116
  description: "Thread target, e.g. '#engineering:abcd1234' or 'dm:@alice:abcd1234'"
49117
+ },
49118
+ {
49119
+ flags: "--reason <reason>",
49120
+ description: "Short reason shown in the thread-local unfollow notice"
48927
49121
  }
48928
49122
  ]
48929
49123
  },
@@ -48938,7 +49132,8 @@ var threadUnfollowCommand = defineCommand(
48938
49132
  const agentContext = ctx.loadAgentContext();
48939
49133
  const client = ctx.createApiClient(agentContext);
48940
49134
  const agentApi = createAgentApiSurfaceClient(client);
48941
- const res = await agentApi.threads.unfollow({ thread });
49135
+ const reason = opts.reason?.trim() || "no longer following";
49136
+ const res = await agentApi.threads.unfollow({ thread, reason });
48942
49137
  if (!res.ok) {
48943
49138
  throw new CliError({
48944
49139
  code: res.status >= 500 ? "SERVER_5XX" : "UNFOLLOW_FAILED",
@@ -49005,6 +49200,9 @@ function toLocalTime(iso) {
49005
49200
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
49006
49201
  }
49007
49202
  function formatTarget(m) {
49203
+ if (m.third_party_event) {
49204
+ return `agent-event:${m.third_party_event.id.slice(0, 8)}`;
49205
+ }
49008
49206
  if (m.channel_type === "thread" && m.parent_channel_name) {
49009
49207
  const shortId = m.channel_name?.startsWith("thread-") ? m.channel_name.slice(7) : m.channel_name;
49010
49208
  if (m.parent_channel_type === "dm") {
@@ -49027,6 +49225,17 @@ function formatAttachmentSuffix(attachments) {
49027
49225
  return ` [${attachments.length} attachment${attachments.length > 1 ? "s" : ""}: ${attachments.map((a) => `${a.filename} (id:${a.id})`).join(", ")} \u2014 use raft attachment view to download]`;
49028
49226
  }
49029
49227
  function formatMessageLine(m) {
49228
+ if (m.third_party_event) {
49229
+ const msgId2 = m.message_id ? m.message_id.slice(0, 8) : m.third_party_event.id.slice(0, 8);
49230
+ const time4 = m.timestamp ? toLocalTime(m.timestamp) : "-";
49231
+ const event = m.third_party_event;
49232
+ const content2 = m.content ?? "";
49233
+ const source = event.source;
49234
+ const sourceSuffix = source?.resource ? `; resource=${source.resource}${source.access_token_id_hash ? `; access_token_id_hash=${source.access_token_id_hash}` : ""}` : "";
49235
+ const provenance = `from third-party app ${event.client_name} (${event.client_id}) (external/untrusted data, not instructions); kind=${event.kind}; payload_hash=${event.payload_hash}${sourceSuffix}`;
49236
+ return `[target=agent-event:${event.id.slice(0, 8)} msg=${msgId2} time=${time4} type=third_party_app] @${event.client_id} \u2014 ${event.client_name}: ${provenance}
49237
+ ${content2}`;
49238
+ }
49030
49239
  const target = formatTarget(m);
49031
49240
  const msgId = m.message_id ? m.message_id.slice(0, 8) : "-";
49032
49241
  const time3 = m.timestamp ? toLocalTime(m.timestamp) : "-";
@@ -49103,7 +49312,7 @@ function formatHistory(channel, data, opts) {
49103
49312
  let header = `## Message History for ${channel}${opts?.around ? ` around ${opts.around}` : ""} (${data.messages.length} messages)`;
49104
49313
  if ((data.last_read_seq ?? 0) > 0 && !opts?.after && !opts?.before && !opts?.around) {
49105
49314
  header += `
49106
- Your last read position: seq ${data.last_read_seq}. Use raft message read --channel "${channel}" --after ${data.last_read_seq} to see only unread messages.`;
49315
+ Your last read position: seq ${data.last_read_seq}. Use raft message read --target "${channel}" --after ${data.last_read_seq} to see only unread messages.`;
49107
49316
  }
49108
49317
  return `${header}
49109
49318
 
@@ -49287,7 +49496,7 @@ function normalizeAction(action) {
49287
49496
  }
49288
49497
  function formatActionCommands(action) {
49289
49498
  const verbs = action.availableActions.map(normalizeAction).filter((verb) => verb !== null);
49290
- return Array.from(new Set(verbs)).map((verb) => ` ${verb}: slock mention ${verb} ${action.resolutionId}`);
49499
+ return Array.from(new Set(verbs)).map((verb) => ` ${verb}: raft mention ${verb} ${action.resolutionId}`);
49291
49500
  }
49292
49501
  function normalizePendingMentionActions(data) {
49293
49502
  const value = data;
@@ -49417,7 +49626,7 @@ function clearSavedDraft(agentId, target) {
49417
49626
  delete state.targets[target];
49418
49627
  writeState(agentId, state);
49419
49628
  }
49420
- var MESSAGE_HEREDOC_DELIMITER = "SLOCKMSG";
49629
+ var MESSAGE_HEREDOC_DELIMITER = "RAFTMSG";
49421
49630
  var SendContentError = class extends Error {
49422
49631
  constructor(code, message) {
49423
49632
  super(message);
@@ -49746,6 +49955,28 @@ function registerCheckCommand(parent, runtimeOptions) {
49746
49955
  registerCliCommand(parent, messageCheckCommand, runtimeOptions);
49747
49956
  }
49748
49957
  init_esm_shims();
49958
+ init_esm_shims();
49959
+ function resolveTargetAlias(opts) {
49960
+ const target = opts.target?.trim();
49961
+ const legacyChannel = opts.channel?.trim();
49962
+ if (target && legacyChannel && target !== legacyChannel) {
49963
+ throw new CliError({
49964
+ code: "INVALID_ARG",
49965
+ message: "--target and legacy --channel must refer to the same target when both are provided"
49966
+ });
49967
+ }
49968
+ return target || legacyChannel || void 0;
49969
+ }
49970
+ function requireTargetAlias(opts) {
49971
+ const target = resolveTargetAlias(opts);
49972
+ if (!target) {
49973
+ throw new CliError({
49974
+ code: "INVALID_ARG",
49975
+ message: "--target is required (legacy --channel is accepted during the transition)"
49976
+ });
49977
+ }
49978
+ return target;
49979
+ }
49749
49980
  function parsePositiveInt2(name, raw) {
49750
49981
  if (raw === void 0) return void 0;
49751
49982
  const n = Number(raw);
@@ -49784,13 +50015,7 @@ function mapReadFailure(res) {
49784
50015
  });
49785
50016
  }
49786
50017
  function validateReadOpts(opts) {
49787
- const channel = opts.channel?.trim();
49788
- if (!channel) {
49789
- throw new CliError({
49790
- code: "INVALID_ARG",
49791
- message: "--channel is required"
49792
- });
49793
- }
50018
+ const channel = requireTargetAlias(opts);
49794
50019
  const limit = parsePositiveInt2("limit", opts.limit);
49795
50020
  const before = opts.before?.trim();
49796
50021
  const after = opts.after?.trim();
@@ -49807,10 +50032,11 @@ var messageReadCommand = defineCommand(
49807
50032
  name: "read",
49808
50033
  description: "Read message history for a channel, DM, or thread",
49809
50034
  options: [
49810
- { flags: "--channel <target>", description: "Target: '#channel', 'dm:@peer', '#channel:threadId', 'dm:@peer:threadId'" },
49811
- { flags: "--before <idOrSeq>", description: "Return messages strictly before this message id or seq anchor" },
49812
- { flags: "--after <idOrSeq>", description: "Return messages strictly after this message id or seq anchor" },
49813
- { flags: "--around <idOrSeq>", description: "Center the window on this message id or seq anchor" },
50035
+ { flags: "--target <target>", description: "Target: '#channel', 'dm:@peer', '#channel:threadId', 'dm:@peer:threadId'" },
50036
+ { flags: "--channel <target>", description: "Legacy alias for --target (accepted during transition)" },
50037
+ { flags: "--before <idOrSeq>", description: "Return messages strictly before this full/short message id or seq anchor" },
50038
+ { flags: "--after <idOrSeq>", description: "Return messages strictly after this full/short message id or seq anchor" },
50039
+ { flags: "--around <idOrSeq>", description: "Center the window on this full/short message id or seq anchor" },
49814
50040
  { flags: "--limit <n>", description: "Max messages to return (server default applies if omitted)" }
49815
50041
  ]
49816
50042
  },
@@ -49910,13 +50136,13 @@ function normalizeSearchOpts(opts) {
49910
50136
  message: `--sort must be "relevance" or "recent"; got ${opts.sort}`
49911
50137
  });
49912
50138
  }
49913
- const channel = opts.channel?.trim();
50139
+ const channel = resolveTargetAlias(opts);
49914
50140
  const sender = opts.sender ? normalizeMemberHandleRef(opts.sender) : void 0;
49915
50141
  const hasFilter = Boolean(channel || sender || opts.before || opts.after);
49916
50142
  if (!query && !hasFilter) {
49917
50143
  throw new CliError({
49918
50144
  code: "INVALID_ARG",
49919
- message: "--query is required unless --sender, --channel, --before, or --after is provided"
50145
+ message: "--query is required unless --sender, --target, --before, or --after is provided"
49920
50146
  });
49921
50147
  }
49922
50148
  if (!query && opts.sort === "relevance") {
@@ -49955,7 +50181,8 @@ var messageSearchCommand = defineCommand(
49955
50181
  description: "Search messages across channels the agent can see",
49956
50182
  options: [
49957
50183
  { flags: "--query <q>", description: "Search query string (optional when filters are provided)" },
49958
- { flags: "--channel <target>", description: "Restrict to a single channel/DM/thread" },
50184
+ { flags: "--target <target>", description: "Restrict to a single channel/DM/thread" },
50185
+ { flags: "--channel <target>", description: "Legacy alias for --target (accepted during transition)" },
49959
50186
  { flags: "--sender <handle>", description: "Restrict to messages by sender handle, e.g. @alice" },
49960
50187
  { flags: "--sort <mode>", description: "Sort results by relevance or recent (default: relevance; filter-only searches use recent)" },
49961
50188
  { flags: "--before <iso>", description: "Only messages before this ISO datetime" },
@@ -50196,9 +50423,10 @@ var attachmentUploadCommand = defineCommand(
50196
50423
  options: [
50197
50424
  { flags: "--path <filepath>", description: "Absolute path to the local file to upload" },
50198
50425
  {
50199
- flags: "--channel <target>",
50426
+ flags: "--target <target>",
50200
50427
  description: "Target where the attachment will be used: '#channel', 'dm:@peer', or thread variants. Required by the v0 server until channel-less uploads land."
50201
50428
  },
50429
+ { flags: "--channel <target>", description: "Legacy alias for --target (accepted during transition)" },
50202
50430
  { flags: "--mime-type <type>", description: "Explicit MIME type override, e.g. image/png" }
50203
50431
  ]
50204
50432
  },
@@ -50219,10 +50447,11 @@ var attachmentUploadCommand = defineCommand(
50219
50447
  if (err instanceof AttachmentUploadArgError) throw cliError(err.code, err.message, { cause: err });
50220
50448
  throw err;
50221
50449
  }
50222
- if (!opts.channel) {
50450
+ const target = resolveTargetAlias(opts);
50451
+ if (!target) {
50223
50452
  throw cliError(
50224
50453
  "MISSING_CHANNEL",
50225
- "v0 server requires a channel to attach the upload to. Pass --channel '#name', 'dm:@peer', or a thread target."
50454
+ "v0 server requires a target to attach the upload to. Pass --target '#name', 'dm:@peer', or a thread target."
50226
50455
  );
50227
50456
  }
50228
50457
  const buffer = readFileSync3(opts.path);
@@ -50238,10 +50467,10 @@ var attachmentUploadCommand = defineCommand(
50238
50467
  const agentContext = ctx.loadAgentContext();
50239
50468
  const client = ctx.createApiClient(agentContext);
50240
50469
  const agentApi = createAgentApiSurfaceClient(client);
50241
- const resolved = await agentApi.channels.resolve({ target: opts.channel });
50470
+ const resolved = await agentApi.channels.resolve({ target });
50242
50471
  if (!resolved.ok || !resolved.data?.channelId) {
50243
50472
  const code = resolved.status >= 500 ? "SERVER_5XX" : "RESOLVE_FAILED";
50244
- throw cliError(code, resolved.error ?? `Could not resolve channel: ${opts.channel}`);
50473
+ throw cliError(code, resolved.error ?? `Could not resolve target: ${target}`);
50245
50474
  }
50246
50475
  const channelId = resolved.data.channelId;
50247
50476
  const blob = new Blob([buffer], { type: uploadMimeType });
@@ -50270,13 +50499,21 @@ function registerAttachmentUploadCommand(parent, runtimeOptions = {}) {
50270
50499
  registerCliCommand(parent, attachmentUploadCommand, runtimeOptions);
50271
50500
  }
50272
50501
  init_esm_shims();
50273
- function validateViewOpts(opts) {
50274
- const id = opts.id?.trim();
50502
+ function validateViewOpts(positionalId, opts) {
50503
+ const positional = positionalId?.trim();
50504
+ const optionId = opts.id?.trim();
50505
+ if (positional && optionId) {
50506
+ throw new CliError({
50507
+ code: "INVALID_ARG",
50508
+ message: "pass the attachment id either positionally or with --id, not both"
50509
+ });
50510
+ }
50511
+ const id = positional || optionId;
50275
50512
  const output = opts.output;
50276
50513
  if (!id) {
50277
50514
  throw new CliError({
50278
50515
  code: "INVALID_ARG",
50279
- message: "--id is required"
50516
+ message: "attachment id is required (pass <attachmentId> or --id)"
50280
50517
  });
50281
50518
  }
50282
50519
  if (!output) {
@@ -50291,13 +50528,16 @@ var attachmentViewCommand = defineCommand(
50291
50528
  {
50292
50529
  name: "view",
50293
50530
  description: "Download an attachment by id and save it to a local path",
50531
+ arguments: ["[attachmentId]"],
50294
50532
  options: [
50295
- { flags: "--id <attachmentId>", description: "Attachment UUID" },
50533
+ { flags: "--id <attachmentId>", description: "Attachment UUID (transition alias; prefer positional <attachmentId>)" },
50296
50534
  { flags: "--output <path>", description: "Local path to write the file to" }
50297
50535
  ]
50298
50536
  },
50299
- async (ctx, opts) => {
50300
- const { id, output } = validateViewOpts(opts);
50537
+ async (ctx, attachmentIdOrOpts, maybeOpts) => {
50538
+ const positionalId = typeof attachmentIdOrOpts === "string" ? attachmentIdOrOpts : void 0;
50539
+ const opts = typeof attachmentIdOrOpts === "object" && attachmentIdOrOpts !== null ? attachmentIdOrOpts : maybeOpts ?? {};
50540
+ const { id, output } = validateViewOpts(positionalId, opts);
50301
50541
  const agentContext = ctx.loadAgentContext();
50302
50542
  const client = ctx.createApiClient(agentContext);
50303
50543
  const res = await createAgentApiSurfaceClient(client).attachments.view({ attachmentId: id });
@@ -50447,13 +50687,7 @@ function formatTaskStatusUpdated(taskNumber, status) {
50447
50687
  }
50448
50688
  var VALID_STATUSES = ["all", "todo", "in_progress", "in_review", "done", "closed"];
50449
50689
  function validateListOpts(opts) {
50450
- const channel = opts.channel?.trim();
50451
- if (!channel) {
50452
- throw new CliError({
50453
- code: "INVALID_ARG",
50454
- message: "--channel is required"
50455
- });
50456
- }
50690
+ const channel = requireTargetAlias(opts);
50457
50691
  if (opts.status && !VALID_STATUSES.includes(opts.status)) {
50458
50692
  throw new CliError({
50459
50693
  code: "INVALID_ARG",
@@ -50470,7 +50704,8 @@ var taskListCommand = defineCommand(
50470
50704
  name: "list",
50471
50705
  description: "List tasks in a channel",
50472
50706
  options: [
50473
- { flags: "--channel <target>", description: "Channel target: '#channel'" },
50707
+ { flags: "--target <target>", description: "Channel target: '#channel'" },
50708
+ { flags: "--channel <target>", description: "Legacy alias for --target (accepted during transition)" },
50474
50709
  { flags: "--status <s>", description: "Filter: all|todo|in_progress|in_review|done (default: server-side)" }
50475
50710
  ]
50476
50711
  },
@@ -50509,7 +50744,8 @@ var taskCreateCommand = defineCommand(
50509
50744
  name: "create",
50510
50745
  description: "Create one or more tasks in a channel",
50511
50746
  options: [
50512
- { flags: "--channel <target>", description: "Channel target: '#channel'" },
50747
+ { flags: "--target <target>", description: "Channel target: '#channel'" },
50748
+ { flags: "--channel <target>", description: "Legacy alias for --target (accepted during transition)" },
50513
50749
  {
50514
50750
  flags: "--title <title>",
50515
50751
  description: "Task title (repeatable for batch create)",
@@ -50518,10 +50754,7 @@ var taskCreateCommand = defineCommand(
50518
50754
  ]
50519
50755
  },
50520
50756
  async (ctx, opts) => {
50521
- const channel = opts.channel?.trim();
50522
- if (!channel) {
50523
- throw cliError("INVALID_ARG", "--channel is required");
50524
- }
50757
+ const channel = requireTargetAlias(opts);
50525
50758
  const titles = opts.title ?? [];
50526
50759
  if (titles.length === 0) throw cliError("INVALID_ARG", "--title is required (at least one)");
50527
50760
  const body = { channel, tasks: titles.map((title) => ({ title })) };
@@ -50551,7 +50784,8 @@ var taskClaimCommand = defineCommand(
50551
50784
  name: "claim",
50552
50785
  description: "Claim one or more tasks (by task number or message id)",
50553
50786
  options: [
50554
- { flags: "--channel <target>", description: "Channel target: '#channel'" },
50787
+ { flags: "--target <target>", description: "Channel target: '#channel'" },
50788
+ { flags: "--channel <target>", description: "Legacy alias for --target (accepted during transition)" },
50555
50789
  {
50556
50790
  flags: "--number <n>",
50557
50791
  description: "Task number to claim (repeatable)",
@@ -50565,9 +50799,7 @@ var taskClaimCommand = defineCommand(
50565
50799
  ]
50566
50800
  },
50567
50801
  async (ctx, opts) => {
50568
- if (!opts.channel?.trim()) {
50569
- throw cliError("INVALID_ARG", "--channel is required");
50570
- }
50802
+ const channel = requireTargetAlias(opts);
50571
50803
  const numbers = (opts.number ?? []).map((raw) => {
50572
50804
  const n = Number(raw);
50573
50805
  if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
@@ -50579,7 +50811,7 @@ var taskClaimCommand = defineCommand(
50579
50811
  if (numbers.length === 0 && messageIds.length === 0) {
50580
50812
  throw cliError("INVALID_ARG", "Provide at least one --number or --message-id");
50581
50813
  }
50582
- const body = { channel: opts.channel };
50814
+ const body = { channel };
50583
50815
  if (numbers.length > 0) body.task_numbers = numbers;
50584
50816
  if (messageIds.length > 0) body.message_ids = messageIds;
50585
50817
  const agentContext = ctx.loadAgentContext();
@@ -50594,7 +50826,7 @@ var taskClaimCommand = defineCommand(
50594
50826
  throw cliError("INVALID_JSON_RESPONSE", "Agent API taskClaim returned an empty response body");
50595
50827
  }
50596
50828
  if (isFreshnessHeldResponse(res.data)) {
50597
- writeText(ctx.io, formatFreshnessHoldOutput(opts.channel, res.data, {
50829
+ writeText(ctx.io, formatFreshnessHoldOutput(channel, res.data, {
50598
50830
  heldAction: "Your task claim was not applied.",
50599
50831
  draftInstructions: "After reviewing the newer context, rerun the task claim command if it is still correct.\n"
50600
50832
  }));
@@ -50603,7 +50835,7 @@ var taskClaimCommand = defineCommand(
50603
50835
  if (!isTaskClaimSuccessResponse(res.data)) {
50604
50836
  throw cliError("INVALID_JSON_RESPONSE", "Agent API taskClaim returned an unexpected response body");
50605
50837
  }
50606
- writeText(ctx.io, formatClaimResults(opts.channel, res.data) + "\n");
50838
+ writeText(ctx.io, formatClaimResults(channel, res.data) + "\n");
50607
50839
  }
50608
50840
  );
50609
50841
  function registerTaskClaimCommand(parent, runtimeOptions = {}) {
@@ -50621,13 +50853,7 @@ function parseTaskNumber(raw) {
50621
50853
  return n;
50622
50854
  }
50623
50855
  function validateUnclaimOpts(opts) {
50624
- const channel = opts.channel?.trim();
50625
- if (!channel) {
50626
- throw new CliError({
50627
- code: "INVALID_ARG",
50628
- message: "--channel is required"
50629
- });
50630
- }
50856
+ const channel = requireTargetAlias(opts);
50631
50857
  return { channel, taskNumber: parseTaskNumber(opts.number) };
50632
50858
  }
50633
50859
  var taskUnclaimCommand = defineCommand(
@@ -50635,7 +50861,8 @@ var taskUnclaimCommand = defineCommand(
50635
50861
  name: "unclaim",
50636
50862
  description: "Release a previously-claimed task",
50637
50863
  options: [
50638
- { flags: "--channel <target>", description: "Channel target: '#channel'" },
50864
+ { flags: "--target <target>", description: "Channel target: '#channel'" },
50865
+ { flags: "--channel <target>", description: "Legacy alias for --target (accepted during transition)" },
50639
50866
  { flags: "--number <n>", description: "Task number to unclaim" }
50640
50867
  ]
50641
50868
  },
@@ -50687,13 +50914,7 @@ function parseStatus(raw) {
50687
50914
  return raw;
50688
50915
  }
50689
50916
  function validateUpdateOpts(opts) {
50690
- const channel = opts.channel?.trim();
50691
- if (!channel) {
50692
- throw new CliError({
50693
- code: "INVALID_ARG",
50694
- message: "--channel is required"
50695
- });
50696
- }
50917
+ const channel = requireTargetAlias(opts);
50697
50918
  return {
50698
50919
  channel,
50699
50920
  taskNumber: parseTaskNumber2(opts.number),
@@ -50705,7 +50926,8 @@ var taskUpdateCommand = defineCommand(
50705
50926
  name: "update",
50706
50927
  description: "Update task status",
50707
50928
  options: [
50708
- { flags: "--channel <target>", description: "Channel target: '#channel'" },
50929
+ { flags: "--target <target>", description: "Channel target: '#channel'" },
50930
+ { flags: "--channel <target>", description: "Legacy alias for --target (accepted during transition)" },
50709
50931
  { flags: "--number <n>", description: "Task number to update" },
50710
50932
  { flags: "--status <status>", description: `New status. One of: ${STATUSES.join(", ")}` }
50711
50933
  ]
@@ -50881,13 +51103,13 @@ function pushServiceBlock(lines, service, active) {
50881
51103
  lines.push(`- ${service.name}`);
50882
51104
  lines.push(` service: ${service.clientId}`);
50883
51105
  lines.push(` id: ${service.id}`);
50884
- if (service.appType === "slock_builtin") lines.push(" type: built-in Slock app");
51106
+ if (service.appType === "slock_builtin") lines.push(" type: built-in Raft app");
50885
51107
  lines.push(` status: ${active ? "active login" : "not logged in"}`);
50886
51108
  lines.push(` return URL: ${formatMaybe(service.returnUrl)}`);
50887
51109
  if (service.agentManifestUrl) {
50888
51110
  lines.push(` agent behavior manifest: ${service.agentManifestUrl}`);
50889
51111
  lines.push(` local CLI env: raft integration env --service ${JSON.stringify(service.clientId)}`);
50890
- lines.push(` if manifest exposes HTTP API actions: raft integration invoke --service ${JSON.stringify(service.clientId)} --list-actions`);
51112
+ lines.push(` for login_with_raft HTTP API action manifests: raft integration invoke --service ${JSON.stringify(service.clientId)} --list-actions`);
50891
51113
  }
50892
51114
  if (service.homepageUrl) lines.push(` homepage: ${service.homepageUrl}`);
50893
51115
  if (service.description) lines.push(` description: ${service.description}`);
@@ -50899,7 +51121,7 @@ function formatIntegrationList(data) {
50899
51121
  const registeredServices = data.services.filter((service) => service.appType !== "slock_builtin");
50900
51122
  const lines = [];
50901
51123
  if (builtInServices.length > 0) {
50902
- lines.push("Built-in Slock apps:");
51124
+ lines.push("Built-in Raft apps:");
50903
51125
  for (const service of builtInServices) {
50904
51126
  pushServiceBlock(lines, service, activeByServiceId.get(service.id));
50905
51127
  }
@@ -50927,7 +51149,7 @@ function formatIntegrationList(data) {
50927
51149
  if (login.agentManifestUrl) {
50928
51150
  lines.push(` agent behavior manifest: ${login.agentManifestUrl}`);
50929
51151
  lines.push(` local CLI env: raft integration env --service ${JSON.stringify(login.clientId)}`);
50930
- lines.push(` if manifest exposes HTTP API actions: raft integration invoke --service ${JSON.stringify(login.clientId)} --list-actions`);
51152
+ lines.push(` for login_with_raft HTTP API action manifests: raft integration invoke --service ${JSON.stringify(login.clientId)} --list-actions`);
50931
51153
  }
50932
51154
  lines.push(` created: ${login.createdAt}`);
50933
51155
  }
@@ -50964,16 +51186,16 @@ function formatIntegrationLogin(data) {
50964
51186
  if (data.service.agentManifestUrl) {
50965
51187
  lines.push(`agent behavior manifest: ${data.service.agentManifestUrl}`);
50966
51188
  lines.push(`local CLI env: raft integration env --service ${JSON.stringify(data.service.clientId)}`);
50967
- lines.push(`if manifest exposes HTTP API actions: raft integration invoke --service ${JSON.stringify(data.service.clientId)} --list-actions`);
50968
- }
50969
- lines.push("complete: this agent login is configured in Slock; no human OAuth is required");
50970
- lines.push("identity: run `raft profile show` if the service or human asks for your Slock Agent identity card");
50971
- const callbackHandoffUrl = buildAgentCallbackHandoffUrl(data.service.returnUrl, data.requestId);
50972
- if (callbackHandoffUrl) {
50973
- lines.push(`service callback handoff URL: ${callbackHandoffUrl}`);
50974
- lines.push("note: stateless Login with Raft API-action services use this callback once to create their service session");
50975
- lines.push(`next: prefer \`raft integration invoke --service ${JSON.stringify(data.service.clientId)} --list-actions\` when the service manifest exposes actions`);
51189
+ lines.push(`for login_with_raft HTTP API action manifests: raft integration invoke --service ${JSON.stringify(data.service.clientId)} --list-actions`);
51190
+ }
51191
+ lines.push("complete: this agent login is configured in Raft; no human OAuth is required");
51192
+ lines.push("identity: run `raft profile show` if the service or human asks for your Raft Agent identity card");
51193
+ if (data.session) {
51194
+ lines.push(`session: service session ${data.session.source === "fresh" ? "created" : "reused"} and stored for this agent`);
51195
+ if (data.session.path) lines.push(`session store: ${data.session.path}`);
51196
+ lines.push(`next: use \`raft integration invoke --service ${JSON.stringify(data.service.clientId)} --list-actions\` only for login_with_raft HTTP API action manifests; for session-cookie services, use the established service session per service docs`);
50976
51197
  } else {
51198
+ lines.push("session: no service callback session was established; Raft grant is active");
50977
51199
  lines.push("next: use the service, or run `raft integration list` to confirm active login");
50978
51200
  }
50979
51201
  return lines.join("\n");
@@ -50981,7 +51203,7 @@ function formatIntegrationLogin(data) {
50981
51203
  var integrationListCommand = defineCommand(
50982
51204
  {
50983
51205
  name: "list",
50984
- description: "List built-in Slock apps, registered services, and this agent's active logins",
51206
+ description: "List built-in Raft apps, registered services, and this agent's active logins",
50985
51207
  options: [{ flags: "--json", description: "Emit machine-readable JSON" }]
50986
51208
  },
50987
51209
  async (ctx, opts) => {
@@ -51004,6 +51226,195 @@ function registerIntegrationListCommand(parent, runtimeOptions = {}) {
51004
51226
  registerCliCommand(parent, integrationListCommand, runtimeOptions);
51005
51227
  }
51006
51228
  init_esm_shims();
51229
+ init_esm_shims();
51230
+ function safeUrl(value, label) {
51231
+ let url2;
51232
+ try {
51233
+ url2 = new URL(value);
51234
+ } catch {
51235
+ throw cliError("INVALID_ARG", `${label} must be a valid URL`);
51236
+ }
51237
+ if (url2.protocol !== "https:" && url2.protocol !== "http:") {
51238
+ throw cliError("INVALID_ARG", `${label} must use http or https`);
51239
+ }
51240
+ if (url2.username || url2.password) {
51241
+ throw cliError("INVALID_ARG", `${label} must not include credentials`);
51242
+ }
51243
+ return url2;
51244
+ }
51245
+ function resolveStateRoot(env) {
51246
+ const configured = env.RAFT_HOME?.trim() || env.SLOCK_HOME?.trim();
51247
+ if (configured) return configured;
51248
+ const home = env.HOME ?? os4.homedir();
51249
+ return path8.join(home, ".slock");
51250
+ }
51251
+ function integrationSessionFilePath(input) {
51252
+ const root = input.agentContext.profileCredentialPath ? path8.dirname(input.agentContext.profileCredentialPath) : path8.join(resolveStateRoot(input.env), "integration-sessions", input.agentContext.agentId);
51253
+ const safeClientId = encodeURIComponent(input.service.clientId).replace(/%/g, "_");
51254
+ return path8.join(root, "integrations", `${safeClientId}.json`);
51255
+ }
51256
+ function setCookieHeaderValues(headers) {
51257
+ const getSetCookie = headers.getSetCookie;
51258
+ return typeof getSetCookie === "function" ? getSetCookie.call(headers) : [headers.get("set-cookie")].filter((value) => Boolean(value));
51259
+ }
51260
+ function defaultCookiePath(pathname) {
51261
+ if (!pathname.startsWith("/") || pathname === "/") return "/";
51262
+ const lastSlash = pathname.lastIndexOf("/");
51263
+ if (lastSlash <= 0) return "/";
51264
+ return pathname.slice(0, lastSlash);
51265
+ }
51266
+ function parseCookieExpiry(parts) {
51267
+ const now = Date.now();
51268
+ for (const part of parts) {
51269
+ const separator = part.indexOf("=");
51270
+ const rawName = separator >= 0 ? part.slice(0, separator) : part;
51271
+ const rawValue = separator >= 0 ? part.slice(separator + 1) : "";
51272
+ const name = rawName.trim().toLowerCase();
51273
+ if (name === "max-age") {
51274
+ const seconds = Number(rawValue.trim());
51275
+ if (Number.isFinite(seconds)) return new Date(now + Math.max(0, seconds) * 1e3).toISOString();
51276
+ }
51277
+ if (name === "expires") {
51278
+ const time3 = Date.parse(rawValue.trim());
51279
+ if (Number.isFinite(time3)) return new Date(time3).toISOString();
51280
+ }
51281
+ }
51282
+ return void 0;
51283
+ }
51284
+ function parseSessionCookie(value, sourceUrl) {
51285
+ const parts = value.split(";").map((part) => part.trim()).filter(Boolean);
51286
+ const pair = parts.shift();
51287
+ if (!pair || !pair.includes("=") || pair.startsWith("=")) return null;
51288
+ const sourceHost = sourceUrl.hostname.toLowerCase();
51289
+ let host = sourceHost;
51290
+ let cookiePath = defaultCookiePath(sourceUrl.pathname);
51291
+ let secure = false;
51292
+ for (const part of parts) {
51293
+ const separator = part.indexOf("=");
51294
+ const rawName = separator >= 0 ? part.slice(0, separator) : part;
51295
+ const rawValue = separator >= 0 ? part.slice(separator + 1) : "";
51296
+ const name = rawName.trim().toLowerCase();
51297
+ if (name === "secure") {
51298
+ secure = true;
51299
+ } else if (name === "path" && rawValue.trim().startsWith("/")) {
51300
+ cookiePath = rawValue.trim();
51301
+ } else if (name === "domain") {
51302
+ const domain2 = rawValue.trim().replace(/^\./, "").toLowerCase();
51303
+ if (domain2 !== sourceHost) return null;
51304
+ host = domain2;
51305
+ }
51306
+ }
51307
+ return { pair, host, path: cookiePath, secure, expiresAt: parseCookieExpiry(parts) };
51308
+ }
51309
+ function cookiePathMatches(requestPath, cookiePath) {
51310
+ if (requestPath === cookiePath) return true;
51311
+ if (cookiePath.endsWith("/")) return requestPath.startsWith(cookiePath);
51312
+ return requestPath.startsWith(`${cookiePath}/`);
51313
+ }
51314
+ function cookieHeaderForUrl(cookies, url2) {
51315
+ const host = url2.hostname.toLowerCase();
51316
+ const valid = cookies.filter((cookie) => cookie.host === host).filter((cookie) => !cookie.secure || url2.protocol === "https:").filter((cookie) => cookiePathMatches(url2.pathname || "/", cookie.path)).map((cookie) => cookie.pair);
51317
+ return valid.length > 0 ? valid.join("; ") : null;
51318
+ }
51319
+ function sessionCookiesFromSetCookie(headers, sourceUrl) {
51320
+ return setCookieHeaderValues(headers).map((value) => parseSessionCookie(value, sourceUrl)).filter((value) => Boolean(value));
51321
+ }
51322
+ function isCookieFresh(cookie) {
51323
+ if (!cookie.expiresAt) return true;
51324
+ return Date.parse(cookie.expiresAt) > Date.now() + 3e4;
51325
+ }
51326
+ function freshCookies(cookies) {
51327
+ return cookies.filter(isCookieFresh);
51328
+ }
51329
+ function loadStoredIntegrationSession(input) {
51330
+ const filePath = integrationSessionFilePath(input);
51331
+ if (!filePath) return null;
51332
+ let raw;
51333
+ try {
51334
+ raw = fs5.readFileSync(filePath, "utf8");
51335
+ } catch {
51336
+ return null;
51337
+ }
51338
+ let parsed;
51339
+ try {
51340
+ parsed = JSON.parse(raw);
51341
+ } catch {
51342
+ return null;
51343
+ }
51344
+ if (!parsed || typeof parsed !== "object") return null;
51345
+ const session = parsed;
51346
+ if (session.serviceId !== input.service.id || session.clientId !== input.service.clientId || session.returnUrl !== input.service.returnUrl || !Array.isArray(session.cookies)) {
51347
+ return null;
51348
+ }
51349
+ const cookies = freshCookies(session.cookies);
51350
+ if (cookies.length === 0) return null;
51351
+ return { ...session, cookies };
51352
+ }
51353
+ function storeIntegrationSession(input) {
51354
+ const filePath = integrationSessionFilePath(input);
51355
+ if (!filePath) return null;
51356
+ const now = (/* @__PURE__ */ new Date()).toISOString();
51357
+ const previous = loadStoredIntegrationSession(input);
51358
+ const body = {
51359
+ serviceId: input.service.id,
51360
+ clientId: input.service.clientId,
51361
+ returnUrl: input.service.returnUrl ?? "",
51362
+ cookies: freshCookies(input.cookies),
51363
+ createdAt: previous?.createdAt ?? now,
51364
+ updatedAt: now
51365
+ };
51366
+ fs5.mkdirSync(path8.dirname(filePath), { recursive: true, mode: 448 });
51367
+ fs5.writeFileSync(filePath, `${JSON.stringify(body, null, 2)}
51368
+ `, { mode: 384 });
51369
+ return filePath;
51370
+ }
51371
+ async function consumeAgentLoginHandoff(input) {
51372
+ if (!input.login.requestId) {
51373
+ throw cliError("INTEGRATION_LOGIN_FAILED", "agent login response did not include an internal one-time handoff request");
51374
+ }
51375
+ const callbackUrl = buildAgentCallbackHandoffUrl(input.service.returnUrl, input.login.requestId);
51376
+ if (!callbackUrl) {
51377
+ throw cliError("INTEGRATION_LOGIN_FAILED", "service return URL cannot be used for Agent Login callback handoff");
51378
+ }
51379
+ const parsedCallbackUrl = safeUrl(callbackUrl, "service callback URL");
51380
+ const response = await fetch(callbackUrl, {
51381
+ method: "GET",
51382
+ redirect: "manual",
51383
+ headers: { accept: "text/html,application/json" }
51384
+ });
51385
+ if (response.status < 200 || response.status >= 400) {
51386
+ if (response.status === 409) {
51387
+ throw cliError(
51388
+ "INTEGRATION_LOGIN_FAILED",
51389
+ "service callback handoff was rejected as expired or already used; rerun `raft integration login` to obtain a fresh handoff"
51390
+ );
51391
+ }
51392
+ throw cliError("INTEGRATION_LOGIN_FAILED", `service callback handoff failed with HTTP ${response.status}`);
51393
+ }
51394
+ const cookies = sessionCookiesFromSetCookie(response.headers, parsedCallbackUrl);
51395
+ if (cookies.length === 0) {
51396
+ throw cliError(
51397
+ "INTEGRATION_LOGIN_FAILED",
51398
+ "service callback handoff did not set a session cookie; the service may not support stateless Agent Login sessions yet"
51399
+ );
51400
+ }
51401
+ return cookies;
51402
+ }
51403
+ async function ensureIntegrationServiceSession(input) {
51404
+ if (!input.refresh) {
51405
+ const stored = loadStoredIntegrationSession(input);
51406
+ if (stored) {
51407
+ return {
51408
+ cookies: stored.cookies,
51409
+ source: "cache",
51410
+ sessionPath: integrationSessionFilePath(input)
51411
+ };
51412
+ }
51413
+ }
51414
+ const cookies = await consumeAgentLoginHandoff(input);
51415
+ const sessionPath = storeIntegrationSession({ ...input, cookies });
51416
+ return { cookies, source: "fresh", sessionPath };
51417
+ }
51007
51418
  function normalizeScopes(raw) {
51008
51419
  if (!raw || raw.length === 0) return void 0;
51009
51420
  const scopes = Array.from(new Set(
@@ -51014,10 +51425,15 @@ function normalizeScopes(raw) {
51014
51425
  }
51015
51426
  return scopes;
51016
51427
  }
51428
+ function redactSuccessfulRequestId(data) {
51429
+ if (data.status === "approval_required") return data;
51430
+ const { requestId: _requestId, ...rest } = data;
51431
+ return rest;
51432
+ }
51017
51433
  var integrationLoginCommand = defineCommand(
51018
51434
  {
51019
51435
  name: "login",
51020
- description: "Provision or reuse this agent's login for a built-in Slock app or registered service",
51436
+ description: "Provision or reuse this agent's login for a built-in Raft app or registered service",
51021
51437
  options: [
51022
51438
  { flags: "--service <id>", description: "Registered service id, client id, or exact service name" },
51023
51439
  {
@@ -51049,11 +51465,30 @@ var integrationLoginCommand = defineCommand(
51049
51465
  const code = res.status >= 500 ? "SERVER_5XX" : "INTEGRATION_LOGIN_FAILED";
51050
51466
  throw cliError(code, res.error ?? `HTTP ${res.status}`);
51051
51467
  }
51468
+ let data = res.data;
51469
+ if (data.status !== "approval_required" && data.service.returnUrl) {
51470
+ const session = await ensureIntegrationServiceSession({
51471
+ login: data,
51472
+ service: data.service,
51473
+ agentContext,
51474
+ env: ctx.env,
51475
+ refresh: true
51476
+ });
51477
+ data = {
51478
+ ...data,
51479
+ session: {
51480
+ status: "stored",
51481
+ source: session.source,
51482
+ path: session.sessionPath
51483
+ }
51484
+ };
51485
+ }
51486
+ const outputData = redactSuccessfulRequestId(data);
51052
51487
  if (opts.json) {
51053
- writeJson(ctx.io, { ok: true, data: res.data });
51488
+ writeJson(ctx.io, { ok: true, data: outputData });
51054
51489
  return;
51055
51490
  }
51056
- writeText(ctx.io, `${formatIntegrationLogin(res.data)}
51491
+ writeText(ctx.io, `${formatIntegrationLogin(outputData)}
51057
51492
  `);
51058
51493
  }
51059
51494
  );
@@ -51129,22 +51564,22 @@ function requireEndpointPath(value, field) {
51129
51564
  if (typeof value !== "string" || !value.trim()) {
51130
51565
  throw new Error(`${field} must be a non-empty path string`);
51131
51566
  }
51132
- const path9 = value.trim();
51133
- if (!path9.startsWith("/")) {
51567
+ const path10 = value.trim();
51568
+ if (!path10.startsWith("/")) {
51134
51569
  throw new Error(`${field} must start with /`);
51135
51570
  }
51136
- if (path9.startsWith("//")) {
51571
+ if (path10.startsWith("//")) {
51137
51572
  throw new Error(`${field} must be a relative service path`);
51138
51573
  }
51139
51574
  try {
51140
- const parsed = new URL(path9, "https://manifest.local");
51575
+ const parsed = new URL(path10, "https://manifest.local");
51141
51576
  if (parsed.origin !== "https://manifest.local" || parsed.username || parsed.password || parsed.hash) {
51142
51577
  throw new Error();
51143
51578
  }
51144
51579
  } catch {
51145
51580
  throw new Error(`${field} must be a relative service path`);
51146
51581
  }
51147
- return path9;
51582
+ return path10;
51148
51583
  }
51149
51584
  function normalizeActionMethod(value) {
51150
51585
  if (typeof value !== "string") {
@@ -51340,14 +51775,14 @@ function sanitizePathSegment(value) {
51340
51775
  const segment = value.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
51341
51776
  return segment || "service";
51342
51777
  }
51343
- function resolveSlockHome(env, homeDir = os4.homedir()) {
51778
+ function resolveSlockHome(env, homeDir = os5.homedir()) {
51344
51779
  const configured = env.SLOCK_HOME?.trim() || env.RAFT_HOME?.trim();
51345
- const raw = configured && configured.length > 0 ? configured : path8.join(homeDir, ".slock");
51346
- return path8.resolve(expandHome(raw, homeDir));
51780
+ const raw = configured && configured.length > 0 ? configured : path9.join(homeDir, ".slock");
51781
+ return path9.resolve(expandHome(raw, homeDir));
51347
51782
  }
51348
51783
  function expandHome(input, homeDir) {
51349
51784
  if (input === "~") return homeDir;
51350
- if (input.startsWith("~/")) return path8.join(homeDir, input.slice(2));
51785
+ if (input.startsWith("~/")) return path9.join(homeDir, input.slice(2));
51351
51786
  return input;
51352
51787
  }
51353
51788
  function buildLocalCliProfileEnv(input) {
@@ -51361,15 +51796,15 @@ function buildLocalCliProfileEnv(input) {
51361
51796
  throw new Error("manifest must set credential_boundary.forbid_user_home=true for local_cli isolation");
51362
51797
  }
51363
51798
  const root = resolveSlockHome(input.env ?? process.env, input.homeDir);
51364
- const profileHome = path8.join(
51799
+ const profileHome = path9.join(
51365
51800
  root,
51366
51801
  "integration-profiles",
51367
51802
  sanitizePathSegment(input.ctx.serverId ?? "server"),
51368
51803
  sanitizePathSegment(input.ctx.agentId),
51369
51804
  sanitizePathSegment(input.serviceId)
51370
51805
  );
51371
- fs5.mkdirSync(profileHome, { recursive: true, mode: 448 });
51372
- fs5.chmodSync(profileHome, 448);
51806
+ fs6.mkdirSync(profileHome, { recursive: true, mode: 448 });
51807
+ fs6.chmodSync(profileHome, 448);
51373
51808
  return {
51374
51809
  serviceId: input.serviceId,
51375
51810
  command: input.manifest.execution.command,
@@ -51378,10 +51813,10 @@ function buildLocalCliProfileEnv(input) {
51378
51813
  SLOCK_INTEGRATION_SERVICE: input.serviceId,
51379
51814
  SLOCK_INTEGRATION_PROFILE_HOME: profileHome,
51380
51815
  HOME: profileHome,
51381
- XDG_CONFIG_HOME: path8.join(profileHome, ".config"),
51382
- XDG_CACHE_HOME: path8.join(profileHome, ".cache"),
51383
- XDG_DATA_HOME: path8.join(profileHome, ".local", "share"),
51384
- XDG_STATE_HOME: path8.join(profileHome, ".local", "state")
51816
+ XDG_CONFIG_HOME: path9.join(profileHome, ".config"),
51817
+ XDG_CACHE_HOME: path9.join(profileHome, ".cache"),
51818
+ XDG_DATA_HOME: path9.join(profileHome, ".local", "share"),
51819
+ XDG_STATE_HOME: path9.join(profileHome, ".local", "state")
51385
51820
  }
51386
51821
  };
51387
51822
  }
@@ -51390,9 +51825,9 @@ function shellQuote(value) {
51390
51825
  }
51391
51826
  function formatShellExports(profile) {
51392
51827
  const lines = [
51393
- `# Slock integration profile for ${profile.serviceId}`,
51828
+ `# Raft integration profile for ${profile.serviceId}`,
51394
51829
  `# command: ${profile.command}`,
51395
- "# This only exports env; Slock does not execute manifest commands.",
51830
+ "# This only exports env; Raft does not execute manifest commands.",
51396
51831
  "# Apply these exports before invoking the local CLI yourself."
51397
51832
  ];
51398
51833
  for (const [key, value] of Object.entries(profile.env)) {
@@ -51418,10 +51853,10 @@ function describeNoLocalEnv(manifest) {
51418
51853
  return "manifest execution mode is http_api; no local CLI env is required";
51419
51854
  }
51420
51855
  if (!manifest.credential_boundary) {
51421
- return "manifest does not request a Slock-managed local environment";
51856
+ return "manifest does not request a Raft-managed local environment";
51422
51857
  }
51423
51858
  if (manifest.credential_boundary.storage === "slock_managed_token") {
51424
- return "manifest uses Slock-managed token storage; no local HOME/XDG exports are required";
51859
+ return "manifest uses Raft-managed token storage; no local HOME/XDG exports are required";
51425
51860
  }
51426
51861
  return "manifest does not request local CLI env exports";
51427
51862
  }
@@ -51500,7 +51935,7 @@ async function resolveIntegrationEnv(input) {
51500
51935
  }
51501
51936
  function formatNoLocalEnv(input) {
51502
51937
  const lines = [
51503
- `# Slock integration profile for ${input.service}`,
51938
+ `# Raft integration profile for ${input.service}`,
51504
51939
  input.manifestUrl ? `# manifest: ${input.manifestUrl}` : "# manifest: none declared",
51505
51940
  "# No local CLI environment exports are required for this service.",
51506
51941
  `# ${input.message}`
@@ -51510,7 +51945,7 @@ function formatNoLocalEnv(input) {
51510
51945
  lines.push(`# list actions: raft integration invoke --service ${JSON.stringify(input.service)} --list-actions`);
51511
51946
  lines.push(`# invoke action: raft integration invoke --service ${JSON.stringify(input.service)} --action <name>`);
51512
51947
  }
51513
- lines.push("# Slock did not set HOME/XDG exports and did not execute manifest commands.");
51948
+ lines.push("# Raft did not set HOME/XDG exports and did not execute manifest commands.");
51514
51949
  return lines.join("\n");
51515
51950
  }
51516
51951
  var integrationEnvCommand = defineCommand(
@@ -51624,10 +52059,10 @@ function parseHandlerArgs(serviceArgOrOpts, actionArgOrOpts, maybeOpts) {
51624
52059
  }
51625
52060
  function readTextReference(value) {
51626
52061
  if (!value.startsWith("@")) return value;
51627
- const path9 = value.slice(1);
51628
- if (!path9) throw cliError("INVALID_ARG", "@ file references must include a path");
51629
- if (path9 === "-") return fs6.readFileSync(0, "utf8");
51630
- return fs6.readFileSync(path9, "utf8");
52062
+ const path10 = value.slice(1);
52063
+ if (!path10) throw cliError("INVALID_ARG", "@ file references must include a path");
52064
+ if (path10 === "-") return fs7.readFileSync(0, "utf8");
52065
+ return fs7.readFileSync(path10, "utf8");
51631
52066
  }
51632
52067
  function parseJsonObject(raw, label) {
51633
52068
  let parsed;
@@ -51650,7 +52085,7 @@ function parseActionPayload(opts) {
51650
52085
  Object.assign(payload, parseJsonObject(opts.dataJson, "--data-json"));
51651
52086
  }
51652
52087
  if (opts.dataFile) {
51653
- const raw = opts.dataFile === "-" ? fs6.readFileSync(0, "utf8") : fs6.readFileSync(opts.dataFile, "utf8");
52088
+ const raw = opts.dataFile === "-" ? fs7.readFileSync(0, "utf8") : fs7.readFileSync(opts.dataFile, "utf8");
51654
52089
  Object.assign(payload, parseJsonObject(raw, "--data-file"));
51655
52090
  }
51656
52091
  for (const rawParam of opts.param ?? []) {
@@ -51672,7 +52107,7 @@ function validateRequiredParams(action, payload) {
51672
52107
  }
51673
52108
  }
51674
52109
  }
51675
- function safeUrl(value, label) {
52110
+ function safeUrl2(value, label) {
51676
52111
  let url2;
51677
52112
  try {
51678
52113
  url2 = new URL(value);
@@ -51688,87 +52123,16 @@ function safeUrl(value, label) {
51688
52123
  return url2;
51689
52124
  }
51690
52125
  function resolveActionUrl(input) {
51691
- const base = input.manifest.execution.base_url ?? input.manifest.app_origin ?? input.service.homepageUrl ?? (input.service.returnUrl ? safeUrl(input.service.returnUrl, "service return URL").origin : null);
52126
+ const base = input.manifest.execution.base_url ?? input.manifest.app_origin ?? input.service.homepageUrl ?? (input.service.returnUrl ? safeUrl2(input.service.returnUrl, "service return URL").origin : null);
51692
52127
  if (!base) {
51693
52128
  throw cliError(
51694
52129
  "INVALID_ARG",
51695
52130
  "manifest must provide execution.base_url or app_origin, or the service must provide a homepage/return URL"
51696
52131
  );
51697
52132
  }
51698
- const baseUrl = safeUrl(base, "action base URL");
52133
+ const baseUrl = safeUrl2(base, "action base URL");
51699
52134
  return new URL(input.action.endpoint.path, baseUrl);
51700
52135
  }
51701
- function setCookieHeaderValues(headers) {
51702
- const getSetCookie = headers.getSetCookie;
51703
- return typeof getSetCookie === "function" ? getSetCookie.call(headers) : [headers.get("set-cookie")].filter((value) => Boolean(value));
51704
- }
51705
- function defaultCookiePath(pathname) {
51706
- if (!pathname.startsWith("/") || pathname === "/") return "/";
51707
- const lastSlash = pathname.lastIndexOf("/");
51708
- if (lastSlash <= 0) return "/";
51709
- return pathname.slice(0, lastSlash);
51710
- }
51711
- function parseSessionCookie(value, sourceUrl) {
51712
- const parts = value.split(";").map((part) => part.trim()).filter(Boolean);
51713
- const pair = parts.shift();
51714
- if (!pair || !pair.includes("=") || pair.startsWith("=")) return null;
51715
- const sourceHost = sourceUrl.hostname.toLowerCase();
51716
- let host = sourceHost;
51717
- let path9 = defaultCookiePath(sourceUrl.pathname);
51718
- let secure = false;
51719
- for (const part of parts) {
51720
- const separator = part.indexOf("=");
51721
- const rawName = separator >= 0 ? part.slice(0, separator) : part;
51722
- const rawValue = separator >= 0 ? part.slice(separator + 1) : "";
51723
- const name = rawName.trim().toLowerCase();
51724
- if (name === "secure") {
51725
- secure = true;
51726
- } else if (name === "path" && rawValue.trim().startsWith("/")) {
51727
- path9 = rawValue.trim();
51728
- } else if (name === "domain") {
51729
- const domain2 = rawValue.trim().replace(/^\./, "").toLowerCase();
51730
- if (domain2 !== sourceHost) return null;
51731
- host = domain2;
51732
- }
51733
- }
51734
- return { pair, host, path: path9, secure };
51735
- }
51736
- function cookiePathMatches(requestPath, cookiePath) {
51737
- if (requestPath === cookiePath) return true;
51738
- if (cookiePath.endsWith("/")) return requestPath.startsWith(cookiePath);
51739
- return requestPath.startsWith(`${cookiePath}/`);
51740
- }
51741
- function cookieHeaderForUrl(cookies, url2) {
51742
- const host = url2.hostname.toLowerCase();
51743
- const valid = cookies.filter((cookie) => cookie.host === host).filter((cookie) => !cookie.secure || url2.protocol === "https:").filter((cookie) => cookiePathMatches(url2.pathname || "/", cookie.path)).map((cookie) => cookie.pair);
51744
- return valid.length > 0 ? valid.join("; ") : null;
51745
- }
51746
- function sessionCookiesFromSetCookie(headers, sourceUrl) {
51747
- return setCookieHeaderValues(headers).map((value) => parseSessionCookie(value, sourceUrl)).filter((value) => Boolean(value));
51748
- }
51749
- async function establishServiceSession(input) {
51750
- const callbackUrl = buildAgentCallbackHandoffUrl(input.service.returnUrl, input.login.requestId);
51751
- if (!callbackUrl) {
51752
- throw cliError("INTEGRATION_INVOKE_FAILED", "service return URL cannot be used for Agent Login callback handoff");
51753
- }
51754
- const parsedCallbackUrl = safeUrl(callbackUrl, "service callback URL");
51755
- const response = await fetch(callbackUrl, {
51756
- method: "GET",
51757
- redirect: "manual",
51758
- headers: { accept: "text/html,application/json" }
51759
- });
51760
- if (response.status < 200 || response.status >= 400) {
51761
- throw cliError("INTEGRATION_INVOKE_FAILED", `service callback handoff failed with HTTP ${response.status}`);
51762
- }
51763
- const cookies = sessionCookiesFromSetCookie(response.headers, parsedCallbackUrl);
51764
- if (cookies.length === 0) {
51765
- throw cliError(
51766
- "INTEGRATION_INVOKE_FAILED",
51767
- "service callback handoff did not set a session cookie; the service may not support stateless Agent Login API actions yet"
51768
- );
51769
- }
51770
- return cookies;
51771
- }
51772
52136
  function appendPayloadAsQuery(url2, payload) {
51773
52137
  for (const [key, value] of Object.entries(payload)) {
51774
52138
  if (value === void 0 || value === null) continue;
@@ -51806,6 +52170,15 @@ async function invokeHttpAction(input) {
51806
52170
  throw cliError("INVALID_JSON_RESPONSE", `service action returned invalid JSON (HTTP ${response.status})`);
51807
52171
  });
51808
52172
  if (!response.ok) {
52173
+ if (response.status === 401 || response.status === 403) {
52174
+ throw cliError(
52175
+ "INTEGRATION_INVOKE_FAILED",
52176
+ `service session was rejected or expired (HTTP ${response.status})`,
52177
+ {
52178
+ suggestedNextAction: `Run \`raft integration login --service ${input.service.clientId}\` and retry the action.`
52179
+ }
52180
+ );
52181
+ }
51809
52182
  const message = value2 && typeof value2 === "object" && "error" in value2 ? String(value2.error) : `service action failed with HTTP ${response.status}`;
51810
52183
  throw cliError("INTEGRATION_INVOKE_FAILED", message);
51811
52184
  }
@@ -51813,6 +52186,15 @@ async function invokeHttpAction(input) {
51813
52186
  }
51814
52187
  const value = await response.text();
51815
52188
  if (!response.ok) {
52189
+ if (response.status === 401 || response.status === 403) {
52190
+ throw cliError(
52191
+ "INTEGRATION_INVOKE_FAILED",
52192
+ `service session was rejected or expired (HTTP ${response.status})`,
52193
+ {
52194
+ suggestedNextAction: `Run \`raft integration login --service ${input.service.clientId}\` and retry the action.`
52195
+ }
52196
+ );
52197
+ }
51816
52198
  throw cliError("INTEGRATION_INVOKE_FAILED", value || `service action failed with HTTP ${response.status}`);
51817
52199
  }
51818
52200
  return { kind: "text", status: response.status, value };
@@ -51858,7 +52240,53 @@ function formatActionResult(input) {
51858
52240
  }
51859
52241
  return lines.join("\n");
51860
52242
  }
51861
- async function fetchManifestForInvoke(service) {
52243
+ function unsupportedAuthNextAction(service, handoff2) {
52244
+ const loginCommand = `raft integration login --service ${JSON.stringify(service.clientId)}`;
52245
+ const manifestGuidance = [
52246
+ "or ask the service owner to publish a current login_with_raft HTTP API action manifest for integration invoke.",
52247
+ "`oauth_session_cookie` manifests are session-cookie services and are not directly invokable through this command yet."
52248
+ ];
52249
+ if (handoff2?.kind === "handoff_url") {
52250
+ return [
52251
+ "A login request was created or reused for this agent.",
52252
+ `Use the service callback handoff URL to establish the service session: ${handoff2.url}`,
52253
+ ...manifestGuidance
52254
+ ].join(" ");
52255
+ }
52256
+ if (handoff2?.kind === "approval_required") {
52257
+ const card = handoff2.actionCardMessageId ? `Approval request ${handoff2.requestId} was posted to ${handoff2.target ?? "-"} as card ${handoff2.actionCardMessageId}.` : `Approval request ${handoff2.requestId} was created but no approval card was posted.`;
52258
+ return [
52259
+ "Human approval is required before a service callback handoff URL can be generated.",
52260
+ card,
52261
+ "Ask a server owner/admin to approve it, then rerun this command to receive the callback handoff URL.",
52262
+ `To post an approval card, rerun with --target <channel-or-thread>, or run \`${loginCommand} --target <channel-or-thread>\`.`,
52263
+ ...manifestGuidance
52264
+ ].join(" ");
52265
+ }
52266
+ if (service.returnUrl) {
52267
+ const lines = [
52268
+ `Run \`${loginCommand}\` and use the printed service callback handoff URL to establish the service session,`,
52269
+ ...manifestGuidance
52270
+ ];
52271
+ if (handoff2?.kind === "unavailable") {
52272
+ lines.unshift(`Could not prepare a callback handoff URL automatically: ${handoff2.reason}.`);
52273
+ }
52274
+ return lines.join(" ");
52275
+ }
52276
+ return [
52277
+ "Ask the service owner to publish a current login_with_raft HTTP API action manifest for integration invoke.",
52278
+ "`oauth_session_cookie` manifests are session-cookie services and are not directly invokable through this command yet."
52279
+ ].join(" ");
52280
+ }
52281
+ async function manifestInvalidNextAction(service, err, prepareHandoff) {
52282
+ const message = err instanceof Error ? err.message : String(err);
52283
+ if (/auth\.type must be login_with_raft/.test(message)) {
52284
+ return unsupportedAuthNextAction(service, await prepareHandoff?.());
52285
+ }
52286
+ return void 0;
52287
+ }
52288
+ async function fetchManifestForInvoke(input) {
52289
+ const service = input.service;
51862
52290
  if (!service.agentManifestUrl) {
51863
52291
  throw cliError("INTEGRATION_MANIFEST_MISSING", `${service.name} does not expose an agent behavior manifest`);
51864
52292
  }
@@ -51872,9 +52300,20 @@ async function fetchManifestForInvoke(service) {
51872
52300
  if (err instanceof AgentManifestResponseFormatError) {
51873
52301
  throw cliError("INTEGRATION_MANIFEST_INVALID", err.message, { cause: err });
51874
52302
  }
51875
- throw cliError("INTEGRATION_MANIFEST_INVALID", err.message, { cause: err });
52303
+ const suggestedNextAction = await manifestInvalidNextAction(
52304
+ service,
52305
+ err,
52306
+ input.prepareUnsupportedAuthHandoff
52307
+ );
52308
+ throw cliError("INTEGRATION_MANIFEST_INVALID", err.message, {
52309
+ cause: err,
52310
+ suggestedNextAction
52311
+ });
51876
52312
  }
51877
52313
  }
52314
+ function loginFailureReason(res) {
52315
+ return res.error ?? `HTTP ${res.status}`;
52316
+ }
51878
52317
  var integrationInvokeCommand = defineCommand(
51879
52318
  {
51880
52319
  name: "invoke",
@@ -51924,7 +52363,44 @@ var integrationInvokeCommand = defineCommand(
51924
52363
  if (!service) {
51925
52364
  throw cliError("INTEGRATION_NOT_FOUND", `No registered integration matched ${serviceQuery}`);
51926
52365
  }
51927
- const manifest = await fetchManifestForInvoke(service);
52366
+ const prepareUnsupportedAuthHandoff = async () => {
52367
+ if (!service.returnUrl) return void 0;
52368
+ let scopes2;
52369
+ try {
52370
+ scopes2 = normalizeScopes2(opts.scope);
52371
+ } catch (err) {
52372
+ return { kind: "unavailable", reason: err instanceof Error ? err.message : String(err) };
52373
+ }
52374
+ const loginRes = await api.integrations.login({
52375
+ service: service.clientId,
52376
+ scopes: scopes2,
52377
+ target: opts.target?.trim() || void 0
52378
+ });
52379
+ if (!loginRes.ok || !loginRes.data) {
52380
+ return { kind: "unavailable", reason: loginFailureReason(loginRes) };
52381
+ }
52382
+ if (loginRes.data.status === "approval_required") {
52383
+ const requestId = loginRes.data.approval?.requestId ?? loginRes.data.requestId;
52384
+ if (!requestId) {
52385
+ return { kind: "unavailable", reason: "approval-required login response did not include a request id" };
52386
+ }
52387
+ return {
52388
+ kind: "approval_required",
52389
+ requestId,
52390
+ target: loginRes.data.approval?.target ?? null,
52391
+ actionCardMessageId: loginRes.data.approval?.actionCardMessageId ?? null
52392
+ };
52393
+ }
52394
+ if (!loginRes.data.requestId) {
52395
+ return { kind: "unavailable", reason: "agent login response did not include an internal one-time handoff request" };
52396
+ }
52397
+ const callbackHandoffUrl = buildAgentCallbackHandoffUrl(
52398
+ loginRes.data.service.returnUrl ?? service.returnUrl,
52399
+ loginRes.data.requestId
52400
+ );
52401
+ return callbackHandoffUrl ? { kind: "handoff_url", url: callbackHandoffUrl } : { kind: "unavailable", reason: "service return URL cannot be used for Agent Login callback handoff" };
52402
+ };
52403
+ const manifest = await fetchManifestForInvoke({ service, prepareUnsupportedAuthHandoff });
51928
52404
  if (manifest.execution.mode !== "http_api") {
51929
52405
  throw cliError("INTEGRATION_MANIFEST_UNSUPPORTED", "manifest execution mode is not http_api");
51930
52406
  }
@@ -51949,25 +52425,36 @@ var integrationInvokeCommand = defineCommand(
51949
52425
  const payload = parseActionPayload(opts);
51950
52426
  validateRequiredParams(action, payload);
51951
52427
  const scopes = normalizeScopes2(opts.scope);
51952
- const loginRes = await api.integrations.login({
51953
- service: service.clientId,
51954
- scopes,
51955
- target: opts.target?.trim() || void 0
51956
- });
51957
- if (!loginRes.ok || !loginRes.data) {
51958
- const code = loginRes.status >= 500 ? "SERVER_5XX" : "INTEGRATION_LOGIN_FAILED";
51959
- throw cliError(code, loginRes.error ?? `HTTP ${loginRes.status}`);
51960
- }
51961
- if (loginRes.data.status === "approval_required") {
51962
- throw cliError(
51963
- "INTEGRATION_APPROVAL_REQUIRED",
51964
- "human approval is required before invoking this integration action",
51965
- { suggestedNextAction: "Ask a server owner/admin to approve the integration login request, then rerun the command." }
51966
- );
52428
+ const storedSession = scopes || opts.target ? null : loadStoredIntegrationSession({ service, agentContext, env: cmdCtx.env });
52429
+ let cookies = storedSession?.cookies ?? null;
52430
+ if (!cookies) {
52431
+ const loginRes = await api.integrations.login({
52432
+ service: service.clientId,
52433
+ scopes,
52434
+ target: opts.target?.trim() || void 0
52435
+ });
52436
+ if (!loginRes.ok || !loginRes.data) {
52437
+ const code = loginRes.status >= 500 ? "SERVER_5XX" : "INTEGRATION_LOGIN_FAILED";
52438
+ throw cliError(code, loginRes.error ?? `HTTP ${loginRes.status}`);
52439
+ }
52440
+ if (loginRes.data.status === "approval_required") {
52441
+ throw cliError(
52442
+ "INTEGRATION_APPROVAL_REQUIRED",
52443
+ "human approval is required before invoking this integration action",
52444
+ { suggestedNextAction: "Ask a server owner/admin to approve the integration login request, then rerun the command." }
52445
+ );
52446
+ }
52447
+ const session = await ensureIntegrationServiceSession({
52448
+ login: loginRes.data,
52449
+ service,
52450
+ agentContext,
52451
+ env: cmdCtx.env,
52452
+ refresh: true
52453
+ });
52454
+ cookies = session.cookies;
51967
52455
  }
51968
- const cookies = await establishServiceSession({ login: loginRes.data, service });
51969
52456
  const url2 = resolveActionUrl({ service, manifest, action });
51970
- const result2 = await invokeHttpAction({ url: url2, action, payload, cookies });
52457
+ const result2 = await invokeHttpAction({ url: url2, action, payload, cookies, service });
51971
52458
  if (opts.json) {
51972
52459
  writeJson(cmdCtx.io, {
51973
52460
  ok: true,
@@ -52194,6 +52681,18 @@ function formatReminderType(r) {
52194
52681
  return `(recurring \xB7 ${r.recurrence.description})`;
52195
52682
  }
52196
52683
  function buildScheduleBody(opts, now = () => Intl.DateTimeFormat().resolvedOptions().timeZone) {
52684
+ const canonicalMessageId = opts.messageId?.trim();
52685
+ const legacyMsgId = opts.msgId?.trim();
52686
+ if (canonicalMessageId && legacyMsgId && canonicalMessageId !== legacyMsgId) {
52687
+ return {
52688
+ body: {},
52689
+ error: {
52690
+ code: "INVALID_ARG",
52691
+ message: "Pass only one message anchor; --msg-id is a deprecated alias for --message-id"
52692
+ }
52693
+ };
52694
+ }
52695
+ const msgId = canonicalMessageId || legacyMsgId || void 0;
52197
52696
  if (!opts.delaySeconds && !opts.fireAt && !opts.repeat) {
52198
52697
  return {
52199
52698
  body: {},
@@ -52209,7 +52708,7 @@ function buildScheduleBody(opts, now = () => Intl.DateTimeFormat().resolvedOptio
52209
52708
  }
52210
52709
  };
52211
52710
  }
52212
- const body = { title: opts.title, msgId: opts.msgId ?? null };
52711
+ const body = { title: opts.title, msgId: msgId ?? null };
52213
52712
  if (opts.delaySeconds !== void 0) {
52214
52713
  const n = Number(opts.delaySeconds);
52215
52714
  if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
@@ -52234,7 +52733,7 @@ function buildScheduleBody(opts, now = () => Intl.DateTimeFormat().resolvedOptio
52234
52733
  body: {},
52235
52734
  error: {
52236
52735
  code: "INVALID_ARG",
52237
- message: "Reminder create requires an anchor msgId; resolve a message first and pass --msg-id"
52736
+ message: "Reminder create requires an anchor msgId; resolve a message first and pass --message-id"
52238
52737
  }
52239
52738
  };
52240
52739
  }
@@ -52250,7 +52749,8 @@ var reminderScheduleCommand = defineCommand(
52250
52749
  { flags: "--fire-at <iso>", description: "ISO-8601 UTC timestamp, e.g. 2026-04-21T09:00:00Z. Use only for absolute calendar times" },
52251
52750
  { flags: "--repeat <rule>", description: "Recurrence rule: every:15m | every:2h | every:1d | daily@09:00 | weekly:mon,fri@09:00" },
52252
52751
  { flags: "--channel <ref>", description: "Optional channel to post a receipt message in (e.g. #general, dm:@alice)." },
52253
- { flags: "--msg-id <id>", description: "Message id this reminder is anchored to. Required for agent-created reminders." }
52752
+ { flags: "--message-id <id>", description: "Message id (full or short) this reminder is anchored to. Required for agent-created reminders." },
52753
+ { flags: "--msg-id <id>", description: "Deprecated alias for --message-id." }
52254
52754
  ]
52255
52755
  },
52256
52756
  async (ctx, opts) => {
@@ -52504,20 +53004,12 @@ var reminderLogCommand = defineCommand(
52504
53004
  function registerReminderLogCommand(parent, runtimeOptions = {}) {
52505
53005
  registerCliCommand(parent, reminderLogCommand, runtimeOptions);
52506
53006
  }
52507
- function resolveCliInvocationName(argv1) {
52508
- if (process.env.SLOCK_CLI_INVOCATION_NAME === "raft") {
52509
- return "raft";
52510
- }
52511
- const basename3 = argv1?.split(/[\\/]/).pop() ?? "";
52512
- return basename3 === "raft" ? "raft" : "slock";
52513
- }
52514
53007
  var program2 = new Command();
52515
- var cliName = resolveCliInvocationName(process.argv[1]);
52516
- program2.name(cliName).description(
52517
- "Agent-facing CLI for Slock. Two entry shapes: (A) external agent via `raft agent login --profile-slug <slug>` to create a profile, then `raft --profile <slug>` (or RAFT_PROFILE=<slug>) to use it; (B) daemon-injected runner, where the local `slock` wrapper sets the SLOCK_AGENT_* env vars for you."
53008
+ program2.name("raft").description(
53009
+ "Agent-facing CLI for Raft. Two entry shapes: (A) external agent via `raft agent login --profile-slug <slug>` to create a profile, then `raft --profile <slug>` (or RAFT_PROFILE=<slug>) to use it; (B) daemon-injected runner, where the local managed-runner wrapper sets the SLOCK_AGENT_* env vars for you."
52518
53010
  ).option(
52519
53011
  "-p, --profile <slug>",
52520
- "Use the credential at $SLOCK_HOME/profiles/<slug>/credential.json (or ~/.slock/profiles/<slug>/credential.json when SLOCK_HOME is unset). Equivalent to setting RAFT_PROFILE=<slug>. To create a new profile, use `raft agent login --profile-slug <slug>`."
53012
+ "Use an existing local profile credential. Equivalent to setting RAFT_PROFILE=<slug>. To create a new profile, use `raft agent login --profile-slug <slug>`."
52521
53013
  ).version(readCliVersion());
52522
53014
  program2.hook("preAction", () => {
52523
53015
  const opts = program2.opts();
@@ -52527,7 +53019,7 @@ program2.hook("preAction", () => {
52527
53019
  });
52528
53020
  var authCmd = program2.command("auth").description("Auth introspection");
52529
53021
  registerWhoamiCommand(authCmd);
52530
- var agentCmd = program2.command("agent").description("External agent onboarding (device-code login \u2192 sk_agent_* mint \u2192 ~/.slock/profiles/<slug>/credential.json)");
53022
+ var agentCmd = program2.command("agent").description("External agent onboarding (device-code login \u2192 sk_agent_* mint \u2192 local profile credential)");
52531
53023
  registerAgentLoginCommand(agentCmd);
52532
53024
  registerAgentListCommand(agentCmd);
52533
53025
  registerAgentBridgeCommand(agentCmd);
@@ -52546,7 +53038,7 @@ registerThreadUnfollowCommand(threadCmd);
52546
53038
  var serverCmd = program2.command("server").description("Server / workspace introspection");
52547
53039
  registerServerInfoCommand(serverCmd);
52548
53040
  registerServerUpdateCommand(serverCmd);
52549
- var manualCmd = program2.command("manual").description("Slock Manual for Agents retrieval (canonical operating topics)");
53041
+ var manualCmd = program2.command("manual").description("Raft Manual for Agents retrieval (canonical operating topics)");
52550
53042
  registerKnowledgeGetCommand(manualCmd);
52551
53043
  var knowledgeCmd = program2.command("knowledge").description("Legacy alias for `raft manual`");
52552
53044
  registerKnowledgeGetCommand(knowledgeCmd);