deepline 0.1.243 → 0.1.244

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 (71) hide show
  1. package/README.md +1 -1
  2. package/dist/bundling-sources/sdk/src/plays/bundle-play-file.ts +5 -25
  3. package/dist/bundling-sources/sdk/src/release.ts +23 -21
  4. package/dist/bundling-sources/sdk/src/types.ts +1 -1
  5. package/dist/bundling-sources/shared_libs/play-runtime/backend.ts +2 -21
  6. package/dist/bundling-sources/shared_libs/play-runtime/governor/governor.ts +5 -6
  7. package/dist/bundling-sources/shared_libs/play-runtime/governor/policy.ts +6 -13
  8. package/dist/bundling-sources/shared_libs/play-runtime/governor/rate-state-backend.ts +9 -26
  9. package/dist/bundling-sources/shared_libs/play-runtime/internal-step-ids.ts +1 -2
  10. package/dist/bundling-sources/shared_libs/play-runtime/map-row-identity.ts +1 -1
  11. package/dist/bundling-sources/shared_libs/play-runtime/output-size-limits.ts +191 -29
  12. package/dist/bundling-sources/shared_libs/play-runtime/play-latency-trace.ts +1 -1
  13. package/dist/bundling-sources/shared_libs/play-runtime/providers.ts +1 -36
  14. package/dist/bundling-sources/shared_libs/play-runtime/run-ledger.ts +2 -3
  15. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/index.ts +0 -7
  16. package/dist/bundling-sources/shared_libs/play-runtime/runtime-api.ts +1 -12
  17. package/dist/bundling-sources/shared_libs/play-runtime/runtime-pg-driver-pg.ts +2 -3
  18. package/dist/bundling-sources/shared_libs/play-runtime/runtime-pg-driver.ts +5 -15
  19. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backend.ts +6 -21
  20. package/dist/bundling-sources/shared_libs/play-runtime/tool-result.ts +3 -4
  21. package/dist/bundling-sources/shared_libs/plays/artifact-kind-guard.ts +16 -29
  22. package/dist/bundling-sources/shared_libs/plays/artifact-types.ts +4 -8
  23. package/dist/bundling-sources/shared_libs/plays/bundling/index.ts +21 -712
  24. package/dist/bundling-sources/shared_libs/plays/bundling/limits.ts +1 -18
  25. package/dist/cli/index.js +29 -71
  26. package/dist/cli/index.mjs +29 -71
  27. package/dist/{compiler-manifest-CYcwzSOJ.d.ts → compiler-manifest-DlE7dnRm.d.mts} +2 -8
  28. package/dist/{compiler-manifest-CYcwzSOJ.d.mts → compiler-manifest-DlE7dnRm.d.ts} +2 -8
  29. package/dist/index.d.mts +2 -2
  30. package/dist/index.d.ts +2 -2
  31. package/dist/index.js +24 -22
  32. package/dist/index.mjs +24 -22
  33. package/dist/plays/bundle-play-file.d.mts +7 -22
  34. package/dist/plays/bundle-play-file.d.ts +7 -22
  35. package/dist/plays/bundle-play-file.mjs +26 -614
  36. package/package.json +2 -2
  37. package/dist/bundling-sources/apps/play-runner-workers/src/coordinator-entry.ts +0 -4504
  38. package/dist/bundling-sources/apps/play-runner-workers/src/dedup-do.ts +0 -1386
  39. package/dist/bundling-sources/apps/play-runner-workers/src/durable-object-deploy-handoff.ts +0 -30
  40. package/dist/bundling-sources/apps/play-runner-workers/src/entry.ts +0 -8385
  41. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/README.md +0 -21
  42. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/batching.ts +0 -251
  43. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/coordinator-progress.ts +0 -289
  44. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/csv-rows.ts +0 -85
  45. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/customer-console.ts +0 -23
  46. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/dataset-handles.ts +0 -528
  47. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/harness-receipt-store.ts +0 -229
  48. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/ledger-event-batches.ts +0 -81
  49. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/live-progress.ts +0 -22
  50. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/map-chunk-plan.ts +0 -920
  51. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/map-latency-profile.ts +0 -90
  52. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/output-datasets.ts +0 -475
  53. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/receipts.ts +0 -570
  54. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/result-dataset-persistence.ts +0 -50
  55. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/row-isolation.ts +0 -5
  56. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/run-work-dispatcher.ts +0 -519
  57. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/tool-batch.ts +0 -107
  58. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/tool-dispatch.ts +0 -2541
  59. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/tool-http-errors.ts +0 -7
  60. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/tool-receipts.ts +0 -227
  61. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/work-budget.ts +0 -130
  62. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/worker-platform-budget.ts +0 -39
  63. package/dist/bundling-sources/apps/play-runner-workers/src/runtime/workflow-preview.ts +0 -26
  64. package/dist/bundling-sources/apps/play-runner-workers/src/runtime-api-retry.ts +0 -23
  65. package/dist/bundling-sources/apps/play-runner-workers/src/workflow-instance-create.ts +0 -47
  66. package/dist/bundling-sources/apps/play-runner-workers/src/workflow-retry-state.ts +0 -167
  67. package/dist/bundling-sources/apps/play-runner-workers/src/workflow-retry.ts +0 -91
  68. package/dist/bundling-sources/sdk/src/plays/harness-stub.ts +0 -329
  69. package/dist/bundling-sources/sdk/src/worker-play-entry.ts +0 -240
  70. package/dist/bundling-sources/shared_libs/play-runtime/governor/coordinator-rate-state-backend.ts +0 -252
  71. package/dist/bundling-sources/shared_libs/play-runtime/runtime-pg-driver-neon-serverless.ts +0 -217
@@ -1,91 +0,0 @@
1
- import { normalizePlayRunFailure } from '../../../shared_libs/play-runtime/run-failure';
2
-
3
- export const PLATFORM_DEPLOY_WORKFLOW_RETRY_LIMIT = 5;
4
-
5
- export type WorkflowRetryDecision =
6
- | {
7
- action: 'retry';
8
- reason: string;
9
- nextAttempt: number;
10
- message: string;
11
- }
12
- | {
13
- action: 'fail';
14
- reason: string | null;
15
- message: string | null;
16
- };
17
-
18
- function workflowRetryReasonForFailure(failure: {
19
- code: string;
20
- cause?: string;
21
- }): string {
22
- if (failure.code === 'PLATFORM_WORKFLOW_ENDPOINT_INTERRUPTED') {
23
- return 'cloudflare_workflow_endpoint_unavailable';
24
- }
25
- if (failure.code === 'PLATFORM_WORKER_SUBREQUEST_INTERRUPTED') {
26
- return 'cloudflare_worker_subrequest_limit';
27
- }
28
- if (
29
- failure.cause &&
30
- /runtime API 404:[\s\S]*(?:DeploymentNotFound|DEPLOYMENT_NOT_FOUND|requested deployment .*exist|deployment could not be found on Vercel)/i.test(
31
- failure.cause,
32
- )
33
- ) {
34
- return 'vercel_runtime_api_deployment_missing';
35
- }
36
- return 'cloudflare_durable_object_reset';
37
- }
38
-
39
- function workflowRetryExhaustedReasonForFailure(failure: {
40
- code: string;
41
- cause?: string;
42
- }): string {
43
- return `${workflowRetryReasonForFailure(failure)}_retry_exhausted`;
44
- }
45
-
46
- export function decideWorkflowPlatformRetry(input: {
47
- workflowStatus: string;
48
- error: string | null;
49
- retryAttempts: number;
50
- }): WorkflowRetryDecision {
51
- if (!input.error) {
52
- return { action: 'fail', reason: null, message: null };
53
- }
54
- const failure = normalizePlayRunFailure(input.error);
55
- const retryablePlatformReset =
56
- failure.code === 'PLATFORM_DEPLOY_INTERRUPTED' ||
57
- failure.code === 'PLATFORM_WORKFLOW_ENDPOINT_INTERRUPTED' ||
58
- failure.code === 'PLATFORM_WORKER_SUBREQUEST_INTERRUPTED';
59
- if (
60
- retryablePlatformReset &&
61
- input.retryAttempts < PLATFORM_DEPLOY_WORKFLOW_RETRY_LIMIT
62
- ) {
63
- return {
64
- action: 'retry',
65
- reason: workflowRetryReasonForFailure(failure),
66
- nextAttempt: input.retryAttempts + 1,
67
- message: failure.message,
68
- };
69
- }
70
- return {
71
- action: 'fail',
72
- reason: retryablePlatformReset
73
- ? workflowRetryExhaustedReasonForFailure(failure)
74
- : null,
75
- message: failure.message,
76
- };
77
- }
78
-
79
- export function shouldPublishWorkflowRuntimeFailure(input: {
80
- error: unknown;
81
- retryAttempts: number;
82
- }): boolean {
83
- const message =
84
- input.error instanceof Error ? input.error.message : String(input.error);
85
- const decision = decideWorkflowPlatformRetry({
86
- workflowStatus: 'errored',
87
- error: message,
88
- retryAttempts: input.retryAttempts,
89
- });
90
- return decision.action !== 'retry';
91
- }
@@ -1,329 +0,0 @@
1
- /**
2
- * Per-play stub that calls into the long-lived Play Harness Worker via
3
- * `env.HARNESS`.
4
- *
5
- * This file is what ends up bundled into every per-play Worker. It MUST
6
- * stay tiny — every byte here is paid by every fresh-graphHash V8
7
- * compile in CF's WorkerLoader. Target: <2 KB minified.
8
- *
9
- * What it does:
10
- * - Exposes thin functions that look like the in-bundle implementations
11
- * they're replacing (runtime-api call, staged dataset IO, …).
12
- * - Each function calls `env.HARNESS.<method>(...)` — the typed RPC
13
- * stub provided by the Cloudflare service binding.
14
- *
15
- * What it does NOT do:
16
- * - Does NOT import the harness Worker's `PlayHarness` class (that
17
- * would re-bundle the whole harness; only TYPES are imported).
18
- * - Does NOT cache RPC results across plays — caching belongs to
19
- * callers if they want it. This file stays stateless so it composes
20
- * cleanly under the per-play orchestrator's expectations.
21
- *
22
- * How the env binding reaches per-play code:
23
- * The coordinator's `WorkerLoader` factory passes `HARNESS` in the
24
- * per-play Worker's `env` map (see
25
- * `apps/play-runner-workers/src/coordinator-entry.ts` near
26
- * `loadDynamicPlayWorkerSync`). The per-play harness then reads it
27
- * off `WorkerEnv` and stashes it via `setHarnessBinding`.
28
- *
29
- * @see {@link ../../../apps/play-harness-worker/README.md}
30
- */
31
-
32
- import type {
33
- PlayHarnessRpc,
34
- PreloadedRuntimeDbSessionInput,
35
- CompleteRuntimeReceiptInput,
36
- CompleteRuntimeReceiptsInput,
37
- FailRuntimeReceiptInput,
38
- FailRuntimeReceiptsInput,
39
- HeartbeatRuntimeReceiptsInput,
40
- MarkRuntimeReceiptsRunningInput,
41
- ReleaseRuntimeReceiptInput,
42
- RuntimeApiCallInput,
43
- RuntimeApiCallResult,
44
- RuntimeReceiptInput,
45
- RuntimeReceiptsInput,
46
- SheetAttemptHeartbeatInput,
47
- SheetAttemptHeartbeatResult,
48
- SheetAttemptReleaseInput,
49
- SheetAttemptReleaseResult,
50
- WorkReceiptReleaseInput,
51
- WorkReceiptReleaseResult,
52
- SheetDatasetRowKeysInput,
53
- SheetDatasetRowKeysResult,
54
- SheetDatasetRowsInput,
55
- SheetDatasetRowsResult,
56
- StagedFileChunkInput,
57
- StagedFileChunkResult,
58
- } from '../../../apps/play-harness-worker/src/rpc-types';
59
- import type {
60
- WorkReceipt,
61
- WorkReceiptClaim,
62
- } from '../../../shared_libs/play-runtime/work-receipts';
63
-
64
- /**
65
- * Service-binding RPC stub shape — what `env.HARNESS` looks like inside
66
- * a per-play Worker. Cloudflare exposes WorkerEntrypoint methods as
67
- * promise-returning RPC stubs; the type matches `PlayHarnessRpc`.
68
- */
69
- export type HarnessBinding = PlayHarnessRpc;
70
-
71
- /**
72
- * Module-level holder for the binding. Set by the per-play harness on
73
- * worker init (see `apps/play-runner-workers/src/entry.ts → setHarnessBinding`).
74
- *
75
- * Why a module-level holder instead of threading the binding through
76
- * every call site: most leaf-call sites are deep inside SDK utilities
77
- * (`ctx.tools.execute`, `ctx.csv`, etc.) and threading a binding everywhere would
78
- * be a structural mess. A single set-once holder, set very early in the
79
- * worker's lifecycle, gives us clean call sites without sacrificing
80
- * isolation — each per-play Worker is its own isolate, so the holder is
81
- * never shared across plays.
82
- */
83
- let cachedBinding: HarnessBinding | null = null;
84
-
85
- /**
86
- * Install the harness binding for this worker. Called once on init from
87
- * the per-play harness. Subsequent calls overwrite — the last writer
88
- * wins. In practice the per-play harness sets this exactly once before
89
- * any user code runs, so overwrites should never happen in production.
90
- */
91
- export function setHarnessBinding(binding: HarnessBinding | null): void {
92
- cachedBinding = binding;
93
- }
94
-
95
- /**
96
- * Read the installed binding or throw a loud error. We deliberately
97
- * throw rather than fall back to a HTTP-fetch path: fall-backs hide
98
- * misconfiguration and let perf regressions creep in silently. If
99
- * HARNESS is missing, the coordinator forgot to wire it in the
100
- * WorkerLoader factory — that's a deploy bug, not a runtime contingency.
101
- */
102
- function requireBinding(): HarnessBinding {
103
- if (!cachedBinding) {
104
- throw new Error(
105
- '[harness-stub] env.HARNESS is not wired. The coordinator must pass HARNESS in the WorkerLoader factory env. ' +
106
- 'See apps/play-runner-workers/src/coordinator-entry.ts -> loadDynamicPlayWorkerSync.',
107
- );
108
- }
109
- return cachedBinding;
110
- }
111
-
112
- // ---------------------------------------------------------------------------
113
- // Public stub functions — these are what call sites use instead of the
114
- // in-bundle implementations they replace.
115
- //
116
- // Each function MUST stay a one-line forwarder to keep the per-play
117
- // bundle minimal. If a stub starts growing logic, that logic belongs in
118
- // the harness Worker, not here.
119
- // ---------------------------------------------------------------------------
120
-
121
- /**
122
- * Liveness ping. Mostly used by tests + diagnostics that run inside a
123
- * play context; production code rarely calls this.
124
- */
125
- export async function harnessPing(): Promise<{ ok: true; ts: number }> {
126
- return requireBinding().ping();
127
- }
128
-
129
- /**
130
- * Forward a runtime-API call through the harness.
131
- *
132
- * Replaces what was previously a direct `fetch(env.RUNTIME_API, ...)`
133
- * call in the per-play harness. The transport is identical (HTTPS to
134
- * the upstream), but the HTTP client lives in the harness Worker so
135
- * its retry/timeout/error code doesn't ride in every per-play bundle.
136
- */
137
- export async function harnessRuntimeApiCall(
138
- input: RuntimeApiCallInput,
139
- ): Promise<RuntimeApiCallResult> {
140
- return requireBinding().runtimeApiCall(input);
141
- }
142
-
143
- export async function harnessClaimRuntimeReceipt(
144
- input: RuntimeReceiptInput,
145
- ): Promise<WorkReceiptClaim> {
146
- return requireBinding().claimRuntimeReceipt(input);
147
- }
148
-
149
- export async function harnessClaimRuntimeReceipts(
150
- input: RuntimeReceiptsInput,
151
- ): Promise<WorkReceiptClaim[]> {
152
- return requireBinding().claimRuntimeReceipts(input);
153
- }
154
-
155
- export async function harnessGetRuntimeReceipt(
156
- input: RuntimeReceiptInput,
157
- ): Promise<WorkReceipt | null> {
158
- return requireBinding().getRuntimeReceipt(input);
159
- }
160
-
161
- export async function harnessMarkRuntimeReceiptsRunning(
162
- input: MarkRuntimeReceiptsRunningInput,
163
- ): Promise<Array<WorkReceipt | null>> {
164
- return requireBinding().markRuntimeReceiptsRunning(input);
165
- }
166
-
167
- export async function harnessCompleteRuntimeReceipt(
168
- input: CompleteRuntimeReceiptInput,
169
- ): Promise<WorkReceipt | null> {
170
- return requireBinding().completeRuntimeReceipt(input);
171
- }
172
-
173
- export async function harnessCompleteRuntimeReceipts(
174
- input: CompleteRuntimeReceiptsInput,
175
- ): Promise<Array<WorkReceipt | null>> {
176
- return requireBinding().completeRuntimeReceipts(input);
177
- }
178
-
179
- export async function harnessFailRuntimeReceipt(
180
- input: FailRuntimeReceiptInput,
181
- ): Promise<WorkReceipt | null> {
182
- return requireBinding().failRuntimeReceipt(input);
183
- }
184
-
185
- export async function harnessReleaseRuntimeReceipt(
186
- input: ReleaseRuntimeReceiptInput,
187
- ): Promise<WorkReceipt | null> {
188
- return requireBinding().releaseRuntimeReceipt(input);
189
- }
190
-
191
- export async function harnessFailRuntimeReceipts(
192
- input: FailRuntimeReceiptsInput,
193
- ): Promise<Array<WorkReceipt | null>> {
194
- return requireBinding().failRuntimeReceipts(input);
195
- }
196
-
197
- export async function harnessHeartbeatRuntimeReceipts(
198
- input: HeartbeatRuntimeReceiptsInput,
199
- ): Promise<Array<WorkReceipt | null>> {
200
- return requireBinding().heartbeatRuntimeReceipts(input);
201
- }
202
-
203
- /**
204
- * Read a bounded staged-file byte range through typed harness RPC. This is the
205
- * only staged-file data path for per-play Workers; there is intentionally no
206
- * HTTP fetch fallback because stale parallel paths caused empty CSV streams in
207
- * preview.
208
- */
209
- export async function harnessReadStagedFileChunk(
210
- input: StagedFileChunkInput,
211
- ): Promise<StagedFileChunkResult> {
212
- return requireBinding().readStagedFileChunk(input);
213
- }
214
-
215
- export async function harnessReadSheetDatasetRows(
216
- input: SheetDatasetRowsInput,
217
- ): Promise<SheetDatasetRowsResult> {
218
- return requireBinding().readSheetDatasetRows(input);
219
- }
220
-
221
- export async function harnessReadSheetDatasetRowKeys(
222
- input: SheetDatasetRowKeysInput,
223
- ): Promise<SheetDatasetRowKeysResult> {
224
- return requireBinding().readSheetDatasetRowKeys(input);
225
- }
226
-
227
- export async function harnessHeartbeatSheetAttempt(
228
- input: SheetAttemptHeartbeatInput,
229
- ): Promise<SheetAttemptHeartbeatResult> {
230
- return requireBinding().heartbeatSheetAttempt(input);
231
- }
232
-
233
- export async function harnessReleaseSheetAttempt(
234
- input: SheetAttemptReleaseInput,
235
- ): Promise<SheetAttemptReleaseResult> {
236
- return requireBinding().releaseSheetAttempt(input);
237
- }
238
-
239
- export async function harnessReleaseRuntimeReceipts(
240
- input: WorkReceiptReleaseInput,
241
- ): Promise<WorkReceiptReleaseResult> {
242
- return requireBinding().releaseRuntimeReceipts(input);
243
- }
244
-
245
- /**
246
- * Warm Postgres sessions in the long-lived harness Worker. This preserves the
247
- * map fast path without bundling the Neon client into every dynamic play.
248
- */
249
- export async function harnessPrewarmPostgresSessions(input: {
250
- executorToken: string;
251
- orgId: string;
252
- playName: string;
253
- sessions: PreloadedRuntimeDbSessionInput[];
254
- }): Promise<{ ok: true; sessions: number }> {
255
- return requireBinding().prewarmPostgresSessions(input);
256
- }
257
-
258
- /**
259
- * Start or continue a map dataset write inside the harness, so this call
260
- * skips per-play callback overhead for heavy Postgres writes.
261
- */
262
- export async function harnessStartSheetDataset(input: {
263
- baseUrl: string;
264
- executorToken: string;
265
- orgId: string;
266
- preloadedDbSessions?: PreloadedRuntimeDbSessionInput[] | null;
267
- playName: string;
268
- tableNamespace: string;
269
- sheetContract: unknown;
270
- rows: Array<Record<string, unknown>>;
271
- runId: string;
272
- attemptId?: string | null;
273
- attemptOwnerRunId?: string | null;
274
- attemptExpiresAt?: string | null;
275
- attemptSeq?: number | null;
276
- attemptLeaseTtlMs?: number | null;
277
- writeVersion?: number | null;
278
- inputOffset?: number;
279
- force?: boolean;
280
- userEmail?: string | null;
281
- }): Promise<{
282
- inserted: number;
283
- skipped: number;
284
- pendingRows: Array<Record<string, unknown>>;
285
- completedRows: Array<Record<string, unknown>>;
286
- blockedRows: Array<Record<string, unknown>>;
287
- tableNamespace: string;
288
- attemptId?: string;
289
- attemptOwnerRunId?: string;
290
- attemptExpiresAt?: string;
291
- attemptSeq?: number;
292
- writeVersion?: number;
293
- timings?: Array<Record<string, unknown>>;
294
- }> {
295
- return requireBinding().startSheetDataset(input);
296
- }
297
-
298
- /**
299
- * Persist completed map rows inside the harness, directly through the
300
- * scoped Neon callback surface.
301
- */
302
- export async function harnessPersistCompletedSheetRows(input: {
303
- baseUrl: string;
304
- executorToken: string;
305
- orgId: string;
306
- preloadedDbSessions?: PreloadedRuntimeDbSessionInput[] | null;
307
- playName: string;
308
- tableNamespace: string;
309
- sheetContract: unknown;
310
- rows: Array<Record<string, unknown>>;
311
- outputFields: string[];
312
- runId: string;
313
- attemptId?: string | null;
314
- attemptOwnerRunId?: string | null;
315
- attemptExpiresAt?: string | null;
316
- attemptSeq?: number | null;
317
- writeVersion?: number | null;
318
- forceFailedRows?: boolean;
319
- userEmail?: string | null;
320
- }): Promise<{
321
- ok: true;
322
- rowsWritten: number;
323
- tableNamespace: string;
324
- fencedKeys?: string[];
325
- staleDropped?: number;
326
- staleDroppedKeys?: string[];
327
- }> {
328
- return requireBinding().persistCompletedMapRows(input);
329
- }
@@ -1,240 +0,0 @@
1
- /**
2
- * Workers-only Deepline SDK entry.
3
- *
4
- * The normal `deepline` package entry exports the REST client, config loading,
5
- * file writers, and CLI-oriented helpers. Per-graphHash Workers only need the
6
- * tiny play-definition DSL at runtime. The esm_workers bundler aliases
7
- * `import { definePlay } from "deepline"` to this file so user plays do not
8
- * compile the full SDK client into every dynamic Worker isolate.
9
- */
10
-
11
- import type {
12
- ConditionalStepResolver,
13
- DefinePlayConfig,
14
- DeeplinePlayRuntimeContext,
15
- DefinedPlay,
16
- PlayBindings,
17
- PlayInputContract,
18
- PlayReturnObject,
19
- PlayStepProgramStep,
20
- StepProgram,
21
- StepProgramResolver,
22
- StepOptions,
23
- StepResolver,
24
- } from './play.js';
25
-
26
- export type {
27
- ConditionalStepResolver,
28
- DefinePlayConfig,
29
- DeeplineNamedPlay,
30
- DeeplinePlayRuntimeContext,
31
- DefinedPlay,
32
- ColumnMap,
33
- CsvInput,
34
- FileInput,
35
- ColumnResolver,
36
- DatasetBuilder,
37
- PlayBindings,
38
- PlayDataset,
39
- PlayDatasetInput,
40
- PlayInputContract,
41
- PlayJob,
42
- PlayReturnObject,
43
- PlayStepProgramStep,
44
- PrebuiltPlayRef,
45
- StepProgram,
46
- StepProgramResolver,
47
- StepOptions,
48
- StepResolver,
49
- ToolExecuteResult,
50
- } from './play.js';
51
-
52
- const PLAY_METADATA_SYMBOL = Symbol.for('deepline.play.metadata');
53
-
54
- type PlayMetadata = {
55
- name: string;
56
- description?: string;
57
- bindings?: PlayBindings;
58
- inputSchema?: Record<string, unknown>;
59
- billing?: PlayBindings['billing'];
60
- };
61
-
62
- class WorkerConditionalStepResolver<
63
- Row,
64
- Value,
65
- ElseValue,
66
- > implements ConditionalStepResolver<Row, Value, ElseValue> {
67
- readonly kind = 'conditional' as const;
68
-
69
- constructor(
70
- readonly when: (row: Row, index: number) => boolean | Promise<boolean>,
71
- readonly run: StepResolver<Row, Value>,
72
- readonly elseValue: ElseValue,
73
- ) {}
74
-
75
- else<ValueElse>(
76
- value: ValueElse,
77
- ): ConditionalStepResolver<Row, Value, ValueElse> {
78
- return new WorkerConditionalStepResolver(this.when, this.run, value);
79
- }
80
- }
81
-
82
- class WorkerStepProgram<Input, Output, ReturnValue> implements StepProgram<
83
- Input,
84
- Output,
85
- ReturnValue
86
- > {
87
- readonly kind = 'steps' as const;
88
- declare readonly __inputType?: (input: Input) => void;
89
-
90
- constructor(
91
- readonly steps: readonly PlayStepProgramStep[],
92
- readonly returnResolver?: StepResolver<Output, ReturnValue>,
93
- ) {}
94
-
95
- step<Name extends string, Value>(
96
- name: Name,
97
- resolver:
98
- | StepResolver<Output, Value>
99
- | ConditionalStepResolver<Output, Value>
100
- | StepProgramResolver<Output, Value>,
101
- ): StepProgram<Input, Output & Record<Name, Value>, ReturnValue>;
102
- step<Name extends string, Value>(
103
- name: Name,
104
- resolver: StepResolver<Output, Value> | StepProgramResolver<Output, Value>,
105
- options: StepOptions<Output, Value>,
106
- ): StepProgram<Input, Output & Record<Name, Value | null>, ReturnValue>;
107
- step<Name extends string, Value>(
108
- name: Name,
109
- resolver:
110
- | StepResolver<Output, Value>
111
- | ConditionalStepResolver<Output, Value>
112
- | StepProgramResolver<Output, Value>,
113
- options?: StepOptions<Output, Value>,
114
- ): StepProgram<Input, Output & Record<Name, Value | null>, ReturnValue> {
115
- const stepResolver =
116
- options?.runIf && !isConditionalStepResolver(resolver)
117
- ? new WorkerConditionalStepResolver(
118
- options.runIf,
119
- resolver as StepResolver<Output, Value>,
120
- null,
121
- )
122
- : resolver;
123
- return new WorkerStepProgram(
124
- [
125
- ...this.steps,
126
- {
127
- name,
128
- ...(options?.recompute === true ? { recompute: true } : {}),
129
- ...(options?.recomputeOnError === true
130
- ? { recomputeOnError: true }
131
- : {}),
132
- ...(typeof options?.staleAfterSeconds === 'number'
133
- ? { staleAfterSeconds: options.staleAfterSeconds }
134
- : {}),
135
- resolver: stepResolver as PlayStepProgramStep['resolver'],
136
- },
137
- ],
138
- this.returnResolver as StepResolver<
139
- Output & Record<Name, Value | null>,
140
- ReturnValue
141
- >,
142
- );
143
- }
144
-
145
- return<Value>(
146
- resolver: StepResolver<Output, Value>,
147
- ): StepProgram<Input, Output, Value> {
148
- return new WorkerStepProgram(this.steps, resolver);
149
- }
150
- }
151
-
152
- function isConditionalStepResolver(
153
- value: unknown,
154
- ): value is ConditionalStepResolver<unknown, unknown> {
155
- return (value as { kind?: unknown } | null)?.kind === 'conditional';
156
- }
157
-
158
- export function steps<TInput>(): StepProgram<TInput, TInput, TInput> {
159
- return new WorkerStepProgram<TInput, TInput, TInput>([]);
160
- }
161
-
162
- export function runIf<Row, Value>(
163
- predicate: (row: Row, index: number) => boolean | Promise<boolean>,
164
- resolver: StepResolver<Row, Value>,
165
- ): ConditionalStepResolver<Row, Value, null> {
166
- return new WorkerConditionalStepResolver(predicate, resolver, null);
167
- }
168
-
169
- export function defineInput<TInput>(
170
- schema: Record<string, unknown>,
171
- ): PlayInputContract<TInput> {
172
- return { schema };
173
- }
174
-
175
- export function definePlay<TInput, TOutput extends PlayReturnObject>(
176
- config: DefinePlayConfig<TInput, TOutput>,
177
- ): DefinedPlay<TInput, TOutput>;
178
- export function definePlay<TInput, TOutput extends PlayReturnObject>(
179
- name: string,
180
- fn: (ctx: DeeplinePlayRuntimeContext, input: TInput) => Promise<TOutput>,
181
- bindings?: PlayBindings,
182
- ): DefinedPlay<TInput, TOutput>;
183
- export function definePlay<TInput, TOutput extends PlayReturnObject>(
184
- nameOrConfig: string | DefinePlayConfig<TInput, TOutput>,
185
- maybeFn?: (
186
- ctx: DeeplinePlayRuntimeContext,
187
- input: TInput,
188
- ) => Promise<TOutput>,
189
- maybeBindings?: PlayBindings,
190
- ): DefinedPlay<TInput, TOutput> {
191
- const config =
192
- typeof nameOrConfig === 'string'
193
- ? {
194
- name: nameOrConfig,
195
- fn: maybeFn,
196
- bindings: maybeBindings,
197
- description: maybeBindings?.description,
198
- inputSchema: undefined,
199
- billing: maybeBindings?.billing,
200
- }
201
- : {
202
- name: nameOrConfig.id,
203
- fn: nameOrConfig.run,
204
- bindings: nameOrConfig.bindings,
205
- description: nameOrConfig.description,
206
- inputSchema: nameOrConfig.input.schema,
207
- billing: nameOrConfig.billing,
208
- };
209
-
210
- const name = config.name;
211
- const fn = config.fn;
212
- const description = config.description?.trim();
213
-
214
- const metadata: PlayMetadata = {
215
- name,
216
- ...(description ? { description } : {}),
217
- ...(config.bindings ? { bindings: config.bindings } : {}),
218
- ...(config.inputSchema ? { inputSchema: config.inputSchema } : {}),
219
- ...(config.billing ? { billing: config.billing } : {}),
220
- };
221
- const play = fn as DefinedPlay<TInput, TOutput>;
222
-
223
- Object.defineProperties(play, {
224
- [PLAY_METADATA_SYMBOL]: { value: metadata },
225
- playName: { value: name, enumerable: true },
226
- bindings: { value: config.bindings, enumerable: true },
227
- name: { value: name },
228
- });
229
- return play;
230
- }
231
-
232
- export const defineWorkflow = definePlay;
233
-
234
- export function getDefinedPlayMetadata(value: unknown): PlayMetadata | null {
235
- return typeof value === 'function'
236
- ? (((value as unknown as Record<PropertyKey, unknown>)[
237
- PLAY_METADATA_SYMBOL
238
- ] as PlayMetadata | undefined) ?? null)
239
- : null;
240
- }