@wrongstack/core 0.309.1 → 0.310.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/chronicle/index.js +113 -41
  2. package/dist/chronicle/metrics-ingest.d.ts +7 -0
  3. package/dist/chronicle/metrics-schema.d.ts +4 -1
  4. package/dist/chronicle/project-server.js +94 -38
  5. package/dist/chronicle/query.d.ts +1 -0
  6. package/dist/chronicle/sqlite-journal-schema.d.ts +2 -1
  7. package/dist/chronicle/types.d.ts +2 -0
  8. package/dist/{agent-status-helpers.d.ts → coordination/agent-status-helpers.d.ts} +1 -1
  9. package/dist/{agent-status-tracker.d.ts → coordination/agent-status-tracker.d.ts} +2 -2
  10. package/dist/{middleware → coordination}/collab-pause.d.ts +1 -1
  11. package/dist/coordination/director-kanban-queue-helpers.d.ts +1 -1
  12. package/dist/coordination/fleet-status-tool.d.ts +1 -1
  13. package/dist/coordination/index.d.ts +5 -1
  14. package/dist/coordination/index.js +2061 -346
  15. package/dist/coordination/kanban-dispatch-port.d.ts +30 -0
  16. package/dist/coordination/kanban-ops-port.d.ts +21 -0
  17. package/dist/coordination/mailbox-hooks.d.ts +1 -1
  18. package/dist/coordination/mailbox-project-server.js +14 -9
  19. package/dist/core/context.d.ts +35 -44
  20. package/dist/core/conversation-state.d.ts +16 -52
  21. package/dist/core/index.js +53 -16
  22. package/dist/core/provider-runner.d.ts +2 -2
  23. package/dist/core/run-env.d.ts +7 -28
  24. package/dist/core/streaming-response-builder.d.ts +2 -2
  25. package/dist/execution/index.js +111 -153
  26. package/dist/goal/index.js +100 -22
  27. package/dist/hq/auth-store.d.ts +9 -0
  28. package/dist/hq/cost-bridge.d.ts +1 -1
  29. package/dist/hq/index.js +24 -2
  30. package/dist/index.d.ts +12 -5
  31. package/dist/index.js +27806 -33937
  32. package/dist/infrastructure/index.js +210 -132
  33. package/dist/infrastructure/provider-cache-ledger.d.ts +1 -1
  34. package/dist/infrastructure/token-counter.d.ts +5 -1
  35. package/dist/kernel/events/file-events.d.ts +6 -0
  36. package/dist/kernel/events/provider-events.d.ts +10 -7
  37. package/dist/kernel/events/session-events.d.ts +4 -4
  38. package/dist/kernel/events/tool-events.d.ts +12 -2
  39. package/dist/plugin/index.js +105 -35
  40. package/dist/security/index.d.ts +1 -0
  41. package/dist/security/index.js +47 -18
  42. package/dist/security/kanban-boundary.d.ts +1 -1
  43. package/dist/security/kanban-governance-port.d.ts +28 -0
  44. package/dist/session-catalog/index.js +2 -3
  45. package/dist/session-catalog/project-server.js +2 -3
  46. package/dist/session-catalog/protocol.d.ts +1 -1
  47. package/dist/session-catalog/registry.d.ts +1 -1
  48. package/dist/session-catalog/store-schema.d.ts +1 -1
  49. package/dist/session-catalog/store.d.ts +1 -1
  50. package/dist/storage/annotations-store.d.ts +1 -1
  51. package/dist/storage/board-store-port.d.ts +45 -0
  52. package/dist/storage/completed-work-checkpoint.d.ts +1 -1
  53. package/dist/storage/config-loader/types.d.ts +1 -1
  54. package/dist/storage/event-bus-port.d.ts +27 -0
  55. package/dist/storage/file-session-writer.d.ts +47 -5
  56. package/dist/storage/goal-coordination.d.ts +1 -1
  57. package/dist/storage/goal-store.d.ts +1 -1
  58. package/dist/storage/index.d.ts +3 -4
  59. package/dist/storage/index.js +1063 -1459
  60. package/dist/storage/plan-store.d.ts +1 -1
  61. package/dist/storage/queue-store.d.ts +1 -1
  62. package/dist/storage/replay-log-store.d.ts +1 -1
  63. package/dist/storage/session-recovery.d.ts +10 -0
  64. package/dist/storage/session-resume-validation.d.ts +13 -1
  65. package/dist/storage/session-store/events.d.ts +1 -1
  66. package/dist/storage/session-store/load-session-data.d.ts +1 -1
  67. package/dist/storage/session-store/rename-session.d.ts +1 -1
  68. package/dist/storage/session-store/resume-session.d.ts +3 -1
  69. package/dist/storage/session-store/session-store-index.d.ts +2 -1
  70. package/dist/storage/session-store/types.d.ts +1 -1
  71. package/dist/storage/session-store.d.ts +70 -0
  72. package/dist/storage/session-summary-tracker.d.ts +8 -0
  73. package/dist/storage/session-write-buffer.d.ts +31 -2
  74. package/dist/storage/task-store.d.ts +1 -1
  75. package/dist/storage/todos-checkpoint.d.ts +1 -1
  76. package/dist/storage/tool-audit-log.d.ts +1 -1
  77. package/dist/tasking/index.js +100 -22
  78. package/dist/tasking/task-tracker.d.ts +24 -1
  79. package/dist/types/compactor.d.ts +2 -2
  80. package/dist/types/context.d.ts +212 -0
  81. package/dist/types/conversation-state.d.ts +109 -0
  82. package/dist/types/error-handler.d.ts +2 -2
  83. package/dist/types/file-event-record.d.ts +6 -0
  84. package/dist/types/index.d.ts +3 -3
  85. package/dist/types/index.js +17 -1
  86. package/dist/types/permission.d.ts +3 -3
  87. package/dist/types/plugin.d.ts +3 -3
  88. package/dist/types/provider-runner.d.ts +2 -2
  89. package/dist/types/provider.d.ts +10 -0
  90. package/dist/types/run-env.d.ts +32 -0
  91. package/dist/types/session.d.ts +3 -0
  92. package/dist/types/slash-command.d.ts +2 -2
  93. package/dist/types/token-counter.d.ts +30 -1
  94. package/dist/types/tool-executor.d.ts +2 -2
  95. package/dist/types/tool.d.ts +5 -5
  96. package/dist/utils/context-breakdown.d.ts +2 -2
  97. package/dist/utils/context-evidence.d.ts +12 -12
  98. package/dist/utils/crash-shield.d.ts +9 -0
  99. package/dist/utils/heap-watchdog.js +11 -3
  100. package/dist/utils/index.d.ts +1 -1
  101. package/dist/utils/index.js +72 -156
  102. package/dist/utils/regex-guard.d.ts +7 -30
  103. package/dist/utils/todos-format.d.ts +1 -1
  104. package/dist/utils/tree-kill.d.ts +2 -0
  105. package/dist/utils/tree-kill.js +1 -0
  106. package/instructions/coordination/subagent-baseline.md +10 -0
  107. package/instructions/system-lite.md +2 -0
  108. package/instructions/system-pro.md +40 -0
  109. package/instructions/system.md +15 -0
  110. package/package.json +6 -9
  111. package/dist/defaults/index.d.ts +0 -69
  112. package/dist/defaults/index.js +0 -38133
  113. /package/dist/{fleet-notifier.d.ts → coordination/fleet-notifier.d.ts} +0 -0
  114. /package/dist/{session-registry-atomic-file.d.ts → session-catalog/session-registry-atomic-file.d.ts} +0 -0
  115. /package/dist/{session-registry-types.d.ts → session-catalog/session-registry-types.d.ts} +0 -0
  116. /package/dist/{session-registry.d.ts → session-catalog/session-registry.d.ts} +0 -0
@@ -1118,6 +1118,153 @@ var DefaultPathResolver = class {
1118
1118
  }
1119
1119
  };
1120
1120
 
1121
+ // src/utils/error.ts
1122
+ function toErrorMessage(err) {
1123
+ return err instanceof Error ? err.message : String(err);
1124
+ }
1125
+
1126
+ // src/types/errors.ts
1127
+ var ERROR_CODES = {
1128
+ // Provider
1129
+ PROVIDER_RATE_LIMITED: "PROVIDER_RATE_LIMITED",
1130
+ PROVIDER_AUTH_FAILED: "PROVIDER_AUTH_FAILED",
1131
+ PROVIDER_OVERLOADED: "PROVIDER_OVERLOADED",
1132
+ PROVIDER_INVALID_REQUEST: "PROVIDER_INVALID_REQUEST",
1133
+ PROVIDER_SERVER_ERROR: "PROVIDER_SERVER_ERROR",
1134
+ PROVIDER_NETWORK_ERROR: "PROVIDER_NETWORK_ERROR",
1135
+ PROVIDER_CONTEXT_OVERFLOW: "PROVIDER_CONTEXT_OVERFLOW",
1136
+ // Tool
1137
+ TOOL_NOT_FOUND: "TOOL_NOT_FOUND",
1138
+ TOOL_PERMISSION_DENIED: "TOOL_PERMISSION_DENIED",
1139
+ TOOL_EXECUTION_FAILED: "TOOL_EXECUTION_FAILED",
1140
+ TOOL_TIMEOUT: "TOOL_TIMEOUT",
1141
+ TOOL_INPUT_INVALID: "TOOL_INPUT_INVALID",
1142
+ // Config
1143
+ CONFIG_INVALID: "CONFIG_INVALID",
1144
+ CONFIG_NOT_FOUND: "CONFIG_NOT_FOUND",
1145
+ CONFIG_PARSE_FAILED: "CONFIG_PARSE_FAILED",
1146
+ CONFIG_MIGRATION_NEEDED: "CONFIG_MIGRATION_NEEDED",
1147
+ // Plugin
1148
+ PLUGIN_LOAD_FAILED: "PLUGIN_LOAD_FAILED",
1149
+ PLUGIN_API_MISMATCH: "PLUGIN_API_MISMATCH",
1150
+ PLUGIN_MISSING_DEPENDENCY: "PLUGIN_MISSING_DEPENDENCY",
1151
+ // Agent
1152
+ AGENT_ITERATION_LIMIT: "AGENT_ITERATION_LIMIT",
1153
+ AGENT_CONTEXT_OVERFLOW: "AGENT_CONTEXT_OVERFLOW",
1154
+ AGENT_ABORTED: "AGENT_ABORTED",
1155
+ AGENT_RUN_FAILED: "AGENT_RUN_FAILED",
1156
+ // Session
1157
+ SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
1158
+ SESSION_CORRUPTED: "SESSION_CORRUPTED",
1159
+ SESSION_WRITE_FAILED: "SESSION_WRITE_FAILED",
1160
+ // Container / Registry
1161
+ CONTAINER_TOKEN_ALREADY_BOUND: "CONTAINER_TOKEN_ALREADY_BOUND",
1162
+ CONTAINER_TOKEN_NOT_BOUND: "CONTAINER_TOKEN_NOT_BOUND",
1163
+ CONTAINER_CIRCULAR_DEPENDENCY: "CONTAINER_CIRCULAR_DEPENDENCY",
1164
+ REGISTRY_DUPLICATE: "REGISTRY_DUPLICATE",
1165
+ REGISTRY_NOT_FOUND: "REGISTRY_NOT_FOUND",
1166
+ REGISTRY_INVALID: "REGISTRY_INVALID",
1167
+ // File system
1168
+ FS_READ_FAILED: "FS_READ_FAILED",
1169
+ FS_WRITE_FAILED: "FS_WRITE_FAILED",
1170
+ FS_MKDIR_FAILED: "FS_MKDIR_FAILED",
1171
+ FS_DELETE_FAILED: "FS_DELETE_FAILED",
1172
+ FS_ATOMIC_WRITE_FAILED: "FS_ATOMIC_WRITE_FAILED",
1173
+ // SDD (Spec-Driven Development)
1174
+ SDD_VALIDATION_FAILED: "SDD_VALIDATION_FAILED",
1175
+ SDD_PARSE_FAILED: "SDD_PARSE_FAILED",
1176
+ SDD_INVALID_STATE: "SDD_INVALID_STATE",
1177
+ SDD_NOT_READY: "SDD_NOT_READY",
1178
+ // General
1179
+ VALIDATION_ERROR: "VALIDATION_ERROR",
1180
+ PARSE_FAILED: "PARSE_FAILED",
1181
+ UNKNOWN: "UNKNOWN"
1182
+ };
1183
+ var WrongStackError = class extends Error {
1184
+ code;
1185
+ subsystem;
1186
+ severity;
1187
+ recoverable;
1188
+ context;
1189
+ constructor(opts) {
1190
+ super(opts.message, { cause: opts.cause });
1191
+ this.name = "WrongStackError";
1192
+ this.code = opts.code;
1193
+ this.subsystem = opts.subsystem;
1194
+ this.severity = opts.severity ?? "error";
1195
+ this.recoverable = opts.recoverable ?? false;
1196
+ this.context = opts.context;
1197
+ }
1198
+ /**
1199
+ * Render a one-line user-facing description.
1200
+ * Subclasses should override for domain-specific formatting.
1201
+ */
1202
+ describe() {
1203
+ const ctx = this.context ? ` ${formatContext(this.context)}` : "";
1204
+ return `${this.code}: ${this.message}${ctx}`;
1205
+ }
1206
+ };
1207
+ function formatContext(ctx) {
1208
+ const parts = Object.entries(ctx).filter(([, v]) => v !== void 0).slice(0, 3).map(([k, v]) => `${k}=${String(v)}`);
1209
+ return parts.length > 0 ? `[${parts.join(" ")}]` : "";
1210
+ }
1211
+ var ConfigError = class extends WrongStackError {
1212
+ constructor(opts) {
1213
+ super({
1214
+ message: opts.message,
1215
+ code: opts.code,
1216
+ subsystem: "config",
1217
+ severity: "fatal",
1218
+ recoverable: false,
1219
+ context: opts.context,
1220
+ cause: opts.cause
1221
+ });
1222
+ this.name = "ConfigError";
1223
+ }
1224
+ };
1225
+ var FsError = class extends WrongStackError {
1226
+ path;
1227
+ constructor(opts) {
1228
+ super({
1229
+ message: opts.message,
1230
+ code: opts.code,
1231
+ subsystem: "fs",
1232
+ severity: "error",
1233
+ recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,
1234
+ context: { path: opts.path, ...opts.context },
1235
+ cause: opts.cause
1236
+ });
1237
+ this.name = "FsError";
1238
+ this.path = opts.path;
1239
+ }
1240
+ };
1241
+
1242
+ // src/types/provider.ts
1243
+ function effectiveInputTokens(usage) {
1244
+ return usage.input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
1245
+ }
1246
+ function promptCacheHitRatio(usage) {
1247
+ const total = effectiveInputTokens(usage);
1248
+ if (!Number.isFinite(total) || total <= 0) return 0;
1249
+ const cached = Number.isFinite(usage.cacheRead) ? Math.max(0, usage.cacheRead ?? 0) : 0;
1250
+ return Math.min(1, cached / total);
1251
+ }
1252
+ var MAX_RESET_HINT_MS = 7 * 24 * 60 * 60 * 1e3;
1253
+ var KIND_TO_CODE = {
1254
+ network: ERROR_CODES.PROVIDER_NETWORK_ERROR,
1255
+ timeout: ERROR_CODES.PROVIDER_NETWORK_ERROR,
1256
+ rate_limit: ERROR_CODES.PROVIDER_RATE_LIMITED,
1257
+ quota_exhausted: ERROR_CODES.PROVIDER_RATE_LIMITED,
1258
+ auth: ERROR_CODES.PROVIDER_AUTH_FAILED,
1259
+ overloaded: ERROR_CODES.PROVIDER_OVERLOADED,
1260
+ context_overflow: ERROR_CODES.PROVIDER_CONTEXT_OVERFLOW,
1261
+ server: ERROR_CODES.PROVIDER_SERVER_ERROR,
1262
+ stream_hang: ERROR_CODES.PROVIDER_SERVER_ERROR,
1263
+ content_filter: ERROR_CODES.PROVIDER_INVALID_REQUEST,
1264
+ invalid_request: ERROR_CODES.PROVIDER_INVALID_REQUEST,
1265
+ unknown: ERROR_CODES.PROVIDER_INVALID_REQUEST
1266
+ };
1267
+
1121
1268
  // src/infrastructure/token-counter.ts
1122
1269
  var PRICE_CACHE_MAX_SIZE = 100;
1123
1270
  var DefaultTokenCounter = class {
@@ -1125,9 +1272,12 @@ var DefaultTokenCounter = class {
1125
1272
  output = 0;
1126
1273
  cacheRead = 0;
1127
1274
  cacheWrite = 0;
1275
+ cacheWrite5m = 0;
1276
+ cacheWrite1h = 0;
1128
1277
  costInput = 0;
1129
1278
  costOutput = 0;
1130
1279
  cacheSaved = 0;
1280
+ cacheByProvider = /* @__PURE__ */ new Map();
1131
1281
  registry;
1132
1282
  providerId;
1133
1283
  events;
@@ -1151,10 +1301,15 @@ var DefaultTokenCounter = class {
1151
1301
  this.input += usage.input;
1152
1302
  this.output += usage.output;
1153
1303
  this.cacheRead += usage.cacheRead ?? 0;
1154
- this.cacheWrite += usage.cacheWrite ?? 0;
1304
+ const ttlAggregate = usage.cacheWrite5m !== void 0 || usage.cacheWrite1h !== void 0 ? (usage.cacheWrite5m ?? 0) + (usage.cacheWrite1h ?? 0) : 0;
1305
+ const cacheWriteTotal = usage.cacheWrite ?? ttlAggregate;
1306
+ this.cacheWrite += cacheWriteTotal;
1307
+ this.cacheWrite5m += usage.cacheWrite5m ?? 0;
1308
+ this.cacheWrite1h += usage.cacheWrite1h ?? 0;
1309
+ this.recordProviderCache(usage, providerId, cacheWriteTotal);
1155
1310
  this.lastInput = usage.input;
1156
1311
  this.lastCacheRead = usage.cacheRead ?? 0;
1157
- this.lastCacheWrite = usage.cacheWrite ?? 0;
1312
+ this.lastCacheWrite = cacheWriteTotal;
1158
1313
  const priceKey = providerId && model ? `${providerId}\0${model}` : void 0;
1159
1314
  const price = priceKey ? this.priceCache.get(priceKey) : void 0;
1160
1315
  if (price) {
@@ -1192,10 +1347,15 @@ var DefaultTokenCounter = class {
1192
1347
  this.input += usage.input;
1193
1348
  this.output += usage.output;
1194
1349
  this.cacheRead += usage.cacheRead ?? 0;
1195
- this.cacheWrite += usage.cacheWrite ?? 0;
1350
+ const ttlAggregate = usage.cacheWrite5m !== void 0 || usage.cacheWrite1h !== void 0 ? (usage.cacheWrite5m ?? 0) + (usage.cacheWrite1h ?? 0) : 0;
1351
+ const cacheWriteTotal = usage.cacheWrite ?? ttlAggregate;
1352
+ this.cacheWrite += cacheWriteTotal;
1353
+ this.cacheWrite5m += usage.cacheWrite5m ?? 0;
1354
+ this.cacheWrite1h += usage.cacheWrite1h ?? 0;
1355
+ this.recordProviderCache(usage, resolved.providerId, cacheWriteTotal);
1196
1356
  this.lastInput = usage.input;
1197
1357
  this.lastCacheRead = usage.cacheRead ?? 0;
1198
- this.lastCacheWrite = usage.cacheWrite ?? 0;
1358
+ this.lastCacheWrite = cacheWriteTotal;
1199
1359
  const price = priceFromModel(resolved);
1200
1360
  if (this.priceCache.size >= PRICE_CACHE_MAX_SIZE) {
1201
1361
  const keys = [...this.priceCache.keys()];
@@ -1214,7 +1374,11 @@ var DefaultTokenCounter = class {
1214
1374
  };
1215
1375
  }
1216
1376
  currentRequestTokens() {
1217
- return { input: this.lastInput, cacheRead: this.lastCacheRead, cacheWrite: this.lastCacheWrite };
1377
+ return {
1378
+ input: this.lastInput,
1379
+ cacheRead: this.lastCacheRead,
1380
+ cacheWrite: this.lastCacheWrite
1381
+ };
1218
1382
  }
1219
1383
  setCurrentRequestTokens(input, cacheRead, cacheWrite) {
1220
1384
  this.lastInput = input;
@@ -1230,12 +1394,26 @@ var DefaultTokenCounter = class {
1230
1394
  };
1231
1395
  }
1232
1396
  cacheStats() {
1233
- const denom = this.cacheRead + this.input;
1397
+ const exposeTtlSplit = this.cacheWrite5m > 0 || this.cacheWrite1h > 0;
1234
1398
  return {
1235
1399
  readTokens: this.cacheRead,
1236
1400
  writeTokens: this.cacheWrite,
1237
- hitRatio: denom === 0 ? 0 : this.cacheRead / denom,
1238
- savedUsd: round4(this.cacheSaved)
1401
+ ...exposeTtlSplit ? { cacheWrite5m: this.cacheWrite5m, cacheWrite1h: this.cacheWrite1h } : {},
1402
+ hitRatio: promptCacheHitRatio({
1403
+ input: this.input,
1404
+ output: this.output,
1405
+ cacheRead: this.cacheRead,
1406
+ cacheWrite: this.cacheWrite
1407
+ }),
1408
+ savedUsd: round4(this.cacheSaved),
1409
+ providers: [...this.cacheByProvider.entries()].map(([provider, usage]) => ({
1410
+ provider,
1411
+ input: usage.input,
1412
+ cacheRead: usage.cacheRead,
1413
+ cacheWrite: usage.cacheWrite,
1414
+ ...usage.cacheWrite5m > 0 || usage.cacheWrite1h > 0 ? { cacheWrite5m: usage.cacheWrite5m, cacheWrite1h: usage.cacheWrite1h } : {},
1415
+ hitRatio: promptCacheHitRatio({ ...usage, output: 0 })
1416
+ })).sort((a, b) => b.cacheRead - a.cacheRead)
1239
1417
  };
1240
1418
  }
1241
1419
  /** Invalidate cached prices so the next account() call fetches fresh data. */
@@ -1247,7 +1425,11 @@ var DefaultTokenCounter = class {
1247
1425
  ...sessionId ? { sessionId } : {},
1248
1426
  usage: this.total(),
1249
1427
  ...deltaUsage ? { deltaUsage: { ...deltaUsage } } : {},
1250
- cost: { input: this.costInput, output: this.costOutput, total: this.costInput + this.costOutput },
1428
+ cost: {
1429
+ input: this.costInput,
1430
+ output: this.costOutput,
1431
+ total: this.costInput + this.costOutput
1432
+ },
1251
1433
  ...providerId ? { provider: providerId } : {},
1252
1434
  ...model ? { model } : {}
1253
1435
  });
@@ -1265,9 +1447,12 @@ var DefaultTokenCounter = class {
1265
1447
  this.output = 0;
1266
1448
  this.cacheRead = 0;
1267
1449
  this.cacheWrite = 0;
1450
+ this.cacheWrite5m = 0;
1451
+ this.cacheWrite1h = 0;
1268
1452
  this.costInput = 0;
1269
1453
  this.costOutput = 0;
1270
1454
  this.cacheSaved = 0;
1455
+ this.cacheByProvider.clear();
1271
1456
  this.lastInput = 0;
1272
1457
  this.lastCacheRead = 0;
1273
1458
  this.lastCacheWrite = 0;
@@ -1278,6 +1463,16 @@ var DefaultTokenCounter = class {
1278
1463
  cacheWrite: 0
1279
1464
  });
1280
1465
  }
1466
+ recordProviderCache(usage, providerId, derivedCacheWrite) {
1467
+ const key = providerId ?? "unknown";
1468
+ const current = this.cacheByProvider.get(key) ?? { input: 0, cacheRead: 0, cacheWrite: 0, cacheWrite5m: 0, cacheWrite1h: 0 };
1469
+ current.input += usage.input;
1470
+ current.cacheRead += usage.cacheRead ?? 0;
1471
+ current.cacheWrite += derivedCacheWrite;
1472
+ current.cacheWrite5m += usage.cacheWrite5m ?? 0;
1473
+ current.cacheWrite1h += usage.cacheWrite1h ?? 0;
1474
+ this.cacheByProvider.set(key, current);
1475
+ }
1281
1476
  applyPrice(usage, price) {
1282
1477
  if (price.input) this.costInput += usage.input / 1e6 * price.input;
1283
1478
  if (price.output) this.costOutput += usage.output / 1e6 * price.output;
@@ -1356,13 +1551,17 @@ var ProviderCacheLedger = class {
1356
1551
  perProvider() {
1357
1552
  const out = [];
1358
1553
  for (const [provider, a] of this.byProvider) {
1359
- const denom = a.cacheRead + a.input;
1360
1554
  out.push({
1361
1555
  provider,
1362
1556
  input: a.input,
1363
1557
  cacheRead: a.cacheRead,
1364
1558
  cacheWrite: a.cacheWrite,
1365
- hitRatio: denom === 0 ? 0 : a.cacheRead / denom
1559
+ hitRatio: promptCacheHitRatio({
1560
+ input: a.input,
1561
+ output: 0,
1562
+ cacheRead: a.cacheRead,
1563
+ cacheWrite: a.cacheWrite
1564
+ })
1366
1565
  });
1367
1566
  }
1368
1567
  return out.sort((x, y) => y.cacheRead - x.cacheRead);
@@ -2202,127 +2401,6 @@ import * as fs2 from "node:fs";
2202
2401
  import * as fsp2 from "node:fs/promises";
2203
2402
  import * as path3 from "node:path";
2204
2403
 
2205
- // src/utils/error.ts
2206
- function toErrorMessage(err) {
2207
- return err instanceof Error ? err.message : String(err);
2208
- }
2209
-
2210
- // src/types/errors.ts
2211
- var ERROR_CODES = {
2212
- // Provider
2213
- PROVIDER_RATE_LIMITED: "PROVIDER_RATE_LIMITED",
2214
- PROVIDER_AUTH_FAILED: "PROVIDER_AUTH_FAILED",
2215
- PROVIDER_OVERLOADED: "PROVIDER_OVERLOADED",
2216
- PROVIDER_INVALID_REQUEST: "PROVIDER_INVALID_REQUEST",
2217
- PROVIDER_SERVER_ERROR: "PROVIDER_SERVER_ERROR",
2218
- PROVIDER_NETWORK_ERROR: "PROVIDER_NETWORK_ERROR",
2219
- PROVIDER_CONTEXT_OVERFLOW: "PROVIDER_CONTEXT_OVERFLOW",
2220
- // Tool
2221
- TOOL_NOT_FOUND: "TOOL_NOT_FOUND",
2222
- TOOL_PERMISSION_DENIED: "TOOL_PERMISSION_DENIED",
2223
- TOOL_EXECUTION_FAILED: "TOOL_EXECUTION_FAILED",
2224
- TOOL_TIMEOUT: "TOOL_TIMEOUT",
2225
- TOOL_INPUT_INVALID: "TOOL_INPUT_INVALID",
2226
- // Config
2227
- CONFIG_INVALID: "CONFIG_INVALID",
2228
- CONFIG_NOT_FOUND: "CONFIG_NOT_FOUND",
2229
- CONFIG_PARSE_FAILED: "CONFIG_PARSE_FAILED",
2230
- CONFIG_MIGRATION_NEEDED: "CONFIG_MIGRATION_NEEDED",
2231
- // Plugin
2232
- PLUGIN_LOAD_FAILED: "PLUGIN_LOAD_FAILED",
2233
- PLUGIN_API_MISMATCH: "PLUGIN_API_MISMATCH",
2234
- PLUGIN_MISSING_DEPENDENCY: "PLUGIN_MISSING_DEPENDENCY",
2235
- // Agent
2236
- AGENT_ITERATION_LIMIT: "AGENT_ITERATION_LIMIT",
2237
- AGENT_CONTEXT_OVERFLOW: "AGENT_CONTEXT_OVERFLOW",
2238
- AGENT_ABORTED: "AGENT_ABORTED",
2239
- AGENT_RUN_FAILED: "AGENT_RUN_FAILED",
2240
- // Session
2241
- SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
2242
- SESSION_CORRUPTED: "SESSION_CORRUPTED",
2243
- SESSION_WRITE_FAILED: "SESSION_WRITE_FAILED",
2244
- // Container / Registry
2245
- CONTAINER_TOKEN_ALREADY_BOUND: "CONTAINER_TOKEN_ALREADY_BOUND",
2246
- CONTAINER_TOKEN_NOT_BOUND: "CONTAINER_TOKEN_NOT_BOUND",
2247
- CONTAINER_CIRCULAR_DEPENDENCY: "CONTAINER_CIRCULAR_DEPENDENCY",
2248
- REGISTRY_DUPLICATE: "REGISTRY_DUPLICATE",
2249
- REGISTRY_NOT_FOUND: "REGISTRY_NOT_FOUND",
2250
- REGISTRY_INVALID: "REGISTRY_INVALID",
2251
- // File system
2252
- FS_READ_FAILED: "FS_READ_FAILED",
2253
- FS_WRITE_FAILED: "FS_WRITE_FAILED",
2254
- FS_MKDIR_FAILED: "FS_MKDIR_FAILED",
2255
- FS_DELETE_FAILED: "FS_DELETE_FAILED",
2256
- FS_ATOMIC_WRITE_FAILED: "FS_ATOMIC_WRITE_FAILED",
2257
- // SDD (Spec-Driven Development)
2258
- SDD_VALIDATION_FAILED: "SDD_VALIDATION_FAILED",
2259
- SDD_PARSE_FAILED: "SDD_PARSE_FAILED",
2260
- SDD_INVALID_STATE: "SDD_INVALID_STATE",
2261
- SDD_NOT_READY: "SDD_NOT_READY",
2262
- // General
2263
- VALIDATION_ERROR: "VALIDATION_ERROR",
2264
- PARSE_FAILED: "PARSE_FAILED",
2265
- UNKNOWN: "UNKNOWN"
2266
- };
2267
- var WrongStackError = class extends Error {
2268
- code;
2269
- subsystem;
2270
- severity;
2271
- recoverable;
2272
- context;
2273
- constructor(opts) {
2274
- super(opts.message, { cause: opts.cause });
2275
- this.name = "WrongStackError";
2276
- this.code = opts.code;
2277
- this.subsystem = opts.subsystem;
2278
- this.severity = opts.severity ?? "error";
2279
- this.recoverable = opts.recoverable ?? false;
2280
- this.context = opts.context;
2281
- }
2282
- /**
2283
- * Render a one-line user-facing description.
2284
- * Subclasses should override for domain-specific formatting.
2285
- */
2286
- describe() {
2287
- const ctx = this.context ? ` ${formatContext(this.context)}` : "";
2288
- return `${this.code}: ${this.message}${ctx}`;
2289
- }
2290
- };
2291
- function formatContext(ctx) {
2292
- const parts = Object.entries(ctx).filter(([, v]) => v !== void 0).slice(0, 3).map(([k, v]) => `${k}=${String(v)}`);
2293
- return parts.length > 0 ? `[${parts.join(" ")}]` : "";
2294
- }
2295
- var ConfigError = class extends WrongStackError {
2296
- constructor(opts) {
2297
- super({
2298
- message: opts.message,
2299
- code: opts.code,
2300
- subsystem: "config",
2301
- severity: "fatal",
2302
- recoverable: false,
2303
- context: opts.context,
2304
- cause: opts.cause
2305
- });
2306
- this.name = "ConfigError";
2307
- }
2308
- };
2309
- var FsError = class extends WrongStackError {
2310
- path;
2311
- constructor(opts) {
2312
- super({
2313
- message: opts.message,
2314
- code: opts.code,
2315
- subsystem: "fs",
2316
- severity: "error",
2317
- recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,
2318
- context: { path: opts.path, ...opts.context },
2319
- cause: opts.cause
2320
- });
2321
- this.name = "FsError";
2322
- this.path = opts.path;
2323
- }
2324
- };
2325
-
2326
2404
  // src/types/secret-vault.ts
2327
2405
  var ENCRYPTED_PREFIX_PATTERN = /^enc:v(\d+):/;
2328
2406
  function encryptedPrefixForVersion(version) {
@@ -4,7 +4,7 @@ export interface ProviderCacheEntry {
4
4
  input: number;
5
5
  cacheRead: number;
6
6
  cacheWrite: number;
7
- /** cacheRead / (cacheRead + input); 0 when nothing cached. */
7
+ /** cacheRead / total prompt context; clamped to [0, 1]. */
8
8
  hitRatio: number;
9
9
  }
10
10
  /**
@@ -1,6 +1,6 @@
1
1
  import type { EventBus } from '../kernel/events.js';
2
2
  import type { ModelsRegistry, ResolvedModel } from '../types/models-registry.js';
3
- import type { Usage } from '../types/provider.js';
3
+ import { type Usage } from '../types/provider.js';
4
4
  import type { CacheStats, TokenCounter } from '../types/token-counter.js';
5
5
  /**
6
6
  * Token counter that derives pricing from the ModelsRegistry instead of a
@@ -12,9 +12,12 @@ export declare class DefaultTokenCounter implements TokenCounter {
12
12
  private output;
13
13
  private cacheRead;
14
14
  private cacheWrite;
15
+ private cacheWrite5m;
16
+ private cacheWrite1h;
15
17
  private costInput;
16
18
  private costOutput;
17
19
  private cacheSaved;
20
+ private readonly cacheByProvider;
18
21
  private readonly registry?;
19
22
  private readonly providerId?;
20
23
  private readonly events?;
@@ -54,6 +57,7 @@ export declare class DefaultTokenCounter implements TokenCounter {
54
57
  private currentSessionId;
55
58
  private currentProviderId;
56
59
  reset(): void;
60
+ private recordProviderCache;
57
61
  private applyPrice;
58
62
  }
59
63
  //# sourceMappingURL=token-counter.d.ts.map
@@ -38,6 +38,12 @@ export interface FileEventMap {
38
38
  provider: string;
39
39
  /** LLM model id */
40
40
  model: string;
41
+ /** Logical provider request that produced the mutating tool call. */
42
+ logicalRequestId?: string | undefined;
43
+ /** Content-addressed provider-visible prompt identity. */
44
+ promptManifestId?: string | undefined;
45
+ /** Strength of the prompt-to-file attribution edge. */
46
+ provenanceConfidence?: 'explicit' | 'correlated' | 'inferred' | 'unknown' | undefined;
41
47
  /** Tool name */
42
48
  toolName: string;
43
49
  /** Tool-use block correlation ID */
@@ -1,6 +1,6 @@
1
1
  import type { ChroniclePromptManifest } from '../../chronicle/prompt-manifest.js';
2
- import type { Context } from '../../core/context.js';
3
2
  import type { ContentBlock } from '../../types/blocks.js';
3
+ import type { AgentContext } from '../../types/context.js';
4
4
  import type { ProviderErrorBody, Usage } from '../../types/provider.js';
5
5
  export interface ProviderEventMap {
6
6
  /** Fired before every physical provider/model attempt, including attempt zero. */
@@ -9,6 +9,7 @@ export interface ProviderEventMap {
9
9
  traceId?: string | undefined;
10
10
  agentId?: string | undefined;
11
11
  logicalRequestId: string;
12
+ promptManifestId?: string | undefined;
12
13
  attemptId: string;
13
14
  attempt: number;
14
15
  providerId: string;
@@ -29,6 +30,7 @@ export interface ProviderEventMap {
29
30
  traceId?: string | undefined;
30
31
  agentId?: string | undefined;
31
32
  logicalRequestId: string;
33
+ promptManifestId?: string | undefined;
32
34
  attemptId: string;
33
35
  attempt: number;
34
36
  providerId: string;
@@ -49,6 +51,7 @@ export interface ProviderEventMap {
49
51
  traceId?: string | undefined;
50
52
  agentId?: string | undefined;
51
53
  logicalRequestId: string;
54
+ promptManifestId?: string | undefined;
52
55
  attemptId: string;
53
56
  attempt: number;
54
57
  providerId: string;
@@ -72,7 +75,7 @@ export interface ProviderEventMap {
72
75
  };
73
76
  'provider.response': {
74
77
  sessionId?: string | undefined;
75
- ctx: Context;
78
+ ctx: AgentContext;
76
79
  model: string;
77
80
  content?: ContentBlock[] | undefined;
78
81
  usage: Usage;
@@ -80,23 +83,23 @@ export interface ProviderEventMap {
80
83
  };
81
84
  'provider.text_delta': {
82
85
  sessionId?: string | undefined;
83
- ctx: Context;
86
+ ctx: AgentContext;
84
87
  text: string;
85
88
  };
86
89
  'provider.thinking_delta': {
87
90
  sessionId?: string | undefined;
88
- ctx: Context;
91
+ ctx: AgentContext;
89
92
  text: string;
90
93
  };
91
94
  'provider.tool_use_start': {
92
95
  sessionId?: string | undefined;
93
- ctx: Context;
96
+ ctx: AgentContext;
94
97
  id: string;
95
98
  name: string;
96
99
  };
97
100
  'provider.tool_use_stop': {
98
101
  sessionId?: string | undefined;
99
- ctx: Context;
102
+ ctx: AgentContext;
100
103
  id: string;
101
104
  name: string;
102
105
  };
@@ -108,7 +111,7 @@ export interface ProviderEventMap {
108
111
  */
109
112
  'provider.stream_error': {
110
113
  sessionId?: string | undefined;
111
- ctx: Context;
114
+ ctx: AgentContext;
112
115
  eventType: string;
113
116
  msg: string;
114
117
  };
@@ -1,4 +1,4 @@
1
- import type { Context } from '../../core/context.js';
1
+ import type { AgentContext } from '../../types/context.js';
2
2
  import type { Usage } from '../../types/provider.js';
3
3
  import type { WorkspaceCheckpointRef } from '../../types/session.js';
4
4
  import type { TrackedAgentSnapshot } from '../events.js';
@@ -35,12 +35,12 @@ export interface SessionEventMap {
35
35
  };
36
36
  'iteration.started': {
37
37
  sessionId?: string | undefined;
38
- ctx: Context;
38
+ ctx: AgentContext;
39
39
  index: number;
40
40
  };
41
41
  'iteration.completed': {
42
42
  sessionId?: string | undefined;
43
- ctx: Context;
43
+ ctx: AgentContext;
44
44
  index: number;
45
45
  };
46
46
  /**
@@ -88,7 +88,7 @@ export interface SessionEventMap {
88
88
  };
89
89
  'context.repaired': {
90
90
  sessionId?: string | undefined;
91
- ctx: Context;
91
+ ctx: AgentContext;
92
92
  changed: boolean;
93
93
  removedToolUses: string[];
94
94
  removedToolResults: string[];
@@ -1,4 +1,4 @@
1
- import type { Context } from '../../core/context.js';
1
+ import type { AgentContext } from '../../types/context.js';
2
2
  import type { ToolOutputMetadata } from '../../types/context-evidence.js';
3
3
  import type { PermissionDecision } from '../../types/permission.js';
4
4
  import type { RiskTier, Tool, ToolErrorCategory, ToolProgressEvent } from '../../types/tool.js';
@@ -6,6 +6,8 @@ export interface ToolEventMap {
6
6
  'tool.started': {
7
7
  sessionId?: string | undefined;
8
8
  traceId?: string | undefined;
9
+ logicalRequestId?: string | undefined;
10
+ promptManifestId?: string | undefined;
9
11
  agentId?: string | undefined;
10
12
  agentName?: string | undefined;
11
13
  name: string;
@@ -29,6 +31,8 @@ export interface ToolEventMap {
29
31
  id: string;
30
32
  sessionId: string;
31
33
  traceId?: string | undefined;
34
+ logicalRequestId?: string | undefined;
35
+ promptManifestId?: string | undefined;
32
36
  agentId: string;
33
37
  durationMs: number;
34
38
  outputChars: number;
@@ -41,6 +45,8 @@ export interface ToolEventMap {
41
45
  id: string;
42
46
  sessionId: string;
43
47
  traceId?: string | undefined;
48
+ logicalRequestId?: string | undefined;
49
+ promptManifestId?: string | undefined;
44
50
  agentId: string;
45
51
  durationMs: number;
46
52
  category: ToolErrorCategory;
@@ -82,6 +88,8 @@ export interface ToolEventMap {
82
88
  'permission.evaluated': {
83
89
  sessionId?: string | undefined;
84
90
  traceId?: string | undefined;
91
+ logicalRequestId?: string | undefined;
92
+ promptManifestId?: string | undefined;
85
93
  agentId?: string | undefined;
86
94
  name: string;
87
95
  id: string;
@@ -147,7 +155,7 @@ export interface ToolEventMap {
147
155
  */
148
156
  'tool.loop_detected': {
149
157
  sessionId?: string | undefined;
150
- ctx: Context;
158
+ ctx: AgentContext;
151
159
  /** Comma-separated tool names involved in the loop, or empty string for pure message loops. */
152
160
  tools: string;
153
161
  /** Number of repeats detected (consecutive iterations, or identical calls within the window for `scope: 'call'`). */
@@ -184,6 +192,8 @@ export interface ToolEventMap {
184
192
  'tool.executed': {
185
193
  sessionId?: string | undefined;
186
194
  traceId?: string | undefined;
195
+ logicalRequestId?: string | undefined;
196
+ promptManifestId?: string | undefined;
187
197
  agentId?: string | undefined;
188
198
  agentName?: string | undefined;
189
199
  /**