@leitwerk-dev/ui 0.1.9 → 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 (170) 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-CSkNdC4m.js +1 -0
  10. package/dist/assets/PageHeader-DPuQInDo.css +1 -0
  11. package/dist/assets/PageHeader-sphJnWL1.js +1 -0
  12. package/dist/assets/ProcessActionsMenu-DLMywI9c.js +1 -0
  13. package/dist/assets/ProcessActionsMenu-VKT7PE6z.css +1 -0
  14. package/dist/assets/ProcessDetailPage-Cth6A0DN.css +1 -0
  15. package/dist/assets/ProcessDetailPage-fvvdvO19.js +14 -0
  16. package/dist/assets/ProcessFlowDiagram-Dx2wheGN.js +2 -0
  17. package/dist/assets/ProcessesPage-uLl7LXp8.js +1 -0
  18. package/dist/assets/ProcessesPage-yPjjrzjg.css +1 -0
  19. package/dist/assets/ScheduleDateTimePicker-DmojMRxN.js +1 -0
  20. package/dist/assets/{ScheduleDateTimePicker-CadXN9z7.css → ScheduleDateTimePicker-uacJAkIq.css} +1 -1
  21. package/dist/assets/SkillsPage-CJrtt8xU.css +1 -0
  22. package/dist/assets/SkillsPage-CotbGUxm.js +2 -0
  23. package/dist/assets/WatchersPage-ByWGNJet.js +1 -0
  24. package/dist/assets/WatchersPage-cRBnmTAD.css +1 -0
  25. package/dist/assets/external-links-CX92-VRP.js +1 -0
  26. package/dist/assets/http-client-VpPXJwbR.js +2 -0
  27. package/dist/assets/index-C7zNe3je.js +6 -0
  28. package/dist/assets/index-DtEI5gsQ.css +1 -0
  29. package/dist/assets/index-client-BYQviCtQ.js +2 -0
  30. package/dist/assets/{mermaid-render.worker-DAVgiVRG.js → mermaid-render.worker-QW2WZpEE.js} +12 -12
  31. package/dist/assets/process-terminal-display-BQRQwGod.js +1 -0
  32. package/dist/assets/router.svelte-EEldxHlO.js +1 -0
  33. package/dist/index.html +8 -8
  34. package/package.json +8 -8
  35. package/src/App.svelte +36 -0
  36. package/src/chronicle/components/ChronicleActionSection.svelte +70 -143
  37. package/src/chronicle/components/ChronicleCreateIssueButton.svelte +22 -0
  38. package/src/chronicle/components/ChronicleEntryHeader.svelte +76 -0
  39. package/src/chronicle/components/ChronicleExpandButton.svelte +11 -34
  40. package/src/chronicle/components/ChronicleFailureMessage.svelte +41 -0
  41. package/src/chronicle/components/ChronicleFlow.svelte +133 -28
  42. package/src/chronicle/components/ChronicleLeafOutcomeRendererHost.svelte +1 -8
  43. package/src/chronicle/components/ChronicleLeafOutcomeSection.svelte +25 -52
  44. package/src/chronicle/components/ChronicleLiveChip.svelte +1 -35
  45. package/src/chronicle/components/ChronicleLiveTail.svelte +55 -154
  46. package/src/chronicle/components/ChronicleMarkdown.svelte +6 -6
  47. package/src/chronicle/components/ChronicleOperatorInputSection.svelte +5 -18
  48. package/src/chronicle/components/ChronicleProcessErrorSection.svelte +10 -107
  49. package/src/chronicle/components/ChroniclePromptSection.svelte +6 -26
  50. package/src/chronicle/components/ChronicleQuestionRequest.svelte +22 -5
  51. package/src/chronicle/components/ChronicleReasoningDetailsOverlay.svelte +71 -109
  52. package/src/chronicle/components/ChronicleRecoverySection.svelte +96 -264
  53. package/src/chronicle/components/ChronicleScheduledActionSection.svelte +1 -1
  54. package/src/chronicle/components/ChronicleSectionHeader.svelte +1 -4
  55. package/src/chronicle/components/ChronicleStartupHistory.svelte +63 -0
  56. package/src/chronicle/components/ChronicleStartupRecoverySection.svelte +10 -26
  57. package/src/chronicle/components/ChronicleThinkingSection.svelte +25 -165
  58. package/src/chronicle/components/ChronicleThinkingText.svelte +1 -0
  59. package/src/chronicle/components/ChronicleToolApproval.svelte +40 -0
  60. package/src/chronicle/components/ChronicleToolCallItem.svelte +1 -1
  61. package/src/chronicle/components/ChronicleTurnCluster.svelte +208 -284
  62. package/src/chronicle/components/ChronicleTurnDetailsButton.svelte +16 -0
  63. package/src/chronicle/components/ChronicleTurnProgress.svelte +77 -54
  64. package/src/chronicle/components/ChronicleTurnRail.svelte +327 -391
  65. package/src/chronicle/components/CompactActionComposer.svelte +36 -13
  66. package/src/chronicle/components/ReadonlyJsonValue.svelte +30 -0
  67. package/src/chronicle/lib/action-bindings.ts +1 -1
  68. package/src/chronicle/lib/action-model-display.ts +2 -2
  69. package/src/chronicle/lib/action-preview.ts +1 -1
  70. package/src/chronicle/lib/chronicle-projection.ts +125 -109
  71. package/src/chronicle/lib/chronicle-rail-groups.ts +158 -0
  72. package/src/chronicle/lib/chronicle-selectable-items.ts +16 -11
  73. package/src/chronicle/lib/chronicle-ticket-artifact.ts +7 -0
  74. package/src/chronicle/lib/formatting.ts +19 -0
  75. package/src/chronicle/lib/leaf-outcome-loader.ts +30 -111
  76. package/src/chronicle/lib/leaf-outcome-runtime.ts +3 -15
  77. package/src/chronicle/lib/result-presentation.ts +40 -0
  78. package/src/chronicle/lib/retry-groups.ts +24 -0
  79. package/src/chronicle/lib/scroll-sync.ts +1 -0
  80. package/src/chronicle/lib/tool-call-summary.ts +1 -9
  81. package/src/chronicle/ticket-selection.ts +23 -0
  82. package/src/components/ElapsedTime.svelte +31 -0
  83. package/src/components/ExternalLink.svelte +39 -0
  84. package/src/components/FormFieldRenderer.svelte +4 -1
  85. package/src/components/GenericLauncher.svelte +40 -15
  86. package/src/components/KeyboardShortcutsModal.svelte +2 -2
  87. package/src/components/LaunchChecklist.svelte +184 -0
  88. package/src/components/ModalShell.svelte +43 -32
  89. package/src/components/PageHeader.svelte +7 -33
  90. package/src/components/ProcessActionsMenu.svelte +217 -140
  91. package/src/components/ProcessInfoOverlay.svelte +13 -21
  92. package/src/components/ProgressChecklist.svelte +46 -0
  93. package/src/components/ProgressChecklistRows.svelte +80 -0
  94. package/src/components/launcher-form-copy.ts +4 -1
  95. package/src/components/launcher-model-config.ts +1 -1
  96. package/src/extension-ui-dev-server.ts +2 -5
  97. package/src/lib/api-tokens.ts +34 -0
  98. package/src/lib/api.ts +323 -455
  99. package/src/lib/elapsed-time.ts +19 -0
  100. package/src/lib/external-links.ts +81 -0
  101. package/src/lib/flow-layout.ts +1 -8
  102. package/src/lib/format.ts +3 -26
  103. package/src/lib/future-launch-detail.ts +1 -1
  104. package/src/lib/http-client.ts +79 -0
  105. package/src/lib/launch-updates.ts +17 -0
  106. package/src/lib/markdown.ts +8 -1
  107. package/src/lib/primary-path-detail.ts +97 -3
  108. package/src/lib/primary-path-replay.ts +13 -7
  109. package/src/lib/process-row-view.ts +1 -1
  110. package/src/lib/process-terminal-display.ts +4 -7
  111. package/src/lib/processes.svelte.ts +41 -9
  112. package/src/lib/reasoning-history.ts +95 -0
  113. package/src/lib/retry-config.svelte.ts +1 -1
  114. package/src/lib/rich-markdown-elements.ts +2 -2
  115. package/src/lib/router-logic.ts +3 -0
  116. package/src/lib/runtime-config.ts +1 -3
  117. package/src/lib/test-fixtures.ts +1 -1
  118. package/src/lib/tool-call-rendering.ts +4 -1
  119. package/src/lib/ui-extensions.svelte.ts +78 -127
  120. package/src/lib/ws-classifier.ts +8 -1
  121. package/src/pages/ApiTokensPage.svelte +213 -0
  122. package/src/pages/FutureLaunchDetailPage.svelte +7 -35
  123. package/src/pages/HomePage.svelte +7 -7
  124. package/src/pages/ProcessCard.svelte +1 -1
  125. package/src/pages/ProcessDetailPage.svelte +158 -62
  126. package/src/pages/ProcessGallery.svelte +1 -1
  127. package/src/pages/ProcessesPage.svelte +7 -42
  128. package/src/pages/SkillsPage.svelte +37 -26
  129. package/src/pages/WatchersPage.svelte +31 -53
  130. package/src/pages/process-detail/ProcessDetailChronicle.svelte +125 -28
  131. package/src/pages/process-detail/ProcessDetailHeader.svelte +24 -2
  132. package/src/pages/process-detail/ProcessSummary.svelte +35 -0
  133. package/src/pages/process-detail/TicketCreationComposer.svelte +219 -0
  134. package/src/pages/process-detail/process-detail-action-drafts.svelte.ts +5 -5
  135. package/src/pages/process-detail/process-detail-actions.svelte.ts +4 -2
  136. package/src/pages/process-detail/process-detail-chronicle-dom.ts +39 -14
  137. package/src/pages/process-detail/process-detail-chronicle-scroll.svelte.ts +68 -10
  138. package/src/pages/process-detail/process-detail-view-model.ts +10 -24
  139. package/src/shell/AppShell.svelte +4 -1
  140. package/src/shell/Sidebar.svelte +88 -125
  141. package/src/styles/controls.css +188 -0
  142. package/dist/assets/ChronicleMarkdown-B1hD4HFS.js +0 -16
  143. package/dist/assets/ChronicleMarkdown-D6hFzERy.css +0 -1
  144. package/dist/assets/FutureLaunchDetailPage-Dy3FlLih.js +0 -1
  145. package/dist/assets/FutureLaunchDetailPage-UFgp7Ju4.css +0 -1
  146. package/dist/assets/GenericLauncher-BPEQjJ1J.js +0 -1
  147. package/dist/assets/GenericLauncher-D_GMtsQ5.css +0 -1
  148. package/dist/assets/HomePage-E41Krxko.js +0 -1
  149. package/dist/assets/PageHeader-DDgWPeHS.js +0 -1
  150. package/dist/assets/PageHeader-vhyfX7xT.css +0 -1
  151. package/dist/assets/ProcessActionsMenu-BWlFe5c4.css +0 -1
  152. package/dist/assets/ProcessActionsMenu-cI0j2LWe.js +0 -1
  153. package/dist/assets/ProcessDetailPage-DVHldJgi.js +0 -12
  154. package/dist/assets/ProcessDetailPage-Oh6ld320.css +0 -1
  155. package/dist/assets/ProcessFlowDiagram-C6m6V_cB.js +0 -2
  156. package/dist/assets/ProcessesPage-B2QGyCZO.js +0 -1
  157. package/dist/assets/ProcessesPage-BcM38HMs.css +0 -1
  158. package/dist/assets/ScheduleDateTimePicker-aey_oMiH.js +0 -1
  159. package/dist/assets/SkillsPage-MPITMvhn.css +0 -1
  160. package/dist/assets/SkillsPage-iB4sbq7r.js +0 -2
  161. package/dist/assets/WatchersPage-BOSgjtw0.css +0 -1
  162. package/dist/assets/WatchersPage-l0rwv-Nx.js +0 -1
  163. package/dist/assets/api-CtKbU0lT.js +0 -1
  164. package/dist/assets/dist-eOPUi0B8.js +0 -2
  165. package/dist/assets/index-B4flHG_s.js +0 -7
  166. package/dist/assets/index-DunTIQSW.css +0 -1
  167. package/dist/assets/index-client-CnG8mWmF.js +0 -2
  168. package/dist/assets/retry-config.svelte-WukHimiy.js +0 -1
  169. package/dist/assets/router.svelte-2RvxUvs5.js +0 -1
  170. 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
 
@@ -265,6 +243,10 @@ export async function fetchAuthMeWithRetry(
265
243
  }
266
244
 
267
245
  export type LauncherSubmitResult =
246
+ | {
247
+ kind: "launch_started";
248
+ launchRunId: string;
249
+ }
268
250
  | {
269
251
  kind: "success";
270
252
  process: ProcessInstance;
@@ -274,13 +256,6 @@ export type LauncherSubmitResult =
274
256
  kind: "scheduled";
275
257
  futureExecution: FutureLaunchSummary;
276
258
  }
277
- | {
278
- kind: "partial_success";
279
- status: number;
280
- warning: string;
281
- process: ProcessInstance;
282
- projects: ProcessProject[];
283
- }
284
259
  | {
285
260
  kind: "validation_error";
286
261
  status: number;
@@ -292,47 +267,6 @@ export type LauncherSubmitResult =
292
267
  error: string;
293
268
  };
294
269
 
295
- const unknownRecordSchema = v.pipe(
296
- v.unknown(),
297
- v.check(
298
- (value) => typeof value === "object" && value !== null && !Array.isArray(value),
299
- "Expected object",
300
- ),
301
- v.record(v.string(), v.unknown()),
302
- );
303
-
304
- async function tryReadJson(response: Response): Promise<unknown> {
305
- try {
306
- return await response.json();
307
- } catch {
308
- return null;
309
- }
310
- }
311
-
312
- async function readJsonObject<T extends object>(response: Response, context: string): Promise<T> {
313
- const body = await tryReadJson(response);
314
- if (!v.safeParse(unknownRecordSchema, body).success) {
315
- throw new Error(`${context}: response body must be a JSON object`);
316
- }
317
- return body as T;
318
- }
319
-
320
- function readOptionalString(value: unknown): string | null {
321
- return typeof value === "string" ? value : null;
322
- }
323
-
324
- function readErrorMessage(body: unknown): string | null {
325
- const response = body as (ErrorResponseBody & { message?: unknown }) | null;
326
- const error = readOptionalString(response?.error) ?? readOptionalString(response?.message);
327
- return error && error.trim() !== "" ? error : null;
328
- }
329
-
330
- async function requireSuccessfulMutation(response: Response, fallbackError: string): Promise<void> {
331
- if (response.ok) return;
332
- const body = await tryReadJson(response);
333
- throw new Error(readErrorMessage(body) ?? `${fallbackError}: ${response.status}`);
334
- }
335
-
336
270
  function isLauncherValidationError(value: unknown): value is LauncherValidationError {
337
271
  const parsedValue = v.safeParse(unknownRecordSchema, value);
338
272
  if (!parsedValue.success) {
@@ -358,9 +292,11 @@ export async function fetchProcessesList(): Promise<{
358
292
  processes: ProcessOverviewItem[];
359
293
  futureExecutions: FutureExecutionOverviewItem[];
360
294
  }> {
361
- const res = await getFetchImpl()(resolveApiUrl("/api/processes/overview"));
362
- if (!res.ok) throw new Error(`Couldn't load the process list: ${res.status}`);
363
- 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
+ );
364
300
  }
365
301
 
366
302
  export interface ProcessBrowseRequest {
@@ -383,49 +319,55 @@ export async function fetchProcessBrowse(
383
319
  }
384
320
  }
385
321
  const query = params.size > 0 ? `?${params.toString()}` : "";
386
- const res = await getFetchImpl()(resolveApiUrl(`/api/processes/browse${query}`));
387
- if (!res.ok) throw new Error(`Couldn't browse processes: ${res.status}`);
388
- 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
+ );
389
327
  }
390
328
 
391
329
  export async function fetchLaunchers(): Promise<UiLauncherSummary[]> {
392
- const res = await getFetchImpl()(resolveApiUrl("/api/launchers"));
393
- if (!res.ok) throw new Error(`Couldn't load available processes: ${res.status}`);
394
- 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
+ );
395
335
  return body.launchers;
396
336
  }
397
337
 
398
338
  export async function fetchWatchers(): Promise<WatcherSummary[]> {
399
- const res = await getFetchImpl()(resolveApiUrl("/api/watchers"));
400
- if (!res.ok) throw new Error(`Couldn't load registered watchers: ${res.status}`);
401
- 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
+ );
402
344
  return body.watchers;
403
345
  }
404
346
 
405
347
  export async function fetchSkills(): Promise<SkillsCatalogResponseBody> {
406
- const res = await getFetchImpl()(resolveApiUrl("/api/skills"));
407
- if (!res.ok) throw new Error(`Couldn't load the skill catalog: ${res.status}`);
408
- 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
+ );
409
353
  }
410
354
 
411
355
  export async function refreshSkills(): Promise<SkillsCatalogResponseBody> {
412
- const res = await getFetchImpl()(resolveApiUrl("/api/skills/refresh"), { method: "POST" });
413
- if (!res.ok) throw new Error(`Couldn't refresh skill repositories: ${res.status}`);
414
- 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
+ );
415
362
  }
416
363
 
417
364
  export async function fetchSkillDetail(
418
365
  repositoryId: string,
419
366
  skillId: string,
420
367
  ): Promise<SkillCatalogDetail> {
421
- const res = await getFetchImpl()(
422
- resolveApiUrl(
423
- `/api/skills/available/${encodeURIComponent(repositoryId)}/${encodeURIComponent(skillId)}`,
424
- ),
425
- );
426
- if (!res.ok) throw new Error(`Couldn't load skill details: ${res.status}`);
427
- const body = await readJsonObject<SkillCatalogDetailResponseBody>(
428
- res,
368
+ const body = await requestStatusJson<SkillCatalogDetailResponseBody>(
369
+ `/api/skills/available/${encodeURIComponent(repositoryId)}/${encodeURIComponent(skillId)}`,
370
+ "Couldn't load skill details",
429
371
  "Malformed skill detail response",
430
372
  );
431
373
  return body.skill;
@@ -434,57 +376,46 @@ export async function fetchSkillDetail(
434
376
  export async function fetchInstalledSkillDetail(
435
377
  skillId: string,
436
378
  ): Promise<InstalledSkillCatalogDetail> {
437
- const res = await getFetchImpl()(
438
- resolveApiUrl(`/api/skills/installed/${encodeURIComponent(skillId)}`),
439
- );
440
- if (!res.ok) throw new Error(`Couldn't load installed skill details: ${res.status}`);
441
- const body = await readJsonObject<InstalledSkillCatalogDetailResponseBody>(
442
- res,
379
+ const body = await requestStatusJson<InstalledSkillCatalogDetailResponseBody>(
380
+ `/api/skills/installed/${encodeURIComponent(skillId)}`,
381
+ "Couldn't load installed skill details",
443
382
  "Malformed installed skill detail response",
444
383
  );
445
384
  return body.skill;
446
385
  }
447
386
 
448
387
  export async function registerSkill(repositoryId: string, skillId: string): Promise<void> {
449
- const res = await getFetchImpl()(
450
- resolveApiUrl(
451
- `/api/skills/available/${encodeURIComponent(repositoryId)}/${encodeURIComponent(skillId)}/register`,
452
- ),
388
+ return requestMutation(
389
+ `/api/skills/available/${encodeURIComponent(repositoryId)}/${encodeURIComponent(skillId)}/register`,
390
+ "Couldn't register the skill",
453
391
  { method: "POST" },
454
392
  );
455
- await requireSuccessfulMutation(res, "Couldn't register the skill");
456
393
  }
457
394
 
458
395
  export async function removeSkill(skillId: string): Promise<void> {
459
- const res = await getFetchImpl()(
460
- resolveApiUrl(`/api/skills/installed/${encodeURIComponent(skillId)}`),
396
+ return requestMutation(
397
+ `/api/skills/installed/${encodeURIComponent(skillId)}`,
398
+ "Couldn't remove the skill",
461
399
  { method: "DELETE" },
462
400
  );
463
- await requireSuccessfulMutation(res, "Couldn't remove the skill");
464
401
  }
465
402
 
466
- export async function fetchLauncherDefaults(launcherId: string): Promise<{
467
- defaults: Record<string, unknown>;
468
- title: string | null;
469
- modelConfig: LauncherModelConfigDefaults;
470
- warnings?: LauncherValidationError[];
471
- }> {
472
- const res = await getFetchImpl()(
473
- 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",
474
410
  );
475
- if (!res.ok) throw new Error(`Couldn't load default values: ${res.status}`);
476
- return readJsonObject<LauncherDefaultsResponseBody>(res, "Malformed launcher defaults response");
477
411
  }
478
412
 
479
413
  export async function fetchLauncherRecentValues(
480
414
  launcherId: string,
481
415
  ): Promise<Record<string, readonly string[]>> {
482
- const res = await getFetchImpl()(
483
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/recent-values`),
484
- );
485
- if (!res.ok) throw new Error(`Couldn't load recent launcher values: ${res.status}`);
486
- const body = await readJsonObject<LauncherRecentValuesResponseBody>(
487
- res,
416
+ const body = await requestStatusJson<LauncherRecentValuesResponseBody>(
417
+ `/api/launchers/${encodeURIComponent(launcherId)}/recent-values`,
418
+ "Couldn't load recent launcher values",
488
419
  "Malformed launcher recent values response",
489
420
  );
490
421
  return body.values;
@@ -494,18 +425,11 @@ export async function fetchLauncherOptions(
494
425
  launcherId: string,
495
426
  launcherInput: Record<string, unknown>,
496
427
  ): Promise<Record<string, readonly LauncherFieldOptionDefinition[]>> {
497
- const res = await getFetchImpl()(
498
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/options`),
499
- {
500
- method: "POST",
501
- headers: { "content-type": "application/json" },
502
- body: JSON.stringify({ launcherInput }),
503
- },
504
- );
505
- if (!res.ok) throw new Error(`Couldn't refresh the available options: ${res.status}`);
506
- const body = await readJsonObject<LauncherOptionsResponseBody>(
507
- res,
428
+ const body = await requestStatusJson<LauncherOptionsResponseBody>(
429
+ `/api/launchers/${encodeURIComponent(launcherId)}/options`,
430
+ "Couldn't refresh the available options",
508
431
  "Malformed launcher options response",
432
+ jsonRequestInit("POST", { launcherInput }),
509
433
  );
510
434
  return body.options;
511
435
  }
@@ -515,18 +439,11 @@ export async function fetchLauncherModelConfigPreview(
515
439
  launcherInput: Record<string, unknown>,
516
440
  modelConfig: LauncherModelConfigDefaults = {},
517
441
  ): Promise<LauncherModelConfigPreview> {
518
- const res = await getFetchImpl()(
519
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/model-config-preview`),
520
- {
521
- method: "POST",
522
- headers: { "content-type": "application/json" },
523
- body: JSON.stringify({ launcherInput, modelConfig }),
524
- },
525
- );
526
- if (!res.ok) throw new Error(`Couldn't refresh the model preview: ${res.status}`);
527
- const body = await readJsonObject<LauncherModelConfigPreviewResponseBody>(
528
- res,
442
+ const body = await requestStatusJson<LauncherModelConfigPreviewResponseBody>(
443
+ `/api/launchers/${encodeURIComponent(launcherId)}/model-config-preview`,
444
+ "Couldn't refresh the model preview",
529
445
  "Malformed launcher model preview response",
446
+ jsonRequestInit("POST", { launcherInput, modelConfig }),
530
447
  );
531
448
  return body.preview;
532
449
  }
@@ -534,8 +451,8 @@ export async function fetchLauncherModelConfigPreview(
534
451
  async function parseLauncherErrorResponse(
535
452
  res: Response,
536
453
  fallbackMessagePrefix: string,
454
+ body: unknown,
537
455
  ): Promise<LauncherSubmitResult> {
538
- const body = await tryReadJson(res);
539
456
  const errors = readLauncherValidationErrors(body);
540
457
  if (errors.length > 0) {
541
458
  return { kind: "validation_error", status: res.status, errors };
@@ -547,6 +464,59 @@ async function parseLauncherErrorResponse(
547
464
  };
548
465
  }
549
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
+
550
520
  export async function launchLauncher(
551
521
  launcherId: string,
552
522
  title: string | null,
@@ -555,74 +525,49 @@ export async function launchLauncher(
555
525
  schedule: ScheduleConfigInput = { mode: "now" },
556
526
  skillIds: readonly string[] = [],
557
527
  ): Promise<LauncherSubmitResult> {
528
+ if (schedule.mode === "now") {
529
+ return startLaunchRun(launcherId, title, launcherInput, modelConfig, skillIds);
530
+ }
558
531
  const res = await getFetchImpl()(
559
- resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/launch`),
560
- {
561
- method: "POST",
562
- headers: { "content-type": "application/json" },
563
- body: JSON.stringify({ title, launcherInput, modelConfig, schedule, skillIds }),
564
- },
532
+ resolveApiUrl(`/api/launchers/${encodeURIComponent(launcherId)}/future-launches`),
533
+ jsonRequestInit("POST", { title, launcherInput, modelConfig, schedule, skillIds }),
565
534
  );
566
535
  if (!res.ok) {
567
- return parseLauncherErrorResponse(res, "Couldn't start this process");
536
+ return parseLauncherErrorResponse(res, "Couldn't start this process", await tryReadJson(res));
568
537
  }
569
- const body = await readJsonObject<LauncherMutationResponseBody>(
538
+ const body = await readJsonObject<FutureLaunchMutationResponseBody>(
570
539
  res,
571
- "Malformed launcher launch response",
540
+ "Malformed future launch response",
572
541
  );
573
- const projects = body.projects ?? [];
574
- const errorMessage = body.error ?? `Couldn't start this process: ${res.status}`;
575
- if (res.status === 201 && body.futureExecution) {
576
- return { kind: "scheduled", futureExecution: body.futureExecution };
577
- }
578
- if (res.status === 201 && body.process) {
579
- return { kind: "success", process: body.process, projects };
580
- }
581
- if (body.process) {
582
- return {
583
- kind: "partial_success",
584
- status: res.status,
585
- warning: errorMessage,
586
- process: body.process,
587
- projects,
588
- };
589
- }
590
- const errors = body.errors ?? [];
591
- if (errors.length > 0) {
592
- return { kind: "validation_error", status: res.status, errors };
593
- }
594
- 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
+ };
595
549
  }
596
550
 
597
551
  export async function fetchProcessDiagnostics(instanceId: string): Promise<ProcessDiagnosticsData> {
598
- const res = await getFetchImpl()(
599
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/diagnostics`),
600
- );
601
- if (!res.ok) throw new Error(`Couldn't load this process: ${res.status}`);
602
- return readJsonObject<ProcessDiagnosticsResponseBody>(
603
- res,
552
+ return requestStatusJson<ProcessDiagnosticsResponseBody>(
553
+ `/api/processes/${encodeURIComponent(instanceId)}/diagnostics`,
554
+ "Couldn't load this process",
604
555
  "Malformed process diagnostics response",
605
556
  );
606
557
  }
607
558
 
608
559
  export async function fetchPrimaryPathSnapshot(instanceId: string): Promise<PrimaryPathSnapshot> {
609
- const res = await getFetchImpl()(
610
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/primary-path`),
611
- );
612
- if (!res.ok) throw new Error(`Couldn't load this process: ${res.status}`);
613
- return readJsonObject<PrimaryPathSnapshotResponseBody>(
614
- res,
560
+ return requestStatusJson<PrimaryPathSnapshotResponseBody>(
561
+ `/api/processes/${encodeURIComponent(instanceId)}/primary-path`,
562
+ "Couldn't load this process",
615
563
  "Malformed primary path snapshot response",
616
564
  );
617
565
  }
618
566
 
619
567
  export async function fetchProcessDetail(instanceId: string): Promise<ProcessDetailData> {
620
- const res = await getFetchImpl()(
621
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/ui-snapshot`),
622
- );
623
- if (!res.ok) throw new Error(`Couldn't load this process: ${res.status}`);
624
- return readJsonObject<ProcessDetailUiSnapshotResponseBody>(
625
- res,
568
+ return requestStatusJson(
569
+ `/api/processes/${encodeURIComponent(instanceId)}/ui-snapshot`,
570
+ "Couldn't load this process",
626
571
  "Malformed process UI snapshot response",
627
572
  );
628
573
  }
@@ -633,7 +578,7 @@ export async function fetchTurnReasoningDetail(
633
578
  sessionSignature: string | null,
634
579
  signal?: AbortSignal,
635
580
  ): Promise<TurnReasoningDetailResponseBody> {
636
- const params = new URLSearchParams({ sessionSignature: sessionSignature ?? "" });
581
+ const params = new URLSearchParams(sessionSignature === null ? {} : { sessionSignature });
637
582
  const res = await getFetchImpl()(
638
583
  resolveApiUrl(
639
584
  `/api/processes/${encodeURIComponent(instanceId)}/turn-records/${encodeURIComponent(turnRecordId)}/reasoning?${params.toString()}`,
@@ -655,16 +600,11 @@ export async function fetchTurnReasoningDetail(
655
600
  export async function fetchFutureExecution(
656
601
  futureExecutionId: string,
657
602
  ): Promise<FutureExecutionDetailResponseBody> {
658
- const res = await getFetchImpl()(
659
- resolveApiUrl(`/api/future-executions/${encodeURIComponent(futureExecutionId)}`),
660
- );
661
- if (!res.ok) {
662
- throw new ApiResponseError(`Couldn't load scheduled item: ${res.status}`, res.status);
663
- }
664
- return readJsonObject<FutureExecutionDetailResponseBody>(
665
- res,
666
- "Malformed scheduled item response",
667
- );
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
+ });
668
608
  }
669
609
 
670
610
  export async function postProcessRetry(
@@ -672,20 +612,11 @@ export async function postProcessRetry(
672
612
  nextTurnModelProfileId?: string | null,
673
613
  providerOptions?: Readonly<Record<string, string>>,
674
614
  ): Promise<void> {
675
- const res = await getFetchImpl()(
676
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/retry`),
677
- {
678
- method: "POST",
679
- headers: { "content-type": "application/json" },
680
- body: JSON.stringify({
681
- ...(nextTurnModelProfileId === undefined ? {} : { nextTurnModelProfileId }),
682
- ...(providerOptions === undefined ? {} : { providerOptions }),
683
- }),
684
- },
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 }),
685
619
  );
686
- if (!res.ok) {
687
- throw new Error(`Couldn't retry this process: ${res.status}`);
688
- }
689
620
  }
690
621
 
691
622
  export async function fetchModelProviderOptions(
@@ -697,10 +628,7 @@ export async function fetchModelProviderOptions(
697
628
  `/api/processes/${encodeURIComponent(instanceId)}/model-profiles/${encodeURIComponent(modelProfileId)}/provider-options`,
698
629
  ),
699
630
  );
700
- if (!res.ok) {
701
- const body = await tryReadJson(res);
702
- throw new Error(readErrorMessage(body) ?? `Couldn't load provider options: ${res.status}`);
703
- }
631
+ await requireSuccessfulResponse(res, "Couldn't load provider options");
704
632
  return (await res.json()) as ModelProviderOptionsResponseBody;
705
633
  }
706
634
 
@@ -711,24 +639,11 @@ export async function postProcessTurnContinue(
711
639
  nextTurnModelProfileId?: string | null,
712
640
  providerOptions?: Readonly<Record<string, string>>,
713
641
  ): Promise<void> {
714
- const res = await getFetchImpl()(
715
- resolveApiUrl(
716
- `/api/processes/${encodeURIComponent(instanceId)}/turn-records/${encodeURIComponent(turnRecordId)}/continue`,
717
- ),
718
- {
719
- method: "POST",
720
- headers: { "content-type": "application/json" },
721
- body: JSON.stringify({
722
- ...(prompt === undefined ? {} : { prompt }),
723
- ...(nextTurnModelProfileId === undefined ? {} : { nextTurnModelProfileId }),
724
- ...(providerOptions === undefined ? {} : { providerOptions }),
725
- }),
726
- },
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 }),
727
646
  );
728
- if (!res.ok) {
729
- const body = await tryReadJson(res);
730
- throw new Error(readErrorMessage(body) ?? `Couldn't continue this failed turn: ${res.status}`);
731
- }
732
647
  }
733
648
 
734
649
  export async function postProcessStartupRetry(
@@ -737,58 +652,65 @@ export async function postProcessStartupRetry(
737
652
  nextTurnModelProfileId?: string | null,
738
653
  providerOptions?: Readonly<Record<string, string>>,
739
654
  ): Promise<void> {
740
- const res = await getFetchImpl()(
741
- resolveApiUrl(
742
- `/api/processes/${encodeURIComponent(instanceId)}/turn-starts/${encodeURIComponent(startRecordId)}/retry`,
743
- ),
744
- {
745
- method: "POST",
746
- headers: { "content-type": "application/json" },
747
- body: JSON.stringify({
748
- ...(nextTurnModelProfileId === undefined ? {} : { nextTurnModelProfileId }),
749
- ...(providerOptions === undefined ? {} : { providerOptions }),
750
- }),
751
- },
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" },
752
683
  );
753
- if (!res.ok) {
754
- const body = await tryReadJson(res);
755
- throw new Error(readErrorMessage(body) ?? `Couldn't retry worker startup: ${res.status}`);
756
- }
757
684
  }
758
685
 
759
686
  export async function deleteProcess(instanceId: string): Promise<void> {
760
- const response = await getFetchImpl()(
761
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}`),
687
+ return requestMutation(
688
+ `/api/processes/${encodeURIComponent(instanceId)}`,
689
+ "Couldn't delete this process",
762
690
  { method: "DELETE" },
763
691
  );
764
- await requireSuccessfulMutation(response, "Couldn't delete this process");
765
692
  }
766
693
 
767
694
  export async function postProcessAbort(instanceId: string): Promise<void> {
768
- const response = await getFetchImpl()(
769
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/abort`),
695
+ return requestMutation(
696
+ `/api/processes/${encodeURIComponent(instanceId)}/abort`,
697
+ "Couldn't abort this process",
770
698
  { method: "POST" },
771
699
  );
772
- await requireSuccessfulMutation(response, "Couldn't abort this process");
773
700
  }
774
701
 
775
702
  export async function postProcessAbortTurn(instanceId: string): Promise<void> {
776
- const response = await getFetchImpl()(
777
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/abort-turn`),
703
+ return requestMutation(
704
+ `/api/processes/${encodeURIComponent(instanceId)}/abort-turn`,
705
+ "Couldn't stop this turn",
778
706
  { method: "POST" },
779
707
  );
780
- await requireSuccessfulMutation(response, "Couldn't stop this turn");
781
708
  }
782
709
 
783
710
  export async function fetchProcessRetryConfig(instanceId: string): Promise<ProcessRetryConfig> {
784
- const res = await getFetchImpl()(
785
- resolveApiUrl(`/api/processes/${encodeURIComponent(instanceId)}/retry-config`),
786
- );
787
- if (!res.ok) {
788
- throw new Error(`Couldn't load retry config: ${res.status}`);
789
- }
790
- return readJsonObject<ProcessRetryConfigResponseBody>(
791
- res,
711
+ return requestStatusJson<ProcessRetryConfigResponseBody>(
712
+ `/api/processes/${encodeURIComponent(instanceId)}/retry-config`,
713
+ "Couldn't load retry config",
792
714
  "Malformed process retry config response",
793
715
  );
794
716
  }
@@ -802,26 +724,12 @@ export async function fetchProcessActionModelPreview(
802
724
  actionId: string,
803
725
  input: Record<string, unknown> = {},
804
726
  ): Promise<ProcessActionModelPreview> {
805
- const res = await getFetchImpl()(
806
- resolveApiUrl(
807
- `/api/processes/${encodeURIComponent(instanceId)}/actions/${encodeURIComponent(actionId)}/model-preview`,
808
- ),
809
- {
810
- method: "POST",
811
- headers: { "content-type": "application/json" },
812
- body: JSON.stringify({ input }),
813
- },
814
- );
815
- if (!res.ok) {
816
- const body = await tryReadJson(res);
817
- throw new Error(
818
- readErrorMessage(body) ?? `Couldn't refresh the action model preview: ${res.status}`,
819
- );
820
- }
821
- const body = await readJsonObject<ProcessActionModelPreviewResponseBody>(
822
- res,
823
- "Malformed process action model preview response",
824
- );
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
+ });
825
733
  return body.preview;
826
734
  }
827
735
 
@@ -834,32 +742,16 @@ export async function postProcessAction(
834
742
  schedule?: ScheduleConfigInput;
835
743
  } = {},
836
744
  ): Promise<ProcessActionSubmitResult> {
837
- const res = await getFetchImpl()(
838
- resolveApiUrl(
839
- `/api/processes/${encodeURIComponent(instanceId)}/actions/${encodeURIComponent(actionId)}`,
840
- ),
841
- {
842
- method: "POST",
843
- headers: { "content-type": "application/json" },
844
- body: JSON.stringify({
845
- input,
846
- schedule: opts.schedule ?? { mode: "now" },
847
- ...(opts.nextTurnModelProfileId !== undefined
848
- ? { nextTurnModelProfileId: opts.nextTurnModelProfileId }
849
- : {}),
850
- }),
851
- },
852
- );
853
- if (!res.ok) {
854
- const body = await tryReadJson(res);
855
- throw new Error(
856
- readErrorMessage(body) ?? `Couldn't run "${formatDefinition(actionId)}": ${res.status}`,
857
- );
858
- }
859
- const body = await readJsonObject<ScheduledActionMutationResponseBody>(
860
- res,
861
- "Malformed process action response",
862
- );
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
+ });
863
755
  if (body.scheduledAction) {
864
756
  return { kind: "scheduled", scheduledAction: body.scheduledAction };
865
757
  }
@@ -876,14 +768,14 @@ export async function updateScheduledLaunch(
876
768
  ): Promise<LauncherSubmitResult> {
877
769
  const res = await getFetchImpl()(
878
770
  resolveApiUrl(`/api/future-executions/${encodeURIComponent(futureExecutionId)}/launch`),
879
- {
880
- method: "PUT",
881
- headers: { "content-type": "application/json" },
882
- body: JSON.stringify({ title, launcherInput, modelConfig, schedule, skillIds }),
883
- },
771
+ jsonRequestInit("PUT", { title, launcherInput, modelConfig, schedule, skillIds }),
884
772
  );
885
773
  if (!res.ok) {
886
- 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
+ );
887
779
  }
888
780
  const body = await readJsonObject<LauncherMutationResponseBody>(
889
781
  res,
@@ -912,30 +804,16 @@ export async function updateScheduledAction(
912
804
  schedule: ScheduleConfigInput;
913
805
  },
914
806
  ): Promise<ProcessActionSubmitResult> {
915
- const res = await getFetchImpl()(
916
- resolveApiUrl(`/api/future-executions/${encodeURIComponent(futureExecutionId)}/action`),
917
- {
918
- method: "PUT",
919
- headers: { "content-type": "application/json" },
920
- body: JSON.stringify({
921
- input,
922
- schedule: opts.schedule,
923
- ...(opts.nextTurnModelProfileId !== undefined
924
- ? { nextTurnModelProfileId: opts.nextTurnModelProfileId }
925
- : {}),
926
- }),
927
- },
928
- );
929
- if (!res.ok) {
930
- const body = await tryReadJson(res);
931
- throw new Error(
932
- readErrorMessage(body) ?? `Couldn't update this scheduled action: ${res.status}`,
933
- );
934
- }
935
- const body = await readJsonObject<ScheduledActionMutationResponseBody>(
936
- res,
937
- "Malformed scheduled action update response",
938
- );
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
+ });
939
817
  if (body.scheduledAction) {
940
818
  return { kind: "scheduled", scheduledAction: body.scheduledAction };
941
819
  }
@@ -943,30 +821,20 @@ export async function updateScheduledAction(
943
821
  }
944
822
 
945
823
  export async function deleteFutureExecution(futureExecutionId: string): Promise<void> {
946
- const res = await getFetchImpl()(
947
- resolveApiUrl(`/api/future-executions/${encodeURIComponent(futureExecutionId)}`),
824
+ return requestMutation(
825
+ `/api/future-executions/${encodeURIComponent(futureExecutionId)}`,
826
+ "Couldn't cancel this scheduled item",
948
827
  { method: "DELETE" },
949
828
  );
950
- if (!res.ok) {
951
- const body = await tryReadJson(res);
952
- throw new Error(readErrorMessage(body) ?? `Couldn't cancel this scheduled item: ${res.status}`);
953
- }
954
829
  }
955
830
 
956
831
  export async function previewCronExpression(expression: string): Promise<string> {
957
- const res = await getFetchImpl()(resolveApiUrl("/api/future-executions/cron-preview"), {
958
- method: "POST",
959
- headers: { "content-type": "application/json" },
960
- 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",
961
837
  });
962
- if (!res.ok) {
963
- const body = await tryReadJson(res);
964
- throw new Error(readErrorMessage(body) ?? `Couldn't preview this cron: ${res.status}`);
965
- }
966
- const body = await readJsonObject<CronPreviewResponseBody>(
967
- res,
968
- "Malformed cron preview response",
969
- );
970
838
  if (typeof body.nextRunAt !== "string") {
971
839
  throw new Error("Malformed cron preview response: nextRunAt must be a string");
972
840
  }