@kmmao/happy-agent 0.5.3 → 0.5.5

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