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