store-port.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /**
  2. * `ThreadGoalStore` —— pluggable persistence interface. agent-core is
  3. * IO-free; concrete implementations live in host packages
  4. * (`local-runtime/SqliteThreadGoalStore`, future `cloud-runtime/…`).
  5. *
  6. * The store is the single source of truth for goal state. Tool impls,
  7. * the HTTP API, the orchestrator, and the UI projection all funnel
  8. * through this contract so SSE events can be derived from store writes
  9. * deterministically.
  10. */
  11. import type {
  12. GoalTurnBinding,
  13. LastVerificationV1,
  14. LastWorkerProposalV1,
  15. ThreadGoalAttachment,
  16. ThreadGoalState,
  17. ThreadGoalStatus,
  18. ThreadGoalStatusReason,
  19. } from './types.js';
  20. /**
  21. * Input for `create()`. The store assigns `goalId` / timestamps; callers
  22. * never pass them in. `tokenBudget` is the codex per-goal token cap —
  23. * `undefined` or `null` means "no cap" (the goal runs until the user
  24. * clears it or the model marks it complete).
  25. */
  26. export interface ThreadGoalCreateInput {
  27. readonly sessionId: string;
  28. readonly objective: string;
  29. readonly tokenBudget?: number | null;
  30. /** Immutable attachment snapshot for the first Goal Turn. */
  31. readonly kickoffAttachments?: readonly ThreadGoalAttachment[];
  32. readonly objectiveResources?: readonly ThreadGoalAttachment[];
  33. }
  34. /**
  35. * Input for `patch()`. `status`, `objective`, or `tokenBudget` may be
  36. * supplied in any combination. Implementations must update `updatedAt`
  37. * on every write. An explicit `tokenBudget: null` clears the cap — pass
  38. * `undefined` to leave it alone (`undefined` means "don't touch", `null`
  39. * means "remove").
  40. *
  41. * `rejectIfCurrentStatus` is an internal optimistic-concurrency guard for
  42. * model-authored status writes. Implementations must include it in the same
  43. * atomic write that applies the patch; a read-then-write check is insufficient
  44. * because the user may pause the goal between those operations.
  45. *
  46. * `rejectIfObjectiveChangedFrom` is the equivalent compare-and-set guard for
  47. * user-authored objective edits. A model status write must not complete the
  48. * replacement objective when it was generated against the previous text.
  49. *
  50. * `rejectIfUpdatedAtChangedFrom` guards model-authored budget edits with the
  51. * exact decision epoch returned by get_goal. It must participate in the same
  52. * write as the budget change and any token-limit recovery transition.
  53. */
  54. export interface ThreadGoalPatchInput {
  55. readonly status?: ThreadGoalStatus;
  56. readonly objective?: string;
  57. /** Omitted preserves resources; [] clears them with the replacement objective. */
  58. readonly objectiveResources?: readonly ThreadGoalAttachment[];
  59. readonly expectedGoalId?: string;
  60. readonly tokenBudget?: number | null;
  61. readonly statusReason?: ThreadGoalStatusReason | null;
  62. readonly rejectIfCurrentStatus?: ThreadGoalStatus;
  63. readonly rejectIfObjectiveChangedFrom?: string;
  64. readonly rejectIfUpdatedAtChangedFrom?: number;
  65. }
  66. export type ThreadGoalBudgetDimension = 'token' | 'main_turn' | 'active_time';
  67. export interface ThreadGoalBoundUsageDelta {
  68. readonly tokens: number;
  69. readonly activeSeconds: number;
  70. readonly mainTurns: 0 | 1;
  71. }
  72. export interface ThreadGoalBudgetLimits {
  73. readonly tokens: number | null;
  74. readonly mainTurns: number | null;
  75. readonly activeSeconds: number | null;
  76. }
  77. export type ThreadGoalBudgetCheckResult =
  78. | { readonly decision: 'allow' }
  79. | { readonly decision: 'steer'; readonly message: string }
  80. | { readonly decision: 'stop'; readonly message: string };
  81. export type ThreadGoalBoundUsageStaleReason = 'missing_goal' | 'goal_epoch' | 'objective_digest';
  82. /** Usage is still attributed when the bound Goal exists, even if stale. */
  83. export interface ThreadGoalBoundUsageResult {
  84. readonly goal?: ThreadGoalState;
  85. readonly decisionEpoch?: number;
  86. readonly transitioned?: ThreadGoalBudgetDimension | null;
  87. readonly staleReason?: ThreadGoalBoundUsageStaleReason;
  88. }
  89. export interface ThreadGoalSettleBoundTurnInput {
  90. readonly goalId: string;
  91. readonly expectedEpoch: number;
  92. readonly objectiveDigest: string;
  93. readonly next: {
  94. readonly status: Exclude<ThreadGoalStatus, 'active'>;
  95. readonly statusReason: ThreadGoalStatusReason;
  96. };
  97. /** Worker claim committed atomically with the host-owned decision. */
  98. readonly workerProposal?: ThreadGoalWorkerProposalInput;
  99. }
  100. export type ThreadGoalWorkerProposalInput = Pick<
  101. LastWorkerProposalV1,
  102. 'type' | 'turnId' | 'summary'
  103. >;
  104. export type ThreadGoalDecisionStaleReason = ThreadGoalBoundUsageStaleReason | 'goal_status';
  105. export type ThreadGoalDecisionResult =
  106. | {
  107. readonly status: 'settled';
  108. readonly goal: ThreadGoalState;
  109. readonly decisionEpoch: number;
  110. }
  111. | {
  112. readonly status: 'stale';
  113. readonly staleReason: ThreadGoalDecisionStaleReason;
  114. readonly goal?: ThreadGoalState;
  115. };
  116. export interface ThreadGoalRecordVerificationInput {
  117. readonly goalId: string;
  118. readonly expectedEpoch: number;
  119. readonly objectiveDigest: string;
  120. readonly result: LastVerificationV1;
  121. /** Runtime policy captured for this dispatch; config reloads apply on the next dispatch. */
  122. readonly repeatedNotMetLimit: number;
  123. /** Completion claim committed atomically with the verifier result. */
  124. readonly workerProposal?: ThreadGoalWorkerProposalInput;
  125. readonly decision?: {
  126. readonly status: Exclude<ThreadGoalStatus, 'active'>;
  127. readonly statusReason: ThreadGoalStatusReason;
  128. };
  129. }
  130. export interface ThreadGoalBoundStoreOperations {
  131. bumpBoundUsage(
  132. binding: GoalTurnBinding,
  133. delta: ThreadGoalBoundUsageDelta,
  134. limits: ThreadGoalBudgetLimits,
  135. ): Promise<ThreadGoalBoundUsageResult>;
  136. settleBoundTurn(input: ThreadGoalSettleBoundTurnInput): Promise<ThreadGoalDecisionResult>;
  137. recordVerification(input: ThreadGoalRecordVerificationInput): Promise<ThreadGoalDecisionResult>;
  138. }
  139. /**
  140. * What the settling Turn is known to have done with tools.
  141. *
  142. * `unknown` is NOT "zero tool calls": it means the host could not observe the
  143. * committed history for this Turn, so the no-tool streak must reset instead of
  144. * letting an observation gap be stitched into a consecutive run.
  145. */
  146. export type ThreadGoalToolActivity = 'used' | 'absent' | 'unknown';
  147. export interface ThreadGoalBreakerInput {
  148. /** Goal epoch captured after this Turn's accounting write. */
  149. readonly expectedEpoch: number;
  150. /**
  151. * sha256 of the normalized final main-worker reply, or `null` when this Turn
  152. * produced no usable reply text. `null` leaves the persisted fingerprint and
  153. * repeated-reply streak untouched — an empty reply may not silence the
  154. * independent no-tool condition.
  155. */
  156. readonly fingerprint: string | null;
  157. /** Tool activity observed for this Turn; drives the no-tool condition. */
  158. readonly toolActivity: ThreadGoalToolActivity;
  159. /** Shared limit: consecutive identical replies OR consecutive tool-less turns that pause the Goal. */
  160. readonly limit: number;
  161. /** Durable reason selected when a no-progress pause overrides a completion claim. */
  162. readonly pauseReason?: Extract<
  163. ThreadGoalStatusReason,
  164. 'paused(no_progress)' | 'paused(no_progress_after_completion_claim)'
  165. >;
  166. }
  167. /** Which independent breaker condition produced the decided action. */
  168. export type ThreadGoalBreakerCause = 'repeated_reply' | 'no_tool';
  169. export type ThreadGoalBreakerStaleReason = 'missing_goal' | 'goal_epoch' | 'goal_status';
  170. export type ThreadGoalBreakerResult =
  171. | {
  172. readonly action: 'none' | 'nudge' | 'pause';
  173. readonly goal: ThreadGoalState;
  174. readonly epoch: number;
  175. /** Absent when `action` is `none`. */
  176. readonly cause?: ThreadGoalBreakerCause;
  177. }
  178. | {
  179. readonly action: 'stale';
  180. readonly staleReason: ThreadGoalBreakerStaleReason;
  181. readonly goal?: ThreadGoalState;
  182. };
  183. export interface ThreadGoalStore {
  184. /**
  185. * Return the current goal for `sessionId`, or `undefined` if none exists.
  186. * Implementations must return a fresh value on each call — callers must
  187. * not mutate the returned record.
  188. */
  189. getBySession(sessionId: string): Promise<ThreadGoalState | undefined>;
  190. /**
  191. * Return a goal by its opaque `goalId`, or `undefined` if not found.
  192. * Used by the REST API path `GET /goal/:goalId`.
  193. */
  194. getById(goalId: string): Promise<ThreadGoalState | undefined>;
  195. /**
  196. * Create a new goal for `sessionId` with `status: 'active'`.
  197. *
  198. * Mirrors codex `insert_thread_goal` (`ON CONFLICT … WHERE
  199. * status = 'complete'`): an existing goal is silently replaced ONLY
  200. * when it is `complete`. Any other status — `active`, `paused`,
  201. * `blocked`, `budget_limited` — counts as unfinished and
  202. * implementations MUST throw `ThreadGoalAlreadyExistsError`; the
  203. * caller (tool impl or HTTP route) decides how to surface the
  204. * rejection.
  205. *
  206. * Returns the freshly created record (with assigned `goalId`,
  207. * `createdAt`, `updatedAt`, `status: 'active'`, and the optional
  208. * `tokenBudget` from `input`).
  209. */
  210. create(input: ThreadGoalCreateInput): Promise<ThreadGoalState>;
  211. /**
  212. * Apply a partial update to the goal identified by `goalId`. Throws if
  213. * the goal does not exist. Returns the updated record.
  214. */
  215. patch(goalId: string, input: ThreadGoalPatchInput): Promise<ThreadGoalState>;
  216. /**
  217. * Compare-and-set the durable repeated-reply breaker for an active Goal.
  218. * Implementations must update fingerprint, streak, epoch, and an optional
  219. * no-progress transition in one short transaction.
  220. */
  221. updateBreaker(goalId: string, input: ThreadGoalBreakerInput): Promise<ThreadGoalBreakerResult>;
  222. /**
  223. * Persist the latest verifier result and any verifier-owned terminal decision
  224. * through the same active-Goal compare-and-set.
  225. */
  226. recordVerification(input: ThreadGoalRecordVerificationInput): Promise<ThreadGoalDecisionResult>;
  227. /**
  228. * Delete the goal by `goalId`. No-op if it does not exist.
  229. */
  230. delete(goalId: string): Promise<void>;
  231. }
  232. /**
  233. * Sentinel error thrown by `create()` when an unfinished goal (any
  234. * status other than `complete`) already exists for the session. Hosts
  235. * can pattern-match on `instanceof` to map it to HTTP 409 or the
  236. * codex-verbatim tool rejection text.
  237. */
  238. export class ThreadGoalAlreadyExistsError extends Error {
  239. readonly existingGoalId: string;
  240. constructor(existingGoalId: string) {
  241. super(`Unfinished thread goal already exists (goalId=${existingGoalId}).`);
  242. this.name = 'ThreadGoalAlreadyExistsError';
  243. this.existingGoalId = existingGoalId;
  244. }
  245. }
  246. /**
  247. * Raised when a patch observes a status it may not move away from. The
  248. * model-facing tool sets an explicit guard status and maps this to a normal
  249. * tool rejection; a user-authored PATCH hits it only on a transition the
  250. * surface refuses outright, `complete` back to `active` among them.
  251. */
  252. export class ThreadGoalStatusConflictError extends Error {
  253. constructor(
  254. readonly goalId: string,
  255. readonly currentStatus: ThreadGoalStatus,
  256. ) {
  257. super(`Thread goal status conflict (goalId=${goalId}, currentStatus=${currentStatus}).`);
  258. this.name = 'ThreadGoalStatusConflictError';
  259. }
  260. }
  261. /** Raised when a guarded model status write observes a newer objective. */
  262. export class ThreadGoalObjectiveConflictError extends Error {
  263. constructor(
  264. readonly goalId: string,
  265. readonly expectedObjective: string,
  266. readonly currentObjective: string,
  267. ) {
  268. super(`Thread goal objective conflict (goalId=${goalId}).`);
  269. this.name = 'ThreadGoalObjectiveConflictError';
  270. }
  271. }
  272. /** Raised when a budget-exhausted Goal is explicitly rearmed. */
  273. export class ThreadGoalBudgetLimitedError extends Error {
  274. readonly code = 'GOAL_BUDGET_LIMITED';
  275. constructor(readonly goalId: string) {
  276. super(`Budget-limited thread goal cannot be resumed (goalId=${goalId}).`);
  277. this.name = 'ThreadGoalBudgetLimitedError';
  278. }
  279. }
  280. /** Raised when a token cap would already be exhausted by accounted usage. */
  281. export class ThreadGoalTokenBudgetExhaustedError extends Error {
  282. readonly code = 'GOAL_TOKEN_BUDGET_EXHAUSTED';
  283. constructor(
  284. readonly goalId: string,
  285. readonly tokensUsed: number,
  286. readonly tokenBudget: number,
  287. ) {
  288. super(
  289. `Token budget must exceed accounted usage (goalId=${goalId}, tokensUsed=${tokensUsed}, tokenBudget=${tokenBudget}).`,
  290. );
  291. this.name = 'ThreadGoalTokenBudgetExhaustedError';
  292. }
  293. }
  294. /** Raised when a guarded write no longer matches the Goal decision epoch. */
  295. export class ThreadGoalEpochConflictError extends Error {
  296. readonly code = 'GOAL_EPOCH_CONFLICT';
  297. constructor(
  298. readonly goalId: string,
  299. readonly expectedUpdatedAt: number,
  300. readonly currentUpdatedAt: number,
  301. ) {
  302. super(`Thread goal decision epoch changed (goalId=${goalId}).`);
  303. this.name = 'ThreadGoalEpochConflictError';
  304. }
  305. }