deepline 0.3.533 → 0.3.535

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 (173) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +68 -7
  2. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  3. package/dist/bundling-sources/shared_libs/play-runtime/call-requeue-state-machine.ts +420 -0
  4. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +677 -26
  5. package/dist/bundling-sources/shared_libs/play-runtime/ctx-types.ts +26 -0
  6. package/dist/bundling-sources/shared_libs/play-runtime/durable-retry-policy.ts +624 -0
  7. package/dist/bundling-sources/shared_libs/play-runtime/execution-capabilities.ts +26 -0
  8. package/dist/bundling-sources/shared_libs/play-runtime/freshness-receipt-execution.ts +32 -14
  9. package/dist/bundling-sources/shared_libs/play-runtime/governor/governor.ts +51 -1
  10. package/dist/bundling-sources/shared_libs/play-runtime/internal-bootstrap-token.ts +9 -0
  11. package/dist/bundling-sources/shared_libs/play-runtime/map-memory-limits.ts +245 -1
  12. package/dist/bundling-sources/shared_libs/play-runtime/output-size-limits.ts +21 -0
  13. package/dist/bundling-sources/shared_libs/play-runtime/provider-no-progress.ts +6 -2
  14. package/dist/bundling-sources/shared_libs/play-runtime/resource-governor.ts +10 -0
  15. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-tool-hooks.ts +55 -0
  16. package/dist/bundling-sources/shared_libs/play-runtime/runtime-authority.ts +8 -0
  17. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +21 -0
  18. package/dist/bundling-sources/shared_libs/play-runtime/tool-cache-policy.ts +12 -1
  19. package/dist/bundling-sources/shared_libs/play-runtime/tool-execute-retry-policy.ts +6 -0
  20. package/dist/bundling-sources/shared_libs/play-runtime/workflow-executor-auth.ts +2 -0
  21. package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +101 -0
  22. package/dist/bundling-sources/shared_libs/plays/share/static-pipeline-summary.ts +63 -13
  23. package/dist/cli/auth-VDCU3T6A.js +43 -0
  24. package/dist/cli/{auth-2TZNPIJQ.mjs → auth-ZCTMB5RA.mjs} +5 -5
  25. package/dist/cli/{billing-HQYTRIV3.js → billing-GVFKZQH3.js} +82 -82
  26. package/dist/cli/{billing-LR4WJIHO.mjs → billing-OU2ZHL72.mjs} +7 -7
  27. package/dist/cli/{chunk-HOTJSXLY.js → chunk-243O3FH5.js} +5 -5
  28. package/dist/cli/{chunk-TU56J4OV.js → chunk-2D6SWQTK.js} +13 -13
  29. package/dist/cli/{chunk-4YP2YAIZ.js → chunk-4NLRWKZB.js} +26 -26
  30. package/dist/cli/{chunk-NW736SOD.mjs → chunk-4QELPWUW.mjs} +2 -2
  31. package/dist/cli/{chunk-LTF2J3JM.js → chunk-5EKNDNFQ.js} +2 -2
  32. package/dist/cli/{chunk-VPQDKL5O.js → chunk-6LHX33VN.js} +6 -6
  33. package/dist/cli/{chunk-LZMRCUVD.mjs → chunk-6TYRRNXY.mjs} +2 -2
  34. package/dist/cli/{chunk-YZK5RSUL.mjs → chunk-7CWSAEYS.mjs} +1 -1
  35. package/dist/cli/{chunk-A4JP6RPX.js → chunk-7PXP2FQK.js} +2 -2
  36. package/dist/cli/{chunk-2TMNRF5R.mjs → chunk-7R5DAANG.mjs} +1 -1
  37. package/dist/cli/{chunk-NKVW552R.mjs → chunk-AUEUAPVS.mjs} +1 -1
  38. package/dist/cli/{chunk-3KQBV2CG.mjs → chunk-BF65LB7X.mjs} +3 -3
  39. package/dist/cli/{chunk-33SNTG5F.js → chunk-CIDATNTY.js} +16 -16
  40. package/dist/cli/{chunk-O7RSUW75.js → chunk-D4MHCCIR.js} +4 -4
  41. package/dist/cli/{chunk-5XTXC45Z.js → chunk-DAPKLYST.js} +41 -41
  42. package/dist/cli/{chunk-USAQ42OG.mjs → chunk-DFJODFMC.mjs} +5 -5
  43. package/dist/cli/{chunk-KKUOIVQO.mjs → chunk-DWPY6ZID.mjs} +1 -1
  44. package/dist/cli/{chunk-MNAEALPG.js → chunk-DYIWDUY4.js} +182 -127
  45. package/dist/cli/{chunk-EVXRQXNV.mjs → chunk-E3CLOVG5.mjs} +47 -0
  46. package/dist/cli/{chunk-SVVUC3B4.js → chunk-FGN75ZN6.js} +138 -104
  47. package/dist/cli/{chunk-XZN3DBTP.mjs → chunk-FZKPPB5P.mjs} +40 -6
  48. package/dist/cli/{chunk-NFDYVMGC.mjs → chunk-G2DLG32W.mjs} +68 -13
  49. package/dist/cli/{chunk-LZ3PBEQH.mjs → chunk-H6SWS5CG.mjs} +2 -2
  50. package/dist/cli/{chunk-EYWES7F5.js → chunk-HWPOXCCK.js} +3 -3
  51. package/dist/cli/{chunk-425ERNBL.js → chunk-HYBZWSSH.js} +44 -44
  52. package/dist/cli/{chunk-CANHB6DH.mjs → chunk-J75DANZY.mjs} +2 -2
  53. package/dist/cli/{chunk-CWIGRIIX.mjs → chunk-JQQG4QL4.mjs} +3 -3
  54. package/dist/cli/{chunk-2UYERVXF.mjs → chunk-JWWYLGUT.mjs} +2 -2
  55. package/dist/cli/{chunk-735ZOYQN.js → chunk-K3IPGMGP.js} +11 -11
  56. package/dist/cli/{chunk-VKGNQC2S.mjs → chunk-K53NKWZO.mjs} +5 -5
  57. package/dist/cli/{chunk-3O3AL5RI.mjs → chunk-K76AEBFY.mjs} +4 -4
  58. package/dist/cli/{chunk-BWZHMWM5.js → chunk-KA6ZERJL.js} +6 -6
  59. package/dist/cli/{chunk-4CYNH47Y.js → chunk-KOZBZPRM.js} +53 -53
  60. package/dist/cli/{chunk-QZWURUBP.js → chunk-KWGXHPHL.js} +7 -7
  61. package/dist/cli/{chunk-XUX5KGCQ.mjs → chunk-LVISZFYO.mjs} +2 -2
  62. package/dist/cli/{chunk-B4ZNWXUW.js → chunk-OM732MGV.js} +9 -9
  63. package/dist/cli/{chunk-352XVCGE.js → chunk-PHLNYBAA.js} +5 -5
  64. package/dist/cli/{chunk-ZH5HCAN3.js → chunk-PI5R65OQ.js} +1 -1
  65. package/dist/cli/{chunk-JZ7LJS3P.mjs → chunk-QYBAHYP4.mjs} +6 -6
  66. package/dist/cli/{chunk-G3GJ3IGU.mjs → chunk-R2KKEHJN.mjs} +5 -5
  67. package/dist/cli/{chunk-R7YDZSN7.js → chunk-RFQWSH6I.js} +3 -3
  68. package/dist/cli/{chunk-MKUYZ7LR.mjs → chunk-RKY4LBX3.mjs} +1 -1
  69. package/dist/cli/{chunk-WF652G74.js → chunk-T7RBM2WX.js} +14 -14
  70. package/dist/cli/{chunk-G3RVDRYL.mjs → chunk-TCVCFZP6.mjs} +1 -1
  71. package/dist/cli/{chunk-E4VWBU2E.js → chunk-UUQ2OXMH.js} +16 -16
  72. package/dist/cli/{chunk-IETLUG4C.mjs → chunk-W5YJYU4G.mjs} +1 -1
  73. package/dist/cli/{chunk-HPOVAUQF.mjs → chunk-W6T23EUC.mjs} +1 -1
  74. package/dist/cli/{chunk-BSI7UHQZ.mjs → chunk-WAIBM6KX.mjs} +5 -5
  75. package/dist/cli/{chunk-4UADZTU5.js → chunk-WNNA4L6Z.js} +22 -22
  76. package/dist/cli/{chunk-V6LUMGVI.js → chunk-XSOTEVOB.js} +47 -0
  77. package/dist/cli/{chunk-PIACHLYY.mjs → chunk-YFZLZNTH.mjs} +2 -2
  78. package/dist/cli/{chunk-274Y66HP.js → chunk-ZUVE63Y7.js} +2 -2
  79. package/dist/cli/command-docs.js +2 -2
  80. package/dist/cli/command-docs.mjs +1 -1
  81. package/dist/cli/{csv-MBSCHS4H.js → csv-CD55KEIO.js} +13 -13
  82. package/dist/cli/{csv-CJKKHGNQ.mjs → csv-CLPVMIRF.mjs} +4 -4
  83. package/dist/cli/{db-EAFR6N45.mjs → db-AU4SMWUN.mjs} +6 -6
  84. package/dist/cli/{db-45HNPCY3.js → db-MQKLDAEO.js} +27 -27
  85. package/dist/cli/describe-5BFNHT5V.js +50 -0
  86. package/dist/cli/{describe-IXW3LDGC.mjs → describe-AWJUXE2U.mjs} +18 -18
  87. package/dist/cli/describe-core.d.mts +3 -3
  88. package/dist/cli/describe-core.d.ts +3 -3
  89. package/dist/cli/{executions-SZAES2S4.js → executions-77GOLWRM.js} +8 -8
  90. package/dist/cli/{executions-ZATZV7O6.mjs → executions-TFIJPUX7.mjs} +6 -6
  91. package/dist/cli/{feedback-NY63KEK2.mjs → feedback-2WRSZ5WL.mjs} +6 -6
  92. package/dist/cli/{feedback-KXLF4GR4.js → feedback-OV5YAL3A.js} +14 -14
  93. package/dist/cli/git-HGMX52XU.js +25 -0
  94. package/dist/cli/{git-BSSSTR6N.mjs → git-VNS4ATLZ.mjs} +5 -5
  95. package/dist/cli/index.js +145 -145
  96. package/dist/cli/index.mjs +44 -44
  97. package/dist/cli/{legacy-noops-CYF6DJBF.mjs → legacy-noops-C732QDCY.mjs} +6 -6
  98. package/dist/cli/{legacy-noops-XQANGML3.js → legacy-noops-HDOB5C6F.js} +9 -9
  99. package/dist/cli/{monitors-ABJVLWIP.mjs → monitors-2LYEFXOU.mjs} +7 -7
  100. package/dist/cli/{monitors-F3PTNP45.js → monitors-5IUMHH3E.js} +100 -100
  101. package/dist/cli/{org-WQAPZI5Q.js → org-ADW2EVAC.js} +86 -86
  102. package/dist/cli/{org-BHF6Y5R7.mjs → org-G4YGZPHS.mjs} +6 -6
  103. package/dist/cli/{pages-W4HWVJUG.mjs → pages-KXKWSCEV.mjs} +6 -6
  104. package/dist/cli/{pages-U3EJ2NPL.js → pages-VTJGAI2D.js} +18 -18
  105. package/dist/cli/{play-3T4X3ZKH.mjs → play-7GQ56C2D.mjs} +69 -22
  106. package/dist/cli/{play-2UHKONON.js → play-EHSOSSHT.js} +367 -320
  107. package/dist/cli/{providers-LUK5LIUA.js → providers-PWCF6OOO.js} +9 -9
  108. package/dist/cli/{providers-2G2VTNDG.mjs → providers-WL3YTCSV.mjs} +6 -6
  109. package/dist/cli/{quickstart-XP4PJZ7N.mjs → quickstart-323XOPGI.mjs} +4 -4
  110. package/dist/cli/{quickstart-76P6PGID.js → quickstart-ZKI5MURA.js} +6 -6
  111. package/dist/cli/{run-S2KHGBCM.js → run-XZPWA6JS.js} +41 -41
  112. package/dist/cli/{run-ACIHA53A.mjs → run-ZCNZU3K2.mjs} +23 -23
  113. package/dist/cli/{search-VFIJCUZL.mjs → search-CVLVSFMJ.mjs} +8 -8
  114. package/dist/cli/search-J6EY7DQN.js +33 -0
  115. package/dist/cli/{search-output-2KFLZS5F.mjs → search-output-6PY6RN2R.mjs} +4 -4
  116. package/dist/cli/{search-output-GV7NNB4X.js → search-output-7HRSSRBS.js} +6 -6
  117. package/dist/cli/{secrets-MAQLBVC4.mjs → secrets-6S2ZWDIM.mjs} +6 -6
  118. package/dist/cli/{secrets-KJSFEW2F.js → secrets-IYD5VKY4.js} +15 -15
  119. package/dist/cli/sessions-7HPIVSQ4.js +22 -0
  120. package/dist/cli/{sessions-G5MWNJ75.mjs → sessions-GVEX5TUJ.mjs} +6 -6
  121. package/dist/cli/{settings-MR6UFOK5.mjs → settings-BN5MJZ3C.mjs} +13 -13
  122. package/dist/cli/{settings-VXGRPFXP.js → settings-CANK4HJQ.js} +86 -86
  123. package/dist/cli/{setup-ZOBXMONM.mjs → setup-JNMSCCU4.mjs} +10 -10
  124. package/dist/cli/{setup-C74BRK7N.js → setup-YSGKGLSJ.js} +50 -50
  125. package/dist/cli/{skills-4CG3MHOY.mjs → skills-QCQN2UM2.mjs} +8 -8
  126. package/dist/cli/skills-WDGSSKJZ.js +37 -0
  127. package/dist/cli/{tools-YXCXZ4ZD.mjs → tools-CDPOID7V.mjs} +17 -17
  128. package/dist/cli/tools-URNVXSTZ.js +57 -0
  129. package/dist/cli/{update-Z3C5W3I4.mjs → update-D3ZERUQ3.mjs} +10 -10
  130. package/dist/cli/update-Q6JW32IA.js +35 -0
  131. package/dist/cli/{views-XGP2GZ52.js → views-4NV2KQKA.js} +18 -18
  132. package/dist/cli/{views-45B2FZQT.mjs → views-RDZRWQBQ.mjs} +6 -6
  133. package/dist/cli/{workflow-KQRWSNBH.mjs → workflow-2CG3TVCG.mjs} +7 -7
  134. package/dist/cli/{workflow-DWO35XHZ.js → workflow-RABJCAZC.js} +17 -17
  135. package/dist/{client-Bd2meveV.d.mts → client-DhSvMO3A.d.mts} +1 -1
  136. package/dist/{client-core-CGj8V9mw.d.mts → client-core-CVG1Et-4.d.mts} +41 -2
  137. package/dist/{client-core-CsRRWCFy.d.ts → client-core-CdWH6Sii.d.ts} +41 -2
  138. package/dist/{client-CBCVhL8U.d.ts → client-oGNJMQFd.d.ts} +1 -1
  139. package/dist/{compiler-manifest-DsxsQP-T.d.ts → compiler-manifest-D2ZlBGxj.d.mts} +44 -0
  140. package/dist/{compiler-manifest-DsxsQP-T.d.mts → compiler-manifest-D2ZlBGxj.d.ts} +44 -0
  141. package/dist/{errors-qdJUVQ3g.d.mts → errors-B-gOQdj-.d.mts} +1 -1
  142. package/dist/{errors-Bk5h1D-C.d.ts → errors-CB0KAmmV.d.ts} +1 -1
  143. package/dist/{index-PaupwX1B.d.mts → index-BbJADro4.d.mts} +1 -1
  144. package/dist/{index-bL66eHYz.d.ts → index-c3nvUGCS.d.ts} +1 -1
  145. package/dist/index.d.mts +7 -7
  146. package/dist/index.d.ts +7 -7
  147. package/dist/index.js +9 -9
  148. package/dist/index.mjs +6 -6
  149. package/dist/install-integrity.json +118 -116
  150. package/dist/plays/bundle-play-file.d.mts +3 -3
  151. package/dist/plays/bundle-play-file.d.ts +3 -3
  152. package/dist/plays/bundle-play-file.mjs +52 -0
  153. package/dist/plays/play-description.d.mts +2 -2
  154. package/dist/plays/play-description.d.ts +2 -2
  155. package/dist/plays/run-request.d.mts +2 -2
  156. package/dist/plays/run-request.d.ts +2 -2
  157. package/dist/release.d.mts +1 -1
  158. package/dist/release.d.ts +1 -1
  159. package/dist/release.js +2 -2
  160. package/dist/release.mjs +1 -1
  161. package/dist/server.d.mts +4 -4
  162. package/dist/server.d.ts +4 -4
  163. package/dist/server.js +5 -5
  164. package/dist/server.mjs +3 -3
  165. package/package.json +1 -1
  166. package/dist/cli/auth-KE6RFHUE.js +0 -43
  167. package/dist/cli/describe-PYLZAVRI.js +0 -50
  168. package/dist/cli/git-T5JTVBYZ.js +0 -25
  169. package/dist/cli/search-5MD65V43.js +0 -33
  170. package/dist/cli/sessions-FDMO7PAA.js +0 -22
  171. package/dist/cli/skills-KRUL7QCT.js +0 -37
  172. package/dist/cli/tools-CGHOSCPS.js +0 -57
  173. package/dist/cli/update-S2TILEHZ.js +0 -35
@@ -3544,10 +3544,7 @@ export class DeeplineClient {
3544
3544
  }
3545
3545
 
3546
3546
  /** Who can open a view: workspace members, or anyone with its URL. */
3547
- async setViewAccess(
3548
- id: string,
3549
- access: ViewAccess,
3550
- ): Promise<View> {
3547
+ async setViewAccess(id: string, access: ViewAccess): Promise<View> {
3551
3548
  return await this.http.post<View>(
3552
3549
  `/api/v2/views/${encodeURIComponent(id)}/access`,
3553
3550
  { access },
@@ -3590,9 +3587,7 @@ export class DeeplineClient {
3590
3587
 
3591
3588
  /** Delete a view. Its Play and runs are not touched. */
3592
3589
  async deleteView(id: string): Promise<{ id: string; deleted: boolean }> {
3593
- return await this.http.delete(
3594
- `/api/v2/views/${encodeURIComponent(id)}`,
3595
- );
3590
+ return await this.http.delete(`/api/v2/views/${encodeURIComponent(id)}`);
3596
3591
  }
3597
3592
 
3598
3593
  /** The workspace view rules and what the caller may do. */
@@ -5937,6 +5932,28 @@ export class DeeplineClient {
5937
5932
  );
5938
5933
  }
5939
5934
 
5935
+ /** Register an editing attempt so the author's open working canvas can show a rejected save. */
5936
+ async beginWorkingPlaySave(playName: string): Promise<{ attemptId: string }> {
5937
+ return this.http.post(
5938
+ `/api/v2/plays/${encodeURIComponent(playName)}/pipeline`,
5939
+ { action: 'begin' },
5940
+ undefined,
5941
+ { maxRetries: 0, exactUrlOnly: true },
5942
+ );
5943
+ }
5944
+
5945
+ /** Report a save outcome for that specific editing attempt. */
5946
+ async finishWorkingPlaySave(
5947
+ playName: string,
5948
+ attemptId: string,
5949
+ action: 'invalid_source' | 'saved',
5950
+ ): Promise<{ accepted: boolean }> {
5951
+ return this.http.post(
5952
+ `/api/v2/plays/${encodeURIComponent(playName)}/pipeline`,
5953
+ { action, attemptId },
5954
+ );
5955
+ }
5956
+
5940
5957
  /** Retry-safe field patch; omitted fields retain their current value. */
5941
5958
  async updatePlaySettings(
5942
5959
  playName: string,
@@ -6002,6 +6019,33 @@ export class DeeplineClient {
6002
6019
  return this.http.get(`/api/v2/integrations/balance?${params}`);
6003
6020
  }
6004
6021
 
6022
+ /** List the internal pilot's workspace connections. */
6023
+ async listWorkspaceIntegrationConnections(): Promise<{
6024
+ connections: Array<{
6025
+ id: string;
6026
+ provider: string;
6027
+ owner: 'workspace';
6028
+ label: string;
6029
+ status: string;
6030
+ authorizationVersion: number;
6031
+ }>;
6032
+ }> {
6033
+ return this.http.get('/api/v2/integrations/connections');
6034
+ }
6035
+
6036
+ /** Manage a workspace-owned OAuth connection. Consent completes in the browser. */
6037
+ async manageWorkspaceIntegrationConnection(input: {
6038
+ action: 'connect' | 'reconnect' | 'replace' | 'disconnect';
6039
+ provider: 'hubspot' | 'google_calendar_availability';
6040
+ connectionId?: string;
6041
+ authorizationVersion?: number;
6042
+ }): Promise<{ url?: string }> {
6043
+ return this.http.post('/api/v2/integrations/connections', {
6044
+ ...input,
6045
+ owner: 'workspace',
6046
+ });
6047
+ }
6048
+
6005
6049
  /** Get the dashboard link where a workspace owner or admin can connect a provider. */
6006
6050
  async getIntegrationConnectLink(
6007
6051
  provider: string,
@@ -6014,13 +6058,30 @@ export class DeeplineClient {
6014
6058
  async setIntegrationCredentials(
6015
6059
  provider: string,
6016
6060
  credentials: Record<string, string>,
6061
+ options?: { expectedConnectionId?: string },
6017
6062
  ): Promise<{ ok: boolean; credential_saved?: boolean }> {
6018
6063
  return this.http.post('/api/v2/integrations/connect', {
6019
6064
  provider,
6020
6065
  credentials,
6066
+ ...(options?.expectedConnectionId
6067
+ ? { expected_connection_id: options.expectedConnectionId }
6068
+ : {}),
6021
6069
  });
6022
6070
  }
6023
6071
 
6072
+ /** Calendar discovery compatibility method. The managed pilot requires calendar IDs in tool and Play inputs. */
6073
+ async listAvailabilityCalendars(cursor?: string): Promise<{
6074
+ connection_id: string;
6075
+ calendars: Array<{ id: string; name: string }>;
6076
+ cursor: string | null;
6077
+ }> {
6078
+ const params = new URLSearchParams();
6079
+ if (cursor) params.set('cursor', cursor);
6080
+ return this.http.get(
6081
+ `/api/v2/integrations/calendar-availability/calendars?${params}`,
6082
+ );
6083
+ }
6084
+
6024
6085
  /** Start provider OAuth and return the URL to open in a browser. */
6025
6086
  async startIntegrationOAuth(
6026
6087
  provider: string,
@@ -205,7 +205,7 @@ export const SDK_RELEASE = {
205
205
  // getters keep their established compatibility behavior.
206
206
  // 0.3.1 deprecated the legacy `deepline enrich` command in favor of Plays.
207
207
  // 0.3.90 is the first deliberately versioned SDK release for API v3.
208
- version: '0.3.533',
208
+ version: '0.3.535',
209
209
  updateSummary: {
210
210
  introducedIn: '0.3.90',
211
211
  summary:
@@ -0,0 +1,420 @@
1
+ /**
2
+ * The call requeue state machine: what happens to one logical Play tool call
3
+ * after its in-call retries are spent on a retryable error class.
4
+ *
5
+ * absent ──start──▶ in_call ──succeed──▶ succeeded (terminal)
6
+ * │ ├────exhaust──▶ exhausted (terminal)
7
+ * │ ├───────park──▶ parked
8
+ * │ └─wait_for_billing─▶ waiting_for_billing
9
+ * parked / waiting_for_billing ──resume──▶ resumed ──retry──▶ in_call
10
+ *
11
+ * The record lives in the run checkpoint (`PlayCheckpoint.callRequeueStates`),
12
+ * keyed by the call's durable receipt identity, and only `transitionCallRequeue`
13
+ * changes it. A terminal transition removes the record, so the checkpoint
14
+ * holds only calls that are parked or being retried. Every park records the
15
+ * Durable retry policy version it used.
16
+ *
17
+ * The decision (`decideCallRequeue`) reads only the policy snapshot taken at
18
+ * attempt start; it never fetches.
19
+ */
20
+ import type { PlayToolCallRetryPolicy } from '../plays/authoring-contract';
21
+ import type {
22
+ DurableRetryErrorClass,
23
+ DurableRetryPolicySnapshot,
24
+ } from './durable-retry-policy';
25
+ import { EXECUTION_GATEWAY_MAX_REQUEUE_PARKS } from './tool-execute-retry-policy';
26
+
27
+ export const CALL_REQUEUE_STATES = [
28
+ 'in_call',
29
+ 'parked',
30
+ 'waiting_for_billing',
31
+ 'resumed',
32
+ 'succeeded',
33
+ 'exhausted',
34
+ ] as const;
35
+ export type CallRequeueState = (typeof CALL_REQUEUE_STATES)[number];
36
+
37
+ export const CALL_REQUEUE_TERMINAL_STATES: ReadonlySet<CallRequeueState> =
38
+ new Set(['succeeded', 'exhausted']);
39
+
40
+ export const CALL_REQUEUE_TRANSITIONS = {
41
+ start: { from: ['absent'], to: 'in_call' },
42
+ succeed: { from: ['in_call'], to: 'succeeded' },
43
+ exhaust: { from: ['in_call'], to: 'exhausted' },
44
+ park: { from: ['in_call'], to: 'parked' },
45
+ wait_for_billing: { from: ['in_call'], to: 'waiting_for_billing' },
46
+ resume: { from: ['parked', 'waiting_for_billing'], to: 'resumed' },
47
+ retry: { from: ['resumed'], to: 'in_call' },
48
+ } as const satisfies Record<
49
+ string,
50
+ { from: readonly (CallRequeueState | 'absent')[]; to: CallRequeueState }
51
+ >;
52
+ export type CallRequeueTransition = keyof typeof CALL_REQUEUE_TRANSITIONS;
53
+
54
+ /** Persisted per call while it is not terminal. Fixed size. */
55
+ export type CallRequeueRecord = {
56
+ state: CallRequeueState;
57
+ errorClass: DurableRetryErrorClass | null;
58
+ /** Stored policy version the last park used; null means compiled defaults. */
59
+ policySequence: number | null;
60
+ parks: number;
61
+ /** Parks in a row that ended in the same class again. */
62
+ consecutive: number;
63
+ firstParkAtMs: number | null;
64
+ retryAtMs: number | null;
65
+ /** Window extensions granted so far. */
66
+ extensionsUsed: number;
67
+ /**
68
+ * The invocation attempt the call resumes at after its latest park; a
69
+ * fenced resend claims it so the gateway checks prior outcomes per park
70
+ * segment (`requeue_from_invocation_attempt`). Optional: absent in records
71
+ * written before it existed.
72
+ */
73
+ requeueFromInvocationAttempt?: number | null;
74
+ /**
75
+ * Requests the provider received for this call so far, in-call resends and
76
+ * durable retries together; a call's `retry.maximumAttempts` bounds it.
77
+ * Refusals before dispatch are not counted. Optional: absent in records
78
+ * written before it existed (read as `parks`, the fewest it can be).
79
+ */
80
+ sends?: number;
81
+ lastTransition: CallRequeueTransition;
82
+ lastTransitionAtMs: number;
83
+ };
84
+
85
+ export class IllegalCallRequeueTransitionError extends Error {
86
+ constructor(transition: CallRequeueTransition, from: string) {
87
+ super(`Call requeue transition ${transition} is not allowed from ${from}.`);
88
+ this.name = 'IllegalCallRequeueTransitionError';
89
+ }
90
+ }
91
+
92
+ /**
93
+ * The only writer of a call's requeue state. Returns the new record, or null
94
+ * when the call reached a terminal state (the owner deletes it).
95
+ */
96
+ export function transitionCallRequeue(
97
+ record: CallRequeueRecord | undefined,
98
+ transition: CallRequeueTransition,
99
+ nowMs: number,
100
+ patch: Partial<
101
+ Omit<CallRequeueRecord, 'state' | 'lastTransition' | 'lastTransitionAtMs'>
102
+ > = {},
103
+ ): CallRequeueRecord | null {
104
+ const rule = CALL_REQUEUE_TRANSITIONS[transition];
105
+ const from = record?.state ?? 'absent';
106
+ if (!(rule.from as readonly string[]).includes(from)) {
107
+ throw new IllegalCallRequeueTransitionError(transition, from);
108
+ }
109
+ if (CALL_REQUEUE_TERMINAL_STATES.has(rule.to)) return null;
110
+ return {
111
+ errorClass: null,
112
+ policySequence: null,
113
+ parks: 0,
114
+ consecutive: 0,
115
+ firstParkAtMs: null,
116
+ retryAtMs: null,
117
+ extensionsUsed: 0,
118
+ ...record,
119
+ ...patch,
120
+ state: rule.to,
121
+ lastTransition: transition,
122
+ lastTransitionAtMs: nowMs,
123
+ } as CallRequeueRecord;
124
+ }
125
+
126
+ export type CallRequeueExhaustReason =
127
+ | 'not_in_call'
128
+ | 'park_limit'
129
+ | 'park_disabled'
130
+ | 'not_eligible'
131
+ | 'consecutive_limit'
132
+ | 'window'
133
+ /** The call's own `retry.nonRetryable` lists the class. */
134
+ | 'non_retryable'
135
+ /** The call's own `retry.maximumAttempts` is spent. */
136
+ | 'maximum_attempts';
137
+
138
+ export type CallRequeueDecision =
139
+ | {
140
+ kind: 'park';
141
+ transition: 'park' | 'wait_for_billing';
142
+ retryAtMs: number;
143
+ waitMs: number;
144
+ /** The record to persist (already transitioned). */
145
+ record: CallRequeueRecord;
146
+ }
147
+ | { kind: 'exhaust'; reason: CallRequeueExhaustReason };
148
+
149
+ export const BILLING_ERROR_CLASSES: ReadonlySet<DurableRetryErrorClass> =
150
+ new Set(['billing_insufficient_credits', 'billing_monthly_cap']);
151
+
152
+ /**
153
+ * The Durable retry class of a failure whose in-call retries are spent, or
154
+ * null when it never parks (caller errors, customer-set run caps, and
155
+ * failures this build does not classify). Structured fields only, never text.
156
+ */
157
+ export function classifyDurableRetryErrorClass(input: {
158
+ status: number;
159
+ /** `ToolExecuteHttpFailureOutcome.reason`. */
160
+ reason: string;
161
+ knownNotDispatched: boolean;
162
+ /** `ToolExecutionError.origin` when the envelope is structured. */
163
+ origin: string | null;
164
+ /** The failure's code (`ToolExecutionError.code` or body `code`). */
165
+ code: string | null;
166
+ /**
167
+ * The provider's own HTTP status (failure body `upstream_status`). The
168
+ * execute route answers every provider 5xx with 502, so the provider's 500
169
+ * is only visible here. Absent or invalid: the response status is used.
170
+ */
171
+ upstreamStatus?: number | null;
172
+ /**
173
+ * The failure body's raw `error_category`. `model_output` is a
174
+ * provider-origin 500 that is the model's answer (MODEL_OUTPUT_INVALID),
175
+ * not an outage, and never parks.
176
+ */
177
+ category?: string | null;
178
+ /**
179
+ * The failure body's `network_kind` for a provider transport failure. The
180
+ * execute route answers every one with 502, so a response-wait timeout is
181
+ * only visible here.
182
+ */
183
+ networkKind?: string | null;
184
+ }): DurableRetryErrorClass | null {
185
+ if (input.reason === 'hard_billing_error') {
186
+ if (input.code === 'INSUFFICIENT_CREDITS') {
187
+ return 'billing_insufficient_credits';
188
+ }
189
+ if (input.code === 'MONTHLY_BILLING_LIMIT_EXCEEDED') {
190
+ return 'billing_monthly_cap';
191
+ }
192
+ // RUN_BILLING_CAP_EXCEEDED and every other denial is the customer's own
193
+ // limit or a terminal answer: never parked.
194
+ return null;
195
+ }
196
+ if (input.knownNotDispatched) return 'never_sent';
197
+ if (input.status === 429) {
198
+ return input.origin === 'provider' ? 'rate_limit_429' : null;
199
+ }
200
+ if (input.origin !== 'provider') return null;
201
+ if (input.category === 'model_output') return null;
202
+ // A transport timeout: a failure proven to be before send is `never_sent`
203
+ // above, so this one may have reached the provider. Owner rule: a timeout
204
+ // is not retried (the class is off unless turned on live).
205
+ if (input.networkKind === 'timeout') return 'timeout_after_send';
206
+ const upstream = input.upstreamStatus;
207
+ const status =
208
+ typeof upstream === 'number' &&
209
+ Number.isSafeInteger(upstream) &&
210
+ upstream >= 400 &&
211
+ upstream <= 599
212
+ ? upstream
213
+ : input.status;
214
+ if (status === 502 || status === 503) return 'provider_unavailable';
215
+ // A gateway timeout after the request reached the provider: owner rule, a
216
+ // timeout is not retried (the class is off unless turned on live).
217
+ if (status === 504) return 'timeout_after_send';
218
+ if (status === 500) return 'provider_ambiguous_500';
219
+ return null;
220
+ }
221
+
222
+ /**
223
+ * Decide, after a call's in-call retries are spent, whether it parks and
224
+ * until when, or is exhausted (the original error reaches the Play).
225
+ */
226
+ export function decideCallRequeue(input: {
227
+ record: CallRequeueRecord | undefined;
228
+ errorClass: DurableRetryErrorClass;
229
+ snapshot: DurableRetryPolicySnapshot;
230
+ /** null when the action's effect is unknown: treated as a write. */
231
+ effect: 'read' | 'write' | 'destructive' | null;
232
+ /** The provider honors the stable idempotency key the runtime sends. */
233
+ idempotencyKeyHonored: boolean;
234
+ /**
235
+ * The write's class (`@deepline/integrations/write-idempotency`); null
236
+ * when unknown, which counts as non-idempotent.
237
+ */
238
+ writeIdempotency?: 'idempotent_write' | 'non_idempotent_write' | null;
239
+ nowMs: number;
240
+ random?: () => number;
241
+ /** The invocation attempt that just failed; the resume starts after it. */
242
+ failedInvocationAttempt?: number;
243
+ /** The call runs under the gateway's durable execution fence. */
244
+ fenced?: boolean;
245
+ /**
246
+ * The call's own retry policy (`ctx.tools.execute({ retry })`). Its fields
247
+ * replace the class rule's: `maximumAttempts` bounds every request the
248
+ * provider received (`sends`), like an activity retry policy; the interval
249
+ * fields replace the park ladder.
250
+ */
251
+ callRetry?: PlayToolCallRetryPolicy;
252
+ /**
253
+ * Requests the provider received for this call so far, the burst that just
254
+ * failed included. Absent: the prior record's count plus one.
255
+ */
256
+ sends?: number;
257
+ }): CallRequeueDecision {
258
+ const rule = input.snapshot.policy.classes[input.errorClass];
259
+ const callRetry = input.callRetry;
260
+ if (callRetry?.nonRetryable?.includes(input.errorClass)) {
261
+ return { kind: 'exhaust', reason: 'non_retryable' };
262
+ }
263
+ // Every request the provider received counts, in-call resends and durable
264
+ // retries alike. The call's own limit applies before the class rule, like
265
+ // an activity retry policy.
266
+ const sends = input.sends ?? callRequeueSends(input.record) + 1;
267
+ if (
268
+ callRetry?.maximumAttempts !== undefined &&
269
+ sends >= callRetry.maximumAttempts
270
+ ) {
271
+ return { kind: 'exhaust', reason: 'maximum_attempts' };
272
+ }
273
+ if (!rule.park.enabled) return { kind: 'exhaust', reason: 'park_disabled' };
274
+ const isRead = input.effect === 'read';
275
+ const writes = rule.eligibility.writes;
276
+ const eligible = isRead
277
+ ? rule.eligibility.reads
278
+ : writes === 'all' ||
279
+ ((writes === 'idempotency_key' || writes === 'idempotent_write') &&
280
+ input.idempotencyKeyHonored) ||
281
+ (writes === 'idempotent_write' &&
282
+ input.writeIdempotency === 'idempotent_write');
283
+ if (!eligible) return { kind: 'exhaust', reason: 'not_eligible' };
284
+
285
+ const prior = input.record;
286
+ // Only a call being retried (or never parked) can park. A record in any
287
+ // other state means another invocation owns it: fail normally rather than
288
+ // replace the Play's error with an illegal-transition error.
289
+ if (prior && prior.state !== 'in_call') {
290
+ return { kind: 'exhaust', reason: 'not_in_call' };
291
+ }
292
+ // A call is judged only on its own history (as a Temporal activity is):
293
+ // other rows or calls succeeding never reset it or extend its window.
294
+ const sameClass = prior?.errorClass === input.errorClass;
295
+ const consecutive = sameClass ? (prior?.consecutive ?? 0) + 1 : 1;
296
+ const limit = rule.park.consecutiveFailureLimit;
297
+ if (limit !== null && consecutive > limit) {
298
+ return { kind: 'exhaust', reason: 'consecutive_limit' };
299
+ }
300
+
301
+ const parks = prior?.parks ?? 0;
302
+ // The gateway accepts at most this many parks for a fenced call; stop
303
+ // before a resend it would refuse, whatever the live policy allows.
304
+ if (
305
+ input.fenced === true &&
306
+ parks + 1 > EXECUTION_GATEWAY_MAX_REQUEUE_PARKS
307
+ ) {
308
+ return { kind: 'exhaust', reason: 'park_limit' };
309
+ }
310
+ const ladder = rule.park.ladderMs;
311
+ const base =
312
+ callRetryIntervalMs(callRetry, parks, ladder) ??
313
+ ladder[Math.min(parks, ladder.length - 1)]!;
314
+ const jitter = rule.inCall.jitterRatio;
315
+ const waitMs = Math.max(
316
+ 1_000,
317
+ Math.round(base * (1 + ((input.random ?? Math.random)() * 2 - 1) * jitter)),
318
+ );
319
+ const retryAtMs = input.nowMs + waitMs;
320
+ const firstParkAtMs = prior?.firstParkAtMs ?? input.nowMs;
321
+
322
+ // The window starts at the call's first park and grows on a fixed
323
+ // schedule (12 h, then 18 h, then 24 h by default): each extension is
324
+ // entered when the next wait would pass the current end.
325
+ let extensionsUsed = prior?.extensionsUsed ?? 0;
326
+ const windowEnd = () =>
327
+ firstParkAtMs +
328
+ rule.window.initialMs +
329
+ rule.window.extensionsMs
330
+ .slice(0, extensionsUsed)
331
+ .reduce((sum, step) => sum + step, 0);
332
+ while (
333
+ retryAtMs > windowEnd() &&
334
+ extensionsUsed < rule.window.extensionsMs.length
335
+ ) {
336
+ extensionsUsed += 1;
337
+ }
338
+ if (retryAtMs > windowEnd()) return { kind: 'exhaust', reason: 'window' };
339
+
340
+ const transition = BILLING_ERROR_CLASSES.has(input.errorClass)
341
+ ? ('wait_for_billing' as const)
342
+ : ('park' as const);
343
+ const record = transitionCallRequeue(
344
+ prior ?? transitionCallRequeue(undefined, 'start', input.nowMs)!,
345
+ transition,
346
+ input.nowMs,
347
+ {
348
+ errorClass: input.errorClass,
349
+ policySequence: input.snapshot.sequence,
350
+ parks: parks + 1,
351
+ sends,
352
+ consecutive,
353
+ firstParkAtMs,
354
+ retryAtMs,
355
+ extensionsUsed,
356
+ // A never_sent refusal wrote no outcome for its attempt, so the resume
357
+ // reuses that attempt; every other class resumes after it.
358
+ requeueFromInvocationAttempt:
359
+ input.failedInvocationAttempt === undefined
360
+ ? null
361
+ : input.errorClass === 'never_sent'
362
+ ? input.failedInvocationAttempt
363
+ : input.failedInvocationAttempt + 1,
364
+ },
365
+ )!;
366
+ return { kind: 'park', transition, retryAtMs, waitMs, record };
367
+ }
368
+
369
+ /** Requests the provider received for a call before this burst. */
370
+ export function callRequeueSends(
371
+ record: CallRequeueRecord | undefined,
372
+ ): number {
373
+ if (!record) return 0;
374
+ return record.sends ?? record.parks;
375
+ }
376
+
377
+ /**
378
+ * The wait before retry `parks + 1` under a call's own interval fields, or
379
+ * null when it sets none (the class ladder applies). Unset fields take the
380
+ * ladder's first step, a coefficient of 2, and the ladder's longest step.
381
+ */
382
+ export function callRetryIntervalMs(
383
+ callRetry: PlayToolCallRetryPolicy | undefined,
384
+ parks: number,
385
+ ladder: readonly number[],
386
+ ): number | null {
387
+ if (
388
+ !callRetry ||
389
+ (callRetry.initialIntervalMs === undefined &&
390
+ callRetry.backoffCoefficient === undefined &&
391
+ callRetry.maximumIntervalMs === undefined)
392
+ ) {
393
+ return null;
394
+ }
395
+ const initial = callRetry.initialIntervalMs ?? ladder[0]!;
396
+ const coefficient = callRetry.backoffCoefficient ?? 2;
397
+ const maximum = Math.max(
398
+ initial,
399
+ callRetry.maximumIntervalMs ?? Math.max(...ladder),
400
+ );
401
+ return Math.min(maximum, Math.round(initial * coefficient ** parks));
402
+ }
403
+
404
+ /**
405
+ * A generic HTTP request's write class by method: GET (the default), HEAD,
406
+ * PUT and DELETE are idempotent; POST and anything else is not. The one
407
+ * definition; `@deepline/integrations/write-idempotency` re-exports it.
408
+ */
409
+ export function genericHttpWriteIdempotency(
410
+ method: unknown,
411
+ ): 'idempotent_write' | 'non_idempotent_write' {
412
+ const normalized =
413
+ typeof method === 'string' ? method.trim().toUpperCase() : 'GET';
414
+ return normalized === 'GET' ||
415
+ normalized === 'HEAD' ||
416
+ normalized === 'PUT' ||
417
+ normalized === 'DELETE'
418
+ ? 'idempotent_write'
419
+ : 'non_idempotent_write';
420
+ }