global-events.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import type { AskQuestionnaireRequest } from "./questionnaire.js";
  2. import type { SessionLLMRetryEventPayload } from "./llm-retry-event.js";
  3. // Contract admission rules: ./global-events/README.md
  4. export const GLOBAL_EVENT_TYPES = [
  5. "agent.created",
  6. "agent.updated",
  7. "session.created",
  8. "session.visibility_updated",
  9. "session.deleted",
  10. "session.pinned_updated",
  11. "session.title_updated",
  12. "session.model_updated",
  13. "session.interaction_mode.changed",
  14. "session.start",
  15. "session.finish",
  16. "session.error",
  17. "session.abort",
  18. "session.queue.updated",
  19. "session.compaction.started",
  20. "session.compaction.completed",
  21. "session.compaction.failed",
  22. "session.llm_retry",
  23. "permission.ask",
  24. "permission.resolved",
  25. "config.permission_mode.changed",
  26. "config.browser_use_tooling.changed",
  27. "questionnaire.ask",
  28. "questionnaire.dismiss",
  29. "questionnaire.superseded",
  30. "message.rewind",
  31. "notification.read",
  32. "notification.refresh",
  33. "content.retry.exceeded",
  34. "rotation.completed",
  35. "thread_goal.updated",
  36. "thread_goal.cleared",
  37. "thread_goal.objective_updated_steering",
  38. "workspace.git.changed",
  39. ] as const satisfies readonly (keyof GlobalEventPayloadMap)[];
  40. export type GlobalEventType = keyof GlobalEventPayloadMap;
  41. export interface CompactionTokenUsage {
  42. inputTokens: number;
  43. outputTokens: number;
  44. cacheReadTokens: number;
  45. cacheWriteTokens: number;
  46. totalTokens: number;
  47. incomplete: boolean;
  48. }
  49. /** Correlated event name + payload emitted by backend product-event producers. */
  50. export type GlobalEventInput<Type extends GlobalEventType = GlobalEventType> = {
  51. [EventType in Type]: {
  52. type: EventType;
  53. payload: GlobalEventPayloadMap[EventType];
  54. };
  55. }[Type];
  56. type SessionStartSource =
  57. | "queued-drain"
  58. | "background-task-delivery"
  59. | "subagent-headless-turn";
  60. type SessionTerminalSource =
  61. | "background-task-delivery"
  62. | "subagent-headless-turn";
  63. type SessionTerminalPayload<
  64. Status extends "finished" | "error" | "aborted" | "interrupted",
  65. > = {
  66. sessionId: string;
  67. agentName: string;
  68. turnId: string;
  69. status: Status;
  70. taskId?: string;
  71. source?: SessionTerminalSource;
  72. date?: string;
  73. error?: string;
  74. errorCode?: number;
  75. errorSource?: string;
  76. errorDetail?: string;
  77. errorProviderId?: string;
  78. };
  79. export type GlobalThreadGoalStatusReason =
  80. | "complete(worker_proposal)"
  81. | "complete(verifier_met)"
  82. | "complete(user_requested)"
  83. | "paused(user_requested)"
  84. | "paused(retracted)"
  85. | "paused(infra_retryable)"
  86. | "paused(accounting_unavailable)"
  87. | "paused(verifier_unavailable)"
  88. | "paused(route_unavailable)"
  89. | "paused(verifier_timeout)"
  90. | "paused(verifier_protocol)"
  91. | "paused(verifier_runtime)"
  92. | "paused(verifier_budget)"
  93. | "paused(verifier_capability)"
  94. | "paused(verifier_aborted)"
  95. | "paused(no_progress)"
  96. | "paused(no_progress_after_completion_claim)"
  97. | "blocked(worker_reported)"
  98. | "blocked(safety_policy)"
  99. | "blocked(verifier_impossible)"
  100. | "budget_limited(token)"
  101. | "budget_limited(main_turn)"
  102. | "budget_limited(active_time)"
  103. | "usage_limited(provider_quota)"
  104. | "usage_limited(rate_limit)";
  105. /** Why an `active` Goal has not started its next Turn. Mirrors `ThreadGoalWaitReason`. */
  106. export type GlobalThreadGoalWaitReason =
  107. | "questionnaire"
  108. | "permission"
  109. | "plan"
  110. | "required_background"
  111. | "automation_owner_conflict"
  112. | "dependency_unavailable"
  113. | "verification"
  114. | "unknown";
  115. export type GlobalThreadGoal = {
  116. goalId: string;
  117. sessionId: string;
  118. objective: string;
  119. status:
  120. | "active"
  121. | "paused"
  122. | "blocked"
  123. | "complete"
  124. | "budget_limited"
  125. | "usage_limited";
  126. createdAt: number;
  127. updatedAt: number;
  128. tokensUsed: number;
  129. turnsUsed: number;
  130. timeUsedSeconds: number;
  131. tokenBudget: number | null;
  132. statusReason: GlobalThreadGoalStatusReason | null;
  133. lastVerification?: {
  134. backend: "evaluator" | "subagent";
  135. verdict: "met" | "not_met" | "impossible" | "inconclusive";
  136. reason: string;
  137. missing: string[];
  138. notMetStreak: number;
  139. at: number;
  140. };
  141. hasKickoffAttachments: boolean;
  142. /**
  143. * Why an `active` Goal is not running yet; `null`/absent when unblocked.
  144. * Orthogonal to `status`; follows the local Goal execution state.
  145. */
  146. executionWait?: {
  147. reason: GlobalThreadGoalWaitReason;
  148. sinceMs: number;
  149. } | null;
  150. };
  151. /** Closed catalog of product events exchanged between the runtime and its frontends. */
  152. export type GlobalEventPayloadMap = {
  153. "agent.created": { agentName: string };
  154. "agent.updated": {
  155. agentName: string;
  156. agentId?: string;
  157. change?: "updated";
  158. };
  159. "session.created": {
  160. sessionId: string;
  161. agentName: string;
  162. sessionType: "root" | "branch";
  163. sessionKind?: string;
  164. visibility?: "visible" | "hidden";
  165. title?: string | null;
  166. parentSessionId?: string | null;
  167. };
  168. "session.visibility_updated": {
  169. sessionId: string;
  170. agentName?: string;
  171. visibility: "visible" | "hidden";
  172. };
  173. "session.deleted": { sessionId: string; agentName?: string };
  174. "session.pinned_updated": {
  175. sessionId: string;
  176. agentName?: string;
  177. pinned: boolean;
  178. };
  179. "session.title_updated": {
  180. sessionId: string;
  181. agentName?: string;
  182. title: string;
  183. };
  184. "session.model_updated": {
  185. /** Omitted for a committed global-default selection. */
  186. sessionId?: string;
  187. agentName?: string;
  188. providerId: string;
  189. modelId: string;
  190. variant?: string | null;
  191. thinking?: { effort?: string } | null;
  192. contextLimit?: number | null;
  193. };
  194. "session.interaction_mode.changed": {
  195. sessionId: string;
  196. interactionMode: "default" | "plan" | "goal";
  197. };
  198. "session.start": {
  199. sessionId: string;
  200. agentName: string;
  201. turnId?: string;
  202. taskId?: string;
  203. source?: SessionStartSource;
  204. queueItemIds?: string[];
  205. };
  206. "session.finish": SessionTerminalPayload<"finished">;
  207. "session.error": SessionTerminalPayload<"error">;
  208. "session.abort": SessionTerminalPayload<"aborted" | "interrupted">;
  209. "session.queue.updated": {
  210. sessionId: string;
  211. itemId?: string;
  212. status?:
  213. | "queued"
  214. | "running"
  215. | "completed"
  216. | "failed"
  217. | "expired"
  218. | "cancelled"
  219. | "injected"
  220. | "accepted"
  221. | "composer-transferred"
  222. | "admission-rejected";
  223. failedReason?: string;
  224. queuedCount?: number;
  225. source?: string;
  226. clientRequestId?: string;
  227. reason?:
  228. | "enqueued"
  229. | "cancelled"
  230. | "expired"
  231. | "accepted"
  232. | "injected"
  233. | "composer-transferred"
  234. | "admission-rejected";
  235. admissionReason?:
  236. | `policy:${string}`
  237. | "invalid-session"
  238. | "unsupported-runtime"
  239. | "ingress-conflict"
  240. | "duplicate-ingress";
  241. /** Optional structured rejection details; not a Session lifecycle error. */
  242. errorSource?: string;
  243. error?: string;
  244. };
  245. "session.compaction.started": { sessionId: string; compactionId: string };
  246. "session.compaction.completed": {
  247. sessionId: string;
  248. compactionId: string;
  249. messagesBefore: number;
  250. messagesAfter: number;
  251. tokensBefore: number;
  252. tokensAfter: number;
  253. tokenUsage?: CompactionTokenUsage;
  254. };
  255. "session.compaction.failed": {
  256. sessionId: string;
  257. compactionId: string;
  258. tokenUsage?: CompactionTokenUsage;
  259. };
  260. "session.llm_retry": SessionLLMRetryEventPayload;
  261. "permission.ask": {
  262. requestId: string;
  263. sessionId: string;
  264. /** Turn that produced this ask. Missing only on historical/external events. */
  265. turnId?: string;
  266. agentName: string;
  267. toolName: string;
  268. ruleContents: string[];
  269. toolInput?: string;
  270. toolDescription?: string;
  271. reason: string;
  272. allowAlwaysSupported: boolean;
  273. createdAt: number;
  274. };
  275. "permission.resolved": {
  276. requestId: string;
  277. sessionId: string;
  278. decision: "allowAlways" | "allowOnce" | "deny";
  279. };
  280. "config.permission_mode.changed": {
  281. permissionMode:
  282. | "default"
  283. | "acceptEdits"
  284. | "bypassPermissions"
  285. | "auto"
  286. | "off";
  287. };
  288. "config.browser_use_tooling.changed": { browserUseTooling: boolean };
  289. "questionnaire.ask": {
  290. requestId: string;
  291. sessionId: string;
  292. agentName?: string;
  293. request: AskQuestionnaireRequest;
  294. };
  295. "questionnaire.dismiss": {
  296. requestId: string;
  297. sessionId: string;
  298. agentName?: string;
  299. status: "answered" | "dismissed";
  300. };
  301. "questionnaire.superseded": {
  302. requestId: string;
  303. sessionId: string;
  304. agentName?: string;
  305. keepRequestId: string;
  306. supersededAt: number;
  307. };
  308. "message.rewind": { sessionId: string; contextReset?: boolean };
  309. "notification.read": {
  310. notification_id: string;
  311. read_at_ms: number;
  312. };
  313. "notification.refresh": {
  314. scope: "user" | "biz";
  315. reason:
  316. | "direct_created"
  317. | "broadcast_created"
  318. | "revoked"
  319. | "mark_all_read";
  320. };
  321. "content.retry.exceeded": {
  322. sessionId: string;
  323. variant: "content" | "network" | "auth";
  324. lastUserMsgId?: string;
  325. };
  326. "rotation.completed": {
  327. agentName: string;
  328. oldSessionId: string;
  329. newSessionId: string;
  330. reason: string;
  331. };
  332. "thread_goal.updated": { goal: GlobalThreadGoal };
  333. "thread_goal.cleared": { sessionId: string; goalId: string };
  334. "thread_goal.objective_updated_steering": {
  335. sessionId: string;
  336. goalId: string;
  337. };
  338. "workspace.git.changed": {
  339. /** Canonical realpath owned by the Runtime snapshot manager. */
  340. workspace: string;
  341. /** Caller-visible spellings that share the canonical snapshot. */
  342. aliases?: string[];
  343. snapshotId: string;
  344. kind: "workspace" | "repository";
  345. reason: "watcher" | "watcher-error" | "mutation" | "manual";
  346. };
  347. };
  348. type AssertNever<Value extends never> = Value;
  349. type GlobalEventCatalogMissingTypeMustBeNever = AssertNever<
  350. Exclude<GlobalEventType, (typeof GLOBAL_EVENT_TYPES)[number]>
  351. >;
  352. type GlobalEventFor<Type extends GlobalEventType> = {
  353. type: Type;
  354. timestamp: number;
  355. source: "local-runtime";
  356. payload: GlobalEventPayloadMap[Type];
  357. };
  358. export type GlobalEvent = {
  359. [Type in GlobalEventType]: GlobalEventFor<Type>;
  360. }[GlobalEventType] &
  361. ([GlobalEventCatalogMissingTypeMustBeNever] extends [never]
  362. ? unknown
  363. : never);
  364. export type DecodedGlobalEventFrame =
  365. | { kind: "heartbeat"; timestamp: number }
  366. | { kind: "event"; event: GlobalEvent };
  367. const GLOBAL_EVENT_TYPE_SET: ReadonlySet<string> = new Set(GLOBAL_EVENT_TYPES);
  368. export function isGlobalEventType(value: unknown): value is GlobalEventType {
  369. return typeof value === "string" && GLOBAL_EVENT_TYPE_SET.has(value);
  370. }
  371. /** Decode the generated Thrift/SSE frame without duplicating every payload schema at runtime. */
  372. export function decodeGlobalEventFrame(
  373. frame: unknown,
  374. ): DecodedGlobalEventFrame | undefined {
  375. if (!isRecord(frame) || !isTimestamp(frame.timestamp)) return undefined;
  376. if (frame.kind === "heartbeat") {
  377. return { kind: "heartbeat", timestamp: frame.timestamp };
  378. }
  379. if (
  380. frame.kind !== "event" ||
  381. frame.source !== "local-runtime" ||
  382. !isGlobalEventType(frame.type) ||
  383. typeof frame.payloadJson !== "string"
  384. ) {
  385. return undefined;
  386. }
  387. let payload: unknown;
  388. try {
  389. payload = JSON.parse(frame.payloadJson);
  390. } catch {
  391. return undefined;
  392. }
  393. if (!isRecord(payload)) return undefined;
  394. return {
  395. kind: "event",
  396. event: {
  397. type: frame.type,
  398. timestamp: frame.timestamp,
  399. source: "local-runtime",
  400. payload,
  401. } as GlobalEvent,
  402. };
  403. }
  404. function isRecord(value: unknown): value is Record<string, unknown> {
  405. return typeof value === "object" && value !== null && !Array.isArray(value);
  406. }
  407. function isTimestamp(value: unknown): value is number {
  408. return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
  409. }