@kmmao/happy-agent 0.5.4 → 0.7.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.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  var commander = require('commander');
4
+ var node_crypto = require('node:crypto');
4
5
  var node_os = require('node:os');
5
6
  var node_path = require('node:path');
6
7
  var node_fs = require('node:fs');
7
- var node_crypto = require('node:crypto');
8
8
  var tweetnacl = require('tweetnacl');
9
9
  var axios = require('axios');
10
10
  var qrcode = require('qrcode-terminal');
@@ -13,13 +13,33 @@ var socket_ioClient = require('socket.io-client');
13
13
  var child_process = require('child_process');
14
14
  var util = require('util');
15
15
  var promises = require('fs/promises');
16
- var crypto = require('crypto');
16
+ var crypto$1 = require('crypto');
17
17
  var path = require('path');
18
18
  var fs = require('fs');
19
19
  var os = require('os');
20
20
  var http = require('http');
21
+ var z = require('zod');
21
22
 
22
- var version = "0.5.4";
23
+ function _interopNamespaceDefault(e) {
24
+ var n = Object.create(null);
25
+ if (e) {
26
+ Object.keys(e).forEach(function (k) {
27
+ if (k !== 'default') {
28
+ var d = Object.getOwnPropertyDescriptor(e, k);
29
+ Object.defineProperty(n, k, d.get ? d : {
30
+ enumerable: true,
31
+ get: function () { return e[k]; }
32
+ });
33
+ }
34
+ });
35
+ }
36
+ n.default = e;
37
+ return Object.freeze(n);
38
+ }
39
+
40
+ var z__namespace = /*#__PURE__*/_interopNamespaceDefault(z);
41
+
42
+ var version = "0.7.0";
23
43
 
24
44
  function loadConfig() {
25
45
  const serverUrl = (process.env.HAPPY_SERVER_URL ?? "https://s.sangreal.code.xycloud.info:2443").replace(/\/+$/, "");
@@ -228,7 +248,7 @@ async function authLogin(config, opts) {
228
248
  }
229
249
  const startTime = Date.now();
230
250
  while (Date.now() - startTime < AUTH_TIMEOUT_MS) {
231
- await sleep(POLL_INTERVAL_MS);
251
+ await sleep$1(POLL_INTERVAL_MS);
232
252
  let result;
233
253
  try {
234
254
  const resp = await axios.post(`${config.serverUrl}/v1/auth/account/request`, {
@@ -272,7 +292,7 @@ async function authStatus(config) {
272
292
  console.log("- Action: Run `happy-agent auth login` to authenticate.");
273
293
  }
274
294
  }
275
- function sleep(ms) {
295
+ function sleep$1(ms) {
276
296
  return new Promise((resolve) => setTimeout(resolve, ms));
277
297
  }
278
298
 
@@ -308,6 +328,7 @@ function decryptSession(raw, creds) {
308
328
  active: raw.active,
309
329
  activeAt: raw.activeAt,
310
330
  metadata: decryptField(raw.metadata, encryption),
331
+ metadataVersion: raw.metadataVersion,
311
332
  agentState: decryptField(raw.agentState, encryption),
312
333
  dataEncryptionKey: raw.dataEncryptionKey,
313
334
  encryption
@@ -977,7 +998,7 @@ function registerAgentHandlers(rpcHandlerManager, workingDirectory, sessionId) {
977
998
  if (data.expectedHash !== null && data.expectedHash !== void 0) {
978
999
  try {
979
1000
  const existingBuffer = await promises.readFile(resolvedPath);
980
- const existingHash = crypto.createHash("sha256").update(existingBuffer).digest("hex");
1001
+ const existingHash = crypto$1.createHash("sha256").update(existingBuffer).digest("hex");
981
1002
  if (existingHash !== data.expectedHash) {
982
1003
  return {
983
1004
  success: false,
@@ -995,7 +1016,7 @@ function registerAgentHandlers(rpcHandlerManager, workingDirectory, sessionId) {
995
1016
  await promises.mkdir(dir, { recursive: true });
996
1017
  const buffer = Buffer.from(data.content, "base64");
997
1018
  await promises.writeFile(resolvedPath, buffer);
998
- const hash = crypto.createHash("sha256").update(buffer).digest("hex");
1019
+ const hash = crypto$1.createHash("sha256").update(buffer).digest("hex");
999
1020
  return { success: true, hash };
1000
1021
  } catch (error) {
1001
1022
  logger.debug("Failed to write file:", error);
@@ -1430,6 +1451,12 @@ class SessionClient extends node_events.EventEmitter {
1430
1451
  this.sessionId = opts.sessionId;
1431
1452
  this.encryptionKey = opts.encryptionKey;
1432
1453
  this.encryptionVariant = opts.encryptionVariant;
1454
+ if (opts.initialMetadata !== void 0) {
1455
+ this.metadata = opts.initialMetadata;
1456
+ }
1457
+ if (opts.initialMetadataVersion !== void 0) {
1458
+ this.metadataVersion = opts.initialMetadataVersion;
1459
+ }
1433
1460
  if (opts.initialAgentState !== void 0) {
1434
1461
  this.agentState = opts.initialAgentState;
1435
1462
  }
@@ -1482,6 +1509,9 @@ class SessionClient extends node_events.EventEmitter {
1482
1509
  getMetadata() {
1483
1510
  return this.metadata;
1484
1511
  }
1512
+ getMetadataVersion() {
1513
+ return this.metadataVersion;
1514
+ }
1485
1515
  getAgentState() {
1486
1516
  return this.agentState;
1487
1517
  }
@@ -1582,42 +1612,51 @@ class SessionClient extends node_events.EventEmitter {
1582
1612
  // -----------------------------------------------------------------------
1583
1613
  // New: OCC metadata/state updates
1584
1614
  // -----------------------------------------------------------------------
1585
- async updateMetadata(newMetadata) {
1615
+ async updateMetadataOnce(newMetadata) {
1586
1616
  const encrypted = encodeBase64(
1587
1617
  encrypt(this.encryptionKey, this.encryptionVariant, newMetadata)
1588
1618
  );
1589
- await withBackoff(
1590
- () => new Promise((resolve, reject) => {
1591
- this.socket.emit(
1592
- "update-metadata",
1593
- {
1594
- sid: this.sessionId,
1595
- expectedVersion: this.metadataVersion,
1596
- metadata: encrypted
1597
- },
1598
- (answer) => {
1599
- if (answer.result === "success" && answer.version !== void 0) {
1600
- this.metadataVersion = answer.version;
1601
- this.metadata = newMetadata;
1602
- resolve();
1603
- } else if (answer.result === "version-mismatch" && answer.version !== void 0) {
1604
- this.metadataVersion = answer.version;
1605
- if (answer.metadata) {
1606
- this.metadata = decrypt(
1607
- this.encryptionKey,
1608
- this.encryptionVariant,
1609
- decodeBase64(answer.metadata)
1610
- );
1611
- }
1612
- reject(new Error("version-mismatch"));
1613
- } else {
1614
- reject(new Error(`update-metadata failed: ${answer.result}`));
1619
+ await new Promise((resolve, reject) => {
1620
+ this.socket.emit(
1621
+ "update-metadata",
1622
+ {
1623
+ sid: this.sessionId,
1624
+ expectedVersion: this.metadataVersion,
1625
+ metadata: encrypted
1626
+ },
1627
+ (answer) => {
1628
+ if (answer.result === "success" && answer.version !== void 0) {
1629
+ this.metadataVersion = answer.version;
1630
+ this.metadata = newMetadata;
1631
+ resolve();
1632
+ } else if (answer.result === "version-mismatch" && answer.version !== void 0) {
1633
+ this.metadataVersion = answer.version;
1634
+ if (answer.metadata) {
1635
+ this.metadata = decrypt(
1636
+ this.encryptionKey,
1637
+ this.encryptionVariant,
1638
+ decodeBase64(answer.metadata)
1639
+ );
1615
1640
  }
1641
+ reject(new Error("version-mismatch"));
1642
+ } else {
1643
+ reject(new Error(`update-metadata failed: ${answer.result}`));
1616
1644
  }
1617
- );
1618
- }),
1619
- { maxRetries: 3, label: "updateMetadata" }
1620
- );
1645
+ }
1646
+ );
1647
+ });
1648
+ }
1649
+ async updateMetadata(newMetadata) {
1650
+ await withBackoff(() => this.updateMetadataOnce(newMetadata), {
1651
+ maxRetries: 3,
1652
+ label: "updateMetadata"
1653
+ });
1654
+ }
1655
+ async updateMetadataWith(handler) {
1656
+ await withBackoff(async () => {
1657
+ const updated = handler(this.metadata);
1658
+ await this.updateMetadataOnce(updated);
1659
+ }, { maxRetries: 3, label: "updateMetadataWith" });
1621
1660
  }
1622
1661
  async updateAgentState(newState) {
1623
1662
  const encrypted = newState !== null ? encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, newState)) : null;
@@ -2222,6 +2261,8 @@ function handleTaskTrigger(data, serverUrl, _authToken, scheduler) {
2222
2261
  approvedNewDirectoryCreation: true,
2223
2262
  automationContext: { kind: "task", trigger: "task-dispatch", projectId: data.projectId },
2224
2263
  environmentVariables: {
2264
+ // Profile-resolved env applied first so task-specific overrides win.
2265
+ ...data.runtimeProfile?.environmentVariables ?? {},
2225
2266
  HAPPY_INITIAL_PROMPT_FILE: promptFile,
2226
2267
  HAPPY_TASK_ID: data.taskId,
2227
2268
  HAPPY_TASK_PRIORITY: data.priority,
@@ -2682,7 +2723,7 @@ class AutomationScheduler {
2682
2723
  }
2683
2724
  }
2684
2725
  const job = {
2685
- id: crypto.randomUUID(),
2726
+ id: crypto$1.randomUUID(),
2686
2727
  kind: opts.kind,
2687
2728
  dedupeKey: opts.dedupeKey,
2688
2729
  priority: opts.priority,
@@ -2857,7 +2898,7 @@ class AgentLoopCoordinator {
2857
2898
  // -----------------------------------------------------------------------
2858
2899
  createLoop(input) {
2859
2900
  const loop = {
2860
- id: crypto.randomUUID(),
2901
+ id: crypto$1.randomUUID(),
2861
2902
  name: input.name,
2862
2903
  prompt: input.prompt,
2863
2904
  directory: input.directory,
@@ -3430,9 +3471,2324 @@ function daemonStatus() {
3430
3471
  }
3431
3472
  }
3432
3473
 
3474
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
3475
+
3476
+ var cuid2 = {};
3477
+
3478
+ var src = {};
3479
+
3480
+ var sha3 = {};
3481
+
3482
+ var _u64 = {};
3483
+
3484
+ var hasRequired_u64;
3485
+
3486
+ function require_u64 () {
3487
+ if (hasRequired_u64) return _u64;
3488
+ hasRequired_u64 = 1;
3489
+ Object.defineProperty(_u64, "__esModule", { value: true });
3490
+ _u64.toBig = _u64.shrSL = _u64.shrSH = _u64.rotrSL = _u64.rotrSH = _u64.rotrBL = _u64.rotrBH = _u64.rotr32L = _u64.rotr32H = _u64.rotlSL = _u64.rotlSH = _u64.rotlBL = _u64.rotlBH = _u64.add5L = _u64.add5H = _u64.add4L = _u64.add4H = _u64.add3L = _u64.add3H = void 0;
3491
+ _u64.add = add;
3492
+ _u64.fromBig = fromBig;
3493
+ _u64.split = split;
3494
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
3495
+ const _32n = /* @__PURE__ */ BigInt(32);
3496
+ function fromBig(n, le = false) {
3497
+ if (le)
3498
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
3499
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
3500
+ }
3501
+ function split(lst, le = false) {
3502
+ const len = lst.length;
3503
+ let Ah = new Uint32Array(len);
3504
+ let Al = new Uint32Array(len);
3505
+ for (let i = 0; i < len; i++) {
3506
+ const { h, l } = fromBig(lst[i], le);
3507
+ [Ah[i], Al[i]] = [h, l];
3508
+ }
3509
+ return [Ah, Al];
3510
+ }
3511
+ const toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0);
3512
+ _u64.toBig = toBig;
3513
+ const shrSH = (h, _l, s) => h >>> s;
3514
+ _u64.shrSH = shrSH;
3515
+ const shrSL = (h, l, s) => h << 32 - s | l >>> s;
3516
+ _u64.shrSL = shrSL;
3517
+ const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
3518
+ _u64.rotrSH = rotrSH;
3519
+ const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
3520
+ _u64.rotrSL = rotrSL;
3521
+ const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
3522
+ _u64.rotrBH = rotrBH;
3523
+ const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
3524
+ _u64.rotrBL = rotrBL;
3525
+ const rotr32H = (_h, l) => l;
3526
+ _u64.rotr32H = rotr32H;
3527
+ const rotr32L = (h, _l) => h;
3528
+ _u64.rotr32L = rotr32L;
3529
+ const rotlSH = (h, l, s) => h << s | l >>> 32 - s;
3530
+ _u64.rotlSH = rotlSH;
3531
+ const rotlSL = (h, l, s) => l << s | h >>> 32 - s;
3532
+ _u64.rotlSL = rotlSL;
3533
+ const rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
3534
+ _u64.rotlBH = rotlBH;
3535
+ const rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
3536
+ _u64.rotlBL = rotlBL;
3537
+ function add(Ah, Al, Bh, Bl) {
3538
+ const l = (Al >>> 0) + (Bl >>> 0);
3539
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
3540
+ }
3541
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
3542
+ _u64.add3L = add3L;
3543
+ const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
3544
+ _u64.add3H = add3H;
3545
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
3546
+ _u64.add4L = add4L;
3547
+ const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
3548
+ _u64.add4H = add4H;
3549
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
3550
+ _u64.add5L = add5L;
3551
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
3552
+ _u64.add5H = add5H;
3553
+ const u64 = {
3554
+ fromBig,
3555
+ split,
3556
+ toBig,
3557
+ shrSH,
3558
+ shrSL,
3559
+ rotrSH,
3560
+ rotrSL,
3561
+ rotrBH,
3562
+ rotrBL,
3563
+ rotr32H,
3564
+ rotr32L,
3565
+ rotlSH,
3566
+ rotlSL,
3567
+ rotlBH,
3568
+ rotlBL,
3569
+ add,
3570
+ add3L,
3571
+ add3H,
3572
+ add4L,
3573
+ add4H,
3574
+ add5H,
3575
+ add5L
3576
+ };
3577
+ _u64.default = u64;
3578
+ return _u64;
3579
+ }
3580
+
3581
+ var utils = {};
3582
+
3583
+ var crypto = {};
3584
+
3585
+ var hasRequiredCrypto;
3586
+
3587
+ function requireCrypto () {
3588
+ if (hasRequiredCrypto) return crypto;
3589
+ hasRequiredCrypto = 1;
3590
+ Object.defineProperty(crypto, "__esModule", { value: true });
3591
+ crypto.crypto = void 0;
3592
+ crypto.crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
3593
+ return crypto;
3594
+ }
3595
+
3596
+ var hasRequiredUtils;
3597
+
3598
+ function requireUtils () {
3599
+ if (hasRequiredUtils) return utils;
3600
+ hasRequiredUtils = 1;
3601
+ (function (exports$1) {
3602
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3603
+ Object.defineProperty(exports$1, "__esModule", { value: true });
3604
+ exports$1.wrapXOFConstructorWithOpts = exports$1.wrapConstructorWithOpts = exports$1.wrapConstructor = exports$1.Hash = exports$1.nextTick = exports$1.swap32IfBE = exports$1.byteSwapIfBE = exports$1.swap8IfBE = exports$1.isLE = void 0;
3605
+ exports$1.isBytes = isBytes;
3606
+ exports$1.anumber = anumber;
3607
+ exports$1.abytes = abytes;
3608
+ exports$1.ahash = ahash;
3609
+ exports$1.aexists = aexists;
3610
+ exports$1.aoutput = aoutput;
3611
+ exports$1.u8 = u8;
3612
+ exports$1.u32 = u32;
3613
+ exports$1.clean = clean;
3614
+ exports$1.createView = createView;
3615
+ exports$1.rotr = rotr;
3616
+ exports$1.rotl = rotl;
3617
+ exports$1.byteSwap = byteSwap;
3618
+ exports$1.byteSwap32 = byteSwap32;
3619
+ exports$1.bytesToHex = bytesToHex;
3620
+ exports$1.hexToBytes = hexToBytes;
3621
+ exports$1.asyncLoop = asyncLoop;
3622
+ exports$1.utf8ToBytes = utf8ToBytes;
3623
+ exports$1.bytesToUtf8 = bytesToUtf8;
3624
+ exports$1.toBytes = toBytes;
3625
+ exports$1.kdfInputToBytes = kdfInputToBytes;
3626
+ exports$1.concatBytes = concatBytes;
3627
+ exports$1.checkOpts = checkOpts;
3628
+ exports$1.createHasher = createHasher;
3629
+ exports$1.createOptHasher = createOptHasher;
3630
+ exports$1.createXOFer = createXOFer;
3631
+ exports$1.randomBytes = randomBytes;
3632
+ const crypto_1 = requireCrypto();
3633
+ function isBytes(a) {
3634
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
3635
+ }
3636
+ function anumber(n) {
3637
+ if (!Number.isSafeInteger(n) || n < 0)
3638
+ throw new Error("positive integer expected, got " + n);
3639
+ }
3640
+ function abytes(b, ...lengths) {
3641
+ if (!isBytes(b))
3642
+ throw new Error("Uint8Array expected");
3643
+ if (lengths.length > 0 && !lengths.includes(b.length))
3644
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
3645
+ }
3646
+ function ahash(h) {
3647
+ if (typeof h !== "function" || typeof h.create !== "function")
3648
+ throw new Error("Hash should be wrapped by utils.createHasher");
3649
+ anumber(h.outputLen);
3650
+ anumber(h.blockLen);
3651
+ }
3652
+ function aexists(instance, checkFinished = true) {
3653
+ if (instance.destroyed)
3654
+ throw new Error("Hash instance has been destroyed");
3655
+ if (checkFinished && instance.finished)
3656
+ throw new Error("Hash#digest() has already been called");
3657
+ }
3658
+ function aoutput(out, instance) {
3659
+ abytes(out);
3660
+ const min = instance.outputLen;
3661
+ if (out.length < min) {
3662
+ throw new Error("digestInto() expects output buffer of length at least " + min);
3663
+ }
3664
+ }
3665
+ function u8(arr) {
3666
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
3667
+ }
3668
+ function u32(arr) {
3669
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3670
+ }
3671
+ function clean(...arrays) {
3672
+ for (let i = 0; i < arrays.length; i++) {
3673
+ arrays[i].fill(0);
3674
+ }
3675
+ }
3676
+ function createView(arr) {
3677
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3678
+ }
3679
+ function rotr(word, shift) {
3680
+ return word << 32 - shift | word >>> shift;
3681
+ }
3682
+ function rotl(word, shift) {
3683
+ return word << shift | word >>> 32 - shift >>> 0;
3684
+ }
3685
+ exports$1.isLE = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
3686
+ function byteSwap(word) {
3687
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
3688
+ }
3689
+ exports$1.swap8IfBE = exports$1.isLE ? (n) => n : (n) => byteSwap(n);
3690
+ exports$1.byteSwapIfBE = exports$1.swap8IfBE;
3691
+ function byteSwap32(arr) {
3692
+ for (let i = 0; i < arr.length; i++) {
3693
+ arr[i] = byteSwap(arr[i]);
3694
+ }
3695
+ return arr;
3696
+ }
3697
+ exports$1.swap32IfBE = exports$1.isLE ? (u) => u : byteSwap32;
3698
+ const hasHexBuiltin = /* @__PURE__ */ (() => (
3699
+ // @ts-ignore
3700
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
3701
+ ))();
3702
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
3703
+ function bytesToHex(bytes) {
3704
+ abytes(bytes);
3705
+ if (hasHexBuiltin)
3706
+ return bytes.toHex();
3707
+ let hex = "";
3708
+ for (let i = 0; i < bytes.length; i++) {
3709
+ hex += hexes[bytes[i]];
3710
+ }
3711
+ return hex;
3712
+ }
3713
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
3714
+ function asciiToBase16(ch) {
3715
+ if (ch >= asciis._0 && ch <= asciis._9)
3716
+ return ch - asciis._0;
3717
+ if (ch >= asciis.A && ch <= asciis.F)
3718
+ return ch - (asciis.A - 10);
3719
+ if (ch >= asciis.a && ch <= asciis.f)
3720
+ return ch - (asciis.a - 10);
3721
+ return;
3722
+ }
3723
+ function hexToBytes(hex) {
3724
+ if (typeof hex !== "string")
3725
+ throw new Error("hex string expected, got " + typeof hex);
3726
+ if (hasHexBuiltin)
3727
+ return Uint8Array.fromHex(hex);
3728
+ const hl = hex.length;
3729
+ const al = hl / 2;
3730
+ if (hl % 2)
3731
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
3732
+ const array = new Uint8Array(al);
3733
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
3734
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
3735
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
3736
+ if (n1 === void 0 || n2 === void 0) {
3737
+ const char = hex[hi] + hex[hi + 1];
3738
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
3739
+ }
3740
+ array[ai] = n1 * 16 + n2;
3741
+ }
3742
+ return array;
3743
+ }
3744
+ const nextTick = async () => {
3745
+ };
3746
+ exports$1.nextTick = nextTick;
3747
+ async function asyncLoop(iters, tick, cb) {
3748
+ let ts = Date.now();
3749
+ for (let i = 0; i < iters; i++) {
3750
+ cb(i);
3751
+ const diff = Date.now() - ts;
3752
+ if (diff >= 0 && diff < tick)
3753
+ continue;
3754
+ await (0, exports$1.nextTick)();
3755
+ ts += diff;
3756
+ }
3757
+ }
3758
+ function utf8ToBytes(str) {
3759
+ if (typeof str !== "string")
3760
+ throw new Error("string expected");
3761
+ return new Uint8Array(new TextEncoder().encode(str));
3762
+ }
3763
+ function bytesToUtf8(bytes) {
3764
+ return new TextDecoder().decode(bytes);
3765
+ }
3766
+ function toBytes(data) {
3767
+ if (typeof data === "string")
3768
+ data = utf8ToBytes(data);
3769
+ abytes(data);
3770
+ return data;
3771
+ }
3772
+ function kdfInputToBytes(data) {
3773
+ if (typeof data === "string")
3774
+ data = utf8ToBytes(data);
3775
+ abytes(data);
3776
+ return data;
3777
+ }
3778
+ function concatBytes(...arrays) {
3779
+ let sum = 0;
3780
+ for (let i = 0; i < arrays.length; i++) {
3781
+ const a = arrays[i];
3782
+ abytes(a);
3783
+ sum += a.length;
3784
+ }
3785
+ const res = new Uint8Array(sum);
3786
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
3787
+ const a = arrays[i];
3788
+ res.set(a, pad);
3789
+ pad += a.length;
3790
+ }
3791
+ return res;
3792
+ }
3793
+ function checkOpts(defaults, opts) {
3794
+ if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]")
3795
+ throw new Error("options should be object or undefined");
3796
+ const merged = Object.assign(defaults, opts);
3797
+ return merged;
3798
+ }
3799
+ class Hash {
3800
+ }
3801
+ exports$1.Hash = Hash;
3802
+ function createHasher(hashCons) {
3803
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
3804
+ const tmp = hashCons();
3805
+ hashC.outputLen = tmp.outputLen;
3806
+ hashC.blockLen = tmp.blockLen;
3807
+ hashC.create = () => hashCons();
3808
+ return hashC;
3809
+ }
3810
+ function createOptHasher(hashCons) {
3811
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
3812
+ const tmp = hashCons({});
3813
+ hashC.outputLen = tmp.outputLen;
3814
+ hashC.blockLen = tmp.blockLen;
3815
+ hashC.create = (opts) => hashCons(opts);
3816
+ return hashC;
3817
+ }
3818
+ function createXOFer(hashCons) {
3819
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
3820
+ const tmp = hashCons({});
3821
+ hashC.outputLen = tmp.outputLen;
3822
+ hashC.blockLen = tmp.blockLen;
3823
+ hashC.create = (opts) => hashCons(opts);
3824
+ return hashC;
3825
+ }
3826
+ exports$1.wrapConstructor = createHasher;
3827
+ exports$1.wrapConstructorWithOpts = createOptHasher;
3828
+ exports$1.wrapXOFConstructorWithOpts = createXOFer;
3829
+ function randomBytes(bytesLength = 32) {
3830
+ if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
3831
+ return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
3832
+ }
3833
+ if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === "function") {
3834
+ return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
3835
+ }
3836
+ throw new Error("crypto.getRandomValues must be defined");
3837
+ }
3838
+ } (utils));
3839
+ return utils;
3840
+ }
3841
+
3842
+ var hasRequiredSha3;
3843
+
3844
+ function requireSha3 () {
3845
+ if (hasRequiredSha3) return sha3;
3846
+ hasRequiredSha3 = 1;
3847
+ Object.defineProperty(sha3, "__esModule", { value: true });
3848
+ sha3.shake256 = sha3.shake128 = sha3.keccak_512 = sha3.keccak_384 = sha3.keccak_256 = sha3.keccak_224 = sha3.sha3_512 = sha3.sha3_384 = sha3.sha3_256 = sha3.sha3_224 = sha3.Keccak = void 0;
3849
+ sha3.keccakP = keccakP;
3850
+ const _u64_ts_1 = /*@__PURE__*/ require_u64();
3851
+ const utils_ts_1 = /*@__PURE__*/ requireUtils();
3852
+ const _0n = BigInt(0);
3853
+ const _1n = BigInt(1);
3854
+ const _2n = BigInt(2);
3855
+ const _7n = BigInt(7);
3856
+ const _256n = BigInt(256);
3857
+ const _0x71n = BigInt(113);
3858
+ const SHA3_PI = [];
3859
+ const SHA3_ROTL = [];
3860
+ const _SHA3_IOTA = [];
3861
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
3862
+ [x, y] = [y, (2 * x + 3 * y) % 5];
3863
+ SHA3_PI.push(2 * (5 * y + x));
3864
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
3865
+ let t = _0n;
3866
+ for (let j = 0; j < 7; j++) {
3867
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
3868
+ if (R & _2n)
3869
+ t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
3870
+ }
3871
+ _SHA3_IOTA.push(t);
3872
+ }
3873
+ const IOTAS = (0, _u64_ts_1.split)(_SHA3_IOTA, true);
3874
+ const SHA3_IOTA_H = IOTAS[0];
3875
+ const SHA3_IOTA_L = IOTAS[1];
3876
+ const rotlH = (h, l, s) => s > 32 ? (0, _u64_ts_1.rotlBH)(h, l, s) : (0, _u64_ts_1.rotlSH)(h, l, s);
3877
+ const rotlL = (h, l, s) => s > 32 ? (0, _u64_ts_1.rotlBL)(h, l, s) : (0, _u64_ts_1.rotlSL)(h, l, s);
3878
+ function keccakP(s, rounds = 24) {
3879
+ const B = new Uint32Array(5 * 2);
3880
+ for (let round = 24 - rounds; round < 24; round++) {
3881
+ for (let x = 0; x < 10; x++)
3882
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
3883
+ for (let x = 0; x < 10; x += 2) {
3884
+ const idx1 = (x + 8) % 10;
3885
+ const idx0 = (x + 2) % 10;
3886
+ const B0 = B[idx0];
3887
+ const B1 = B[idx0 + 1];
3888
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
3889
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
3890
+ for (let y = 0; y < 50; y += 10) {
3891
+ s[x + y] ^= Th;
3892
+ s[x + y + 1] ^= Tl;
3893
+ }
3894
+ }
3895
+ let curH = s[2];
3896
+ let curL = s[3];
3897
+ for (let t = 0; t < 24; t++) {
3898
+ const shift = SHA3_ROTL[t];
3899
+ const Th = rotlH(curH, curL, shift);
3900
+ const Tl = rotlL(curH, curL, shift);
3901
+ const PI = SHA3_PI[t];
3902
+ curH = s[PI];
3903
+ curL = s[PI + 1];
3904
+ s[PI] = Th;
3905
+ s[PI + 1] = Tl;
3906
+ }
3907
+ for (let y = 0; y < 50; y += 10) {
3908
+ for (let x = 0; x < 10; x++)
3909
+ B[x] = s[y + x];
3910
+ for (let x = 0; x < 10; x++)
3911
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
3912
+ }
3913
+ s[0] ^= SHA3_IOTA_H[round];
3914
+ s[1] ^= SHA3_IOTA_L[round];
3915
+ }
3916
+ (0, utils_ts_1.clean)(B);
3917
+ }
3918
+ class Keccak extends utils_ts_1.Hash {
3919
+ // NOTE: we accept arguments in bytes instead of bits here.
3920
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
3921
+ super();
3922
+ this.pos = 0;
3923
+ this.posOut = 0;
3924
+ this.finished = false;
3925
+ this.destroyed = false;
3926
+ this.enableXOF = false;
3927
+ this.blockLen = blockLen;
3928
+ this.suffix = suffix;
3929
+ this.outputLen = outputLen;
3930
+ this.enableXOF = enableXOF;
3931
+ this.rounds = rounds;
3932
+ (0, utils_ts_1.anumber)(outputLen);
3933
+ if (!(0 < blockLen && blockLen < 200))
3934
+ throw new Error("only keccak-f1600 function is supported");
3935
+ this.state = new Uint8Array(200);
3936
+ this.state32 = (0, utils_ts_1.u32)(this.state);
3937
+ }
3938
+ clone() {
3939
+ return this._cloneInto();
3940
+ }
3941
+ keccak() {
3942
+ (0, utils_ts_1.swap32IfBE)(this.state32);
3943
+ keccakP(this.state32, this.rounds);
3944
+ (0, utils_ts_1.swap32IfBE)(this.state32);
3945
+ this.posOut = 0;
3946
+ this.pos = 0;
3947
+ }
3948
+ update(data) {
3949
+ (0, utils_ts_1.aexists)(this);
3950
+ data = (0, utils_ts_1.toBytes)(data);
3951
+ (0, utils_ts_1.abytes)(data);
3952
+ const { blockLen, state } = this;
3953
+ const len = data.length;
3954
+ for (let pos = 0; pos < len; ) {
3955
+ const take = Math.min(blockLen - this.pos, len - pos);
3956
+ for (let i = 0; i < take; i++)
3957
+ state[this.pos++] ^= data[pos++];
3958
+ if (this.pos === blockLen)
3959
+ this.keccak();
3960
+ }
3961
+ return this;
3962
+ }
3963
+ finish() {
3964
+ if (this.finished)
3965
+ return;
3966
+ this.finished = true;
3967
+ const { state, suffix, pos, blockLen } = this;
3968
+ state[pos] ^= suffix;
3969
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
3970
+ this.keccak();
3971
+ state[blockLen - 1] ^= 128;
3972
+ this.keccak();
3973
+ }
3974
+ writeInto(out) {
3975
+ (0, utils_ts_1.aexists)(this, false);
3976
+ (0, utils_ts_1.abytes)(out);
3977
+ this.finish();
3978
+ const bufferOut = this.state;
3979
+ const { blockLen } = this;
3980
+ for (let pos = 0, len = out.length; pos < len; ) {
3981
+ if (this.posOut >= blockLen)
3982
+ this.keccak();
3983
+ const take = Math.min(blockLen - this.posOut, len - pos);
3984
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
3985
+ this.posOut += take;
3986
+ pos += take;
3987
+ }
3988
+ return out;
3989
+ }
3990
+ xofInto(out) {
3991
+ if (!this.enableXOF)
3992
+ throw new Error("XOF is not possible for this instance");
3993
+ return this.writeInto(out);
3994
+ }
3995
+ xof(bytes) {
3996
+ (0, utils_ts_1.anumber)(bytes);
3997
+ return this.xofInto(new Uint8Array(bytes));
3998
+ }
3999
+ digestInto(out) {
4000
+ (0, utils_ts_1.aoutput)(out, this);
4001
+ if (this.finished)
4002
+ throw new Error("digest() was already called");
4003
+ this.writeInto(out);
4004
+ this.destroy();
4005
+ return out;
4006
+ }
4007
+ digest() {
4008
+ return this.digestInto(new Uint8Array(this.outputLen));
4009
+ }
4010
+ destroy() {
4011
+ this.destroyed = true;
4012
+ (0, utils_ts_1.clean)(this.state);
4013
+ }
4014
+ _cloneInto(to) {
4015
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
4016
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
4017
+ to.state32.set(this.state32);
4018
+ to.pos = this.pos;
4019
+ to.posOut = this.posOut;
4020
+ to.finished = this.finished;
4021
+ to.rounds = rounds;
4022
+ to.suffix = suffix;
4023
+ to.outputLen = outputLen;
4024
+ to.enableXOF = enableXOF;
4025
+ to.destroyed = this.destroyed;
4026
+ return to;
4027
+ }
4028
+ }
4029
+ sha3.Keccak = Keccak;
4030
+ const gen = (suffix, blockLen, outputLen) => (0, utils_ts_1.createHasher)(() => new Keccak(blockLen, suffix, outputLen));
4031
+ sha3.sha3_224 = (() => gen(6, 144, 224 / 8))();
4032
+ sha3.sha3_256 = (() => gen(6, 136, 256 / 8))();
4033
+ sha3.sha3_384 = (() => gen(6, 104, 384 / 8))();
4034
+ sha3.sha3_512 = (() => gen(6, 72, 512 / 8))();
4035
+ sha3.keccak_224 = (() => gen(1, 144, 224 / 8))();
4036
+ sha3.keccak_256 = (() => gen(1, 136, 256 / 8))();
4037
+ sha3.keccak_384 = (() => gen(1, 104, 384 / 8))();
4038
+ sha3.keccak_512 = (() => gen(1, 72, 512 / 8))();
4039
+ const genShake = (suffix, blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true));
4040
+ sha3.shake128 = (() => genShake(31, 168, 128 / 8))();
4041
+ sha3.shake256 = (() => genShake(31, 136, 256 / 8))();
4042
+ return sha3;
4043
+ }
4044
+
4045
+ var hasRequiredSrc;
4046
+
4047
+ function requireSrc () {
4048
+ if (hasRequiredSrc) return src;
4049
+ hasRequiredSrc = 1;
4050
+ const { sha3_512: sha3 } = /*@__PURE__*/ requireSha3();
4051
+ const defaultLength = 24;
4052
+ const bigLength = 32;
4053
+ const createEntropy = (length = 4, random = Math.random) => {
4054
+ let entropy = "";
4055
+ while (entropy.length < length) {
4056
+ entropy = entropy + Math.floor(random() * 36).toString(36);
4057
+ }
4058
+ return entropy;
4059
+ };
4060
+ function bufToBigInt(buf) {
4061
+ let bits = 8n;
4062
+ let value = 0n;
4063
+ for (const i of buf.values()) {
4064
+ const bi = BigInt(i);
4065
+ value = (value << bits) + bi;
4066
+ }
4067
+ return value;
4068
+ }
4069
+ const hash = (input = "") => {
4070
+ return bufToBigInt(sha3(input)).toString(36).slice(1);
4071
+ };
4072
+ const alphabet = Array.from(
4073
+ { length: 26 },
4074
+ (x, i) => String.fromCharCode(i + 97)
4075
+ );
4076
+ const randomLetter = (random) => alphabet[Math.floor(random() * alphabet.length)];
4077
+ const createFingerprint = ({
4078
+ globalObj = typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof window !== "undefined" ? window : {},
4079
+ random = Math.random
4080
+ } = {}) => {
4081
+ const globals = Object.keys(globalObj).toString();
4082
+ const sourceString = globals.length ? globals + createEntropy(bigLength, random) : createEntropy(bigLength, random);
4083
+ return hash(sourceString).substring(0, bigLength);
4084
+ };
4085
+ const createCounter = (count) => () => {
4086
+ return count++;
4087
+ };
4088
+ const initialCountMax = 476782367;
4089
+ const init = ({
4090
+ // Fallback if the user does not pass in a CSPRNG. This should be OK
4091
+ // because we don't rely solely on the random number generator for entropy.
4092
+ // We also use the host fingerprint, current time, and a session counter.
4093
+ random = Math.random,
4094
+ counter = createCounter(Math.floor(random() * initialCountMax)),
4095
+ length = defaultLength,
4096
+ fingerprint = createFingerprint({ random })
4097
+ } = {}) => {
4098
+ return function cuid2() {
4099
+ const firstLetter = randomLetter(random);
4100
+ const time = Date.now().toString(36);
4101
+ const count = counter().toString(36);
4102
+ const salt = createEntropy(length, random);
4103
+ const hashInput = `${time + salt + count + fingerprint}`;
4104
+ return `${firstLetter + hash(hashInput).substring(1, length)}`;
4105
+ };
4106
+ };
4107
+ const createId = init();
4108
+ const isCuid = (id, { minLength = 2, maxLength = bigLength } = {}) => {
4109
+ const length = id.length;
4110
+ const regex = /^[0-9a-z]+$/;
4111
+ try {
4112
+ if (typeof id === "string" && length >= minLength && length <= maxLength && regex.test(id))
4113
+ return true;
4114
+ } finally {
4115
+ }
4116
+ return false;
4117
+ };
4118
+ src.getConstants = () => ({ defaultLength, bigLength });
4119
+ src.init = init;
4120
+ src.createId = createId;
4121
+ src.bufToBigInt = bufToBigInt;
4122
+ src.createCounter = createCounter;
4123
+ src.createFingerprint = createFingerprint;
4124
+ src.isCuid = isCuid;
4125
+ return src;
4126
+ }
4127
+
4128
+ var hasRequiredCuid2;
4129
+
4130
+ function requireCuid2 () {
4131
+ if (hasRequiredCuid2) return cuid2;
4132
+ hasRequiredCuid2 = 1;
4133
+ const { createId, init, getConstants, isCuid } = requireSrc();
4134
+ cuid2.createId = createId;
4135
+ cuid2.init = init;
4136
+ cuid2.getConstants = getConstants;
4137
+ cuid2.isCuid = isCuid;
4138
+ return cuid2;
4139
+ }
4140
+
4141
+ var cuid2Exports = requireCuid2();
4142
+
4143
+ const sessionRoleSchema = z__namespace.enum(["user", "agent"]);
4144
+ const sessionTextEventSchema = z__namespace.object({
4145
+ t: z__namespace.literal("text"),
4146
+ text: z__namespace.string(),
4147
+ thinking: z__namespace.boolean().optional()
4148
+ });
4149
+ const sessionTextDeltaEventSchema = z__namespace.object({
4150
+ t: z__namespace.literal("text-delta"),
4151
+ stream: z__namespace.string(),
4152
+ delta: z__namespace.string(),
4153
+ thinking: z__namespace.boolean().optional()
4154
+ });
4155
+ const sessionServiceMessageEventSchema = z__namespace.object({
4156
+ t: z__namespace.literal("service"),
4157
+ text: z__namespace.string()
4158
+ });
4159
+ const sessionToolCallStartEventSchema = z__namespace.object({
4160
+ t: z__namespace.literal("tool-call-start"),
4161
+ call: z__namespace.string(),
4162
+ name: z__namespace.string(),
4163
+ title: z__namespace.string(),
4164
+ description: z__namespace.string(),
4165
+ args: z__namespace.record(z__namespace.string(), z__namespace.unknown())
4166
+ });
4167
+ const sessionToolCallEndEventSchema = z__namespace.object({
4168
+ t: z__namespace.literal("tool-call-end"),
4169
+ call: z__namespace.string(),
4170
+ /** Background task ID when Bash command runs with run_in_background */
4171
+ backgroundTaskId: z__namespace.string().optional(),
4172
+ /** Path to the task output file on the CLI machine */
4173
+ outputFile: z__namespace.string().optional()
4174
+ });
4175
+ const sessionFileEventSchema = z__namespace.object({
4176
+ t: z__namespace.literal("file"),
4177
+ ref: z__namespace.string(),
4178
+ name: z__namespace.string(),
4179
+ size: z__namespace.number(),
4180
+ image: z__namespace.object({
4181
+ width: z__namespace.number(),
4182
+ height: z__namespace.number(),
4183
+ thumbhash: z__namespace.string()
4184
+ }).optional()
4185
+ });
4186
+ const sessionTurnStartEventSchema = z__namespace.object({
4187
+ t: z__namespace.literal("turn-start")
4188
+ });
4189
+ const sessionStartEventSchema = z__namespace.object({
4190
+ t: z__namespace.literal("start"),
4191
+ title: z__namespace.string().optional()
4192
+ });
4193
+ const sessionTurnEndStatusSchema = z__namespace.enum([
4194
+ "completed",
4195
+ "failed",
4196
+ "cancelled"
4197
+ ]);
4198
+ const sessionModelUsageSchema = z__namespace.object({
4199
+ inputTokens: z__namespace.number(),
4200
+ outputTokens: z__namespace.number(),
4201
+ cacheReadInputTokens: z__namespace.number(),
4202
+ cacheCreationInputTokens: z__namespace.number(),
4203
+ costUSD: z__namespace.number(),
4204
+ contextWindow: z__namespace.number(),
4205
+ maxOutputTokens: z__namespace.number()
4206
+ });
4207
+ const sessionTurnEndEventSchema = z__namespace.object({
4208
+ t: z__namespace.literal("turn-end"),
4209
+ status: sessionTurnEndStatusSchema,
4210
+ model: z__namespace.string().optional(),
4211
+ usage: z__namespace.object({
4212
+ input_tokens: z__namespace.number(),
4213
+ output_tokens: z__namespace.number(),
4214
+ cache_creation_input_tokens: z__namespace.number().optional(),
4215
+ cache_read_input_tokens: z__namespace.number().optional()
4216
+ }).optional(),
4217
+ durationMs: z__namespace.number().optional(),
4218
+ totalCostUsd: z__namespace.number().optional(),
4219
+ numTurns: z__namespace.number().optional(),
4220
+ modelUsage: z__namespace.record(z__namespace.string(), sessionModelUsageSchema).optional()
4221
+ });
4222
+ const sessionStopEventSchema = z__namespace.object({
4223
+ t: z__namespace.literal("stop")
4224
+ });
4225
+ const sessionUsageUpdateEventSchema = z__namespace.object({
4226
+ t: z__namespace.literal("usage-update"),
4227
+ model: z__namespace.string().optional(),
4228
+ usage: z__namespace.object({
4229
+ input_tokens: z__namespace.number(),
4230
+ output_tokens: z__namespace.number(),
4231
+ cache_creation_input_tokens: z__namespace.number().optional(),
4232
+ cache_read_input_tokens: z__namespace.number().optional()
4233
+ }),
4234
+ durationMs: z__namespace.number().optional()
4235
+ });
4236
+ const sessionTaskStartEventSchema = z__namespace.object({
4237
+ t: z__namespace.literal("task-start"),
4238
+ taskId: z__namespace.string(),
4239
+ toolUseId: z__namespace.string().optional(),
4240
+ description: z__namespace.string(),
4241
+ taskType: z__namespace.string().optional(),
4242
+ /** meta.name from the workflow script (e.g. 'spec'). Only set when taskType is 'local_workflow'. */
4243
+ workflowName: z__namespace.string().optional()
4244
+ });
4245
+ const sessionTaskProgressEventSchema = z__namespace.object({
4246
+ t: z__namespace.literal("task-progress"),
4247
+ taskId: z__namespace.string(),
4248
+ description: z__namespace.string(),
4249
+ usage: z__namespace.object({
4250
+ totalTokens: z__namespace.number(),
4251
+ toolUses: z__namespace.number(),
4252
+ durationMs: z__namespace.number()
4253
+ }).optional(),
4254
+ lastToolName: z__namespace.string().optional(),
4255
+ /** AI-generated progress summary (~30s interval, from agentProgressSummaries) */
4256
+ summary: z__namespace.string().optional()
4257
+ });
4258
+ const sessionTaskEndEventSchema = z__namespace.object({
4259
+ t: z__namespace.literal("task-end"),
4260
+ taskId: z__namespace.string(),
4261
+ status: z__namespace.enum(["completed", "failed", "stopped"]),
4262
+ summary: z__namespace.string(),
4263
+ usage: z__namespace.object({
4264
+ totalTokens: z__namespace.number(),
4265
+ toolUses: z__namespace.number(),
4266
+ durationMs: z__namespace.number()
4267
+ }).optional()
4268
+ });
4269
+ const sessionToolProgressEventSchema = z__namespace.object({
4270
+ t: z__namespace.literal("tool-progress"),
4271
+ toolUseId: z__namespace.string(),
4272
+ toolName: z__namespace.string(),
4273
+ elapsedSeconds: z__namespace.number(),
4274
+ taskId: z__namespace.string().optional()
4275
+ });
4276
+ const sessionPromptSuggestionEventSchema = z__namespace.object({
4277
+ t: z__namespace.literal("prompt-suggestion"),
4278
+ suggestion: z__namespace.string()
4279
+ });
4280
+ const sessionNeedsContinueEventSchema = z__namespace.object({
4281
+ t: z__namespace.literal("needs-continue")
4282
+ });
4283
+ const sessionStateChangedEventSchema = z__namespace.object({
4284
+ t: z__namespace.literal("session-state-changed"),
4285
+ /** Authoritative session lifecycle state from the SDK */
4286
+ state: z__namespace.enum(["idle", "running", "requires_action"])
4287
+ });
4288
+ const sessionContextUsageCategorySchema = z__namespace.object({
4289
+ name: z__namespace.string(),
4290
+ tokens: z__namespace.number(),
4291
+ color: z__namespace.string().optional()
4292
+ });
4293
+ const sessionTaskLogEventSchema = z__namespace.object({
4294
+ t: z__namespace.literal("task-log"),
4295
+ /** Background task ID or tool call ID that owns this log stream */
4296
+ taskId: z__namespace.string(),
4297
+ /** Path to the output file on the CLI machine */
4298
+ outputFile: z__namespace.string(),
4299
+ /** Incremental log content (new lines since last push) */
4300
+ chunk: z__namespace.string(),
4301
+ /** Byte offset in the output file where this chunk starts */
4302
+ offset: z__namespace.number()
4303
+ });
4304
+ const sessionContextUsageEventSchema = z__namespace.object({
4305
+ t: z__namespace.literal("context-usage"),
4306
+ totalTokens: z__namespace.number(),
4307
+ maxTokens: z__namespace.number(),
4308
+ percentage: z__namespace.number(),
4309
+ model: z__namespace.string().optional(),
4310
+ categories: z__namespace.array(sessionContextUsageCategorySchema).optional(),
4311
+ isAutoCompactEnabled: z__namespace.boolean().optional(),
4312
+ autoCompactThreshold: z__namespace.number().optional(),
4313
+ messageBreakdown: z__namespace.object({
4314
+ toolCallTokens: z__namespace.number(),
4315
+ toolResultTokens: z__namespace.number(),
4316
+ attachmentTokens: z__namespace.number(),
4317
+ assistantMessageTokens: z__namespace.number(),
4318
+ userMessageTokens: z__namespace.number()
4319
+ }).optional()
4320
+ });
4321
+ const sessionEventSchema = z__namespace.discriminatedUnion("t", [
4322
+ sessionTextEventSchema,
4323
+ sessionTextDeltaEventSchema,
4324
+ sessionServiceMessageEventSchema,
4325
+ sessionToolCallStartEventSchema,
4326
+ sessionToolCallEndEventSchema,
4327
+ sessionFileEventSchema,
4328
+ sessionTurnStartEventSchema,
4329
+ sessionStartEventSchema,
4330
+ sessionTurnEndEventSchema,
4331
+ sessionStopEventSchema,
4332
+ sessionUsageUpdateEventSchema,
4333
+ sessionTaskStartEventSchema,
4334
+ sessionTaskProgressEventSchema,
4335
+ sessionTaskEndEventSchema,
4336
+ sessionToolProgressEventSchema,
4337
+ sessionPromptSuggestionEventSchema,
4338
+ sessionNeedsContinueEventSchema,
4339
+ sessionStateChangedEventSchema,
4340
+ sessionContextUsageEventSchema,
4341
+ sessionTaskLogEventSchema
4342
+ ]);
4343
+ const sessionEnvelopeSchema = z__namespace.object({
4344
+ id: z__namespace.string(),
4345
+ time: z__namespace.number(),
4346
+ role: sessionRoleSchema,
4347
+ turn: z__namespace.string().optional(),
4348
+ subagent: z__namespace.string().refine((value) => cuid2Exports.isCuid(value), {
4349
+ message: "subagent must be a cuid2 value"
4350
+ }).optional(),
4351
+ ev: sessionEventSchema
4352
+ }).superRefine((envelope, ctx) => {
4353
+ if (envelope.ev.t === "service" && envelope.role !== "agent") {
4354
+ ctx.addIssue({
4355
+ code: z__namespace.ZodIssueCode.custom,
4356
+ message: 'service events must use role "agent"',
4357
+ path: ["role"]
4358
+ });
4359
+ }
4360
+ if ((envelope.ev.t === "start" || envelope.ev.t === "stop" || envelope.ev.t === "usage-update" || envelope.ev.t === "task-start" || envelope.ev.t === "task-progress" || envelope.ev.t === "task-end" || envelope.ev.t === "tool-progress" || envelope.ev.t === "prompt-suggestion" || envelope.ev.t === "needs-continue" || envelope.ev.t === "session-state-changed" || envelope.ev.t === "context-usage" || envelope.ev.t === "task-log") && envelope.role !== "agent") {
4361
+ ctx.addIssue({
4362
+ code: z__namespace.ZodIssueCode.custom,
4363
+ message: `${envelope.ev.t} events must use role "agent"`,
4364
+ path: ["role"]
4365
+ });
4366
+ }
4367
+ });
4368
+
4369
+ const MessageMetaSchema = z__namespace.object({
4370
+ sentFrom: z__namespace.string().optional(),
4371
+ permissionMode: z__namespace.enum(["default", "acceptEdits", "bypassPermissions", "plan", "dontAsk", "auto", "read-only", "safe-yolo", "yolo"]).optional(),
4372
+ model: z__namespace.string().nullable().optional(),
4373
+ fallbackModel: z__namespace.string().nullable().optional(),
4374
+ customSystemPrompt: z__namespace.string().nullable().optional(),
4375
+ appendSystemPrompt: z__namespace.string().nullable().optional(),
4376
+ allowedTools: z__namespace.array(z__namespace.string()).nullable().optional(),
4377
+ disallowedTools: z__namespace.array(z__namespace.string()).nullable().optional(),
4378
+ displayText: z__namespace.string().optional(),
4379
+ /**
4380
+ * When false, the message is appended to the transcript without triggering
4381
+ * an assistant turn. Requires @anthropic-ai/claude-agent-sdk 0.2.110+ on CLI.
4382
+ * Defaults to true when unset (normal turn-triggering message).
4383
+ */
4384
+ shouldQuery: z__namespace.boolean().optional()
4385
+ });
4386
+
4387
+ const UserMessageSchema = z__namespace.object({
4388
+ role: z__namespace.literal("user"),
4389
+ content: z__namespace.object({
4390
+ type: z__namespace.literal("text"),
4391
+ text: z__namespace.string()
4392
+ }),
4393
+ localKey: z__namespace.string().optional(),
4394
+ meta: MessageMetaSchema.optional()
4395
+ });
4396
+ const AgentMessageSchema = z__namespace.object({
4397
+ role: z__namespace.literal("agent"),
4398
+ content: z__namespace.object({
4399
+ type: z__namespace.string()
4400
+ }).passthrough(),
4401
+ meta: MessageMetaSchema.optional()
4402
+ });
4403
+ z__namespace.discriminatedUnion("role", [UserMessageSchema, AgentMessageSchema]);
4404
+
4405
+ const SessionMessageContentSchema = z__namespace.object({
4406
+ c: z__namespace.string(),
4407
+ t: z__namespace.literal("encrypted")
4408
+ });
4409
+ const SessionMessageSchema = z__namespace.object({
4410
+ id: z__namespace.string(),
4411
+ seq: z__namespace.number(),
4412
+ localId: z__namespace.string().nullish(),
4413
+ content: SessionMessageContentSchema,
4414
+ createdAt: z__namespace.number(),
4415
+ updatedAt: z__namespace.number()
4416
+ });
4417
+ const SessionProtocolMessageSchema = z__namespace.object({
4418
+ role: z__namespace.literal("session"),
4419
+ content: sessionEnvelopeSchema,
4420
+ meta: MessageMetaSchema.optional()
4421
+ });
4422
+ z__namespace.discriminatedUnion("role", [
4423
+ UserMessageSchema,
4424
+ AgentMessageSchema,
4425
+ SessionProtocolMessageSchema
4426
+ ]);
4427
+ const VersionedEncryptedValueSchema = z__namespace.object({
4428
+ version: z__namespace.number(),
4429
+ value: z__namespace.string()
4430
+ });
4431
+ const VersionedNullableEncryptedValueSchema = z__namespace.object({
4432
+ version: z__namespace.number(),
4433
+ value: z__namespace.string().nullable()
4434
+ });
4435
+ const UpdateNewMessageBodySchema = z__namespace.object({
4436
+ t: z__namespace.literal("new-message"),
4437
+ sid: z__namespace.string(),
4438
+ message: SessionMessageSchema
4439
+ });
4440
+ const UpdateSessionBodySchema = z__namespace.object({
4441
+ t: z__namespace.literal("update-session"),
4442
+ id: z__namespace.string(),
4443
+ metadata: VersionedEncryptedValueSchema.nullish(),
4444
+ agentState: VersionedNullableEncryptedValueSchema.nullish(),
4445
+ preferences: VersionedNullableEncryptedValueSchema.nullish()
4446
+ });
4447
+ const VersionedMachineEncryptedValueSchema = z__namespace.object({
4448
+ version: z__namespace.number(),
4449
+ value: z__namespace.string()
4450
+ });
4451
+ const UpdateMachineBodySchema = z__namespace.object({
4452
+ t: z__namespace.literal("update-machine"),
4453
+ machineId: z__namespace.string(),
4454
+ metadata: VersionedMachineEncryptedValueSchema.nullish(),
4455
+ daemonState: VersionedMachineEncryptedValueSchema.nullish(),
4456
+ active: z__namespace.boolean().optional(),
4457
+ activeAt: z__namespace.number().optional()
4458
+ });
4459
+ const CoreUpdateBodySchema = z__namespace.discriminatedUnion("t", [
4460
+ UpdateNewMessageBodySchema,
4461
+ UpdateSessionBodySchema,
4462
+ UpdateMachineBodySchema
4463
+ ]);
4464
+ z__namespace.object({
4465
+ id: z__namespace.string(),
4466
+ seq: z__namespace.number(),
4467
+ body: CoreUpdateBodySchema,
4468
+ createdAt: z__namespace.number()
4469
+ });
4470
+
4471
+ z__namespace.object({
4472
+ host: z__namespace.string(),
4473
+ platform: z__namespace.string(),
4474
+ happyCliVersion: z__namespace.string(),
4475
+ homeDir: z__namespace.string(),
4476
+ happyHomeDir: z__namespace.string(),
4477
+ happyLibDir: z__namespace.string()
4478
+ });
4479
+ const TailscaleServeEntrySchema = z__namespace.object({
4480
+ port: z__namespace.number(),
4481
+ path: z__namespace.string().optional(),
4482
+ protocol: z__namespace.string(),
4483
+ target: z__namespace.string(),
4484
+ funnel: z__namespace.boolean(),
4485
+ hostname: z__namespace.string()
4486
+ });
4487
+ const TailscaleInfoSchema = z__namespace.object({
4488
+ status: z__namespace.enum(["connected", "disconnected", "not-installed"]),
4489
+ ipv4: z__namespace.string().optional(),
4490
+ ipv6: z__namespace.string().optional(),
4491
+ hostname: z__namespace.string().optional(),
4492
+ tailnetName: z__namespace.string().optional(),
4493
+ version: z__namespace.string().optional(),
4494
+ serves: z__namespace.array(TailscaleServeEntrySchema).optional()
4495
+ });
4496
+ const TunnelEntrySchema = z__namespace.object({
4497
+ provider: z__namespace.string(),
4498
+ localPort: z__namespace.number(),
4499
+ remotePort: z__namespace.number().optional(),
4500
+ protocol: z__namespace.string(),
4501
+ path: z__namespace.string().optional(),
4502
+ target: z__namespace.string(),
4503
+ publicUrl: z__namespace.string().optional(),
4504
+ accessScope: z__namespace.enum(["public", "private", "tailnet"]),
4505
+ hostname: z__namespace.string().optional(),
4506
+ metadata: z__namespace.record(z__namespace.string(), z__namespace.string()).optional()
4507
+ });
4508
+ const TunnelProviderInfoSchema = z__namespace.object({
4509
+ provider: z__namespace.string(),
4510
+ status: z__namespace.enum(["available", "unavailable", "not-installed"]),
4511
+ version: z__namespace.string().optional(),
4512
+ entries: z__namespace.array(TunnelEntrySchema),
4513
+ metadata: z__namespace.record(z__namespace.string(), z__namespace.string()).optional()
4514
+ });
4515
+ const TunnelStateSchema = z__namespace.object({
4516
+ providers: z__namespace.array(TunnelProviderInfoSchema)
4517
+ });
4518
+ const AutomationPrioritySchema = z__namespace.enum(["urgent", "user", "background"]);
4519
+ const AutomationJobKindSchema = z__namespace.enum(["supervisor", "webhook", "agent_loop", "task"]);
4520
+ const AutomationJobStatusSchema = z__namespace.enum([
4521
+ "queued",
4522
+ "dispatching",
4523
+ "running",
4524
+ "completed",
4525
+ "failed",
4526
+ "cancelled"
4527
+ ]);
4528
+ const AutomationJobSummarySchema = z__namespace.object({
4529
+ id: z__namespace.string(),
4530
+ kind: AutomationJobKindSchema,
4531
+ status: AutomationJobStatusSchema,
4532
+ priority: AutomationPrioritySchema,
4533
+ dedupeKey: z__namespace.string(),
4534
+ attempt: z__namespace.number(),
4535
+ maxAttempts: z__namespace.number(),
4536
+ createdAt: z__namespace.number(),
4537
+ updatedAt: z__namespace.number(),
4538
+ dispatchedAt: z__namespace.number().optional(),
4539
+ completedAt: z__namespace.number().optional(),
4540
+ nextRunAt: z__namespace.number().optional(),
4541
+ sessionId: z__namespace.string().optional(),
4542
+ label: z__namespace.string().optional(),
4543
+ projectId: z__namespace.string().optional(),
4544
+ runId: z__namespace.string().optional(),
4545
+ loopId: z__namespace.string().optional(),
4546
+ loopIteration: z__namespace.number().optional(),
4547
+ continuityKey: z__namespace.string().optional(),
4548
+ errorMessage: z__namespace.string().optional(),
4549
+ recovered: z__namespace.boolean().optional()
4550
+ });
4551
+ const AutomationGuardianSummarySchema = z__namespace.object({
4552
+ key: z__namespace.string(),
4553
+ projectId: z__namespace.string(),
4554
+ loopId: z__namespace.string().optional(),
4555
+ sessionId: z__namespace.string(),
4556
+ updatedAt: z__namespace.number(),
4557
+ lastRunId: z__namespace.string().optional(),
4558
+ attached: z__namespace.boolean().optional(),
4559
+ recovered: z__namespace.boolean().optional()
4560
+ });
4561
+ const AutomationGuardianUsageSummarySchema = z__namespace.object({
4562
+ key: z__namespace.string(),
4563
+ projectId: z__namespace.string().optional(),
4564
+ loopId: z__namespace.string().optional(),
4565
+ reuseCount: z__namespace.number(),
4566
+ rememberCount: z__namespace.number(),
4567
+ resetCount: z__namespace.number(),
4568
+ lastUsedAt: z__namespace.number(),
4569
+ currentSessionId: z__namespace.string().optional()
4570
+ });
4571
+ const AutomationAuditEventSummarySchema = z__namespace.object({
4572
+ id: z__namespace.string(),
4573
+ occurredAt: z__namespace.number(),
4574
+ kind: z__namespace.string(),
4575
+ jobId: z__namespace.string().optional(),
4576
+ dedupeKey: z__namespace.string().optional(),
4577
+ sessionId: z__namespace.string().optional(),
4578
+ projectId: z__namespace.string().optional(),
4579
+ runId: z__namespace.string().optional(),
4580
+ loopId: z__namespace.string().optional(),
4581
+ trigger: z__namespace.string().optional(),
4582
+ status: z__namespace.string().optional(),
4583
+ guardianKey: z__namespace.string().optional(),
4584
+ guardianSessionId: z__namespace.string().optional(),
4585
+ message: z__namespace.string().optional()
4586
+ });
4587
+ const AutomationAuditStatsSchema = z__namespace.object({
4588
+ totalEvents: z__namespace.number(),
4589
+ lastEventAt: z__namespace.number().optional(),
4590
+ queuedCount: z__namespace.number(),
4591
+ sessionStartedCount: z__namespace.number(),
4592
+ terminalCompletedCount: z__namespace.number(),
4593
+ terminalFailedCount: z__namespace.number(),
4594
+ terminalCancelledCount: z__namespace.number(),
4595
+ guardianReuseCount: z__namespace.number(),
4596
+ guardianRememberCount: z__namespace.number(),
4597
+ guardianResetCount: z__namespace.number(),
4598
+ sessionReattachedCount: z__namespace.number(),
4599
+ watchdogStopCount: z__namespace.number(),
4600
+ stopRequestCount: z__namespace.number(),
4601
+ guardianEligibleRunCount: z__namespace.number(),
4602
+ guardianReuseRate: z__namespace.number(),
4603
+ activeGuardianCount: z__namespace.number()
4604
+ });
4605
+ const AutomationCountsSchema = z__namespace.object({
4606
+ queued: z__namespace.number(),
4607
+ dispatching: z__namespace.number(),
4608
+ running: z__namespace.number(),
4609
+ completed: z__namespace.number(),
4610
+ failed: z__namespace.number(),
4611
+ cancelled: z__namespace.number()
4612
+ });
4613
+ const AgentLoopSummarySchema = z__namespace.object({
4614
+ id: z__namespace.string(),
4615
+ name: z__namespace.string().optional(),
4616
+ directory: z__namespace.string(),
4617
+ enabled: z__namespace.boolean(),
4618
+ intervalMs: z__namespace.number(),
4619
+ cronExpression: z__namespace.string().optional(),
4620
+ iteration: z__namespace.number(),
4621
+ nextRunAt: z__namespace.number(),
4622
+ runtimeState: z__namespace.string(),
4623
+ phase: z__namespace.string(),
4624
+ lastTriggerSource: z__namespace.string().optional(),
4625
+ lastBriefSummary: z__namespace.string().optional(),
4626
+ lastError: z__namespace.string().optional(),
4627
+ agent: z__namespace.string()
4628
+ });
4629
+ const BootstrapProfileSummarySchema = z__namespace.object({
4630
+ id: z__namespace.string(),
4631
+ name: z__namespace.string().optional(),
4632
+ rootDirectory: z__namespace.string(),
4633
+ intervalMs: z__namespace.number(),
4634
+ enabled: z__namespace.boolean(),
4635
+ status: z__namespace.string(),
4636
+ statusUpdatedAt: z__namespace.number(),
4637
+ lastRunAt: z__namespace.number().optional(),
4638
+ lastRepoCount: z__namespace.number().optional(),
4639
+ lastSuggestionCount: z__namespace.number().optional(),
4640
+ lastError: z__namespace.string().optional()
4641
+ });
4642
+ const AutoDreamProfileSummarySchema = z__namespace.object({
4643
+ id: z__namespace.string(),
4644
+ name: z__namespace.string().optional(),
4645
+ rootDirectory: z__namespace.string(),
4646
+ intervalMs: z__namespace.number(),
4647
+ enabled: z__namespace.boolean(),
4648
+ nextRunAt: z__namespace.number(),
4649
+ status: z__namespace.string(),
4650
+ stage: z__namespace.string(),
4651
+ statusUpdatedAt: z__namespace.number(),
4652
+ lastRunAt: z__namespace.number().optional(),
4653
+ lastMemoryFiles: z__namespace.number().optional(),
4654
+ lastError: z__namespace.string().optional()
4655
+ });
4656
+ const AutomationStateSchema = z__namespace.object({
4657
+ updatedAt: z__namespace.number(),
4658
+ counts: AutomationCountsSchema,
4659
+ recentJobs: z__namespace.array(AutomationJobSummarySchema),
4660
+ guardians: z__namespace.array(AutomationGuardianSummarySchema).optional(),
4661
+ guardianUsage: z__namespace.array(AutomationGuardianUsageSummarySchema).optional(),
4662
+ auditStats: AutomationAuditStatsSchema.optional(),
4663
+ recentAuditEvents: z__namespace.array(AutomationAuditEventSummarySchema).optional(),
4664
+ loops: z__namespace.array(AgentLoopSummarySchema).optional(),
4665
+ bootstrapProfiles: z__namespace.array(BootstrapProfileSummarySchema).optional(),
4666
+ autoDreamProfiles: z__namespace.array(AutoDreamProfileSummarySchema).optional()
4667
+ });
4668
+ const BriefMessageSchema = z__namespace.object({
4669
+ loopId: z__namespace.string(),
4670
+ loopName: z__namespace.string().optional(),
4671
+ status: z__namespace.enum(["completed", "failed", "cancelled"]),
4672
+ summary: z__namespace.string(),
4673
+ detail: z__namespace.string(),
4674
+ generatedAt: z__namespace.number(),
4675
+ sessionId: z__namespace.string().optional()
4676
+ });
4677
+ const CliInstallSourceSchema = z__namespace.enum([
4678
+ "npm-global",
4679
+ "local-source",
4680
+ "unknown"
4681
+ ]);
4682
+ const CliInstallInfoSchema = z__namespace.object({
4683
+ source: CliInstallSourceSchema,
4684
+ canSelfUpgrade: z__namespace.boolean()
4685
+ });
4686
+ z__namespace.object({
4687
+ status: z__namespace.union([
4688
+ z__namespace.enum(["running", "shutting-down"]),
4689
+ z__namespace.string()
4690
+ ]),
4691
+ pid: z__namespace.number().optional(),
4692
+ httpPort: z__namespace.number().optional(),
4693
+ startTime: z__namespace.union([z__namespace.number(), z__namespace.string()]).optional(),
4694
+ startedAt: z__namespace.number().optional(),
4695
+ startedWithCliVersion: z__namespace.string().optional(),
4696
+ shutdownRequestedAt: z__namespace.number().optional(),
4697
+ shutdownSource: z__namespace.union([
4698
+ z__namespace.enum(["mobile-app", "cli", "os-signal", "unknown"]),
4699
+ z__namespace.string()
4700
+ ]).optional(),
4701
+ tailscale: TailscaleInfoSchema.optional(),
4702
+ tunnels: TunnelStateSchema.optional(),
4703
+ automation: AutomationStateSchema.optional(),
4704
+ recentBriefs: z__namespace.array(BriefMessageSchema).optional(),
4705
+ cliInstall: CliInstallInfoSchema.optional(),
4706
+ killed: z__namespace.boolean().optional()
4707
+ });
4708
+
4709
+ const KnowledgeEntryTypeSchema = z__namespace.enum([
4710
+ "discovery",
4711
+ // New insight or finding
4712
+ "decision",
4713
+ // Architecture / tech choice
4714
+ "fix",
4715
+ // Bug fix record
4716
+ "convention",
4717
+ // Code convention / process rule
4718
+ "warning"
4719
+ // Known pitfall or gotcha
4720
+ ]);
4721
+ const KnowledgeContributorTypeSchema = z__namespace.enum([
4722
+ "session",
4723
+ // Auto-generated by Claude session
4724
+ "supervisor",
4725
+ // Generated by Supervisor analysis
4726
+ "user"
4727
+ // Manually added by user
4728
+ ]);
4729
+ const KnowledgeActionSchema = z__namespace.enum([
4730
+ "create",
4731
+ // New entry
4732
+ "amend",
4733
+ // Correction / supplement
4734
+ "supersede",
4735
+ // Replace old knowledge
4736
+ "verify"
4737
+ // Confirm still valid
4738
+ ]);
4739
+ const KnowledgeStatusSchema = z__namespace.enum([
4740
+ "active",
4741
+ // Currently valid
4742
+ "superseded",
4743
+ // Replaced by newer knowledge
4744
+ "archived"
4745
+ // Manually archived by user
4746
+ ]);
4747
+ const KnowledgeConfidenceSchema = z__namespace.enum(["high", "medium", "low"]);
4748
+ z__namespace.object({
4749
+ entryType: KnowledgeEntryTypeSchema,
4750
+ contributorType: KnowledgeContributorTypeSchema,
4751
+ action: KnowledgeActionSchema,
4752
+ title: z__namespace.string().min(1).max(200),
4753
+ content: z__namespace.string().min(1),
4754
+ // Structured SOAP-like fields (optional)
4755
+ request: z__namespace.string().optional(),
4756
+ // S: What the user asked
4757
+ findings: z__namespace.string().optional(),
4758
+ // O: What was discovered
4759
+ analysis: z__namespace.string().optional(),
4760
+ // A: Root cause / assessment
4761
+ outcome: z__namespace.string().optional(),
4762
+ // P: What was done
4763
+ nextSteps: z__namespace.string().optional(),
4764
+ // Follow-up suggestions
4765
+ tags: z__namespace.array(z__namespace.string().max(50)).max(20).default([]),
4766
+ confidence: KnowledgeConfidenceSchema.default("medium"),
4767
+ sessionId: z__namespace.string().optional(),
4768
+ model: z__namespace.string().optional(),
4769
+ supersedesId: z__namespace.string().optional(),
4770
+ relatedIds: z__namespace.array(z__namespace.string()).max(10).default([]),
4771
+ affectedFiles: z__namespace.array(z__namespace.string()).max(50).default([])
4772
+ });
4773
+ z__namespace.object({
4774
+ status: KnowledgeStatusSchema.optional(),
4775
+ pinned: z__namespace.boolean().optional(),
4776
+ title: z__namespace.string().min(1).max(200).optional(),
4777
+ content: z__namespace.string().min(1).optional(),
4778
+ tags: z__namespace.array(z__namespace.string().max(50)).max(20).optional(),
4779
+ confidence: KnowledgeConfidenceSchema.optional()
4780
+ });
4781
+ z__namespace.object({
4782
+ entryType: KnowledgeEntryTypeSchema.optional(),
4783
+ status: KnowledgeStatusSchema.optional(),
4784
+ tags: z__namespace.array(z__namespace.string()).optional(),
4785
+ search: z__namespace.string().max(500).optional(),
4786
+ limit: z__namespace.number().int().min(1).max(100).default(20),
4787
+ offset: z__namespace.number().int().min(0).default(0)
4788
+ });
4789
+ const ProjectProfileSchema = z__namespace.object({
4790
+ techStack: z__namespace.array(z__namespace.string()),
4791
+ architectureType: z__namespace.string().optional(),
4792
+ knownPitfalls: z__namespace.array(z__namespace.string()),
4793
+ coreConventions: z__namespace.array(z__namespace.string()),
4794
+ lastUpdatedAt: z__namespace.number(),
4795
+ lastUpdatedBy: z__namespace.string().optional()
4796
+ });
4797
+ const KnowledgeInjectionModeSchema = z__namespace.enum(["auto", "full", "minimal"]);
4798
+ z__namespace.object({
4799
+ mode: KnowledgeInjectionModeSchema,
4800
+ contextHints: z__namespace.array(z__namespace.string()).optional()
4801
+ // Keywords from user message for relevance
4802
+ });
4803
+ z__namespace.object({
4804
+ profile: ProjectProfileSchema.nullable(),
4805
+ entries: z__namespace.array(z__namespace.object({
4806
+ id: z__namespace.string(),
4807
+ entryType: KnowledgeEntryTypeSchema,
4808
+ title: z__namespace.string(),
4809
+ content: z__namespace.string(),
4810
+ tags: z__namespace.array(z__namespace.string()),
4811
+ confidence: KnowledgeConfidenceSchema,
4812
+ createdAt: z__namespace.string()
4813
+ }))
4814
+ });
4815
+ const KnowledgeChainRelationSchema = z__namespace.object({
4816
+ from: z__namespace.string(),
4817
+ to: z__namespace.string(),
4818
+ type: z__namespace.enum(["supersedes", "related"])
4819
+ });
4820
+ const KnowledgeChainEntrySchema = z__namespace.object({
4821
+ id: z__namespace.string(),
4822
+ entryType: KnowledgeEntryTypeSchema,
4823
+ action: KnowledgeActionSchema,
4824
+ status: KnowledgeStatusSchema,
4825
+ title: z__namespace.string(),
4826
+ content: z__namespace.string(),
4827
+ tags: z__namespace.array(z__namespace.string()),
4828
+ confidence: KnowledgeConfidenceSchema,
4829
+ supersedesId: z__namespace.string().nullable(),
4830
+ createdAt: z__namespace.string()
4831
+ });
4832
+ z__namespace.object({
4833
+ chain: z__namespace.array(KnowledgeChainEntrySchema),
4834
+ relations: z__namespace.array(KnowledgeChainRelationSchema)
4835
+ });
4836
+ const CrossProjectSearchResultSchema = z__namespace.object({
4837
+ id: z__namespace.string(),
4838
+ projectId: z__namespace.string(),
4839
+ projectPath: z__namespace.string(),
4840
+ entryType: KnowledgeEntryTypeSchema,
4841
+ title: z__namespace.string(),
4842
+ content: z__namespace.string(),
4843
+ tags: z__namespace.array(z__namespace.string()),
4844
+ confidence: KnowledgeConfidenceSchema,
4845
+ similarity: z__namespace.number().optional(),
4846
+ // Present when using semantic search
4847
+ createdAt: z__namespace.string()
4848
+ });
4849
+ z__namespace.object({
4850
+ results: z__namespace.array(CrossProjectSearchResultSchema),
4851
+ total: z__namespace.number()
4852
+ });
4853
+ z__namespace.object({
4854
+ projectId: z__namespace.string(),
4855
+ sessionId: z__namespace.string(),
4856
+ model: z__namespace.string(),
4857
+ turnId: z__namespace.string(),
4858
+ turnData: z__namespace.object({
4859
+ userMessage: z__namespace.string().max(2e3),
4860
+ assistantText: z__namespace.string().max(5e3),
4861
+ fileEdits: z__namespace.array(z__namespace.object({
4862
+ path: z__namespace.string(),
4863
+ type: z__namespace.enum(["create", "edit"])
4864
+ })).max(50),
4865
+ toolCallCount: z__namespace.number().int(),
4866
+ outputTokens: z__namespace.number().int()
4867
+ })
4868
+ });
4869
+
4870
+ const VoiceTokenAllowedSchema = z__namespace.object({
4871
+ allowed: z__namespace.literal(true),
4872
+ token: z__namespace.string(),
4873
+ agentId: z__namespace.string(),
4874
+ elevenUserId: z__namespace.string(),
4875
+ usedSeconds: z__namespace.number(),
4876
+ limitSeconds: z__namespace.number()
4877
+ });
4878
+ const VoiceTokenDeniedSchema = z__namespace.object({
4879
+ allowed: z__namespace.literal(false),
4880
+ reason: z__namespace.enum(["voice_limit_reached", "subscription_required"]),
4881
+ usedSeconds: z__namespace.number(),
4882
+ limitSeconds: z__namespace.number(),
4883
+ agentId: z__namespace.string()
4884
+ });
4885
+ z__namespace.discriminatedUnion("allowed", [
4886
+ VoiceTokenAllowedSchema,
4887
+ VoiceTokenDeniedSchema
4888
+ ]);
4889
+
4890
+ const CODEX_APP_SERVER_BACKEND = "codex-app-server";
4891
+ const CODEX_MCP_LEGACY_BACKEND = "codex-mcp-legacy";
4892
+ const CodexBackendModeSchema = z__namespace.enum([
4893
+ "auto",
4894
+ CODEX_APP_SERVER_BACKEND,
4895
+ CODEX_MCP_LEGACY_BACKEND
4896
+ ]);
4897
+ const CodexRequestedBackendSchema = CodexBackendModeSchema;
4898
+ const CodexResolvedBackendSchema = z__namespace.enum([
4899
+ CODEX_APP_SERVER_BACKEND,
4900
+ CODEX_MCP_LEGACY_BACKEND
4901
+ ]);
4902
+ const CodexConfigModeSchema = z__namespace.enum([
4903
+ "inherit",
4904
+ "managed-profile",
4905
+ "managed-overrides"
4906
+ ]);
4907
+ const CODEX_REQUESTED_BACKEND_ALIASES = {
4908
+ auto: ["", "auto"],
4909
+ [CODEX_APP_SERVER_BACKEND]: ["app-server", "appserver", CODEX_APP_SERVER_BACKEND],
4910
+ [CODEX_MCP_LEGACY_BACKEND]: [
4911
+ "legacy",
4912
+ "mcp",
4913
+ "mcp-legacy",
4914
+ CODEX_MCP_LEGACY_BACKEND
4915
+ ]
4916
+ };
4917
+ new Map(
4918
+ Object.entries(CODEX_REQUESTED_BACKEND_ALIASES).flatMap(
4919
+ ([backend, aliases]) => aliases.map((alias) => [alias, backend])
4920
+ )
4921
+ );
4922
+
4923
+ function isTemplateAwareUrl(value) {
4924
+ if (!value) return true;
4925
+ if (/^\$\{[A-Z_][A-Z0-9_]*(:-[^}]*)?\}$/.test(value)) return true;
4926
+ try {
4927
+ new URL(value);
4928
+ return true;
4929
+ } catch {
4930
+ return false;
4931
+ }
4932
+ }
4933
+ const BuiltInAIBackendProfileIdSchema = z.z.enum([
4934
+ "anthropic",
4935
+ "deepseek",
4936
+ "zai",
4937
+ "openai",
4938
+ "azure-openai",
4939
+ "minimax",
4940
+ "kimi"
4941
+ ]);
4942
+ new Set(
4943
+ BuiltInAIBackendProfileIdSchema.options
4944
+ );
4945
+ const EnvironmentVariableSchema = z.z.object({
4946
+ name: z.z.string().regex(/^[A-Z_][A-Z0-9_]*$/, "Invalid environment variable name"),
4947
+ value: z.z.string()
4948
+ });
4949
+ const ProfileCompatibilitySchema = z.z.object({
4950
+ claude: z.z.boolean().default(true),
4951
+ codex: z.z.boolean().default(true),
4952
+ gemini: z.z.boolean().default(true)
4953
+ });
4954
+ const AnthropicConfigSchema = z.z.object({
4955
+ baseUrl: z.z.string().refine(isTemplateAwareUrl, {
4956
+ message: "Must be a valid URL or ${VAR} or ${VAR:-default} template string"
4957
+ }).optional(),
4958
+ authToken: z.z.string().optional(),
4959
+ model: z.z.string().optional()
4960
+ });
4961
+ const OpenAIConfigSchema = z.z.object({
4962
+ apiKey: z.z.string().optional(),
4963
+ baseUrl: z.z.string().refine(isTemplateAwareUrl, {
4964
+ message: "Must be a valid URL or ${VAR} or ${VAR:-default} template string"
4965
+ }).optional(),
4966
+ model: z.z.string().optional()
4967
+ });
4968
+ const AzureOpenAIConfigSchema = z.z.object({
4969
+ apiKey: z.z.string().optional(),
4970
+ endpoint: z.z.string().refine(isTemplateAwareUrl, {
4971
+ message: "Must be a valid URL or ${VAR} or ${VAR:-default} template string"
4972
+ }).optional(),
4973
+ apiVersion: z.z.string().optional(),
4974
+ deploymentName: z.z.string().optional()
4975
+ });
4976
+ const TogetherAIConfigSchema = z.z.object({
4977
+ apiKey: z.z.string().optional(),
4978
+ model: z.z.string().optional()
4979
+ });
4980
+ const CodexConfigSchema = z.z.object({
4981
+ backendMode: CodexBackendModeSchema.optional(),
4982
+ configMode: CodexConfigModeSchema.optional(),
4983
+ codexProfileName: z.z.string().optional(),
4984
+ model: z.z.string().optional(),
4985
+ reasoningEffort: z.z.string().optional(),
4986
+ reasoningSummary: z.z.string().optional(),
4987
+ verbosity: z.z.string().optional(),
4988
+ personality: z.z.string().optional(),
4989
+ serviceTier: z.z.string().optional(),
4990
+ webSearchEnabled: z.z.boolean().optional(),
4991
+ approvalPolicy: z.z.string().optional(),
4992
+ sandboxMode: z.z.string().optional()
4993
+ });
4994
+ const TmuxConfigSchema = z.z.object({
4995
+ sessionName: z.z.string().optional(),
4996
+ tmpDir: z.z.string().optional(),
4997
+ updateEnvironment: z.z.boolean().optional()
4998
+ });
4999
+ const CustomModelSchema = z.z.object({
5000
+ id: z.z.string().min(1),
5001
+ name: z.z.string().min(1).max(100),
5002
+ description: z.z.string().nullish()
5003
+ });
5004
+ const DefaultPermissionModeSchema = z.z.enum([
5005
+ "default",
5006
+ "acceptEdits",
5007
+ "auto",
5008
+ "bypassPermissions",
5009
+ "plan",
5010
+ "read-only",
5011
+ "safe-yolo",
5012
+ "yolo"
5013
+ ]);
5014
+ z.z.object({
5015
+ id: z.z.string().min(1),
5016
+ name: z.z.string().min(1).max(100),
5017
+ description: z.z.string().max(500).optional(),
5018
+ anthropicConfig: AnthropicConfigSchema.optional(),
5019
+ openaiConfig: OpenAIConfigSchema.optional(),
5020
+ azureOpenAIConfig: AzureOpenAIConfigSchema.optional(),
5021
+ togetherAIConfig: TogetherAIConfigSchema.optional(),
5022
+ codexConfig: CodexConfigSchema.optional(),
5023
+ tmuxConfig: TmuxConfigSchema.optional(),
5024
+ startupBashScript: z.z.string().optional(),
5025
+ environmentVariables: z.z.array(EnvironmentVariableSchema).default([]),
5026
+ customModels: z.z.array(CustomModelSchema).optional(),
5027
+ modelMappings: z.z.record(z.z.string(), z.z.string()).optional(),
5028
+ defaultSessionType: z.z.enum(["simple", "worktree"]).optional(),
5029
+ defaultPermissionMode: DefaultPermissionModeSchema.optional(),
5030
+ defaultModelMode: z.z.string().optional(),
5031
+ compatibility: ProfileCompatibilitySchema.default({
5032
+ claude: true,
5033
+ codex: true,
5034
+ gemini: true
5035
+ }),
5036
+ isBuiltIn: z.z.boolean().default(false),
5037
+ createdAt: z.z.number().default(() => Date.now()),
5038
+ updatedAt: z.z.number().default(() => Date.now()),
5039
+ version: z.z.string().default("1.0.0")
5040
+ });
5041
+ const RuntimeProfileSourceSchema = z.z.enum([
5042
+ "built-in-profile",
5043
+ "account-profile",
5044
+ "local-profile",
5045
+ "ad-hoc"
5046
+ ]);
5047
+ const RuntimeProfileTrustSchema = z.z.enum(["trusted", "untrusted"]);
5048
+ const RESOLVED_RUNTIME_PROFILE_SCHEMA_VERSION = 1;
5049
+ const ResolvedRuntimeProfileSchema = z.z.object({
5050
+ schemaVersion: z.z.literal(RESOLVED_RUNTIME_PROFILE_SCHEMA_VERSION).default(RESOLVED_RUNTIME_PROFILE_SCHEMA_VERSION),
5051
+ profileId: z.z.string().optional(),
5052
+ profileName: z.z.string().optional(),
5053
+ source: RuntimeProfileSourceSchema,
5054
+ trust: RuntimeProfileTrustSchema,
5055
+ isBuiltIn: z.z.boolean().optional(),
5056
+ compatibility: ProfileCompatibilitySchema.optional(),
5057
+ environmentVariables: z.z.record(z.z.string(), z.z.string()).default({}),
5058
+ startupBashScript: z.z.string().optional(),
5059
+ customModels: z.z.array(CustomModelSchema).optional(),
5060
+ modelMappings: z.z.record(z.z.string(), z.z.string()).optional(),
5061
+ defaultSessionType: z.z.enum(["simple", "worktree"]).optional(),
5062
+ defaultPermissionMode: DefaultPermissionModeSchema.optional(),
5063
+ defaultModelMode: z.z.string().optional()
5064
+ });
5065
+
5066
+ const TaskPrioritySchema = z__namespace.enum([
5067
+ "urgent",
5068
+ // User-initiated, needs immediate execution
5069
+ "user",
5070
+ // Normal user-created task (default)
5071
+ "background"
5072
+ // Automated / scheduled tasks
5073
+ ]);
5074
+ const TaskStatusSchema = z__namespace.enum([
5075
+ "queued",
5076
+ // Waiting in queue
5077
+ "dispatching",
5078
+ // Being sent to CLI daemon
5079
+ "running",
5080
+ // Executing on CLI
5081
+ "completed",
5082
+ // Finished successfully
5083
+ "failed",
5084
+ // Execution failed
5085
+ "cancelled"
5086
+ // Cancelled by user
5087
+ ]);
5088
+ const TaskTriggerTypeSchema = z__namespace.enum([
5089
+ "manual",
5090
+ // Created from App by user
5091
+ "cron",
5092
+ // Created by TriggerSchedule
5093
+ "webhook"
5094
+ // Created by WebhookTrigger
5095
+ ]);
5096
+ z__namespace.object({
5097
+ id: z__namespace.string(),
5098
+ projectId: z__namespace.string().nullable(),
5099
+ machineId: z__namespace.string(),
5100
+ priority: TaskPrioritySchema,
5101
+ status: TaskStatusSchema,
5102
+ triggerType: TaskTriggerTypeSchema,
5103
+ triggerRef: z__namespace.string().optional(),
5104
+ attempt: z__namespace.number(),
5105
+ maxAttempts: z__namespace.number(),
5106
+ sessionId: z__namespace.string().optional(),
5107
+ errorMessage: z__namespace.string().optional(),
5108
+ dispatchedAt: z__namespace.number().optional(),
5109
+ completedAt: z__namespace.number().optional(),
5110
+ createdAt: z__namespace.number(),
5111
+ updatedAt: z__namespace.number(),
5112
+ // Encrypted prompt preview (first 100 chars)
5113
+ promptPreview: z__namespace.string().optional(),
5114
+ // Names of bound skills for display
5115
+ skillNames: z__namespace.array(z__namespace.string()).optional()
5116
+ });
5117
+ z__namespace.object({
5118
+ projectId: z__namespace.string().optional(),
5119
+ machineId: z__namespace.string(),
5120
+ prompt: z__namespace.string().min(1),
5121
+ // Encrypted by App
5122
+ priority: TaskPrioritySchema.default("user"),
5123
+ maxAttempts: z__namespace.number().int().min(1).max(10).default(3),
5124
+ skillIds: z__namespace.array(z__namespace.string()).max(10).default([]),
5125
+ // Profile binding (wire 0.15.0). Business key — built-in id like
5126
+ // "anthropic" or AiBackendProfile.profileKey for the account. Optional:
5127
+ // when omitted the server falls back to Project.supervisorConfig.defaultProfileId
5128
+ // via the unified runtimeProfileResolver (feature-flagged).
5129
+ profileId: z__namespace.string().optional()
5130
+ });
5131
+ z__namespace.object({
5132
+ type: z__namespace.literal("task-trigger"),
5133
+ taskId: z__namespace.string(),
5134
+ prompt: z__namespace.string(),
5135
+ // Encrypted prompt
5136
+ directory: z__namespace.string(),
5137
+ // Project directory on machine
5138
+ priority: TaskPrioritySchema,
5139
+ projectId: z__namespace.string().optional(),
5140
+ resultToken: z__namespace.string().optional(),
5141
+ skillContents: z__namespace.array(z__namespace.object({
5142
+ name: z__namespace.string(),
5143
+ content: z__namespace.string()
5144
+ })).optional(),
5145
+ agentType: z__namespace.string().nullable().optional(),
5146
+ // "claude" | "codex" | "gemini" — null = inherit CLI default
5147
+ modelOverride: z__namespace.string().nullable().optional(),
5148
+ // e.g. "claude-sonnet-4-20250514" — null = agent default
5149
+ // Profile binding for this task. `profileId` references the AIBackendProfile
5150
+ // selected when the task was created (Task.profileId column). `runtimeProfile`
5151
+ // is the resolved snapshot (env vars, startup script, permission mode, etc.)
5152
+ // that the CLI should honor when spawning the session. Both optional for
5153
+ // backward compatibility; starting from wire 0.14.0 + server unified resolver
5154
+ // these are always populated for scheduled/webhook/manual tasks.
5155
+ profileId: z__namespace.string().optional(),
5156
+ runtimeProfile: ResolvedRuntimeProfileSchema.optional()
5157
+ });
5158
+ const TaskOutcomeSchema = z__namespace.enum([
5159
+ "completed",
5160
+ "failed",
5161
+ "blocked"
5162
+ ]);
5163
+ z__namespace.object({
5164
+ taskId: z__namespace.string(),
5165
+ status: TaskStatusSchema,
5166
+ outcome: TaskOutcomeSchema.optional(),
5167
+ sessionId: z__namespace.string().optional(),
5168
+ errorMessage: z__namespace.string().optional()
5169
+ });
5170
+ z__namespace.object({
5171
+ type: z__namespace.literal("task-status-changed"),
5172
+ taskId: z__namespace.string(),
5173
+ machineId: z__namespace.string().optional(),
5174
+ status: TaskStatusSchema,
5175
+ sessionId: z__namespace.string().optional(),
5176
+ errorMessage: z__namespace.string().optional(),
5177
+ completedAt: z__namespace.number().optional()
5178
+ });
5179
+
5180
+ z__namespace.object({
5181
+ id: z__namespace.string(),
5182
+ projectId: z__namespace.string().nullable(),
5183
+ name: z__namespace.string(),
5184
+ description: z__namespace.string().optional(),
5185
+ content: z__namespace.string(),
5186
+ attachments: z__namespace.array(z__namespace.string()),
5187
+ sourceKnowledgeId: z__namespace.string().optional(),
5188
+ archived: z__namespace.boolean(),
5189
+ createdAt: z__namespace.number(),
5190
+ updatedAt: z__namespace.number()
5191
+ });
5192
+ z__namespace.object({
5193
+ projectId: z__namespace.string().optional(),
5194
+ name: z__namespace.string().min(1).max(100),
5195
+ description: z__namespace.string().max(500).optional(),
5196
+ content: z__namespace.string().min(1).max(5e4),
5197
+ attachments: z__namespace.array(z__namespace.string()).max(10).default([]),
5198
+ sourceKnowledgeId: z__namespace.string().optional()
5199
+ });
5200
+ z__namespace.object({
5201
+ name: z__namespace.string().min(1).max(100).optional(),
5202
+ description: z__namespace.string().max(500).optional(),
5203
+ content: z__namespace.string().min(1).max(5e4).optional(),
5204
+ attachments: z__namespace.array(z__namespace.string()).max(10).optional(),
5205
+ archived: z__namespace.boolean().optional()
5206
+ });
5207
+ z__namespace.object({
5208
+ name: z__namespace.string(),
5209
+ content: z__namespace.string()
5210
+ });
5211
+
5212
+ const InboxCategorySchema = z__namespace.enum([
5213
+ "task",
5214
+ // Task queue events (completed, failed, cancelled)
5215
+ "trigger",
5216
+ // Cron/webhook trigger fired
5217
+ "supervisor",
5218
+ // Supervisor run results
5219
+ "session",
5220
+ // Session lifecycle events
5221
+ "knowledge",
5222
+ // Knowledge base changes
5223
+ "system"
5224
+ // System notifications
5225
+ ]);
5226
+ const InboxSeveritySchema = z__namespace.enum([
5227
+ "info",
5228
+ "warning",
5229
+ "error"
5230
+ ]);
5231
+ const InboxItemSummarySchema = z__namespace.object({
5232
+ id: z__namespace.string(),
5233
+ category: InboxCategorySchema,
5234
+ eventType: z__namespace.string(),
5235
+ // e.g. "task.completed", "trigger.cron.fired"
5236
+ severity: InboxSeveritySchema,
5237
+ title: z__namespace.string(),
5238
+ body: z__namespace.string().optional(),
5239
+ read: z__namespace.boolean(),
5240
+ referenceUrl: z__namespace.string().optional(),
5241
+ // Deep link, e.g. "/machine/xxx/tasks"
5242
+ refType: z__namespace.string().optional(),
5243
+ // Polymorphic ref: "task" | "trigger" | "session" | ...
5244
+ refId: z__namespace.string().optional(),
5245
+ // ID of referenced entity
5246
+ groupKey: z__namespace.string().optional(),
5247
+ // Dedup key (same source within 1h → skip)
5248
+ createdAt: z__namespace.number()
5249
+ });
5250
+ z__namespace.object({
5251
+ type: z__namespace.literal("inbox-new-item"),
5252
+ item: InboxItemSummarySchema
5253
+ });
5254
+ z__namespace.object({
5255
+ type: z__namespace.literal("inbox-unread-count"),
5256
+ count: z__namespace.number()
5257
+ });
5258
+
5259
+ const SessionEventTypeSchema = z__namespace.enum([
5260
+ "file_edit",
5261
+ // File created/modified/deleted
5262
+ "bash_command",
5263
+ // Shell command executed
5264
+ "tool_call",
5265
+ // Tool invocation (Read, Grep, etc.)
5266
+ "git_operation",
5267
+ // Git commit, push, branch, etc.
5268
+ "error",
5269
+ // Error occurred during session
5270
+ "session_start",
5271
+ // Session started
5272
+ "session_end"
5273
+ // Session ended
5274
+ ]);
5275
+ const SessionEventSummarySchema = z__namespace.object({
5276
+ id: z__namespace.string(),
5277
+ sessionId: z__namespace.string(),
5278
+ eventType: SessionEventTypeSchema,
5279
+ summary: z__namespace.string(),
5280
+ // Human-readable one-liner
5281
+ detail: z__namespace.record(z__namespace.string(), z__namespace.unknown()).optional(),
5282
+ // Structured metadata (JSON)
5283
+ createdAt: z__namespace.number()
5284
+ });
5285
+ z__namespace.object({
5286
+ sessionId: z__namespace.string(),
5287
+ eventType: SessionEventTypeSchema,
5288
+ summary: z__namespace.string().max(500),
5289
+ detail: z__namespace.record(z__namespace.string(), z__namespace.unknown()).optional()
5290
+ });
5291
+ z__namespace.object({
5292
+ type: z__namespace.literal("session-event-created"),
5293
+ event: SessionEventSummarySchema
5294
+ });
5295
+
5296
+ z__namespace.object({
5297
+ /** Shell to use (defaults to user's default shell) */
5298
+ shell: z__namespace.string().optional(),
5299
+ /** Working directory */
5300
+ cwd: z__namespace.string().optional(),
5301
+ /** Initial terminal dimensions */
5302
+ cols: z__namespace.number().int().min(1).max(500).optional(),
5303
+ rows: z__namespace.number().int().min(1).max(200).optional()
5304
+ });
5305
+ z__namespace.object({
5306
+ success: z__namespace.boolean(),
5307
+ terminalId: z__namespace.string().optional(),
5308
+ error: z__namespace.string().optional()
5309
+ });
5310
+ z__namespace.object({
5311
+ terminalId: z__namespace.string(),
5312
+ cols: z__namespace.number().int().min(1).max(500),
5313
+ rows: z__namespace.number().int().min(1).max(200)
5314
+ });
5315
+ z__namespace.object({
5316
+ terminalId: z__namespace.string()
5317
+ });
5318
+ z__namespace.object({
5319
+ machineId: z__namespace.string(),
5320
+ terminalId: z__namespace.string(),
5321
+ data: z__namespace.string()
5322
+ });
5323
+ z__namespace.object({
5324
+ machineId: z__namespace.string(),
5325
+ terminalId: z__namespace.string(),
5326
+ data: z__namespace.string()
5327
+ });
5328
+ z__namespace.object({
5329
+ machineId: z__namespace.string(),
5330
+ terminalId: z__namespace.string(),
5331
+ exitCode: z__namespace.number()
5332
+ });
5333
+
5334
+ const sessionProgressTodoStatusSchema = z__namespace.enum([
5335
+ "pending",
5336
+ "in_progress",
5337
+ "completed"
5338
+ ]);
5339
+ const sessionProgressTodoSchema = z__namespace.object({
5340
+ content: z__namespace.string(),
5341
+ status: sessionProgressTodoStatusSchema,
5342
+ /** SDK-native: imperative-present form shown when status is in_progress. */
5343
+ activeForm: z__namespace.string().optional(),
5344
+ /** Optional phase/stage label a step belongs to, e.g. "Phase 2". */
5345
+ stage: z__namespace.string().optional(),
5346
+ /**
5347
+ * Carried over from SDK's `TodoWriteOutput.verificationNudgeNeeded` — SDK
5348
+ * flags items it suspects were marked completed without verification.
5349
+ */
5350
+ verificationNudgeNeeded: z__namespace.boolean().optional()
5351
+ });
5352
+ const sessionProgressListSchema = z__namespace.object({
5353
+ /** Stable UUID for tab switching / explicit Agent addressing. */
5354
+ id: z__namespace.string(),
5355
+ /** Short human-readable label; auto-derived from first todo if absent. */
5356
+ label: z__namespace.string().optional(),
5357
+ todos: z__namespace.array(sessionProgressTodoSchema),
5358
+ /** Optional overall stage for this list (set via MCP). */
5359
+ currentStage: z__namespace.string().optional(),
5360
+ /** Optional blocker list (set via MCP). */
5361
+ blockers: z__namespace.array(z__namespace.string()).optional(),
5362
+ startedAt: z__namespace.number(),
5363
+ updatedAt: z__namespace.number(),
5364
+ /** When this list stopped being active (got pushed to history). */
5365
+ archivedAt: z__namespace.number().optional(),
5366
+ /**
5367
+ * Tool-call message IDs for file-editing tools (Edit/Write/MultiEdit/
5368
+ * NotebookEdit) that ran while this list was the active one. Consumers
5369
+ * resolve these against the session message stream to render per-list
5370
+ * file change summaries without duplicating diff content into metadata.
5371
+ */
5372
+ toolCallIds: z__namespace.array(z__namespace.string()).optional(),
5373
+ /**
5374
+ * Timestamp at which an auto-summary was triggered for this list's
5375
+ * completion (all todos completed → all completed transition). Dedup flag
5376
+ * so the CLI hook only fires ONE synthetic summary-trigger message per
5377
+ * list lifecycle, even if subsequent TodoWrite calls keep it all done.
5378
+ */
5379
+ summaryGeneratedAt: z__namespace.number().optional()
5380
+ });
5381
+ z__namespace.object({
5382
+ /** Ordered by startedAt asc; last item is typically the active one. */
5383
+ lists: z__namespace.array(sessionProgressListSchema).optional(),
5384
+ /** Points at the active list within `lists`. */
5385
+ currentListId: z__namespace.string().optional(),
5386
+ /**
5387
+ * Legacy flat fields. Still written for backward compat with older
5388
+ * readers — kept in sync with `lists[currentListId]` on each update.
5389
+ */
5390
+ todos: z__namespace.array(sessionProgressTodoSchema).optional(),
5391
+ currentStage: z__namespace.string().optional(),
5392
+ blockers: z__namespace.array(z__namespace.string()).optional(),
5393
+ updatedAt: z__namespace.number()
5394
+ });
5395
+ const sessionSummaryStateSchema = z__namespace.object({
5396
+ goal: z__namespace.string(),
5397
+ currentFocus: z__namespace.string().optional(),
5398
+ keyDecisions: z__namespace.array(z__namespace.string()).optional(),
5399
+ openQuestions: z__namespace.array(z__namespace.string()).optional(),
5400
+ impactScope: z__namespace.array(z__namespace.string()).optional(),
5401
+ updatedAt: z__namespace.number()
5402
+ });
5403
+ const sessionSummaryRefreshActiveRequestSchema = z__namespace.object({
5404
+ requestId: z__namespace.string().min(1),
5405
+ requestedAt: z__namespace.number(),
5406
+ requester: z__namespace.enum(["happy-agent", "app", "system"]),
5407
+ command: z__namespace.literal("summary-refresh"),
5408
+ requireSummary: z__namespace.boolean()
5409
+ });
5410
+ const sessionSummaryRefreshRecentEntrySchema = z__namespace.object({
5411
+ requestId: z__namespace.string().min(1),
5412
+ status: z__namespace.enum(["applied", "superseded"]),
5413
+ resolvedAt: z__namespace.number(),
5414
+ summaryUpdatedAt: z__namespace.number().optional(),
5415
+ supersededByRequestId: z__namespace.string().min(1).optional()
5416
+ });
5417
+ const sessionSummaryRefreshStateSchema = z__namespace.object({
5418
+ protocolVersion: z__namespace.literal(1),
5419
+ active: sessionSummaryRefreshActiveRequestSchema.optional(),
5420
+ recent: z__namespace.array(sessionSummaryRefreshRecentEntrySchema).optional()
5421
+ });
5422
+
5423
+ const HAPPY_MCP_TOOL_NAMES = [
5424
+ "change_title",
5425
+ "query_project_knowledge",
5426
+ "update_progress",
5427
+ "update_session_summary"
5428
+ ];
5429
+ const HAPPY_MCP_TOOL_SPECS = {
5430
+ change_title: {
5431
+ title: "Change Title",
5432
+ description: 'Set or update the chat session title. Titles should be short (under 50 chars) and action-oriented, e.g. "Fix auth token refresh".',
5433
+ failureLabel: "Failed to change chat title",
5434
+ inputSchema: {
5435
+ title: z.z.string().describe("The new title for the chat session")
5436
+ },
5437
+ hideSuccessfulCall: true,
5438
+ autoApproveByDefault: true,
5439
+ permissionAction: "Waiting for approval to update chat title",
5440
+ dynamicAction: "Updating chat title",
5441
+ fallbackAction: "Update chat title",
5442
+ reasonPhrases: ["title update", "title updates", "change_title"]
5443
+ },
5444
+ query_project_knowledge: {
5445
+ title: "Project Knowledge",
5446
+ description: "Search the project knowledge base for relevant context, past decisions, known pitfalls, and conventions.",
5447
+ failureLabel: "Knowledge query failed",
5448
+ inputSchema: {
5449
+ query: z.z.string().describe("Search query describing what you want to know")
5450
+ },
5451
+ hideSuccessfulCall: false,
5452
+ autoApproveByDefault: false,
5453
+ permissionAction: "Waiting for approval to search project knowledge",
5454
+ dynamicAction: "Searching project knowledge",
5455
+ fallbackAction: "Search project knowledge",
5456
+ reasonPhrases: []
5457
+ },
5458
+ update_progress: {
5459
+ title: "Update Progress",
5460
+ description: 'Optional override for the App\'s Progress tab. In most cases your TodoWrite calls are auto-mirrored, so you do NOT need to call this. Use it only when you want to set extra fields the CLI hook does not capture (currentStage, blockers) or to force a new list boundary with `listId: "new"`.',
5461
+ failureLabel: "Failed to update progress",
5462
+ inputSchema: {
5463
+ todos: z.z.array(
5464
+ z.z.object({
5465
+ content: z.z.string().describe("Concise description of the task"),
5466
+ status: z.z.enum(["pending", "in_progress", "completed"]).describe("Current status of the task"),
5467
+ activeForm: z.z.string().optional().describe(
5468
+ "Imperative-present form shown when status is in_progress"
5469
+ ),
5470
+ stage: z.z.string().optional().describe("Optional phase/stage label")
5471
+ })
5472
+ ).describe("The full checklist \u2014 always send every item, not a delta"),
5473
+ currentStage: z.z.string().optional().describe("Optional overall stage name for the checklist"),
5474
+ blockers: z.z.array(z.z.string()).optional().describe("Optional list of things blocking progress"),
5475
+ listId: z.z.string().optional().describe("Target list id. Use 'new' to force a fresh list"),
5476
+ label: z.z.string().optional().describe("Short human-readable name for this task list")
5477
+ },
5478
+ hideSuccessfulCall: false,
5479
+ autoApproveByDefault: true,
5480
+ permissionAction: "Waiting for approval to update progress",
5481
+ dynamicAction: "Updating progress",
5482
+ fallbackAction: "Update progress",
5483
+ reasonPhrases: ["progress update", "progress updates", "update_progress"]
5484
+ },
5485
+ update_session_summary: {
5486
+ title: "Update Session Summary",
5487
+ description: "Write a narrative session summary the App shows above the progress checklist. Call at milestones, not per task: after first understanding the goal, when scope shifts significantly, when key decisions are made, or when moving to a new phase. Full rewrite each call.",
5488
+ failureLabel: "Failed to update session summary",
5489
+ inputSchema: {
5490
+ goal: z.z.string().describe("What the user ultimately wants to accomplish"),
5491
+ currentFocus: z.z.string().optional().describe("Brief description of the active task or phase"),
5492
+ keyDecisions: z.z.array(z.z.string()).optional().describe("Important choices already made this session"),
5493
+ openQuestions: z.z.array(z.z.string()).optional().describe("Unresolved questions or pending decisions"),
5494
+ impactScope: z.z.array(z.z.string()).optional().describe("Modules/files/areas affected by this session's work"),
5495
+ requestId: z.z.string().optional().describe(
5496
+ "Optional request identifier that runtimes may record in sessionSummaryRefresh recent history for request-level confirmation"
5497
+ )
5498
+ },
5499
+ hideSuccessfulCall: false,
5500
+ autoApproveByDefault: true,
5501
+ permissionAction: "Waiting for approval to update session summary",
5502
+ dynamicAction: "Updating session summary",
5503
+ fallbackAction: "Update session summary",
5504
+ reasonPhrases: [
5505
+ "session summary",
5506
+ "update_session_summary",
5507
+ "summary update"
5508
+ ]
5509
+ }
5510
+ };
5511
+ new Set(HAPPY_MCP_TOOL_NAMES);
5512
+ HAPPY_MCP_TOOL_NAMES.filter(
5513
+ (toolName) => HAPPY_MCP_TOOL_SPECS[toolName].autoApproveByDefault
5514
+ );
5515
+ HAPPY_MCP_TOOL_NAMES.filter(
5516
+ (toolName) => HAPPY_MCP_TOOL_SPECS[toolName].hideSuccessfulCall
5517
+ );
5518
+
5519
+ const CodexRuntimeConfigSchema = z__namespace.object({
5520
+ model: z__namespace.string().nullish(),
5521
+ profile: z__namespace.string().nullish(),
5522
+ approvalPolicy: z__namespace.string().nullish(),
5523
+ sandboxMode: z__namespace.string().nullish(),
5524
+ serviceTier: z__namespace.string().nullish(),
5525
+ reasoningEffort: z__namespace.string().nullish(),
5526
+ reasoningSummary: z__namespace.string().nullish(),
5527
+ verbosity: z__namespace.string().nullish(),
5528
+ webSearch: z__namespace.string().nullish()
5529
+ });
5530
+ const CodexAccountSchema = z__namespace.object({
5531
+ type: z__namespace.enum(["apiKey", "chatgpt"]).nullable().optional(),
5532
+ email: z__namespace.string().nullish(),
5533
+ planType: z__namespace.string().nullish(),
5534
+ requiresOpenaiAuth: z__namespace.boolean().optional()
5535
+ });
5536
+ const CodexRateLimitsSchema = z__namespace.object({
5537
+ limitId: z__namespace.string().nullish(),
5538
+ limitName: z__namespace.string().nullish(),
5539
+ planType: z__namespace.string().nullish(),
5540
+ hasCredits: z__namespace.boolean().optional()
5541
+ });
5542
+ const CodexExperimentalFeatureSchema = z__namespace.object({
5543
+ name: z__namespace.string(),
5544
+ stage: z__namespace.string(),
5545
+ enabled: z__namespace.boolean(),
5546
+ defaultEnabled: z__namespace.boolean()
5547
+ });
5548
+ const CodexSkillSummarySchema = z__namespace.object({
5549
+ name: z__namespace.string(),
5550
+ description: z__namespace.string(),
5551
+ path: z__namespace.string(),
5552
+ enabled: z__namespace.boolean()
5553
+ });
5554
+ const CodexPromptSummarySchema = z__namespace.object({
5555
+ name: z__namespace.string(),
5556
+ path: z__namespace.string(),
5557
+ description: z__namespace.string().nullish()
5558
+ });
5559
+ const CodexAgentSummarySchema = z__namespace.object({
5560
+ name: z__namespace.string(),
5561
+ path: z__namespace.string()
5562
+ });
5563
+ const CodexMcpServerSummarySchema = z__namespace.object({
5564
+ name: z__namespace.string(),
5565
+ authStatus: z__namespace.string(),
5566
+ toolCount: z__namespace.number()
5567
+ });
5568
+ z__namespace.object({
5569
+ requestedBackend: CodexRequestedBackendSchema.optional(),
5570
+ resolvedBackend: CodexResolvedBackendSchema.optional(),
5571
+ configMode: CodexConfigModeSchema.optional(),
5572
+ fallbackReason: z__namespace.string().optional(),
5573
+ backendVersion: z__namespace.string().optional(),
5574
+ threadId: z__namespace.string().optional(),
5575
+ config: CodexRuntimeConfigSchema.optional(),
5576
+ account: CodexAccountSchema.optional(),
5577
+ rateLimits: CodexRateLimitsSchema.optional(),
5578
+ experimentalFeatures: z__namespace.array(CodexExperimentalFeatureSchema).optional(),
5579
+ skills: z__namespace.array(CodexSkillSummarySchema).optional(),
5580
+ prompts: z__namespace.array(CodexPromptSummarySchema).optional(),
5581
+ agents: z__namespace.array(CodexAgentSummarySchema).optional(),
5582
+ mcpServers: z__namespace.array(CodexMcpServerSummarySchema).optional()
5583
+ });
5584
+
5585
+ z.z.object({}).strict();
5586
+ z.z.object({
5587
+ /** Pre-formatted single-line summary (same text `/usage` prints in non-interactive mode). */
5588
+ formatted: z.z.string(),
5589
+ /** Total USD spent on this session so far. */
5590
+ totalUsd: z.z.number().nonnegative(),
5591
+ /** Optional breakdown by model. */
5592
+ byModel: z.z.record(z.z.string(), z.z.object({
5593
+ inputTokens: z.z.number().int().nonnegative(),
5594
+ outputTokens: z.z.number().int().nonnegative(),
5595
+ cacheCreationInputTokens: z.z.number().int().nonnegative().optional(),
5596
+ cacheReadInputTokens: z.z.number().int().nonnegative().optional(),
5597
+ costUsd: z.z.number().nonnegative()
5598
+ })).optional()
5599
+ }).strict();
5600
+ z.z.object({}).strict();
5601
+ z.z.object({
5602
+ /** Remote Claude Code binary version string, e.g. "2.1.119". */
5603
+ version: z.z.string(),
5604
+ /** Path to the binary if resolvable, informational only. */
5605
+ binaryPath: z.z.string().optional(),
5606
+ /** Happy-cli package version for context. */
5607
+ happyCliVersion: z.z.string().optional()
5608
+ }).strict();
5609
+ z.z.object({
5610
+ /** Agent color name or the literal "default" to reset. */
5611
+ color: z.z.string().min(1).max(64)
5612
+ }).strict();
5613
+ z.z.object({
5614
+ success: z.z.literal(true),
5615
+ color: z.z.string()
5616
+ }).strict();
5617
+ z.z.object({
5618
+ /** Path relative to cwd or absolute. CLI applies path blacklist + Read-tool permission gating. */
5619
+ path: z.z.string().min(1).max(4096),
5620
+ /** Optional max bytes to return; server-side hard cap enforces <= 1 MiB. */
5621
+ maxBytes: z.z.number().int().positive().max(1024 * 1024).optional()
5622
+ }).strict();
5623
+ z.z.object({
5624
+ /** Null when permission denied / missing / blocked by CLI path blacklist. */
5625
+ result: z.z.object({
5626
+ contents: z.z.string(),
5627
+ absPath: z.z.string(),
5628
+ truncated: z.z.boolean().optional()
5629
+ }).nullable(),
5630
+ /** Machine-readable reason when result is null. */
5631
+ deniedReason: z.z.enum(["not_found", "permission_denied", "blacklisted_path", "too_large", "error"]).optional()
5632
+ }).strict();
5633
+ z.z.object({
5634
+ /** Fully-qualified MCP tool name, e.g. `mcp__fs__read`. Must pass CLI whitelist. */
5635
+ tool: z.z.string().regex(/^mcp__[a-z0-9_-]+__[a-z0-9_.-]+$/i, "must be of form mcp__<server>__<tool>"),
5636
+ /** Tool arguments; schema-free, CLI passes through to MCP server. */
5637
+ arguments: z.z.record(z.z.string(), z.z.unknown()).optional(),
5638
+ /**
5639
+ * Client-nonce that App must have displayed to the user in a 2-step
5640
+ * confirm dialog. CLI uses this only for audit logging — the actual
5641
+ * confirmation happens on App side and is logged for security review.
5642
+ */
5643
+ clientConfirmToken: z.z.string().min(8).max(128)
5644
+ }).strict();
5645
+ z.z.object({
5646
+ success: z.z.boolean(),
5647
+ /** Tool response payload, shape defined by each MCP tool. */
5648
+ result: z.z.unknown().optional(),
5649
+ /** Error code for UI to localize; see CLI handler for enum values. */
5650
+ errorCode: z.z.enum([
5651
+ "not_whitelisted",
5652
+ "server_unavailable",
5653
+ "tool_not_found",
5654
+ "invalid_arguments",
5655
+ "permission_denied",
5656
+ /**
5657
+ * SDK 0.2.119 defines the `mcp_call` control protocol type but does
5658
+ * not expose a public runtime method on the `Query` interface. Until
5659
+ * upstream lands a `callMcpTool()` / equivalent, the CLI handler
5660
+ * returns this code so the App can surface an honest "waiting on
5661
+ * SDK" state instead of masking the gap as a server error.
5662
+ */
5663
+ "sdk_not_implemented",
5664
+ "unknown"
5665
+ ]).optional(),
5666
+ errorMessage: z.z.string().optional()
5667
+ }).strict();
5668
+
5669
+ function buildSummaryRefreshPrompt(requestId) {
5670
+ return [
5671
+ "Please call mcp__happy__update_session_summary to record the current session summary with: goal, currentFocus, keyDecisions (if any), openQuestions (if any), impactScope (if any). Keep it accurate and concise.",
5672
+ "",
5673
+ `Request ID: ${requestId}`,
5674
+ "Important: include this requestId exactly in the tool input as `requestId` when you call mcp__happy__update_session_summary."
5675
+ ].join("\n");
5676
+ }
5677
+ function toMetadataRecord(metadata) {
5678
+ if (metadata == null || typeof metadata !== "object" || Array.isArray(metadata)) {
5679
+ return {};
5680
+ }
5681
+ return metadata;
5682
+ }
5683
+ function appendRecentEntry(existing, entry) {
5684
+ return [
5685
+ ...(existing ?? []).filter((item) => item.requestId !== entry.requestId),
5686
+ entry
5687
+ ].slice(-4);
5688
+ }
5689
+ function extractSessionSummaryState(metadata) {
5690
+ const parsed = sessionSummaryStateSchema.safeParse(
5691
+ toMetadataRecord(metadata).sessionSummary
5692
+ );
5693
+ return parsed.success ? parsed.data : null;
5694
+ }
5695
+ function extractSessionSummaryRefreshState(metadata) {
5696
+ const parsed = sessionSummaryRefreshStateSchema.safeParse(
5697
+ toMetadataRecord(metadata).sessionSummaryRefresh
5698
+ );
5699
+ return parsed.success ? parsed.data : null;
5700
+ }
5701
+ function buildActiveSummaryRefreshState(args) {
5702
+ const existing = extractSessionSummaryRefreshState(args.metadata);
5703
+ const previousActive = existing?.active;
5704
+ const recent = previousActive && previousActive.requestId !== args.requestId ? appendRecentEntry(existing?.recent, {
5705
+ requestId: previousActive.requestId,
5706
+ status: "superseded",
5707
+ resolvedAt: args.requestedAt,
5708
+ supersededByRequestId: args.requestId
5709
+ }) : [...existing?.recent ?? []];
5710
+ return {
5711
+ protocolVersion: 1,
5712
+ active: {
5713
+ requestId: args.requestId,
5714
+ requestedAt: args.requestedAt,
5715
+ requester: "happy-agent",
5716
+ command: "summary-refresh",
5717
+ requireSummary: args.requireSummary
5718
+ },
5719
+ recent
5720
+ };
5721
+ }
5722
+ function getRecentSummaryRefreshEntry(metadata, requestId) {
5723
+ const refresh = extractSessionSummaryRefreshState(metadata);
5724
+ const recent = refresh?.recent;
5725
+ if (!recent) {
5726
+ return null;
5727
+ }
5728
+ for (let index = recent.length - 1; index >= 0; index -= 1) {
5729
+ if (recent[index]?.requestId === requestId) {
5730
+ return recent[index] ?? null;
5731
+ }
5732
+ }
5733
+ return null;
5734
+ }
5735
+ function waitForSummaryRefreshRecentApplied(client, opts) {
5736
+ const getEntry = (metadata) => getRecentSummaryRefreshEntry(metadata, opts.requestId);
5737
+ const immediate = getEntry(client.getMetadata());
5738
+ if (immediate?.status === "applied") {
5739
+ return Promise.resolve(immediate);
5740
+ }
5741
+ if (immediate?.status === "superseded") {
5742
+ return Promise.reject(
5743
+ new Error(
5744
+ `Summary refresh request ${opts.requestId} was superseded${immediate.supersededByRequestId ? ` by ${immediate.supersededByRequestId}` : ""}`
5745
+ )
5746
+ );
5747
+ }
5748
+ return new Promise((resolve, reject) => {
5749
+ const onStateChange = (data) => {
5750
+ const entry = getEntry(data.metadata ?? client.getMetadata());
5751
+ if (!entry) {
5752
+ return;
5753
+ }
5754
+ if (entry.status === "applied") {
5755
+ cleanup();
5756
+ resolve(entry);
5757
+ return;
5758
+ }
5759
+ cleanup();
5760
+ reject(
5761
+ new Error(
5762
+ `Summary refresh request ${opts.requestId} was superseded${entry.supersededByRequestId ? ` by ${entry.supersededByRequestId}` : ""}`
5763
+ )
5764
+ );
5765
+ };
5766
+ const onDisconnect = () => {
5767
+ cleanup();
5768
+ reject(
5769
+ new Error(
5770
+ "Socket disconnected while waiting for summary refresh acknowledgement"
5771
+ )
5772
+ );
5773
+ };
5774
+ const cleanup = () => {
5775
+ clearTimeout(timeout);
5776
+ client.removeListener("state-change", onStateChange);
5777
+ client.removeListener("disconnected", onDisconnect);
5778
+ };
5779
+ const timeout = setTimeout(() => {
5780
+ cleanup();
5781
+ reject(new Error("Timeout waiting for summary refresh acknowledgement"));
5782
+ }, opts.timeoutMs);
5783
+ client.on("state-change", onStateChange);
5784
+ client.on("disconnected", onDisconnect);
5785
+ });
5786
+ }
5787
+
3433
5788
  function formatTime(ts) {
3434
5789
  if (!ts) return "-";
3435
5790
  const date = new Date(ts);
5791
+ if (Number.isNaN(date.getTime())) return "-";
3436
5792
  const now = /* @__PURE__ */ new Date();
3437
5793
  const diffMs = now.getTime() - date.getTime();
3438
5794
  const diffMin = Math.floor(diffMs / 6e4);
@@ -3469,7 +5825,7 @@ function normalizeListValue(value) {
3469
5825
  function toNonEmptyString(value) {
3470
5826
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
3471
5827
  }
3472
- function extractSessionSummary(meta) {
5828
+ function extractSessionName(meta) {
3473
5829
  const direct = toNonEmptyString(meta.summary);
3474
5830
  if (direct) return direct;
3475
5831
  if (meta.summary != null && typeof meta.summary === "object") {
@@ -3477,13 +5833,21 @@ function extractSessionSummary(meta) {
3477
5833
  }
3478
5834
  return void 0;
3479
5835
  }
5836
+ function formatMarkdownListSection(title, items) {
5837
+ if (items.length === 0) return [];
5838
+ return [
5839
+ "",
5840
+ `### ${title}`,
5841
+ ...items.map((item) => `- ${normalizeListValue(item)}`)
5842
+ ];
5843
+ }
3480
5844
  function formatSessionTable(sessions) {
3481
5845
  if (sessions.length === 0) {
3482
5846
  return "## Sessions\n\n- Total: 0\n- Items: none";
3483
5847
  }
3484
5848
  const sections = sessions.map((s, index) => {
3485
5849
  const meta = s.metadata ?? {};
3486
- const name = normalizeListValue(extractSessionSummary(meta) ?? toNonEmptyString(meta.tag) ?? "-");
5850
+ const name = normalizeListValue(extractSessionName(meta) ?? toNonEmptyString(meta.tag) ?? "-");
3487
5851
  const path = normalizeListValue(toNonEmptyString(meta.path) ?? "-");
3488
5852
  const status = s.active ? "active" : "inactive";
3489
5853
  const lastActive = normalizeListValue(formatLastActive(s.activeAt));
@@ -3506,7 +5870,7 @@ function formatSessionStatus(session) {
3506
5870
  const meta = session.metadata ?? {};
3507
5871
  const state = session.agentState ?? null;
3508
5872
  const tag = toNonEmptyString(meta.tag);
3509
- const summary = extractSessionSummary(meta);
5873
+ const summary = extractSessionName(meta);
3510
5874
  const path = toNonEmptyString(meta.path);
3511
5875
  const host = toNonEmptyString(meta.host);
3512
5876
  const lifecycleState = toNonEmptyString(meta.lifecycleState);
@@ -3535,6 +5899,30 @@ function formatSessionStatus(session) {
3535
5899
  }
3536
5900
  return lines.join("\n");
3537
5901
  }
5902
+ function formatSessionNarrativeSummary(session) {
5903
+ const summary = extractSessionSummaryState(session.metadata);
5904
+ const lines = [
5905
+ "## Session Summary",
5906
+ "",
5907
+ `- Session ID: ${toMarkdownInline(session.id)}`
5908
+ ];
5909
+ if (!summary) {
5910
+ lines.push("- Status: missing");
5911
+ lines.push(
5912
+ `- Hint: Run ${toMarkdownInline(`happy-agent summary refresh ${session.id}`)} to request one.`
5913
+ );
5914
+ return lines.join("\n");
5915
+ }
5916
+ lines.push(`- Updated: ${formatLastActive(summary.updatedAt)}`);
5917
+ lines.push(`- Goal: ${normalizeListValue(summary.goal)}`);
5918
+ if (summary.currentFocus) {
5919
+ lines.push(`- Focus: ${normalizeListValue(summary.currentFocus)}`);
5920
+ }
5921
+ lines.push(...formatMarkdownListSection("Key Decisions", summary.keyDecisions ?? []));
5922
+ lines.push(...formatMarkdownListSection("Open Questions", summary.openQuestions ?? []));
5923
+ lines.push(...formatMarkdownListSection("Impact Scope", summary.impactScope ?? []));
5924
+ return lines.join("\n");
5925
+ }
3538
5926
  function formatMessageHistory(messages) {
3539
5927
  if (messages.length === 0) {
3540
5928
  return "## Message History\n\n- Count: 0\n- Items: none";
@@ -3601,9 +5989,48 @@ function createClient(session, creds, config) {
3601
5989
  encryptionVariant: session.encryption.variant,
3602
5990
  token: creds.token,
3603
5991
  serverUrl: config.serverUrl,
5992
+ initialMetadata: session.metadata ?? null,
5993
+ initialMetadataVersion: session.metadataVersion,
3604
5994
  initialAgentState: session.agentState ?? null
3605
5995
  });
3606
5996
  }
5997
+ function sleep(ms) {
5998
+ return new Promise((resolve) => setTimeout(resolve, ms));
5999
+ }
6000
+ async function hydrateSessionLiveState(session, creds, config) {
6001
+ const client = createClient(session, creds, config);
6002
+ let liveData = false;
6003
+ try {
6004
+ await new Promise((resolve) => {
6005
+ let resolved = false;
6006
+ const done = () => {
6007
+ if (resolved) return;
6008
+ resolved = true;
6009
+ clearTimeout(timeout);
6010
+ client.removeAllListeners("state-change");
6011
+ client.removeAllListeners("connect_error");
6012
+ resolve();
6013
+ };
6014
+ const timeout = setTimeout(done, 3e3);
6015
+ client.once(
6016
+ "state-change",
6017
+ (data) => {
6018
+ session.metadata = data.metadata ?? session.metadata;
6019
+ session.metadataVersion = client.getMetadataVersion();
6020
+ session.agentState = data.agentState ?? session.agentState;
6021
+ liveData = true;
6022
+ done();
6023
+ }
6024
+ );
6025
+ client.once("connect_error", () => {
6026
+ done();
6027
+ });
6028
+ });
6029
+ } finally {
6030
+ client.close();
6031
+ }
6032
+ return liveData;
6033
+ }
3607
6034
  const program = new commander.Command();
3608
6035
  program.name("happy-agent").description("CLI client for controlling Happy Coder agents remotely").version(version);
3609
6036
  program.command("auth").description("Manage authentication").addCommand(
@@ -3636,36 +6063,7 @@ program.command("status").description("Get live session state").argument("<sessi
3636
6063
  const config = loadConfig();
3637
6064
  const creds = requireCredentials(config);
3638
6065
  const session = await resolveSession(config, creds, sessionId);
3639
- const client = createClient(session, creds, config);
3640
- let liveData = false;
3641
- try {
3642
- await new Promise((resolve) => {
3643
- let resolved = false;
3644
- const done = () => {
3645
- if (resolved) return;
3646
- resolved = true;
3647
- clearTimeout(timeout);
3648
- client.removeAllListeners("state-change");
3649
- client.removeAllListeners("connect_error");
3650
- resolve();
3651
- };
3652
- const timeout = setTimeout(done, 3e3);
3653
- client.once(
3654
- "state-change",
3655
- (data) => {
3656
- session.metadata = data.metadata ?? session.metadata;
3657
- session.agentState = data.agentState ?? session.agentState;
3658
- liveData = true;
3659
- done();
3660
- }
3661
- );
3662
- client.once("connect_error", () => {
3663
- done();
3664
- });
3665
- });
3666
- } finally {
3667
- client.close();
3668
- }
6066
+ const liveData = await hydrateSessionLiveState(session, creds, config);
3669
6067
  if (opts.json) {
3670
6068
  console.log(formatJson(session));
3671
6069
  } else {
@@ -3675,6 +6073,131 @@ program.command("status").description("Get live session state").argument("<sessi
3675
6073
  console.log(formatSessionStatus(session));
3676
6074
  }
3677
6075
  });
6076
+ program.command("summary").description("Inspect or refresh session summaries").addCommand(
6077
+ new commander.Command("show").description("Show the narrative session summary").argument("<session-id>", "Session ID or prefix").option("--json", "Output as JSON").action(async (sessionId, opts) => {
6078
+ const config = loadConfig();
6079
+ const creds = requireCredentials(config);
6080
+ const session = await resolveSession(config, creds, sessionId);
6081
+ const liveData = await hydrateSessionLiveState(session, creds, config);
6082
+ const summary = extractSessionSummaryState(session.metadata);
6083
+ if (opts.json) {
6084
+ console.log(
6085
+ formatJson({
6086
+ sessionId: session.id,
6087
+ live: liveData,
6088
+ summary
6089
+ })
6090
+ );
6091
+ } else {
6092
+ if (!liveData) {
6093
+ console.log("> Note: showing cached summary (could not get live state).");
6094
+ }
6095
+ console.log(formatSessionNarrativeSummary(session));
6096
+ }
6097
+ })
6098
+ ).addCommand(
6099
+ new commander.Command("refresh").description("Ask the agent to rewrite the session summary").argument("<session-id>", "Session ID or prefix").option("--wait", "Wait for agent to become idle").option(
6100
+ "--require-summary",
6101
+ "Wait until this refresh request is acknowledged in sessionSummaryRefresh.recent"
6102
+ ).option(
6103
+ "--timeout <seconds>",
6104
+ "Timeout in seconds when using --wait or --require-summary",
6105
+ (v) => {
6106
+ const n = parseInt(v, 10);
6107
+ if (isNaN(n) || n <= 0)
6108
+ throw new Error("--timeout must be a positive integer");
6109
+ return n;
6110
+ },
6111
+ 300
6112
+ ).option("--json", "Output as JSON").action(
6113
+ async (sessionId, opts) => {
6114
+ const config = loadConfig();
6115
+ const creds = requireCredentials(config);
6116
+ const session = await resolveSession(config, creds, sessionId);
6117
+ const timeoutMs = opts.timeout * 1e3;
6118
+ const requestId = `summary-refresh_${node_crypto.randomUUID()}`;
6119
+ const requestedAt = Date.now();
6120
+ let summaryConfirmed = false;
6121
+ const client = createClient(session, creds, config);
6122
+ try {
6123
+ await client.waitForConnect();
6124
+ if (opts.requireSummary) {
6125
+ await client.updateMetadataWith((current) => {
6126
+ const base = current != null && typeof current === "object" && !Array.isArray(current) ? current : {};
6127
+ return {
6128
+ ...base,
6129
+ sessionSummaryRefresh: buildActiveSummaryRefreshState({
6130
+ metadata: current,
6131
+ requestId,
6132
+ requestedAt,
6133
+ requireSummary: true
6134
+ })
6135
+ };
6136
+ });
6137
+ }
6138
+ const summaryAckPromise = opts.requireSummary ? waitForSummaryRefreshRecentApplied(client, {
6139
+ requestId,
6140
+ timeoutMs
6141
+ }) : null;
6142
+ client.sendMessage(buildSummaryRefreshPrompt(requestId), {
6143
+ sentFrom: "happy-agent-summary-refresh",
6144
+ requestId
6145
+ });
6146
+ if (summaryAckPromise) {
6147
+ await summaryAckPromise;
6148
+ summaryConfirmed = true;
6149
+ }
6150
+ if (opts.wait) {
6151
+ await sleep(500);
6152
+ await client.waitForIdle(timeoutMs);
6153
+ } else if (!opts.requireSummary) {
6154
+ await sleep(500);
6155
+ }
6156
+ const latestMetadata = client.getMetadata();
6157
+ if (latestMetadata !== null) {
6158
+ session.metadata = latestMetadata;
6159
+ }
6160
+ session.metadataVersion = client.getMetadataVersion();
6161
+ } finally {
6162
+ client.close();
6163
+ }
6164
+ const summary = extractSessionSummaryState(session.metadata);
6165
+ if (opts.json) {
6166
+ console.log(
6167
+ formatJson({
6168
+ sessionId: session.id,
6169
+ requestId,
6170
+ requested: true,
6171
+ requiredSummary: opts.requireSummary === true,
6172
+ summaryConfirmed,
6173
+ waited: opts.wait === true,
6174
+ summary: opts.wait === true || opts.requireSummary === true ? summary : void 0
6175
+ })
6176
+ );
6177
+ } else if (opts.wait || opts.requireSummary) {
6178
+ if (!summary) {
6179
+ console.log(
6180
+ opts.requireSummary ? "> Note: summary update was required, but no valid narrative summary is available." : "> Note: summary was requested, but the session has not recorded a narrative summary yet."
6181
+ );
6182
+ }
6183
+ console.log(formatSessionNarrativeSummary(session));
6184
+ } else {
6185
+ console.log(
6186
+ [
6187
+ "## Summary Refresh Requested",
6188
+ "",
6189
+ `- Session ID: \`${session.id}\``,
6190
+ `- Request ID: \`${requestId}\``,
6191
+ `- Required Summary Update: ${opts.requireSummary ? "yes" : "no"}`,
6192
+ `- Summary Confirmed: ${summaryConfirmed ? "yes" : "no"}`,
6193
+ `- Waited For Idle: ${opts.wait ? "yes" : "no"}`,
6194
+ `- Hint: Run \`happy-agent summary show ${session.id}\` to inspect the updated summary.`
6195
+ ].join("\n")
6196
+ );
6197
+ }
6198
+ }
6199
+ )
6200
+ );
3678
6201
  program.command("create").description("Create a new session").requiredOption("--tag <tag>", "Session tag").option("--path <path>", "Working directory path").option("--json", "Output as JSON").action(async (opts) => {
3679
6202
  const config = loadConfig();
3680
6203
  const creds = requireCredentials(config);