@conveno/cli 0.2.0-rc.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +3 -5
  2. package/dist/{acp-BVk6rmXR.js → acp-BUddItzP.js} +39 -7
  3. package/dist/{agy-relay-D8eZcLuc.js → agy-relay-BZ3d_-FS.js} +4 -2
  4. package/dist/{args-B3Cj2Ie4.js → args-CtyKPZuN.js} +29 -8
  5. package/dist/bin.js +16 -2
  6. package/dist/daemon.js +4 -3139
  7. package/dist/{daemonError-C05GqdhQ.js → daemonError-CDgEtvy7.js} +1 -1
  8. package/dist/dist-BNhTPp5p.js +4509 -0
  9. package/dist/{dist-BRjg9CLd.js → dist-BOwFdixw.js} +23 -50
  10. package/dist/{dist-DaIpdMke.js → dist-CFsDqevs.js} +51 -9
  11. package/dist/dist-CNdqmI3E.js +1065 -0
  12. package/dist/{dist-STNJjbNH.js → dist-CSSvrcKr.js} +1516 -599
  13. package/dist/{dist-BjdBeCHy.js → dist-D6Xoip5W.js} +63 -17
  14. package/dist/{dist-D_O_JLLq.js → dist-DAVtixeC.js} +19 -5
  15. package/dist/{dist-MK-cK1JY.js → dist-DTMnNySx.js} +39 -19
  16. package/dist/{hook-CDF1A8AY.js → hook-BA-tI6Oc.js} +101 -7
  17. package/dist/hook-entry-BwzBtAnd.js +1346 -0
  18. package/dist/hook-entry-Cgt5ZH1s.js +1 -0
  19. package/dist/{main-Kv31Qxro.js → main-kKnLA7Hj.js} +58 -21
  20. package/dist/{pick-DLp6w_-z.js → pick-BsMvXuDo.js} +1 -1
  21. package/dist/run-PQBzaHv1.js +8193 -0
  22. package/dist/{runtime-xjPzIGmp.js → runtime-0FMqklYn.js} +171 -119
  23. package/dist/{uninstall-8AHErPRN.js → uninstall-DcxkIDpk.js} +356 -56
  24. package/dist/{watch-D0KIPowJ.js → watch-BIepRTXJ.js} +29 -7
  25. package/package.json +14 -15
  26. package/dist/dist-CVdpCNJo.js +0 -793
  27. package/dist/dist-DzpERiRx.js +0 -624
  28. package/dist/hook-entry-BTJK7aO0.js +0 -2500
  29. package/dist/hook-entry-D6zup0QV.js +0 -1
  30. package/dist/run-BPtFUGtu.js +0 -5609
@@ -1,133 +1,10 @@
1
- import { homedir, tmpdir } from "node:os";
1
+ import { homedir, tmpdir, userInfo } from "node:os";
2
2
  import { dirname, join, posix, win32 } from "node:path";
3
- import { execFile, spawn, spawnSync } from "node:child_process";
4
- import { accessSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
5
- import { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
4
+ import { accessSync, appendFileSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
6
6
  import crypto, { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
7
7
  import { applyEdits, findNodeAtLocation, modify, parse as parse$1, parseTree, printParseErrorCode } from "jsonc-parser";
8
- // ../../node_modules/.pnpm/ulid@3.0.2/node_modules/ulid/dist/node/index.js
9
- const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
10
- const ENCODING_LEN = 32;
11
- const RANDOM_LEN = 16;
12
- const TIME_MAX = 0xffffffffffff;
13
- var ULIDErrorCode;
14
- (function(ULIDErrorCode) {
15
- ULIDErrorCode["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
16
- ULIDErrorCode["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
17
- ULIDErrorCode["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
18
- ULIDErrorCode["EncodeTimeNegative"] = "ENC_TIME_NEG";
19
- ULIDErrorCode["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
20
- ULIDErrorCode["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
21
- ULIDErrorCode["PRNGDetectFailure"] = "PRNG_DETECT";
22
- ULIDErrorCode["ULIDInvalid"] = "ULID_INVALID";
23
- ULIDErrorCode["Unexpected"] = "UNEXPECTED";
24
- ULIDErrorCode["UUIDInvalid"] = "UUID_INVALID";
25
- })(ULIDErrorCode || (ULIDErrorCode = {}));
26
- var ULIDError = class extends Error {
27
- constructor(errorCode, message) {
28
- super(`${message} (${errorCode})`);
29
- this.name = "ULIDError";
30
- this.code = errorCode;
31
- }
32
- };
33
- function randomChar(prng) {
34
- const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
35
- return ENCODING.charAt(randomPosition);
36
- }
37
- function replaceCharAt(str, index, char) {
38
- if (index > str.length - 1) return str;
39
- return str.substr(0, index) + char + str.substr(index + 1);
40
- }
41
- function incrementBase32(str) {
42
- let done = void 0, index = str.length, char, charIndex, output = str;
43
- const maxCharIndex = 31;
44
- while (!done && index-- >= 0) {
45
- char = output[index];
46
- charIndex = ENCODING.indexOf(char);
47
- if (charIndex === -1) throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
48
- if (charIndex === maxCharIndex) {
49
- output = replaceCharAt(output, index, ENCODING[0]);
50
- continue;
51
- }
52
- done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
53
- }
54
- if (typeof done === "string") return done;
55
- throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
56
- }
57
- /**
58
- * Detect the best PRNG (pseudo-random number generator)
59
- * @param root The root to check from (global/window)
60
- * @returns The PRNG function
61
- */
62
- function detectPRNG(root) {
63
- const rootLookup = detectRoot();
64
- const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof crypto !== "undefined" ? crypto : null);
65
- if (typeof globalCrypto?.getRandomValues === "function") return () => {
66
- const buffer = /* @__PURE__ */ new Uint8Array(1);
67
- globalCrypto.getRandomValues(buffer);
68
- return buffer[0] / 256;
69
- };
70
- else if (typeof globalCrypto?.randomBytes === "function") return () => globalCrypto.randomBytes(1).readUInt8() / 256;
71
- else if (crypto?.randomBytes) return () => crypto.randomBytes(1).readUInt8() / 256;
72
- throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
73
- }
74
- function detectRoot() {
75
- if (inWebWorker()) return self;
76
- if (typeof window !== "undefined") return window;
77
- if (typeof global !== "undefined") return global;
78
- if (typeof globalThis !== "undefined") return globalThis;
79
- return null;
80
- }
81
- function encodeRandom(len, prng) {
82
- let str = "";
83
- for (; len > 0; len--) str = randomChar(prng) + str;
84
- return str;
85
- }
86
- /**
87
- * Encode the time portion of a ULID
88
- * @param now The current timestamp
89
- * @param len Length to generate
90
- * @returns The encoded time
91
- */
92
- function encodeTime(now, len = 10) {
93
- if (isNaN(now)) throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
94
- else if (now > 0xffffffffffff) throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
95
- else if (now < 0) throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
96
- else if (Number.isInteger(now) === false) throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
97
- let mod, str = "";
98
- for (let currentLen = len; currentLen > 0; currentLen--) {
99
- mod = now % ENCODING_LEN;
100
- str = ENCODING.charAt(mod) + str;
101
- now = (now - mod) / ENCODING_LEN;
102
- }
103
- return str;
104
- }
105
- function inWebWorker() {
106
- return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
107
- }
108
- /**
109
- * Create a ULID factory to generate monotonically-increasing
110
- * ULIDs
111
- * @param prng The PRNG to use
112
- * @returns A ulid factory
113
- * @example
114
- * const ulid = monotonicFactory();
115
- * ulid(); // "01HNZXD07M5CEN5XA66EMZSRZW"
116
- */
117
- function monotonicFactory(prng) {
118
- const currentPRNG = prng || detectPRNG();
119
- let lastTime = 0, lastRandom;
120
- return function _ulid(seedTime) {
121
- const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
122
- if (seed <= lastTime) {
123
- const incrementedRandom = lastRandom = incrementBase32(lastRandom);
124
- return encodeTime(lastTime, 10) + incrementedRandom;
125
- }
126
- lastTime = seed;
127
- const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
128
- return encodeTime(seed, 10) + newRandom;
129
- };
130
- }
131
8
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
132
9
  function getEnumValues(entries) {
133
10
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
@@ -5690,76 +5567,328 @@ function superRefine(fn, params) {
5690
5567
  function datetime(params) {
5691
5568
  return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
5692
5569
  }
5693
- // ../protocol/dist/index.js
5694
- const encoder = new TextEncoder();
5695
- /** Number of bytes `s` occupies when encoded as UTF-8. */
5696
- function utf8ByteLength(s) {
5697
- return encoder.encode(s).length;
5698
- }
5570
+ // ../protocol/dist/account-api.js
5699
5571
  /**
5700
- * Make free text safe for a one-line display: control characters (newlines and tabs included)
5701
- * become spaces, runs of whitespace collapse to one space, and the ends are trimmed.
5572
+ * The HTTP contract between the open client (`@conveno/core`, `conveno login`) and the account
5573
+ * server (api.conveno.dev). PROTOCOL.md section 8 describes it; the JSON files under
5574
+ * `fixtures/account-api/` pin it. The client replays every fixture through its own code, and the
5575
+ * account server's tests check that the real Worker answers the same way.
5576
+ *
5577
+ * Response schemas are lenient (unknown fields are ignored) so a newer server does not break an
5578
+ * older client. The server-side tests additionally refuse fields a schema does not list.
5702
5579
  */
5703
- function sanitizeLine(s) {
5704
- return s.replace(/[\p{Cc}\u2028\u2029]/gu, " ").replace(/\s+/g, " ").trim();
5580
+ /** The `client_id` of the device authorization grant. The server accepts only this one. */
5581
+ const ACCOUNT_DEVICE_CLIENT_ID = "conveno-cli";
5582
+ /** The `grant_type` of a device token poll (RFC 8628 section 3.4). */
5583
+ const DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
5584
+ /** The `aud` claim of every access token. */
5585
+ const ACCESS_TOKEN_AUDIENCE = "conveno";
5586
+ const AccountPlan = _enum(["free", "pro"]);
5587
+ /** A relay device id: a ULID. */
5588
+ const DeviceIdString = string().regex(/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/);
5589
+ /** The claims of an access token. No email, no name: nothing else is ever present. */
5590
+ const AccessTokenClaims = object({
5591
+ /** The user id, an opaque string: the account id. */
5592
+ sub: string().min(1),
5593
+ plan: AccountPlan,
5594
+ /** The relay device id the login is bound to. Absent before `POST /api/device/bind`. */
5595
+ did: DeviceIdString.optional(),
5596
+ /** The account's relay epoch: how many times the owner reset the devices. */
5597
+ rep: number().int().nonnegative(),
5598
+ /** Seconds since the epoch. */
5599
+ iat: number().int(),
5600
+ /** `iat` plus 15 minutes. */
5601
+ exp: number().int(),
5602
+ iss: string().min(1),
5603
+ aud: literal(ACCESS_TOKEN_AUDIENCE)
5604
+ });
5605
+ /** The error body of the account server's own routes. */
5606
+ const ApiError = object({ error: string().min(1) });
5607
+ /** The error body of the Better Auth routes (`/api/auth/token`, `/api/auth/sign-out`). */
5608
+ const BetterAuthError = object({
5609
+ message: string().min(1),
5610
+ code: string().optional()
5611
+ });
5612
+ const AuthTokenResponse = object({ token: string().min(1) });
5613
+ object({ deviceId: string() });
5614
+ const DeviceBindResponse = object({
5615
+ ok: literal(true),
5616
+ deviceId: DeviceIdString
5617
+ });
5618
+ const AccountMeResponse = object({
5619
+ user: object({
5620
+ id: string(),
5621
+ name: string()
5622
+ }),
5623
+ plan: AccountPlan,
5624
+ /** Stripe's subscription status, or null when the user never subscribed. */
5625
+ status: string().nullable(),
5626
+ /** Unix seconds, set while a trial runs. */
5627
+ trialEnd: number().nullable(),
5628
+ trialDaysLeft: number().nullable(),
5629
+ currentPeriodEnd: number().nullable(),
5630
+ cancelAtPeriodEnd: boolean(),
5631
+ paymentFailed: boolean()
5632
+ });
5633
+ object({ client_id: string() });
5634
+ const DeviceCodeResponse = object({
5635
+ device_code: string().min(1),
5636
+ user_code: string().min(1),
5637
+ verification_uri: string().min(1),
5638
+ verification_uri_complete: string().optional(),
5639
+ /** Seconds between polls. */
5640
+ interval: number().optional(),
5641
+ /** Seconds until the code stops working. */
5642
+ expires_in: number().optional()
5643
+ });
5644
+ object({
5645
+ grant_type: literal(DEVICE_GRANT_TYPE),
5646
+ device_code: string(),
5647
+ client_id: string()
5648
+ });
5649
+ /** `access_token` is the session token, which the client keeps as its refresh token. */
5650
+ const DeviceTokenSuccess = object({
5651
+ access_token: string().min(1),
5652
+ token_type: string().optional(),
5653
+ expires_in: number().optional(),
5654
+ scope: string().optional()
5655
+ });
5656
+ const DeviceTokenError = object({
5657
+ /** RFC 8628 section 3.5. A client treats a code it does not know as a server failure. */
5658
+ error: string().min(1),
5659
+ error_description: string().optional()
5660
+ });
5661
+ const ACCOUNT_API_SCHEMA_NAMES = Object.keys({
5662
+ AccessTokenClaims,
5663
+ AccountMeResponse,
5664
+ ApiError,
5665
+ AuthTokenResponse,
5666
+ BetterAuthError,
5667
+ DeviceBindResponse,
5668
+ DeviceCodeResponse,
5669
+ DeviceTokenError,
5670
+ DeviceTokenSuccess
5671
+ });
5672
+ /**
5673
+ * One request and the answer the account server gives. `setup` names the server state the case
5674
+ * needs (the account server's tests build it); the client ignores it. `schema` is the
5675
+ * {@link accountApiSchemas} entry the response body satisfies. `exact` means the body is
5676
+ * deterministic, so a server must answer it verbatim. Headers may use `{{refreshToken}}`.
5677
+ */
5678
+ const AccountFixtureCase = object({
5679
+ name: string().min(1),
5680
+ description: string().min(1),
5681
+ setup: string().min(1),
5682
+ request: object({
5683
+ method: _enum(["GET", "POST"]),
5684
+ path: string().startsWith("/"),
5685
+ headers: record(string(), string()).optional(),
5686
+ body: unknown().optional()
5687
+ }),
5688
+ response: object({
5689
+ status: number().int(),
5690
+ schema: _enum(ACCOUNT_API_SCHEMA_NAMES),
5691
+ exact: boolean().optional(),
5692
+ body: unknown()
5693
+ })
5694
+ });
5695
+ object({
5696
+ endpoint: string().min(1),
5697
+ cases: array(AccountFixtureCase).min(1)
5698
+ });
5699
+ // ../../node_modules/.pnpm/ulid@3.0.2/node_modules/ulid/dist/node/index.js
5700
+ const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
5701
+ const ENCODING_LEN = 32;
5702
+ const RANDOM_LEN = 16;
5703
+ const TIME_MAX = 0xffffffffffff;
5704
+ var ULIDErrorCode;
5705
+ (function(ULIDErrorCode) {
5706
+ ULIDErrorCode["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
5707
+ ULIDErrorCode["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
5708
+ ULIDErrorCode["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
5709
+ ULIDErrorCode["EncodeTimeNegative"] = "ENC_TIME_NEG";
5710
+ ULIDErrorCode["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
5711
+ ULIDErrorCode["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
5712
+ ULIDErrorCode["PRNGDetectFailure"] = "PRNG_DETECT";
5713
+ ULIDErrorCode["ULIDInvalid"] = "ULID_INVALID";
5714
+ ULIDErrorCode["Unexpected"] = "UNEXPECTED";
5715
+ ULIDErrorCode["UUIDInvalid"] = "UUID_INVALID";
5716
+ })(ULIDErrorCode || (ULIDErrorCode = {}));
5717
+ var ULIDError = class extends Error {
5718
+ constructor(errorCode, message) {
5719
+ super(`${message} (${errorCode})`);
5720
+ this.name = "ULIDError";
5721
+ this.code = errorCode;
5722
+ }
5723
+ };
5724
+ function randomChar(prng) {
5725
+ const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
5726
+ return ENCODING.charAt(randomPosition);
5705
5727
  }
5706
- /** Maximum size of one NDJSON line, excluding the terminating newline. */
5707
- const MAX_LINE_BYTES = 1048576;
5708
- /** Serialise `obj` as one NDJSON line (JSON + `\n`). Throws if the line would exceed `maxLineBytes`. */
5709
- function encodeFrame(obj, maxLineBytes = MAX_LINE_BYTES) {
5710
- const json = JSON.stringify(obj);
5711
- if (json === void 0) throw new TypeError("value is not JSON-serialisable");
5712
- if (utf8ByteLength(json) > maxLineBytes) throw new RangeError(`frame exceeds ${maxLineBytes} bytes`);
5713
- return `${json}\n`;
5728
+ function replaceCharAt(str, index, char) {
5729
+ if (index > str.length - 1) return str;
5730
+ return str.substr(0, index) + char + str.substr(index + 1);
5731
+ }
5732
+ function incrementBase32(str) {
5733
+ let done = void 0, index = str.length, char, charIndex, output = str;
5734
+ const maxCharIndex = 31;
5735
+ while (!done && index-- >= 0) {
5736
+ char = output[index];
5737
+ charIndex = ENCODING.indexOf(char);
5738
+ if (charIndex === -1) throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
5739
+ if (charIndex === maxCharIndex) {
5740
+ output = replaceCharAt(output, index, ENCODING[0]);
5741
+ continue;
5742
+ }
5743
+ done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
5744
+ }
5745
+ if (typeof done === "string") return done;
5746
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
5714
5747
  }
5715
5748
  /**
5716
- * Incremental NDJSON decoder. Handles lines split across chunks (including mid-UTF-8-sequence),
5717
- * several lines in one chunk, CRLF, and blank lines (skipped). A line longer than `maxLineBytes`
5718
- * yields one `line_too_long` error; the rest of that line is discarded so decoding resyncs at the
5719
- * next newline. Malformed JSON yields `invalid_json` for that line only.
5749
+ * Detect the best PRNG (pseudo-random number generator)
5750
+ * @param root The root to check from (global/window)
5751
+ * @returns The PRNG function
5720
5752
  */
5721
- function createLineDecoder(maxLineBytes = MAX_LINE_BYTES) {
5722
- const utf8 = new TextDecoder("utf-8");
5723
- let pending = "";
5724
- let pendingBytes = 0;
5725
- let discarding = false;
5726
- const tooLong = () => ({
5727
- ok: false,
5728
- error: {
5729
- code: "line_too_long",
5730
- message: `line exceeds ${maxLineBytes} bytes`
5731
- }
5732
- });
5733
- const parseLine = (raw) => {
5734
- const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
5735
- if (line.trim() === "") return [];
5736
- try {
5737
- return [{
5738
- ok: true,
5739
- value: JSON.parse(line)
5740
- }];
5741
- } catch (e) {
5742
- return [{
5743
- ok: false,
5744
- error: {
5745
- code: "invalid_json",
5746
- message: e.message
5747
- }
5748
- }];
5749
- }
5753
+ function detectPRNG(root) {
5754
+ const rootLookup = detectRoot();
5755
+ const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof crypto !== "undefined" ? crypto : null);
5756
+ if (typeof globalCrypto?.getRandomValues === "function") return () => {
5757
+ const buffer = /* @__PURE__ */ new Uint8Array(1);
5758
+ globalCrypto.getRandomValues(buffer);
5759
+ return buffer[0] / 256;
5750
5760
  };
5751
- const decode = (chunk, last) => typeof chunk === "string" ? chunk : utf8.decode(chunk, { stream: !last });
5752
- const consume = (text) => {
5753
- const out = [];
5754
- let start = 0;
5755
- for (;;) {
5756
- const nl = text.indexOf("\n", start);
5757
- if (nl === -1) break;
5758
- const segment = text.slice(start, nl);
5759
- start = nl + 1;
5760
- if (discarding) discarding = false;
5761
- else if (pendingBytes + utf8ByteLength(segment) > maxLineBytes) out.push(tooLong());
5762
- else out.push(...parseLine(pending + segment));
5761
+ else if (typeof globalCrypto?.randomBytes === "function") return () => globalCrypto.randomBytes(1).readUInt8() / 256;
5762
+ else if (crypto?.randomBytes) return () => crypto.randomBytes(1).readUInt8() / 256;
5763
+ throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
5764
+ }
5765
+ function detectRoot() {
5766
+ if (inWebWorker()) return self;
5767
+ if (typeof window !== "undefined") return window;
5768
+ if (typeof global !== "undefined") return global;
5769
+ if (typeof globalThis !== "undefined") return globalThis;
5770
+ return null;
5771
+ }
5772
+ function encodeRandom(len, prng) {
5773
+ let str = "";
5774
+ for (; len > 0; len--) str = randomChar(prng) + str;
5775
+ return str;
5776
+ }
5777
+ /**
5778
+ * Encode the time portion of a ULID
5779
+ * @param now The current timestamp
5780
+ * @param len Length to generate
5781
+ * @returns The encoded time
5782
+ */
5783
+ function encodeTime(now, len = 10) {
5784
+ if (isNaN(now)) throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
5785
+ else if (now > 0xffffffffffff) throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
5786
+ else if (now < 0) throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
5787
+ else if (Number.isInteger(now) === false) throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
5788
+ let mod, str = "";
5789
+ for (let currentLen = len; currentLen > 0; currentLen--) {
5790
+ mod = now % ENCODING_LEN;
5791
+ str = ENCODING.charAt(mod) + str;
5792
+ now = (now - mod) / ENCODING_LEN;
5793
+ }
5794
+ return str;
5795
+ }
5796
+ function inWebWorker() {
5797
+ return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
5798
+ }
5799
+ /**
5800
+ * Create a ULID factory to generate monotonically-increasing
5801
+ * ULIDs
5802
+ * @param prng The PRNG to use
5803
+ * @returns A ulid factory
5804
+ * @example
5805
+ * const ulid = monotonicFactory();
5806
+ * ulid(); // "01HNZXD07M5CEN5XA66EMZSRZW"
5807
+ */
5808
+ function monotonicFactory(prng) {
5809
+ const currentPRNG = prng || detectPRNG();
5810
+ let lastTime = 0, lastRandom;
5811
+ return function _ulid(seedTime) {
5812
+ const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
5813
+ if (seed <= lastTime) {
5814
+ const incrementedRandom = lastRandom = incrementBase32(lastRandom);
5815
+ return encodeTime(lastTime, 10) + incrementedRandom;
5816
+ }
5817
+ lastTime = seed;
5818
+ const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
5819
+ return encodeTime(seed, 10) + newRandom;
5820
+ };
5821
+ }
5822
+ // ../protocol/dist/index.js
5823
+ const encoder = new TextEncoder();
5824
+ /** Number of bytes `s` occupies when encoded as UTF-8. */
5825
+ function utf8ByteLength(s) {
5826
+ return encoder.encode(s).length;
5827
+ }
5828
+ /**
5829
+ * Make free text safe for a one-line display: control characters (newlines and tabs included)
5830
+ * become spaces, runs of whitespace collapse to one space, and the ends are trimmed.
5831
+ */
5832
+ function sanitizeLine(s) {
5833
+ return s.replace(/[\p{Cc}\u2028\u2029]/gu, " ").replace(/\s+/g, " ").trim();
5834
+ }
5835
+ /** Maximum size of one NDJSON line, excluding the terminating newline. */
5836
+ const MAX_LINE_BYTES = 1048576;
5837
+ /** Serialise `obj` as one NDJSON line (JSON + `\n`). Throws if the line would exceed `maxLineBytes`. */
5838
+ function encodeFrame(obj, maxLineBytes = MAX_LINE_BYTES) {
5839
+ const json = JSON.stringify(obj);
5840
+ if (json === void 0) throw new TypeError("value is not JSON-serialisable");
5841
+ if (utf8ByteLength(json) > maxLineBytes) throw new RangeError(`frame exceeds ${maxLineBytes} bytes`);
5842
+ return `${json}\n`;
5843
+ }
5844
+ /**
5845
+ * Incremental NDJSON decoder. Handles lines split across chunks (including mid-UTF-8-sequence),
5846
+ * several lines in one chunk, CRLF, and blank lines (skipped). A line longer than `maxLineBytes`
5847
+ * yields one `line_too_long` error; the rest of that line is discarded so decoding resyncs at the
5848
+ * next newline. Malformed JSON yields `invalid_json` for that line only.
5849
+ */
5850
+ function createLineDecoder(maxLineBytes = MAX_LINE_BYTES) {
5851
+ const utf8 = new TextDecoder("utf-8");
5852
+ let pending = "";
5853
+ let pendingBytes = 0;
5854
+ let discarding = false;
5855
+ const tooLong = () => ({
5856
+ ok: false,
5857
+ error: {
5858
+ code: "line_too_long",
5859
+ message: `line exceeds ${maxLineBytes} bytes`
5860
+ }
5861
+ });
5862
+ const parseLine = (raw) => {
5863
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
5864
+ if (line.trim() === "") return [];
5865
+ try {
5866
+ return [{
5867
+ ok: true,
5868
+ value: JSON.parse(line)
5869
+ }];
5870
+ } catch (e) {
5871
+ return [{
5872
+ ok: false,
5873
+ error: {
5874
+ code: "invalid_json",
5875
+ message: e.message
5876
+ }
5877
+ }];
5878
+ }
5879
+ };
5880
+ const decode = (chunk, last) => typeof chunk === "string" ? chunk : utf8.decode(chunk, { stream: !last });
5881
+ const consume = (text) => {
5882
+ const out = [];
5883
+ let start = 0;
5884
+ for (;;) {
5885
+ const nl = text.indexOf("\n", start);
5886
+ if (nl === -1) break;
5887
+ const segment = text.slice(start, nl);
5888
+ start = nl + 1;
5889
+ if (discarding) discarding = false;
5890
+ else if (pendingBytes + utf8ByteLength(segment) > maxLineBytes) out.push(tooLong());
5891
+ else out.push(...parseLine(pending + segment));
5763
5892
  pending = "";
5764
5893
  pendingBytes = 0;
5765
5894
  }
@@ -5816,8 +5945,6 @@ const CLI_KINDS = [
5816
5945
  "claude",
5817
5946
  "codex",
5818
5947
  "antigravity",
5819
- "cursor",
5820
- "copilot",
5821
5948
  "opencode",
5822
5949
  "grok"
5823
5950
  ];
@@ -5939,7 +6066,8 @@ const RelayState = _enum([
5939
6066
  "connecting",
5940
6067
  "connected",
5941
6068
  "disconnected",
5942
- "revoked"
6069
+ "revoked",
6070
+ "upgrade_required"
5943
6071
  ]);
5944
6072
  const DeviceName = string().min(1).max(64);
5945
6073
  const Fingerprint = string().min(1).max(64);
@@ -6160,12 +6288,21 @@ const RepoInfo = object({
6160
6288
  /** SHA-256 of the normalised `origin` URL; lets sessions on different machines match repos without exposing the URL. */
6161
6289
  remoteUrlHash: Sha256Hex.optional()
6162
6290
  });
6291
+ /**
6292
+ * A client of a CLI that is not the CLI itself: `app` is the Antigravity desktop app, which shares
6293
+ * agy's settings and so loads Conveno the same way.
6294
+ */
6295
+ const SessionVariant = literal("app");
6163
6296
  const Session = object({
6164
6297
  id: SessionId,
6165
6298
  /** `<device>:<name>` for a session on another device (`remote`). */
6166
6299
  name: union([SessionName, RemoteSessionName]),
6167
6300
  cli: CliKind,
6168
6301
  cliVersion: string().min(1).max(64).optional(),
6302
+ /** The model and effort a background worker runs on (`sonnet · high`), when known. Not stored. */
6303
+ model: string().min(1).max(200).optional(),
6304
+ /** Set when the session is a desktop app of `cli` rather than the CLI. Screens say "Antigravity app". */
6305
+ variant: SessionVariant.optional(),
6169
6306
  deviceId: DeviceId,
6170
6307
  cwd: string().min(1),
6171
6308
  repo: RepoInfo.optional(),
@@ -6191,11 +6328,19 @@ const Session = object({
6191
6328
  unreadCount: number().int().min(0).optional(),
6192
6329
  startedAt: IsoTimestamp,
6193
6330
  lastSeenAt: IsoTimestamp,
6331
+ /** When the session last sent a message. Absent until it has sent one. */
6332
+ lastSentAt: IsoTimestamp.optional(),
6194
6333
  /**
6195
6334
  * The CLI's own id for this session (Codex's thread id), set by its hooks with
6196
6335
  * `session.setNative`. Hooks of a CLI that runs many sessions in one process find theirs by it.
6197
6336
  */
6198
6337
  nativeId: string().min(1).max(256).optional(),
6338
+ /**
6339
+ * Can something wake this session when it is idle right now (a connected listener, relay or
6340
+ * watcher, a daemon waker with a conversation to wake, or an ACP host)? False: a message waits
6341
+ * until the user's next prompt. Absent on a daemon or device that does not report it.
6342
+ */
6343
+ wakeable: boolean().optional(),
6199
6344
  /** Set on sessions of the owner's other devices, reached through the relay. */
6200
6345
  remote: literal(true).optional(),
6201
6346
  /** Display name of the device a remote session runs on. */
@@ -6203,6 +6348,8 @@ const Session = object({
6203
6348
  });
6204
6349
  /** Wire protocol identifier. Bumped only on breaking changes. */
6205
6350
  const PROTOCOL_VERSION = "conveno/1";
6351
+ /** What a device's daemon calls itself in a relay `hello` (`client.name`). */
6352
+ const RELAY_CLIENT_NAME = "conveno-cli";
6206
6353
  const ClientKind = _enum([
6207
6354
  "mcp",
6208
6355
  "cli",
@@ -6228,11 +6375,17 @@ const AuthParams = object({
6228
6375
  proof: Sha256Hex });
6229
6376
  const sid = { sessionId: SessionId };
6230
6377
  const SessionResult = object({ session: Session });
6378
+ /** An absolute path (POSIX, drive or UNC) without control characters. */
6379
+ const AbsolutePath = string().min(1).max(1024).regex(/^(?:[A-Za-z]:[\\/]|\\\\|\/)/, "must be an absolute path").regex(/^[^\u0000-\u001f\u007f]*$/, "must not contain control characters");
6231
6380
  const RegisterParams = object({
6232
6381
  /** Requested name. If omitted the daemon assigns one such as `claude@repo-1`. */
6233
6382
  name: SessionNameInput.optional(),
6234
6383
  cli: CliKind,
6235
6384
  cliVersion: string().min(1).max(64).optional(),
6385
+ /** The worker's model and effort as a short label (`sonnet · high`), shown on its card. */
6386
+ model: string().min(1).max(200).optional(),
6387
+ /** The session runs in a desktop app of `cli`. See `Session.variant`. */
6388
+ variant: SessionVariant.optional(),
6236
6389
  cwd: string().min(1),
6237
6390
  repo: RepoInfo.optional(),
6238
6391
  pid: number().int().positive().optional(),
@@ -6246,7 +6399,7 @@ const RegisterParams = object({
6246
6399
  spawned: boolean().default(false),
6247
6400
  /**
6248
6401
  * A `conveno acp-host` registers the session it drives over the Agent Client Protocol: the
6249
- * session's delivery tier is `acp`, and its host prompts it with waiting messages (section 6.8).
6402
+ * session's delivery tier is `acp`, and its host prompts it with waiting messages (section 5.8).
6250
6403
  */
6251
6404
  acp: boolean().default(false)
6252
6405
  });
@@ -6299,6 +6452,21 @@ const SendResult = object({
6299
6452
  name: union([SessionName, literal("you")])
6300
6453
  })
6301
6454
  });
6455
+ /** One message between two sessions, as `message.recent` lists it for the app's activity list. */
6456
+ const RecentMessage = object({
6457
+ id: MessageId,
6458
+ from: SessionId,
6459
+ /** The sender's name when it sent the message (`<device>:<name>` for another machine's). */
6460
+ fromName: string().max(200).optional(),
6461
+ fromCli: CliKind.optional(),
6462
+ /** The session that got it. */
6463
+ to: SessionId,
6464
+ toName: string().max(200),
6465
+ toCli: CliKind.optional(),
6466
+ /** The first line of the text (or a handoff's goal), one plain line, cut. */
6467
+ text: string().max(200),
6468
+ createdAt: IsoTimestamp
6469
+ });
6302
6470
  const EVENT_NAMES = [
6303
6471
  "message.received",
6304
6472
  "session.updated",
@@ -6344,6 +6512,8 @@ function makeEventNotification(payload) {
6344
6512
  params: payload
6345
6513
  };
6346
6514
  }
6515
+ /** In the NotFound message for a heartbeat of a retired session. The MCP server exits on it. */
6516
+ const SESSION_ENDED_TEXT = "has ended and will not come back";
6347
6517
  const ipcMethods = {
6348
6518
  hello: {
6349
6519
  params: HelloParams,
@@ -6358,11 +6528,22 @@ const ipcMethods = {
6358
6528
  result: SessionResult
6359
6529
  },
6360
6530
  "session.heartbeat": {
6361
- params: object(sid),
6531
+ params: object({
6532
+ ...sid,
6533
+ pid: number().int().positive().optional(),
6534
+ model: string().min(1).max(200).optional()
6535
+ }),
6362
6536
  result: object({ lastSeenAt: IsoTimestamp })
6363
6537
  },
6364
6538
  "session.unregister": {
6365
- params: object(sid),
6539
+ params: object({
6540
+ ...sid,
6541
+ pid: number().int().positive().optional()
6542
+ }),
6543
+ result: object({ ok: literal(true) })
6544
+ },
6545
+ "session.remove": {
6546
+ params: object({ ...sid }),
6366
6547
  result: object({ ok: literal(true) })
6367
6548
  },
6368
6549
  "session.rename": {
@@ -6396,6 +6577,36 @@ const ipcMethods = {
6396
6577
  }),
6397
6578
  result: SessionResult
6398
6579
  },
6580
+ "session.bind": {
6581
+ params: object({
6582
+ cli: CliKind,
6583
+ nativeId: string().min(1).max(256),
6584
+ sessionId: SessionId.optional(),
6585
+ /** The calling MCP process, attached to the surviving session on a merge. */
6586
+ pid: number().int().positive().optional(),
6587
+ hostPid: number().int().positive().optional(),
6588
+ /**
6589
+ * A hook's direct parent pid, in place of `hostPid`, so the hook skips the process walk
6590
+ * when the daemon can tell without it. The answer is a session, none, or `needsHost`: the
6591
+ * hook then walks and asks again with `hostPid`.
6592
+ */
6593
+ ppid: number().int().positive().optional(),
6594
+ cwd: string().min(1).optional(),
6595
+ turnStart: boolean().default(false)
6596
+ }).refine((p) => p.sessionId !== void 0 || p.hostPid !== void 0 || p.ppid !== void 0, { message: "provide sessionId, hostPid or ppid" }),
6597
+ result: object({
6598
+ session: Session.nullable(),
6599
+ needsHost: boolean().optional()
6600
+ })
6601
+ },
6602
+ "session.setCwd": {
6603
+ params: object({
6604
+ ...sid,
6605
+ cwd: AbsolutePath,
6606
+ variant: SessionVariant.optional()
6607
+ }),
6608
+ result: SessionResult
6609
+ },
6399
6610
  "session.hostOf": {
6400
6611
  params: object({
6401
6612
  cli: CliKind,
@@ -6426,6 +6637,11 @@ const ipcMethods = {
6426
6637
  ...sid,
6427
6638
  /** Chosen by the listener. The newest listener of a session wins; older ones are told to stop. */
6428
6639
  listenerId: string().regex(/^[A-Za-z0-9_-]{8,64}$/, "invalid listener id"),
6640
+ /**
6641
+ * The conversation this listener serves. When the session has moved to another one
6642
+ * (`session.bind`), the listener is superseded: it gets nothing and must stop.
6643
+ */
6644
+ nativeId: string().min(1).max(256).optional(),
6429
6645
  maxChars
6430
6646
  }),
6431
6647
  result: TurnDelivery.extend({ superseded: boolean() })
@@ -6439,12 +6655,52 @@ const ipcMethods = {
6439
6655
  result: object({ sessions: array(Session) })
6440
6656
  },
6441
6657
  "orchestrator.claim": {
6442
- params: object(sid),
6658
+ params: object({
6659
+ ...sid,
6660
+ via: _enum([
6661
+ "tool",
6662
+ "cli",
6663
+ "home"
6664
+ ]).optional()
6665
+ }),
6443
6666
  result: object({
6444
6667
  orchestrator: SessionId,
6445
6668
  previous: SessionId.nullable()
6446
6669
  })
6447
6670
  },
6671
+ "permission.ask": {
6672
+ params: object({
6673
+ ...sid,
6674
+ title: string().max(500).optional(),
6675
+ kind: string().max(100).optional(),
6676
+ timeoutMs: number().int().min(1).max(3e5),
6677
+ /** What happens when nobody answers, for the notice to the spawner. Default deny. */
6678
+ unanswered: _enum(["deny", "allow"]).optional()
6679
+ }),
6680
+ result: object({
6681
+ answer: _enum([
6682
+ "allow_once",
6683
+ "allow_always",
6684
+ "deny",
6685
+ "unanswered",
6686
+ "worker_offline",
6687
+ "no_spawner"
6688
+ ]),
6689
+ by: SessionId.optional()
6690
+ })
6691
+ },
6692
+ "permission.answer": {
6693
+ params: object({
6694
+ ...sid,
6695
+ requestId: string().min(1).max(64),
6696
+ answer: _enum([
6697
+ "allow_once",
6698
+ "allow_always",
6699
+ "deny"
6700
+ ])
6701
+ }),
6702
+ result: object({ ok: literal(true) })
6703
+ },
6448
6704
  "orchestrator.clear": {
6449
6705
  params: object({}),
6450
6706
  result: object({ previous: SessionId.nullable() })
@@ -6489,6 +6745,10 @@ const ipcMethods = {
6489
6745
  }),
6490
6746
  result: object({ acked: number().int().min(0) })
6491
6747
  },
6748
+ "message.recent": {
6749
+ params: object({ limit: number().int().min(1).max(200).default(50) }),
6750
+ result: object({ messages: array(RecentMessage) })
6751
+ },
6492
6752
  "owner.send": {
6493
6753
  params: object({
6494
6754
  to: Recipient,
@@ -6590,20 +6850,30 @@ const b64Bytes = (n) => {
6590
6850
  const RelayKey32 = b64Bytes(32);
6591
6851
  /** A 64-byte Ed25519 signature, base64. */
6592
6852
  const RelaySig = b64Bytes(64);
6853
+ /** Relay to device, first frame: a fresh nonce the device signs in `hello`. */
6854
+ const RelayChallenge = object({
6855
+ t: literal("challenge"),
6856
+ v,
6857
+ nonce: b64Bytes(32)
6858
+ });
6859
+ /** What sent a `hello`: the program and its version. Not signed; the relay only reads it. */
6860
+ const RelayClientInfo = object({
6861
+ name: string().min(1).max(64),
6862
+ version: string().min(1).max(64)
6863
+ });
6593
6864
  const RelayFrame = discriminatedUnion("t", [
6594
- object({
6595
- t: literal("challenge"),
6596
- v,
6597
- nonce: b64Bytes(32)
6598
- }),
6865
+ RelayChallenge,
6599
6866
  object({
6600
6867
  t: literal("hello"),
6601
6868
  v,
6602
6869
  deviceId: DeviceId,
6603
6870
  /** Ed25519 public key, base64. */
6604
6871
  signingKey: RelayKey32,
6605
- /** Ed25519 signature over the canonical hello bytes (PROTOCOL.md section 7.2). */
6606
- sig: RelaySig
6872
+ /** Ed25519 signature over the canonical hello bytes (PROTOCOL.md section 6.2). */
6873
+ sig: RelaySig,
6874
+ client: RelayClientInfo.optional(),
6875
+ /** Optional protocol features the device supports, for the relay to branch on later. */
6876
+ features: array(string().min(1).max(64)).max(32).optional()
6607
6877
  }),
6608
6878
  object({
6609
6879
  t: literal("ready"),
@@ -6652,7 +6922,9 @@ const RelayFrame = discriminatedUnion("t", [
6652
6922
  object({
6653
6923
  t: literal("error"),
6654
6924
  code: string().min(1).max(64),
6655
- message: string().max(1e3)
6925
+ message: string().max(1e3),
6926
+ /** With `upgrade_required`: the oldest client version the relay accepts. */
6927
+ minVersion: string().min(1).max(64).optional()
6656
6928
  })
6657
6929
  ]);
6658
6930
  /** A session as published to the owner's other devices. Process ids stay on their machine. */
@@ -6736,17 +7008,247 @@ function socketPathTooLongMessage(path, platform) {
6736
7008
  return `The Conveno socket path is too long for this system (${utf8ByteLength(path)} bytes, the limit is ${max}): ${path}. Set XDG_RUNTIME_DIR to a shorter directory and try again.`;
6737
7009
  }
6738
7010
  // ../core/dist/index.js
7011
+ const defaultIsFile = (path) => {
7012
+ try {
7013
+ return statSync(path).isFile();
7014
+ } catch {
7015
+ return false;
7016
+ }
7017
+ };
7018
+ /** Environment variable lookup that ignores case, as Windows does (`Path`, `PATH`, `PathExt`). */
7019
+ function envGet(env, name) {
7020
+ const want = name.toLowerCase();
7021
+ for (const [k, v] of Object.entries(env)) if (k.toLowerCase() === want && v !== void 0) return v;
7022
+ }
7023
+ const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
7024
+ /** Only these can be started safely: other PATHEXT entries (.JS, .VBS) open Windows Script Host. */
7025
+ const LAUNCHABLE = /* @__PURE__ */ new Set([
7026
+ ".com",
7027
+ ".exe",
7028
+ ".bat",
7029
+ ".cmd"
7030
+ ]);
6739
7031
  /**
6740
- * Conveno account tokens on this machine, and how to get and renew them.
6741
- *
6742
- * The account server (packages/account-web, api.conveno.dev) signs a short-lived access token, a
6743
- * JWT, and the CLI keeps it with a long-lived refresh token in `<data dir>/account.json`
6744
- * (mode 0600). The relay's client reads the access token with {@link currentAccessToken}.
6745
- * The contract is in packages/account-web/README.md and packages/protocol/PROTOCOL.md.
7032
+ * Find `command` the way cmd.exe does: each PATH directory in order, each PATHEXT extension in
7033
+ * order. A name that already ends in a launchable extension is tried as written first. Returns
7034
+ * undefined when nothing matches.
6746
7035
  */
6747
- const ACCOUNT_API = "https://api.conveno.dev";
7036
+ function resolveWindowsCommand(command, env, isFile = defaultIsFile) {
7037
+ const exts = (envGet(env, "PATHEXT") ?? DEFAULT_PATHEXT).split(";").map((e) => e.trim()).filter((e) => LAUNCHABLE.has(e.toLowerCase()));
7038
+ const own = win32.extname(command).toLowerCase();
7039
+ const candidatesIn = (base) => [...LAUNCHABLE.has(own) ? [base] : [], ...exts.map((e) => base + e)];
7040
+ const dirs = /[\\/]/.test(command) || win32.isAbsolute(command) ? [""] : (envGet(env, "PATH") ?? "").split(";").map((d) => d.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
7041
+ for (const dir of dirs) for (const candidate of candidatesIn(dir === "" ? command : win32.join(dir, command))) if (isFile(candidate)) return candidate;
7042
+ }
7043
+ /** Characters cmd.exe treats specially, plus the ones cross-spawn escapes defensively. */
7044
+ const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
7045
+ /** The program name part of a cmd.exe command line: escape only, never wrap in quotes. */
7046
+ function escapeCmdCommand(command) {
7047
+ return command.replace(CMD_META, "^$1");
7048
+ }
7049
+ /**
7050
+ * Quote one argument for a `cmd.exe /d /s /c "..."` command line, the way cross-spawn does:
7051
+ * make it safe for the program's own parser (backslashes before a quote are doubled, the quote
7052
+ * is backslash-escaped, the whole thing is wrapped in quotes), then caret-escape every
7053
+ * character cmd.exe would act on, including the quotes themselves.
7054
+ */
7055
+ function escapeCmdArg(arg) {
7056
+ let a = `${arg}`;
7057
+ a = a.replace(/(\\*)"/g, "$1$1\\\"");
7058
+ a = a.replace(/(\\*)$/, "$1$1");
7059
+ a = `"${a}"`;
7060
+ return a.replace(CMD_META, "^$1");
7061
+ }
7062
+ /** `cmd.exe /d /s /c "<command line>"` for a .cmd or .bat file. */
7063
+ function cmdShimPlan(file, args, env) {
7064
+ const line = [escapeCmdCommand(file), ...args.map(escapeCmdArg)].join(" ");
7065
+ return {
7066
+ file: envGet(env, "ComSpec") || "cmd.exe",
7067
+ args: [
7068
+ "/d",
7069
+ "/s",
7070
+ "/c",
7071
+ `"${line}"`
7072
+ ],
7073
+ windowsVerbatimArguments: true
7074
+ };
7075
+ }
7076
+ /**
7077
+ * What to spawn for `command args...`. On Windows the command is resolved on PATH: .exe and .com
7078
+ * run directly, .cmd and .bat (npm shims) go through cmd.exe with one quoted command line. Never
7079
+ * uses a shell option with an args array. Elsewhere, and when nothing is found, the command is
7080
+ * returned unchanged so the caller sees the normal ENOENT.
7081
+ */
7082
+ function planSpawn(command, args, opts = {}) {
7083
+ if ((opts.platform ?? process.platform) !== "win32") return {
7084
+ file: command,
7085
+ args
7086
+ };
7087
+ const env = opts.env ?? process.env;
7088
+ const found = resolveWindowsCommand(command, env, opts.isFile);
7089
+ if (!found) return {
7090
+ file: command,
7091
+ args
7092
+ };
7093
+ const ext = win32.extname(found).toLowerCase();
7094
+ if (ext === ".cmd" || ext === ".bat") return cmdShimPlan(found, args, env);
7095
+ return {
7096
+ file: found,
7097
+ args
7098
+ };
7099
+ }
7100
+ /**
7101
+ * Files only the current user may read: account tokens, device keys, the daemon token. POSIX
7102
+ * gets mode 0600; Windows ignores the mode, so there the file gets a user-only ACL from icacls.
7103
+ */
7104
+ /**
7105
+ * The icacls command that leaves only the current user with access to `path`: inherited entries
7106
+ * removed (`/inheritance:r`), full control granted to the user, replacing any earlier grant
7107
+ * (`/grant:r`). For a directory, `inherit` makes the grant apply to files and folders created in
7108
+ * it (`(OI)(CI)`), so they are user-only from the moment they exist.
7109
+ * See https://learn.microsoft.com/windows-server/administration/windows-commands/icacls.
7110
+ * icacls is run from System32 by absolute path, never looked up on PATH.
7111
+ */
7112
+ function userOnlyAclPlan(path, env, user, isFile, inherit = false) {
7113
+ const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows";
7114
+ const icacls = win32.join(systemRoot, "System32", "icacls.exe");
7115
+ const domain = env.USERDOMAIN;
7116
+ return planSpawn(icacls, [
7117
+ path,
7118
+ "/inheritance:r",
7119
+ "/grant:r",
7120
+ `${domain ? `${domain}\\${user}` : user}:${inherit ? "(OI)(CI)" : ""}F`
7121
+ ], {
7122
+ platform: "win32",
7123
+ env,
7124
+ ...isFile ? { isFile } : {}
7125
+ });
7126
+ }
7127
+ const runPlan = (plan) => {
7128
+ execFileSync(plan.file, plan.args, {
7129
+ stdio: "ignore",
7130
+ windowsHide: true,
7131
+ ...plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
7132
+ });
7133
+ };
7134
+ /**
7135
+ * Make a file readable by the current user only: mode 0600 on POSIX, a user-only ACL on Windows
7136
+ * (where the mode is ignored). A directory gets 0700, or an ACL its new entries inherit.
7137
+ */
7138
+ function restrictToUser(path, platform = process.platform, directory = false, run = runPlan, sid = currentUserSid) {
7139
+ if (platform !== "win32") {
7140
+ chmodSync(path, directory ? 448 : 384);
7141
+ return;
7142
+ }
7143
+ const id = sid();
7144
+ const env = {
7145
+ ...process.env,
7146
+ USERDOMAIN: void 0
7147
+ };
7148
+ const principals = id ? [`*${id}`, userInfo().username] : [userInfo().username];
7149
+ for (const principal of principals) try {
7150
+ run(userOnlyAclPlan(path, env, principal, void 0, directory));
7151
+ return;
7152
+ } catch {}
7153
+ }
7154
+ let sidCache = null;
7155
+ /** The current user's SID from `whoami /user`, or undefined. Read once per process. */
7156
+ function currentUserSid() {
7157
+ if (sidCache !== null) return sidCache;
7158
+ sidCache = void 0;
7159
+ try {
7160
+ const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT ?? "C:\\Windows";
7161
+ const out = execFileSync(win32.join(systemRoot, "System32", "whoami.exe"), [
7162
+ "/user",
7163
+ "/fo",
7164
+ "csv",
7165
+ "/nh"
7166
+ ], {
7167
+ encoding: "utf8",
7168
+ windowsHide: true,
7169
+ stdio: [
7170
+ "ignore",
7171
+ "pipe",
7172
+ "ignore"
7173
+ ]
7174
+ });
7175
+ sidCache = /"(S-1-[0-9-]+)"/.exec(out)?.[1];
7176
+ } catch {}
7177
+ return sidCache;
7178
+ }
7179
+ const tmpName = (path) => `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
7180
+ const busy = (e) => {
7181
+ const code = e.code;
7182
+ return code === "EPERM" || code === "EACCES" || code === "EBUSY";
7183
+ };
7184
+ /**
7185
+ * Write `body` to `path`, readable by this user only. The file is written next to its final
7186
+ * place, restricted, then renamed over it, so a reader never sees a half-written file or one with
7187
+ * looser permissions (a rename on one volume keeps the ACL). On Windows the temporary file is
7188
+ * restricted while still empty, before the secret is written into it.
7189
+ */
7190
+ async function writePrivateFile(path, body, o = {}) {
7191
+ const platform = o.platform ?? process.platform;
7192
+ const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
7193
+ await mkdir(dirname(path), { recursive: true });
7194
+ const tmp = tmpName(path);
7195
+ try {
7196
+ if (platform === "win32") {
7197
+ await writeFile(tmp, "", { flag: "wx" });
7198
+ restrict(tmp);
7199
+ await writeFile(tmp, body);
7200
+ } else {
7201
+ await writeFile(tmp, body, {
7202
+ mode: 384,
7203
+ flag: "wx"
7204
+ });
7205
+ restrict(tmp);
7206
+ }
7207
+ for (let attempt = 0;; attempt++) try {
7208
+ await rename(tmp, path);
7209
+ break;
7210
+ } catch (e) {
7211
+ if (platform !== "win32" || attempt >= 20 || !busy(e)) throw e;
7212
+ await new Promise((r) => setTimeout(r, Math.min(25 * (attempt + 1), 200)));
7213
+ }
7214
+ } catch (e) {
7215
+ await rm(tmp, { force: true });
7216
+ throw e;
7217
+ }
7218
+ }
7219
+ /** {@link writePrivateFile}, synchronously. */
7220
+ function writePrivateFileSync(path, body, o = {}) {
7221
+ const platform = o.platform ?? process.platform;
7222
+ const restrict = o.restrict ?? ((f) => restrictToUser(f, platform));
7223
+ mkdirSync(dirname(path), { recursive: true });
7224
+ const tmp = tmpName(path);
7225
+ try {
7226
+ if (platform === "win32") {
7227
+ writeFileSync(tmp, "", { flag: "wx" });
7228
+ restrict(tmp);
7229
+ writeFileSync(tmp, body);
7230
+ } else {
7231
+ writeFileSync(tmp, body, {
7232
+ mode: 384,
7233
+ flag: "wx"
7234
+ });
7235
+ restrict(tmp);
7236
+ }
7237
+ const wait = new Int32Array(new SharedArrayBuffer(4));
7238
+ for (let attempt = 0;; attempt++) try {
7239
+ renameSync(tmp, path);
7240
+ break;
7241
+ } catch (e) {
7242
+ if (platform !== "win32" || attempt >= 20 || !busy(e)) throw e;
7243
+ Atomics.wait(wait, 0, 0, Math.min(25 * (attempt + 1), 200));
7244
+ }
7245
+ } catch (e) {
7246
+ rmSync(tmp, { force: true });
7247
+ throw e;
7248
+ }
7249
+ }
6748
7250
  /** The `client_id` of the device authorization grant. The server accepts only this one. */
6749
- const DEVICE_CLIENT_ID = "conveno-cli";
7251
+ const DEVICE_CLIENT_ID = ACCOUNT_DEVICE_CLIENT_ID;
6750
7252
  /** Renew an access token this long before it expires, so a request never carries a dead one. */
6751
7253
  const REFRESH_SKEW_MS = 6e4;
6752
7254
  var AccountError = class extends Error {
@@ -6757,14 +7259,36 @@ var AccountError = class extends Error {
6757
7259
  this.name = "AccountError";
6758
7260
  }
6759
7261
  };
6760
- const base = (io) => (io.apiBase ?? "https://api.conveno.dev").replace(/\/+$/, "");
7262
+ const trimBase = (url) => url.replace(/\/+$/, "");
7263
+ const base = (io) => trimBase(io.apiBase ?? "https://api.conveno.dev");
7264
+ /** Where requests carrying these tokens go: the server that issued them, never another one. */
7265
+ const baseFor = (t, io) => t.apiBase ? trimBase(t.apiBase) : base(io);
6761
7266
  const doFetch = (io) => io.fetch ?? fetch;
6762
7267
  const clock = (io) => (io.now ?? Date.now)();
6763
7268
  function isTokens(v) {
6764
7269
  if (!v || typeof v !== "object") return false;
6765
7270
  const t = v;
6766
- return typeof t.accessToken === "string" && typeof t.refreshToken === "string" && t.refreshToken.length > 0 && typeof t.expiresAt === "number" && Number.isFinite(t.expiresAt);
7271
+ return typeof t.accessToken === "string" && typeof t.refreshToken === "string" && t.refreshToken.length > 0 && typeof t.expiresAt === "number" && Number.isFinite(t.expiresAt) && (t.apiBase === void 0 || typeof t.apiBase === "string" && t.apiBase.length > 0);
6767
7272
  }
7273
+ /**
7274
+ * The account server for a new login: `CONVENO_API_URL`, else {@link ACCOUNT_API}. Every other
7275
+ * request uses {@link signedInAccountApi}.
7276
+ */
7277
+ const loginAccountApi = (env = process.env) => trimBase(env.CONVENO_API_URL || "https://api.conveno.dev");
7278
+ /**
7279
+ * The account server of the saved login: the one saved in `account.json`, else
7280
+ * `CONVENO_API_URL`, else {@link ACCOUNT_API}. Also the server whose `/account` page the user
7281
+ * should visit.
7282
+ */
7283
+ function signedInAccountApi(path, env = process.env) {
7284
+ try {
7285
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
7286
+ if (isTokens(parsed) && parsed.apiBase) return trimBase(parsed.apiBase);
7287
+ } catch {}
7288
+ return loginAccountApi(env);
7289
+ }
7290
+ /** The relay the daemon connects to: `CONVENO_RELAY_URL`, else {@link RELAY_URL}. */
7291
+ const relayUrl = (env = process.env) => env.CONVENO_RELAY_URL || "wss://relay.conveno.dev/v1/connect";
6768
7292
  /** The saved tokens, or null when the user is not logged in or the file is unreadable. */
6769
7293
  async function readAccountTokens(path) {
6770
7294
  let text;
@@ -6780,27 +7304,14 @@ async function readAccountTokens(path) {
6780
7304
  return null;
6781
7305
  }
6782
7306
  }
6783
- /**
6784
- * Save the tokens, readable by this user only. The file is written next to its final place with
6785
- * the mode set at creation, then renamed over it, so a reader never sees a half-written file or
6786
- * one with looser permissions.
6787
- */
7307
+ /** Save the tokens, readable by this user only. See {@link writePrivateFile}. */
6788
7308
  async function writeAccountTokens(path, tokens) {
6789
- await mkdir(dirname(path), { recursive: true });
6790
- const tmp = `${path}.${process.pid}.tmp`;
6791
- const body = `${JSON.stringify({
7309
+ await writePrivateFile(path, `${JSON.stringify({
6792
7310
  accessToken: tokens.accessToken,
6793
7311
  refreshToken: tokens.refreshToken,
6794
- expiresAt: tokens.expiresAt
6795
- }, null, 2)}\n`;
6796
- try {
6797
- await writeFile(tmp, body, { mode: 384 });
6798
- await chmod(tmp, 384);
6799
- await rename(tmp, path);
6800
- } catch (e) {
6801
- await rm(tmp, { force: true });
6802
- throw e;
6803
- }
7312
+ expiresAt: tokens.expiresAt,
7313
+ ...tokens.apiBase ? { apiBase: tokens.apiBase } : {}
7314
+ }, null, 2)}\n`);
6804
7315
  }
6805
7316
  /** Delete the saved tokens. Returns whether there was a file. */
6806
7317
  async function clearAccountTokens(path) {
@@ -6841,11 +7352,11 @@ async function requestAccessToken(refreshToken, io = {}) {
6841
7352
  }
6842
7353
  if (res.status === 401 || res.status === 403) throw new AccountError("session_expired", "The login has expired or was revoked.");
6843
7354
  if (!res.ok) throw new AccountError("server", `The account server answered ${res.status}.`);
6844
- const body = await res.json().catch(() => null);
6845
- if (typeof body?.token !== "string") throw new AccountError("server", "The account server sent no access token.");
6846
- const expiresAt = jwtExpiry(body.token) ?? clock(io) + 9e5;
7355
+ const body = AuthTokenResponse.safeParse(await res.json().catch(() => null));
7356
+ if (!body.success) throw new AccountError("server", "The account server sent no access token.");
7357
+ const expiresAt = jwtExpiry(body.data.token) ?? clock(io) + 9e5;
6847
7358
  return {
6848
- accessToken: body.token,
7359
+ accessToken: body.data.token,
6849
7360
  expiresAt
6850
7361
  };
6851
7362
  }
@@ -6854,8 +7365,12 @@ async function refreshAccountTokens(path, io = {}) {
6854
7365
  const current = await readAccountTokens(path);
6855
7366
  if (!current) throw new AccountError("not_logged_in", "Not logged in. Run conveno login.");
6856
7367
  const next = {
6857
- ...await requestAccessToken(current.refreshToken, io),
6858
- refreshToken: current.refreshToken
7368
+ ...await requestAccessToken(current.refreshToken, {
7369
+ ...io,
7370
+ apiBase: baseFor(current, io)
7371
+ }),
7372
+ refreshToken: current.refreshToken,
7373
+ ...current.apiBase ? { apiBase: current.apiBase } : {}
6859
7374
  };
6860
7375
  await writeAccountTokens(path, next);
6861
7376
  return next;
@@ -6886,7 +7401,7 @@ async function devicePost(path, route, deviceId, io) {
6886
7401
  const tokens = await readAccountTokens(path);
6887
7402
  if (!tokens) throw new AccountError("not_logged_in", "Not logged in. Run conveno login.");
6888
7403
  try {
6889
- return await doFetch(io)(`${base(io)}/api/device/${route}`, {
7404
+ return await doFetch(io)(`${baseFor(tokens, io)}/api/device/${route}`, {
6890
7405
  method: "POST",
6891
7406
  headers: {
6892
7407
  authorization: `Bearer ${tokens.refreshToken}`,
@@ -6926,7 +7441,9 @@ async function fetchAccountStatus(refreshToken, io = {}) {
6926
7441
  }
6927
7442
  if (res.status === 401) throw new AccountError("session_expired", "The login has expired or was revoked.");
6928
7443
  if (!res.ok) throw new AccountError("server", `The account server answered ${res.status}.`);
6929
- return await res.json();
7444
+ const body = AccountMeResponse.safeParse(await res.json().catch(() => null));
7445
+ if (!body.success) throw new AccountError("server", "The account server sent an unexpected account status.");
7446
+ return body.data;
6930
7447
  }
6931
7448
  const json = (body) => ({
6932
7449
  method: "POST",
@@ -6945,15 +7462,16 @@ async function requestDeviceCode(io = {}) {
6945
7462
  throw new AccountError("network", "Could not reach the Conveno account server.");
6946
7463
  }
6947
7464
  if (!res.ok) throw new AccountError("server", `The account server answered ${res.status}.`);
6948
- const b = await res.json().catch(() => null);
6949
- if (!b || typeof b.device_code !== "string" || typeof b.user_code !== "string" || typeof b.verification_uri !== "string") throw new AccountError("server", "The account server sent an unexpected device code.");
7465
+ const parsed = DeviceCodeResponse.safeParse(await res.json().catch(() => null));
7466
+ if (!parsed.success) throw new AccountError("server", "The account server sent an unexpected device code.");
7467
+ const b = parsed.data;
6950
7468
  return {
6951
7469
  deviceCode: b.device_code,
6952
7470
  userCode: b.user_code,
6953
7471
  verificationUri: b.verification_uri,
6954
- verificationUriComplete: typeof b.verification_uri_complete === "string" ? b.verification_uri_complete : b.verification_uri,
6955
- interval: typeof b.interval === "number" && b.interval > 0 ? b.interval : 5,
6956
- expiresIn: typeof b.expires_in === "number" && b.expires_in > 0 ? b.expires_in : 900
7472
+ verificationUriComplete: b.verification_uri_complete ?? b.verification_uri,
7473
+ interval: b.interval !== void 0 && b.interval > 0 ? b.interval : 5,
7474
+ expiresIn: b.expires_in !== void 0 && b.expires_in > 0 ? b.expires_in : 900
6957
7475
  };
6958
7476
  }
6959
7477
  const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -6973,16 +7491,18 @@ async function pollDeviceCode(code, o = {}) {
6973
7491
  let res;
6974
7492
  try {
6975
7493
  res = await doFetch(o)(`${base(o)}/api/auth/device/token`, json({
6976
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
7494
+ grant_type: DEVICE_GRANT_TYPE,
6977
7495
  device_code: code.deviceCode,
6978
7496
  client_id: DEVICE_CLIENT_ID
6979
7497
  }));
6980
7498
  } catch {
6981
7499
  continue;
6982
7500
  }
6983
- const body = await res.json().catch(() => null);
6984
- if (res.ok && typeof body?.access_token === "string") return body.access_token;
6985
- switch (body?.error) {
7501
+ const raw = await res.json().catch(() => null);
7502
+ const granted = DeviceTokenSuccess.safeParse(raw);
7503
+ if (res.ok && granted.success) return granted.data.access_token;
7504
+ const failed = DeviceTokenError.safeParse(raw);
7505
+ switch (failed.success ? failed.data.error : void 0) {
6986
7506
  case "authorization_pending": continue;
6987
7507
  case "slow_down":
6988
7508
  interval += 5;
@@ -6993,11 +7513,15 @@ async function pollDeviceCode(code, o = {}) {
6993
7513
  }
6994
7514
  }
6995
7515
  }
6996
- /** After approval: keep the session token as the refresh token and get a first access token. */
7516
+ /**
7517
+ * After approval: keep the session token as the refresh token and get a first access token. The
7518
+ * account server is saved with them, so later requests go back to it.
7519
+ */
6997
7520
  async function completeLogin(path, sessionToken, io = {}) {
6998
7521
  const tokens = {
6999
7522
  ...await requestAccessToken(sessionToken, io),
7000
- refreshToken: sessionToken
7523
+ refreshToken: sessionToken,
7524
+ apiBase: base(io)
7001
7525
  };
7002
7526
  await writeAccountTokens(path, tokens);
7003
7527
  return tokens;
@@ -7009,18 +7533,21 @@ async function completeLogin(path, sessionToken, io = {}) {
7009
7533
  async function logoutAccount(path, io = {}) {
7010
7534
  const tokens = await readAccountTokens(path);
7011
7535
  let revoked = false;
7012
- if (tokens) try {
7013
- const res = await doFetch(io)(`${base(io)}/api/auth/sign-out`, {
7014
- ...json({}),
7015
- headers: {
7016
- "content-type": "application/json",
7017
- authorization: `Bearer ${tokens.refreshToken}`,
7018
- origin: base(io)
7019
- }
7020
- });
7021
- revoked = res.ok || res.status === 401;
7022
- } catch {
7023
- revoked = false;
7536
+ if (tokens) {
7537
+ const server = baseFor(tokens, io);
7538
+ try {
7539
+ const res = await doFetch(io)(`${server}/api/auth/sign-out`, {
7540
+ ...json({}),
7541
+ headers: {
7542
+ "content-type": "application/json",
7543
+ authorization: `Bearer ${tokens.refreshToken}`,
7544
+ origin: server
7545
+ }
7546
+ });
7547
+ revoked = res.ok || res.status === 401;
7548
+ } catch {
7549
+ revoked = false;
7550
+ }
7024
7551
  }
7025
7552
  const removed = await clearAccountTokens(path);
7026
7553
  return {
@@ -7028,6 +7555,206 @@ async function logoutAccount(path, io = {}) {
7028
7555
  revoked
7029
7556
  };
7030
7557
  }
7558
+ /**
7559
+ * Every supported CLI's descriptor, in the order lists show them (onboarding, spawn). Adding a CLI
7560
+ * means a file in this folder and an entry here; the compiler flags a `CliKind` that is missing.
7561
+ */
7562
+ const CLIS = {
7563
+ claude: {
7564
+ id: "claude",
7565
+ name: "Claude Code",
7566
+ shortName: "claude",
7567
+ binaries: ["claude"],
7568
+ install: {
7569
+ route: {
7570
+ kind: "script",
7571
+ sh: "https://claude.ai/install.sh",
7572
+ ps: "https://claude.ai/install.ps1"
7573
+ },
7574
+ dirs: [{
7575
+ from: "home",
7576
+ path: [".local", "bin"]
7577
+ }]
7578
+ },
7579
+ spawn: {
7580
+ interactive: (task) => task === void 0 ? [] : [task],
7581
+ modelArgs: (c) => [...c.model ? ["--model", c.model] : [], ...c.effort ? ["--effort", c.effort] : []],
7582
+ interactivePrompt: true,
7583
+ docs: ["https://code.claude.com/docs/en/cli-reference (claude \"query\")"],
7584
+ acp: {
7585
+ binaries: ["claude-agent-acp"],
7586
+ args: [],
7587
+ adapterPackage: "@agentclientprotocol/claude-agent-acp",
7588
+ modes: {
7589
+ read: "plan",
7590
+ edit: "acceptEdits",
7591
+ full: "bypassPermissions"
7592
+ },
7593
+ note: "Claude Code has no ACP server of its own. The ACP project's npm package @agentclientprotocol/claude-agent-acp provides one and uses the Claude Code sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
7594
+ docs: ["https://github.com/agentclientprotocol/claude-agent-acp (Apache-2.0, maintained by the ACP project)", "https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp (bin claude-agent-acp)"]
7595
+ }
7596
+ },
7597
+ oneWindowPerHost: true,
7598
+ deliveryTier: "next_turn"
7599
+ },
7600
+ codex: {
7601
+ id: "codex",
7602
+ name: "Codex",
7603
+ shortName: "codex",
7604
+ binaries: ["codex"],
7605
+ install: {
7606
+ route: {
7607
+ kind: "npm",
7608
+ package: "@openai/codex"
7609
+ },
7610
+ dirs: [{ from: "npmPrefix" }]
7611
+ },
7612
+ spawn: {
7613
+ interactive: (task) => task === void 0 ? [] : [task],
7614
+ modelArgs: (c) => [...c.model ? ["-m", c.model] : [], ...c.effort ? ["-c", `model_reasoning_effort=${c.effort}`] : []],
7615
+ interactivePrompt: true,
7616
+ docs: ["https://developers.openai.com/codex/cli/reference (codex [PROMPT])", "reference/src/codex/codex-rs/tui/src/cli.rs (the optional PROMPT argument)"],
7617
+ acp: {
7618
+ binaries: ["codex-acp"],
7619
+ args: [],
7620
+ adapterPackage: "@agentclientprotocol/codex-acp",
7621
+ modes: {
7622
+ read: "read-only",
7623
+ edit: "workspace-write",
7624
+ full: "agent-full-access"
7625
+ },
7626
+ note: "Codex has no ACP server of its own. The ACP project's npm package @agentclientprotocol/codex-acp provides one and uses the Codex sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
7627
+ docs: [
7628
+ "https://github.com/agentclientprotocol/codex-acp (Apache-2.0, built on the Codex app server)",
7629
+ "https://www.npmjs.com/package/@agentclientprotocol/codex-acp (bin codex-acp)",
7630
+ "reference/src/codex/codex-rs/app-server (the app server it drives)"
7631
+ ]
7632
+ }
7633
+ },
7634
+ oneWindowPerHost: false,
7635
+ deliveryTier: "next_turn",
7636
+ conversationMetaKey: "threadId"
7637
+ },
7638
+ opencode: {
7639
+ id: "opencode",
7640
+ name: "OpenCode",
7641
+ shortName: "opencode",
7642
+ binaries: ["opencode"],
7643
+ install: {
7644
+ route: {
7645
+ kind: "npm",
7646
+ package: "@opencode/cli"
7647
+ },
7648
+ dirs: [{ from: "npmPrefix" }]
7649
+ },
7650
+ spawn: {
7651
+ interactive: (task) => task === void 0 ? [] : ["--prompt", task],
7652
+ modelArgs: (c) => c.model ? ["-m", c.model] : [],
7653
+ interactivePrompt: true,
7654
+ docs: ["https://opencode.ai/docs/cli/ (the TUI --prompt flag)", "reference/src/opencode/packages/cli/src/commands/commands.ts at v2.4.3 (--prompt)"],
7655
+ acp: {
7656
+ binaries: ["opencode"],
7657
+ args: ["acp"],
7658
+ modes: {
7659
+ read: "plan",
7660
+ edit: "build",
7661
+ full: "build"
7662
+ },
7663
+ note: "",
7664
+ docs: ["https://opencode.ai/docs/cli/acp/ (opencode acp, stdio, protocol version 1)", "reference/src/opencode/packages/opencode/src/cli/cmd/acp.ts"]
7665
+ }
7666
+ },
7667
+ oneWindowPerHost: true,
7668
+ deliveryTier: "inbox",
7669
+ conversationMetaKey: "ai.opencode/sessionID"
7670
+ },
7671
+ antigravity: {
7672
+ id: "antigravity",
7673
+ name: "Antigravity",
7674
+ shortName: "antigravity",
7675
+ binaries: ["agy"],
7676
+ install: {
7677
+ route: {
7678
+ kind: "script",
7679
+ sh: "https://antigravity.google/cli/install.sh",
7680
+ ps: "https://antigravity.google/cli/install.ps1"
7681
+ },
7682
+ dirs: [{
7683
+ from: "localAppData",
7684
+ path: ["agy", "bin"],
7685
+ only: "win32"
7686
+ }, {
7687
+ from: "home",
7688
+ path: [".local", "bin"],
7689
+ only: "posix"
7690
+ }]
7691
+ },
7692
+ spawn: {
7693
+ interactive: () => [],
7694
+ modelArgs: (c) => [...c.model ? ["--model", c.model] : [], ...c.effort ? ["--effort", c.effort] : []],
7695
+ interactivePrompt: false,
7696
+ docs: ["https://antigravity.google/docs/cli/acp (agy)"],
7697
+ acp: {
7698
+ binaries: ["agy"],
7699
+ args: ["acp"],
7700
+ modes: {
7701
+ read: "plan",
7702
+ edit: "accept-edits",
7703
+ full: "default"
7704
+ },
7705
+ note: "Uses the sign-in cached by an interactive `agy`.",
7706
+ docs: ["https://antigravity.google/docs/cli/acp (agy acp, stdio)"]
7707
+ }
7708
+ },
7709
+ oneWindowPerHost: true,
7710
+ deliveryTier: "next_turn",
7711
+ launcher: { winCmdShim: true },
7712
+ conversationMetaKey: "antigravity.google/root_conversation_id"
7713
+ },
7714
+ grok: {
7715
+ id: "grok",
7716
+ name: "Grok Build",
7717
+ shortName: "grok",
7718
+ binaries: ["grok"],
7719
+ install: {
7720
+ route: {
7721
+ kind: "script",
7722
+ sh: "https://x.ai/cli/install.sh",
7723
+ ps: "https://x.ai/cli/install.ps1"
7724
+ },
7725
+ dirs: [{
7726
+ from: "home",
7727
+ path: [".grok", "bin"]
7728
+ }]
7729
+ },
7730
+ spawn: {
7731
+ interactive: (task) => task === void 0 ? [] : [task],
7732
+ modelArgs: (c) => [...c.model ? ["-m", c.model] : [], ...c.effort ? ["--reasoning-effort", c.effort] : []],
7733
+ interactivePrompt: true,
7734
+ docs: ["reference/src/grok-build/crates/codegen/xai-grok-pager/src/app/cli.rs (prompt)"],
7735
+ acp: {
7736
+ binaries: ["grok"],
7737
+ args: ["agent", "stdio"],
7738
+ note: "",
7739
+ docs: ["reference/src/grok-build/crates/codegen/xai-grok-pager/src/app/cli.rs (grok agent stdio)", "reference/src/grok-build/crates/codegen/xai-grok-pager/docs/user-guide/15-agent-mode.md"]
7740
+ }
7741
+ },
7742
+ oneWindowPerHost: true,
7743
+ deliveryTier: "inbox",
7744
+ launcher: { winCmdShim: false }
7745
+ }
7746
+ };
7747
+ /** The descriptors in display order. */
7748
+ const CLI_DESCRIPTORS = Object.values(CLIS);
7749
+ /** The descriptor of `cli`, or undefined for an id that is not a supported CLI. */
7750
+ const cliDescriptor = (cli) => Object.hasOwn(CLIS, cli) ? CLIS[cli] : void 0;
7751
+ /**
7752
+ * Is the CLI's window one host process, so a second MCP server under it belongs to the window's
7753
+ * session (see `CliDescriptor.oneWindowPerHost`).
7754
+ */
7755
+ const oneWindowPerHost = (cli) => CLIS[cli].oneWindowPerHost;
7756
+ /** The delivery tier of a CLI's own (non-ACP) sessions; an unknown CLI gets `inbox`. */
7757
+ const cliDeliveryTier = (cli) => cliDescriptor(cli)?.deliveryTier ?? "inbox";
7031
7758
  const pathApi$2 = (platform) => platform === "win32" ? win32 : posix;
7032
7759
  /**
7033
7760
  * Conveno data directory. Pure: platform, environment and home directory are arguments.
@@ -7072,7 +7799,13 @@ function dataPaths(platform, dir) {
7072
7799
  /** Conveno account tokens from `conveno login`, mode 0600. See account.ts. */
7073
7800
  account: p.join(dir, "account.json"),
7074
7801
  /** Choices the user made, such as whether ACP adapters may be fetched with npx. See settings.ts. */
7075
- settings: p.join(dir, "settings.json")
7802
+ settings: p.join(dir, "settings.json"),
7803
+ /** The models and effort levels each CLI offered its last worker. See worker-models.ts. */
7804
+ workerModels: p.join(dir, "worker-models.json"),
7805
+ /** The relay client's device keys, mode 0600. See daemon/src/relay/state.ts. */
7806
+ relayIdentity: p.join(dir, "device-key.json"),
7807
+ /** The relay client's device list, device name and seen envelope ids, mode 0600. */
7808
+ relayDatabase: p.join(dir, "relay.db")
7076
7809
  };
7077
7810
  }
7078
7811
  /** Best effort: deletes the markers in `dir` not touched for `ASKED_MAX_AGE_MS`. */
@@ -7085,6 +7818,12 @@ async function pruneAsked(dir, now = Date.now()) {
7085
7818
  } catch {}
7086
7819
  }
7087
7820
  /**
7821
+ * The key of an ask that is made once per session and conversation: a window's session moves
7822
+ * between conversations, and a helper started for one does not serve the next. Without a
7823
+ * conversation id, the session alone.
7824
+ */
7825
+ const askedKey = (sessionId, conversationId) => conversationId === void 0 || conversationId === "" ? sessionId : `${sessionId}_${conversationId}`;
7826
+ /**
7088
7827
  * "Asked once per session" for a Stop hook request: one empty file per Conveno session in
7089
7828
  * `<data dir>/<folder>`. Best effort both ways: a failure only means the request can repeat.
7090
7829
  */
@@ -7176,7 +7915,10 @@ function formatFramedMessage(message, options = {}) {
7176
7915
  const sender = senderOf(message);
7177
7916
  const reply = message.replyTo ? ` Reply to message ${message.replyTo}.` : "";
7178
7917
  const when = formatClock(message.createdAt);
7179
- const header = isFromOwner(message) ? `[conveno] Message from the user (the person at this computer) at ${when}.${reply} ${FROM_USER_NOTICE}` : `[conveno] ${options.task ? "Task from the orchestrator" : "Message from"} ${sender.name} (${sender.cli}) at ${when}.${reply} ${options.task ? ORCHESTRATOR_TASK_NOTICE : NOT_FROM_USER_NOTICE}`;
7918
+ const lead = options.task === true;
7919
+ const asTask = lead && !message.replyTo;
7920
+ const label = asTask ? "Task from the orchestrator" : lead ? "Reply from the orchestrator" : "Message from";
7921
+ const header = isFromOwner(message) ? `[conveno] Message from the user (the person at this computer) at ${when}.${reply} ${FROM_USER_NOTICE}` : `[conveno] ${label} ${sender.name} (${sender.cli}) at ${when}.${reply} ${asTask ? ORCHESTRATOR_TASK_NOTICE : NOT_FROM_USER_NOTICE}`;
7180
7922
  const meta = [`Message id: ${message.id}`];
7181
7923
  if (message.urgent) meta.push("Marked urgent by the sender.");
7182
7924
  const body = renderBody(message);
@@ -7210,8 +7952,8 @@ function formatHookContext(messages) {
7210
7952
  }
7211
7953
  /**
7212
7954
  * The prompt for a turn Conveno starts by itself (end of turn or idle wake). It says
7213
- * that Conveno, not the user, started the turn. Tasks from the current orchestrator carry the task
7214
- * notice; every other message keeps the not-from-user notice.
7955
+ * that Conveno, not the user, started the turn. New messages from the current orchestrator carry the task
7956
+ * notice (replies do not, so workers do not answer a reply); every other message keeps the not-from-user notice.
7215
7957
  */
7216
7958
  function formatContinuation(messages, orchestrator, remaining = 0) {
7217
7959
  if (messages.length === 0) return "";
@@ -7439,42 +8181,24 @@ function parseCliVersion(output) {
7439
8181
  }
7440
8182
  var clis = {
7441
8183
  "claude": {
7442
- "verified": "2.1.332",
7443
- "minimum": "2.1.332"
7444
- },
7445
- "codex": {
7446
- "verified": "0.172.0",
7447
- "minimum": "0.172.0"
7448
- },
7449
- "opencode": {
7450
- "verified": "2.4.3",
7451
- "minimum": "1.19.6"
7452
- },
7453
- "cursor": {
7454
- "verified": "2026.11.22-e9042b2",
7455
- "minimum": "2026.11.22-e9042b2"
7456
- },
7457
- "copilot": {
7458
- "verified": "1.0.117",
7459
- "minimum": "1.0.117"
8184
+ "verified": "2.1.335",
8185
+ "minimum": "2.1.139"
7460
8186
  },
8187
+ "codex": { "verified": "0.173.0" },
8188
+ "opencode": { "verified": "2.4.4" },
7461
8189
  "antigravity": {
7462
- "verified": "1.5.20",
7463
- "minimum": "1.5.20"
8190
+ "verified": "1.5.22",
8191
+ "minimum": "1.5.8"
7464
8192
  },
7465
- "grok": {
7466
- "verified": "1.0.92",
7467
- "minimum": "1.0.92"
7468
- }
8193
+ "grok": { "verified": "1.0.100" }
7469
8194
  };
7470
8195
  var acpAdapters = {
7471
- "@agentclientprotocol/codex-acp": "2.10.0",
7472
- "@agentclientprotocol/claude-agent-acp": "0.110.0"
8196
+ "@agentclientprotocol/codex-acp": "2.12.0",
8197
+ "@agentclientprotocol/claude-agent-acp": "0.112.0"
7473
8198
  };
7474
8199
  /**
7475
8200
  * Versions per CLI, from `compat.json`. The nightly compat workflow raises `verified` when a newer
7476
- * release passes its checks. `minimum` changes only by hand, when a format change drops older
7477
- * releases.
8201
+ * release passes its checks. `minimum` changes only by hand, when Conveno starts to need a feature older releases lack.
7478
8202
  */
7479
8203
  const COMPAT = clis;
7480
8204
  /** The numeric part of a version: `2.1.332`, `0.172.0-alpha.3` or `2026.11.22-e9042b2`. */
@@ -7483,8 +8207,8 @@ function versionParts(version) {
7483
8207
  }
7484
8208
  /**
7485
8209
  * Negative when `a` is older than `b`, 0 when equal, positive when newer; undefined when either
7486
- * has no numeric version. Only the dotted numbers count: a suffix such as `-e9042b2` (Cursor's
7487
- * commit) or `-alpha.3` is ignored, and a missing part is 0 (`1.2` equals `1.2.0`).
8210
+ * has no numeric version. Only the dotted numbers count: a suffix such as `-e9042b2` (a
8211
+ * commit hash) or `-alpha.3` is ignored, and a missing part is 0 (`1.2` equals `1.2.0`).
7488
8212
  */
7489
8213
  function compareVersions(a, b) {
7490
8214
  const pa = versionParts(a);
@@ -7500,10 +8224,10 @@ function compareVersions(a, b) {
7500
8224
  function compatStatus(cli, version, table = COMPAT) {
7501
8225
  const entry = table[cli];
7502
8226
  if (!entry || !version) return { kind: "unknown" };
7503
- const vsMin = compareVersions(version, entry.minimum);
8227
+ const vsMin = entry.minimum === void 0 ? 0 : compareVersions(version, entry.minimum);
7504
8228
  const vsVerified = compareVersions(version, entry.verified);
7505
8229
  if (vsMin === void 0 || vsVerified === void 0) return { kind: "unknown" };
7506
- if (vsMin < 0) return {
8230
+ if (vsMin < 0 && entry.minimum !== void 0) return {
7507
8231
  kind: "older",
7508
8232
  minimum: entry.minimum
7509
8233
  };
@@ -7604,6 +8328,7 @@ function openWatch(o) {
7604
8328
  const r = await client["turn.wake"]({
7605
8329
  sessionId: id,
7606
8330
  listenerId,
8331
+ ...o.nativeId === void 0 ? {} : { nativeId: o.nativeId },
7607
8332
  ...o.maxChars === void 0 ? {} : { maxChars: o.maxChars }
7608
8333
  });
7609
8334
  if (r.superseded) return {
@@ -7710,17 +8435,65 @@ async function runWaker(o) {
7710
8435
  /** Longest wait between two tries to reach the daemon again (`reconnectMs`). */
7711
8436
  const MAX_RECONNECT_MS = 6e4;
7712
8437
  /**
8438
+ * The pid of the CLI above the hook: the one the context already knows, else the walk up the
8439
+ * process tree (`resolveHostPid`, which runs once). Undefined when no session of the CLI is online.
8440
+ */
8441
+ async function hostPidOf(ctx) {
8442
+ if (ctx.hostPid !== void 0) return ctx.hostPid;
8443
+ return ctx.resolveHostPid ? await ctx.resolveHostPid() : void 0;
8444
+ }
8445
+ /** Is the host CLI still running. True when there is no check or the host is not known. */
8446
+ async function hostAlive(ctx) {
8447
+ if (!ctx.isAlive) return true;
8448
+ const pid = await hostPidOf(ctx);
8449
+ return pid === void 0 || ctx.isAlive(pid);
8450
+ }
8451
+ /** The daemon cannot take `ppid` (an older one): fall back to the walk. */
8452
+ const noPpidSupport = (e) => {
8453
+ const code = e?.code;
8454
+ return code === RpcErrorCode.MethodNotFound || code === RpcErrorCode.InvalidParams;
8455
+ };
8456
+ /**
7713
8457
  * The session that owns the hook's host process, when it is a session of the hook's own CLI. Every
7714
8458
  * helper below goes through here before taking messages, so a hook running inside another CLI
7715
- * (which would print a format that CLI discards) never marks anything delivered. With
7716
- * `includeOffline`, a session that just went offline (still in the daemon's removal grace) counts.
8459
+ * (which would print a format that CLI discards) never marks anything delivered.
7717
8460
  */
7718
- async function ownSession(ctx, opts = {}) {
8461
+ async function ownSession(ctx) {
8462
+ if (ctx.nativeId !== void 0 && ctx.cli !== void 0) try {
8463
+ const base = {
8464
+ cli: ctx.cli,
8465
+ nativeId: ctx.nativeId,
8466
+ ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
8467
+ turnStart: ctx.turnStart === true
8468
+ };
8469
+ let r;
8470
+ if (ctx.hostPid === void 0 && ctx.ppid !== void 0) try {
8471
+ r = await ctx.client["session.bind"]({
8472
+ ...base,
8473
+ ppid: ctx.ppid
8474
+ });
8475
+ } catch (e) {
8476
+ if (!noPpidSupport(e)) throw e;
8477
+ }
8478
+ if (!r || r.needsHost) {
8479
+ const hostPid = await hostPidOf(ctx);
8480
+ if (hostPid === void 0) return null;
8481
+ r = await ctx.client["session.bind"]({
8482
+ ...base,
8483
+ hostPid
8484
+ });
8485
+ }
8486
+ const { session } = r;
8487
+ return session && session.cli !== ctx.cli ? null : session;
8488
+ } catch (e) {
8489
+ if (e?.code !== RpcErrorCode.MethodNotFound) throw e;
8490
+ }
8491
+ const pid = await hostPidOf(ctx);
8492
+ if (pid === void 0) return null;
7719
8493
  const { session } = await ctx.client["session.byHost"]({
7720
- pid: ctx.hostPid,
8494
+ pid,
7721
8495
  ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
7722
- ...ctx.nativeId === void 0 ? {} : { nativeId: ctx.nativeId },
7723
- ...opts.includeOffline ? { includeOffline: true } : {}
8496
+ ...ctx.nativeId === void 0 ? {} : { nativeId: ctx.nativeId }
7724
8497
  });
7725
8498
  if (session && ctx.cli !== void 0 && session.cli !== ctx.cli) return null;
7726
8499
  return session;
@@ -7767,7 +8540,10 @@ async function pendingHookContext(ctx, opts = {}) {
7767
8540
  async function startTurnContext(ctx, opts = {}) {
7768
8541
  try {
7769
8542
  const session = await ownSession(ctx);
7770
- if (!session) return null;
8543
+ if (!session) {
8544
+ await opts.onNoSession?.();
8545
+ return null;
8546
+ }
7771
8547
  try {
7772
8548
  await ctx.client["turn.start"]({ sessionId: session.id });
7773
8549
  } catch {}
@@ -7801,32 +8577,9 @@ async function endTurnContinuation(ctx, opts = {}) {
7801
8577
  return null;
7802
8578
  }
7803
8579
  const text = formatContinuation(r.messages, r.orchestrator, r.remaining);
7804
- return text === "" ? null : text;
7805
- } catch {
7806
- return null;
7807
- }
7808
- }
7809
- /**
7810
- * Put messages the hook took back to queued, for a hook that learns its CLI will not show them
7811
- * (Copilot stopping). Finds the session even when it went offline a moment ago, as a CLI that is
7812
- * exiting often unregisters it first. Returns how many went back; 0 on any failure.
7813
- */
7814
- async function requeueOwnMessages(ctx, ids) {
7815
- try {
7816
- if (ids.length === 0) return 0;
7817
- const session = await ownSession(ctx, { includeOffline: true });
7818
- if (!session) return 0;
7819
- let n = 0;
7820
- for (let i = 0; i < ids.length; i += 100) {
7821
- const r = await ctx.client["message.requeue"]({
7822
- sessionId: session.id,
7823
- ids: ids.slice(i, i + 100)
7824
- });
7825
- n += r.requeued;
7826
- }
7827
- return n;
8580
+ return text === "" ? null : text;
7828
8581
  } catch {
7829
- return 0;
8582
+ return null;
7830
8583
  }
7831
8584
  }
7832
8585
  const DEFAULT_REGISTER_POLL_MS = 1e3;
@@ -7848,15 +8601,20 @@ async function waitForWork(ctx, opts = {}) {
7848
8601
  */
7849
8602
  async function awaitOwnSession(ctx, waitMs, pollMs, signal) {
7850
8603
  const until = Date.now() + waitMs;
8604
+ let own = ctx;
7851
8605
  for (;;) {
7852
8606
  try {
7853
- const session = await ownSession(ctx);
8607
+ const session = await ownSession(own);
7854
8608
  if (session) return session;
7855
8609
  } catch {
7856
8610
  return "disconnected";
7857
8611
  }
7858
8612
  if (Date.now() + pollMs > until || signal?.aborted) return null;
7859
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return null;
8613
+ if (!await hostAlive(ctx)) return null;
8614
+ if (own.turnStart) own = {
8615
+ ...own,
8616
+ turnStart: false
8617
+ };
7860
8618
  await new Promise((r) => setTimeout(r, pollMs));
7861
8619
  }
7862
8620
  }
@@ -7868,7 +8626,7 @@ async function pauseWhileAlive(ctx, ms, stepMs, deadline, signal) {
7868
8626
  const until = Math.min(Date.now() + ms, deadline);
7869
8627
  for (;;) {
7870
8628
  if (signal?.aborted || Date.now() >= deadline) return false;
7871
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return false;
8629
+ if (!await hostAlive(ctx)) return false;
7872
8630
  const left = until - Date.now();
7873
8631
  if (left <= 0) return true;
7874
8632
  await new Promise((r) => setTimeout(r, Math.min(left, stepMs)));
@@ -7877,7 +8635,8 @@ async function pauseWhileAlive(ctx, ms, stepMs, deadline, signal) {
7877
8635
  /** `waitForWork`, returning the whole batch and its session (for a requeue). */
7878
8636
  async function waitForWorkBatch(ctx, opts = {}) {
7879
8637
  const deadline = opts.maxMs === void 0 ? 1e400 : Date.now() + opts.maxMs;
7880
- const { isAlive, hostPid } = ctx;
8638
+ const { isAlive } = ctx;
8639
+ const hostPid = isAlive ? await hostPidOf(ctx) : void 0;
7881
8640
  const listenerId = opts.listenerId ?? randomBytes(12).toString("base64url");
7882
8641
  let delay = opts.reconnectMs;
7883
8642
  /** After a lost connection: wait, then go round again. False when the listener must stop. */
@@ -7887,24 +8646,30 @@ async function waitForWorkBatch(ctx, opts = {}) {
7887
8646
  delay = Math.min(delay * 2, Math.max(opts.reconnectMs ?? 0, MAX_RECONNECT_MS));
7888
8647
  return ok;
7889
8648
  };
8649
+ let round = ctx;
7890
8650
  for (;;) {
7891
- const session = await awaitOwnSession(ctx, opts.registerWaitMs ?? 0, opts.registerPollMs ?? DEFAULT_REGISTER_POLL_MS, opts.signal);
8651
+ const session = await awaitOwnSession(round, opts.registerWaitMs ?? 0, opts.registerPollMs ?? DEFAULT_REGISTER_POLL_MS, opts.signal);
7892
8652
  if (session === "disconnected") {
7893
8653
  if (await retry()) continue;
7894
8654
  return null;
7895
8655
  }
7896
8656
  if (!session) return null;
7897
8657
  delay = opts.reconnectMs;
8658
+ if (round.turnStart) round = {
8659
+ ...round,
8660
+ turnStart: false
8661
+ };
7898
8662
  const r = await waitForWake({
7899
8663
  client: ctx.client,
7900
8664
  sessionId: session.id,
7901
8665
  listenerId,
8666
+ ...ctx.nativeId !== void 0 ? { nativeId: ctx.nativeId } : {},
7902
8667
  ...opts.pollMs !== void 0 ? { pollMs: opts.pollMs } : {},
7903
8668
  ...opts.hostCheckMs !== void 0 ? { hostCheckMs: opts.hostCheckMs } : {},
7904
8669
  ...deadline !== 1e400 ? { maxMs: Math.max(0, deadline - Date.now()) } : {},
7905
8670
  ...opts.signal !== void 0 ? { signal: opts.signal } : {},
7906
8671
  ...opts.maxChars !== void 0 ? { maxChars: opts.maxChars } : {},
7907
- ...isAlive ? { isHostAlive: () => isAlive(hostPid) } : {}
8672
+ ...isAlive && hostPid !== void 0 ? { isHostAlive: () => isAlive(hostPid) } : {}
7908
8673
  });
7909
8674
  if (r.ok) return {
7910
8675
  sessionId: session.id,
@@ -7914,6 +8679,51 @@ async function waitForWorkBatch(ctx, opts = {}) {
7914
8679
  return null;
7915
8680
  }
7916
8681
  }
8682
+ /** The log rotates once it passes this size; one old file is kept (`hooks.log.1`). */
8683
+ const HOOK_LOG_MAX_BYTES = 1e6;
8684
+ /** `<data dir>/logs/hooks.log`. */
8685
+ const hookLogPath = (dataDir) => join(dataDir, "logs", "hooks.log");
8686
+ /** `<data dir>/logs/lead.log`: one line per change of the lead (see `leadLogLine`). */
8687
+ const leadLogPath = (dataDir) => join(dataDir, "logs", "lead.log");
8688
+ /** Keep a logged word to plain characters, so one entry is one line and nothing is injected. */
8689
+ const plain = (v, max, extra = "") => v.replace(new RegExp(`[^A-Za-z0-9_.@:${extra}-]`, "g"), "_").slice(0, max);
8690
+ /** A duration in whole ms, or `-` when there is none. */
8691
+ const num = (v) => v === void 0 || !Number.isFinite(v) ? "-" : String(Math.max(0, Math.round(v)));
8692
+ /**
8693
+ * One line: `<iso time> cli=<cli> event=<event> conv=<the conversation id> session=<name
8694
+ * or none> result=<result> host_ms=<n or -> ms=<n or ->`. No message text and no tokens: only ids the CLI hands to hooks and the
8695
+ * session's name.
8696
+ */
8697
+ function hookLogLine(e) {
8698
+ const conv = e.conversationId ? plain(e.conversationId, 64) : "-";
8699
+ return `${(e.at ?? /* @__PURE__ */ new Date()).toISOString()} cli=${plain(e.cli, 16)} event=${plain(e.event, 32)} conv=${conv} session=${e.session ? plain(e.session, 64) : "none"} result=${plain(e.result, 40, " ")} host_ms=${num(e.hostMs)} ms=${num(e.ms)}\n`;
8700
+ }
8701
+ /** One line: `<iso time> lead=<name or none> previous=<name or none> via=<how>`. */
8702
+ function leadLogLine(e) {
8703
+ const name = (v) => v ? plain(v, 64) : "none";
8704
+ return `${(e.at ?? /* @__PURE__ */ new Date()).toISOString()} lead=${name(e.lead)} previous=${name(e.previous)} via=${plain(e.via, 16)}\n`;
8705
+ }
8706
+ /**
8707
+ * Append one line to the hook log, rotating at `HOOK_LOG_MAX_BYTES`. Synchronous and tiny so a hook
8708
+ * is not made slower, and it never throws: a log that cannot be written must not change a hook.
8709
+ */
8710
+ function appendHookLog(path, line, maxBytes = HOOK_LOG_MAX_BYTES) {
8711
+ try {
8712
+ try {
8713
+ if (statSync(path).size > maxBytes) {
8714
+ rmSync(`${path}.1`, { force: true });
8715
+ renameSync(path, `${path}.1`);
8716
+ }
8717
+ } catch {}
8718
+ try {
8719
+ appendFileSync(path, line, { mode: 384 });
8720
+ } catch (e) {
8721
+ if (e.code !== "ENOENT") throw e;
8722
+ mkdirSync(dirname(path), { recursive: true });
8723
+ appendFileSync(path, line, { mode: 384 });
8724
+ }
8725
+ } catch {}
8726
+ }
7917
8727
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7918
8728
  const PARSE_OPTIONS = { allowTrailingComma: true };
7919
8729
  /**
@@ -8185,15 +8995,16 @@ const fallback = (env) => {
8185
8995
  };
8186
8996
  /**
8187
8997
  * The command an agent runs for a Conveno helper of `cli`, as words (not yet quoted). Grok keeps a
8188
- * plain `conveno` when the PATH one is this install. Antigravity on Windows prefers the PATH
8189
- * `conveno.cmd`. In every other case it is the launcher, or the configured command when no launcher
8190
- * is known.
8998
+ * plain `conveno` when the PATH one is this install. A CLI with `launcher.winCmdShim`
8999
+ * (Antigravity) prefers the PATH `conveno.cmd` on Windows. In every other case it is the launcher,
9000
+ * or the configured command when no launcher is known.
8191
9001
  */
8192
9002
  function agentCommand(env, cli) {
8193
9003
  const l = env.conveno.launcher;
8194
9004
  if (!l) return env.conveno.command;
8195
- if (cli === "antigravity" && env.platform === "win32" && l.onPath && l.cmdShim) return ["conveno.cmd"];
8196
- if (l.onPath && !(cli === "antigravity" && env.platform === "win32")) return ["conveno"];
9005
+ const cmdShim = CLIS[cli].launcher.winCmdShim && env.platform === "win32";
9006
+ if (cmdShim && l.onPath && l.cmdShim) return ["conveno.cmd"];
9007
+ if (l.onPath && !cmdShim) return ["conveno"];
8197
9008
  if (l.spaced) return fallback(env);
8198
9009
  return [slashed(l.path, env.platform)];
8199
9010
  }
@@ -8268,7 +9079,7 @@ function statusAfterLiveness(current, verdict) {
8268
9079
  return current;
8269
9080
  }
8270
9081
  const isOnline = (s) => s.status !== "offline";
8271
- const MAX_NAME = 64;
9082
+ const MAX_NAME$1 = 64;
8272
9083
  /** Make a directory name safe to embed in a session name: lowercase, `[a-z0-9._-]`, non-empty. */
8273
9084
  function sanitizeNamePart(raw) {
8274
9085
  const cleaned = raw.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/-+$/, "");
@@ -8283,7 +9094,7 @@ function generateSessionName(cli, repoBasename, sessions) {
8283
9094
  const prefix = `${cli}@`;
8284
9095
  for (let n = 1;; n++) {
8285
9096
  const suffix = `-${n}`;
8286
- const room = MAX_NAME - prefix.length - suffix.length;
9097
+ const room = MAX_NAME$1 - prefix.length - suffix.length;
8287
9098
  const name = `${prefix}${sanitizeNamePart(repoBasename).slice(0, room)}${suffix}`;
8288
9099
  if (!taken.has(name)) return name;
8289
9100
  }
@@ -8355,93 +9166,46 @@ function clearOrchestrator(holder, sessions) {
8355
9166
  function holderAfterDeparture(holder, departed) {
8356
9167
  return holder === departed ? null : holder;
8357
9168
  }
8358
- const defaultIsFile = (path) => {
8359
- try {
8360
- return statSync(path).isFile();
8361
- } catch {
8362
- return false;
8363
- }
8364
- };
8365
- /** Environment variable lookup that ignores case, as Windows does (`Path`, `PATH`, `PathExt`). */
8366
- function envGet(env, name) {
8367
- const want = name.toLowerCase();
8368
- for (const [k, v] of Object.entries(env)) if (k.toLowerCase() === want && v !== void 0) return v;
8369
- }
8370
- const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
8371
- /** Only these can be started safely: other PATHEXT entries (.JS, .VBS) open Windows Script Host. */
8372
- const LAUNCHABLE = /* @__PURE__ */ new Set([
8373
- ".com",
8374
- ".exe",
8375
- ".bat",
8376
- ".cmd"
8377
- ]);
8378
- /**
8379
- * Find `command` the way cmd.exe does: each PATH directory in order, each PATHEXT extension in
8380
- * order. A name that already ends in a launchable extension is tried as written first. Returns
8381
- * undefined when nothing matches.
8382
- */
8383
- function resolveWindowsCommand(command, env, isFile = defaultIsFile) {
8384
- const exts = (envGet(env, "PATHEXT") ?? DEFAULT_PATHEXT).split(";").map((e) => e.trim()).filter((e) => LAUNCHABLE.has(e.toLowerCase()));
8385
- const own = win32.extname(command).toLowerCase();
8386
- const candidatesIn = (base) => [...LAUNCHABLE.has(own) ? [base] : [], ...exts.map((e) => base + e)];
8387
- const dirs = /[\\/]/.test(command) || win32.isAbsolute(command) ? [""] : (envGet(env, "PATH") ?? "").split(";").map((d) => d.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
8388
- for (const dir of dirs) for (const candidate of candidatesIn(dir === "" ? command : win32.join(dir, command))) if (isFile(candidate)) return candidate;
8389
- }
8390
- /** Characters cmd.exe treats specially, plus the ones cross-spawn escapes defensively. */
8391
- const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
8392
- /** The program name part of a cmd.exe command line: escape only, never wrap in quotes. */
8393
- function escapeCmdCommand(command) {
8394
- return command.replace(CMD_META, "^$1");
8395
- }
8396
- /**
8397
- * Quote one argument for a `cmd.exe /d /s /c "..."` command line, the way cross-spawn does:
8398
- * make it safe for the program's own parser (backslashes before a quote are doubled, the quote
8399
- * is backslash-escaped, the whole thing is wrapped in quotes), then caret-escape every
8400
- * character cmd.exe would act on, including the quotes themselves.
8401
- */
8402
- function escapeCmdArg(arg) {
8403
- let a = `${arg}`;
8404
- a = a.replace(/(\\*)"/g, "$1$1\\\"");
8405
- a = a.replace(/(\\*)$/, "$1$1");
8406
- a = `"${a}"`;
8407
- return a.replace(CMD_META, "^$1");
8408
- }
8409
- /** `cmd.exe /d /s /c "<command line>"` for a .cmd or .bat file. */
8410
- function cmdShimPlan(file, args, env) {
8411
- const line = [escapeCmdCommand(file), ...args.map(escapeCmdArg)].join(" ");
8412
- return {
8413
- file: envGet(env, "ComSpec") || "cmd.exe",
8414
- args: [
8415
- "/d",
8416
- "/s",
8417
- "/c",
8418
- `"${line}"`
8419
- ],
8420
- windowsVerbatimArguments: true
8421
- };
8422
- }
9169
+ /** Claude Code's notes (the hooks write them, the MCP server takes them). */
9170
+ const CLAUDE_PENDING_TURN_FOLDER = "claude-pending-turn";
9171
+ /** A note older than this is from a turn long over. */
9172
+ const PENDING_TURN_MAX_AGE_MS = 6e5;
8423
9173
  /**
8424
- * What to spawn for `command args...`. On Windows the command is resolved on PATH: .exe and .com
8425
- * run directly, .cmd and .bat (npm shims) go through cmd.exe with one quoted command line. Never
8426
- * uses a shell option with an args array. Elsewhere, and when nothing is found, the command is
8427
- * returned unchanged so the caller sees the normal ENOENT.
9174
+ * "A turn started before this window's session registered." A CLI can run its first prompt's hook
9175
+ * before its MCP server has registered (Claude Code started with a prompt, as `conveno spawn` does),
9176
+ * so the hook finds no session and the turn would show as idle. The hook leaves one empty file per
9177
+ * conversation in `<data dir>/<folder>`; the MCP server takes it when it registers and starts the
9178
+ * turn, and the turn's end removes it. Best effort: a failure only loses the busy state of that turn.
8428
9179
  */
8429
- function planSpawn(command, args, opts = {}) {
8430
- if ((opts.platform ?? process.platform) !== "win32") return {
8431
- file: command,
8432
- args
8433
- };
8434
- const env = opts.env ?? process.env;
8435
- const found = resolveWindowsCommand(command, env, opts.isFile);
8436
- if (!found) return {
8437
- file: command,
8438
- args
8439
- };
8440
- const ext = win32.extname(found).toLowerCase();
8441
- if (ext === ".cmd" || ext === ".bat") return cmdShimPlan(found, args, env);
9180
+ function pendingTurn(dir, folder) {
9181
+ const file = (conversationId) => join(dir, folder, conversationId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128));
8442
9182
  return {
8443
- file: found,
8444
- args
9183
+ async mark(conversationId) {
9184
+ try {
9185
+ const f = file(conversationId);
9186
+ await mkdir(join(f, ".."), { recursive: true });
9187
+ await writeFile(f, "");
9188
+ const now = Date.now();
9189
+ for (const name of await readdir(join(f, ".."))) {
9190
+ const g = join(f, "..", name);
9191
+ if (now - (await stat(g)).mtimeMs > 6e5) await rm(g, { force: true });
9192
+ }
9193
+ } catch {}
9194
+ },
9195
+ /** True when a fresh note was there; the note is removed either way. */
9196
+ async take(conversationId, now = Date.now()) {
9197
+ try {
9198
+ const f = file(conversationId);
9199
+ const fresh = now - (await stat(f)).mtimeMs <= PENDING_TURN_MAX_AGE_MS;
9200
+ await rm(f, { force: true });
9201
+ return fresh;
9202
+ } catch {
9203
+ return false;
9204
+ }
9205
+ },
9206
+ async clear(conversationId) {
9207
+ await rm(file(conversationId), { force: true }).catch(() => {});
9208
+ }
8445
9209
  };
8446
9210
  }
8447
9211
  function exec(file, args, timeoutMs) {
@@ -8544,6 +9308,12 @@ function parseProcStat(stat) {
8544
9308
  const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
8545
9309
  return Number.isInteger(ppid) && ppid >= 0 ? ppid : void 0;
8546
9310
  }
9311
+ const ANTIGRAVITY_APP_EXE = /(?:^|[\\/"])antigravity(?:\.exe)?"?(?:\s|$)/i;
9312
+ const ANTIGRAVITY_APP_HUB = /--subclient_type[=\s]+hub\b/;
9313
+ /** Does the process chain run through the Antigravity desktop app? Needs command lines; false without them. */
9314
+ function isAntigravityApp(entries) {
9315
+ return entries.some((e) => e.command !== void 0 && (ANTIGRAVITY_APP_HUB.test(e.command) || ANTIGRAVITY_APP_EXE.test(e.command)));
9316
+ }
8547
9317
  const norm = (text) => text.replaceAll("\\", "/").toLowerCase();
8548
9318
  /** Split a command line into tokens, keeping quoted parts together and dropping the quotes. */
8549
9319
  function tokens(command) {
@@ -8696,6 +9466,22 @@ async function readTable(io, timeoutMs) {
8696
9466
  return out === null ? null : parseProcessTable(out);
8697
9467
  }
8698
9468
  /**
9469
+ * Every process with its command line, from the same one query the ancestry walk uses (the
9470
+ * Windows Script Host or CIM on Windows, `ps` elsewhere). Null when the table cannot be read.
9471
+ */
9472
+ async function readProcessList(io = defaultProcessIo, timeoutMs = 5e3) {
9473
+ try {
9474
+ const table = await readTable(io, timeoutMs);
9475
+ if (!table || table.size === 0) return null;
9476
+ return [...table].map(([pid, row]) => row.command === void 0 ? { pid } : {
9477
+ pid,
9478
+ command: row.command
9479
+ });
9480
+ } catch {
9481
+ return null;
9482
+ }
9483
+ }
9484
+ /**
8699
9485
  * The command line of a process as one string, or null when the OS does not say (the process is
8700
9486
  * gone, or the query was denied). A null answer means "unknown", never "not the daemon".
8701
9487
  */
@@ -8885,6 +9671,250 @@ async function detectRepo(cwd, fs) {
8885
9671
  basename: baseName(cwd)
8886
9672
  };
8887
9673
  }
9674
+ function globMatch(glob, text) {
9675
+ return new RegExp(`^${glob.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "s").test(text);
9676
+ }
9677
+ /** Does any rule allow a tool call of this kind and title? A call with no kind is `other`. */
9678
+ function isAllowed(rules, call) {
9679
+ const kind = call.kind ?? "other";
9680
+ const title = call.title ?? "";
9681
+ return rules.some((r) => (r.kind === "*" || r.kind === kind) && (r.title === void 0 || globMatch(r.title, title)));
9682
+ }
9683
+ const WORKER_ACCESS = [
9684
+ "read",
9685
+ "edit",
9686
+ "full"
9687
+ ];
9688
+ function parseWorkerAccess(s) {
9689
+ const v = s.trim().toLowerCase();
9690
+ return WORKER_ACCESS.includes(v) ? v : void 0;
9691
+ }
9692
+ const READ_KINDS = [
9693
+ "read",
9694
+ "search",
9695
+ "think"
9696
+ ];
9697
+ const EDIT_KINDS = [
9698
+ ...READ_KINDS,
9699
+ "edit",
9700
+ "move",
9701
+ "fetch"
9702
+ ];
9703
+ /** The allow rules a preset stands for. */
9704
+ function accessRules(access) {
9705
+ if (access === "full") return [{ kind: "*" }];
9706
+ return (access === "read" ? READ_KINDS : EDIT_KINDS).map((kind) => ({ kind }));
9707
+ }
9708
+ const SAFE_READ_COMMANDS = new Set([
9709
+ "ls",
9710
+ "dir",
9711
+ "pwd",
9712
+ "cat",
9713
+ "type",
9714
+ "head",
9715
+ "tail",
9716
+ "wc",
9717
+ "tree",
9718
+ "stat",
9719
+ "Get-ChildItem",
9720
+ "gci",
9721
+ "Get-Content",
9722
+ "Get-Item",
9723
+ "Get-Location",
9724
+ "Test-Path",
9725
+ "Resolve-Path"
9726
+ ].map((c) => c.toLowerCase()));
9727
+ const MAX_COMMAND_CHARS = 500;
9728
+ const TITLE_VERB = /^(?:execute|executing|run|running|command|shell)\b:?\s+/i;
9729
+ const SHELL_WRAPPER = /^(?:cmd\s+\/c|powershell\s+-command|pwsh\s+-c|bash\s+-lc|sh\s+-c)\s+/i;
9730
+ /**
9731
+ * Is the whole title one simple read-only command, such as `ls -la` or `bash -lc "cat a.txt"`?
9732
+ * Anything that chains, redirects, pipes or substitutes is not.
9733
+ */
9734
+ function isSafeReadCommand(title) {
9735
+ if (title.length > MAX_COMMAND_CHARS) return false;
9736
+ let inner = title.trim();
9737
+ inner = inner.replace(TITLE_VERB, "");
9738
+ if (/^`[^`]+`$/.test(inner)) inner = inner.slice(1, -1).trim();
9739
+ if (/[;&|><`()\n\r]/.test(inner) || inner.includes("${")) return false;
9740
+ if (/-exec/i.test(inner)) return false;
9741
+ const wrapper = SHELL_WRAPPER.exec(inner);
9742
+ if (wrapper) {
9743
+ inner = inner.slice(wrapper[0].length).trim();
9744
+ const q = inner[0];
9745
+ if ((q === "\"" || q === "'") && inner.length >= 2 && inner.endsWith(q)) inner = inner.slice(1, -1).trim();
9746
+ }
9747
+ const first = inner.split(/\s+/)[0] ?? "";
9748
+ return SAFE_READ_COMMANDS.has(first.toLowerCase());
9749
+ }
9750
+ /** May a worker with this access, make this tool call without asking? */
9751
+ function accessAllows(access, call) {
9752
+ if (access === "full") return true;
9753
+ return isAllowed(accessRules(access), call) || call.kind === "execute" && isSafeReadCommand(call.title ?? "");
9754
+ }
9755
+ const MAX_NAME = 200;
9756
+ const CONTROL = /\p{Cc}/u;
9757
+ /**
9758
+ * A model or effort name as given by a person or an agent: trimmed, non-empty, bounded, with no
9759
+ * control characters (it ends up on a command line and in a terminal).
9760
+ */
9761
+ function cleanModelName(v) {
9762
+ if (typeof v !== "string") return void 0;
9763
+ const s = v.trim();
9764
+ return s.length > 0 && s.length <= MAX_NAME && !CONTROL.test(s) ? s : void 0;
9765
+ }
9766
+ /**
9767
+ * One item of a menu a CLI offered: a value with a control character is dropped, a name has them
9768
+ * taken out (and falls back to the value when nothing is left).
9769
+ */
9770
+ function menuItem(value, name) {
9771
+ if (typeof value !== "string" || value === "" || CONTROL.test(value)) return void 0;
9772
+ const shown = typeof name === "string" ? name.replace(/\p{Cc}+/gu, " ").trim() : "";
9773
+ return {
9774
+ value,
9775
+ name: shown === "" ? value : shown
9776
+ };
9777
+ }
9778
+ /** Parse the `workerModels` settings value; anything malformed is dropped. */
9779
+ function parseWorkerModels(v) {
9780
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return {};
9781
+ const out = {};
9782
+ for (const cli of CLI_KINDS) {
9783
+ const c = v[cli];
9784
+ if (typeof c !== "object" || c === null) continue;
9785
+ const model = cleanModelName(c.model);
9786
+ const effort = cleanModelName(c.effort);
9787
+ if (model || effort) out[cli] = {
9788
+ ...model ? { model } : {},
9789
+ ...effort ? { effort } : {}
9790
+ };
9791
+ }
9792
+ return out;
9793
+ }
9794
+ /** The worker's model and effort: each field from the request, else the user's default. */
9795
+ function resolveWorkerModel(requested, defaults) {
9796
+ const model = cleanModelName(requested?.model) ?? cleanModelName(defaults?.model);
9797
+ const effort = cleanModelName(requested?.effort) ?? cleanModelName(defaults?.effort);
9798
+ return {
9799
+ ...model ? { model } : {},
9800
+ ...effort ? { effort } : {}
9801
+ };
9802
+ }
9803
+ const MODEL_IDS = ["model"];
9804
+ const EFFORT_IDS = [
9805
+ "effort",
9806
+ "reasoning_effort",
9807
+ "thought_level"
9808
+ ];
9809
+ /** The ACP session config option for `kind`: by category, else by a known id. */
9810
+ function findModelOption(options, kind) {
9811
+ if (!Array.isArray(options)) return void 0;
9812
+ const list = options;
9813
+ const category = kind === "model" ? "model" : "thought_level";
9814
+ const ids = kind === "model" ? MODEL_IDS : EFFORT_IDS;
9815
+ const o = list.find((x) => x?.category === category) ?? list.find((x) => typeof x?.id === "string" && ids.includes(x.id));
9816
+ if (!o || typeof o.id !== "string") return void 0;
9817
+ const flat = (Array.isArray(o.options) ? o.options : []).flatMap((x) => {
9818
+ const item = x;
9819
+ return Array.isArray(item?.options) ? item.options : [x];
9820
+ });
9821
+ const values = [];
9822
+ for (const x of flat) {
9823
+ const item = menuItem(x?.value, x?.name);
9824
+ if (item) values.push(item);
9825
+ }
9826
+ return {
9827
+ id: o.id,
9828
+ ...typeof o.currentValue === "string" && !CONTROL.test(o.currentValue) ? { current: o.currentValue } : {},
9829
+ values
9830
+ };
9831
+ }
9832
+ /** The menu a CLI offers, from its ACP session config options. */
9833
+ function menuFromConfigOptions(options, at) {
9834
+ const m = findModelOption(options, "model");
9835
+ const e = findModelOption(options, "effort");
9836
+ return {
9837
+ models: m?.values ?? [],
9838
+ efforts: e?.values ?? [],
9839
+ current: {
9840
+ ...m?.current ? { model: m.current } : {},
9841
+ ...e?.current ? { effort: e.current } : {}
9842
+ },
9843
+ at
9844
+ };
9845
+ }
9846
+ /** Short label for a card: `sonnet · high`, or undefined when nothing is known. */
9847
+ function modelLabel(c) {
9848
+ const parts = [c?.model, c?.effort].filter((x) => !!x);
9849
+ return parts.length > 0 ? parts.join(" · ") : void 0;
9850
+ }
9851
+ function parseItems(v) {
9852
+ if (!Array.isArray(v)) return [];
9853
+ return v.flatMap((x) => {
9854
+ if (typeof x !== "object" || x === null) return [];
9855
+ const item = menuItem(x.value, x.name);
9856
+ return item ? [item] : [];
9857
+ });
9858
+ }
9859
+ /** Read the remembered menus (`dataPaths(...).workerModels`). Missing or malformed: none. */
9860
+ function readModelMenus(path) {
9861
+ try {
9862
+ const v = JSON.parse(readFileSync(path, "utf8"));
9863
+ if (typeof v !== "object" || v === null) return {};
9864
+ const out = {};
9865
+ for (const cli of CLI_KINDS) {
9866
+ const m = v[cli];
9867
+ if (typeof m !== "object" || m === null) continue;
9868
+ const cur = m.current ?? {};
9869
+ const model = cleanModelName(cur.model);
9870
+ const effort = cleanModelName(cur.effort);
9871
+ out[cli] = {
9872
+ models: parseItems(m.models),
9873
+ efforts: parseItems(m.efforts),
9874
+ current: {
9875
+ ...model ? { model } : {},
9876
+ ...effort ? { effort } : {}
9877
+ },
9878
+ at: typeof m.at === "string" ? m.at : ""
9879
+ };
9880
+ }
9881
+ return out;
9882
+ } catch {
9883
+ return {};
9884
+ }
9885
+ }
9886
+ /** Remember the menu of one CLI. Written atomically; failures are ignored (it is a cache). */
9887
+ function writeModelMenu(path, cli, menu) {
9888
+ try {
9889
+ const all = {
9890
+ ...readModelMenus(path),
9891
+ [cli]: menu
9892
+ };
9893
+ mkdirSync(dirname(path), {
9894
+ recursive: true,
9895
+ mode: 448
9896
+ });
9897
+ const tmp = `${path}.${process.pid}.tmp`;
9898
+ writeFileSync(tmp, `${JSON.stringify(all, null, 2)}\n`, { mode: 384 });
9899
+ renameSync(tmp, path);
9900
+ } catch {}
9901
+ }
9902
+ const WORKER_UNANSWERED = ["deny", "allow"];
9903
+ /** What workers may do, with the default when it was never chosen. */
9904
+ function workerAccessOf(s) {
9905
+ return s.workerAccess ?? "full";
9906
+ }
9907
+ /** What happens to an unanswered request, with the default when it was never chosen. */
9908
+ function workerUnansweredOf(s) {
9909
+ return s.workerUnanswered ?? "deny";
9910
+ }
9911
+ const WORKER_ASK_TIMEOUT_CHOICES = [
9912
+ 60,
9913
+ 120,
9914
+ 300
9915
+ ];
9916
+ /** Seconds a worker waits for its spawner's answer. */
9917
+ const workerAskTimeoutOf = (s) => s.workerAskTimeoutSec ?? 120;
8888
9918
  /** Read the settings. A missing, unreadable or malformed file gives no settings. */
8889
9919
  function readSettings(path) {
8890
9920
  try {
@@ -8893,7 +9923,13 @@ function readSettings(path) {
8893
9923
  const o = v;
8894
9924
  return {
8895
9925
  ...typeof o.acpAdapterNpx === "boolean" ? { acpAdapterNpx: o.acpAdapterNpx } : {},
8896
- ...typeof o.leadCli === "string" && CLI_KINDS.includes(o.leadCli) ? { leadCli: o.leadCli } : {}
9926
+ ...typeof o.leadCli === "string" && CLI_KINDS.includes(o.leadCli) ? { leadCli: o.leadCli } : {},
9927
+ ...Array.isArray(o.tools) ? { tools: [...new Set(o.tools.filter((t) => typeof t === "string" && CLI_KINDS.includes(t)))] } : {},
9928
+ ...typeof o.wakeBeforeFirstPrompt === "boolean" ? { wakeBeforeFirstPrompt: o.wakeBeforeFirstPrompt } : {},
9929
+ ...typeof o.workerAccess === "string" && parseWorkerAccess(o.workerAccess) ? { workerAccess: parseWorkerAccess(o.workerAccess) } : {},
9930
+ ...WORKER_ASK_TIMEOUT_CHOICES.includes(o.workerAskTimeoutSec) ? { workerAskTimeoutSec: o.workerAskTimeoutSec } : {},
9931
+ ...WORKER_UNANSWERED.includes(o.workerUnanswered) ? { workerUnanswered: o.workerUnanswered } : {},
9932
+ ...Object.keys(parseWorkerModels(o.workerModels)).length > 0 ? { workerModels: parseWorkerModels(o.workerModels) } : {}
8897
9933
  };
8898
9934
  } catch {
8899
9935
  return {};
@@ -8910,10 +9946,12 @@ function writeSettings(path, patch) {
8910
9946
  recursive: true,
8911
9947
  mode: 448
8912
9948
  });
8913
- writeFileSync(path, `${JSON.stringify({
9949
+ const next = {
8914
9950
  ...current,
8915
9951
  ...patch
8916
- }, null, 2)}\n`, { mode: 384 });
9952
+ };
9953
+ for (const [k, v] of Object.entries(next)) if (v === null) delete next[k];
9954
+ writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`, { mode: 384 });
8917
9955
  try {
8918
9956
  chmodSync(path, 384);
8919
9957
  } catch {}
@@ -9048,6 +10086,13 @@ const recordFiles = (dataDir) => {
9048
10086
  return [];
9049
10087
  }
9050
10088
  };
10089
+ /** The record of the worker whose host registered `sessionId`, whatever its file is named. */
10090
+ function spawnRecordOfSession(dataDir, sessionId) {
10091
+ for (const path of recordFiles(dataDir)) {
10092
+ const rec = readSpawnRecord(path);
10093
+ if (rec?.sessionId === sessionId) return rec;
10094
+ }
10095
+ }
9051
10096
  /**
9052
10097
  * Records of spawned sessions that are still running. Records of sessions that ended are deleted
9053
10098
  * as they are found.
@@ -9107,7 +10152,6 @@ function decodeAcpLaunchSpec(text) {
9107
10152
  return x;
9108
10153
  };
9109
10154
  if (!strings(o.args)) throw new Error("The ACP launch file has no \"args\".");
9110
- if (!strings(o.allow)) throw new Error("The ACP launch file has no \"allow\".");
9111
10155
  const mcp = o.mcp;
9112
10156
  return {
9113
10157
  file: str("file"),
@@ -9120,13 +10164,18 @@ function decodeAcpLaunchSpec(text) {
9120
10164
  ...typeof o.task === "string" && o.task !== "" ? { task: o.task } : {},
9121
10165
  ...typeof o.spawnedBy === "string" ? { spawnedBy: o.spawnedBy } : {},
9122
10166
  from: str("from"),
9123
- allow: o.allow,
9124
- ...typeof o.fullAccessMode === "string" && o.fullAccessMode !== "" ? { fullAccessMode: o.fullAccessMode } : {},
10167
+ access: (typeof o.access === "string" ? parseWorkerAccess(o.access) : void 0) ?? "full",
10168
+ ...typeof o.mode === "string" && o.mode !== "" ? { mode: o.mode } : {},
9125
10169
  ...mcp && typeof mcp.command === "string" && strings(mcp.args) ? { mcp: {
9126
10170
  command: mcp.command,
9127
10171
  args: mcp.args
9128
10172
  } } : {},
9129
- ...typeof o.setupTimeoutMs === "number" && o.setupTimeoutMs > 0 ? { setupTimeoutMs: o.setupTimeoutMs } : {}
10173
+ askTimeoutMs: typeof o.askTimeoutMs === "number" && o.askTimeoutMs > 0 ? o.askTimeoutMs : 12e4,
10174
+ ...o.unanswered === "allow" || o.unanswered === "deny" ? { unanswered: o.unanswered } : {},
10175
+ ...typeof o.setupTimeoutMs === "number" && o.setupTimeoutMs > 0 ? { setupTimeoutMs: o.setupTimeoutMs } : {},
10176
+ ...cleanModelName(o.model) ? { model: cleanModelName(o.model) } : {},
10177
+ ...cleanModelName(o.effort) ? { effort: cleanModelName(o.effort) } : {},
10178
+ ...typeof o.modelMenuPath === "string" && o.modelMenuPath !== "" ? { modelMenuPath: o.modelMenuPath } : {}
9130
10179
  };
9131
10180
  }
9132
10181
  /** Write an ACP launch file readable by the owner only. */
@@ -9139,65 +10188,6 @@ function takeAcpLaunchFile(path) {
9139
10188
  rmSync(path, { force: true });
9140
10189
  return spec;
9141
10190
  }
9142
- const ACP_TOOL_KINDS = [
9143
- "read",
9144
- "edit",
9145
- "delete",
9146
- "move",
9147
- "search",
9148
- "execute",
9149
- "think",
9150
- "fetch",
9151
- "switch_mode",
9152
- "other"
9153
- ];
9154
- const MAX_RULES = 32;
9155
- /**
9156
- * Parse `--allow` patterns: comma separated, each `<kind>` or `<kind>:<title glob>`, where kind is
9157
- * an ACP tool kind or `*`. Examples: `read,search`, `execute:npm test*`, `*`.
9158
- */
9159
- function parseAllowPatterns(input) {
9160
- const rules = [];
9161
- for (const raw of input.flatMap((s) => s.split(","))) {
9162
- const item = raw.trim();
9163
- if (item === "") continue;
9164
- const colon = item.indexOf(":");
9165
- const kind = (colon === -1 ? item : item.slice(0, colon)).trim();
9166
- const title = colon === -1 ? void 0 : item.slice(colon + 1).trim();
9167
- if (kind !== "*" && !ACP_TOOL_KINDS.includes(kind)) return {
9168
- ok: false,
9169
- message: `"${kind}" is not a tool kind. Use one of: ${ACP_TOOL_KINDS.join(", ")}, or *.`
9170
- };
9171
- if (title === "") return {
9172
- ok: false,
9173
- message: `"${item}" has an empty title pattern.`
9174
- };
9175
- rules.push({
9176
- kind,
9177
- ...title !== void 0 ? { title } : {}
9178
- });
9179
- }
9180
- if (rules.length > MAX_RULES) return {
9181
- ok: false,
9182
- message: `At most ${MAX_RULES} allow patterns.`
9183
- };
9184
- return {
9185
- ok: true,
9186
- rules
9187
- };
9188
- }
9189
- const formatAllowRule = (r) => r.title === void 0 ? r.kind : `${r.kind}:${r.title}`;
9190
- function globMatch(glob, text) {
9191
- return new RegExp(`^${glob.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "s").test(text);
9192
- }
9193
- /** Does any rule allow a tool call of this kind and title? A call with no kind is `other`. */
9194
- function isAllowed(rules, call) {
9195
- const kind = call.kind ?? "other";
9196
- const title = call.title ?? "";
9197
- return rules.some((r) => (r.kind === "*" || r.kind === kind) && (r.title === void 0 || globMatch(r.title, title)));
9198
- }
9199
- /** The allow rules a worker gets when none were given: every kind of tool call. */
9200
- const DEFAULT_ALLOW_RULES = [{ kind: "*" }];
9201
10191
  /** Why a CLI cannot be started the way the caller asked. The message is shown to the user. */
9202
10192
  var SpawnError = class extends Error {
9203
10193
  fix;
@@ -9342,6 +10332,7 @@ async function runLaunchFile(path) {
9342
10332
  const child = spawn(spec.file, spec.args, {
9343
10333
  cwd: spec.cwd,
9344
10334
  stdio: "inherit",
10335
+ env: Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== "CONVENO_ACP_WORKER")),
9345
10336
  ...spec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
9346
10337
  });
9347
10338
  child.once("error", (e) => {
@@ -9460,6 +10451,10 @@ function realSpawnDeps(opts) {
9460
10451
  isDir: isDirectory,
9461
10452
  which: (name) => findOnPath(name, env, platform, platform === "win32" ? entryExists : void 0),
9462
10453
  acpNpxConsent: () => readSettings(dataPaths(platform, opts.dataDir).settings).acpAdapterNpx === true,
10454
+ workerAccess: () => readSettings(dataPaths(platform, opts.dataDir).settings).workerAccess,
10455
+ workerModels: () => readSettings(dataPaths(platform, opts.dataDir).settings).workerModels,
10456
+ workerUnanswered: () => readSettings(dataPaths(platform, opts.dataDir).settings).workerUnanswered ?? "deny",
10457
+ workerAskTimeoutSec: () => workerAskTimeoutOf(readSettings(dataPaths(platform, opts.dataDir).settings)),
9463
10458
  repoExists: existsSync,
9464
10459
  killProcess: (pid) => killProcessTree(pid, platform),
9465
10460
  prepareFiles: (dataDir) => {
@@ -9536,100 +10531,14 @@ function realSpawnDeps(opts) {
9536
10531
  })
9537
10532
  };
9538
10533
  }
9539
- const SPAWN_TABLE = {
9540
- claude: {
9541
- binaries: ["claude"],
9542
- interactive: (task) => task === void 0 ? [] : [task],
9543
- interactivePrompt: true,
9544
- docs: ["https://code.claude.com/docs/en/cli-reference (claude \"query\")"],
9545
- acp: {
9546
- binaries: ["claude-agent-acp"],
9547
- args: [],
9548
- adapterPackage: "@agentclientprotocol/claude-agent-acp",
9549
- fullAccessMode: "bypassPermissions",
9550
- note: "Claude Code has no ACP server of its own. The ACP project's npm package @agentclientprotocol/claude-agent-acp provides one and uses the Claude Code sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
9551
- docs: ["https://github.com/agentclientprotocol/claude-agent-acp (Apache-2.0, maintained by the ACP project)", "https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp (bin claude-agent-acp)"]
9552
- }
9553
- },
9554
- codex: {
9555
- binaries: ["codex"],
9556
- interactive: (task) => task === void 0 ? [] : [task],
9557
- interactivePrompt: true,
9558
- docs: ["https://developers.openai.com/codex/cli/reference (codex [PROMPT])", "reference/src/codex/codex-rs/tui/src/cli.rs (the optional PROMPT argument)"],
9559
- acp: {
9560
- binaries: ["codex-acp"],
9561
- args: [],
9562
- adapterPackage: "@agentclientprotocol/codex-acp",
9563
- fullAccessMode: "agent-full-access",
9564
- note: "Codex has no ACP server of its own. The ACP project's npm package @agentclientprotocol/codex-acp provides one and uses the Codex sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
9565
- docs: [
9566
- "https://github.com/agentclientprotocol/codex-acp (Apache-2.0, built on the Codex app server)",
9567
- "https://www.npmjs.com/package/@agentclientprotocol/codex-acp (bin codex-acp)",
9568
- "reference/src/codex/codex-rs/app-server (the app server it drives)"
9569
- ]
9570
- }
9571
- },
9572
- opencode: {
9573
- binaries: ["opencode"],
9574
- interactive: (task) => task === void 0 ? [] : ["--prompt", task],
9575
- interactivePrompt: true,
9576
- docs: ["https://opencode.ai/docs/cli/ (the TUI --prompt flag)", "reference/src/opencode/packages/cli/src/commands/commands.ts at v2.4.3 (--prompt)"],
9577
- acp: {
9578
- binaries: ["opencode"],
9579
- args: ["acp"],
9580
- note: "",
9581
- docs: ["https://opencode.ai/docs/cli/acp/ (opencode acp, stdio, protocol version 1)", "reference/src/opencode/packages/opencode/src/cli/cmd/acp.ts"]
9582
- }
9583
- },
9584
- cursor: {
9585
- binaries: ["cursor-agent", "agent"],
9586
- interactive: (task) => task === void 0 ? [] : [task],
9587
- interactivePrompt: true,
9588
- docs: ["https://cursor.com/docs/cli/using.md (agent \"prompt\")"],
9589
- acp: {
9590
- binaries: ["cursor-agent", "agent"],
9591
- args: ["acp"],
9592
- note: "Sign in once with `agent login` first.",
9593
- docs: ["https://cursor.com/docs/cli/acp (agent acp, stdio)"]
9594
- }
9595
- },
9596
- copilot: {
9597
- binaries: ["copilot"],
9598
- interactive: (task) => task === void 0 ? [] : [`--interactive=${task}`],
9599
- interactivePrompt: true,
9600
- docs: ["https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-command-reference (-i/--interactive PROMPT)"],
9601
- acp: {
9602
- binaries: ["copilot"],
9603
- args: ["--acp", "--stdio"],
9604
- note: "ACP support in Copilot CLI is in public preview.",
9605
- docs: ["https://docs.github.com/en/copilot/reference/copilot-cli-reference/acp-server (copilot --acp --stdio)"]
9606
- }
9607
- },
9608
- antigravity: {
9609
- binaries: ["agy"],
9610
- interactive: () => [],
9611
- interactivePrompt: false,
9612
- docs: ["https://antigravity.google/docs/cli/acp (agy)"],
9613
- acp: {
9614
- binaries: ["agy"],
9615
- args: ["acp"],
9616
- note: "Uses the sign-in cached by an interactive `agy`.",
9617
- docs: ["https://antigravity.google/docs/cli/acp (agy acp, stdio)"]
9618
- }
9619
- },
9620
- grok: {
9621
- binaries: ["grok"],
9622
- interactive: (task) => task === void 0 ? [] : [task],
9623
- interactivePrompt: true,
9624
- docs: ["reference/src/grok-build/crates/codegen/xai-grok-pager/src/app/cli.rs (prompt)"],
9625
- acp: {
9626
- binaries: ["grok"],
9627
- args: ["agent", "stdio"],
9628
- note: "",
9629
- docs: ["reference/src/grok-build/crates/codegen/xai-grok-pager/src/app/cli.rs (grok agent stdio)", "reference/src/grok-build/crates/codegen/xai-grok-pager/docs/user-guide/15-agent-mode.md"]
9630
- }
9631
- }
9632
- };
10534
+ /**
10535
+ * What `conveno spawn` runs for each CLI, from the descriptors in `clis/`. Every flag there comes
10536
+ * from the CLI's own documentation or source; `docs` names where.
10537
+ */
10538
+ const SPAWN_TABLE = Object.fromEntries(CLI_DESCRIPTORS.map((d) => [d.id, {
10539
+ binaries: d.binaries,
10540
+ ...d.spawn
10541
+ }]));
9633
10542
  const SPAWN_CLIS = Object.keys(SPAWN_TABLE);
9634
10543
  const isSpawnCli = (cli) => Object.hasOwn(SPAWN_TABLE, cli);
9635
10544
  /** The CLIs that have an ACP server Conveno can drive. */
@@ -9642,10 +10551,10 @@ function safePrompt(task) {
9642
10551
  return task.startsWith("-") ? `Task: ${task}` : task;
9643
10552
  }
9644
10553
  /** Arguments (after the program) for a window spawn: the interactive CLI, with the first task. */
9645
- function buildCliArgs(cli, task) {
10554
+ function buildCliArgs(cli, task, choice = {}) {
9646
10555
  const spec = SPAWN_TABLE[cli];
9647
10556
  if (!spec) throw new Error(`No spawn entry for "${cli}".`);
9648
- return spec.interactive(spec.interactivePrompt && task !== void 0 ? safePrompt(task) : void 0);
10557
+ return [...spec.modelArgs?.(choice) ?? [], ...spec.interactive(spec.interactivePrompt && task !== void 0 ? safePrompt(task) : void 0)];
9649
10558
  }
9650
10559
  const NO_TERMINAL_FIX = "Run the session in the background (drop --window), or start the CLI yourself.";
9651
10560
  /** Linux terminals, in the order tried. Each says how to run a program in a directory. */
@@ -9870,10 +10779,8 @@ async function spawnSession(deps, req) {
9870
10779
  isDir: deps.isDir,
9871
10780
  confineToHome: req.confineToHome
9872
10781
  });
9873
- const allow = parseAllowPatterns(req.allow ?? []);
9874
- if (!allow.ok) throw new SpawnError(allow.message, "Fix the --allow patterns.");
9875
10782
  const window = req.window === true;
9876
- if (window && allow.rules.length > 0) throw new SpawnError("--allow only applies to a background worker.", "Drop --window, or drop --allow.");
10783
+ const access = req.access ?? deps.workerAccess?.() ?? "full";
9877
10784
  const acpResolved = spec.acp ? resolveAcpProgram(cli, spec.acp, {
9878
10785
  env: deps.env,
9879
10786
  which: deps.which,
@@ -9906,7 +10813,12 @@ async function spawnSession(deps, req) {
9906
10813
  }))];
9907
10814
  const repo = await detectRepo(cwd, { exists: deps.repoExists });
9908
10815
  const name = req.name !== void 0 ? validateRename(newSessionId(), req.name, named) : generateSessionName(kind.data, repo.basename, named);
9909
- const plan = planProgram(program, window ? buildCliArgs(cli, task) : [...acpRun?.args ?? [], ...spec.acp?.args ?? []], {
10816
+ const chosen = resolveWorkerModel({
10817
+ model: req.model,
10818
+ effort: req.effort
10819
+ }, deps.workerModels?.()?.[cli]);
10820
+ if (window && [chosen.model, chosen.effort].some((v) => v?.startsWith("-"))) throw new SpawnError("A model or effort name cannot start with a dash in a window, the CLI would read it as a flag.");
10821
+ const plan = planProgram(program, window ? buildCliArgs(cli, task, chosen) : [...acpRun?.args ?? [], ...spec.acp?.args ?? []], {
9910
10822
  platform: deps.platform,
9911
10823
  env: deps.env
9912
10824
  });
@@ -9943,8 +10855,8 @@ async function spawnSession(deps, req) {
9943
10855
  ...task !== void 0 ? { task } : {},
9944
10856
  ...req.requester ? { spawnedBy: req.requester.id } : {},
9945
10857
  from: req.requester?.name ?? "the user",
9946
- allow: allow.rules.map(formatAllowRule),
9947
- ...allow.rules.length === 0 && spec.acp?.fullAccessMode ? { fullAccessMode: spec.acp.fullAccessMode } : {},
10858
+ access,
10859
+ ...spec.acp?.modes?.[access] ? { mode: spec.acp.modes[access] } : {},
9948
10860
  mcp: {
9949
10861
  command: node,
9950
10862
  args: [
@@ -9954,6 +10866,11 @@ async function spawnSession(deps, req) {
9954
10866
  cli
9955
10867
  ]
9956
10868
  },
10869
+ unanswered: deps.workerUnanswered?.() === "allow" ? "allow" : "deny",
10870
+ askTimeoutMs: (deps.workerAskTimeoutSec?.() ?? 120) * 1e3,
10871
+ ...chosen.model ? { model: chosen.model } : {},
10872
+ ...chosen.effort ? { effort: chosen.effort } : {},
10873
+ modelMenuPath: dataPaths(deps.platform, deps.dataDir).workerModels,
9957
10874
  ...acpRun?.source.startsWith("npx:") ? { setupTimeoutMs: NPX_SETUP_TIMEOUT_MS } : {}
9958
10875
  });
9959
10876
  run = await deps.launchBackground({
@@ -10000,7 +10917,7 @@ async function spawnSession(deps, req) {
10000
10917
  }
10001
10918
  req.onProgress?.(window ? `Opened ${terminal}. Waiting for ${cli} to register.` : `Started ${cli} over ACP in the background (host pid ${run?.pid}). Waiting for it to register.`);
10002
10919
  const viaNpx = !window && acpRun?.source.startsWith("npx:") === true;
10003
- if (viaNpx) req.onProgress?.(`Fetching the ${cli} adapter with npx (first run downloads it and can take a few minutes).`);
10920
+ if (viaNpx) req.onProgress?.(`Starting the ${cli} adapter with npx (only the first run downloads it).`);
10004
10921
  const session = await waitForRegistration(deps, {
10005
10922
  name,
10006
10923
  cli,
@@ -10081,4 +10998,4 @@ async function waitForRegistration(deps, w) {
10081
10998
  await deps.sleep(250);
10082
10999
  }
10083
11000
  }
10084
- export { isFromOwner as $, uninstallLauncher as $t, completeLogin as A, newSessionId as An, readSpawnRecord as At, editJson as B, literal as Bn, runLaunchFile as Bt, bindAccountDevice as C, ipcMethods as Cn, proofsMatch as Ct, clientProof as D, makeResult as Dn, readCommandLine as Dt, clearOrchestrator as E, makeEventNotification as En, readAncestry as Et, dataPaths as F, socketPathTooLongMessage as Fn, requeueMessages as Ft, fetchAccountStatus as G, spawnSession as Gt, endTurnContinuation as H, object as Hn, sameJson as Ht, decideAutoContinue as I, _enum as In, requeueOwnMessages as It, formatHookContext as J, takeAcpLaunchFile as Jt, findOnPath as K, startTurnContext as Kt, defaultProcessIo as L, array as Ln, resolveAcpProgram as Lt, currentAccessToken as M, parseRelayFrame as Mn, renderBody as Mt, daemonProof as N, safeParse as Nn, requestDeviceCode as Nt, compareVersions as O, newDeviceId as On, readInbox as Ot, dataDir as P, sanitizeLine as Pn, requeueEntries as Pt, isAllowed as Q, turnHops as Qt, detectRepo as R, boolean as Rn, resolveRecipient as Rt, baseName as S, encodeFrame as Sn, pollDeviceCode as St, claimSpawnRecord as T, makeError as Tn, readAccountTokens as Tt, evaluateLiveness as U, string as Un, senderOf as Ut, effectiveHolder as V, number as Vn, runWaker as Vt, existedBefore as W, spawnRecordPath as Wt, generateSessionName as X, takeWithinChars as Xt, formatInbox as Y, takeWithinBytes as Yt, holderAfterDeparture as Z, tooManyUnreadMessage as Zt, agentCommand as _, RpcResponse as _n, pendingHookContext as _t, FROM_USER_NOTICE as a, CLI_KINDS as an, launcherText as at, autoCandidates as b, createLineDecoder as bn, planProgram as bt, ORCHESTRATOR_TASK_NOTICE as c, EVENT_NAMES as cn, markDelivered as ct, SPAWN_TABLE as d, Message as dn, ownSession as dt, updateSpawnRecord as en, isObject as et, SpawnError as f, MessageId as fn, parseAllowPatterns as ft, adapterNpxCommand as g, RpcErrorCode as gn, pendingForInjection as gt, adapterInstallCommand as h, RelayPayload as hn, parsePs1ShimTarget as ht, DEFAULT_ALLOW_RULES as i, writeSettings as in, launcherPath as it, createWmiWalker as j, parseIpcRequest as jn, realSpawnDeps as jt, compatStatus as k, newMessageId as kn, readSettings as kt, RESPONSE_BUDGET_BYTES as l, EVENT_NOTIFICATION_METHOD as ln, needsQuoting as lt, acpOverrideVar as m, PROTOCOL_VERSION as mn, parseCmdShimTarget as mt, AccountError as n, waitForWork as nn, jwtClaim as nt, HEARTBEAT_INTERVAL_MS as o, CliKind as on, loadJson as ot, ackEntries as p, OWNER_SESSION_ID as pn, parseCliVersion as pt, formatContinuation as q, statusAfterLiveness as qt, ConvenoError as r, waitForWorkBatch as rn, late as rt, NOT_FROM_USER_NOTICE as s, DeviceId as sn, logoutAccount as st, ACCOUNT_API as t, validateRename as tn, isOnline as tt, SPAWN_CLIS as u, EventPayload as un, newAuthNonce as ut, askedMarker as v, SESSION_NAME_PATTERN as vn, pinnedAdapter as vt, claimOrchestrator as w, isSocketPathTooLong as wn, putInList as wt, autoLimitsFromEnv as x, defaultSocketPath as xn, planSpawn as xt, attachAcpSession as y, SessionId as yn, planLauncher as yt, dropFromList as z, discriminatedUnion as zn, resolveWindowsCommand as zt };
11001
+ export { endTurnContinuation as $, SESSION_ENDED_TEXT as $n, readModelMenus as $t, baseName as A, validateRename as An, needsQuoting as At, compatStatus as B, CliKind as Bn, pendingTurn as Bt, agentCommand as C, takeAcpLaunchFile as Cn, number as Cr, leadLogPath as Ct, attachAcpSession as D, turnHops as Dn, markDelivered as Dt, askedMarker as E, tooManyUnreadMessage as En, logoutAccount as Et, clearOrchestrator as F, workerUnansweredOf as Fn, parseCmdShimTarget as Ft, dataDir as G, Message as Gn, planSpawn as Gt, createWmiWalker as H, EVENT_NAMES as Hn, pinnedAdapter as Ht, cliDeliveryTier as I, writeModelMenu as In, parsePs1ShimTarget as It, defaultProcessIo as J, PROTOCOL_VERSION as Jn, putInList as Jt, dataPaths as K, MessageId as Kn, pollDeviceCode as Kt, cliDescriptor as L, writePrivateFileSync as Ln, parseWorkerAccess as Lt, claimOrchestrator as M, waitForWorkBatch as Mn, oneWindowPerHost as Mt, claimSpawnRecord as N, workerAccessOf as Nn, ownSession as Nt, autoCandidates as O, uninstallLauncher as On, menuFromConfigOptions as Ot, cleanModelName as P, workerAskTimeoutOf as Pn, parseCliVersion as Pt, effectiveHolder as Q, RpcResponse as Qn, readInbox as Qt, clientProof as R, writeSettings as Rn, pendingForInjection as Rt, adapterNpxCommand as S, statusAfterLiveness as Sn, literal as Sr, leadLogLine as St, askedKey as T, takeWithinChars as Tn, string as Tr, loginAccountApi as Tt, currentAccessToken as U, EVENT_NOTIFICATION_METHOD as Un, planLauncher as Ut, completeLogin as V, DeviceId as Vn, pidAlive as Vt, daemonProof as W, EventPayload as Wn, planProgram as Wt, dropFromList as X, RelayPayload as Xn, readAncestry as Xt, detectRepo as Y, RELAY_CLIENT_NAME as Yn, readAccountTokens as Yt, editJson as Z, RpcErrorCode as Zn, readCommandLine as Zt, WORKER_UNANSWERED as _, signedInAccountApi as _n, socketPathTooLongMessage as _r, isOnline as _t, ConvenoError as a, renderBody as an, ipcMethods as ar, formatContinuation as at, acpOverrideVar as b, spawnSession as bn, boolean as br, launcherPath as bt, NOT_FROM_USER_NOTICE as c, requeueMessages as cn, makeEventNotification as cr, generateSessionName as ct, RESPONSE_BUDGET_BYTES as d, resolveWindowsCommand as dn, newMessageId as dr, hookLogPath as dt, readProcessList as en, SESSION_NAME_PATTERN as er, evaluateLiveness as et, SPAWN_CLIS as f, restrictToUser as fn, newSessionId as fr, hostAlive as ft, WORKER_ASK_TIMEOUT_CHOICES as g, senderOf as gn, sanitizeLine as gr, isObject as gt, WORKER_ACCESS as h, sameJson as hn, safeParse as hr, isFromOwner as ht, CLI_DESCRIPTORS as i, relayUrl as in, encodeFrame as ir, findOnPath as it, bindAccountDevice as j, waitForWork as jn, newAuthNonce as jt, autoLimitsFromEnv as k, updateSpawnRecord as kn, modelLabel as kt, NPX_SETUP_TIMEOUT_MS as l, resolveAcpProgram as ln, makeResult as lr, holderAfterDeparture as lt, SpawnError as m, runWaker as mn, parseRelayFrame as mr, isAntigravityApp as mt, CLAUDE_PENDING_TURN_FOLDER as n, readSpawnRecord as nn, createLineDecoder as nr, fetchAccountStatus as nt, FROM_USER_NOTICE as o, requestDeviceCode as on, isSocketPathTooLong as or, formatHookContext as ot, SPAWN_TABLE as p, runLaunchFile as pn, parseIpcRequest as pr, hostPidOf as pt, decideAutoContinue as q, OWNER_SESSION_ID as qn, proofsMatch as qt, CLIS as r, realSpawnDeps as rn, defaultSocketPath as rr, findModelOption as rt, HEARTBEAT_INTERVAL_MS as s, requeueEntries as sn, makeError as sr, formatInbox as st, AccountError as t, readSettings as tn, SessionId as tr, existedBefore as tt, ORCHESTRATOR_TASK_NOTICE as u, resolveRecipient as un, newDeviceId as ur, hookLogLine as ut, accessAllows as v, spawnRecordOfSession as vn, _enum as vr, jwtClaim as vt, appendHookLog as w, takeWithinBytes as wn, object as wr, loadJson as wt, adapterInstallCommand as x, startTurnContext as xn, discriminatedUnion as xr, launcherText as xt, ackEntries as y, spawnRecordPath as yn, array as yr, late as yt, compareVersions as z, CLI_KINDS as zn, pendingHookContext as zt };