@agentknight/sdk 0.9.57 → 0.9.61

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-MBYKOCA2.js} +4 -4
  2. package/dist/chunks/{chunk-OOCAIULD.js → chunk-3AMFPDE5.js} +435 -21
  3. package/dist/chunks/{chunk-3LEPYV7Y.js → chunk-7CNBPLNE.js} +2 -2
  4. package/dist/chunks/{chunk-7ZYBES47.js → chunk-7OGTK7KB.js} +1 -1
  5. package/dist/chunks/{chunk-WPVH7HKC.js → chunk-A4YCCQ3I.js} +1 -1
  6. package/dist/chunks/{chunk-EDZPP6SJ.js → chunk-ALUQLM54.js} +2 -3
  7. package/dist/chunks/{chunk-USI66MEF.js → chunk-CHKNC6PD.js} +3 -2
  8. package/dist/chunks/{chunk-ZLKFFKAX.js → chunk-CM5LVXVL.js} +4 -3
  9. package/dist/chunks/{chunk-IPJWNGNK.js → chunk-H4SHMWQ6.js} +1 -1
  10. package/dist/chunks/{chunk-KBI5IWPR.js → chunk-P2PH5KMV.js} +842 -557
  11. package/dist/chunks/{chunk-DAKDVZ7X.js → chunk-SIFCCGXF.js} +7 -5
  12. package/dist/chunks/{chunk-LT5ULDVT.js → chunk-ZNQ2I5EF.js} +1 -1
  13. package/dist/chunks/{claude-adapter-GCH36EZ6.js → claude-adapter-D3JWXMNX.js} +209 -59
  14. package/dist/chunks/{codex-adapter-CXD4SVCE.js → codex-adapter-655KHW7H.js} +4 -4
  15. package/dist/chunks/{copilot-adapter-SYFGOAGE.js → copilot-adapter-EZUXHBE3.js} +155 -25
  16. package/dist/chunks/{managed-agent-adapter-ODCNYYO6.js → managed-agent-adapter-BOJNEJ75.js} +25 -7
  17. package/dist/chunks/{pi-adapter-XLY46UDL.js → pi-adapter-LAD5GOCP.js} +4 -4
  18. package/dist/configuration.js +4 -4
  19. package/dist/index.d.ts +142 -1
  20. package/dist/index.js +1487 -578
  21. package/dist/runtime.js +2 -2
  22. package/dist/session-analytics-worker.js +162 -51
  23. package/package.json +1 -1
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  latestPreviewItems
3
- } from "./chunk-IPJWNGNK.js";
3
+ } from "./chunk-H4SHMWQ6.js";
4
4
  import {
5
5
  UnsupportedAgentOperationError
6
- } from "./chunk-3LEPYV7Y.js";
7
- import "./chunk-7ZYBES47.js";
6
+ } from "./chunk-7CNBPLNE.js";
7
+ import "./chunk-7OGTK7KB.js";
8
8
  import {
9
9
  ConversationItemSchema,
10
10
  PromptImageAttachmentSchema,
11
11
  SESSION_TIMELINE_PAGE_SIZE,
12
12
  SessionSummarySchema
13
- } from "./chunk-KBI5IWPR.js";
13
+ } from "./chunk-P2PH5KMV.js";
14
14
 
15
15
  // src/acp-adapter.ts
16
16
  import { spawn } from "node:child_process";
@@ -6,16 +6,18 @@ import {
6
6
  ConversationNormalizer,
7
7
  ConversationToolLifecycles,
8
8
  assistantMessageId
9
- } from "./chunk-LT5ULDVT.js";
9
+ } from "./chunk-ZNQ2I5EF.js";
10
10
  import {
11
11
  isContentfulAssistant
12
- } from "./chunk-IPJWNGNK.js";
12
+ } from "./chunk-H4SHMWQ6.js";
13
13
  import {
14
14
  SessionOperationError
15
- } from "./chunk-7ZYBES47.js";
15
+ } from "./chunk-7OGTK7KB.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-P2PH5KMV.js";
45
52
 
46
53
  // src/session-image-uploader.ts
47
54
  import { createHash } from "node:crypto";
@@ -445,6 +452,9 @@ function isClosedCopilotConnection(error) {
445
452
  function isDisposedCopilotSession(error) {
446
453
  return error instanceof Error && (error.message === "Session has been disposed" || (!("code" in error) || error.code === -32603) && /^Request session\.[A-Za-z0-9.]+ failed with message: Session has been disposed$/u.test(error.message));
447
454
  }
455
+ function isClosedCopilotRuntimeHost(error) {
456
+ return error instanceof Error && (!("code" in error) || error.code === -32603) && /^Request session\.[A-Za-z0-9.]+ failed with message: the runtime host command queue is closed$/u.test(error.message);
457
+ }
448
458
 
449
459
  // src/session-restore-error.ts
450
460
  var restoreMessages = /* @__PURE__ */ new Set([
@@ -1256,6 +1266,222 @@ ${state.deltaContent}`).slice(0, 4096),
1256
1266
  }
1257
1267
  };
1258
1268
 
1269
+ // src/session-directory.ts
1270
+ import { createHash as createHash3 } from "node:crypto";
1271
+ import { lstat, opendir, realpath, stat } from "node:fs/promises";
1272
+ import { isAbsolute, join, relative, sep } from "node:path";
1273
+ var SESSION_DIRECTORY_CONCURRENCY = 4;
1274
+ var SESSION_DIRECTORY_TIMEOUT_MS = 5e3;
1275
+ var SessionDirectoryError = class extends Error {
1276
+ constructor(code, message, options) {
1277
+ super(message, options);
1278
+ this.code = code;
1279
+ }
1280
+ code;
1281
+ };
1282
+ function fail(code, message) {
1283
+ throw new SessionDirectoryError(code, message);
1284
+ }
1285
+ function contained(root, candidate) {
1286
+ const path = relative(root, candidate);
1287
+ return path === "" || !isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`);
1288
+ }
1289
+ function sessionRootIdentity(root, info) {
1290
+ return `${root}\0${info.dev}\0${info.ino}`;
1291
+ }
1292
+ var SessionDirectoryLister = class {
1293
+ constructor(metadata) {
1294
+ this.metadata = metadata;
1295
+ }
1296
+ metadata;
1297
+ #active = 0;
1298
+ #storageCache = /* @__PURE__ */ new Map();
1299
+ async storage(sessionId) {
1300
+ if (this.#active >= SESSION_DIRECTORY_CONCURRENCY) fail("DIRECTORY_BUSY", "Too many directory requests");
1301
+ this.#active++;
1302
+ try {
1303
+ const metadata = await this.metadata(sessionId);
1304
+ const path = metadata?.sessionStateDirectory;
1305
+ if (path === void 0) return void 0;
1306
+ if (!isAbsolute(path)) fail("SESSION_ROOT_UNAVAILABLE", "The session state directory is unavailable");
1307
+ const info = await lstat(path, { bigint: true });
1308
+ if (!info.isDirectory() || info.isSymbolicLink()) fail("DIRECTORY_BLOCKED", "Links cannot be measured");
1309
+ const root = await realpath(path), identity = sessionRootIdentity(root, info);
1310
+ const cached = this.#storageCache.get(sessionId);
1311
+ if (cached?.identity === identity && cached.expires > Date.now()) return cached.value;
1312
+ const pending = [root], deadline = Date.now() + SESSION_DIRECTORY_TIMEOUT_MS;
1313
+ let bytes = 0, files = 0, visited = 0, partial = false;
1314
+ while (pending.length > 0 && visited < 1e4 && Date.now() < deadline) {
1315
+ const target = pending.pop();
1316
+ if (target === void 0) break;
1317
+ if ((await lstat(target)).isSymbolicLink() || !contained(root, await realpath(target))) {
1318
+ fail("DIRECTORY_BLOCKED", "The storage directory changed");
1319
+ }
1320
+ const directory = await opendir(target, { bufferSize: 32 });
1321
+ try {
1322
+ while (visited < 1e4 && Date.now() < deadline) {
1323
+ const entry = await directory.read();
1324
+ if (entry === null) break;
1325
+ visited++;
1326
+ const child = join(target, entry.name);
1327
+ const childInfo = await lstat(child);
1328
+ if (childInfo.isSymbolicLink()) {
1329
+ partial = true;
1330
+ continue;
1331
+ }
1332
+ if (childInfo.isDirectory()) pending.push(child);
1333
+ else if (childInfo.isFile()) {
1334
+ bytes += childInfo.size;
1335
+ files++;
1336
+ } else partial = true;
1337
+ if (!Number.isSafeInteger(bytes)) fail("DIRECTORY_LIMIT_EXCEEDED", "Storage size exceeds the supported range");
1338
+ }
1339
+ } finally {
1340
+ await directory.close();
1341
+ }
1342
+ }
1343
+ partial ||= pending.length > 0 || visited >= 1e4 || Date.now() >= deadline;
1344
+ const latest = await this.metadata(sessionId);
1345
+ const latestInfo = await lstat(path, { bigint: true });
1346
+ if (latest?.sessionStateDirectory !== path || latestInfo.isSymbolicLink() || sessionRootIdentity(await realpath(path), latestInfo) !== identity) {
1347
+ fail("SESSION_ROOT_CHANGED", "The session directory changed");
1348
+ }
1349
+ const value = { bytes, files, partial, sampledAt: (/* @__PURE__ */ new Date()).toISOString() };
1350
+ this.#storageCache.delete(sessionId);
1351
+ if (this.#storageCache.size >= 32) {
1352
+ const oldest = this.#storageCache.keys().next().value;
1353
+ if (oldest !== void 0) this.#storageCache.delete(oldest);
1354
+ }
1355
+ this.#storageCache.set(sessionId, { identity, value, expires: Date.now() + 3e4 });
1356
+ return value;
1357
+ } catch (error) {
1358
+ if (error instanceof SessionDirectoryError) throw error;
1359
+ throw new SessionDirectoryError("DIRECTORY_UNAVAILABLE", "Session storage measurement failed", { cause: error });
1360
+ } finally {
1361
+ this.#active--;
1362
+ }
1363
+ }
1364
+ async list(sessionId, path, space) {
1365
+ if (!isSafeSessionDirectoryPath(path)) {
1366
+ fail("INVALID_DIRECTORY_PATH", "The directory path is not allowed");
1367
+ }
1368
+ if (this.#active >= SESSION_DIRECTORY_CONCURRENCY) {
1369
+ fail("DIRECTORY_BUSY", "Too many directory requests");
1370
+ }
1371
+ this.#active++;
1372
+ const deadline = Date.now() + SESSION_DIRECTORY_TIMEOUT_MS;
1373
+ const checkDeadline = () => {
1374
+ if (Date.now() >= deadline) fail("DIRECTORY_TIMEOUT", "The directory request timed out");
1375
+ };
1376
+ const work = this.#list(sessionId, path, checkDeadline, space).finally(() => {
1377
+ this.#active--;
1378
+ });
1379
+ let timer;
1380
+ try {
1381
+ return await Promise.race([
1382
+ work,
1383
+ new Promise((_, reject) => {
1384
+ timer = setTimeout(() => reject(new SessionDirectoryError(
1385
+ "DIRECTORY_TIMEOUT",
1386
+ "The directory request timed out"
1387
+ )), SESSION_DIRECTORY_TIMEOUT_MS);
1388
+ })
1389
+ ]);
1390
+ } catch (error) {
1391
+ if (error instanceof SessionDirectoryError) throw error;
1392
+ throw new SessionDirectoryError("DIRECTORY_UNAVAILABLE", "The directory is unavailable", { cause: error });
1393
+ } finally {
1394
+ clearTimeout(timer);
1395
+ }
1396
+ }
1397
+ async #list(sessionId, path, checkDeadline, space) {
1398
+ const metadata = await this.metadata(sessionId);
1399
+ checkDeadline();
1400
+ if (metadata === void 0) fail("SESSION_NOT_FOUND", "The session is unavailable");
1401
+ const workingDirectory = space === "session" ? metadata.sessionStateDirectory : metadata.workingDirectory;
1402
+ if (!workingDirectory || !isAbsolute(workingDirectory)) {
1403
+ fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
1404
+ }
1405
+ let root;
1406
+ let rootIdentity2;
1407
+ try {
1408
+ if (space === "session" && (await lstat(workingDirectory)).isSymbolicLink()) {
1409
+ fail("SESSION_ROOT_UNAVAILABLE", "The session state directory is unavailable");
1410
+ }
1411
+ root = await realpath(workingDirectory);
1412
+ const info = await stat(root, { bigint: true });
1413
+ if (!info.isDirectory()) fail("SESSION_ROOT_UNAVAILABLE", "The session working directory is unavailable");
1414
+ rootIdentity2 = sessionRootIdentity(root, info);
1415
+ } catch (error) {
1416
+ throw new SessionDirectoryError(
1417
+ "SESSION_ROOT_UNAVAILABLE",
1418
+ "The session working directory is unavailable",
1419
+ { cause: error }
1420
+ );
1421
+ }
1422
+ checkDeadline();
1423
+ let target = root;
1424
+ for (const segment of path === "" ? [] : path.split("/")) {
1425
+ target = join(target, segment);
1426
+ const info = await lstat(target);
1427
+ checkDeadline();
1428
+ if (info.isSymbolicLink()) fail("DIRECTORY_BLOCKED", "Links cannot be opened");
1429
+ if (!info.isDirectory()) fail("NOT_A_DIRECTORY", "The selected entry is not a directory");
1430
+ if (!contained(root, await realpath(target))) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
1431
+ checkDeadline();
1432
+ }
1433
+ const canonicalTarget = await realpath(target);
1434
+ if (!contained(root, canonicalTarget)) fail("DIRECTORY_BLOCKED", "The directory is outside the session");
1435
+ checkDeadline();
1436
+ const directory = await opendir(target, { bufferSize: 32 });
1437
+ const entries = [];
1438
+ let bytes = 8192 + (space === "session" ? Buffer.byteLength(JSON.stringify(workingDirectory), "utf8") : 0);
1439
+ try {
1440
+ checkDeadline();
1441
+ for (; ; ) {
1442
+ const entry = await directory.read();
1443
+ checkDeadline();
1444
+ if (entry === null) break;
1445
+ if (entries.length >= SESSION_DIRECTORY_MAX_ENTRIES) {
1446
+ fail("DIRECTORY_LIMIT_EXCEEDED", "The directory has too many entries");
1447
+ }
1448
+ let kind = "blocked";
1449
+ if (isSafeSessionDirectoryPath(entry.name) && !entry.name.includes("/")) {
1450
+ const child = join(target, entry.name);
1451
+ const info = await lstat(child);
1452
+ checkDeadline();
1453
+ if (!info.isSymbolicLink() && contained(root, await realpath(child))) {
1454
+ kind = info.isDirectory() ? "directory" : info.isFile() ? "file" : "blocked";
1455
+ }
1456
+ }
1457
+ const result = { name: entry.name, kind };
1458
+ bytes += Buffer.byteLength(JSON.stringify(result), "utf8") + 1;
1459
+ if (bytes > SESSION_DIRECTORY_MAX_RESPONSE_BYTES) {
1460
+ fail("DIRECTORY_LIMIT_EXCEEDED", "The directory listing is too large");
1461
+ }
1462
+ entries.push(result);
1463
+ }
1464
+ const latestMetadata = await this.metadata(sessionId);
1465
+ const latestRoot = await realpath(workingDirectory);
1466
+ const latestInfo = await stat(latestRoot, { bigint: true });
1467
+ if ((space === "session" ? latestMetadata?.sessionStateDirectory : latestMetadata?.workingDirectory) !== workingDirectory || sessionRootIdentity(latestRoot, latestInfo) !== rootIdentity2 || await realpath(target) !== canonicalTarget) {
1468
+ fail("SESSION_ROOT_CHANGED", "The session directory changed");
1469
+ }
1470
+ checkDeadline();
1471
+ } finally {
1472
+ await directory.close();
1473
+ }
1474
+ const order = { directory: 0, file: 1, blocked: 2 };
1475
+ entries.sort((a, b) => order[a.kind] - order[b.kind] || a.name.localeCompare(b.name));
1476
+ return {
1477
+ rootRevision: createHash3("sha256").update(rootIdentity2).digest("base64url"),
1478
+ entries,
1479
+ // SDK links can use a configured home reached through a parent junction.
1480
+ ...space === "session" ? { rootPath: workingDirectory } : {}
1481
+ };
1482
+ }
1483
+ };
1484
+
1259
1485
  // src/git-remote-url.ts
1260
1486
  function sanitizeGitRemoteUrl(value) {
1261
1487
  const remote = value.trim();
@@ -1285,9 +1511,9 @@ function sanitizeGitRemoteUrl(value) {
1285
1511
 
1286
1512
  // src/git-project-identity.ts
1287
1513
  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";
1514
+ import { createHash as createHash4 } from "node:crypto";
1515
+ import { realpath as realpath2 } from "node:fs/promises";
1516
+ import { isAbsolute as isAbsolute2, resolve } from "node:path";
1291
1517
  import { promisify } from "node:util";
1292
1518
  var execFileAsync = promisify(execFile);
1293
1519
  var NotGitDirectoryError = class extends Error {
@@ -1324,13 +1550,13 @@ async function git(args, env) {
1324
1550
  return stdout;
1325
1551
  }
1326
1552
  function absoluteGitPath(value) {
1327
- if (!value || value.includes("\0") || !isAbsolute(value)) {
1553
+ if (!value || value.includes("\0") || !isAbsolute2(value)) {
1328
1554
  throw new Error("Git did not return an absolute repository path");
1329
1555
  }
1330
1556
  return resolve(value);
1331
1557
  }
1332
1558
  async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment()) {
1333
- if (!isAbsolute(workingDirectory) || workingDirectory.includes("\0")) {
1559
+ if (!isAbsolute2(workingDirectory) || workingDirectory.includes("\0")) {
1334
1560
  throw new Error("Git project inspection requires an absolute working directory");
1335
1561
  }
1336
1562
  let output;
@@ -1351,8 +1577,8 @@ async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment(
1351
1577
  }
1352
1578
  const roots = output.replace(/\r?\n$/, "").split(/\r?\n/);
1353
1579
  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]));
1580
+ const worktreeRoot = await realpath2(absoluteGitPath(roots[0]));
1581
+ const commonGitDirectory = await realpath2(absoluteGitPath(roots[1]));
1356
1582
  const worktrees = await git(["-C", workingDirectory, "worktree", "list", "--porcelain", "-z"], env);
1357
1583
  if (!worktrees.endsWith("\0\0")) throw new Error("Git returned an incomplete worktree list");
1358
1584
  const primary = worktrees.split("\0\0", 1)[0]?.split("\0");
@@ -1379,7 +1605,7 @@ async function resolveGitProjectIdentity(workingDirectory, env = gitEnvironment(
1379
1605
  return {
1380
1606
  worktreeRoot,
1381
1607
  commonGitDirectory,
1382
- localRepositoryKey: createHash3("sha256").update(commonGitDirectory).digest("base64url"),
1608
+ localRepositoryKey: createHash4("sha256").update(commonGitDirectory).digest("base64url"),
1383
1609
  ...mainWorktreeRoot === void 0 ? {} : { mainWorktreeRoot },
1384
1610
  ...gitRemoteUrl === void 0 ? {} : { gitRemoteUrl }
1385
1611
  };
@@ -1394,8 +1620,8 @@ var PromptPreparationError = class extends Error {
1394
1620
  };
1395
1621
 
1396
1622
  // src/session-project-identity.ts
1397
- import { realpath as realpath2, stat } from "node:fs/promises";
1398
- import { isAbsolute as isAbsolute2 } from "node:path";
1623
+ import { realpath as realpath3, stat as stat2 } from "node:fs/promises";
1624
+ import { isAbsolute as isAbsolute3 } from "node:path";
1399
1625
  var SESSION_PROJECT_IDENTITY_CONCURRENCY = 20;
1400
1626
  var errors = {
1401
1627
  SESSION_NOT_FOUND: "The session is unavailable",
@@ -1412,8 +1638,8 @@ var SessionProjectIdentityError = class extends Error {
1412
1638
  code;
1413
1639
  };
1414
1640
  async function rootIdentity(workingDirectory) {
1415
- const root = await realpath2(workingDirectory);
1416
- const info = await stat(root);
1641
+ const root = await realpath3(workingDirectory);
1642
+ const info = await stat2(root);
1417
1643
  if (!info.isDirectory()) throw new SessionProjectIdentityError("SESSION_ROOT_UNAVAILABLE");
1418
1644
  return { path: root, key: `${root}\0${info.dev}\0${info.ino}` };
1419
1645
  }
@@ -1435,7 +1661,7 @@ var SessionProjectIdentityReader = class {
1435
1661
  const metadata = await this.metadata(sessionId);
1436
1662
  if (metadata === void 0) throw new SessionProjectIdentityError("SESSION_NOT_FOUND");
1437
1663
  const cwd = metadata.workingDirectory;
1438
- if (!cwd || !isAbsolute2(cwd) || cwd.includes("\0")) {
1664
+ if (!cwd || !isAbsolute3(cwd) || cwd.includes("\0")) {
1439
1665
  throw new SessionProjectIdentityError("SESSION_ROOT_UNAVAILABLE");
1440
1666
  }
1441
1667
  let initialRoot;
@@ -1492,7 +1718,7 @@ var SessionProjectIdentityReader = class {
1492
1718
  };
1493
1719
 
1494
1720
  // src/session-workbench-runtime.ts
1495
- import { createHash as createHash4 } from "node:crypto";
1721
+ import { createHash as createHash5 } from "node:crypto";
1496
1722
  import { z as z3 } from "zod";
1497
1723
  var WorkbenchRuntimeError = class extends SessionOperationError {
1498
1724
  constructor(code, message) {
@@ -1525,6 +1751,100 @@ function nanoAiu(value) {
1525
1751
  }
1526
1752
  return value.toString();
1527
1753
  }
1754
+ function decisionNodes(events) {
1755
+ const nodes = [];
1756
+ const starts = /* @__PURE__ */ new Map();
1757
+ for (const event of events) {
1758
+ if (event.ephemeral === true) continue;
1759
+ let kind;
1760
+ let status = "recorded";
1761
+ let title;
1762
+ let content = "";
1763
+ let invocation;
1764
+ switch (event.type) {
1765
+ case "assistant.reasoning":
1766
+ if (event.data.content.trim().length === 0) continue;
1767
+ kind = "rationale";
1768
+ content = event.data.content;
1769
+ title = content.trim().split(/\r?\n/u)[0] ?? "Rationale";
1770
+ break;
1771
+ case "session.plan_changed":
1772
+ kind = "plan";
1773
+ title = `Plan ${event.data.operation === "create" ? "created" : event.data.operation === "update" ? "updated" : "deleted"}`;
1774
+ break;
1775
+ case "tool.execution_start": {
1776
+ const args = event.data.arguments;
1777
+ const description = args !== null && typeof args === "object" && !Array.isArray(args) && typeof args.description === "string" ? args.description.trim() : void 0;
1778
+ kind = "tool";
1779
+ title = description || event.data.toolTitle?.trim() || event.data.toolName;
1780
+ status = "started";
1781
+ invocation = `tool:${event.data.toolCallId}`;
1782
+ break;
1783
+ }
1784
+ case "tool.execution_complete":
1785
+ kind = "tool";
1786
+ title = event.data.toolDescription?.name ?? "Tool result";
1787
+ status = event.data.success ? "completed" : "failed";
1788
+ content = event.data.error?.message ?? "";
1789
+ invocation = `tool:${event.data.toolCallId}`;
1790
+ break;
1791
+ case "subagent.started":
1792
+ case "subagent.completed":
1793
+ case "subagent.failed":
1794
+ kind = "subagent";
1795
+ title = event.data.agentDisplayName;
1796
+ status = event.type === "subagent.started" ? "started" : event.type === "subagent.completed" ? "completed" : "failed";
1797
+ content = event.type === "subagent.started" ? event.data.agentDescription : event.type === "subagent.failed" ? event.data.error : "";
1798
+ invocation = `subagent:${event.data.toolCallId}`;
1799
+ break;
1800
+ case "assistant.message":
1801
+ if (event.data.content.trim().length === 0 || (event.data.toolRequests?.length ?? 0) > 0) continue;
1802
+ kind = "response";
1803
+ title = "Response";
1804
+ content = event.data.content;
1805
+ break;
1806
+ case "session.compaction_complete":
1807
+ kind = "compaction";
1808
+ status = event.data.success ? "completed" : "failed";
1809
+ title = "Compact context";
1810
+ content = [
1811
+ event.data.preCompactionTokens === void 0 ? void 0 : `Before: ${event.data.preCompactionTokens} tokens`,
1812
+ event.data.postCompactionTokens === void 0 ? void 0 : `After: ${event.data.postCompactionTokens} tokens`,
1813
+ event.data.tokensRemoved === void 0 ? void 0 : `Released: ${event.data.tokensRemoved} tokens`,
1814
+ event.data.trigger,
1815
+ event.data.error
1816
+ ].filter((part) => part !== void 0).join("\n\n");
1817
+ break;
1818
+ default:
1819
+ continue;
1820
+ }
1821
+ const previousIndex = invocation === void 0 ? void 0 : starts.get(invocation);
1822
+ const previous = previousIndex === void 0 ? void 0 : nodes[previousIndex];
1823
+ if (previous !== void 0 && previousIndex !== void 0) {
1824
+ nodes[previousIndex] = {
1825
+ ...previous,
1826
+ status,
1827
+ ...content.length === 0 ? {} : {
1828
+ content: content.slice(0, WORKBENCH_REASONING_TEXT_LIMIT),
1829
+ truncated: content.length > WORKBENCH_REASONING_TEXT_LIMIT
1830
+ }
1831
+ };
1832
+ } else {
1833
+ if (invocation !== void 0) starts.set(invocation, nodes.length);
1834
+ nodes.push({
1835
+ id: event.id,
1836
+ timestamp: event.timestamp,
1837
+ ...event.agentId === void 0 ? {} : { agentId: event.agentId },
1838
+ kind,
1839
+ title: title.trim().slice(0, 256) || kind,
1840
+ status,
1841
+ content: content.slice(0, WORKBENCH_REASONING_TEXT_LIMIT),
1842
+ truncated: content.length > WORKBENCH_REASONING_TEXT_LIMIT
1843
+ });
1844
+ }
1845
+ }
1846
+ return nodes;
1847
+ }
1528
1848
  async function readWorkbenchMetrics(rpc) {
1529
1849
  if (rpc.usage === void 0 || rpc.model === void 0 || rpc.metadata?.contextInfo === void 0) {
1530
1850
  throw new WorkbenchRuntimeError("unsupported", "Runtime usage/context inspection is unavailable");
@@ -1541,6 +1861,7 @@ async function readWorkbenchMetrics(rpc) {
1541
1861
  outputTokenLimit: attributed === void 0 || attributed === null ? 0 : Math.max(0, attributed.limit - attributed.promptTokenLimit),
1542
1862
  ...modelId === void 0 ? {} : { selectedModel: modelId }
1543
1863
  });
1864
+ const heaviest = await rpc.metadata.getContextHeaviestMessages?.({ limit: 10 });
1544
1865
  return {
1545
1866
  ...modelId === void 0 ? {} : { modelId },
1546
1867
  totalPremiumRequestCost: usage.totalPremiumRequestCost,
@@ -1557,7 +1878,31 @@ async function readWorkbenchMetrics(rpc) {
1557
1878
  premiumRequestCost: metric.requests.cost,
1558
1879
  ...metric.totalNanoAiu === void 0 ? {} : { totalNanoAiu: nanoAiu(metric.totalNanoAiu) }
1559
1880
  }]),
1560
- context: contextInfo ?? null
1881
+ context: contextInfo ?? null,
1882
+ ...attributed === void 0 || attributed === null ? {} : {
1883
+ composition: [
1884
+ { kind: "System", count: attributed.categories.systemPrompt },
1885
+ { kind: "Instructions", count: attributed.categories.customInstructions },
1886
+ { kind: "Conversation", count: attributed.categories.messages },
1887
+ { kind: "Tools", count: attributed.categories.systemTools },
1888
+ { kind: "MCP", count: attributed.categories.mcpTools }
1889
+ ],
1890
+ sources: [...attributed.entries].sort((a, b) => b.tokens - a.tokens).slice(0, 24).map((entry) => ({
1891
+ id: entry.id.slice(0, 256),
1892
+ kind: entry.kind.slice(0, 256),
1893
+ label: entry.label.slice(0, 256),
1894
+ tokens: entry.tokens,
1895
+ ...entry.parentId === void 0 ? {} : { parentId: entry.parentId.slice(0, 256) }
1896
+ })),
1897
+ sourcesTruncated: attributed.entries.length > 24,
1898
+ ...attributed.compactions === void 0 ? {} : { compactionCount: attributed.compactions.count }
1899
+ },
1900
+ ...heaviest === void 0 ? {} : { heaviestMessages: heaviest.messages.slice(0, 10).map((message) => ({
1901
+ id: message.id.slice(0, 256),
1902
+ kind: message.role.slice(0, 256),
1903
+ label: message.label.slice(0, 256),
1904
+ tokens: message.tokens
1905
+ })) }
1561
1906
  };
1562
1907
  }
1563
1908
  function projectWorkbenchInsights(result) {
@@ -1583,11 +1928,20 @@ function projectWorkbenchInsights(result) {
1583
1928
  ...result.context === null ? {} : { context: {
1584
1929
  currentTokens: result.context.totalTokens,
1585
1930
  tokenLimit: result.context.promptTokenLimit,
1931
+ displayLimit: result.context.limit,
1932
+ compactionThreshold: result.context.compactionThreshold,
1586
1933
  systemTokens: result.context.systemTokens,
1587
1934
  conversationTokens: result.context.conversationTokens,
1588
1935
  toolTokens: result.context.toolDefinitionsTokens
1589
1936
  } },
1590
1937
  canCompact: result.compactAllowed,
1938
+ ...result.composition === void 0 ? {} : { composition: result.composition },
1939
+ ...result.sources === void 0 ? {} : { sources: result.sources },
1940
+ ...result.sourcesTruncated === void 0 ? {} : { sourcesTruncated: result.sourcesTruncated },
1941
+ ...result.heaviestMessages === void 0 ? {} : { heaviestMessages: result.heaviestMessages },
1942
+ ...result.compactionCount === void 0 ? {} : { compactionCount: result.compactionCount },
1943
+ ...result.telemetry === void 0 ? {} : { telemetry: result.telemetry },
1944
+ ...result.storage === void 0 ? {} : { storage: result.storage },
1591
1945
  ...result.compactDisabledReason === void 0 ? {} : { compactUnavailableReason: result.compactDisabledReason }
1592
1946
  });
1593
1947
  }
@@ -1615,6 +1969,55 @@ var SessionWorkbenchRuntime = class {
1615
1969
  throw new WorkbenchOutcomeUncertainError("Session runtime changed during the operation; do not replay mutations");
1616
1970
  }
1617
1971
  }
1972
+ async reasoning(sessionId, request) {
1973
+ WorkbenchReasoningRequestSchema.parse(request);
1974
+ this.dependencies.assertAvailable(sessionId);
1975
+ const current2 = this.dependencies.currentSession(sessionId);
1976
+ if (current2 === void 0) {
1977
+ throw new WorkbenchRuntimeError("unsupported", "Open the session before reading its thinking history");
1978
+ }
1979
+ const generation = this.#generation(this.dependencies.getRuntime(sessionId));
1980
+ const session = await current2;
1981
+ this.#assertGeneration(sessionId, generation);
1982
+ if (session.rpc.eventLog === void 0) {
1983
+ throw new WorkbenchRuntimeError("unsupported", "Runtime thinking history is unavailable");
1984
+ }
1985
+ const page = await session.rpc.eventLog.read({
1986
+ ...request.cursor === void 0 ? {} : { cursor: request.cursor },
1987
+ direction: "backward",
1988
+ max: WORKBENCH_REASONING_PAGE_SIZE,
1989
+ types: [
1990
+ "assistant.reasoning",
1991
+ "session.plan_changed",
1992
+ "tool.execution_start",
1993
+ "tool.execution_complete",
1994
+ "subagent.started",
1995
+ "subagent.completed",
1996
+ "subagent.failed",
1997
+ "assistant.message",
1998
+ "session.compaction_complete"
1999
+ ],
2000
+ agentScope: "all",
2001
+ includeEphemeral: false
2002
+ });
2003
+ this.#assertGeneration(sessionId, generation);
2004
+ if (page.cursorStatus !== "ok") {
2005
+ throw new WorkbenchRuntimeError("stale-runtime", "Thinking history changed. Refresh to read it again.");
2006
+ }
2007
+ const nodes = decisionNodes(page.events);
2008
+ return WorkbenchReasoningPageSchema.parse({
2009
+ nodes,
2010
+ blocks: nodes.filter((node) => node.kind === "rationale").map((node) => ({
2011
+ id: node.id,
2012
+ timestamp: node.timestamp,
2013
+ ...node.agentId === void 0 ? {} : { agentId: node.agentId },
2014
+ content: node.content,
2015
+ truncated: node.truncated
2016
+ })),
2017
+ cursor: page.cursor,
2018
+ hasMore: page.hasMore
2019
+ });
2020
+ }
1618
2021
  async ask(sessionId, question) {
1619
2022
  z3.string().trim().min(1).max(16 * 1024).parse(question);
1620
2023
  this.dependencies.assertAvailable(sessionId);
@@ -1668,7 +2071,7 @@ var SessionWorkbenchRuntime = class {
1668
2071
  }
1669
2072
  return {
1670
2073
  runtimeGeneration: generation,
1671
- revision: createHash4("sha256").update(JSON.stringify(pending)).digest("hex"),
2074
+ revision: createHash5("sha256").update(JSON.stringify(pending)).digest("hex"),
1672
2075
  sampledAt: (/* @__PURE__ */ new Date()).toISOString(),
1673
2076
  items: [...groups.values()],
1674
2077
  steeringMessages: pending.steeringMessages
@@ -1798,6 +2201,10 @@ var SessionWorkbenchRuntime = class {
1798
2201
  async readInsights(sessionId) {
1799
2202
  const { session, runtime, generation } = await this.#session(sessionId);
1800
2203
  const metrics = await readWorkbenchMetrics(session.rpc);
2204
+ const [telemetry, storage] = await Promise.all([
2205
+ this.dependencies.telemetry?.(sessionId),
2206
+ this.dependencies.storage?.(sessionId)
2207
+ ]);
1801
2208
  const reason = runtime.workbench.compacting ? "Context compaction is in progress" : await this.#compactionDisabledReason(sessionId, session, runtime);
1802
2209
  this.#assertGeneration(sessionId, generation);
1803
2210
  return {
@@ -1805,6 +2212,8 @@ var SessionWorkbenchRuntime = class {
1805
2212
  runtimeGeneration: generation,
1806
2213
  sampledAt: (/* @__PURE__ */ new Date()).toISOString(),
1807
2214
  compactAllowed: reason === void 0,
2215
+ ...telemetry === void 0 ? {} : { telemetry },
2216
+ ...storage === void 0 ? {} : { storage },
1808
2217
  ...reason === void 0 ? {} : { compactDisabledReason: reason }
1809
2218
  };
1810
2219
  }
@@ -1936,6 +2345,7 @@ var SessionWorkbenchRuntime = class {
1936
2345
  export {
1937
2346
  isClosedCopilotConnection,
1938
2347
  isDisposedCopilotSession,
2348
+ isClosedCopilotRuntimeHost,
1939
2349
  isSessionRestoreFailure,
1940
2350
  sessionRestoreFailure,
1941
2351
  SessionImageUploadError,
@@ -1954,6 +2364,10 @@ export {
1954
2364
  SessionRuntime,
1955
2365
  SessionRuntimeRegistry,
1956
2366
  LiveTimelineProjection,
2367
+ SessionDirectoryError,
2368
+ contained,
2369
+ sessionRootIdentity,
2370
+ SessionDirectoryLister,
1957
2371
  sanitizeGitRemoteUrl,
1958
2372
  NotGitDirectoryError,
1959
2373
  resolveGitProjectIdentity,
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  SessionOperationError
3
- } from "./chunk-7ZYBES47.js";
3
+ } from "./chunk-7OGTK7KB.js";
4
4
  import {
5
5
  SESSION_NAME_MAX_LENGTH,
6
6
  SessionNameSchema
7
- } from "./chunk-KBI5IWPR.js";
7
+ } from "./chunk-P2PH5KMV.js";
8
8
 
9
9
  // src/coding-agent-adapter.ts
10
10
  var CODING_AGENT_IDS = ["copilot", "pi", "codex", "claude", "acp"];
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  SessionCommunicationDataSchema,
3
3
  WorkbenchOperationStatusSchema
4
- } from "./chunk-KBI5IWPR.js";
4
+ } from "./chunk-P2PH5KMV.js";
5
5
 
6
6
  // src/session-operations.ts
7
7
  import { createHash, randomUUID } from "node:crypto";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SessionOperationError
3
- } from "./chunk-7ZYBES47.js";
3
+ } from "./chunk-7OGTK7KB.js";
4
4
 
5
5
  // src/adapters/copilot/runtime/session-identity.ts
6
6
  function assertMainSessionId(sessionId) {