sneakoscope 7.3.0 → 7.6.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 (283) hide show
  1. package/README.md +129 -10
  2. package/crates/sks-core/Cargo.lock +1 -1
  3. package/crates/sks-core/Cargo.toml +1 -1
  4. package/dist/cli/codex-app-command.js +1 -1
  5. package/dist/cli/command-manifest-lite.js +4 -1
  6. package/dist/cli/command-registry.js +2 -0
  7. package/dist/cli/install-helpers-codex-lb-chain.js +42 -0
  8. package/dist/cli/install-helpers-codex-lb-config.js +114 -9
  9. package/dist/cli/install-helpers-install-support.js +6 -16
  10. package/dist/cli/install-helpers.js +788 -600
  11. package/dist/cli/router.js +30 -2
  12. package/dist/commands/codex-app.js +37 -1
  13. package/dist/commands/codex-lb.js +491 -300
  14. package/dist/config/skills-manifest.json +57 -71
  15. package/dist/core/align/align-route.js +127 -0
  16. package/dist/core/codex-app/codex-app-fast-ui-repair.js +8 -4
  17. package/dist/core/codex-app/codex-app-restart.js +83 -0
  18. package/dist/core/codex-app/codex-app-ui-state-snapshot.js +8 -4
  19. package/dist/core/codex-app/desktop-routing-snapshot.js +1 -1
  20. package/dist/core/codex-app/menubar/constants.js +5 -0
  21. package/dist/core/codex-app/menubar/generation-transaction-journal.js +1 -3
  22. package/dist/core/codex-app/menubar/installer.js +18 -0
  23. package/dist/core/codex-app/multi-provider-router.js +22 -10
  24. package/dist/core/codex-app/openrouter-activate.js +26 -1
  25. package/dist/core/codex-app.js +118 -26
  26. package/dist/core/codex-control/codex-app-server-runtime-env.js +86 -0
  27. package/dist/core/codex-control/codex-app-server-v2-client.js +78 -8
  28. package/dist/core/codex-control/codex-task-runner.js +2 -2
  29. package/dist/core/codex-lb/capability-runner.js +204 -0
  30. package/dist/core/codex-lb/capability-types.js +1 -0
  31. package/dist/core/codex-lb/codex-lb-env.js +9 -13
  32. package/dist/core/codex-lb/codex-lb-setup.js +45 -8
  33. package/dist/core/codex-lb/codex-lb-tool-catalog.js +52 -74
  34. package/dist/core/codex-lb/codex-lb-tool-output-recovery.js +1 -1
  35. package/dist/core/codex-lb/desktop-auth-invariant.js +185 -0
  36. package/dist/core/codex-lb/desktop-bridge/client.js +34 -0
  37. package/dist/core/codex-lb/desktop-bridge/header-policy.js +106 -0
  38. package/dist/core/codex-lb/desktop-bridge/http-forward.js +101 -0
  39. package/dist/core/codex-lb/desktop-bridge/index.js +10 -0
  40. package/dist/core/codex-lb/desktop-bridge/launchd.js +81 -0
  41. package/dist/core/codex-lb/desktop-bridge/location-rewrite.js +27 -0
  42. package/dist/core/codex-lb/desktop-bridge/security.js +274 -0
  43. package/dist/core/codex-lb/desktop-bridge/server.js +179 -0
  44. package/dist/core/codex-lb/desktop-bridge/state.js +119 -0
  45. package/dist/core/codex-lb/desktop-bridge/types.js +16 -0
  46. package/dist/core/codex-lb/desktop-bridge/websocket-forward.js +151 -0
  47. package/dist/core/codex-lb/desktop-center-credentials.js +189 -0
  48. package/dist/core/codex-lb/desktop-controller.js +1410 -0
  49. package/dist/core/codex-lb/desktop-mode.js +32 -0
  50. package/dist/core/codex-lb/desktop-real-evidence.js +168 -0
  51. package/dist/core/codex-lb/desktop-service.js +613 -0
  52. package/dist/core/codex-lb/legacy-migration.js +575 -0
  53. package/dist/core/codex-lb/migration-receipt.js +246 -0
  54. package/dist/core/codex-lb/probes/auxiliary-surfaces-probe.js +60 -0
  55. package/dist/core/codex-lb/probes/bridge-probe.js +75 -0
  56. package/dist/core/codex-lb/probes/catalog-probe.js +128 -0
  57. package/dist/core/codex-lb/probes/computer-use-probe.js +50 -0
  58. package/dist/core/codex-lb/probes/image-generation-probe.js +47 -0
  59. package/dist/core/codex-lb/probes/probe-evidence.js +39 -0
  60. package/dist/core/codex-lb/probes/voice-realtime-probe.js +44 -0
  61. package/dist/core/codex-lb/trusted-deep-evidence.js +403 -0
  62. package/dist/core/codex-native/core-skill-manifest.js +22 -6
  63. package/dist/core/codex-runtime/codex-desktop-config-policy.js +2 -1
  64. package/dist/core/commands/align-command.js +220 -0
  65. package/dist/core/commands/image-ux-review-command.js +280 -68
  66. package/dist/core/commands/naruto-command.js +257 -8
  67. package/dist/core/commands/ppt-command.js +2 -2
  68. package/dist/core/commands/telegram-command.js +402 -34
  69. package/dist/core/commands/triwiki-command.js +11 -1
  70. package/dist/core/commands/triwiki-graph-command.js +160 -0
  71. package/dist/core/commands/wiki-command.js +100 -20
  72. package/dist/core/doctor/skill-legacy-surface.js +1 -3
  73. package/dist/core/errors/message.js +3 -0
  74. package/dist/core/evidence/evidence-freshness.js +14 -0
  75. package/dist/core/feature-fixtures.js +9 -1
  76. package/dist/core/feature-registry.js +5 -3
  77. package/dist/core/fsx.js +7 -3
  78. package/dist/core/hooks-runtime/codex-commit-hooks-selftest.js +82 -0
  79. package/dist/core/hooks-runtime/context-graph-freshness-preflight.js +113 -0
  80. package/dist/core/hooks-runtime/hook-context.js +15 -2
  81. package/dist/core/hooks-runtime/managed-skill-generation-heal.js +46 -0
  82. package/dist/core/hooks-runtime/naruto-terminal-finalization.js +1 -0
  83. package/dist/core/hooks-runtime/official-subagent-lifecycle.js +1 -1
  84. package/dist/core/hooks-runtime/tool-output-quarantine.js +1 -1
  85. package/dist/core/hooks-runtime.js +33 -89
  86. package/dist/core/image-ux-review/callout-extraction.js +6 -0
  87. package/dist/core/image-ux-review/imagegen-adapter.js +64 -23
  88. package/dist/core/image-ux-review/real-callout-extractor.js +1 -0
  89. package/dist/core/image-ux-review.js +230 -12
  90. package/dist/core/imagegen/codex-lb-imagegen-target.js +21 -7
  91. package/dist/core/imagegen/imagegen-capability.js +10 -4
  92. package/dist/core/imagegen/require-imagegen.js +29 -5
  93. package/dist/core/init/skills.js +25 -13
  94. package/dist/core/init.js +1 -1
  95. package/dist/core/install/installed-package-smoke.js +157 -4
  96. package/dist/core/managed-assets/managed-assets-manifest.js +2 -1
  97. package/dist/core/managed-path-safety.js +8 -10
  98. package/dist/core/mcp-config/backup.js +2 -4
  99. package/dist/core/mcp-config/config-reader.js +2 -4
  100. package/dist/core/mcp-config/scope.js +3 -5
  101. package/dist/core/naruto/context-graph-advisor-scope.js +242 -0
  102. package/dist/core/naruto/context-graph-advisor.js +0 -0
  103. package/dist/core/perf/release-latency-slo.js +12 -6
  104. package/dist/core/pipeline-internals/runtime-core.js +78 -0
  105. package/dist/core/pipeline-internals/runtime-gates.js +5 -2
  106. package/dist/core/policy/latest-version-guidance.js +113 -0
  107. package/dist/core/ppt.js +8 -8
  108. package/dist/core/preflight/parallel-preflight-engine.js +1 -1
  109. package/dist/core/proof/auto-finalize.js +98 -6
  110. package/dist/core/proof/route-proof-gate.js +12 -1
  111. package/dist/core/proof/route-proof-policy.js +8 -8
  112. package/dist/core/release/gate-manifest.js +32 -1
  113. package/dist/core/release/npm-stage-contract.js +21 -0
  114. package/dist/core/release/package-size-budget.js +2 -2
  115. package/dist/core/release/release-gate-contract.js +5 -0
  116. package/dist/core/release/release-proof-io.js +1 -3
  117. package/dist/core/release/release-real-contract.js +5 -4
  118. package/dist/core/release/release-stamp-proof.js +1 -3
  119. package/dist/core/release/stage-publish.js +27 -0
  120. package/dist/core/remote/audit-idempotency.js +50 -18
  121. package/dist/core/remote/codex-public-activity.js +283 -0
  122. package/dist/core/remote/index.js +1 -0
  123. package/dist/core/remote/ssh-worker-client.js +4 -1
  124. package/dist/core/remote/worker.js +206 -27
  125. package/dist/core/research/research-adversarial-review.js +1 -3
  126. package/dist/core/research/research-claim-synthesizer.js +1 -3
  127. package/dist/core/research/research-falsification-runner.js +1 -3
  128. package/dist/core/research/research-source-evidence.js +1 -3
  129. package/dist/core/responses-stream.js +65 -19
  130. package/dist/core/routes/constants.js +1 -1
  131. package/dist/core/routes/design-policy.js +7 -2
  132. package/dist/core/routes/dollar-manifest-lite.js +2 -4
  133. package/dist/core/routes/evidence.js +1 -1
  134. package/dist/core/routes.js +30 -10
  135. package/dist/core/safety/command-contract/contracts.js +2 -0
  136. package/dist/core/safety/command-contract/types.js +1 -1
  137. package/dist/core/search/context-graph-seeds.js +205 -0
  138. package/dist/core/search/context.js +0 -0
  139. package/dist/core/search/provider.js +2 -2
  140. package/dist/core/secret-redaction.js +6 -0
  141. package/dist/core/subagents/naruto-help-contract.js +2 -1
  142. package/dist/core/subagents/naruto-host-credentials.js +161 -0
  143. package/dist/core/subagents/official-subagent-preparation.js +4 -1
  144. package/dist/core/subagents/official-subagent-prompt.js +44 -2
  145. package/dist/core/subagents/official-subagent-runner.js +26 -8
  146. package/dist/core/subagents/triwiki-attention.js +135 -123
  147. package/dist/core/telegram/bot-api.js +85 -10
  148. package/dist/core/telegram/center-snapshot.js +718 -0
  149. package/dist/core/telegram/config.js +158 -31
  150. package/dist/core/telegram/hub.js +288 -33
  151. package/dist/core/telegram/index.js +2 -0
  152. package/dist/core/telegram/ingress-spool.js +419 -0
  153. package/dist/core/telegram/ledgers.js +188 -29
  154. package/dist/core/telegram/messages.js +26 -6
  155. package/dist/core/telegram/owner-lock.js +10 -7
  156. package/dist/core/telegram/runtime-projection.js +38 -3
  157. package/dist/core/telegram/runtime.js +298 -63
  158. package/dist/core/telegram/service.js +137 -8
  159. package/dist/core/telegram/setup.js +291 -73
  160. package/dist/core/text/strings.js +3 -0
  161. package/dist/core/triwiki/code-pack.js +12 -120
  162. package/dist/core/triwiki/context-graph/compiler/cache-key.js +277 -0
  163. package/dist/core/triwiki/context-graph/compiler/extract.js +104 -0
  164. package/dist/core/triwiki/context-graph/compiler/freshness.js +108 -0
  165. package/dist/core/triwiki/context-graph/compiler/index.js +237 -0
  166. package/dist/core/triwiki/context-graph/compiler/merge.js +0 -0
  167. package/dist/core/triwiki/context-graph/compiler/serialize.js +115 -0
  168. package/dist/core/triwiki/context-graph/contracts.js +236 -0
  169. package/dist/core/triwiki/context-graph/extractors/code/builders.js +150 -0
  170. package/dist/core/triwiki/context-graph/extractors/code/declarations.js +161 -0
  171. package/dist/core/triwiki/context-graph/extractors/code/index.js +265 -0
  172. package/dist/core/triwiki/context-graph/extractors/code/inventory.js +237 -0
  173. package/dist/core/triwiki/context-graph/extractors/code/module-graph.js +252 -0
  174. package/dist/core/triwiki/context-graph/extractors/code/modules.js +79 -0
  175. package/dist/core/triwiki/context-graph/extractors/code/references.js +184 -0
  176. package/dist/core/triwiki/context-graph/extractors/code/selection.js +100 -0
  177. package/dist/core/triwiki/context-graph/extractors/code/ts-config.js +161 -0
  178. package/dist/core/triwiki/context-graph/extractors/code/types.js +18 -0
  179. package/dist/core/triwiki/context-graph/extractors/evidence/claims.js +289 -0
  180. package/dist/core/triwiki/context-graph/extractors/evidence/index.js +54 -0
  181. package/dist/core/triwiki/context-graph/extractors/evidence/proof-index.js +213 -0
  182. package/dist/core/triwiki/context-graph/extractors/evidence/proofs.js +266 -0
  183. package/dist/core/triwiki/context-graph/extractors/evidence/redaction.js +177 -0
  184. package/dist/core/triwiki/context-graph/extractors/evidence/shared.js +0 -0
  185. package/dist/core/triwiki/context-graph/extractors/evidence/sources.js +154 -0
  186. package/dist/core/triwiki/context-graph/extractors/index.js +7 -0
  187. package/dist/core/triwiki/context-graph/extractors/topology/commands.js +207 -0
  188. package/dist/core/triwiki/context-graph/extractors/topology/gate-edges.js +201 -0
  189. package/dist/core/triwiki/context-graph/extractors/topology/gates.js +182 -0
  190. package/dist/core/triwiki/context-graph/extractors/topology/globs.js +124 -0
  191. package/dist/core/triwiki/context-graph/extractors/topology/index.js +92 -0
  192. package/dist/core/triwiki/context-graph/extractors/topology/routes.js +135 -0
  193. package/dist/core/triwiki/context-graph/extractors/topology/shared.js +215 -0
  194. package/dist/core/triwiki/context-graph/graph-index.js +143 -0
  195. package/dist/core/triwiki/context-graph/ids.js +0 -0
  196. package/dist/core/triwiki/context-graph/lint/index.js +0 -0
  197. package/dist/core/triwiki/context-graph/lint/rules.js +232 -0
  198. package/dist/core/triwiki/context-graph/lint/warnings.js +93 -0
  199. package/dist/core/triwiki/context-graph/paths.js +116 -0
  200. package/dist/core/triwiki/context-graph/profiles.js +78 -0
  201. package/dist/core/triwiki/context-graph/projections/anchors.js +91 -0
  202. package/dist/core/triwiki/context-graph/projections/attention.js +58 -0
  203. package/dist/core/triwiki/context-graph/projections/code-pack-workspace.js +62 -0
  204. package/dist/core/triwiki/context-graph/projections/code-pack.js +144 -0
  205. package/dist/core/triwiki/context-graph/projections/index.js +7 -0
  206. package/dist/core/triwiki/context-graph/projections/module-view.js +140 -0
  207. package/dist/core/triwiki/context-graph/projections/node-summary.js +118 -0
  208. package/dist/core/triwiki/context-graph/projections/pack-contract.js +6 -0
  209. package/dist/core/triwiki/context-graph/query/explain.js +0 -0
  210. package/dist/core/triwiki/context-graph/query/index.js +178 -0
  211. package/dist/core/triwiki/context-graph/query/load.js +116 -0
  212. package/dist/core/triwiki/context-graph/query/pack.js +117 -0
  213. package/dist/core/triwiki/context-graph/query/rank.js +142 -0
  214. package/dist/core/triwiki/context-graph/query/ranking-config.js +64 -0
  215. package/dist/core/triwiki/context-graph/query/seeds.js +241 -0
  216. package/dist/core/triwiki/context-graph/query/snapshot-cache.js +72 -0
  217. package/dist/core/triwiki/context-graph/query/traverse.js +154 -0
  218. package/dist/core/triwiki/context-graph/query-types.js +29 -0
  219. package/dist/core/triwiki/context-graph/store/compile-lock.js +21 -0
  220. package/dist/core/triwiki/context-graph/store/event-log.js +48 -0
  221. package/dist/core/triwiki/context-graph/store/fragment-cache.js +85 -0
  222. package/dist/core/triwiki/context-graph/store/graph-status.js +85 -0
  223. package/dist/core/triwiki/context-graph/store/snapshot-store.js +155 -0
  224. package/dist/core/triwiki/triwiki-proof-bank-index-repair.js +115 -0
  225. package/dist/core/triwiki/triwiki-proof-bank-index-store.js +290 -0
  226. package/dist/core/triwiki/triwiki-proof-bank-index.js +126 -0
  227. package/dist/core/triwiki/triwiki-proof-bank.js +7 -1
  228. package/dist/core/verification/context-graph-affected.js +271 -0
  229. package/dist/core/version.js +1 -1
  230. package/dist/native/sks-menubar/Sources/AlertFactory.swift +11 -3
  231. package/dist/native/sks-menubar/Sources/AppDelegate.swift +9 -0
  232. package/dist/native/sks-menubar/Sources/ControlCenterWindowController.swift +25 -3
  233. package/dist/native/sks-menubar/Sources/ControlKit.swift +19 -8
  234. package/dist/native/sks-menubar/Sources/DiagnosticsViewController.swift +1 -2
  235. package/dist/native/sks-menubar/Sources/MCPServersViewController.swift +45 -17
  236. package/dist/native/sks-menubar/Sources/OverviewSummary.swift +162 -0
  237. package/dist/native/sks-menubar/Sources/OverviewViewController.swift +136 -190
  238. package/dist/native/sks-menubar/Sources/ProcessClient.swift +107 -11
  239. package/dist/native/sks-menubar/Sources/ProvidersMultiProvider.swift +5 -1
  240. package/dist/native/sks-menubar/Sources/ProvidersOpenRouter.swift +16 -4
  241. package/dist/native/sks-menubar/Sources/ProvidersRoleModels.swift +4 -1
  242. package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +131 -0
  243. package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +288 -341
  244. package/dist/native/sks-menubar/Sources/RemoteTelegramCenterState.swift +447 -0
  245. package/dist/native/sks-menubar/Sources/RemoteTelegramRendering.swift +484 -0
  246. package/dist/native/sks-menubar/Sources/RemoteTelegramViewController.swift +364 -115
  247. package/dist/native/sks-menubar/Sources/SettingsViewController.swift +73 -12
  248. package/dist/native/sks-menubar/Sources/SidebarItem.swift +3 -3
  249. package/dist/native/sks-menubar/Sources/StatusItemController.swift +13 -13
  250. package/dist/native/sks-menubar/Sources/TelegramHubSupervisor.swift +469 -0
  251. package/dist/native/sks-menubar/Sources/UpdatesViewController.swift +1 -6
  252. package/dist/native/sks-menubar/Tests/AppRuntimeTestSupport.swift +12 -0
  253. package/dist/native/sks-menubar/Tests/NativeTelegramRegressionRunner.swift +55 -0
  254. package/dist/native/sks-menubar/Tests/ProcessClientTests.swift +33 -0
  255. package/dist/native/sks-menubar/Tests/ProvidersViewControllerTests.swift +142 -0
  256. package/dist/native/sks-menubar/Tests/RemoteTelegramCenterStateTests.swift +56 -0
  257. package/dist/native/sks-menubar/Tests/TelegramHubSupervisorTests.swift +55 -0
  258. package/dist/scripts/codex-lb-catalog-passthrough-check.js +120 -0
  259. package/dist/scripts/codex-lb-desktop-auth-invariant-check.js +169 -0
  260. package/dist/scripts/codex-lb-desktop-bridge-check.js +394 -0
  261. package/dist/scripts/codex-lb-desktop-bridge-latency-check.js +196 -0
  262. package/dist/scripts/codex-lb-desktop-capabilities-check.js +287 -0
  263. package/dist/scripts/codex-lb-desktop-real-evidence-check.js +123 -0
  264. package/dist/scripts/codex-lb-fast-mode-truth-check.js +10 -3
  265. package/dist/scripts/codex-lb-fast-ui-preservation-check.js +81 -40
  266. package/dist/scripts/codex-lb-gpt56-fast-profile-check.js +99 -37
  267. package/dist/scripts/context-graph-check.js +191 -0
  268. package/dist/scripts/doctor-fixes-codex-app-fast-ui-check.js +1 -1
  269. package/dist/scripts/gate-policy-audit-check.js +1 -1
  270. package/dist/scripts/helper-dedup-check.js +0 -2
  271. package/dist/scripts/installed-package-smoke-check.js +4 -1
  272. package/dist/scripts/latest-version-guidance-check.js +74 -0
  273. package/dist/scripts/release-metadata-check.js +21 -4
  274. package/dist/scripts/release-real-check.js +7 -0
  275. package/dist/scripts/ux-review-imagegen-blackbox-check.js +25 -1
  276. package/dist/scripts/ux-review-run-wires-imagegen-check.js +9 -1
  277. package/package.json +8 -3
  278. package/release-gates.v2.json +176 -1
  279. package/runtime-required-scripts.json +30 -0
  280. package/schemas/triwiki/context-graph.schema.json +119 -0
  281. package/dist/cli/install-helpers-codex-lb-selftest-chain.js +0 -112
  282. package/dist/cli/install-helpers-codex-lb-selftest.js +0 -481
  283. package/dist/core/triwiki/code-index-scanner.js +0 -309
@@ -0,0 +1,718 @@
1
+ import path from 'node:path';
2
+ import { createCodexAppServerV2Client } from '../codex-control/codex-app-server-v2-client.js';
3
+ import { prepareCodexAppServerRuntimeEnv } from '../codex-control/codex-app-server-runtime-env.js';
4
+ import { readJson, sha256 } from '../fsx.js';
5
+ import { asRecordOrNull as asRecord } from '../json/records.js';
6
+ import { publicCodexActivityFromItem, publicCodexText } from '../remote/codex-public-activity.js';
7
+ import { RemoteCodexSessionBindingStore, remoteCodexSessionBindingsPath } from '../remote/session-binding.js';
8
+ import { RemoteEventJournal, remoteRuntimePaths } from '../remote/audit-idempotency.js';
9
+ export const TELEGRAM_CENTER_SNAPSHOT_SCHEMA = 'sks.telegram-center-snapshot.v1';
10
+ export const TELEGRAM_CENTER_LIVE_SCHEMA = 'sks.telegram-center-live.v1';
11
+ export const TELEGRAM_CENTER_TRANSCRIPT_MAX_BYTES = 480 * 1024;
12
+ export const TELEGRAM_CENTER_ACTIVITY_MAX_BYTES = 176 * 1024;
13
+ export const TELEGRAM_CENTER_MAX_TRANSCRIPT_ITEMS = 768;
14
+ export const TELEGRAM_CENTER_MAX_ACTIVITY_ITEMS = 768;
15
+ export const TELEGRAM_CENTER_TURN_PAGE_LIMIT = 48;
16
+ const MAX_SOURCE_TURNS = 512;
17
+ const MAX_SOURCE_ITEMS = 8_192;
18
+ const MAX_REGISTERED_SESSIONS = 64;
19
+ const MAX_MESSAGE_BYTES = 16 * 1024;
20
+ const MAX_CURSOR_BYTES = 8 * 1024;
21
+ const CENTER_COMMANDS = [
22
+ '/status',
23
+ '/tail',
24
+ '/diff',
25
+ '/gates',
26
+ '/trust',
27
+ '/proof',
28
+ '/artifacts',
29
+ '/input',
30
+ '/verify',
31
+ '/cancel',
32
+ '/refresh',
33
+ '/open'
34
+ ];
35
+ export async function telegramCenterSnapshot(options) {
36
+ const projectRoot = path.resolve(options.projectRoot);
37
+ const now = options.now?.() ?? new Date();
38
+ const limits = normalizeLimits(options.limits);
39
+ const cursor = normalizeOpaqueCursor(options.cursor);
40
+ const sortDirection = normalizeSortDirection(options.sortDirection);
41
+ const turnPageLimit = Math.min(TELEGRAM_CENTER_TURN_PAGE_LIMIT, limits.sourceTurns);
42
+ const store = options.bindingStore ?? new RemoteCodexSessionBindingStore(remoteCodexSessionBindingsPath(projectRoot));
43
+ const loaded = options.bindings ? [...options.bindings] : await store.list();
44
+ const bindings = loaded
45
+ .filter((binding) => path.resolve(binding.project_root) === projectRoot)
46
+ .sort((left, right) => Date.parse(right.updated_at) - Date.parse(left.updated_at));
47
+ const sessions = bindings.slice(0, MAX_REGISTERED_SESSIONS).map(sessionSummary);
48
+ if (bindings.length === 0) {
49
+ return baseSnapshot({
50
+ now,
51
+ state: 'not_configured',
52
+ sessions,
53
+ selectedSessionId: null,
54
+ guidance: 'Connect a private Telegram bot and register this project before conversation history can appear.'
55
+ });
56
+ }
57
+ const selected = options.sessionId
58
+ ? bindings.find((binding) => binding.session_id === options.sessionId)
59
+ : bindings[0];
60
+ if (!selected)
61
+ throw new Error('telegram_center_session_unknown');
62
+ if (!selected.codex_thread_id) {
63
+ return baseSnapshot({
64
+ now,
65
+ state: 'awaiting_first_message',
66
+ sessions,
67
+ selectedSessionId: selected.session_id,
68
+ guidance: 'Send an ordinary text message to the paired Telegram bot. That first message creates and persists this dedicated Codex thread; then its conversation and public work activity will appear here.',
69
+ selected
70
+ });
71
+ }
72
+ const makeClient = options.codexClientFactory ?? defaultCodexClientFactory;
73
+ const client = await makeClient(projectRoot);
74
+ let read;
75
+ let turnsRead;
76
+ try {
77
+ await client.initialize();
78
+ [read, turnsRead] = await Promise.all([
79
+ client.readThread(selected.codex_thread_id, false),
80
+ client.listThreadTurns(selected.codex_thread_id, {
81
+ ...(cursor ? { cursor } : {}),
82
+ itemsView: 'full',
83
+ limit: turnPageLimit,
84
+ sortDirection
85
+ })
86
+ ]);
87
+ }
88
+ finally {
89
+ await client.close().catch(() => undefined);
90
+ }
91
+ const response = asRecord(read);
92
+ const thread = asRecord(response?.thread);
93
+ if (!thread || String(thread.id || '') !== selected.codex_thread_id) {
94
+ throw new Error('telegram_center_thread_read_mismatch');
95
+ }
96
+ const threadRoot = typeof thread.cwd === 'string' ? path.resolve(thread.cwd) : null;
97
+ if (threadRoot && threadRoot !== projectRoot)
98
+ throw new Error('telegram_center_thread_scope_mismatch');
99
+ const turnsPage = asRecord(turnsRead);
100
+ if (!turnsPage || !Array.isArray(turnsPage.data)) {
101
+ throw new Error('telegram_center_turns_page_invalid');
102
+ }
103
+ const pageTurns = turnsPage.data.map(asRecord).filter(Boolean);
104
+ const orderedTurns = [...pageTurns].sort(compareTurnsChronologically);
105
+ const normalized = normalizeTelegramCenterThread({ ...thread, turns: orderedTurns }, projectRoot, limits);
106
+ const conversationPage = normalizeConversationPage({
107
+ cursor,
108
+ sortDirection,
109
+ limit: turnPageLimit,
110
+ turnCount: pageTurns.length,
111
+ nextCursor: turnsPage.nextCursor,
112
+ backwardsCursor: turnsPage.backwardsCursor
113
+ });
114
+ const liveActivity = await readCenterLiveActivity({
115
+ projectRoot,
116
+ sessionId: selected.session_id,
117
+ ...(options.eventSource !== undefined ? { eventSource: options.eventSource } : {}),
118
+ ...(options.eventHealthPath !== undefined ? { eventHealthPath: options.eventHealthPath } : {}),
119
+ limits
120
+ });
121
+ const merged = mergeActivity(normalized.activity, liveActivity.items, limits);
122
+ const truncated = normalized.truncation.source_turns_omitted > 0
123
+ || normalized.truncation.source_items_omitted > 0
124
+ || normalized.truncation.transcript_items_omitted > 0
125
+ || normalized.truncation.activity_items_omitted > 0
126
+ || liveActivity.omitted > 0
127
+ || merged.omitted > 0;
128
+ return {
129
+ schema: TELEGRAM_CENTER_SNAPSHOT_SCHEMA,
130
+ ok: true,
131
+ state: 'ready',
132
+ generated_at: now.toISOString(),
133
+ selected_session_id: selected.session_id,
134
+ conversation_revision: conversationRevision(selected),
135
+ live_activity_digest: liveActivity.digest,
136
+ sessions,
137
+ binding: sessionSummary(selected),
138
+ thread: normalized.thread,
139
+ conversation_page: conversationPage,
140
+ transcript: normalized.transcript,
141
+ activity: merged.items,
142
+ source: {
143
+ conversation: 'codex_app_server_v2_thread_turns_list',
144
+ live_activity: 'remote_event_journal',
145
+ live_activity_state: liveActivity.state,
146
+ live_activity_error: liveActivity.error,
147
+ reasoning_included: false,
148
+ raw_outputs_included: false
149
+ },
150
+ usage: centerUsage(),
151
+ guidance: liveActivity.state === 'ready'
152
+ ? 'Use Older, Newer, and Latest to browse every stored turn page in this Telegram-bound Codex thread. Reasoning text, raw tool output, and credentials are never projected.'
153
+ : 'Conversation history is available, but the bounded live activity journal is degraded. Open Diagnostics for the redacted journal error; do not resend the Codex turn just to refresh activity.',
154
+ truncation: {
155
+ truncated,
156
+ ...normalized.truncation,
157
+ activity_items_omitted: normalized.truncation.activity_items_omitted + liveActivity.omitted + merged.omitted,
158
+ activity_bytes: merged.bytes,
159
+ transcript_max_bytes: limits.transcriptBytes,
160
+ activity_max_bytes: limits.activityBytes
161
+ }
162
+ };
163
+ }
164
+ export async function telegramCenterLiveSnapshot(options) {
165
+ const projectRoot = path.resolve(options.projectRoot);
166
+ const now = options.now?.() ?? new Date();
167
+ const limits = normalizeLimits(options.limits);
168
+ const store = options.bindingStore ?? new RemoteCodexSessionBindingStore(remoteCodexSessionBindingsPath(projectRoot));
169
+ const loaded = options.bindings ? [...options.bindings] : await store.list();
170
+ const bindings = loaded
171
+ .filter((binding) => path.resolve(binding.project_root) === projectRoot)
172
+ .sort((left, right) => Date.parse(right.updated_at) - Date.parse(left.updated_at));
173
+ const sessions = bindings.slice(0, MAX_REGISTERED_SESSIONS).map(sessionSummary);
174
+ if (bindings.length === 0) {
175
+ return {
176
+ schema: TELEGRAM_CENTER_LIVE_SCHEMA,
177
+ ok: true,
178
+ state: 'not_configured',
179
+ generated_at: now.toISOString(),
180
+ selected_session_id: null,
181
+ sessions,
182
+ binding: null,
183
+ conversation_revision: null,
184
+ live_activity_digest: sha256('[]'),
185
+ activity: [],
186
+ source: {
187
+ live_activity: 'remote_event_journal',
188
+ live_activity_state: 'pending',
189
+ live_activity_error: null
190
+ },
191
+ truncation: {
192
+ truncated: false,
193
+ activity_items_omitted: 0,
194
+ activity_bytes: 2,
195
+ activity_max_bytes: limits.activityBytes
196
+ }
197
+ };
198
+ }
199
+ const selected = options.sessionId
200
+ ? bindings.find((binding) => binding.session_id === options.sessionId)
201
+ : bindings[0];
202
+ if (!selected)
203
+ throw new Error('telegram_center_session_unknown');
204
+ const liveActivity = await readCenterLiveActivity({
205
+ projectRoot,
206
+ sessionId: selected.session_id,
207
+ ...(options.eventSource !== undefined ? { eventSource: options.eventSource } : {}),
208
+ ...(options.eventHealthPath !== undefined ? { eventHealthPath: options.eventHealthPath } : {}),
209
+ limits
210
+ });
211
+ return {
212
+ schema: TELEGRAM_CENTER_LIVE_SCHEMA,
213
+ ok: true,
214
+ state: selected.codex_thread_id ? 'ready' : 'awaiting_first_message',
215
+ generated_at: now.toISOString(),
216
+ selected_session_id: selected.session_id,
217
+ sessions,
218
+ binding: sessionSummary(selected),
219
+ conversation_revision: conversationRevision(selected),
220
+ live_activity_digest: liveActivity.digest,
221
+ activity: liveActivity.items,
222
+ source: {
223
+ live_activity: 'remote_event_journal',
224
+ live_activity_state: liveActivity.state,
225
+ live_activity_error: liveActivity.error
226
+ },
227
+ truncation: {
228
+ truncated: liveActivity.omitted > 0,
229
+ activity_items_omitted: liveActivity.omitted,
230
+ activity_bytes: liveActivity.bytes,
231
+ activity_max_bytes: limits.activityBytes
232
+ }
233
+ };
234
+ }
235
+ export function normalizeTelegramCenterThread(value, projectRoot, inputLimits = {}) {
236
+ const limits = normalizeLimits(inputLimits);
237
+ const thread = asRecord(value) ?? {};
238
+ const allTurns = Array.isArray(thread.turns) ? thread.turns.map(asRecord).filter(Boolean) : [];
239
+ const turns = allTurns.slice(-limits.sourceTurns);
240
+ let sourceItemsRemaining = limits.sourceItems;
241
+ let sourceItemsOmitted = 0;
242
+ const transcript = [];
243
+ const activity = [];
244
+ const selectedTurns = [];
245
+ for (let index = turns.length - 1; index >= 0; index -= 1) {
246
+ const turn = turns[index];
247
+ const allItems = Array.isArray(turn.items) ? turn.items.map(asRecord).filter(Boolean) : [];
248
+ const allowedCount = Math.max(0, Math.min(allItems.length, sourceItemsRemaining));
249
+ selectedTurns.push({ turn, items: allItems.slice(-allowedCount) });
250
+ sourceItemsRemaining -= allowedCount;
251
+ sourceItemsOmitted += allItems.length - allowedCount;
252
+ if (sourceItemsRemaining <= 0) {
253
+ for (let earlier = index - 1; earlier >= 0; earlier -= 1) {
254
+ const earlierItems = Array.isArray(turns[earlier]?.items) ? turns[earlier]?.items : [];
255
+ sourceItemsOmitted += earlierItems.length;
256
+ }
257
+ break;
258
+ }
259
+ }
260
+ selectedTurns.reverse();
261
+ for (const { turn, items } of selectedTurns) {
262
+ const turnId = publicId(turn.id, 240) ?? `turn-${transcript.length + activity.length + 1}`;
263
+ const status = publicState(turn.status);
264
+ const startedAt = isoFromEpoch(turn.startedAt);
265
+ const completedAt = isoFromEpoch(turn.completedAt);
266
+ activity.push(turnActivity(turnId, 'started', status, startedAt, null));
267
+ for (const [index, item] of items.entries()) {
268
+ const type = String(item.type || '');
269
+ const itemId = publicId(item.id, 240) ?? `${turnId}:${type || 'item'}:${index}`;
270
+ if (type === 'userMessage') {
271
+ const text = userMessageText(item.content);
272
+ if (text) {
273
+ transcript.push({
274
+ id: itemId,
275
+ turn_id: turnId,
276
+ role: 'user',
277
+ phase: null,
278
+ text,
279
+ turn_status: status,
280
+ occurred_at: startedAt,
281
+ source: 'codex_app_server_v2'
282
+ });
283
+ }
284
+ continue;
285
+ }
286
+ if (type === 'agentMessage') {
287
+ const text = publicCodexText(item.text, MAX_MESSAGE_BYTES);
288
+ if (text) {
289
+ transcript.push({
290
+ id: itemId,
291
+ turn_id: turnId,
292
+ role: 'assistant',
293
+ phase: publicStateOrNull(item.phase),
294
+ text,
295
+ turn_status: status,
296
+ occurred_at: completedAt ?? startedAt,
297
+ source: 'codex_app_server_v2'
298
+ });
299
+ }
300
+ continue;
301
+ }
302
+ const summary = publicCodexActivityFromItem(item, projectRoot);
303
+ if (!summary)
304
+ continue;
305
+ const lifecycle = status === 'inProgress' ? 'started' : 'completed';
306
+ activity.push({
307
+ id: `history:${turnId}:${itemId}:${lifecycle}`,
308
+ dedupe_key: `item:${itemId}:${lifecycle}`,
309
+ turn_id: turnId,
310
+ item_id: itemId,
311
+ ...summary,
312
+ occurred_at: lifecycle === 'completed' ? completedAt ?? startedAt : startedAt,
313
+ source: 'codex_app_server_v2'
314
+ });
315
+ }
316
+ if (status !== 'inProgress') {
317
+ activity.push(turnActivity(turnId, 'completed', status, completedAt ?? startedAt, publicInteger(turn.durationMs)));
318
+ }
319
+ }
320
+ const boundedTranscript = boundNewest(transcript, limits.transcriptItems, limits.transcriptBytes);
321
+ const boundedActivity = boundNewest(activity, limits.activityItems, limits.activityBytes);
322
+ return {
323
+ thread: {
324
+ id: publicId(thread.id, 240),
325
+ status: publicThreadStatus(thread.status),
326
+ created_at: isoFromEpoch(thread.createdAt),
327
+ updated_at: isoFromEpoch(thread.updatedAt),
328
+ source: publicCodexText(thread.threadSource ?? thread.source, 120),
329
+ loaded_turn_count: allTurns.length,
330
+ projected_turn_count: turns.length
331
+ },
332
+ transcript: boundedTranscript.items,
333
+ activity: boundedActivity.items,
334
+ truncation: {
335
+ source_turns_omitted: Math.max(0, allTurns.length - turns.length),
336
+ source_items_omitted: sourceItemsOmitted,
337
+ transcript_items_omitted: boundedTranscript.omitted,
338
+ activity_items_omitted: boundedActivity.omitted,
339
+ transcript_bytes: boundedTranscript.bytes,
340
+ activity_bytes: boundedActivity.bytes
341
+ }
342
+ };
343
+ }
344
+ function normalizeConversationPage(input) {
345
+ const nextCursor = publicOpaqueCursor(input.nextCursor);
346
+ const backwardsCursor = publicOpaqueCursor(input.backwardsCursor);
347
+ const isLatest = input.cursor === null && input.sortDirection === 'desc';
348
+ const olderCursor = input.sortDirection === 'desc' ? nextCursor : backwardsCursor;
349
+ const newerCursor = isLatest
350
+ ? null
351
+ : input.sortDirection === 'desc'
352
+ ? backwardsCursor
353
+ : nextCursor;
354
+ return {
355
+ navigation: 'cursor',
356
+ items_view: 'full',
357
+ sort_direction: input.sortDirection,
358
+ is_latest: isLatest,
359
+ live_polling_recommended: isLatest,
360
+ cursor_present: input.cursor !== null,
361
+ page_turn_count: input.turnCount,
362
+ requested_turn_limit: input.limit,
363
+ has_older: olderCursor !== null,
364
+ older_cursor: olderCursor,
365
+ older_sort_direction: olderCursor ? 'desc' : null,
366
+ has_newer: newerCursor !== null,
367
+ newer_cursor: newerCursor,
368
+ newer_sort_direction: newerCursor ? 'asc' : null
369
+ };
370
+ }
371
+ function compareTurnsChronologically(left, right) {
372
+ const leftTime = turnEpoch(left);
373
+ const rightTime = turnEpoch(right);
374
+ if (leftTime !== rightTime)
375
+ return leftTime - rightTime;
376
+ return String(left.id || '').localeCompare(String(right.id || ''));
377
+ }
378
+ function turnEpoch(turn) {
379
+ for (const value of [turn.startedAt, turn.completedAt]) {
380
+ if (typeof value === 'number' && Number.isFinite(value))
381
+ return value;
382
+ }
383
+ return 0;
384
+ }
385
+ function baseSnapshot(input) {
386
+ return {
387
+ schema: TELEGRAM_CENTER_SNAPSHOT_SCHEMA,
388
+ ok: true,
389
+ state: input.state,
390
+ generated_at: input.now.toISOString(),
391
+ selected_session_id: input.selectedSessionId,
392
+ conversation_revision: input.selected ? conversationRevision(input.selected) : null,
393
+ live_activity_digest: sha256('[]'),
394
+ sessions: input.sessions,
395
+ binding: input.selected ? sessionSummary(input.selected) : null,
396
+ thread: null,
397
+ conversation_page: {
398
+ navigation: 'cursor',
399
+ items_view: 'full',
400
+ sort_direction: 'desc',
401
+ is_latest: true,
402
+ cursor_present: false,
403
+ page_turn_count: 0,
404
+ requested_turn_limit: TELEGRAM_CENTER_TURN_PAGE_LIMIT,
405
+ has_older: false,
406
+ older_cursor: null,
407
+ older_sort_direction: null,
408
+ has_newer: false,
409
+ newer_cursor: null,
410
+ newer_sort_direction: null
411
+ },
412
+ transcript: [],
413
+ activity: [],
414
+ source: {
415
+ conversation: input.state === 'awaiting_first_message' ? 'pending_codex_thread' : 'not_configured',
416
+ live_activity: 'remote_event_journal',
417
+ live_activity_state: 'pending',
418
+ live_activity_error: null,
419
+ reasoning_included: false,
420
+ raw_outputs_included: false
421
+ },
422
+ usage: centerUsage(),
423
+ guidance: input.guidance,
424
+ truncation: {
425
+ truncated: false,
426
+ source_turns_omitted: 0,
427
+ source_items_omitted: 0,
428
+ transcript_items_omitted: 0,
429
+ activity_items_omitted: 0,
430
+ transcript_bytes: 0,
431
+ activity_bytes: 0,
432
+ transcript_max_bytes: TELEGRAM_CENTER_TRANSCRIPT_MAX_BYTES,
433
+ activity_max_bytes: TELEGRAM_CENTER_ACTIVITY_MAX_BYTES
434
+ }
435
+ };
436
+ }
437
+ async function readCenterLiveActivity(input) {
438
+ const eventSource = input.eventSource
439
+ ?? new RemoteEventJournal(remoteRuntimePaths(input.projectRoot).events, {
440
+ lockPath: remoteRuntimePaths(input.projectRoot).eventLock
441
+ });
442
+ let journal = [];
443
+ let state = 'ready';
444
+ let error = null;
445
+ try {
446
+ journal = await readRecentEvents(eventSource, input.sessionId);
447
+ }
448
+ catch {
449
+ state = 'degraded';
450
+ error = 'remote_event_journal_read_failed';
451
+ }
452
+ const eventHealth = await readJson(input.eventHealthPath ?? remoteRuntimePaths(input.projectRoot).eventHealth, null);
453
+ if (eventHealth?.schema === 'sks.remote-event-journal-health.v1'
454
+ && eventHealth.state === 'degraded') {
455
+ state = 'degraded';
456
+ error = publicLiveActivityError(eventHealth.error_code);
457
+ }
458
+ const bounded = boundNewest(journal.map(eventActivity).filter(Boolean), input.limits.activityItems, input.limits.activityBytes);
459
+ return {
460
+ items: bounded.items,
461
+ state,
462
+ error,
463
+ digest: sha256(JSON.stringify(bounded.items)),
464
+ omitted: bounded.omitted,
465
+ bytes: bounded.bytes
466
+ };
467
+ }
468
+ function conversationRevision(binding) {
469
+ return sha256(JSON.stringify([
470
+ binding.session_id,
471
+ binding.codex_thread_id,
472
+ binding.last_turn_id ?? null,
473
+ binding.last_turn_status ?? null,
474
+ binding.updated_at
475
+ ]));
476
+ }
477
+ function publicLiveActivityError(value) {
478
+ const allowed = new Set([
479
+ 'remote_event_journal_write_failed',
480
+ 'remote_event_journal_read_failed',
481
+ 'remote_event_journal_degraded'
482
+ ]);
483
+ const error = typeof value === 'string' ? value : '';
484
+ return allowed.has(error) ? error : 'remote_event_journal_degraded';
485
+ }
486
+ function sessionSummary(binding) {
487
+ return {
488
+ session_id: binding.session_id,
489
+ machine_id: binding.machine_id,
490
+ project_id: binding.project_id,
491
+ codex_thread_id: binding.codex_thread_id,
492
+ state: binding.codex_thread_id ? 'ready' : 'awaiting_first_message',
493
+ last_turn_id: binding.last_turn_id ?? null,
494
+ last_turn_status: binding.last_turn_status ?? null,
495
+ updated_at: binding.updated_at
496
+ };
497
+ }
498
+ function centerUsage() {
499
+ return {
500
+ ordinary_text: 'Ordinary text starts or resumes the selected dedicated Codex thread, waits for completion, and returns Codex’s final response.',
501
+ conversation_history: 'Center pages every stored turn through Codex App Server thread/turns/list. Older and Newer move one opaque cursor page; Latest returns to the live edge.',
502
+ commands: [...CENTER_COMMANDS],
503
+ safety: 'The dedicated thread uses workspace-write for this project with network access disabled; unpaired chats and arbitrary remote shell remain blocked.'
504
+ };
505
+ }
506
+ function userMessageText(value) {
507
+ const content = Array.isArray(value) ? value.map(asRecord).filter(Boolean) : [];
508
+ const parts = [];
509
+ for (const item of content) {
510
+ if (item.type === 'text') {
511
+ const text = publicCodexText(item.text, MAX_MESSAGE_BYTES);
512
+ if (text)
513
+ parts.push(text);
514
+ continue;
515
+ }
516
+ if (['image', 'localImage'].includes(String(item.type)))
517
+ parts.push('[Image attachment]');
518
+ else if (['audio', 'localAudio'].includes(String(item.type)))
519
+ parts.push('[Audio attachment]');
520
+ else if (item.type === 'skill')
521
+ parts.push(`[Skill: ${publicCodexText(item.name, 120) ?? 'attached'}]`);
522
+ else if (item.type === 'mention')
523
+ parts.push(`[Mention: ${publicCodexText(item.name, 120) ?? 'attached'}]`);
524
+ }
525
+ return publicCodexText(parts.join('\n'), MAX_MESSAGE_BYTES);
526
+ }
527
+ function turnActivity(turnId, lifecycle, status, occurredAt, durationMs) {
528
+ return {
529
+ id: `history:${turnId}:${lifecycle}`,
530
+ dedupe_key: `turn:${turnId}:${lifecycle}`,
531
+ turn_id: turnId,
532
+ item_id: null,
533
+ kind: 'turn',
534
+ status,
535
+ title: lifecycle === 'started' ? 'Codex turn started' : `Codex turn ${status}`,
536
+ detail: null,
537
+ occurred_at: occurredAt,
538
+ duration_ms: durationMs,
539
+ exit_code: null,
540
+ source: 'codex_app_server_v2'
541
+ };
542
+ }
543
+ async function readRecentEvents(source, sessionId) {
544
+ if (source.recent)
545
+ return source.recent(sessionId, 4_096);
546
+ let page = await source.watch(0, sessionId);
547
+ if (page.cursor.gap) {
548
+ const after = Math.max(0, page.cursor.first_available_seq - 1);
549
+ page = await source.watch(after, sessionId);
550
+ }
551
+ const collected = [...page.events];
552
+ if (!Number.isSafeInteger(page.cursor.next_after_seq)
553
+ || !Number.isSafeInteger(page.cursor.last_available_seq)) {
554
+ return collected;
555
+ }
556
+ let after = Number(page.cursor.next_after_seq);
557
+ const last = Number(page.cursor.last_available_seq);
558
+ for (let pageCount = 1; pageCount < 64 && after < last; pageCount += 1) {
559
+ const next = await source.watch(after, sessionId);
560
+ if (next.cursor.gap || next.events.length === 0)
561
+ break;
562
+ collected.push(...next.events);
563
+ const nextAfter = Number(next.cursor.next_after_seq);
564
+ if (!Number.isSafeInteger(nextAfter) || nextAfter <= after)
565
+ break;
566
+ after = nextAfter;
567
+ }
568
+ return collected.slice(-4_096);
569
+ }
570
+ function eventActivity(event) {
571
+ const summary = asRecord(event.summary);
572
+ if (!summary)
573
+ return null;
574
+ if (event.type.startsWith('codex.')) {
575
+ return {
576
+ id: `journal:${event.seq}`,
577
+ dedupe_key: publicCodexText(summary.dedupe_key, 320),
578
+ turn_id: publicId(summary.turn_id, 240),
579
+ item_id: publicId(summary.item_id, 240),
580
+ kind: publicState(summary.kind),
581
+ status: publicState(summary.status),
582
+ title: publicCodexText(summary.title, 320) ?? 'Codex activity',
583
+ detail: publicCodexText(summary.detail, 2 * 1024),
584
+ occurred_at: validIso(event.ts),
585
+ duration_ms: publicInteger(summary.duration_ms),
586
+ exit_code: publicInteger(summary.exit_code),
587
+ source: 'remote_event_journal'
588
+ };
589
+ }
590
+ if (event.type.startsWith('remote.command.')) {
591
+ const kind = publicState(summary.kind);
592
+ const status = publicState(summary.status);
593
+ return {
594
+ id: `journal:${event.seq}`,
595
+ dedupe_key: null,
596
+ turn_id: null,
597
+ item_id: null,
598
+ kind: 'remote_command',
599
+ status,
600
+ title: `Telegram ${kind} ${status}`,
601
+ detail: publicCodexText(summary.error_code, 320),
602
+ occurred_at: validIso(event.ts),
603
+ duration_ms: null,
604
+ exit_code: null,
605
+ source: 'remote_event_journal'
606
+ };
607
+ }
608
+ return null;
609
+ }
610
+ function mergeActivity(history, journal, limits) {
611
+ const historyKeys = new Set(history.map((entry) => entry.dedupe_key).filter(Boolean));
612
+ const uniqueJournal = journal.filter((entry) => !entry.dedupe_key || !historyKeys.has(entry.dedupe_key));
613
+ const merged = [...history, ...uniqueJournal].sort((left, right) => {
614
+ const leftTime = left.occurred_at ? Date.parse(left.occurred_at) : 0;
615
+ const rightTime = right.occurred_at ? Date.parse(right.occurred_at) : 0;
616
+ return leftTime - rightTime || left.id.localeCompare(right.id);
617
+ });
618
+ return boundNewest(merged, limits.activityItems, limits.activityBytes);
619
+ }
620
+ function boundNewest(values, maxItems, maxBytes) {
621
+ const kept = [];
622
+ let bytes = 2;
623
+ for (let index = values.length - 1; index >= 0 && kept.length < maxItems; index -= 1) {
624
+ const value = values[index];
625
+ const size = Buffer.byteLength(JSON.stringify(value), 'utf8') + (kept.length ? 1 : 0);
626
+ if (bytes + size > maxBytes)
627
+ break;
628
+ kept.push(value);
629
+ bytes += size;
630
+ }
631
+ kept.reverse();
632
+ return {
633
+ items: kept,
634
+ omitted: Math.max(0, values.length - kept.length),
635
+ bytes
636
+ };
637
+ }
638
+ function normalizeLimits(input = {}) {
639
+ return {
640
+ transcriptItems: boundedLimit(input.transcriptItems, TELEGRAM_CENTER_MAX_TRANSCRIPT_ITEMS, 1, 2_048),
641
+ activityItems: boundedLimit(input.activityItems, TELEGRAM_CENTER_MAX_ACTIVITY_ITEMS, 1, 2_048),
642
+ transcriptBytes: boundedLimit(input.transcriptBytes, TELEGRAM_CENTER_TRANSCRIPT_MAX_BYTES, 1_024, 640 * 1024),
643
+ activityBytes: boundedLimit(input.activityBytes, TELEGRAM_CENTER_ACTIVITY_MAX_BYTES, 1_024, 256 * 1024),
644
+ sourceTurns: boundedLimit(input.sourceTurns, MAX_SOURCE_TURNS, 1, 2_048),
645
+ sourceItems: boundedLimit(input.sourceItems, MAX_SOURCE_ITEMS, 1, 16_384)
646
+ };
647
+ }
648
+ function boundedLimit(value, fallback, min, max) {
649
+ return typeof value === 'number' && Number.isSafeInteger(value)
650
+ ? Math.max(min, Math.min(max, value))
651
+ : fallback;
652
+ }
653
+ function normalizeSortDirection(value) {
654
+ if (value === undefined || value === null || value === '')
655
+ return 'desc';
656
+ if (value === 'asc' || value === 'desc')
657
+ return value;
658
+ throw new Error('telegram_center_sort_direction_invalid');
659
+ }
660
+ function normalizeOpaqueCursor(value) {
661
+ if (value === undefined || value === null || value === '')
662
+ return null;
663
+ const cursor = typeof value === 'string' ? value : '';
664
+ if (!cursor
665
+ || Buffer.byteLength(cursor, 'utf8') > MAX_CURSOR_BYTES
666
+ || /[\u0000-\u001f\u007f]/.test(cursor)) {
667
+ throw new Error('telegram_center_cursor_invalid');
668
+ }
669
+ return cursor;
670
+ }
671
+ function publicOpaqueCursor(value) {
672
+ try {
673
+ return normalizeOpaqueCursor(value);
674
+ }
675
+ catch {
676
+ return null;
677
+ }
678
+ }
679
+ function publicThreadStatus(value) {
680
+ const record = asRecord(value);
681
+ return publicState(record?.type ?? value);
682
+ }
683
+ function publicState(value) {
684
+ const text = typeof value === 'string' ? value.trim() : '';
685
+ return text && /^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(text) ? text : 'unknown';
686
+ }
687
+ function publicStateOrNull(value) {
688
+ const state = publicState(value);
689
+ return state === 'unknown' ? null : state;
690
+ }
691
+ function publicId(value, maxLength) {
692
+ const text = typeof value === 'string' ? value.trim() : '';
693
+ return text && text.length <= maxLength && /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/.test(text) ? text : null;
694
+ }
695
+ function isoFromEpoch(value) {
696
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
697
+ return null;
698
+ const millis = value > 10_000_000_000 ? value : value * 1_000;
699
+ const date = new Date(millis);
700
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
701
+ }
702
+ function validIso(value) {
703
+ const text = typeof value === 'string' ? value : '';
704
+ return Number.isFinite(Date.parse(text)) ? new Date(text).toISOString() : null;
705
+ }
706
+ function publicInteger(value) {
707
+ return typeof value === 'number' && Number.isSafeInteger(value) ? value : null;
708
+ }
709
+ export async function createTelegramCenterCodexClient(cwd, dependencies = {}) {
710
+ const env = await (dependencies.prepareRuntimeEnv ?? prepareCodexAppServerRuntimeEnv)();
711
+ return (await (dependencies.createClient ?? createCodexAppServerV2Client)({
712
+ cwd,
713
+ env,
714
+ requestedBy: 'telegram-center-snapshot',
715
+ timeoutMs: 12_000
716
+ })).client;
717
+ }
718
+ const defaultCodexClientFactory = createTelegramCenterCodexClient;