@agentknight/sdk 0.9.57 → 0.9.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/dist/chunks/{acp-adapter-WYDK3PLS.js → acp-adapter-OGD5QSNI.js} +4 -4
  2. package/dist/chunks/{chunk-WPVH7HKC.js → chunk-2MERNOK6.js} +1 -1
  3. package/dist/chunks/{chunk-7ZYBES47.js → chunk-3OIHMMDF.js} +1 -1
  4. package/dist/chunks/{chunk-3LEPYV7Y.js → chunk-5DVJ7Y5W.js} +2 -2
  5. package/dist/chunks/{chunk-USI66MEF.js → chunk-AREU4R62.js} +3 -2
  6. package/dist/chunks/{chunk-ZLKFFKAX.js → chunk-DP5KVGWF.js} +4 -3
  7. package/dist/chunks/{chunk-DAKDVZ7X.js → chunk-FDUJP3WA.js} +2 -2
  8. package/dist/chunks/{chunk-KBI5IWPR.js → chunk-LO4ZRE77.js} +747 -513
  9. package/dist/chunks/{chunk-OOCAIULD.js → chunk-LWJNDBIM.js} +431 -21
  10. package/dist/chunks/{chunk-IPJWNGNK.js → chunk-NDEJOXSX.js} +1 -1
  11. package/dist/chunks/{chunk-EDZPP6SJ.js → chunk-X3ZG6WMN.js} +2 -3
  12. package/dist/chunks/{chunk-LT5ULDVT.js → chunk-ZDKBJFA2.js} +1 -1
  13. package/dist/chunks/{claude-adapter-GCH36EZ6.js → claude-adapter-DGZBZSWJ.js} +209 -59
  14. package/dist/chunks/{codex-adapter-CXD4SVCE.js → codex-adapter-2W7RRER3.js} +4 -4
  15. package/dist/chunks/{copilot-adapter-SYFGOAGE.js → copilot-adapter-ZEHU6CFQ.js} +109 -14
  16. package/dist/chunks/{managed-agent-adapter-ODCNYYO6.js → managed-agent-adapter-CGJPJZ2Z.js} +20 -6
  17. package/dist/chunks/{pi-adapter-XLY46UDL.js → pi-adapter-WOVSWBGG.js} +4 -4
  18. package/dist/configuration.js +4 -4
  19. package/dist/index.d.ts +126 -1
  20. package/dist/index.js +1447 -562
  21. package/dist/runtime.js +2 -2
  22. package/dist/session-analytics-worker.js +162 -51
  23. package/package.json +1 -1
@@ -6,16 +6,18 @@ import {
6
6
  ConversationNormalizer,
7
7
  ConversationToolLifecycles,
8
8
  assistantMessageId
9
- } from "./chunk-LT5ULDVT.js";
9
+ } from "./chunk-ZDKBJFA2.js";
10
10
  import {
11
11
  isContentfulAssistant
12
- } from "./chunk-IPJWNGNK.js";
12
+ } from "./chunk-NDEJOXSX.js";
13
13
  import {
14
14
  SessionOperationError
15
- } from "./chunk-7ZYBES47.js";
15
+ } from "./chunk-3OIHMMDF.js";
16
16
  import {
17
17
  IdSchema,
18
18
  SESSION_DIRECTORY_LIST_OPERATION,
19
+ SESSION_DIRECTORY_MAX_ENTRIES,
20
+ SESSION_DIRECTORY_MAX_RESPONSE_BYTES,
19
21
  SESSION_FILE_DOWNLOAD_OPERATION,
20
22
  SESSION_FILE_READ_OPERATION,
21
23
  SESSION_IMAGE_API_PATH,
@@ -34,14 +36,19 @@ import {
34
36
  TIMELINE_SYNC_OPERATION,
35
37
  TimelineResyncReasonSchema,
36
38
  WORKBENCH_OPERATIONS,
39
+ WORKBENCH_REASONING_PAGE_SIZE,
40
+ WORKBENCH_REASONING_TEXT_LIMIT,
37
41
  WorkbenchAskResultSchema,
38
42
  WorkbenchCommandResultSchema,
39
43
  WorkbenchCommandSchema,
40
44
  WorkbenchCompactResultSchema,
41
45
  WorkbenchInsightsSchema,
42
46
  WorkbenchQueueMutationResultSchema,
43
- WorkbenchQueueSnapshotSchema
44
- } from "./chunk-KBI5IWPR.js";
47
+ WorkbenchQueueSnapshotSchema,
48
+ WorkbenchReasoningPageSchema,
49
+ WorkbenchReasoningRequestSchema,
50
+ isSafeSessionDirectoryPath
51
+ } from "./chunk-LO4ZRE77.js";
45
52
 
46
53
  // src/session-image-uploader.ts
47
54
  import { createHash } from "node:crypto";
@@ -1256,6 +1263,222 @@ ${state.deltaContent}`).slice(0, 4096),
1256
1263
  }
1257
1264
  };
1258
1265
 
1266
+ // src/session-directory.ts
1267
+ import { createHash as createHash3 } from "node:crypto";
1268
+ import { lstat, opendir, realpath, stat } from "node:fs/promises";
1269
+ import { isAbsolute, join, relative, sep } from "node:path";
1270
+ var SESSION_DIRECTORY_CONCURRENCY = 4;
1271
+ var SESSION_DIRECTORY_TIMEOUT_MS = 5e3;
1272
+ var SessionDirectoryError = class extends Error {
1273
+ constructor(code, message, options) {
1274
+ super(message, options);
1275
+ this.code = code;
1276
+ }
1277
+ code;
1278
+ };
1279
+ function fail(code, message) {
1280
+ throw new SessionDirectoryError(code, message);
1281
+ }
1282
+ function contained(root, candidate) {
1283
+ const path = relative(root, candidate);
1284
+ return path === "" || !isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`);
1285
+ }
1286
+ function sessionRootIdentity(root, info) {
1287
+ return `${root}\0${info.dev}\0${info.ino}`;
1288
+ }
1289
+ var SessionDirectoryLister = class {
1290
+ constructor(metadata) {
1291
+ this.metadata = metadata;
1292
+ }
1293
+ metadata;
1294
+ #active = 0;
1295
+ #storageCache = /* @__PURE__ */ new Map();
1296
+ async storage(sessionId) {
1297
+ if (this.#active >= SESSION_DIRECTORY_CONCURRENCY) fail("DIRECTORY_BUSY", "Too many directory requests");
1298
+ this.#active++;
1299
+ try {
1300
+ const metadata = await this.metadata(sessionId);
1301
+ const path = metadata?.sessionStateDirectory;
1302
+ if (path === void 0) return void 0;
1303
+ if (!isAbsolute(path)) fail("SESSION_ROOT_UNAVAILABLE", "The session state directory is unavailable");
1304
+ const info = await lstat(path, { bigint: true });
1305
+ if (!info.isDirectory() || info.isSymbolicLink()) fail("DIRECTORY_BLOCKED", "Links cannot be measured");
1306
+ const root = await realpath(path), identity = sessionRootIdentity(root, info);
1307
+ const cached = this.#storageCache.get(sessionId);
1308
+ if (cached?.identity === identity && cached.expires > Date.now()) return cached.value;
1309
+ const pending = [root], deadline = Date.now() + SESSION_DIRECTORY_TIMEOUT_MS;
1310
+ let bytes = 0, files = 0, visited = 0, partial = false;
1311
+ while (pending.length > 0 && visited < 1e4 && Date.now() < deadline) {
1312
+ const target = pending.pop();
1313
+ if (target === void 0) break;
1314
+ if ((await lstat(target)).isSymbolicLink() || !contained(root, await realpath(target))) {
1315
+ fail("DIRECTORY_BLOCKED", "The storage directory changed");
1316
+ }
1317
+ const directory = await opendir(target, { bufferSize: 32 });
1318
+ try {
1319
+ while (visited < 1e4 && Date.now() < deadline) {
1320
+ const entry = await directory.read();
1321
+ if (entry === null) break;
1322
+ visited++;
1323
+ const child = join(target, entry.name);
1324
+ const childInfo = await lstat(child);
1325
+ if (childInfo.isSymbolicLink()) {
1326
+ partial = true;
1327
+ continue;
1328
+ }
1329
+ if (childInfo.isDirectory()) pending.push(child);
1330
+ else if (childInfo.isFile()) {
1331
+ bytes += childInfo.size;
1332
+ files++;
1333
+ } else partial = true;
1334
+ if (!Number.isSafeInteger(bytes)) fail("DIRECTORY_LIMIT_EXCEEDED", "Storage size exceeds the supported range");
1335
+ }
1336
+ } finally {
1337
+ await directory.close();
1338
+ }
1339
+ }
1340
+ partial ||= pending.length > 0 || visited >= 1e4 || Date.now() >= deadline;
1341
+ const latest = await this.metadata(sessionId);
1342
+ const latestInfo = await lstat(path, { bigint: true });
1343
+ if (latest?.sessionStateDirectory !== path || latestInfo.isSymbolicLink() || sessionRootIdentity(await realpath(path), latestInfo) !== identity) {
1344
+ fail("SESSION_ROOT_CHANGED", "The session directory changed");
1345
+ }
1346
+ const value = { bytes, files, partial, sampledAt: (/* @__PURE__ */ new Date()).toISOString() };
1347
+ this.#storageCache.delete(sessionId);
1348
+ if (this.#storageCache.size >= 32) {
1349
+ const oldest = this.#storageCache.keys().next().value;
1350
+ if (oldest !== void 0) this.#storageCache.delete(oldest);
1351
+ }
1352
+ this.#storageCache.set(sessionId, { identity, value, expires: Date.now() + 3e4 });
1353
+ return value;
1354
+ } catch (error) {
1355
+ if (error instanceof SessionDirectoryError) throw error;
1356
+ throw new SessionDirectoryError("DIRECTORY_UNAVAILABLE", "Session storage measurement failed", { cause: error });
1357
+ } finally {
1358
+ this.#active--;
1359
+ }
1360
+ }
1361
+ async list(sessionId, path, space) {
1362
+ if (!isSafeSessionDirectoryPath(path)) {
1363
+ fail("INVALID_DIRECTORY_PATH", "The directory path is not allowed");
1364
+ }
1365
+ if (this.#active >= SESSION_DIRECTORY_CONCURRENCY) {
1366
+ fail("DIRECTORY_BUSY", "Too many directory requests");
1367
+ }
1368
+ this.#active++;
1369
+ const deadline = Date.now() + SESSION_DIRECTORY_TIMEOUT_MS;
1370
+ const checkDeadline = () => {
1371
+ if (Date.now() >= deadline) fail("DIRECTORY_TIMEOUT", "The directory request timed out");
1372
+ };
1373
+ const work = this.#list(sessionId, path, checkDeadline, space).finally(() => {
1374
+ this.#active--;
1375
+ });
1376
+ let timer;
1377
+ try {
1378
+ return await Promise.race([
1379
+ work,
1380
+ new Promise((_, reject) => {
1381
+ timer = setTimeout(() => reject(new SessionDirectoryError(
1382
+ "DIRECTORY_TIMEOUT",
1383
+ "The directory request timed out"
1384
+ )), SESSION_DIRECTORY_TIMEOUT_MS);
1385
+ })
1386
+ ]);
1387
+ } catch (error) {
1388
+ if (error instanceof SessionDirectoryError) throw error;
1389
+ throw new SessionDirectoryError("DIRECTORY_UNAVAILABLE", "The directory is unavailable", { cause: error });
1390
+ } finally {
1391
+ clearTimeout(timer);
1392
+ }
1393
+ }
1394
+ async #list(sessionId, path, checkDeadline, space) {
1395
+ const metadata = await this.metadata(sessionId);
1396
+ checkDeadline();
1397
+ if (metadata === void 0) fail("SESSION_NOT_FOUND", "The session is unavailable");
1398
+ const workingDirectory = space === "session" ? metadata.sessionStateDirectory : metadata.workingDirectory;
1399
+ if (!workingDirectory || !isAbsolute(workingDirectory)) {
1400
+ fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
1401
+ }
1402
+ let root;
1403
+ let rootIdentity2;
1404
+ try {
1405
+ if (space === "session" && (await lstat(workingDirectory)).isSymbolicLink()) {
1406
+ fail("SESSION_ROOT_UNAVAILABLE", "The session state directory is unavailable");
1407
+ }
1408
+ root = await realpath(workingDirectory);
1409
+ const info = await stat(root, { bigint: true });
1410
+ if (!info.isDirectory()) fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
1411
+ rootIdentity2 = sessionRootIdentity(root, info);
1412
+ } catch (error) {
1413
+ throw new SessionDirectoryError(
1414
+ "SESSION_ROOT_UNAVAILABLE",
1415
+ "The session working directory is unavailable",
1416
+ { cause: error }
1417
+ );
1418
+ }
1419
+ checkDeadline();
1420
+ let target = root;
1421
+ for (const segment of path === "" ? [] : path.split("/")) {
1422
+ target = join(target, segment);
1423
+ const info = await lstat(target);
1424
+ checkDeadline();
1425
+ if (info.isSymbolicLink()) fail("DIRECTORY_BLOCKED", "Links cannot be opened");
1426
+ if (!info.isDirectory()) fail("NOT_A_DIRECTORY", "The selected entry is not a directory");
1427
+ if (!contained(root, await realpath(target))) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
1428
+ checkDeadline();
1429
+ }
1430
+ const canonicalTarget = await realpath(target);
1431
+ if (!contained(root, canonicalTarget)) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
1432
+ checkDeadline();
1433
+ const directory = await opendir(target, { bufferSize: 32 });
1434
+ const entries = [];
1435
+ let bytes = 8192 + (space === "session" ? Buffer.byteLength(JSON.stringify(workingDirectory), "utf8") : 0);
1436
+ try {
1437
+ checkDeadline();
1438
+ for (; ; ) {
1439
+ const entry = await directory.read();
1440
+ checkDeadline();
1441
+ if (entry === null) break;
1442
+ if (entries.length >= SESSION_DIRECTORY_MAX_ENTRIES) {
1443
+ fail("DIRECTORY_LIMIT_EXCEEDED", "The directory has too many entries");
1444
+ }
1445
+ let kind = "blocked";
1446
+ if (isSafeSessionDirectoryPath(entry.name) && !entry.name.includes("/")) {
1447
+ const child = join(target, entry.name);
1448
+ const info = await lstat(child);
1449
+ checkDeadline();
1450
+ if (!info.isSymbolicLink() && contained(root, await realpath(child))) {
1451
+ kind = info.isDirectory() ? "directory" : info.isFile() ? "file" : "blocked";
1452
+ }
1453
+ }
1454
+ const result = { name: entry.name, kind };
1455
+ bytes += Buffer.byteLength(JSON.stringify(result), "utf8") + 1;
1456
+ if (bytes > SESSION_DIRECTORY_MAX_RESPONSE_BYTES) {
1457
+ fail("DIRECTORY_LIMIT_EXCEEDED", "The directory listing is too large");
1458
+ }
1459
+ entries.push(result);
1460
+ }
1461
+ const latestMetadata = await this.metadata(sessionId);
1462
+ const latestRoot = await realpath(workingDirectory);
1463
+ const latestInfo = await stat(latestRoot, { bigint: true });
1464
+ if ((space === "session" ? latestMetadata?.sessionStateDirectory : latestMetadata?.workingDirectory) !== workingDirectory || sessionRootIdentity(latestRoot, latestInfo) !== rootIdentity2 || await realpath(target) !== canonicalTarget) {
1465
+ fail("SESSION_ROOT_CHANGED", "The session directory changed");
1466
+ }
1467
+ checkDeadline();
1468
+ } finally {
1469
+ await directory.close();
1470
+ }
1471
+ const order = { directory: 0, file: 1, blocked: 2 };
1472
+ entries.sort((a, b) => order[a.kind] - order[b.kind] || a.name.localeCompare(b.name));
1473
+ return {
1474
+ rootRevision: createHash3("sha256").update(rootIdentity2).digest("base64url"),
1475
+ entries,
1476
+ // SDK links can use a configured home reached through a parent junction.
1477
+ ...space === "session" ? { rootPath: workingDirectory } : {}
1478
+ };
1479
+ }
1480
+ };
1481
+
1259
1482
  // src/git-remote-url.ts
1260
1483
  function sanitizeGitRemoteUrl(value) {
1261
1484
  const remote = value.trim();
@@ -1285,9 +1508,9 @@ function sanitizeGitRemoteUrl(value) {
1285
1508
 
1286
1509
  // src/git-project-identity.ts
1287
1510
  import { execFile } from "node:child_process";
1288
- import { createHash as createHash3 } from "node:crypto";
1289
- import { realpath } from "node:fs/promises";
1290
- import { isAbsolute, resolve } from "node:path";
1511
+ import { createHash as createHash4 } from "node:crypto";
1512
+ import { realpath as realpath2 } from "node:fs/promises";
1513
+ import { isAbsolute as isAbsolute2, resolve } from "node:path";
1291
1514
  import { promisify } from "node:util";
1292
1515
  var execFileAsync = promisify(execFile);
1293
1516
  var NotGitDirectoryError = class extends Error {
@@ -1324,13 +1547,13 @@ async function git(args, env) {
1324
1547
  return stdout;
1325
1548
  }
1326
1549
  function absoluteGitPath(value) {
1327
- if (!value || value.includes("\0") || !isAbsolute(value)) {
1550
+ if (!value || value.includes("\0") || !isAbsolute2(value)) {
1328
1551
  throw new Error("Git did not return an absolute repository path");
1329
1552
  }
1330
1553
  return resolve(value);
1331
1554
  }
1332
1555
  async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment()) {
1333
- if (!isAbsolute(workingDirectory) || workingDirectory.includes("\0")) {
1556
+ if (!isAbsolute2(workingDirectory) || workingDirectory.includes("\0")) {
1334
1557
  throw new Error("Git project inspection requires an absolute working directory");
1335
1558
  }
1336
1559
  let output;
@@ -1351,8 +1574,8 @@ async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment(
1351
1574
  }
1352
1575
  const roots = output.replace(/\r?\n$/, "").split(/\r?\n/);
1353
1576
  if (roots.length !== 2) throw new Error("Git returned ambiguous repository paths");
1354
- const worktreeRoot = await realpath(absoluteGitPath(roots[0]));
1355
- const commonGitDirectory = await realpath(absoluteGitPath(roots[1]));
1577
+ const worktreeRoot = await realpath2(absoluteGitPath(roots[0]));
1578
+ const commonGitDirectory = await realpath2(absoluteGitPath(roots[1]));
1356
1579
  const worktrees = await git(["-C", workingDirectory, "worktree", "list", "--porcelain", "-z"], env);
1357
1580
  if (!worktrees.endsWith("\0\0")) throw new Error("Git returned an incomplete worktree list");
1358
1581
  const primary = worktrees.split("\0\0", 1)[0]?.split("\0");
@@ -1379,7 +1602,7 @@ async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment(
1379
1602
  return {
1380
1603
  worktreeRoot,
1381
1604
  commonGitDirectory,
1382
- localRepositoryKey: createHash3("sha256").update(commonGitDirectory).digest("base64url"),
1605
+ localRepositoryKey: createHash4("sha256").update(commonGitDirectory).digest("base64url"),
1383
1606
  ...mainWorktreeRoot === void 0 ? {} : { mainWorktreeRoot },
1384
1607
  ...gitRemoteUrl === void 0 ? {} : { gitRemoteUrl }
1385
1608
  };
@@ -1394,8 +1617,8 @@ var PromptPreparationError = class extends Error {
1394
1617
  };
1395
1618
 
1396
1619
  // src/session-project-identity.ts
1397
- import { realpath as realpath2, stat } from "node:fs/promises";
1398
- import { isAbsolute as isAbsolute2 } from "node:path";
1620
+ import { realpath as realpath3, stat as stat2 } from "node:fs/promises";
1621
+ import { isAbsolute as isAbsolute3 } from "node:path";
1399
1622
  var SESSION_PROJECT_IDENTITY_CONCURRENCY = 20;
1400
1623
  var errors = {
1401
1624
  SESSION_NOT_FOUND: "The session is unavailable",
@@ -1412,8 +1635,8 @@ var SessionProjectIdentityError = class extends Error {
1412
1635
  code;
1413
1636
  };
1414
1637
  async function rootIdentity(workingDirectory) {
1415
- const root = await realpath2(workingDirectory);
1416
- const info = await stat(root);
1638
+ const root = await realpath3(workingDirectory);
1639
+ const info = await stat2(root);
1417
1640
  if (!info.isDirectory()) throw new SessionProjectIdentityError("SESSION_ROOT_UNAVAILABLE");
1418
1641
  return { path: root, key: `${root}\0${info.dev}\0${info.ino}` };
1419
1642
  }
@@ -1435,7 +1658,7 @@ var SessionProjectIdentityReader = class {
1435
1658
  const metadata = await this.metadata(sessionId);
1436
1659
  if (metadata === void 0) throw new SessionProjectIdentityError("SESSION_NOT_FOUND");
1437
1660
  const cwd = metadata.workingDirectory;
1438
- if (!cwd || !isAbsolute2(cwd) || cwd.includes("\0")) {
1661
+ if (!cwd || !isAbsolute3(cwd) || cwd.includes("\0")) {
1439
1662
  throw new SessionProjectIdentityError("SESSION_ROOT_UNAVAILABLE");
1440
1663
  }
1441
1664
  let initialRoot;
@@ -1492,7 +1715,7 @@ var SessionProjectIdentityReader = class {
1492
1715
  };
1493
1716
 
1494
1717
  // src/session-workbench-runtime.ts
1495
- import { createHash as createHash4 } from "node:crypto";
1718
+ import { createHash as createHash5 } from "node:crypto";
1496
1719
  import { z as z3 } from "zod";
1497
1720
  var WorkbenchRuntimeError = class extends SessionOperationError {
1498
1721
  constructor(code, message) {
@@ -1525,6 +1748,100 @@ function nanoAiu(value) {
1525
1748
  }
1526
1749
  return value.toString();
1527
1750
  }
1751
+ function decisionNodes(events) {
1752
+ const nodes = [];
1753
+ const starts = /* @__PURE__ */ new Map();
1754
+ for (const event of events) {
1755
+ if (event.ephemeral === true) continue;
1756
+ let kind;
1757
+ let status = "recorded";
1758
+ let title;
1759
+ let content = "";
1760
+ let invocation;
1761
+ switch (event.type) {
1762
+ case "assistant.reasoning":
1763
+ if (event.data.content.trim().length === 0) continue;
1764
+ kind = "rationale";
1765
+ content = event.data.content;
1766
+ title = content.trim().split(/\r?\n/u)[0] ?? "Rationale";
1767
+ break;
1768
+ case "session.plan_changed":
1769
+ kind = "plan";
1770
+ title = `Plan ${event.data.operation === "create" ? "created" : event.data.operation === "update" ? "updated" : "deleted"}`;
1771
+ break;
1772
+ case "tool.execution_start": {
1773
+ const args = event.data.arguments;
1774
+ const description = args !== null && typeof args === "object" && !Array.isArray(args) && typeof args.description === "string" ? args.description.trim() : void 0;
1775
+ kind = "tool";
1776
+ title = description || event.data.toolTitle?.trim() || event.data.toolName;
1777
+ status = "started";
1778
+ invocation = `tool:${event.data.toolCallId}`;
1779
+ break;
1780
+ }
1781
+ case "tool.execution_complete":
1782
+ kind = "tool";
1783
+ title = event.data.toolDescription?.name ?? "Tool result";
1784
+ status = event.data.success ? "completed" : "failed";
1785
+ content = event.data.error?.message ?? "";
1786
+ invocation = `tool:${event.data.toolCallId}`;
1787
+ break;
1788
+ case "subagent.started":
1789
+ case "subagent.completed":
1790
+ case "subagent.failed":
1791
+ kind = "subagent";
1792
+ title = event.data.agentDisplayName;
1793
+ status = event.type === "subagent.started" ? "started" : event.type === "subagent.completed" ? "completed" : "failed";
1794
+ content = event.type === "subagent.started" ? event.data.agentDescription : event.type === "subagent.failed" ? event.data.error : "";
1795
+ invocation = `subagent:${event.data.toolCallId}`;
1796
+ break;
1797
+ case "assistant.message":
1798
+ if (event.data.content.trim().length === 0 || (event.data.toolRequests?.length ?? 0) > 0) continue;
1799
+ kind = "response";
1800
+ title = "Response";
1801
+ content = event.data.content;
1802
+ break;
1803
+ case "session.compaction_complete":
1804
+ kind = "compaction";
1805
+ status = event.data.success ? "completed" : "failed";
1806
+ title = "Compact context";
1807
+ content = [
1808
+ event.data.preCompactionTokens === void 0 ? void 0 : `Before: ${event.data.preCompactionTokens} tokens`,
1809
+ event.data.postCompactionTokens === void 0 ? void 0 : `After: ${event.data.postCompactionTokens} tokens`,
1810
+ event.data.tokensRemoved === void 0 ? void 0 : `Released: ${event.data.tokensRemoved} tokens`,
1811
+ event.data.trigger,
1812
+ event.data.error
1813
+ ].filter((part) => part !== void 0).join("\n\n");
1814
+ break;
1815
+ default:
1816
+ continue;
1817
+ }
1818
+ const previousIndex = invocation === void 0 ? void 0 : starts.get(invocation);
1819
+ const previous = previousIndex === void 0 ? void 0 : nodes[previousIndex];
1820
+ if (previous !== void 0 && previousIndex !== void 0) {
1821
+ nodes[previousIndex] = {
1822
+ ...previous,
1823
+ status,
1824
+ ...content.length === 0 ? {} : {
1825
+ content: content.slice(0, WORKBENCH_REASONING_TEXT_LIMIT),
1826
+ truncated: content.length > WORKBENCH_REASONING_TEXT_LIMIT
1827
+ }
1828
+ };
1829
+ } else {
1830
+ if (invocation !== void 0) starts.set(invocation, nodes.length);
1831
+ nodes.push({
1832
+ id: event.id,
1833
+ timestamp: event.timestamp,
1834
+ ...event.agentId === void 0 ? {} : { agentId: event.agentId },
1835
+ kind,
1836
+ title: title.trim().slice(0, 256) || kind,
1837
+ status,
1838
+ content: content.slice(0, WORKBENCH_REASONING_TEXT_LIMIT),
1839
+ truncated: content.length > WORKBENCH_REASONING_TEXT_LIMIT
1840
+ });
1841
+ }
1842
+ }
1843
+ return nodes;
1844
+ }
1528
1845
  async function readWorkbenchMetrics(rpc) {
1529
1846
  if (rpc.usage === void 0 || rpc.model === void 0 || rpc.metadata?.contextInfo === void 0) {
1530
1847
  throw new WorkbenchRuntimeError("unsupported", "Runtime usage/context inspection is unavailable");
@@ -1541,6 +1858,7 @@ async function readWorkbenchMetrics(rpc) {
1541
1858
  outputTokenLimit: attributed === void 0 || attributed === null ? 0 : Math.max(0, attributed.limit - attributed.promptTokenLimit),
1542
1859
  ...modelId === void 0 ? {} : { selectedModel: modelId }
1543
1860
  });
1861
+ const heaviest = await rpc.metadata.getContextHeaviestMessages?.({ limit: 10 });
1544
1862
  return {
1545
1863
  ...modelId === void 0 ? {} : { modelId },
1546
1864
  totalPremiumRequestCost: usage.totalPremiumRequestCost,
@@ -1557,7 +1875,31 @@ async function readWorkbenchMetrics(rpc) {
1557
1875
  premiumRequestCost: metric.requests.cost,
1558
1876
  ...metric.totalNanoAiu === void 0 ? {} : { totalNanoAiu: nanoAiu(metric.totalNanoAiu) }
1559
1877
  }]),
1560
- context: contextInfo ?? null
1878
+ context: contextInfo ?? null,
1879
+ ...attributed === void 0 || attributed === null ? {} : {
1880
+ composition: [
1881
+ { kind: "System", count: attributed.categories.systemPrompt },
1882
+ { kind: "Instructions", count: attributed.categories.customInstructions },
1883
+ { kind: "Conversation", count: attributed.categories.messages },
1884
+ { kind: "Tools", count: attributed.categories.systemTools },
1885
+ { kind: "MCP", count: attributed.categories.mcpTools }
1886
+ ],
1887
+ sources: [...attributed.entries].sort((a, b) => b.tokens - a.tokens).slice(0, 24).map((entry) => ({
1888
+ id: entry.id.slice(0, 256),
1889
+ kind: entry.kind.slice(0, 256),
1890
+ label: entry.label.slice(0, 256),
1891
+ tokens: entry.tokens,
1892
+ ...entry.parentId === void 0 ? {} : { parentId: entry.parentId.slice(0, 256) }
1893
+ })),
1894
+ sourcesTruncated: attributed.entries.length > 24,
1895
+ ...attributed.compactions === void 0 ? {} : { compactionCount: attributed.compactions.count }
1896
+ },
1897
+ ...heaviest === void 0 ? {} : { heaviestMessages: heaviest.messages.slice(0, 10).map((message) => ({
1898
+ id: message.id.slice(0, 256),
1899
+ kind: message.role.slice(0, 256),
1900
+ label: message.label.slice(0, 256),
1901
+ tokens: message.tokens
1902
+ })) }
1561
1903
  };
1562
1904
  }
1563
1905
  function projectWorkbenchInsights(result) {
@@ -1583,11 +1925,20 @@ function projectWorkbenchInsights(result) {
1583
1925
  ...result.context === null ? {} : { context: {
1584
1926
  currentTokens: result.context.totalTokens,
1585
1927
  tokenLimit: result.context.promptTokenLimit,
1928
+ displayLimit: result.context.limit,
1929
+ compactionThreshold: result.context.compactionThreshold,
1586
1930
  systemTokens: result.context.systemTokens,
1587
1931
  conversationTokens: result.context.conversationTokens,
1588
1932
  toolTokens: result.context.toolDefinitionsTokens
1589
1933
  } },
1590
1934
  canCompact: result.compactAllowed,
1935
+ ...result.composition === void 0 ? {} : { composition: result.composition },
1936
+ ...result.sources === void 0 ? {} : { sources: result.sources },
1937
+ ...result.sourcesTruncated === void 0 ? {} : { sourcesTruncated: result.sourcesTruncated },
1938
+ ...result.heaviestMessages === void 0 ? {} : { heaviestMessages: result.heaviestMessages },
1939
+ ...result.compactionCount === void 0 ? {} : { compactionCount: result.compactionCount },
1940
+ ...result.telemetry === void 0 ? {} : { telemetry: result.telemetry },
1941
+ ...result.storage === void 0 ? {} : { storage: result.storage },
1591
1942
  ...result.compactDisabledReason === void 0 ? {} : { compactUnavailableReason: result.compactDisabledReason }
1592
1943
  });
1593
1944
  }
@@ -1615,6 +1966,55 @@ var SessionWorkbenchRuntime = class {
1615
1966
  throw new WorkbenchOutcomeUncertainError("Session runtime changed during the operation; do not replay mutations");
1616
1967
  }
1617
1968
  }
1969
+ async reasoning(sessionId, request) {
1970
+ WorkbenchReasoningRequestSchema.parse(request);
1971
+ this.dependencies.assertAvailable(sessionId);
1972
+ const current2 = this.dependencies.currentSession(sessionId);
1973
+ if (current2 === void 0) {
1974
+ throw new WorkbenchRuntimeError("unsupported", "Open the session before reading its thinking history");
1975
+ }
1976
+ const generation = this.#generation(this.dependencies.getRuntime(sessionId));
1977
+ const session = await current2;
1978
+ this.#assertGeneration(sessionId, generation);
1979
+ if (session.rpc.eventLog === void 0) {
1980
+ throw new WorkbenchRuntimeError("unsupported", "Runtime thinking history is unavailable");
1981
+ }
1982
+ const page = await session.rpc.eventLog.read({
1983
+ ...request.cursor === void 0 ? {} : { cursor: request.cursor },
1984
+ direction: "backward",
1985
+ max: WORKBENCH_REASONING_PAGE_SIZE,
1986
+ types: [
1987
+ "assistant.reasoning",
1988
+ "session.plan_changed",
1989
+ "tool.execution_start",
1990
+ "tool.execution_complete",
1991
+ "subagent.started",
1992
+ "subagent.completed",
1993
+ "subagent.failed",
1994
+ "assistant.message",
1995
+ "session.compaction_complete"
1996
+ ],
1997
+ agentScope: "all",
1998
+ includeEphemeral: false
1999
+ });
2000
+ this.#assertGeneration(sessionId, generation);
2001
+ if (page.cursorStatus !== "ok") {
2002
+ throw new WorkbenchRuntimeError("stale-runtime", "Thinking history changed. Refresh to read it again.");
2003
+ }
2004
+ const nodes = decisionNodes(page.events);
2005
+ return WorkbenchReasoningPageSchema.parse({
2006
+ nodes,
2007
+ blocks: nodes.filter((node) => node.kind === "rationale").map((node) => ({
2008
+ id: node.id,
2009
+ timestamp: node.timestamp,
2010
+ ...node.agentId === void 0 ? {} : { agentId: node.agentId },
2011
+ content: node.content,
2012
+ truncated: node.truncated
2013
+ })),
2014
+ cursor: page.cursor,
2015
+ hasMore: page.hasMore
2016
+ });
2017
+ }
1618
2018
  async ask(sessionId, question) {
1619
2019
  z3.string().trim().min(1).max(16 * 1024).parse(question);
1620
2020
  this.dependencies.assertAvailable(sessionId);
@@ -1668,7 +2068,7 @@ var SessionWorkbenchRuntime = class {
1668
2068
  }
1669
2069
  return {
1670
2070
  runtimeGeneration: generation,
1671
- revision: createHash4("sha256").update(JSON.stringify(pending)).digest("hex"),
2071
+ revision: createHash5("sha256").update(JSON.stringify(pending)).digest("hex"),
1672
2072
  sampledAt: (/* @__PURE__ */ new Date()).toISOString(),
1673
2073
  items: [...groups.values()],
1674
2074
  steeringMessages: pending.steeringMessages
@@ -1798,6 +2198,10 @@ var SessionWorkbenchRuntime = class {
1798
2198
  async readInsights(sessionId) {
1799
2199
  const { session, runtime, generation } = await this.#session(sessionId);
1800
2200
  const metrics = await readWorkbenchMetrics(session.rpc);
2201
+ const [telemetry, storage] = await Promise.all([
2202
+ this.dependencies.telemetry?.(sessionId),
2203
+ this.dependencies.storage?.(sessionId)
2204
+ ]);
1801
2205
  const reason = runtime.workbench.compacting ? "Context compaction is in progress" : await this.#compactionDisabledReason(sessionId, session, runtime);
1802
2206
  this.#assertGeneration(sessionId, generation);
1803
2207
  return {
@@ -1805,6 +2209,8 @@ var SessionWorkbenchRuntime = class {
1805
2209
  runtimeGeneration: generation,
1806
2210
  sampledAt: (/* @__PURE__ */ new Date()).toISOString(),
1807
2211
  compactAllowed: reason === void 0,
2212
+ ...telemetry === void 0 ? {} : { telemetry },
2213
+ ...storage === void 0 ? {} : { storage },
1808
2214
  ...reason === void 0 ? {} : { compactDisabledReason: reason }
1809
2215
  };
1810
2216
  }
@@ -1954,6 +2360,10 @@ export {
1954
2360
  SessionRuntime,
1955
2361
  SessionRuntimeRegistry,
1956
2362
  LiveTimelineProjection,
2363
+ SessionDirectoryError,
2364
+ contained,
2365
+ sessionRootIdentity,
2366
+ SessionDirectoryLister,
1957
2367
  sanitizeGitRemoteUrl,
1958
2368
  NotGitDirectoryError,
1959
2369
  resolveGitProjectIdentity,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  SessionAssistantPreviewSchema,
3
3
  SessionUserPreviewSchema
4
- } from "./chunk-KBI5IWPR.js";
4
+ } from "./chunk-LO4ZRE77.js";
5
5
 
6
6
  // src/assistant-preview.ts
7
7
  function isContentfulAssistant(item) {
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  AgentSessionRenameError,
3
3
  validateSessionName
4
- } from "./chunk-3LEPYV7Y.js";
4
+ } from "./chunk-5DVJ7Y5W.js";
5
5
  import {
6
6
  ConversationItemSchema,
7
7
  GroupChatInfoSchema,
8
8
  GroupChatParticipantSchema,
9
9
  SESSION_TIMELINE_PAGE_SIZE,
10
10
  SessionSummarySchema
11
- } from "./chunk-KBI5IWPR.js";
11
+ } from "./chunk-LO4ZRE77.js";
12
12
 
13
13
  // src/group-chat.ts
14
14
  import { createHash, randomUUID } from "node:crypto";
@@ -1011,7 +1011,6 @@ ${data.content}`,
1011
1011
 
1012
1012
  export {
1013
1013
  GroupChatMessageSchema,
1014
- GROUP_CHAT_MAX_TURNS,
1015
1014
  GroupChatError,
1016
1015
  GroupChatRuntime
1017
1016
  };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CONVERSATION_SOURCE_ID_LIMIT
3
- } from "./chunk-KBI5IWPR.js";
3
+ } from "./chunk-LO4ZRE77.js";
4
4
 
5
5
  // src/conversation-normalizer.ts
6
6
  import { createHash } from "node:crypto";