@leitwerk-dev/ui 0.1.8 → 0.2.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 (173) hide show
  1. package/dist/assets/ApiTokensPage-B15IzsLp.css +1 -0
  2. package/dist/assets/ApiTokensPage-ClJp9PYr.js +1 -0
  3. package/dist/assets/ChronicleMarkdown-lqwX9Ywa.js +16 -0
  4. package/dist/assets/ChronicleMarkdown-wsUF8Z75.css +1 -0
  5. package/dist/assets/FutureLaunchDetailPage-BOoZaG11.css +1 -0
  6. package/dist/assets/FutureLaunchDetailPage-Bdlgm4cJ.js +1 -0
  7. package/dist/assets/GenericLauncher-Bf7Eb1Rw.js +1 -0
  8. package/dist/assets/GenericLauncher-CExW6wei.css +1 -0
  9. package/dist/assets/HomePage-4Q7aqPBl.css +1 -0
  10. package/dist/assets/HomePage-CSkNdC4m.js +1 -0
  11. package/dist/assets/PageHeader-DPuQInDo.css +1 -0
  12. package/dist/assets/PageHeader-sphJnWL1.js +1 -0
  13. package/dist/assets/ProcessActionsMenu-DLMywI9c.js +1 -0
  14. package/dist/assets/ProcessActionsMenu-VKT7PE6z.css +1 -0
  15. package/dist/assets/ProcessDetailPage-Cth6A0DN.css +1 -0
  16. package/dist/assets/ProcessDetailPage-fvvdvO19.js +14 -0
  17. package/dist/assets/ProcessFlowDiagram-Dx2wheGN.js +2 -0
  18. package/dist/assets/ProcessesPage-uLl7LXp8.js +1 -0
  19. package/dist/assets/ProcessesPage-yPjjrzjg.css +1 -0
  20. package/dist/assets/ScheduleDateTimePicker-DmojMRxN.js +1 -0
  21. package/dist/assets/{ScheduleDateTimePicker-CadXN9z7.css → ScheduleDateTimePicker-uacJAkIq.css} +1 -1
  22. package/dist/assets/SkillsPage-CJrtt8xU.css +1 -0
  23. package/dist/assets/SkillsPage-CotbGUxm.js +2 -0
  24. package/dist/assets/WatchersPage-ByWGNJet.js +1 -0
  25. package/dist/assets/WatchersPage-cRBnmTAD.css +1 -0
  26. package/dist/assets/external-links-CX92-VRP.js +1 -0
  27. package/dist/assets/http-client-VpPXJwbR.js +2 -0
  28. package/dist/assets/index-C7zNe3je.js +6 -0
  29. package/dist/assets/index-DtEI5gsQ.css +1 -0
  30. package/dist/assets/index-client-BYQviCtQ.js +2 -0
  31. package/dist/assets/{mermaid-render.worker-DAVgiVRG.js → mermaid-render.worker-QW2WZpEE.js} +12 -12
  32. package/dist/assets/process-terminal-display-BQRQwGod.js +1 -0
  33. package/dist/assets/router.svelte-EEldxHlO.js +1 -0
  34. package/dist/index.html +8 -8
  35. package/package.json +8 -8
  36. package/src/App.svelte +41 -2
  37. package/src/chronicle/components/ChronicleActionSection.svelte +70 -143
  38. package/src/chronicle/components/ChronicleCreateIssueButton.svelte +22 -0
  39. package/src/chronicle/components/ChronicleEntryHeader.svelte +76 -0
  40. package/src/chronicle/components/ChronicleExpandButton.svelte +11 -34
  41. package/src/chronicle/components/ChronicleFailureMessage.svelte +41 -0
  42. package/src/chronicle/components/ChronicleFlow.svelte +135 -28
  43. package/src/chronicle/components/ChronicleLeafOutcomeRendererHost.svelte +1 -8
  44. package/src/chronicle/components/ChronicleLeafOutcomeSection.svelte +25 -52
  45. package/src/chronicle/components/ChronicleLiveChip.svelte +1 -35
  46. package/src/chronicle/components/ChronicleLiveTail.svelte +55 -154
  47. package/src/chronicle/components/ChronicleMarkdown.svelte +6 -6
  48. package/src/chronicle/components/ChronicleOperatorInputSection.svelte +5 -18
  49. package/src/chronicle/components/ChronicleProcessErrorSection.svelte +10 -107
  50. package/src/chronicle/components/ChroniclePromptSection.svelte +6 -26
  51. package/src/chronicle/components/ChronicleQuestionRequest.svelte +22 -5
  52. package/src/chronicle/components/ChronicleReasoningDetailsOverlay.svelte +71 -109
  53. package/src/chronicle/components/ChronicleRecoverySection.svelte +99 -262
  54. package/src/chronicle/components/ChronicleScheduledActionSection.svelte +1 -1
  55. package/src/chronicle/components/ChronicleSectionHeader.svelte +1 -4
  56. package/src/chronicle/components/ChronicleStartupHistory.svelte +63 -0
  57. package/src/chronicle/components/ChronicleStartupRecoverySection.svelte +10 -26
  58. package/src/chronicle/components/ChronicleThinkingSection.svelte +25 -165
  59. package/src/chronicle/components/ChronicleThinkingText.svelte +1 -0
  60. package/src/chronicle/components/ChronicleToolApproval.svelte +40 -0
  61. package/src/chronicle/components/ChronicleToolCallItem.svelte +1 -1
  62. package/src/chronicle/components/ChronicleTurnCluster.svelte +209 -282
  63. package/src/chronicle/components/ChronicleTurnDetailsButton.svelte +16 -0
  64. package/src/chronicle/components/ChronicleTurnProgress.svelte +94 -0
  65. package/src/chronicle/components/ChronicleTurnRail.svelte +339 -394
  66. package/src/chronicle/components/CompactActionComposer.svelte +36 -13
  67. package/src/chronicle/components/ReadonlyJsonValue.svelte +30 -0
  68. package/src/chronicle/lib/action-bindings.ts +1 -1
  69. package/src/chronicle/lib/action-model-display.ts +2 -2
  70. package/src/chronicle/lib/action-preview.ts +1 -1
  71. package/src/chronicle/lib/chronicle-projection.ts +135 -108
  72. package/src/chronicle/lib/chronicle-rail-groups.ts +158 -0
  73. package/src/chronicle/lib/chronicle-selectable-items.ts +16 -11
  74. package/src/chronicle/lib/chronicle-ticket-artifact.ts +7 -0
  75. package/src/chronicle/lib/formatting.ts +19 -0
  76. package/src/chronicle/lib/leaf-outcome-loader.ts +30 -111
  77. package/src/chronicle/lib/leaf-outcome-runtime.ts +3 -15
  78. package/src/chronicle/lib/result-presentation.ts +40 -0
  79. package/src/chronicle/lib/retry-groups.ts +24 -0
  80. package/src/chronicle/lib/scroll-sync.ts +1 -0
  81. package/src/chronicle/lib/tool-call-summary.ts +1 -9
  82. package/src/chronicle/ticket-selection.ts +23 -0
  83. package/src/components/ElapsedTime.svelte +31 -0
  84. package/src/components/ExternalLink.svelte +39 -0
  85. package/src/components/FormFieldRenderer.svelte +4 -1
  86. package/src/components/GenericLauncher.svelte +40 -15
  87. package/src/components/KeyboardShortcutsModal.svelte +2 -2
  88. package/src/components/LaunchChecklist.svelte +184 -0
  89. package/src/components/ModalShell.svelte +49 -15
  90. package/src/components/PageHeader.svelte +36 -35
  91. package/src/components/ProcessActionsMenu.svelte +247 -138
  92. package/src/components/ProcessInfoOverlay.svelte +13 -21
  93. package/src/components/ProgressChecklist.svelte +46 -0
  94. package/src/components/ProgressChecklistRows.svelte +80 -0
  95. package/src/components/launcher-form-copy.ts +4 -1
  96. package/src/components/launcher-model-config.ts +1 -1
  97. package/src/extension-ui-dev-server.ts +2 -5
  98. package/src/lib/api-tokens.ts +34 -0
  99. package/src/lib/api.ts +330 -455
  100. package/src/lib/elapsed-time.ts +19 -0
  101. package/src/lib/external-links.ts +81 -0
  102. package/src/lib/flow-layout.ts +1 -8
  103. package/src/lib/format.ts +3 -26
  104. package/src/lib/future-launch-detail.ts +1 -1
  105. package/src/lib/http-client.ts +79 -0
  106. package/src/lib/launch-updates.ts +17 -0
  107. package/src/lib/markdown.ts +8 -1
  108. package/src/lib/primary-path-detail.ts +97 -3
  109. package/src/lib/primary-path-replay.ts +13 -7
  110. package/src/lib/process-row-view.ts +1 -1
  111. package/src/lib/process-terminal-display.ts +4 -7
  112. package/src/lib/processes.svelte.ts +41 -9
  113. package/src/lib/reasoning-history.ts +95 -0
  114. package/src/lib/retry-config.svelte.ts +1 -1
  115. package/src/lib/rich-markdown-elements.ts +2 -2
  116. package/src/lib/router-logic.ts +3 -0
  117. package/src/lib/runtime-config.ts +1 -3
  118. package/src/lib/test-fixtures.ts +1 -1
  119. package/src/lib/tool-call-rendering.ts +4 -1
  120. package/src/lib/ui-extensions.svelte.ts +78 -127
  121. package/src/lib/ws-classifier.ts +8 -1
  122. package/src/pages/ApiTokensPage.svelte +213 -0
  123. package/src/pages/FutureLaunchDetailPage.svelte +8 -38
  124. package/src/pages/HomePage.svelte +8 -11
  125. package/src/pages/ProcessCard.svelte +1 -1
  126. package/src/pages/ProcessDetailPage.svelte +161 -62
  127. package/src/pages/ProcessGallery.svelte +1 -3
  128. package/src/pages/ProcessesPage.svelte +7 -42
  129. package/src/pages/SkillsPage.svelte +32 -24
  130. package/src/pages/WatchersPage.svelte +31 -55
  131. package/src/pages/process-detail/ProcessDetailChronicle.svelte +415 -19
  132. package/src/pages/process-detail/ProcessDetailHeader.svelte +66 -25
  133. package/src/pages/process-detail/ProcessSummary.svelte +35 -0
  134. package/src/pages/process-detail/TicketCreationComposer.svelte +219 -0
  135. package/src/pages/process-detail/process-detail-action-drafts.svelte.ts +5 -5
  136. package/src/pages/process-detail/process-detail-actions.svelte.ts +4 -2
  137. package/src/pages/process-detail/process-detail-chronicle-dom.ts +39 -14
  138. package/src/pages/process-detail/process-detail-chronicle-scroll.svelte.ts +68 -10
  139. package/src/pages/process-detail/process-detail-view-model.ts +10 -23
  140. package/src/shell/AppShell.svelte +260 -6
  141. package/src/shell/RouteLoadBoundary.svelte +48 -12
  142. package/src/shell/Sidebar.svelte +304 -172
  143. package/src/styles/controls.css +188 -0
  144. package/dist/assets/ChronicleMarkdown-D6hFzERy.css +0 -1
  145. package/dist/assets/ChronicleMarkdown-iH1VLv7x.js +0 -16
  146. package/dist/assets/FutureLaunchDetailPage-BJphZBFH.js +0 -1
  147. package/dist/assets/FutureLaunchDetailPage-VPMBtpYc.css +0 -1
  148. package/dist/assets/GenericLauncher-D_GMtsQ5.css +0 -1
  149. package/dist/assets/GenericLauncher-tr1to52a.js +0 -1
  150. package/dist/assets/HomePage-CSHVQefI.js +0 -1
  151. package/dist/assets/HomePage-DYh_QHXv.css +0 -1
  152. package/dist/assets/PageHeader-6PdvYODN.css +0 -1
  153. package/dist/assets/PageHeader-C4j3zJKF.js +0 -1
  154. package/dist/assets/ProcessActionsMenu-BT2r9vO8.css +0 -1
  155. package/dist/assets/ProcessActionsMenu-gNiZGUCZ.js +0 -1
  156. package/dist/assets/ProcessDetailPage-CGyVxjeH.js +0 -12
  157. package/dist/assets/ProcessDetailPage-CSrjzajF.css +0 -1
  158. package/dist/assets/ProcessFlowDiagram-BX_Zjm2n.js +0 -2
  159. package/dist/assets/ProcessesPage-BcM38HMs.css +0 -1
  160. package/dist/assets/ProcessesPage-D3jjufse.js +0 -1
  161. package/dist/assets/ScheduleDateTimePicker-D72J6EhE.js +0 -1
  162. package/dist/assets/SkillsPage-B30FAFia.css +0 -1
  163. package/dist/assets/SkillsPage-CcYm4ATy.js +0 -2
  164. package/dist/assets/WatchersPage-Bac86WLp.js +0 -1
  165. package/dist/assets/WatchersPage-Dnfi1zUK.css +0 -1
  166. package/dist/assets/api-HGtUzekR.js +0 -1
  167. package/dist/assets/dist-DVNpSD5l.js +0 -2
  168. package/dist/assets/index-66T4Gmbl.css +0 -1
  169. package/dist/assets/index-ChVsVf6R.js +0 -7
  170. package/dist/assets/index-client-BqF3_t3P.js +0 -2
  171. package/dist/assets/retry-config.svelte-DFKCJtCe.js +0 -1
  172. package/dist/assets/router.svelte-C2wi6I7k.js +0 -1
  173. package/src/lib/process-initial-prompt.ts +0 -7
package/src/lib/api.ts CHANGED
@@ -2,16 +2,23 @@ import type {
2
2
  ProcessInstance,
3
3
  ProcessProject,
4
4
  ProcessQuestionRequest,
5
+ ProcessToolApprovalRequest,
5
6
  QuestionAnswerDraft,
6
7
  } from "@leitwerk-dev/domain";
7
- import type { PrimaryPathSnapshot } from "@leitwerk-dev/protocol";
8
+ import type {
9
+ LaunchTicketCreationRequestBody,
10
+ LaunchTicketCreationResponseBody,
11
+ PrimaryPathSnapshot,
12
+ ResolveToolApprovalRequestBody,
13
+ TicketCreationToolSummary,
14
+ } from "@leitwerk-dev/protocol";
8
15
  import type {
9
16
  AuthMeResponseBody,
10
17
  CronPreviewResponseBody,
11
- ErrorResponseBody,
12
18
  FutureExecutionSummary as FullFutureExecutionSummary,
13
19
  FutureExecutionDetailResponseBody,
14
20
  FutureExecutionOverviewItem,
21
+ FutureLaunchMutationResponseBody,
15
22
  FutureLaunchSummary,
16
23
  InstalledSkillCatalogDetail,
17
24
  InstalledSkillCatalogDetailResponseBody,
@@ -23,6 +30,7 @@ import type {
23
30
  LauncherOptionsResponseBody,
24
31
  LauncherRecentValuesResponseBody,
25
32
  LaunchersResponseBody,
33
+ LaunchRunResponseBody,
26
34
  ModelProviderOptionsResponseBody,
27
35
  PrimaryPathSnapshotResponseBody,
28
36
  ProcessActionModelPreview,
@@ -32,6 +40,7 @@ import type {
32
40
  ProcessDiagnosticsData,
33
41
  ProcessDiagnosticsResponseBody,
34
42
  ProcessesOverviewResponseBody,
43
+ ProcessLaunchRunsResponseBody,
35
44
  ProcessOverviewItem,
36
45
  ProcessRetryConfig,
37
46
  ProcessRetryConfigResponseBody,
@@ -42,6 +51,7 @@ import type {
42
51
  SkillCatalogDetail,
43
52
  SkillCatalogDetailResponseBody,
44
53
  SkillsCatalogResponseBody,
54
+ StartLaunchRunResponseBody,
45
55
  TurnReasoningDetailResponseBody,
46
56
  UiLauncherSummary,
47
57
  WatcherSummary,
@@ -53,6 +63,16 @@ import type {
53
63
  } from "@leitwerk-dev/protocol/launcher-contract";
54
64
  import * as v from "valibot";
55
65
  import { formatDefinition } from "./format.js";
66
+ import {
67
+ jsonRequestInit,
68
+ readErrorMessage,
69
+ readJsonObject,
70
+ requestJson,
71
+ requestMutation,
72
+ requireSuccessfulResponse,
73
+ tryReadJson,
74
+ unknownRecordSchema,
75
+ } from "./http-client.js";
56
76
  import { getFetchImpl, resolveApiUrl } from "./runtime-config";
57
77
 
58
78
  export class ApiResponseError extends Error {
@@ -65,93 +85,24 @@ export class ApiResponseError extends Error {
65
85
  }
66
86
  }
67
87
 
68
- export type {
69
- ProcessFlowEdge,
70
- ProcessFlowEdgeKind,
71
- ProcessFlowEndState,
72
- ProcessFlowNode,
73
- ProcessFlowNodeRole,
74
- ProcessFlowView,
75
- } from "@leitwerk-dev/domain";
76
- export type {
77
- FormFieldDefinition,
78
- FormFieldOptionDefinition,
79
- } from "@leitwerk-dev/protocol/form-contract";
80
- export type {
81
- FutureExecutionOverviewItem,
82
- FutureLaunchSummary,
83
- InstalledSkillCatalogDetail,
84
- InstalledSkillCatalogItem,
85
- InstanceTreeNodeSummary,
86
- LauncherDefaultModelPreview,
87
- LauncherModelConfigDefaults,
88
- LauncherModelConfigPreview,
89
- LauncherModelConfigSchema,
90
- LauncherTurnModelConfigPreview,
91
- ModelProfileOptionSummary,
92
- PiSessionContentBlock,
93
- PiSessionEntry,
94
- PiSessionImageContentBlock,
95
- PiSessionMessageRecord,
96
- PiSessionTextContentBlock,
97
- PiSessionThinkingContentBlock,
98
- PiSessionToolCallContentBlock,
99
- PiSessionUsageSnapshot,
100
- ProcessActionFieldDefinition,
101
- ProcessActionFormDefinition,
102
- ProcessActionModelPreview,
103
- ProcessActionModelResolutionPreview,
104
- ProcessActionPreviewSummary,
105
- ProcessActionSummary,
106
- ProcessBrowseFacets,
107
- ProcessBrowseItem,
108
- ProcessBrowsePagination,
109
- ProcessBrowseResponseBody,
110
- ProcessDetailUiSnapshotResponseBody,
111
- ProcessDiagnosticsData,
112
- ProcessExternalTriggerSummary,
113
- ProcessInstanceTreeResponseBody,
114
- ProcessLaunchConfigurationParameterView,
115
- ProcessLaunchConfigurationProjectView,
116
- ProcessLaunchConfigurationView,
117
- ProcessListItem,
118
- ProcessModelConfigurationView,
119
- ProcessOverviewItem,
120
- ProcessRetryConfig,
121
- ProcessRunDetailsView,
122
- ProcessRunToolParameterView,
123
- ProcessRunToolView,
124
- ProcessRunTurnView,
125
- ProcessSelectedTurnSummary,
126
- ProcessTurnModelConfigurationView,
127
- ScheduleConfigInput,
128
- ScheduledActionDetail,
129
- ScheduleMode,
130
- SkillCatalogDetail,
131
- SkillCatalogItem,
132
- SkillRepositorySummary,
133
- SkillsCatalogResponseBody,
134
- SkillUsageProcessSummary,
135
- SkillUsageSummary,
136
- TurnReasoningDetailResponseBody,
137
- TurnTracePreview,
138
- TurnTraceSnapshot,
139
- UiLauncherSummary,
140
- WatcherLaunchModelSummary,
141
- WatcherSummary,
142
- } from "@leitwerk-dev/protocol/http-contracts";
143
- export type {
144
- LauncherCardMetadata,
145
- LauncherFieldDefinition,
146
- LauncherFieldOptionDefinition,
147
- LauncherSchemaDefinition,
148
- LauncherValidationError,
149
- UiLauncherSummaryBase,
150
- } from "@leitwerk-dev/protocol/launcher-contract";
151
- export type {
152
- ToolCallRendererDefinition,
153
- ToolCallRendererFieldDefinition,
154
- } from "@leitwerk-dev/protocol/tool-renderer-contract";
88
+ function requestStatusJson<T extends object>(
89
+ path: string,
90
+ error: string,
91
+ malformed: string,
92
+ init?: RequestInit,
93
+ ): Promise<T> {
94
+ return requestJson({
95
+ path,
96
+ init,
97
+ malformed,
98
+ error: (response) => new Error(`${error}: ${response.status}`),
99
+ });
100
+ }
101
+
102
+ function apiResponseError(message: string) {
103
+ return (response: Response, body: unknown) =>
104
+ new ApiResponseError(readErrorMessage(body) ?? message, response.status);
105
+ }
155
106
 
156
107
  export type ProcessDetailData = ProcessDetailUiSnapshotResponseBody;
157
108
  export type FutureExecutionSummary = FutureExecutionOverviewItem;
@@ -164,25 +115,52 @@ export async function submitQuestionAnswers(input: {
164
115
  requestId: string;
165
116
  draft: QuestionAnswerDraft[];
166
117
  }): Promise<ProcessQuestionRequest> {
167
- const response = await getFetchImpl()(
168
- resolveApiUrl(
169
- `/api/processes/${encodeURIComponent(input.instanceId)}/question-requests/${encodeURIComponent(input.requestId)}/answers`,
170
- ),
171
- {
172
- method: "POST",
173
- headers: { "content-type": "application/json" },
174
- body: JSON.stringify({ draft: input.draft }),
175
- },
176
- );
177
- if (!response.ok) {
178
- const body = await tryReadJson(response);
179
- throw new ApiResponseError(readErrorMessage(body) ?? "Couldn't send answers", response.status);
180
- }
181
118
  return (
182
- await readJsonObject<QuestionRequestMutationResponseBody>(
183
- response,
184
- "Malformed question response",
185
- )
119
+ await requestJson<QuestionRequestMutationResponseBody>({
120
+ path: `/api/processes/${encodeURIComponent(input.instanceId)}/question-requests/${encodeURIComponent(input.requestId)}/answers`,
121
+ init: jsonRequestInit("POST", { draft: input.draft }),
122
+ malformed: "Malformed question response",
123
+ error: apiResponseError("Couldn't send answers"),
124
+ })
125
+ ).request;
126
+ }
127
+
128
+ export async function fetchTicketCreationTools(): Promise<TicketCreationToolSummary[]> {
129
+ return (
130
+ await requestJson<{ tools: TicketCreationToolSummary[] }>({
131
+ path: "/api/ticket-creation/tools",
132
+ malformed: "Malformed ticket tool response",
133
+ error: (response) => new ApiResponseError("Couldn't load ticket systems", response.status),
134
+ })
135
+ ).tools;
136
+ }
137
+
138
+ export function launchTicketCreation(
139
+ instanceId: string,
140
+ body: LaunchTicketCreationRequestBody,
141
+ ): Promise<LaunchTicketCreationResponseBody> {
142
+ const init = jsonRequestInit("POST", body);
143
+ init.headers = { ...init.headers, "idempotency-key": crypto.randomUUID() };
144
+ return requestJson({
145
+ path: `/api/processes/${encodeURIComponent(instanceId)}/ticket-creation`,
146
+ init,
147
+ malformed: "Malformed ticket launch response",
148
+ error: apiResponseError("Couldn't start ticket creation"),
149
+ });
150
+ }
151
+
152
+ export async function resolveToolApproval(input: {
153
+ instanceId: string;
154
+ requestId: string;
155
+ body: ResolveToolApprovalRequestBody;
156
+ }): Promise<ProcessToolApprovalRequest> {
157
+ return (
158
+ await requestJson<{ request: ProcessToolApprovalRequest }>({
159
+ path: `/api/processes/${encodeURIComponent(input.instanceId)}/tool-approval-requests/${encodeURIComponent(input.requestId)}`,
160
+ init: jsonRequestInit("POST", input.body),
161
+ malformed: "Malformed approval response",
162
+ error: apiResponseError("Couldn't resolve approval"),
163
+ })
186
164
  ).request;
187
165
  }
188
166
 
@@ -197,6 +175,13 @@ export async function fetchAuthMe(): Promise<AuthMeResponseBody> {
197
175
  return readJsonObject<AuthMeResponseBody>(res, "Malformed auth status response");
198
176
  }
199
177
 
178
+ export async function logout(): Promise<void> {
179
+ const res = await getFetchImpl()(resolveApiUrl("/auth/logout"), { method: "POST" });
180
+ if (!res.ok) {
181
+ throw new ApiResponseError(`Couldn't log out: ${res.status}`, res.status);
182
+ }
183
+ }
184
+
200
185
  export interface AuthMeRetryOptions {
201
186
  maxAttempts?: number;
202
187
  baseDelayMs?: number;
@@ -258,6 +243,10 @@ export async function fetchAuthMeWithRetry(
258
243
  }
259
244
 
260
245
  export type LauncherSubmitResult =
246
+ | {
247
+ kind: "launch_started";
248
+ launchRunId: string;
249
+ }
261
250
  | {
262
251
  kind: "success";
263
252
  process: ProcessInstance;
@@ -267,13 +256,6 @@ export type LauncherSubmitResult =
267
256
  kind: "scheduled";
268
257
  futureExecution: FutureLaunchSummary;
269
258
  }
270
- | {
271
- kind: "partial_success";
272
- status: number;
273
- warning: string;
274
- process: ProcessInstance;
275
- projects: ProcessProject[];
276
- }
277
259
  | {
278
260
  kind: "validation_error";
279
261
  status: number;
@@ -285,47 +267,6 @@ export type LauncherSubmitResult =
285
267
  error: string;
286
268
  };
287
269
 
288
- const unknownRecordSchema = v.pipe(
289
- v.unknown(),
290
- v.check(
291
- (value) => typeof value === "object" && value !== null && !Array.isArray(value),
292
- "Expected object",
293
- ),
294
- v.record(v.string(), v.unknown()),
295
- );
296
-
297
- async function tryReadJson(response: Response): Promise<unknown> {
298
- try {
299
- return await response.json();
300
- } catch {
301
- return null;
302
- }
303
- }
304
-
305
- async function readJsonObject<T extends object>(response: Response, context: string): Promise<T> {
306
- const body = await tryReadJson(response);
307
- if (!v.safeParse(unknownRecordSchema, body).success) {
308
- throw new Error(`${context}: response body must be a JSON object`);
309
- }
310
- return body as T;
311
- }
312
-
313
- function readOptionalString(value: unknown): string | null {
314
- return typeof value === "string" ? value : null;
315
- }
316
-
317
- function readErrorMessage(body: unknown): string | null {
318
- const response = body as (ErrorResponseBody & { message?: unknown }) | null;
319
- const error = readOptionalString(response?.error) ?? readOptionalString(response?.message);
320
- return error && error.trim() !== "" ? error : null;
321
- }
322
-
323
- async function requireSuccessfulMutation(response: Response, fallbackError: string): Promise<void> {
324
- if (response.ok) return;
325
- const body = await tryReadJson(response);
326
- throw new Error(readErrorMessage(body) ?? `${fallbackError}: ${response.status}`);
327
- }
328
-
329
270
  function isLauncherValidationError(value: unknown): value is LauncherValidationError {
330
271
  const parsedValue = v.safeParse(unknownRecordSchema, value);
331
272
  if (!parsedValue.success) {
@@ -351,9 +292,11 @@ export async function fetchProcessesList(): Promise<{
351
292
  processes: ProcessOverviewItem[];
352
293
  futureExecutions: FutureExecutionOverviewItem[];
353
294
  }> {
354
- const res = await getFetchImpl()(resolveApiUrl("/api/processes/overview"));
355
- if (!res.ok) throw new Error(`Couldn't load the process list: ${res.status}`);
356
- return readJsonObject<ProcessesOverviewResponseBody>(res, "Malformed process overview response");
295
+ return requestStatusJson<ProcessesOverviewResponseBody>(
296
+ "/api/processes/overview",
297
+ "Couldn't load the process list",
298
+ "Malformed process overview response",
299
+ );
357
300
  }
358
301
 
359
302
  export interface ProcessBrowseRequest {
@@ -376,49 +319,55 @@ export async function fetchProcessBrowse(
376
319
  }
377
320
  }
378
321
  const query = params.size > 0 ? `?${params.toString()}` : "";
379
- const res = await getFetchImpl()(resolveApiUrl(`/api/processes/browse${query}`));
380
- if (!res.ok) throw new Error(`Couldn't browse processes: ${res.status}`);
381
- return readJsonObject<ProcessBrowseResponseBody>(res, "Malformed process browse response");
322
+ return requestStatusJson(
323
+ `/api/processes/browse${query}`,
324
+ "Couldn't browse processes",
325
+ "Malformed process browse response",
326
+ );
382
327
  }
383
328
 
384
329
  export async function fetchLaunchers(): Promise<UiLauncherSummary[]> {
385
- const res = await getFetchImpl()(resolveApiUrl("/api/launchers"));
386
- if (!res.ok) throw new Error(`Couldn't load available processes: ${res.status}`);
387
- const body = await readJsonObject<LaunchersResponseBody>(res, "Malformed launchers response");
330
+ const body = await requestStatusJson<LaunchersResponseBody>(
331
+ "/api/launchers",
332
+ "Couldn't load available processes",
333
+ "Malformed launchers response",
334
+ );
388
335
  return body.launchers;
389
336
  }
390
337
 
391
338
  export async function fetchWatchers(): Promise<WatcherSummary[]> {
392
- const res = await getFetchImpl()(resolveApiUrl("/api/watchers"));
393
- if (!res.ok) throw new Error(`Couldn't load registered watchers: ${res.status}`);
394
- const body = await readJsonObject<WatchersResponseBody>(res, "Malformed watchers response");
339
+ const body = await requestStatusJson<WatchersResponseBody>(
340
+ "/api/watchers",
341
+ "Couldn't load registered watchers",
342
+ "Malformed watchers response",
343
+ );
395
344
  return body.watchers;
396
345
  }
397
346
 
398
347
  export async function fetchSkills(): Promise<SkillsCatalogResponseBody> {
399
- const res = await getFetchImpl()(resolveApiUrl("/api/skills"));
400
- if (!res.ok) throw new Error(`Couldn't load the skill catalog: ${res.status}`);
401
- return readJsonObject<SkillsCatalogResponseBody>(res, "Malformed skill catalog response");
348
+ return requestStatusJson(
349
+ "/api/skills",
350
+ "Couldn't load the skill catalog",
351
+ "Malformed skill catalog response",
352
+ );
402
353
  }
403
354
 
404
355
  export async function refreshSkills(): Promise<SkillsCatalogResponseBody> {
405
- const res = await getFetchImpl()(resolveApiUrl("/api/skills/refresh"), { method: "POST" });
406
- if (!res.ok) throw new Error(`Couldn't refresh skill repositories: ${res.status}`);
407
- return readJsonObject<SkillsCatalogResponseBody>(res, "Malformed skill catalog response");
356
+ return requestStatusJson(
357
+ "/api/skills/refresh",
358
+ "Couldn't refresh skill repositories",
359
+ "Malformed skill catalog response",
360
+ { method: "POST" },
361
+ );
408
362
  }
409
363
 
410
364
  export async function fetchSkillDetail(
411
365
  repositoryId: string,
412
366
  skillId: string,
413
367
  ): Promise<SkillCatalogDetail> {
414
- const res = await getFetchImpl()(
415
- resolveApiUrl(
416
- `/api/skills/available/${encodeURIComponent(repositoryId)}/${encodeURIComponent(skillId)}`,
417
- ),
418
- );
419
- if (!res.ok) throw new Error(`Couldn't load skill details: ${res.status}`);
420
- const body = await readJsonObject<SkillCatalogDetailResponseBody>(
421
- res,
368
+ const body = await requestStatusJson<SkillCatalogDetailResponseBody>(
369
+ `/api/skills/available/${encodeURIComponent(repositoryId)}/${encodeURIComponent(skillId)}`,
370
+ "Couldn't load skill details",
422
371
  "Malformed skill detail response",
423
372
  );
424
373
  return body.skill;
@@ -427,57 +376,46 @@ export async function fetchSkillDetail(
427
376
  export async function fetchInstalledSkillDetail(
428
377
  skillId: string,
429
378
  ): Promise<InstalledSkillCatalogDetail> {
430
- const res = await getFetchImpl()(
431
- resolveApiUrl(`/api/skills/installed/${encodeURIComponent(skillId)}`),
432
- );
433
- if (!res.ok) throw new Error(`Couldn't load installed skill details: ${res.status}`);
434
- const body = await readJsonObject<InstalledSkillCatalogDetailResponseBody>(
435
- res,
379
+ const body = await requestStatusJson<InstalledSkillCatalogDetailResponseBody>(
380
+ `/api/skills/installed/${encodeURIComponent(skillId)}`,
381
+ "Couldn't load installed skill details",
436
382
  "Malformed installed skill detail response",
437
383
  );
438
384
  return body.skill;
439
385
  }
440
386
 
441
387
  export async function registerSkill(repositoryId: string, skillId: string): Promise<void> {
442
- const res = await getFetchImpl()(
443
- resolveApiUrl(
444
- `/api/skills/available/${encodeURIComponent(repositoryId)}/${encodeURIComponent(skillId)}/register`,
445
- ),
388
+ return requestMutation(
389
+ `/api/skills/available/${encodeURIComponent(repositoryId)}/${encodeURIComponent(skillId)}/register`,
390
+ "Couldn't register the skill",
446
391
  { method: "POST" },
447
392
  );
448
- await requireSuccessfulMutation(res, "Couldn't register the skill");
449
393
  }
450
394
 
451
395
  export async function removeSkill(skillId: string): Promise<void> {
452
- const res = await getFetchImpl()(
453
- resolveApiUrl(`/api/skills/installed/${encodeURIComponent(skillId)}`),
396
+ return requestMutation(
397
+ `/api/skills/installed/${encodeURIComponent(skillId)}`,
398
+ "Couldn't remove the skill",
454
399
  { method: "DELETE" },
455
400
  );
456
- await requireSuccessfulMutation(res, "Couldn't remove the skill");
457
401
  }
458
402
 
459
- export async function fetchLauncherDefaults(launcherId: string): Promise<{
460
- defaults: Record<string, unknown>;
461
- title: string | null;
462
- modelConfig: LauncherModelConfigDefaults;
463
- warnings?: LauncherValidationError[];
464
- }> {
465
- const res = await getFetchImpl()(
466
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/defaults`),
403
+ export async function fetchLauncherDefaults(
404
+ launcherId: string,
405
+ ): Promise<LauncherDefaultsResponseBody> {
406
+ return requestStatusJson(
407
+ `/api/launchers/${encodeURIComponent(launcherId)}/defaults`,
408
+ "Couldn't load default values",
409
+ "Malformed launcher defaults response",
467
410
  );
468
- if (!res.ok) throw new Error(`Couldn't load default values: ${res.status}`);
469
- return readJsonObject<LauncherDefaultsResponseBody>(res, "Malformed launcher defaults response");
470
411
  }
471
412
 
472
413
  export async function fetchLauncherRecentValues(
473
414
  launcherId: string,
474
415
  ): Promise<Record<string, readonly string[]>> {
475
- const res = await getFetchImpl()(
476
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/recent-values`),
477
- );
478
- if (!res.ok) throw new Error(`Couldn't load recent launcher values: ${res.status}`);
479
- const body = await readJsonObject<LauncherRecentValuesResponseBody>(
480
- res,
416
+ const body = await requestStatusJson<LauncherRecentValuesResponseBody>(
417
+ `/api/launchers/${encodeURIComponent(launcherId)}/recent-values`,
418
+ "Couldn't load recent launcher values",
481
419
  "Malformed launcher recent values response",
482
420
  );
483
421
  return body.values;
@@ -487,18 +425,11 @@ export async function fetchLauncherOptions(
487
425
  launcherId: string,
488
426
  launcherInput: Record<string, unknown>,
489
427
  ): Promise<Record<string, readonly LauncherFieldOptionDefinition[]>> {
490
- const res = await getFetchImpl()(
491
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/options`),
492
- {
493
- method: "POST",
494
- headers: { "content-type": "application/json" },
495
- body: JSON.stringify({ launcherInput }),
496
- },
497
- );
498
- if (!res.ok) throw new Error(`Couldn't refresh the available options: ${res.status}`);
499
- const body = await readJsonObject<LauncherOptionsResponseBody>(
500
- res,
428
+ const body = await requestStatusJson<LauncherOptionsResponseBody>(
429
+ `/api/launchers/${encodeURIComponent(launcherId)}/options`,
430
+ "Couldn't refresh the available options",
501
431
  "Malformed launcher options response",
432
+ jsonRequestInit("POST", { launcherInput }),
502
433
  );
503
434
  return body.options;
504
435
  }
@@ -508,18 +439,11 @@ export async function fetchLauncherModelConfigPreview(
508
439
  launcherInput: Record<string, unknown>,
509
440
  modelConfig: LauncherModelConfigDefaults = {},
510
441
  ): Promise<LauncherModelConfigPreview> {
511
- const res = await getFetchImpl()(
512
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/model-config-preview`),
513
- {
514
- method: "POST",
515
- headers: { "content-type": "application/json" },
516
- body: JSON.stringify({ launcherInput, modelConfig }),
517
- },
518
- );
519
- if (!res.ok) throw new Error(`Couldn't refresh the model preview: ${res.status}`);
520
- const body = await readJsonObject<LauncherModelConfigPreviewResponseBody>(
521
- res,
442
+ const body = await requestStatusJson<LauncherModelConfigPreviewResponseBody>(
443
+ `/api/launchers/${encodeURIComponent(launcherId)}/model-config-preview`,
444
+ "Couldn't refresh the model preview",
522
445
  "Malformed launcher model preview response",
446
+ jsonRequestInit("POST", { launcherInput, modelConfig }),
523
447
  );
524
448
  return body.preview;
525
449
  }
@@ -527,8 +451,8 @@ export async function fetchLauncherModelConfigPreview(
527
451
  async function parseLauncherErrorResponse(
528
452
  res: Response,
529
453
  fallbackMessagePrefix: string,
454
+ body: unknown,
530
455
  ): Promise<LauncherSubmitResult> {
531
- const body = await tryReadJson(res);
532
456
  const errors = readLauncherValidationErrors(body);
533
457
  if (errors.length > 0) {
534
458
  return { kind: "validation_error", status: res.status, errors };
@@ -540,6 +464,59 @@ async function parseLauncherErrorResponse(
540
464
  };
541
465
  }
542
466
 
467
+ export async function fetchLaunchRun(
468
+ launchRunId: string,
469
+ ): Promise<LaunchRunResponseBody["launchRun"]> {
470
+ return (
471
+ await requestJson<LaunchRunResponseBody>({
472
+ path: `/api/launch-runs/${encodeURIComponent(launchRunId)}`,
473
+ malformed: "Malformed launch run response",
474
+ error: (response) =>
475
+ new ApiResponseError(`Couldn't load launch progress: ${response.status}`, response.status),
476
+ })
477
+ ).launchRun;
478
+ }
479
+
480
+ export async function fetchProcessLaunchRuns(
481
+ instanceId: string,
482
+ ): Promise<ProcessLaunchRunsResponseBody["launchRuns"]> {
483
+ return (
484
+ await requestJson<ProcessLaunchRunsResponseBody>({
485
+ path: `/api/processes/${encodeURIComponent(instanceId)}/launch-runs`,
486
+ malformed: "Malformed process launch runs response",
487
+ error: (response) =>
488
+ new ApiResponseError(`Couldn't load launch progress: ${response.status}`, response.status),
489
+ })
490
+ ).launchRuns;
491
+ }
492
+
493
+ export async function startLaunchRun(
494
+ launcherId: string,
495
+ title: string | null,
496
+ launcherInput: Record<string, unknown>,
497
+ modelConfig: LauncherModelConfigDefaults = {},
498
+ skillIds: readonly string[] = [],
499
+ ): Promise<LauncherSubmitResult> {
500
+ const init = jsonRequestInit("POST", {
501
+ title,
502
+ launcherInput,
503
+ modelConfig,
504
+ schedule: { mode: "now" },
505
+ skillIds,
506
+ });
507
+ init.headers = { ...init.headers, "idempotency-key": crypto.randomUUID() };
508
+ const response = await requestJson<StartLaunchRunResponseBody | LauncherSubmitResult>({
509
+ path: `/api/launchers/${encodeURIComponent(launcherId)}/launch-runs`,
510
+ init,
511
+ malformed: "Malformed launch run response",
512
+ onError: (response, body) =>
513
+ parseLauncherErrorResponse(response, "Couldn't start this process", body),
514
+ });
515
+ return "launchRunId" in response
516
+ ? { kind: "launch_started", launchRunId: response.launchRunId }
517
+ : response;
518
+ }
519
+
543
520
  export async function launchLauncher(
544
521
  launcherId: string,
545
522
  title: string | null,
@@ -548,74 +525,49 @@ export async function launchLauncher(
548
525
  schedule: ScheduleConfigInput = { mode: "now" },
549
526
  skillIds: readonly string[] = [],
550
527
  ): Promise<LauncherSubmitResult> {
528
+ if (schedule.mode === "now") {
529
+ return startLaunchRun(launcherId, title, launcherInput, modelConfig, skillIds);
530
+ }
551
531
  const res = await getFetchImpl()(
552
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/launch`),
553
- {
554
- method: "POST",
555
- headers: { "content-type": "application/json" },
556
- body: JSON.stringify({ title, launcherInput, modelConfig, schedule, skillIds }),
557
- },
532
+ resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/future-launches`),
533
+ jsonRequestInit("POST", { title, launcherInput, modelConfig, schedule, skillIds }),
558
534
  );
559
535
  if (!res.ok) {
560
- return parseLauncherErrorResponse(res, "Couldn't start this process");
536
+ return parseLauncherErrorResponse(res, "Couldn't start this process", await tryReadJson(res));
561
537
  }
562
- const body = await readJsonObject<LauncherMutationResponseBody>(
538
+ const body = await readJsonObject<FutureLaunchMutationResponseBody>(
563
539
  res,
564
- "Malformed launcher launch response",
540
+ "Malformed future launch response",
565
541
  );
566
- const projects = body.projects ?? [];
567
- const errorMessage = body.error ?? `Couldn't start this process: ${res.status}`;
568
- if (res.status === 201 && body.futureExecution) {
569
- return { kind: "scheduled", futureExecution: body.futureExecution };
570
- }
571
- if (res.status === 201 && body.process) {
572
- return { kind: "success", process: body.process, projects };
573
- }
574
- if (body.process) {
575
- return {
576
- kind: "partial_success",
577
- status: res.status,
578
- warning: errorMessage,
579
- process: body.process,
580
- projects,
581
- };
582
- }
583
- const errors = body.errors ?? [];
584
- if (errors.length > 0) {
585
- return { kind: "validation_error", status: res.status, errors };
586
- }
587
- return { kind: "failure", status: res.status, error: errorMessage };
542
+ return body.futureExecution
543
+ ? { kind: "scheduled", futureExecution: body.futureExecution }
544
+ : {
545
+ kind: "failure",
546
+ status: res.status,
547
+ error: body.error ?? "The future launch response did not include the saved launch",
548
+ };
588
549
  }
589
550
 
590
551
  export async function fetchProcessDiagnostics(instanceId: string): Promise<ProcessDiagnosticsData> {
591
- const res = await getFetchImpl()(
592
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/diagnostics`),
593
- );
594
- if (!res.ok) throw new Error(`Couldn't load this process: ${res.status}`);
595
- return readJsonObject<ProcessDiagnosticsResponseBody>(
596
- res,
552
+ return requestStatusJson<ProcessDiagnosticsResponseBody>(
553
+ `/api/processes/${encodeURIComponent(instanceId)}/diagnostics`,
554
+ "Couldn't load this process",
597
555
  "Malformed process diagnostics response",
598
556
  );
599
557
  }
600
558
 
601
559
  export async function fetchPrimaryPathSnapshot(instanceId: string): Promise<PrimaryPathSnapshot> {
602
- const res = await getFetchImpl()(
603
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/primary-path`),
604
- );
605
- if (!res.ok) throw new Error(`Couldn't load this process: ${res.status}`);
606
- return readJsonObject<PrimaryPathSnapshotResponseBody>(
607
- res,
560
+ return requestStatusJson<PrimaryPathSnapshotResponseBody>(
561
+ `/api/processes/${encodeURIComponent(instanceId)}/primary-path`,
562
+ "Couldn't load this process",
608
563
  "Malformed primary path snapshot response",
609
564
  );
610
565
  }
611
566
 
612
567
  export async function fetchProcessDetail(instanceId: string): Promise<ProcessDetailData> {
613
- const res = await getFetchImpl()(
614
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/ui-snapshot`),
615
- );
616
- if (!res.ok) throw new Error(`Couldn't load this process: ${res.status}`);
617
- return readJsonObject<ProcessDetailUiSnapshotResponseBody>(
618
- res,
568
+ return requestStatusJson(
569
+ `/api/processes/${encodeURIComponent(instanceId)}/ui-snapshot`,
570
+ "Couldn't load this process",
619
571
  "Malformed process UI snapshot response",
620
572
  );
621
573
  }
@@ -626,7 +578,7 @@ export async function fetchTurnReasoningDetail(
626
578
  sessionSignature: string | null,
627
579
  signal?: AbortSignal,
628
580
  ): Promise<TurnReasoningDetailResponseBody> {
629
- const params = new URLSearchParams({ sessionSignature: sessionSignature ?? "" });
581
+ const params = new URLSearchParams(sessionSignature === null ? {} : { sessionSignature });
630
582
  const res = await getFetchImpl()(
631
583
  resolveApiUrl(
632
584
  `/api/processes/${encodeURIComponent(instanceId)}/turn-records/${encodeURIComponent(turnRecordId)}/reasoning?${params.toString()}`,
@@ -648,16 +600,11 @@ export async function fetchTurnReasoningDetail(
648
600
  export async function fetchFutureExecution(
649
601
  futureExecutionId: string,
650
602
  ): Promise<FutureExecutionDetailResponseBody> {
651
- const res = await getFetchImpl()(
652
- resolveApiUrl(`/api/future-executions/${encodeURIComponent(futureExecutionId)}`),
653
- );
654
- if (!res.ok) {
655
- throw new ApiResponseError(`Couldn't load scheduled item: ${res.status}`, res.status);
656
- }
657
- return readJsonObject<FutureExecutionDetailResponseBody>(
658
- res,
659
- "Malformed scheduled item response",
660
- );
603
+ return requestJson({
604
+ path: `/api/future-executions/${encodeURIComponent(futureExecutionId)}`,
605
+ error: (res) => new ApiResponseError(`Couldn't load scheduled item: ${res.status}`, res.status),
606
+ malformed: "Malformed scheduled item response",
607
+ });
661
608
  }
662
609
 
663
610
  export async function postProcessRetry(
@@ -665,20 +612,11 @@ export async function postProcessRetry(
665
612
  nextTurnModelProfileId?: string | null,
666
613
  providerOptions?: Readonly<Record<string, string>>,
667
614
  ): Promise<void> {
668
- const res = await getFetchImpl()(
669
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/retry`),
670
- {
671
- method: "POST",
672
- headers: { "content-type": "application/json" },
673
- body: JSON.stringify({
674
- ...(nextTurnModelProfileId === undefined ? {} : { nextTurnModelProfileId }),
675
- ...(providerOptions === undefined ? {} : { providerOptions }),
676
- }),
677
- },
615
+ return requestMutation(
616
+ `/api/processes/${encodeURIComponent(instanceId)}/retry`,
617
+ (response) => new Error(`Couldn't retry this process: ${response.status}`),
618
+ jsonRequestInit("POST", { nextTurnModelProfileId, providerOptions }),
678
619
  );
679
- if (!res.ok) {
680
- throw new Error(`Couldn't retry this process: ${res.status}`);
681
- }
682
620
  }
683
621
 
684
622
  export async function fetchModelProviderOptions(
@@ -690,10 +628,7 @@ export async function fetchModelProviderOptions(
690
628
  `/api/processes/${encodeURIComponent(instanceId)}/model-profiles/${encodeURIComponent(modelProfileId)}/provider-options`,
691
629
  ),
692
630
  );
693
- if (!res.ok) {
694
- const body = await tryReadJson(res);
695
- throw new Error(readErrorMessage(body) ?? `Couldn't load provider options: ${res.status}`);
696
- }
631
+ await requireSuccessfulResponse(res, "Couldn't load provider options");
697
632
  return (await res.json()) as ModelProviderOptionsResponseBody;
698
633
  }
699
634
 
@@ -704,24 +639,11 @@ export async function postProcessTurnContinue(
704
639
  nextTurnModelProfileId?: string | null,
705
640
  providerOptions?: Readonly<Record<string, string>>,
706
641
  ): Promise<void> {
707
- const res = await getFetchImpl()(
708
- resolveApiUrl(
709
- `/api/processes/${encodeURIComponent(instanceId)}/turn-records/${encodeURIComponent(turnRecordId)}/continue`,
710
- ),
711
- {
712
- method: "POST",
713
- headers: { "content-type": "application/json" },
714
- body: JSON.stringify({
715
- ...(prompt === undefined ? {} : { prompt }),
716
- ...(nextTurnModelProfileId === undefined ? {} : { nextTurnModelProfileId }),
717
- ...(providerOptions === undefined ? {} : { providerOptions }),
718
- }),
719
- },
642
+ return requestMutation(
643
+ `/api/processes/${encodeURIComponent(instanceId)}/turn-records/${encodeURIComponent(turnRecordId)}/continue`,
644
+ "Couldn't continue this failed turn",
645
+ jsonRequestInit("POST", { prompt, nextTurnModelProfileId, providerOptions }),
720
646
  );
721
- if (!res.ok) {
722
- const body = await tryReadJson(res);
723
- throw new Error(readErrorMessage(body) ?? `Couldn't continue this failed turn: ${res.status}`);
724
- }
725
647
  }
726
648
 
727
649
  export async function postProcessStartupRetry(
@@ -730,58 +652,65 @@ export async function postProcessStartupRetry(
730
652
  nextTurnModelProfileId?: string | null,
731
653
  providerOptions?: Readonly<Record<string, string>>,
732
654
  ): Promise<void> {
733
- const res = await getFetchImpl()(
734
- resolveApiUrl(
735
- `/api/processes/${encodeURIComponent(instanceId)}/turn-starts/${encodeURIComponent(startRecordId)}/retry`,
736
- ),
737
- {
738
- method: "POST",
739
- headers: { "content-type": "application/json" },
740
- body: JSON.stringify({
741
- ...(nextTurnModelProfileId === undefined ? {} : { nextTurnModelProfileId }),
742
- ...(providerOptions === undefined ? {} : { providerOptions }),
743
- }),
744
- },
655
+ return requestMutation(
656
+ `/api/processes/${encodeURIComponent(instanceId)}/turn-starts/${encodeURIComponent(startRecordId)}/retry`,
657
+ "Couldn't retry worker startup",
658
+ jsonRequestInit("POST", { nextTurnModelProfileId, providerOptions }),
659
+ );
660
+ }
661
+
662
+ export interface SessionTransferGrantResponse {
663
+ transferUrl: string;
664
+ expiresAt: string;
665
+ }
666
+
667
+ export async function createSessionTransferGrant(
668
+ instanceId: string,
669
+ ): Promise<SessionTransferGrantResponse> {
670
+ return requestJson<SessionTransferGrantResponse>({
671
+ path: `/api/processes/${encodeURIComponent(instanceId)}/session-transfers`,
672
+ init: { method: "POST" },
673
+ malformed: "Malformed transfer link response",
674
+ error: "Couldn't create local transfer link",
675
+ });
676
+ }
677
+
678
+ export async function cancelSessionTransfer(instanceId: string, attemptId: string): Promise<void> {
679
+ return requestMutation(
680
+ `/api/processes/${encodeURIComponent(instanceId)}/session-transfers/${encodeURIComponent(attemptId)}/cancel`,
681
+ "Couldn't cancel the local session transfer",
682
+ { method: "POST" },
745
683
  );
746
- if (!res.ok) {
747
- const body = await tryReadJson(res);
748
- throw new Error(readErrorMessage(body) ?? `Couldn't retry worker startup: ${res.status}`);
749
- }
750
684
  }
751
685
 
752
686
  export async function deleteProcess(instanceId: string): Promise<void> {
753
- const response = await getFetchImpl()(
754
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}`),
687
+ return requestMutation(
688
+ `/api/processes/${encodeURIComponent(instanceId)}`,
689
+ "Couldn't delete this process",
755
690
  { method: "DELETE" },
756
691
  );
757
- await requireSuccessfulMutation(response, "Couldn't delete this process");
758
692
  }
759
693
 
760
694
  export async function postProcessAbort(instanceId: string): Promise<void> {
761
- const response = await getFetchImpl()(
762
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/abort`),
695
+ return requestMutation(
696
+ `/api/processes/${encodeURIComponent(instanceId)}/abort`,
697
+ "Couldn't abort this process",
763
698
  { method: "POST" },
764
699
  );
765
- await requireSuccessfulMutation(response, "Couldn't abort this process");
766
700
  }
767
701
 
768
702
  export async function postProcessAbortTurn(instanceId: string): Promise<void> {
769
- const response = await getFetchImpl()(
770
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/abort-turn`),
703
+ return requestMutation(
704
+ `/api/processes/${encodeURIComponent(instanceId)}/abort-turn`,
705
+ "Couldn't stop this turn",
771
706
  { method: "POST" },
772
707
  );
773
- await requireSuccessfulMutation(response, "Couldn't stop this turn");
774
708
  }
775
709
 
776
710
  export async function fetchProcessRetryConfig(instanceId: string): Promise<ProcessRetryConfig> {
777
- const res = await getFetchImpl()(
778
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/retry-config`),
779
- );
780
- if (!res.ok) {
781
- throw new Error(`Couldn't load retry config: ${res.status}`);
782
- }
783
- return readJsonObject<ProcessRetryConfigResponseBody>(
784
- res,
711
+ return requestStatusJson<ProcessRetryConfigResponseBody>(
712
+ `/api/processes/${encodeURIComponent(instanceId)}/retry-config`,
713
+ "Couldn't load retry config",
785
714
  "Malformed process retry config response",
786
715
  );
787
716
  }
@@ -795,26 +724,12 @@ export async function fetchProcessActionModelPreview(
795
724
  actionId: string,
796
725
  input: Record<string, unknown> = {},
797
726
  ): Promise<ProcessActionModelPreview> {
798
- const res = await getFetchImpl()(
799
- resolveApiUrl(
800
- `/api/processes/${encodeURIComponent(instanceId)}/actions/${encodeURIComponent(actionId)}/model-preview`,
801
- ),
802
- {
803
- method: "POST",
804
- headers: { "content-type": "application/json" },
805
- body: JSON.stringify({ input }),
806
- },
807
- );
808
- if (!res.ok) {
809
- const body = await tryReadJson(res);
810
- throw new Error(
811
- readErrorMessage(body) ?? `Couldn't refresh the action model preview: ${res.status}`,
812
- );
813
- }
814
- const body = await readJsonObject<ProcessActionModelPreviewResponseBody>(
815
- res,
816
- "Malformed process action model preview response",
817
- );
727
+ const body = await requestJson<ProcessActionModelPreviewResponseBody>({
728
+ path: `/api/processes/${encodeURIComponent(instanceId)}/actions/${encodeURIComponent(actionId)}/model-preview`,
729
+ init: jsonRequestInit("POST", { input }),
730
+ error: "Couldn't refresh the action model preview",
731
+ malformed: "Malformed process action model preview response",
732
+ });
818
733
  return body.preview;
819
734
  }
820
735
 
@@ -827,32 +742,16 @@ export async function postProcessAction(
827
742
  schedule?: ScheduleConfigInput;
828
743
  } = {},
829
744
  ): Promise<ProcessActionSubmitResult> {
830
- const res = await getFetchImpl()(
831
- resolveApiUrl(
832
- `/api/processes/${encodeURIComponent(instanceId)}/actions/${encodeURIComponent(actionId)}`,
833
- ),
834
- {
835
- method: "POST",
836
- headers: { "content-type": "application/json" },
837
- body: JSON.stringify({
838
- input,
839
- schedule: opts.schedule ?? { mode: "now" },
840
- ...(opts.nextTurnModelProfileId !== undefined
841
- ? { nextTurnModelProfileId: opts.nextTurnModelProfileId }
842
- : {}),
843
- }),
844
- },
845
- );
846
- if (!res.ok) {
847
- const body = await tryReadJson(res);
848
- throw new Error(
849
- readErrorMessage(body) ?? `Couldn't run "${formatDefinition(actionId)}": ${res.status}`,
850
- );
851
- }
852
- const body = await readJsonObject<ScheduledActionMutationResponseBody>(
853
- res,
854
- "Malformed process action response",
855
- );
745
+ const body = await requestJson<ScheduledActionMutationResponseBody>({
746
+ path: `/api/processes/${encodeURIComponent(instanceId)}/actions/${encodeURIComponent(actionId)}`,
747
+ init: jsonRequestInit("POST", {
748
+ input,
749
+ schedule: opts.schedule ?? { mode: "now" },
750
+ nextTurnModelProfileId: opts.nextTurnModelProfileId,
751
+ }),
752
+ error: `Couldn't run "${formatDefinition(actionId)}"`,
753
+ malformed: "Malformed process action response",
754
+ });
856
755
  if (body.scheduledAction) {
857
756
  return { kind: "scheduled", scheduledAction: body.scheduledAction };
858
757
  }
@@ -869,14 +768,14 @@ export async function updateScheduledLaunch(
869
768
  ): Promise<LauncherSubmitResult> {
870
769
  const res = await getFetchImpl()(
871
770
  resolveApiUrl(`/api/future-executions/${encodeURIComponent(futureExecutionId)}/launch`),
872
- {
873
- method: "PUT",
874
- headers: { "content-type": "application/json" },
875
- body: JSON.stringify({ title, launcherInput, modelConfig, schedule, skillIds }),
876
- },
771
+ jsonRequestInit("PUT", { title, launcherInput, modelConfig, schedule, skillIds }),
877
772
  );
878
773
  if (!res.ok) {
879
- return parseLauncherErrorResponse(res, "Couldn't update this scheduled launch");
774
+ return parseLauncherErrorResponse(
775
+ res,
776
+ "Couldn't update this scheduled launch",
777
+ await tryReadJson(res),
778
+ );
880
779
  }
881
780
  const body = await readJsonObject<LauncherMutationResponseBody>(
882
781
  res,
@@ -905,30 +804,16 @@ export async function updateScheduledAction(
905
804
  schedule: ScheduleConfigInput;
906
805
  },
907
806
  ): Promise<ProcessActionSubmitResult> {
908
- const res = await getFetchImpl()(
909
- resolveApiUrl(`/api/future-executions/${encodeURIComponent(futureExecutionId)}/action`),
910
- {
911
- method: "PUT",
912
- headers: { "content-type": "application/json" },
913
- body: JSON.stringify({
914
- input,
915
- schedule: opts.schedule,
916
- ...(opts.nextTurnModelProfileId !== undefined
917
- ? { nextTurnModelProfileId: opts.nextTurnModelProfileId }
918
- : {}),
919
- }),
920
- },
921
- );
922
- if (!res.ok) {
923
- const body = await tryReadJson(res);
924
- throw new Error(
925
- readErrorMessage(body) ?? `Couldn't update this scheduled action: ${res.status}`,
926
- );
927
- }
928
- const body = await readJsonObject<ScheduledActionMutationResponseBody>(
929
- res,
930
- "Malformed scheduled action update response",
931
- );
807
+ const body = await requestJson<ScheduledActionMutationResponseBody>({
808
+ path: `/api/future-executions/${encodeURIComponent(futureExecutionId)}/action`,
809
+ init: jsonRequestInit("PUT", {
810
+ input,
811
+ schedule: opts.schedule,
812
+ nextTurnModelProfileId: opts.nextTurnModelProfileId,
813
+ }),
814
+ error: "Couldn't update this scheduled action",
815
+ malformed: "Malformed scheduled action update response",
816
+ });
932
817
  if (body.scheduledAction) {
933
818
  return { kind: "scheduled", scheduledAction: body.scheduledAction };
934
819
  }
@@ -936,30 +821,20 @@ export async function updateScheduledAction(
936
821
  }
937
822
 
938
823
  export async function deleteFutureExecution(futureExecutionId: string): Promise<void> {
939
- const res = await getFetchImpl()(
940
- resolveApiUrl(`/api/future-executions/${encodeURIComponent(futureExecutionId)}`),
824
+ return requestMutation(
825
+ `/api/future-executions/${encodeURIComponent(futureExecutionId)}`,
826
+ "Couldn't cancel this scheduled item",
941
827
  { method: "DELETE" },
942
828
  );
943
- if (!res.ok) {
944
- const body = await tryReadJson(res);
945
- throw new Error(readErrorMessage(body) ?? `Couldn't cancel this scheduled item: ${res.status}`);
946
- }
947
829
  }
948
830
 
949
831
  export async function previewCronExpression(expression: string): Promise<string> {
950
- const res = await getFetchImpl()(resolveApiUrl("/api/future-executions/cron-preview"), {
951
- method: "POST",
952
- headers: { "content-type": "application/json" },
953
- body: JSON.stringify({ expression }),
832
+ const body = await requestJson<CronPreviewResponseBody>({
833
+ path: "/api/future-executions/cron-preview",
834
+ init: jsonRequestInit("POST", { expression }),
835
+ error: "Couldn't preview this cron",
836
+ malformed: "Malformed cron preview response",
954
837
  });
955
- if (!res.ok) {
956
- const body = await tryReadJson(res);
957
- throw new Error(readErrorMessage(body) ?? `Couldn't preview this cron: ${res.status}`);
958
- }
959
- const body = await readJsonObject<CronPreviewResponseBody>(
960
- res,
961
- "Malformed cron preview response",
962
- );
963
838
  if (typeof body.nextRunAt !== "string") {
964
839
  throw new Error("Malformed cron preview response: nextRunAt must be a string");
965
840
  }