deepline 0.3.231 → 0.3.233

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.
@@ -1951,7 +1951,7 @@ configureProxyFromEnv();
1951
1951
 
1952
1952
  // src/cli/index.ts
1953
1953
  import { mkdtemp as mkdtemp4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
1954
- import { join as join28 } from "path";
1954
+ import { join as join29 } from "path";
1955
1955
  import { tmpdir as tmpdir7 } from "os";
1956
1956
  import { Command as Command5 } from "commander";
1957
1957
 
@@ -2996,6 +2996,409 @@ function resolveCliCommandContext(inputConfig, requestedScope) {
2996
2996
  };
2997
2997
  }
2998
2998
 
2999
+ // ../integration-contracts/theirstack/execution-policy.ts
3000
+ var THEIRSTACK_SLOW_JOB_SEARCH_PROVIDER_TIMEOUT_MS = 135e3;
3001
+ var THEIRSTACK_SLOW_JOB_SEARCH_CLIENT_TIMEOUT_MS = 6e4 + THEIRSTACK_SLOW_JOB_SEARCH_PROVIDER_TIMEOUT_MS + 15e3;
3002
+ var THEIRSTACK_COMPANY_SEARCH_CLIENT_TIMEOUT_MS = 21e4;
3003
+ var LONG_JOB_SEARCH_WINDOW_MS = 365 * 24 * 60 * 60 * 1e3;
3004
+ var DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
3005
+ function parseDateOnly(value) {
3006
+ if (typeof value !== "string" || !DATE_ONLY_PATTERN.test(value)) {
3007
+ return null;
3008
+ }
3009
+ const timestamp = Date.parse(`${value}T00:00:00.000Z`);
3010
+ if (!Number.isFinite(timestamp)) {
3011
+ return null;
3012
+ }
3013
+ return new Date(timestamp).toISOString().slice(0, 10) === value ? timestamp : null;
3014
+ }
3015
+ function usesLongExplicitDateWindow(payload) {
3016
+ const postedAtGte = parseDateOnly(payload.posted_at_gte);
3017
+ const postedAtLte = parseDateOnly(payload.posted_at_lte);
3018
+ if (postedAtGte !== null && postedAtLte !== null) {
3019
+ return postedAtLte - postedAtGte >= LONG_JOB_SEARCH_WINDOW_MS;
3020
+ }
3021
+ if (postedAtGte !== null) {
3022
+ return Date.now() - postedAtGte >= LONG_JOB_SEARCH_WINDOW_MS;
3023
+ }
3024
+ return postedAtLte !== null && payload.posted_at_gte == null;
3025
+ }
3026
+ function parseMaxAgeDays(value) {
3027
+ if (typeof value === "number") {
3028
+ return Number.isFinite(value) ? value : null;
3029
+ }
3030
+ if (typeof value !== "string" || !/^-?\d+$/.test(value.trim())) {
3031
+ return null;
3032
+ }
3033
+ const parsed = Number(value.trim());
3034
+ return Number.isSafeInteger(parsed) ? parsed : null;
3035
+ }
3036
+ function usesExtendedTheirstackJobSearchBudget(endpointId, payload) {
3037
+ if (endpointId !== "theirstack_job_search") {
3038
+ return false;
3039
+ }
3040
+ if (payload.include_total_results === true) {
3041
+ return true;
3042
+ }
3043
+ const maxAgeDays = parseMaxAgeDays(payload.posted_at_max_age_days);
3044
+ return maxAgeDays !== null && maxAgeDays >= 365 ? true : usesLongExplicitDateWindow(payload);
3045
+ }
3046
+ function resolveTheirstackClientTimeoutMs(endpointId, payload) {
3047
+ if (endpointId === "theirstack_company_search") {
3048
+ return THEIRSTACK_COMPANY_SEARCH_CLIENT_TIMEOUT_MS;
3049
+ }
3050
+ return usesExtendedTheirstackJobSearchBudget(endpointId, payload) ? THEIRSTACK_SLOW_JOB_SEARCH_CLIENT_TIMEOUT_MS : null;
3051
+ }
3052
+
3053
+ // ../integration-contracts/waterfall/execution-policy.ts
3054
+ var WATERFALL_PROSPECTOR_CLIENT_TIMEOUT_MS = 18e4;
3055
+ var WATERFALL_PROSPECTOR_LAUNCHER_TOOL_IDS = /* @__PURE__ */ new Set([
3056
+ "prospector",
3057
+ "deepline_native_prospector"
3058
+ ]);
3059
+ function resolveWaterfallClientTimeoutMs(toolId) {
3060
+ return WATERFALL_PROSPECTOR_LAUNCHER_TOOL_IDS.has(toolId.trim().toLowerCase()) ? WATERFALL_PROSPECTOR_CLIENT_TIMEOUT_MS : null;
3061
+ }
3062
+
3063
+ // ../integration-contracts/bettercontact/execution-policy.ts
3064
+ var BETTERCONTACT_LAUNCHER_CLIENT_TIMEOUT_MS = 12e4;
3065
+ var BETTERCONTACT_LAUNCHER_TOOL_IDS = /* @__PURE__ */ new Set([
3066
+ "bettercontact_enrich",
3067
+ "bettercontact_bulk_enrich"
3068
+ ]);
3069
+ function usesExtendedBetterContactLauncherBudget(toolId) {
3070
+ return BETTERCONTACT_LAUNCHER_TOOL_IDS.has(toolId.trim().toLowerCase());
3071
+ }
3072
+
3073
+ // ../plays/tool-response-contract.ts
3074
+ var RAW_V2_TOOL_RESPONSE_CONTRACT = "raw-v2";
3075
+ function legacyRawFromToolResponseRawV2(rawV2, view, responseMeta) {
3076
+ const legacyRaw = view === "data" && rawV2 && typeof rawV2 === "object" && !Array.isArray(rawV2) ? rawV2.data : rawV2;
3077
+ const deeplineBilling = responseMeta?.deepline_billing;
3078
+ if (view === "rawV2" && deeplineBilling !== void 0 && legacyRaw && typeof legacyRaw === "object" && !Array.isArray(legacyRaw)) {
3079
+ return {
3080
+ ...legacyRaw,
3081
+ deepline_billing: deeplineBilling
3082
+ };
3083
+ }
3084
+ return legacyRaw;
3085
+ }
3086
+ function providerMetaFromToolResponseRawV2(rawV2, view) {
3087
+ if (view !== "data" || !rawV2 || typeof rawV2 !== "object" || Array.isArray(rawV2)) {
3088
+ return void 0;
3089
+ }
3090
+ const meta = rawV2.meta;
3091
+ return meta && typeof meta === "object" && !Array.isArray(meta) ? meta : void 0;
3092
+ }
3093
+
3094
+ // src/tool-calls.ts
3095
+ var INCLUDE_TOOL_METADATA_HEADER = "x-deepline-include-tool-metadata";
3096
+ var EXECUTE_RESPONSE_CONTRACT_HEADER = "x-deepline-execute-response-contract";
3097
+ var EXECUTE_RESPONSE_INTENT_HEADER = "x-deepline-execute-response-intent";
3098
+ var RAW_V2_EXECUTE_RESPONSE_CONTRACT = RAW_V2_TOOL_RESPONSE_CONTRACT;
3099
+ var DEFAULT_EXECUTION_RECOVERY_TIMEOUT_MS = 15 * 60 * 1e3;
3100
+ function validateExecutionIdempotencyKey(key) {
3101
+ if (typeof key !== "string" || key.length < 1 || key.length > 200 || !/^[A-Za-z0-9._:-]+$/.test(key)) {
3102
+ throw new DeeplineError(
3103
+ "Execution idempotency keys must be 1\u2013200 ASCII letters, digits, dots, underscores, colons, or hyphens.",
3104
+ void 0,
3105
+ "IDEMPOTENCY_KEY_INVALID"
3106
+ );
3107
+ }
3108
+ }
3109
+ function getExecutionRecoveryState(value) {
3110
+ if (!isRecord2(value) || !isRecord2(value.executionRecovery)) return null;
3111
+ const state = value.executionRecovery.state;
3112
+ return state === "running" || state === "completed" || state === "outcome_unknown" ? state : null;
3113
+ }
3114
+ function isRecoverableExecutionAttemptError(error) {
3115
+ if (error instanceof ToolExecutionError) {
3116
+ return error.code === "EXECUTION_IN_PROGRESS" || error.origin === "deepline" && error.category === "network" && error.networkScope === "client_to_deepline";
3117
+ }
3118
+ return error instanceof DeeplineError && (error.code === "EXECUTION_IN_PROGRESS" || error.code?.startsWith("NETWORK_") === true && error.statusCode === void 0);
3119
+ }
3120
+ function isRecoverableExecutionLookupError(error) {
3121
+ if (isRecoverableExecutionAttemptError(error)) return true;
3122
+ return error instanceof DeeplineError && (error.statusCode === 429 || error.statusCode !== void 0 && error.statusCode >= 500);
3123
+ }
3124
+ function timeoutWithinRecoveryBudget(requestTimeoutMs, defaultRequestTimeoutMs, remainingMs) {
3125
+ return Math.min(requestTimeoutMs ?? defaultRequestTimeoutMs, remainingMs);
3126
+ }
3127
+ function executionRecoveryError(input2) {
3128
+ return new ToolExecutionError(input2.message, {
3129
+ toolId: input2.toolId,
3130
+ provider: null,
3131
+ operation: input2.toolId,
3132
+ code: input2.code,
3133
+ origin: "deepline",
3134
+ category: input2.code === "EXECUTION_OUTCOME_UNKNOWN" ? "unknown" : "conflict",
3135
+ retryable: input2.code !== "EXECUTION_OUTCOME_UNKNOWN",
3136
+ statusCode: null,
3137
+ requestId: null,
3138
+ retryAfterMs: null,
3139
+ networkKind: null,
3140
+ networkScope: null,
3141
+ publicDetails: { idempotencyKey: input2.idempotencyKey }
3142
+ });
3143
+ }
3144
+ var DEEPLINEAGENT_EXECUTE_TIMEOUT_MS = 15 * 60 * 1e3;
3145
+ var APIFY_SYNC_DEFAULT_TIMEOUT_MS = 3e5;
3146
+ var APIFY_SYNC_RESPONSE_GRACE_MS = 9e4;
3147
+ function resolveToolExecuteTimeoutMs(toolId, input2) {
3148
+ const normalized = toolId.trim().toLowerCase();
3149
+ if (normalized === "apify_run_actor_sync") {
3150
+ const requestedTimeoutMs = input2.timeoutMs ?? APIFY_SYNC_DEFAULT_TIMEOUT_MS;
3151
+ if (typeof requestedTimeoutMs === "number" && Number.isFinite(requestedTimeoutMs) && requestedTimeoutMs > 0) {
3152
+ return Math.floor(requestedTimeoutMs) + APIFY_SYNC_RESPONSE_GRACE_MS;
3153
+ }
3154
+ }
3155
+ const theirstackTimeoutMs = resolveTheirstackClientTimeoutMs(
3156
+ normalized,
3157
+ input2
3158
+ );
3159
+ if (theirstackTimeoutMs !== null) return theirstackTimeoutMs;
3160
+ const waterfallTimeoutMs = resolveWaterfallClientTimeoutMs(normalized);
3161
+ if (waterfallTimeoutMs !== null) return waterfallTimeoutMs;
3162
+ if (usesExtendedBetterContactLauncherBudget(normalized)) {
3163
+ return BETTERCONTACT_LAUNCHER_CLIENT_TIMEOUT_MS;
3164
+ }
3165
+ return normalized === "deeplineagent" || normalized === "deeplineagent_deeplineagent" || normalized === "ai_inference" || normalized === "deeplineagent_ai_inference" || normalized === "ai_evaluate" || normalized === "deeplineagent_ai_evaluate" || normalized === "aiinference" ? DEEPLINEAGENT_EXECUTE_TIMEOUT_MS : void 0;
3166
+ }
3167
+ function isRecord2(value) {
3168
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
3169
+ }
3170
+ function materializeToolExecutionResponse(response) {
3171
+ const toolResponse = response.toolResponse;
3172
+ if (!toolResponse && isRecord2(response.result)) {
3173
+ const legacyResult = response.result;
3174
+ if (Object.prototype.hasOwnProperty.call(legacyResult, "data")) {
3175
+ const legacyMeta = isRecord2(legacyResult.meta) ? legacyResult.meta : void 0;
3176
+ return {
3177
+ ...response,
3178
+ toolResponse: {
3179
+ raw: legacyResult.data,
3180
+ ...legacyMeta ? { meta: legacyMeta } : {}
3181
+ }
3182
+ };
3183
+ }
3184
+ }
3185
+ if (!toolResponse || Object.prototype.hasOwnProperty.call(toolResponse, "raw")) {
3186
+ return response;
3187
+ }
3188
+ const rawV2 = toolResponse.rawV2;
3189
+ const view = toolResponse.view;
3190
+ const providerMeta = providerMetaFromToolResponseRawV2(
3191
+ rawV2,
3192
+ view ?? "rawV2"
3193
+ );
3194
+ const responseMeta = isRecord2(toolResponse.responseMeta) ? toolResponse.responseMeta : void 0;
3195
+ return {
3196
+ ...response,
3197
+ toolResponse: {
3198
+ ...toolResponse,
3199
+ raw: legacyRawFromToolResponseRawV2(
3200
+ rawV2,
3201
+ view ?? "rawV2",
3202
+ responseMeta
3203
+ ),
3204
+ ...toolResponse.meta || providerMeta || responseMeta ? {
3205
+ meta: {
3206
+ ...toolResponse.meta ?? {},
3207
+ ...providerMeta ?? {},
3208
+ ...responseMeta ?? {}
3209
+ }
3210
+ } : {}
3211
+ }
3212
+ };
3213
+ }
3214
+ var ToolCalls = class {
3215
+ constructor(http, defaultRequestTimeoutMs) {
3216
+ this.http = http;
3217
+ this.defaultRequestTimeoutMs = defaultRequestTimeoutMs;
3218
+ }
3219
+ async call(toolId, input2, options) {
3220
+ const inputSnapshot = JSON.parse(JSON.stringify(input2));
3221
+ const metadataSnapshot = options?.metadata ? JSON.parse(JSON.stringify(options.metadata)) : void 0;
3222
+ const idempotencyKey = options?.idempotencyKey ?? (options?.recover ? crypto.randomUUID() : void 0);
3223
+ if (idempotencyKey !== void 0) {
3224
+ validateExecutionIdempotencyKey(idempotencyKey);
3225
+ if (options?.recoveryTimeoutMs !== void 0 && (!Number.isFinite(options.recoveryTimeoutMs) || options.recoveryTimeoutMs < 0)) {
3226
+ throw new DeeplineError(
3227
+ "recoveryTimeoutMs must be a finite, non-negative number.",
3228
+ void 0,
3229
+ "IDEMPOTENCY_KEY_INVALID"
3230
+ );
3231
+ }
3232
+ await options?.onExecution?.({ idempotencyKey });
3233
+ }
3234
+ const timeoutMs = options?.timeout ?? resolveToolExecuteTimeoutMs(toolId, inputSnapshot);
3235
+ if (idempotencyKey !== void 0) {
3236
+ await this.lookupExecutionByKey(idempotencyKey, timeoutMs);
3237
+ }
3238
+ const isApifySync = toolId.trim().toLowerCase() === "apify_run_actor_sync";
3239
+ const headers = {
3240
+ [EXECUTE_RESPONSE_CONTRACT_HEADER]: RAW_V2_EXECUTE_RESPONSE_CONTRACT,
3241
+ ...isApifySync ? { "X-Deepline-Apify-Sync-Response-Budget": "extended-v1" } : {},
3242
+ [TOOL_EXECUTION_ERROR_SCHEMA_HEADER]: String(
3243
+ TOOL_EXECUTION_ERROR_SCHEMA_VERSION
3244
+ ),
3245
+ ...options?.includeToolMetadata ? { [INCLUDE_TOOL_METADATA_HEADER]: "true" } : {},
3246
+ [EXECUTE_RESPONSE_INTENT_HEADER]: options?.responseIntent ?? "raw",
3247
+ ...idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {},
3248
+ ...options?.searchRef ? { "x-deepline-search-ref": options.searchRef } : {}
3249
+ };
3250
+ const request = (requestTimeoutMs) => this.http.post(
3251
+ `/api/v2/integrations/${encodeURIComponent(toolId)}/execute`,
3252
+ {
3253
+ payload: inputSnapshot,
3254
+ ...metadataSnapshot ? { metadata: metadataSnapshot } : {}
3255
+ },
3256
+ headers,
3257
+ {
3258
+ timeout: requestTimeoutMs,
3259
+ maxRetries: idempotencyKey ? 0 : options?.maxRetries ?? 0,
3260
+ retryApiErrors: options?.retryApiErrors === true,
3261
+ exactUrlOnly: true,
3262
+ toolId,
3263
+ idempotencyKey
3264
+ }
3265
+ );
3266
+ let response;
3267
+ let recoveryDeadline = null;
3268
+ const recoveryTimeoutMs = options?.recoveryTimeoutMs ?? DEFAULT_EXECUTION_RECOVERY_TIMEOUT_MS;
3269
+ let retryDelayMs = 1e3;
3270
+ const recoveryTimeoutError = () => executionRecoveryError({
3271
+ toolId,
3272
+ idempotencyKey,
3273
+ code: "EXECUTION_RECOVERY_TIMEOUT",
3274
+ message: `Execution recovery for ${idempotencyKey} did not finish before the recovery timeout. Inspect client.executions.getByKey() and resume with the same idempotency key.`
3275
+ });
3276
+ const waitForRecoveryRetry = async (deadline) => {
3277
+ const remainingMs = deadline - Date.now();
3278
+ if (remainingMs <= 0) throw recoveryTimeoutError();
3279
+ await new Promise(
3280
+ (resolve22) => setTimeout(resolve22, Math.min(retryDelayMs, remainingMs))
3281
+ );
3282
+ retryDelayMs = Math.min(retryDelayMs * 2, 5e3);
3283
+ };
3284
+ const lookupDuringRecovery = async () => {
3285
+ while (true) {
3286
+ const remainingMs = recoveryDeadline - Date.now();
3287
+ if (remainingMs <= 0) throw recoveryTimeoutError();
3288
+ try {
3289
+ return await this.lookupExecutionByKey(
3290
+ idempotencyKey,
3291
+ timeoutWithinRecoveryBudget(
3292
+ timeoutMs,
3293
+ this.defaultRequestTimeoutMs,
3294
+ remainingMs
3295
+ )
3296
+ );
3297
+ } catch (error) {
3298
+ if (!isRecoverableExecutionLookupError(error)) throw error;
3299
+ await waitForRecoveryRetry(recoveryDeadline);
3300
+ }
3301
+ }
3302
+ };
3303
+ while (true) {
3304
+ const remainingMs = recoveryDeadline === null ? null : recoveryDeadline - Date.now();
3305
+ if (remainingMs !== null && remainingMs <= 0) {
3306
+ throw recoveryTimeoutError();
3307
+ }
3308
+ try {
3309
+ response = await request(
3310
+ remainingMs === null ? timeoutMs : timeoutWithinRecoveryBudget(
3311
+ timeoutMs,
3312
+ this.defaultRequestTimeoutMs,
3313
+ remainingMs
3314
+ )
3315
+ );
3316
+ const recoveryState = getExecutionRecoveryState(response);
3317
+ if (recoveryState === "outcome_unknown") {
3318
+ if (!idempotencyKey) break;
3319
+ throw executionRecoveryError({
3320
+ toolId,
3321
+ idempotencyKey,
3322
+ code: "EXECUTION_OUTCOME_UNKNOWN",
3323
+ message: `The outcome of execution ${idempotencyKey} is unknown. Do not retry with a new key; inspect client.executions.getByKey().`
3324
+ });
3325
+ }
3326
+ if (!idempotencyKey || recoveryState !== "running") {
3327
+ break;
3328
+ }
3329
+ if (recoveryDeadline === null) {
3330
+ recoveryDeadline = Date.now() + recoveryTimeoutMs;
3331
+ }
3332
+ } catch (error) {
3333
+ if (idempotencyKey && error instanceof DeeplineError && error.code === "EXECUTION_OUTCOME_UNKNOWN") {
3334
+ throw executionRecoveryError({
3335
+ toolId,
3336
+ idempotencyKey,
3337
+ code: "EXECUTION_OUTCOME_UNKNOWN",
3338
+ message: error.message
3339
+ });
3340
+ }
3341
+ if (!idempotencyKey || !isRecoverableExecutionAttemptError(error)) {
3342
+ throw error;
3343
+ }
3344
+ if (recoveryDeadline === null) {
3345
+ recoveryDeadline = Date.now() + recoveryTimeoutMs;
3346
+ }
3347
+ }
3348
+ await waitForRecoveryRetry(recoveryDeadline);
3349
+ const recovered = await lookupDuringRecovery();
3350
+ if (getExecutionRecoveryState(recovered) === "outcome_unknown") {
3351
+ throw executionRecoveryError({
3352
+ toolId,
3353
+ idempotencyKey,
3354
+ code: "EXECUTION_OUTCOME_UNKNOWN",
3355
+ message: `The outcome of execution ${idempotencyKey} is unknown. Do not retry with a new key; inspect client.executions.getByKey().`
3356
+ });
3357
+ }
3358
+ }
3359
+ const materialized = materializeToolExecutionResponse(response);
3360
+ return idempotencyKey ? { ...materialized, idempotencyKey } : materialized;
3361
+ }
3362
+ /** Read the durable state of a keyed tool execution. */
3363
+ async getByKey(idempotencyKey) {
3364
+ validateExecutionIdempotencyKey(idempotencyKey);
3365
+ const result = await this.lookupExecutionByKey(idempotencyKey);
3366
+ if (!result) {
3367
+ throw new DeeplineError(
3368
+ `No execution exists for idempotency key ${idempotencyKey}.`,
3369
+ 404,
3370
+ "EXECUTION_NOT_FOUND"
3371
+ );
3372
+ }
3373
+ return result;
3374
+ }
3375
+ async lookupExecutionByKey(idempotencyKey, timeoutMs) {
3376
+ validateExecutionIdempotencyKey(idempotencyKey);
3377
+ let supported = false;
3378
+ const result = await this.http.get(
3379
+ `/api/v2/executions/by-key/${encodeURIComponent(idempotencyKey)}`,
3380
+ {
3381
+ exactUrlOnly: true,
3382
+ maxRetries: 0,
3383
+ timeout: timeoutMs,
3384
+ idempotencyKey,
3385
+ allowNotFound: true,
3386
+ onResponse: (response) => {
3387
+ supported = response.headers.get("X-Deepline-Idempotency-Supported") === "true";
3388
+ }
3389
+ }
3390
+ );
3391
+ if (!supported) {
3392
+ throw new DeeplineError(
3393
+ "This Deepline server does not support recoverable tool executions; no tool was dispatched.",
3394
+ 422,
3395
+ "IDEMPOTENCY_NOT_SUPPORTED"
3396
+ );
3397
+ }
3398
+ return result;
3399
+ }
3400
+ };
3401
+
2999
3402
  // ../plays/artifact-contract-version.ts
3000
3403
  var CURRENT_PLAY_ARTIFACT_CONTRACT_VERSION = 2;
3001
3404
 
@@ -3046,7 +3449,7 @@ var SDK_RELEASE = {
3046
3449
  // getters keep their established compatibility behavior.
3047
3450
  // 0.3.1 deprecated the legacy `deepline enrich` command in favor of Plays.
3048
3451
  // 0.3.90 is the first deliberately versioned SDK release for API v3.
3049
- version: "0.3.231",
3452
+ version: "0.3.233",
3050
3453
  updateSummary: "Play grep now returns concise results with the matched fields and terms. Automatic CLI updates are enabled by default; use `deepline settings autoupdate off` to opt out, `deepline settings autoupdate on` to re-enable updates, or `deepline settings autoupdate pin <version>` to hold an exact release.",
3051
3454
  packageCapabilities: {
3052
3455
  updatePreferences: 1
@@ -3730,7 +4133,7 @@ function providerLabelFromToolId(toolId) {
3730
4133
  const provider = normalized.split(/[_:./-]+/)[0];
3731
4134
  return provider || normalized || "provider";
3732
4135
  }
3733
- function isRecord2(value) {
4136
+ function isRecord3(value) {
3734
4137
  return value !== null && typeof value === "object" && !Array.isArray(value);
3735
4138
  }
3736
4139
  var HttpClient = class {
@@ -3882,7 +4285,7 @@ var HttpClient = class {
3882
4285
  const parsed = parseResponseBody(body);
3883
4286
  const structuredToolError = options?.toolId && !response.ok ? deserializeToolExecutionFailure(
3884
4287
  apiErrorMessage(parsed, response.status),
3885
- isRecord2(parsed) ? parsed.tool_error : null,
4288
+ isRecord3(parsed) ? parsed.tool_error : null,
3886
4289
  TOOL_EXECUTION_ERROR_SCHEMA_VERSION
3887
4290
  ) : null;
3888
4291
  if (structuredToolError) {
@@ -4953,11 +5356,11 @@ function buildPlayDocflowNodeErrorPreview(error, redactor = createSecretRedactio
4953
5356
  return "Non-Error value thrown (message unavailable)";
4954
5357
  }
4955
5358
  }
4956
- function isRecord3(value) {
5359
+ function isRecord4(value) {
4957
5360
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
4958
5361
  }
4959
5362
  function normalizePreview(value, depth) {
4960
- if (!isRecord3(value) || typeof value.kind !== "string") return null;
5363
+ if (!isRecord4(value) || typeof value.kind !== "string") return null;
4961
5364
  if (value.kind === "null") return { kind: "null" };
4962
5365
  if (value.kind === "scalar") {
4963
5366
  if (typeof value.value === "string" || typeof value.value === "boolean" || typeof value.value === "number" && Number.isFinite(value.value)) {
@@ -5022,7 +5425,7 @@ function normalizePreview(value, depth) {
5022
5425
  ...value.truncated === true || totalItems > items.length ? { truncated: true } : {}
5023
5426
  };
5024
5427
  }
5025
- if (value.kind === "object" && isRecord3(value.fields)) {
5428
+ if (value.kind === "object" && isRecord4(value.fields)) {
5026
5429
  const fields2 = {};
5027
5430
  for (const [key, field] of Object.entries(value.fields).slice(
5028
5431
  0,
@@ -5042,10 +5445,10 @@ function normalizePreview(value, depth) {
5042
5445
  return null;
5043
5446
  }
5044
5447
  function normalizePlayDocflowNodeIoState(value) {
5045
- if (!isRecord3(value)) return void 0;
5448
+ if (!isRecord4(value)) return void 0;
5046
5449
  const attempt = typeof value.attempt === "number" && Number.isFinite(value.attempt) ? Math.max(0, Math.floor(value.attempt)) : 0;
5047
5450
  const normalizeMap = (raw) => {
5048
- if (!isRecord3(raw)) return void 0;
5451
+ if (!isRecord4(raw)) return void 0;
5049
5452
  const output2 = {};
5050
5453
  for (const [path, preview] of Object.entries(raw).slice(
5051
5454
  0,
@@ -5082,11 +5485,11 @@ function normalizePlayDocflowNodeIoState(value) {
5082
5485
  }
5083
5486
 
5084
5487
  // ../play-runtime/activity-observation.ts
5085
- function isRecord4(value) {
5488
+ function isRecord5(value) {
5086
5489
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
5087
5490
  }
5088
5491
  function isPlayActivityObservation(value) {
5089
- if (!isRecord4(value) || value.schemaVersion !== void 0 && value.schemaVersion !== 1 || typeof value.activityId !== "string" || !value.activityId.trim() || typeof value.observedAt !== "number" || !Number.isFinite(value.observedAt) || !isRecord4(value.target) || !isRecord4(value.state)) {
5492
+ if (!isRecord5(value) || value.schemaVersion !== void 0 && value.schemaVersion !== 1 || typeof value.activityId !== "string" || !value.activityId.trim() || typeof value.observedAt !== "number" || !Number.isFinite(value.observedAt) || !isRecord5(value.target) || !isRecord5(value.state)) {
5090
5493
  return false;
5091
5494
  }
5092
5495
  const targetKinds = /* @__PURE__ */ new Set([
@@ -5386,7 +5789,7 @@ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
5386
5789
  "terminated",
5387
5790
  "timed_out"
5388
5791
  ]);
5389
- function isRecord5(value) {
5792
+ function isRecord6(value) {
5390
5793
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
5391
5794
  }
5392
5795
  function finiteNumber(value) {
@@ -5401,7 +5804,7 @@ function isWorkCounterSegmentId(value) {
5401
5804
  );
5402
5805
  }
5403
5806
  function normalizePlayRunLedgerTerminalWorkCounterSegment(value) {
5404
- if (!isRecord5(value)) return void 0;
5807
+ if (!isRecord6(value)) return void 0;
5405
5808
  if (!nonnegativeSafeInteger(value.attempt) || !nonnegativeSafeInteger(value.invocationSeq) || value.invocationSeq === 0 || !isWorkCounterSegmentId(value.segmentId)) {
5406
5809
  return void 0;
5407
5810
  }
@@ -5425,7 +5828,7 @@ function hasConfirmedPlayRunLedgerWorkCounters(snapshot) {
5425
5828
  );
5426
5829
  }
5427
5830
  function normalizeWorkCounters(value) {
5428
- if (!isRecord5(value)) return void 0;
5831
+ if (!isRecord6(value)) return void 0;
5429
5832
  for (const field of [
5430
5833
  "attempt",
5431
5834
  "invocationSeq",
@@ -5515,8 +5918,8 @@ function summarizeRunRowOutcomes(snapshot) {
5515
5918
  const stepTotal = finiteNumber(progress.total);
5516
5919
  totalRows += stepTotal !== null && stepTotal >= 0 ? stepTotal : Math.max(0, finiteNumber(progress.completed) ?? 0) + Math.max(0, finiteNumber(progress.failed) ?? 0) + Math.max(0, finiteNumber(progress.supersededRows) ?? 0);
5517
5920
  }
5518
- const resultSummary = isRecord5(snapshot.resultSummary) ? snapshot.resultSummary : null;
5519
- const resultRowOutcomes = isRecord5(resultSummary?.rowOutcomes) ? resultSummary.rowOutcomes : null;
5921
+ const resultSummary = isRecord6(snapshot.resultSummary) ? snapshot.resultSummary : null;
5922
+ const resultRowOutcomes = isRecord6(resultSummary?.rowOutcomes) ? resultSummary.rowOutcomes : null;
5520
5923
  const terminalCompletedRows = finiteNumber(resultRowOutcomes?.completedRows);
5521
5924
  const terminalFailedRows = finiteNumber(resultRowOutcomes?.failedRows);
5522
5925
  const terminalTotalRows = finiteNumber(resultRowOutcomes?.totalRows);
@@ -5565,21 +5968,21 @@ function createEmptyPlayRunLedgerSnapshot(input2) {
5565
5968
  };
5566
5969
  }
5567
5970
  function normalizePlayRunLedgerSnapshot(value, fallback) {
5568
- if (!isRecord5(value)) {
5971
+ if (!isRecord6(value)) {
5569
5972
  return createEmptyPlayRunLedgerSnapshot(fallback);
5570
5973
  }
5571
5974
  const orderedStepIds = Array.isArray(value.orderedStepIds) ? value.orderedStepIds.filter(
5572
5975
  (entry) => typeof entry === "string" && Boolean(entry.trim())
5573
5976
  ) : [];
5574
- const rawSteps = isRecord5(value.stepsById) ? value.stepsById : {};
5977
+ const rawSteps = isRecord6(value.stepsById) ? value.stepsById : {};
5575
5978
  const stepsById = {};
5576
5979
  for (const [stepId, rawStep] of Object.entries(rawSteps)) {
5577
- if (!stepId.trim() || !isRecord5(rawStep)) continue;
5980
+ if (!stepId.trim() || !isRecord6(rawStep)) continue;
5578
5981
  const rawStatus = normalizeStepStatus(rawStep.status);
5579
5982
  if (!rawStatus) continue;
5580
5983
  const completedAt = finiteNumber(rawStep.completedAt);
5581
5984
  const status = rawStatus === "running" && completedAt !== null ? "completed" : rawStatus;
5582
- const rawProgress = isRecord5(rawStep.progress) ? rawStep.progress : null;
5985
+ const rawProgress = isRecord6(rawStep.progress) ? rawStep.progress : null;
5583
5986
  stepsById[stepId] = {
5584
5987
  stepId,
5585
5988
  label: optionalString(rawStep.label),
@@ -5595,10 +5998,10 @@ function normalizePlayRunLedgerSnapshot(value, fallback) {
5595
5998
  progress: rawProgress ? normalizeStepProgress(rawProgress) : null
5596
5999
  };
5597
6000
  }
5598
- const rawDatasets = isRecord5(value.datasetsById) ? value.datasetsById : {};
6001
+ const rawDatasets = isRecord6(value.datasetsById) ? value.datasetsById : {};
5599
6002
  const datasetsById = {};
5600
6003
  for (const [datasetId, rawDataset] of Object.entries(rawDatasets)) {
5601
- if (!datasetId.trim() || !isRecord5(rawDataset)) continue;
6004
+ if (!datasetId.trim() || !isRecord6(rawDataset)) continue;
5602
6005
  const phase = rawDataset.phase === "available" || rawDataset.phase === "failed" ? rawDataset.phase : "registered";
5603
6006
  const datasetBornFrom = normalizeDatasetBornFrom(rawDataset.bornFrom);
5604
6007
  datasetsById[datasetId] = {
@@ -5621,7 +6024,7 @@ function normalizePlayRunLedgerSnapshot(value, fallback) {
5621
6024
  updatedAt: finiteNumber(rawDataset.updatedAt) ?? 0
5622
6025
  };
5623
6026
  }
5624
- const rawActivities = isRecord5(value.activitiesById) ? value.activitiesById : {};
6027
+ const rawActivities = isRecord6(value.activitiesById) ? value.activitiesById : {};
5625
6028
  const activitiesById = {};
5626
6029
  for (const [activityId, rawActivity] of Object.entries(rawActivities)) {
5627
6030
  if (activityId.trim() && isPlayActivityObservation(rawActivity) && rawActivity.activityId === activityId) {
@@ -5911,18 +6314,18 @@ function normalizePlayRunLiveStatus(value) {
5911
6314
  function isTerminalPlayRunLiveStatus(status) {
5912
6315
  return isTerminalPlayRunLifecycleStatus(status);
5913
6316
  }
5914
- function isRecord6(value) {
6317
+ function isRecord7(value) {
5915
6318
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
5916
6319
  }
5917
6320
  function finiteNumber2(value) {
5918
6321
  return typeof value === "number" && Number.isFinite(value) ? value : null;
5919
6322
  }
5920
6323
  function extractTerminalRunLogTail(result) {
5921
- if (!isRecord6(result) || !isRecord6(result._metadata)) {
6324
+ if (!isRecord7(result) || !isRecord7(result._metadata)) {
5922
6325
  return null;
5923
6326
  }
5924
6327
  const runLogTail = result._metadata.runLogTail;
5925
- if (!isRecord6(runLogTail) || !Array.isArray(runLogTail.tail)) {
6328
+ if (!isRecord7(runLogTail) || !Array.isArray(runLogTail.tail)) {
5926
6329
  return null;
5927
6330
  }
5928
6331
  const logTail = runLogTail.tail.filter(
@@ -6582,80 +6985,6 @@ function isStopAllPlayRunsDryRunResult(result) {
6582
6985
  return "dryRun" in result && result.dryRun === true;
6583
6986
  }
6584
6987
 
6585
- // ../integration-contracts/theirstack/execution-policy.ts
6586
- var THEIRSTACK_SLOW_JOB_SEARCH_PROVIDER_TIMEOUT_MS = 135e3;
6587
- var THEIRSTACK_SLOW_JOB_SEARCH_CLIENT_TIMEOUT_MS = 6e4 + THEIRSTACK_SLOW_JOB_SEARCH_PROVIDER_TIMEOUT_MS + 15e3;
6588
- var THEIRSTACK_COMPANY_SEARCH_CLIENT_TIMEOUT_MS = 21e4;
6589
- var LONG_JOB_SEARCH_WINDOW_MS = 365 * 24 * 60 * 60 * 1e3;
6590
- var DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
6591
- function parseDateOnly(value) {
6592
- if (typeof value !== "string" || !DATE_ONLY_PATTERN.test(value)) {
6593
- return null;
6594
- }
6595
- const timestamp = Date.parse(`${value}T00:00:00.000Z`);
6596
- if (!Number.isFinite(timestamp)) {
6597
- return null;
6598
- }
6599
- return new Date(timestamp).toISOString().slice(0, 10) === value ? timestamp : null;
6600
- }
6601
- function usesLongExplicitDateWindow(payload) {
6602
- const postedAtGte = parseDateOnly(payload.posted_at_gte);
6603
- const postedAtLte = parseDateOnly(payload.posted_at_lte);
6604
- if (postedAtGte !== null && postedAtLte !== null) {
6605
- return postedAtLte - postedAtGte >= LONG_JOB_SEARCH_WINDOW_MS;
6606
- }
6607
- if (postedAtGte !== null) {
6608
- return Date.now() - postedAtGte >= LONG_JOB_SEARCH_WINDOW_MS;
6609
- }
6610
- return postedAtLte !== null && payload.posted_at_gte == null;
6611
- }
6612
- function parseMaxAgeDays(value) {
6613
- if (typeof value === "number") {
6614
- return Number.isFinite(value) ? value : null;
6615
- }
6616
- if (typeof value !== "string" || !/^-?\d+$/.test(value.trim())) {
6617
- return null;
6618
- }
6619
- const parsed = Number(value.trim());
6620
- return Number.isSafeInteger(parsed) ? parsed : null;
6621
- }
6622
- function usesExtendedTheirstackJobSearchBudget(endpointId, payload) {
6623
- if (endpointId !== "theirstack_job_search") {
6624
- return false;
6625
- }
6626
- if (payload.include_total_results === true) {
6627
- return true;
6628
- }
6629
- const maxAgeDays = parseMaxAgeDays(payload.posted_at_max_age_days);
6630
- return maxAgeDays !== null && maxAgeDays >= 365 ? true : usesLongExplicitDateWindow(payload);
6631
- }
6632
- function resolveTheirstackClientTimeoutMs(endpointId, payload) {
6633
- if (endpointId === "theirstack_company_search") {
6634
- return THEIRSTACK_COMPANY_SEARCH_CLIENT_TIMEOUT_MS;
6635
- }
6636
- return usesExtendedTheirstackJobSearchBudget(endpointId, payload) ? THEIRSTACK_SLOW_JOB_SEARCH_CLIENT_TIMEOUT_MS : null;
6637
- }
6638
-
6639
- // ../integration-contracts/waterfall/execution-policy.ts
6640
- var WATERFALL_PROSPECTOR_CLIENT_TIMEOUT_MS = 18e4;
6641
- var WATERFALL_PROSPECTOR_LAUNCHER_TOOL_IDS = /* @__PURE__ */ new Set([
6642
- "prospector",
6643
- "deepline_native_prospector"
6644
- ]);
6645
- function resolveWaterfallClientTimeoutMs(toolId) {
6646
- return WATERFALL_PROSPECTOR_LAUNCHER_TOOL_IDS.has(toolId.trim().toLowerCase()) ? WATERFALL_PROSPECTOR_CLIENT_TIMEOUT_MS : null;
6647
- }
6648
-
6649
- // ../integration-contracts/bettercontact/execution-policy.ts
6650
- var BETTERCONTACT_LAUNCHER_CLIENT_TIMEOUT_MS = 12e4;
6651
- var BETTERCONTACT_LAUNCHER_TOOL_IDS = /* @__PURE__ */ new Set([
6652
- "bettercontact_enrich",
6653
- "bettercontact_bulk_enrich"
6654
- ]);
6655
- function usesExtendedBetterContactLauncherBudget(toolId) {
6656
- return BETTERCONTACT_LAUNCHER_TOOL_IDS.has(toolId.trim().toLowerCase());
6657
- }
6658
-
6659
6988
  // ../plays/artifact-types.ts
6660
6989
  var PLAY_ARTIFACT_KINDS = {
6661
6990
  cjsNode20: "cjs_node20"
@@ -6729,27 +7058,6 @@ function normalizePlayRuntimeEnvironment(value) {
6729
7058
  return typeof value === "string" && PLAY_RUNTIME_ENVIRONMENTS.includes(value) ? value : null;
6730
7059
  }
6731
7060
 
6732
- // ../plays/tool-response-contract.ts
6733
- var RAW_V2_TOOL_RESPONSE_CONTRACT = "raw-v2";
6734
- function legacyRawFromToolResponseRawV2(rawV2, view, responseMeta) {
6735
- const legacyRaw = view === "data" && rawV2 && typeof rawV2 === "object" && !Array.isArray(rawV2) ? rawV2.data : rawV2;
6736
- const deeplineBilling = responseMeta?.deepline_billing;
6737
- if (view === "rawV2" && deeplineBilling !== void 0 && legacyRaw && typeof legacyRaw === "object" && !Array.isArray(legacyRaw)) {
6738
- return {
6739
- ...legacyRaw,
6740
- deepline_billing: deeplineBilling
6741
- };
6742
- }
6743
- return legacyRaw;
6744
- }
6745
- function providerMetaFromToolResponseRawV2(rawV2, view) {
6746
- if (view !== "data" || !rawV2 || typeof rawV2 !== "object" || Array.isArray(rawV2)) {
6747
- return void 0;
6748
- }
6749
- const meta = rawV2.meta;
6750
- return meta && typeof meta === "object" && !Array.isArray(meta) ? meta : void 0;
6751
- }
6752
-
6753
7061
  // src/client.ts
6754
7062
  var MAX_NOTIFICATION_GROUP_CREATE_TARGETS = 50;
6755
7063
  function parseNotificationGroupTarget(value) {
@@ -6788,69 +7096,14 @@ function notificationObjectKey(kind) {
6788
7096
  return `${kind}.${globalThis.crypto.randomUUID()}`;
6789
7097
  }
6790
7098
  var TERMINAL_PLAY_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
6791
- var INCLUDE_TOOL_METADATA_HEADER = "x-deepline-include-tool-metadata";
6792
- var EXECUTE_RESPONSE_CONTRACT_HEADER = "x-deepline-execute-response-contract";
6793
- var EXECUTE_RESPONSE_INTENT_HEADER = "x-deepline-execute-response-intent";
6794
7099
  var MONITOR_NON_RETRYABLE_MUTATION_OPTIONS = {
6795
7100
  maxRetries: 0,
6796
7101
  exactUrlOnly: true
6797
7102
  };
6798
- var RAW_V2_EXECUTE_RESPONSE_CONTRACT = RAW_V2_TOOL_RESPONSE_CONTRACT;
6799
- var DEFAULT_EXECUTION_RECOVERY_TIMEOUT_MS = 15 * 60 * 1e3;
6800
- function validateExecutionIdempotencyKey(key) {
6801
- if (typeof key !== "string" || key.length < 1 || key.length > 200 || !/^[A-Za-z0-9._:-]+$/.test(key)) {
6802
- throw new DeeplineError(
6803
- "Execution idempotency keys must be 1\u2013200 ASCII letters, digits, dots, underscores, colons, or hyphens.",
6804
- void 0,
6805
- "IDEMPOTENCY_KEY_INVALID"
6806
- );
6807
- }
6808
- }
6809
- function isExecutionInProgressResponse(value) {
6810
- return typeof value === "object" && value !== null && typeof value.executionRecovery === "object" && value.executionRecovery.state === "running";
6811
- }
6812
- function getExecutionRecoveryState(value) {
6813
- if (typeof value !== "object" || value === null || typeof value.executionRecovery !== "object") {
6814
- return null;
6815
- }
6816
- const state = value.executionRecovery.state;
6817
- return state === "running" || state === "completed" || state === "outcome_unknown" ? state : null;
6818
- }
6819
- function isRecoverableExecutionAttemptError(error) {
6820
- if (error instanceof ToolExecutionError) {
6821
- return error.code === "EXECUTION_IN_PROGRESS" || error.origin === "deepline" && error.category === "network" && error.networkScope === "client_to_deepline";
6822
- }
6823
- return error instanceof DeeplineError && (error.code === "EXECUTION_IN_PROGRESS" || error.code?.startsWith("NETWORK_") === true && error.statusCode === void 0);
6824
- }
6825
- function isRecoverableExecutionLookupError(error) {
6826
- if (isRecoverableExecutionAttemptError(error)) return true;
6827
- return error instanceof DeeplineError && (error.statusCode === 429 || error.statusCode !== void 0 && error.statusCode >= 500);
6828
- }
6829
- function timeoutWithinRecoveryBudget(requestTimeoutMs, defaultRequestTimeoutMs, remainingMs) {
6830
- return Math.min(requestTimeoutMs ?? defaultRequestTimeoutMs, remainingMs);
6831
- }
6832
- function executionRecoveryError(input2) {
6833
- return new ToolExecutionError(input2.message, {
6834
- toolId: input2.toolId,
6835
- provider: null,
6836
- operation: input2.toolId,
6837
- code: input2.code,
6838
- origin: "deepline",
6839
- category: input2.code === "EXECUTION_OUTCOME_UNKNOWN" ? "unknown" : "conflict",
6840
- retryable: input2.code !== "EXECUTION_OUTCOME_UNKNOWN",
6841
- statusCode: null,
6842
- requestId: null,
6843
- retryAfterMs: null,
6844
- networkKind: null,
6845
- networkScope: null,
6846
- publicDetails: { idempotencyKey: input2.idempotencyKey }
6847
- });
6848
- }
6849
7103
  var COMPILE_MANIFEST_RETRY_DELAYS_MS = [250, 1e3];
6850
7104
  var REGISTER_PLAY_ARTIFACTS_COMPILE_CONCURRENCY = 3;
6851
7105
  var REGISTER_PLAY_ARTIFACTS_MAX_BATCH_COUNT = 3;
6852
7106
  var REGISTER_PLAY_ARTIFACTS_MAX_BATCH_BYTES = 25e5;
6853
- var DEEPLINEAGENT_EXECUTE_TIMEOUT_MS = 15 * 60 * 1e3;
6854
7107
  function normalizePlayRunIntegrationMode(value) {
6855
7108
  if (value === "live" || value === "eval_stub" || value === "fixture") {
6856
7109
  return value;
@@ -7041,28 +7294,6 @@ function chunkRegisterPlayArtifacts(artifacts) {
7041
7294
  }
7042
7295
  return chunks;
7043
7296
  }
7044
- var APIFY_SYNC_DEFAULT_TIMEOUT_MS = 3e5;
7045
- var APIFY_SYNC_RESPONSE_GRACE_MS = 9e4;
7046
- function resolveToolExecuteTimeoutMs(toolId, input2) {
7047
- const normalized = toolId.trim().toLowerCase();
7048
- if (normalized === "apify_run_actor_sync") {
7049
- const requestedTimeoutMs = input2.timeoutMs ?? APIFY_SYNC_DEFAULT_TIMEOUT_MS;
7050
- if (typeof requestedTimeoutMs === "number" && Number.isFinite(requestedTimeoutMs) && requestedTimeoutMs > 0) {
7051
- return Math.floor(requestedTimeoutMs) + APIFY_SYNC_RESPONSE_GRACE_MS;
7052
- }
7053
- }
7054
- const theirstackTimeoutMs = resolveTheirstackClientTimeoutMs(
7055
- normalized,
7056
- input2
7057
- );
7058
- if (theirstackTimeoutMs !== null) return theirstackTimeoutMs;
7059
- const waterfallTimeoutMs = resolveWaterfallClientTimeoutMs(normalized);
7060
- if (waterfallTimeoutMs !== null) return waterfallTimeoutMs;
7061
- if (usesExtendedBetterContactLauncherBudget(normalized)) {
7062
- return BETTERCONTACT_LAUNCHER_CLIENT_TIMEOUT_MS;
7063
- }
7064
- return normalized === "deeplineagent" || normalized === "deeplineagent_deeplineagent" || normalized === "ai_inference" || normalized === "deeplineagent_ai_inference" || normalized === "ai_evaluate" || normalized === "deeplineagent_ai_evaluate" || normalized === "aiinference" ? DEEPLINEAGENT_EXECUTE_TIMEOUT_MS : void 0;
7065
- }
7066
7297
  var RUNS_FAILED_LOG_LIMIT = 20;
7067
7298
  var RUN_LOGS_PAGE_LIMIT = 1e3;
7068
7299
  function requireTargetBillingIdempotencyKey(value) {
@@ -7076,53 +7307,9 @@ function requireTargetBillingIdempotencyKey(value) {
7076
7307
  }
7077
7308
  return normalized;
7078
7309
  }
7079
- function isRecord7(value) {
7310
+ function isRecord8(value) {
7080
7311
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
7081
7312
  }
7082
- function materializeToolExecutionResponse(response) {
7083
- const toolResponse = response.toolResponse;
7084
- if (!toolResponse && isRecord7(response.result)) {
7085
- const legacyResult = response.result;
7086
- if (Object.prototype.hasOwnProperty.call(legacyResult, "data")) {
7087
- const legacyMeta = isRecord7(legacyResult.meta) ? legacyResult.meta : void 0;
7088
- return {
7089
- ...response,
7090
- toolResponse: {
7091
- raw: legacyResult.data,
7092
- ...legacyMeta ? { meta: legacyMeta } : {}
7093
- }
7094
- };
7095
- }
7096
- }
7097
- if (!toolResponse || Object.prototype.hasOwnProperty.call(toolResponse, "raw")) {
7098
- return response;
7099
- }
7100
- const rawV2 = toolResponse.rawV2;
7101
- const view = toolResponse.view;
7102
- const providerMeta = providerMetaFromToolResponseRawV2(
7103
- rawV2,
7104
- view ?? "rawV2"
7105
- );
7106
- const responseMeta = isRecord7(toolResponse.responseMeta) ? toolResponse.responseMeta : void 0;
7107
- return {
7108
- ...response,
7109
- toolResponse: {
7110
- ...toolResponse,
7111
- raw: legacyRawFromToolResponseRawV2(
7112
- rawV2,
7113
- view ?? "rawV2",
7114
- responseMeta
7115
- ),
7116
- ...toolResponse.meta || providerMeta || responseMeta ? {
7117
- meta: {
7118
- ...toolResponse.meta ?? {},
7119
- ...providerMeta ?? {},
7120
- ...responseMeta ?? {}
7121
- }
7122
- } : {}
7123
- }
7124
- };
7125
- }
7126
7313
  function isPrebuiltPlayDescription(play) {
7127
7314
  return play.origin === "prebuilt" || play.ownerType === "deepline";
7128
7315
  }
@@ -7152,10 +7339,10 @@ function normalizePlayStatus(raw) {
7152
7339
  return {
7153
7340
  ...raw,
7154
7341
  runId,
7155
- ...isRecord7(legacyOverview) ? {
7342
+ ...isRecord8(legacyOverview) ? {
7156
7343
  overview: legacyOverview
7157
7344
  } : {},
7158
- ...isRecord7(runStatus) ? { runStatus } : {},
7345
+ ...isRecord8(runStatus) ? { runStatus } : {},
7159
7346
  ...runPackage ? {
7160
7347
  package: runPackage,
7161
7348
  outputs: runPackage.outputs
@@ -7294,7 +7481,7 @@ function updatePlayLiveStatusState(state, event) {
7294
7481
  }
7295
7482
  const runId = typeof payload.runId === "string" && payload.runId ? payload.runId : isPlayRunPackage(payload) ? payload.run.id : state.runId;
7296
7483
  const status = normalizeLiveStatus(payload.status) ?? (isPlayRunPackage(payload) ? normalizeLiveStatus(payload.run.status) : null) ?? state.status;
7297
- const progressPayload = isRecord7(payload.progress) ? payload.progress : {};
7484
+ const progressPayload = isRecord8(payload.progress) ? payload.progress : {};
7298
7485
  if (event.type === "play.run.final_status" && state.logs.length === 0 && state.lastLogSeq === 0) {
7299
7486
  const payloadLogs = readStringArray(payload.logs);
7300
7487
  const progressLogs = readStringArray(progressPayload.logs);
@@ -7343,6 +7530,7 @@ function playRunResultFromStatus(status, startedAt, fallbackRunId) {
7343
7530
  }
7344
7531
  var DeeplineClient = class _DeeplineClient {
7345
7532
  http;
7533
+ toolCalls;
7346
7534
  config;
7347
7535
  /** Canonical run lifecycle namespace backed by `/api/v2/runs`. */
7348
7536
  runs;
@@ -7366,6 +7554,7 @@ var DeeplineClient = class _DeeplineClient {
7366
7554
  constructor(options) {
7367
7555
  this.config = resolveConfig(options);
7368
7556
  this.http = new HttpClient(this.config);
7557
+ this.toolCalls = new ToolCalls(this.http, this.config.timeout);
7369
7558
  this.runs = {
7370
7559
  get: (runId, options2) => this.getRunStatus(runId, options2),
7371
7560
  status: (runId) => this.getRunLifecycleStatus(runId),
@@ -7493,9 +7682,9 @@ var DeeplineClient = class _DeeplineClient {
7493
7682
  return fields2.length > 0 ? { fields: fields2 } : schema;
7494
7683
  }
7495
7684
  schemaMetadata(schema, key) {
7496
- if (!isRecord7(schema)) return null;
7685
+ if (!isRecord8(schema)) return null;
7497
7686
  const value = schema[key];
7498
- return isRecord7(value) ? value : null;
7687
+ return isRecord8(value) ? value : null;
7499
7688
  }
7500
7689
  playRunCommand(play, options) {
7501
7690
  const target = play.reference || play.name;
@@ -7550,7 +7739,7 @@ var DeeplineClient = class _DeeplineClient {
7550
7739
  aliases,
7551
7740
  inputSchema: options?.compact ? this.compactSchema(play.inputSchema) : play.inputSchema ?? null,
7552
7741
  outputSchema: options?.compact ? this.compactSchema(play.outputSchema) : play.outputSchema ?? null,
7553
- staticPipeline: isRecord7(play.staticPipeline) ? play.staticPipeline : isRecord7(play.currentRevision?.staticPipeline) ? play.currentRevision.staticPipeline : isRecord7(play.liveRevision?.staticPipeline) ? play.liveRevision.staticPipeline : null,
7742
+ staticPipeline: isRecord8(play.staticPipeline) ? play.staticPipeline : isRecord8(play.currentRevision?.staticPipeline) ? play.currentRevision.staticPipeline : isRecord8(play.liveRevision?.staticPipeline) ? play.liveRevision.staticPipeline : null,
7554
7743
  ...csvInput ? { csvInput } : {},
7555
7744
  ...rowOutputSchema ? { rowOutputSchema } : {},
7556
7745
  runCommand: runCommand2,
@@ -7770,183 +7959,11 @@ var DeeplineClient = class _DeeplineClient {
7770
7959
  * Deepline execution envelope.
7771
7960
  */
7772
7961
  async executeTool(toolId, input2, options) {
7773
- const inputSnapshot = JSON.parse(JSON.stringify(input2));
7774
- const metadataSnapshot = options?.metadata ? JSON.parse(JSON.stringify(options.metadata)) : void 0;
7775
- const idempotencyKey = options?.idempotencyKey ?? (options?.recover ? crypto.randomUUID() : void 0);
7776
- if (idempotencyKey !== void 0) {
7777
- validateExecutionIdempotencyKey(idempotencyKey);
7778
- if (options?.recoveryTimeoutMs !== void 0 && (!Number.isFinite(options.recoveryTimeoutMs) || options.recoveryTimeoutMs < 0)) {
7779
- throw new DeeplineError(
7780
- "recoveryTimeoutMs must be a finite, non-negative number.",
7781
- void 0,
7782
- "IDEMPOTENCY_KEY_INVALID"
7783
- );
7784
- }
7785
- await options?.onExecution?.({ idempotencyKey });
7786
- const timeoutMs2 = options?.timeout ?? resolveToolExecuteTimeoutMs(toolId, inputSnapshot);
7787
- await this.lookupExecutionByKey(idempotencyKey, timeoutMs2);
7788
- }
7789
- const timeoutMs = options?.timeout ?? resolveToolExecuteTimeoutMs(toolId, inputSnapshot);
7790
- const isApifySync = toolId.trim().toLowerCase() === "apify_run_actor_sync";
7791
- const headers = {
7792
- [EXECUTE_RESPONSE_CONTRACT_HEADER]: RAW_V2_EXECUTE_RESPONSE_CONTRACT,
7793
- ...isApifySync ? { "X-Deepline-Apify-Sync-Response-Budget": "extended-v1" } : {},
7794
- [TOOL_EXECUTION_ERROR_SCHEMA_HEADER]: String(
7795
- TOOL_EXECUTION_ERROR_SCHEMA_VERSION
7796
- ),
7797
- ...options?.includeToolMetadata ? { [INCLUDE_TOOL_METADATA_HEADER]: "true" } : {},
7798
- [EXECUTE_RESPONSE_INTENT_HEADER]: options?.responseIntent ?? "raw",
7799
- ...idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {},
7800
- ...options?.searchRef ? { "x-deepline-search-ref": options.searchRef } : {}
7801
- };
7802
- const request = (requestTimeoutMs) => this.http.post(
7803
- `/api/v2/integrations/${encodeURIComponent(toolId)}/execute`,
7804
- {
7805
- payload: inputSnapshot,
7806
- ...metadataSnapshot ? { metadata: metadataSnapshot } : {}
7807
- },
7808
- headers,
7809
- {
7810
- timeout: requestTimeoutMs,
7811
- maxRetries: idempotencyKey ? 0 : options?.maxRetries ?? 0,
7812
- retryApiErrors: options?.retryApiErrors === true,
7813
- exactUrlOnly: true,
7814
- toolId,
7815
- idempotencyKey
7816
- }
7817
- );
7818
- let response;
7819
- let recoveryDeadline = null;
7820
- const recoveryTimeoutMs = options?.recoveryTimeoutMs ?? DEFAULT_EXECUTION_RECOVERY_TIMEOUT_MS;
7821
- let retryDelayMs = 1e3;
7822
- const recoveryTimeoutError = () => executionRecoveryError({
7823
- toolId,
7824
- idempotencyKey,
7825
- code: "EXECUTION_RECOVERY_TIMEOUT",
7826
- message: `Execution recovery for ${idempotencyKey} did not finish before the recovery timeout. Inspect client.executions.getByKey() and resume with the same idempotency key.`
7827
- });
7828
- const waitForRecoveryRetry = async (deadline) => {
7829
- const remainingMs = deadline - Date.now();
7830
- if (remainingMs <= 0) throw recoveryTimeoutError();
7831
- await new Promise(
7832
- (resolve22) => setTimeout(resolve22, Math.min(retryDelayMs, remainingMs))
7833
- );
7834
- retryDelayMs = Math.min(retryDelayMs * 2, 5e3);
7835
- };
7836
- const lookupDuringRecovery = async () => {
7837
- while (true) {
7838
- const remainingMs = recoveryDeadline - Date.now();
7839
- if (remainingMs <= 0) throw recoveryTimeoutError();
7840
- try {
7841
- return await this.lookupExecutionByKey(
7842
- idempotencyKey,
7843
- timeoutWithinRecoveryBudget(
7844
- timeoutMs,
7845
- this.config.timeout,
7846
- remainingMs
7847
- )
7848
- );
7849
- } catch (error) {
7850
- if (!isRecoverableExecutionLookupError(error)) throw error;
7851
- await waitForRecoveryRetry(recoveryDeadline);
7852
- }
7853
- }
7854
- };
7855
- while (true) {
7856
- const remainingMs = recoveryDeadline === null ? null : recoveryDeadline - Date.now();
7857
- if (remainingMs !== null && remainingMs <= 0) {
7858
- throw recoveryTimeoutError();
7859
- }
7860
- try {
7861
- response = await request(
7862
- remainingMs === null ? timeoutMs : timeoutWithinRecoveryBudget(
7863
- timeoutMs,
7864
- this.config.timeout,
7865
- remainingMs
7866
- )
7867
- );
7868
- if (getExecutionRecoveryState(response) === "outcome_unknown") {
7869
- if (!idempotencyKey) break;
7870
- throw executionRecoveryError({
7871
- toolId,
7872
- idempotencyKey,
7873
- code: "EXECUTION_OUTCOME_UNKNOWN",
7874
- message: `The outcome of execution ${idempotencyKey} is unknown. Do not retry with a new key; inspect client.executions.getByKey().`
7875
- });
7876
- }
7877
- if (!idempotencyKey || !isExecutionInProgressResponse(response)) {
7878
- break;
7879
- }
7880
- if (recoveryDeadline === null) {
7881
- recoveryDeadline = Date.now() + recoveryTimeoutMs;
7882
- }
7883
- } catch (error) {
7884
- if (idempotencyKey && error instanceof DeeplineError && error.code === "EXECUTION_OUTCOME_UNKNOWN") {
7885
- throw executionRecoveryError({
7886
- toolId,
7887
- idempotencyKey,
7888
- code: "EXECUTION_OUTCOME_UNKNOWN",
7889
- message: error.message
7890
- });
7891
- }
7892
- if (!idempotencyKey || !isRecoverableExecutionAttemptError(error)) {
7893
- throw error;
7894
- }
7895
- if (recoveryDeadline === null) {
7896
- recoveryDeadline = Date.now() + recoveryTimeoutMs;
7897
- }
7898
- }
7899
- await waitForRecoveryRetry(recoveryDeadline);
7900
- const recovered = await lookupDuringRecovery();
7901
- if (getExecutionRecoveryState(recovered) === "outcome_unknown") {
7902
- throw executionRecoveryError({
7903
- toolId,
7904
- idempotencyKey,
7905
- code: "EXECUTION_OUTCOME_UNKNOWN",
7906
- message: `The outcome of execution ${idempotencyKey} is unknown. Do not retry with a new key; inspect client.executions.getByKey().`
7907
- });
7908
- }
7909
- }
7910
- const materialized = materializeToolExecutionResponse(response);
7911
- return idempotencyKey ? { ...materialized, idempotencyKey } : materialized;
7962
+ return this.toolCalls.call(toolId, input2, options);
7912
7963
  }
7913
7964
  /** Read the durable state of a keyed tool execution. */
7914
7965
  async getExecutionByKey(idempotencyKey) {
7915
- validateExecutionIdempotencyKey(idempotencyKey);
7916
- const result = await this.lookupExecutionByKey(idempotencyKey);
7917
- if (!result) {
7918
- throw new DeeplineError(
7919
- `No execution exists for idempotency key ${idempotencyKey}.`,
7920
- 404,
7921
- "EXECUTION_NOT_FOUND"
7922
- );
7923
- }
7924
- return result;
7925
- }
7926
- async lookupExecutionByKey(idempotencyKey, timeoutMs) {
7927
- validateExecutionIdempotencyKey(idempotencyKey);
7928
- let supported = false;
7929
- const result = await this.http.get(
7930
- `/api/v2/executions/by-key/${encodeURIComponent(idempotencyKey)}`,
7931
- {
7932
- exactUrlOnly: true,
7933
- maxRetries: 0,
7934
- timeout: timeoutMs,
7935
- idempotencyKey,
7936
- allowNotFound: true,
7937
- onResponse: (response) => {
7938
- supported = response.headers.get("X-Deepline-Idempotency-Supported") === "true";
7939
- }
7940
- }
7941
- );
7942
- if (!supported) {
7943
- throw new DeeplineError(
7944
- "This Deepline server does not support recoverable tool executions; no tool was dispatched.",
7945
- 422,
7946
- "IDEMPOTENCY_NOT_SUPPORTED"
7947
- );
7948
- }
7949
- return result;
7966
+ return this.toolCalls.getByKey(idempotencyKey);
7950
7967
  }
7951
7968
  /** Public recovery namespace. */
7952
7969
  get executions() {
@@ -8754,10 +8771,10 @@ var DeeplineClient = class _DeeplineClient {
8754
8771
  const responseRunStatus = isPlayRunPackage(response) ? response.runStatus : isPlayRunPackage(response.package) ? response.package.runStatus : response.runStatus;
8755
8772
  const responseOverview = isPlayRunPackage(response) ? response.overview : isPlayRunPackage(response.package) ? response.package.overview : response.overview;
8756
8773
  const status = normalizePlayStatus(response);
8757
- if (isRecord7(responseRunStatus)) {
8774
+ if (isRecord8(responseRunStatus)) {
8758
8775
  status.runStatus = responseRunStatus;
8759
8776
  }
8760
- if (isRecord7(responseOverview)) {
8777
+ if (isRecord8(responseOverview)) {
8761
8778
  status.overview = responseOverview;
8762
8779
  }
8763
8780
  if (options?.failedLogs !== true || status.status !== "failed") {
@@ -14582,24 +14599,24 @@ function sanitizeCsvProjectionInfo(input2) {
14582
14599
  const rows = input2.rows.map(stripCsvProjectionFields);
14583
14600
  return { rows, columns };
14584
14601
  }
14585
- function isRecord8(value) {
14602
+ function isRecord9(value) {
14586
14603
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
14587
14604
  }
14588
14605
  function isSerializedDataset(value) {
14589
- return isRecord8(value) && value.kind === "dataset" && typeof value.count === "number" && (Array.isArray(value.preview) || typeof value.tableNamespace === "string");
14606
+ return isRecord9(value) && value.kind === "dataset" && typeof value.count === "number" && (Array.isArray(value.preview) || typeof value.tableNamespace === "string");
14590
14607
  }
14591
14608
  function isPackagedDatasetOutput(value) {
14592
- return isRecord8(value) && value.kind === "dataset" && isRecord8(value.preview) && Array.isArray(value.preview.rows);
14609
+ return isRecord9(value) && value.kind === "dataset" && isRecord9(value.preview) && Array.isArray(value.preview.rows);
14593
14610
  }
14594
14611
  function hasCurrentTableExport(value) {
14595
- if (!isRecord8(value) || !isRecord8(value.actions)) return false;
14612
+ if (!isRecord9(value) || !isRecord9(value.actions)) return false;
14596
14613
  const exportCsv = value.actions.exportCsv;
14597
- return isRecord8(exportCsv) && isRecord8(exportCsv.scope) && exportCsv.scope.kind === "database" && exportCsv.scope.mutability === "current";
14614
+ return isRecord9(exportCsv) && isRecord9(exportCsv.scope) && exportCsv.scope.kind === "database" && exportCsv.scope.mutability === "current";
14598
14615
  }
14599
14616
  function currentTableQueryCommand(value) {
14600
- if (!isRecord8(value) || !isRecord8(value.actions)) return void 0;
14617
+ if (!isRecord9(value) || !isRecord9(value.actions)) return void 0;
14601
14618
  const query = value.actions.queryCurrentTable;
14602
- const command = isRecord8(query) ? query.command : void 0;
14619
+ const command = isRecord9(query) ? query.command : void 0;
14603
14620
  return typeof command === "string" && command.trim() ? command.trim() : void 0;
14604
14621
  }
14605
14622
  function recoveredReturnPaths(value) {
@@ -14618,7 +14635,7 @@ function pathParts(path) {
14618
14635
  function valueAtPath(root, path) {
14619
14636
  let cursor = root;
14620
14637
  for (const part of pathParts(path)) {
14621
- if (!isRecord8(cursor)) {
14638
+ if (!isRecord9(cursor)) {
14622
14639
  return void 0;
14623
14640
  }
14624
14641
  cursor = cursor[part];
@@ -14626,17 +14643,17 @@ function valueAtPath(root, path) {
14626
14643
  return cursor;
14627
14644
  }
14628
14645
  function totalRowsForDataset(result, datasetPath) {
14629
- const metadata = isRecord8(result._metadata) ? result._metadata : null;
14646
+ const metadata = isRecord9(result._metadata) ? result._metadata : null;
14630
14647
  const parentPath = datasetPath.split(".").slice(0, -1).join(".");
14631
14648
  const parent = parentPath ? valueAtPath({ result }, parentPath) : result;
14632
- return metadata?.totalRows ?? metadata?.rowCount ?? metadata?.count ?? (isRecord8(parent) ? parent.totalRows ?? parent.rowCount ?? parent.count : void 0) ?? result.totalRows ?? result.rowCount ?? result.count;
14649
+ return metadata?.totalRows ?? metadata?.rowCount ?? metadata?.count ?? (isRecord9(parent) ? parent.totalRows ?? parent.rowCount ?? parent.count : void 0) ?? result.totalRows ?? result.rowCount ?? result.count;
14633
14650
  }
14634
14651
  function rowArray(value) {
14635
14652
  if (!Array.isArray(value)) {
14636
14653
  return null;
14637
14654
  }
14638
14655
  const rows = value.filter(
14639
- (row) => isRecord8(row)
14656
+ (row) => isRecord9(row)
14640
14657
  );
14641
14658
  return rows.length === value.length ? rows : null;
14642
14659
  }
@@ -14660,7 +14677,7 @@ function inferColumns(rows) {
14660
14677
  return columns;
14661
14678
  }
14662
14679
  function columnsFromDatasetSummary(summary) {
14663
- if (!isRecord8(summary) || !isRecord8(summary.columnStats)) {
14680
+ if (!isRecord9(summary) || !isRecord9(summary.columnStats)) {
14664
14681
  return [];
14665
14682
  }
14666
14683
  return Object.keys(summary.columnStats).filter((column) => column);
@@ -14717,7 +14734,7 @@ function canonicalRowsInfoFromCandidate(input2) {
14717
14734
  candidate.value.recoveredReturnPaths
14718
14735
  )
14719
14736
  } : {},
14720
- ...isRecord8(candidate.value.exportUnavailable) && (candidate.value.exportUnavailable.reason === "empty_dataset" || candidate.value.exportUnavailable.reason === "shared_table_namespace" || candidate.value.exportUnavailable.reason === "returned_dataset_not_persisted") ? {
14737
+ ...isRecord9(candidate.value.exportUnavailable) && (candidate.value.exportUnavailable.reason === "empty_dataset" || candidate.value.exportUnavailable.reason === "shared_table_namespace" || candidate.value.exportUnavailable.reason === "returned_dataset_not_persisted") ? {
14721
14738
  exportUnavailableReason: candidate.value.exportUnavailable.reason,
14722
14739
  ...typeof candidate.value.exportUnavailable.message === "string" ? {
14723
14740
  exportUnavailableMessage: candidate.value.exportUnavailable.message
@@ -14765,7 +14782,7 @@ function collectDatasetCandidates(input2) {
14765
14782
  });
14766
14783
  return;
14767
14784
  }
14768
- if (!isRecord8(input2.value)) {
14785
+ if (!isRecord9(input2.value)) {
14769
14786
  return;
14770
14787
  }
14771
14788
  for (const [key, child] of Object.entries(input2.value)) {
@@ -14782,12 +14799,12 @@ function collectDatasetCandidates(input2) {
14782
14799
  }
14783
14800
  }
14784
14801
  function collectCanonicalRowsInfos(statusOrResult) {
14785
- const root = isRecord8(statusOrResult) ? statusOrResult : null;
14786
- const result = isRecord8(root?.result) ? root.result : root;
14802
+ const root = isRecord9(statusOrResult) ? statusOrResult : null;
14803
+ const result = isRecord9(root?.result) ? root.result : root;
14787
14804
  if (!result) {
14788
14805
  return [];
14789
14806
  }
14790
- const metadata = isRecord8(result._metadata) ? result._metadata : null;
14807
+ const metadata = isRecord9(result._metadata) ? result._metadata : null;
14791
14808
  const totalFromMetadata = metadata?.totalRows ?? metadata?.rowCount ?? metadata?.count;
14792
14809
  const candidates = [
14793
14810
  {
@@ -14811,8 +14828,8 @@ function collectCanonicalRowsInfos(statusOrResult) {
14811
14828
  total: totalFromMetadata ?? result.totalRows ?? result.rowCount ?? result.count
14812
14829
  }
14813
14830
  ];
14814
- if (isRecord8(result.output)) {
14815
- const outputMetadata = isRecord8(result.output._metadata) ? result.output._metadata : null;
14831
+ if (isRecord9(result.output)) {
14832
+ const outputMetadata = isRecord9(result.output._metadata) ? result.output._metadata : null;
14816
14833
  const outputTotalFromMetadata = outputMetadata?.totalRows ?? outputMetadata?.rowCount ?? outputMetadata?.count;
14817
14834
  candidates.push(
14818
14835
  {
@@ -14839,14 +14856,14 @@ function collectCanonicalRowsInfos(statusOrResult) {
14839
14856
  }
14840
14857
  if (Array.isArray(result.steps)) {
14841
14858
  result.steps.forEach((step, index) => {
14842
- if (!isRecord8(step) || !isRecord8(step.output)) {
14859
+ if (!isRecord9(step) || !isRecord9(step.output)) {
14843
14860
  return;
14844
14861
  }
14845
14862
  const source = typeof step.output.path === "string" ? step.output.path : typeof step.id === "string" ? `steps.${step.id}.output` : `steps.${index}.output`;
14846
14863
  candidates.push({
14847
14864
  source,
14848
14865
  value: step.output,
14849
- total: step.output.rowCount ?? (isRecord8(step.output.preview) ? step.output.preview.totalRows : void 0) ?? (isRecord8(step.progress) ? step.progress.total : void 0)
14866
+ total: step.output.rowCount ?? (isRecord9(step.output.preview) ? step.output.preview.totalRows : void 0) ?? (isRecord9(step.progress) ? step.progress.total : void 0)
14850
14867
  });
14851
14868
  });
14852
14869
  }
@@ -14874,15 +14891,15 @@ function collectCanonicalRowsInfos(statusOrResult) {
14874
14891
  return infos;
14875
14892
  }
14876
14893
  function collectPackagedDatasetCandidates(statusOrResult) {
14877
- const root = isRecord8(statusOrResult) ? statusOrResult : null;
14894
+ const root = isRecord9(statusOrResult) ? statusOrResult : null;
14878
14895
  if (!root) {
14879
14896
  return [];
14880
14897
  }
14881
- const pkg = isRecord8(root.package) ? root.package : root;
14898
+ const pkg = isRecord9(root.package) ? root.package : root;
14882
14899
  const datasets = Array.isArray(pkg.datasets) ? pkg.datasets : [];
14883
14900
  const candidates = [];
14884
14901
  for (const output2 of datasets) {
14885
- if (!isRecord8(output2) || !isPackagedDatasetOutput(output2)) {
14902
+ if (!isRecord9(output2) || !isPackagedDatasetOutput(output2)) {
14886
14903
  continue;
14887
14904
  }
14888
14905
  const source = typeof output2.path === "string" && output2.path.trim() ? output2.path.trim() : null;
@@ -14892,18 +14909,18 @@ function collectPackagedDatasetCandidates(statusOrResult) {
14892
14909
  candidates.push({
14893
14910
  source,
14894
14911
  value: output2,
14895
- total: output2.rowCount ?? (isRecord8(output2.preview) ? output2.preview.totalRows : void 0)
14912
+ total: output2.rowCount ?? (isRecord9(output2.preview) ? output2.preview.totalRows : void 0)
14896
14913
  });
14897
14914
  }
14898
14915
  return candidates;
14899
14916
  }
14900
14917
  function collectPackagedStepDatasetCandidates(statusOrResult) {
14901
- const root = isRecord8(statusOrResult) ? statusOrResult : null;
14918
+ const root = isRecord9(statusOrResult) ? statusOrResult : null;
14902
14919
  if (!root) return [];
14903
- const pkg = isRecord8(root.package) ? root.package : root;
14920
+ const pkg = isRecord9(root.package) ? root.package : root;
14904
14921
  const steps = Array.isArray(pkg.steps) ? pkg.steps : [];
14905
14922
  return steps.flatMap((step) => {
14906
- if (!isRecord8(step) || !isPackagedDatasetOutput(step.output)) return [];
14923
+ if (!isRecord9(step) || !isPackagedDatasetOutput(step.output)) return [];
14907
14924
  const source = typeof step.output.path === "string" && step.output.path.trim() ? step.output.path.trim() : null;
14908
14925
  return source ? [
14909
14926
  {
@@ -14915,8 +14932,8 @@ function collectPackagedStepDatasetCandidates(statusOrResult) {
14915
14932
  });
14916
14933
  }
14917
14934
  function collectSerializedDatasetRowsInfos(statusOrResult) {
14918
- const root = isRecord8(statusOrResult) ? statusOrResult : null;
14919
- const result = isRecord8(root?.result) ? root.result : root;
14935
+ const root = isRecord9(statusOrResult) ? statusOrResult : null;
14936
+ const result = isRecord9(root?.result) ? root.result : root;
14920
14937
  const candidates = [];
14921
14938
  if (result) {
14922
14939
  collectDatasetCandidates({
@@ -14924,7 +14941,7 @@ function collectSerializedDatasetRowsInfos(statusOrResult) {
14924
14941
  path: "result",
14925
14942
  output: candidates
14926
14943
  });
14927
- if (isRecord8(result.output)) {
14944
+ if (isRecord9(result.output)) {
14928
14945
  collectDatasetCandidates({
14929
14946
  value: result.output,
14930
14947
  path: "result",
@@ -15007,13 +15024,13 @@ function summarizeSampleValue(value, depth = 0) {
15007
15024
  if (typeof parsed === "number" || typeof parsed === "boolean") return parsed;
15008
15025
  if (depth >= 3) {
15009
15026
  if (Array.isArray(parsed)) return [];
15010
- if (isRecord8(parsed)) return {};
15027
+ if (isRecord9(parsed)) return {};
15011
15028
  return compactScalar(parsed);
15012
15029
  }
15013
15030
  if (Array.isArray(parsed)) {
15014
15031
  return parsed.slice(0, 3).map((item) => summarizeSampleValue(item, depth + 1));
15015
15032
  }
15016
- if (isRecord8(parsed)) {
15033
+ if (isRecord9(parsed)) {
15017
15034
  const out = {};
15018
15035
  for (const [key, nested] of Object.entries(parsed)) {
15019
15036
  if (["__dl", "meta", "metadata"].includes(key)) {
@@ -15044,7 +15061,7 @@ function compactCell(value) {
15044
15061
  }
15045
15062
  return `[${parsed.length} items]`;
15046
15063
  }
15047
- if (isRecord8(parsed)) {
15064
+ if (isRecord9(parsed)) {
15048
15065
  for (const key of ["matched_result", "output"]) {
15049
15066
  if (parsed[key] !== null && parsed[key] !== void 0 && parsed[key] !== "") {
15050
15067
  return compactCell(parsed[key]);
@@ -16478,17 +16495,17 @@ function parsePositiveInteger2(value, flagName) {
16478
16495
  }
16479
16496
  return parsed;
16480
16497
  }
16481
- function isRecord9(value) {
16498
+ function isRecord10(value) {
16482
16499
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
16483
16500
  }
16484
16501
  function stringValue(value) {
16485
16502
  return typeof value === "string" ? value.trim() : "";
16486
16503
  }
16487
16504
  function extractionEntries(value) {
16488
- if (Array.isArray(value)) return value.filter(isRecord9);
16489
- if (!isRecord9(value)) return [];
16505
+ if (Array.isArray(value)) return value.filter(isRecord10);
16506
+ if (!isRecord10(value)) return [];
16490
16507
  return Object.entries(value).map(
16491
- ([name, entry]) => isRecord9(entry) ? { name, ...entry } : { name }
16508
+ ([name, entry]) => isRecord10(entry) ? { name, ...entry } : { name }
16492
16509
  );
16493
16510
  }
16494
16511
  var PlayBootstrapError = class extends Error {
@@ -17049,7 +17066,7 @@ function readCsvSampleRows(sample) {
17049
17066
  relax_column_count: true,
17050
17067
  trim: true
17051
17068
  });
17052
- return Array.isArray(parsedRows) ? parsedRows.filter(isRecord9) : [];
17069
+ return Array.isArray(parsedRows) ? parsedRows.filter(isRecord10) : [];
17053
17070
  }
17054
17071
  function readSourceCsvColumnSpecs(csvPath) {
17055
17072
  const sample = readCsvSample(csvPath);
@@ -17082,16 +17099,16 @@ function packagedCsvPathForPlay(csvPath) {
17082
17099
  return portablePath.startsWith(".") ? portablePath : `./${portablePath}`;
17083
17100
  }
17084
17101
  function getterNamesFromTool(tool, kind) {
17085
- const usageGuidance = isRecord9(tool?.usageGuidance) ? tool.usageGuidance : {};
17086
- const resultGuidance = isRecord9(usageGuidance.toolExecutionResult) ? usageGuidance.toolExecutionResult : isRecord9(usageGuidance.tool_execution_result) ? usageGuidance.tool_execution_result : {};
17102
+ const usageGuidance = isRecord10(tool?.usageGuidance) ? tool.usageGuidance : {};
17103
+ const resultGuidance = isRecord10(usageGuidance.toolExecutionResult) ? usageGuidance.toolExecutionResult : isRecord10(usageGuidance.tool_execution_result) ? usageGuidance.tool_execution_result : {};
17087
17104
  const key = kind === "list" ? "extractedLists" : "extractedValues";
17088
17105
  const snakeKey = kind === "list" ? "extracted_lists" : "extracted_values";
17089
17106
  return extractionEntries(resultGuidance[key] ?? resultGuidance[snakeKey]).map((entry) => stringValue(entry.name)).filter(Boolean);
17090
17107
  }
17091
17108
  function targetGettersFromTool(tool) {
17092
- const record3 = isRecord9(tool) ? tool : {};
17109
+ const record3 = isRecord10(tool) ? tool : {};
17093
17110
  const raw = record3.targetGetters ?? record3.target_getters;
17094
- if (!isRecord9(raw)) return {};
17111
+ if (!isRecord10(raw)) return {};
17095
17112
  const entries = [];
17096
17113
  for (const [target, value] of Object.entries(raw)) {
17097
17114
  const paths = Array.isArray(value) ? value.map((path) => typeof path === "string" ? path.trim() : "").filter(Boolean) : [];
@@ -17112,10 +17129,10 @@ function listRowCandidateKeysFromTool(tool) {
17112
17129
  return [...keys].sort();
17113
17130
  }
17114
17131
  function inputPropertyNames(schema) {
17115
- if (!isRecord9(schema)) return [];
17116
- if (isRecord9(schema.properties)) return Object.keys(schema.properties);
17132
+ if (!isRecord10(schema)) return [];
17133
+ if (isRecord10(schema.properties)) return Object.keys(schema.properties);
17117
17134
  if (Array.isArray(schema.fields)) {
17118
- return schema.fields.filter(isRecord9).map((field) => stringValue(field.name)).filter(Boolean);
17135
+ return schema.fields.filter(isRecord10).map((field) => stringValue(field.name)).filter(Boolean);
17119
17136
  }
17120
17137
  return [];
17121
17138
  }
@@ -17129,7 +17146,7 @@ function schemaFieldDetails(schema) {
17129
17146
  return { required, optional };
17130
17147
  }
17131
17148
  function jsonSchemaTypeExpression(schema) {
17132
- if (!isRecord9(schema)) return "unknown";
17149
+ if (!isRecord10(schema)) return "unknown";
17133
17150
  const type = schema.type;
17134
17151
  if (Array.isArray(type)) {
17135
17152
  return type.map((entry) => jsonSchemaTypeExpression({ ...schema, type: entry })).join(" | ");
@@ -17159,7 +17176,7 @@ function jsonSchemaTypeExpression(schema) {
17159
17176
  }
17160
17177
  }
17161
17178
  function objectPropertySchema(schema, property) {
17162
- return isRecord9(schema) && isRecord9(schema.properties) ? schema.properties[property] : null;
17179
+ return isRecord10(schema) && isRecord10(schema.properties) ? schema.properties[property] : null;
17163
17180
  }
17164
17181
  function playOutputHasField(schema, field) {
17165
17182
  return objectPropertySchema(schema, field) != null;
@@ -17335,14 +17352,14 @@ ${indent2.slice(2)}}`;
17335
17352
  }
17336
17353
  function requiredPlayInputFields(play) {
17337
17354
  const schema = play?.inputSchema;
17338
- if (!isRecord9(schema)) return [];
17355
+ if (!isRecord10(schema)) return [];
17339
17356
  if (Array.isArray(schema.required)) {
17340
17357
  return schema.required.filter(
17341
17358
  (value) => typeof value === "string"
17342
17359
  );
17343
17360
  }
17344
17361
  if (Array.isArray(schema.fields)) {
17345
- return schema.fields.filter(isRecord9).filter(
17362
+ return schema.fields.filter(isRecord10).filter(
17346
17363
  (field) => field.required === true && typeof field.name === "string"
17347
17364
  ).map((field) => String(field.name));
17348
17365
  }
@@ -17523,7 +17540,7 @@ function validateBootstrapRoutes(input2) {
17523
17540
  }
17524
17541
  }
17525
17542
  function staticPipelineSubsteps(pipeline) {
17526
- if (!isRecord9(pipeline)) return [];
17543
+ if (!isRecord10(pipeline)) return [];
17527
17544
  return [
17528
17545
  ...extractionEntries(pipeline.stages),
17529
17546
  ...extractionEntries(pipeline.substeps)
@@ -17531,7 +17548,7 @@ function staticPipelineSubsteps(pipeline) {
17531
17548
  }
17532
17549
  function playUsesMapBackedRuntime(play) {
17533
17550
  const pipeline = play?.staticPipeline;
17534
- if (!isRecord9(pipeline)) return false;
17551
+ if (!isRecord10(pipeline)) return false;
17535
17552
  if (stringValue(pipeline.tableNamespace)) return true;
17536
17553
  return staticPipelineSubsteps(pipeline).some((substep) => {
17537
17554
  if (stringValue(substep.type) === "map") return true;
@@ -17540,7 +17557,7 @@ function playUsesMapBackedRuntime(play) {
17540
17557
  aliases: [],
17541
17558
  runCommand: "",
17542
17559
  examples: [],
17543
- staticPipeline: isRecord9(substep.pipeline) ? substep.pipeline : null
17560
+ staticPipeline: isRecord10(substep.pipeline) ? substep.pipeline : null
17544
17561
  });
17545
17562
  });
17546
17563
  }
@@ -28076,7 +28093,7 @@ function extractPlayValidationErrors(value) {
28076
28093
  if (value instanceof DeeplineError) {
28077
28094
  return extractPlayValidationErrors(value.details);
28078
28095
  }
28079
- if (!isRecord10(value)) {
28096
+ if (!isRecord11(value)) {
28080
28097
  return [];
28081
28098
  }
28082
28099
  const directErrors = stringArrayField(value, "errors");
@@ -28740,7 +28757,7 @@ function formatPlayRuntimeLimit(runtimeLimit) {
28740
28757
  if (seconds % 60 === 0) return `${seconds / 60} min`;
28741
28758
  return `${seconds} sec`;
28742
28759
  }
28743
- function isRecord10(value) {
28760
+ function isRecord11(value) {
28744
28761
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
28745
28762
  }
28746
28763
  function stringValue3(value) {
@@ -28750,14 +28767,14 @@ function asArray(value) {
28750
28767
  return Array.isArray(value) ? value : [];
28751
28768
  }
28752
28769
  function extractionEntries2(value) {
28753
- if (Array.isArray(value)) return value.filter(isRecord10);
28754
- if (!isRecord10(value)) return [];
28770
+ if (Array.isArray(value)) return value.filter(isRecord11);
28771
+ if (!isRecord11(value)) return [];
28755
28772
  return Object.entries(value).map(
28756
- ([name, entry]) => isRecord10(entry) ? { name, ...entry } : { name }
28773
+ ([name, entry]) => isRecord11(entry) ? { name, ...entry } : { name }
28757
28774
  );
28758
28775
  }
28759
28776
  function firstRawPath(entry) {
28760
- const details = isRecord10(entry.details) ? entry.details : {};
28777
+ const details = isRecord11(entry.details) ? entry.details : {};
28761
28778
  const paths = [
28762
28779
  ...asArray(details.rawToolOutputPaths),
28763
28780
  ...asArray(details.raw_tool_output_paths),
@@ -28775,12 +28792,12 @@ function checkHintRawPath(value) {
28775
28792
  function collectStaticPipelineToolIds(staticPipeline) {
28776
28793
  const seen = /* @__PURE__ */ new Set();
28777
28794
  const visitPipeline = (pipeline) => {
28778
- if (!isRecord10(pipeline)) return;
28795
+ if (!isRecord11(pipeline)) return;
28779
28796
  for (const step of [
28780
28797
  ...asArray(pipeline.stages),
28781
28798
  ...asArray(pipeline.substeps)
28782
28799
  ]) {
28783
- if (!isRecord10(step)) continue;
28800
+ if (!isRecord11(step)) continue;
28784
28801
  if (step.type === "tool") {
28785
28802
  const toolId = stringValue3(step.toolId) || stringValue3(step.tool);
28786
28803
  if (toolId) seen.add(toolId);
@@ -28794,9 +28811,9 @@ function collectStaticPipelineToolIds(staticPipeline) {
28794
28811
  return [...seen].sort();
28795
28812
  }
28796
28813
  function toolGetterHintFromMetadata(toolId, tool) {
28797
- const usageGuidance = isRecord10(tool.usageGuidance) ? tool.usageGuidance : {};
28798
- const resultGuidance = isRecord10(usageGuidance.toolExecutionResult) ? usageGuidance.toolExecutionResult : isRecord10(usageGuidance.tool_execution_result) ? usageGuidance.tool_execution_result : {};
28799
- const toolResponse = isRecord10(resultGuidance.toolResponse) ? resultGuidance.toolResponse : isRecord10(resultGuidance.tool_response) ? resultGuidance.tool_response : {};
28814
+ const usageGuidance = isRecord11(tool.usageGuidance) ? tool.usageGuidance : {};
28815
+ const resultGuidance = isRecord11(usageGuidance.toolExecutionResult) ? usageGuidance.toolExecutionResult : isRecord11(usageGuidance.tool_execution_result) ? usageGuidance.tool_execution_result : {};
28816
+ const toolResponse = isRecord11(resultGuidance.toolResponse) ? resultGuidance.toolResponse : isRecord11(resultGuidance.tool_response) ? resultGuidance.tool_response : {};
28800
28817
  const lists = extractionEntries2(
28801
28818
  resultGuidance.extractedLists ?? resultGuidance.extracted_lists
28802
28819
  ).map((entry) => ({
@@ -29159,7 +29176,7 @@ function artifactForProductionCompatibilityCheck(artifact) {
29159
29176
  "DEEPLINE_PROD_CHECK_AUTHORING_CONTRACT_EDITION must be a positive integer."
29160
29177
  );
29161
29178
  }
29162
- const compatibility = isRecord10(artifact.compatibility) ? artifact.compatibility : {};
29179
+ const compatibility = isRecord11(artifact.compatibility) ? artifact.compatibility : {};
29163
29180
  return {
29164
29181
  ...artifact,
29165
29182
  compatibility: {
@@ -34381,7 +34398,7 @@ function isMarkedTestAiInferenceCommand(command) {
34381
34398
  if (normalizeEnrichPlayRef(command.tool) !== "run_javascript") {
34382
34399
  return false;
34383
34400
  }
34384
- return isRecord11(command.payload) && command.payload[ENRICH_TEST_AI_INFERENCE_PAYLOAD_MARKER] === true;
34401
+ return isRecord12(command.payload) && command.payload[ENRICH_TEST_AI_INFERENCE_PAYLOAD_MARKER] === true;
34385
34402
  }
34386
34403
  function enrichDebugEnabled(env = process.env) {
34387
34404
  const raw = String(env.DEEPLINE_DEBUG_ENRICH ?? "").trim().toLowerCase();
@@ -34645,7 +34662,7 @@ function rewriteGeneratedPlayRerunForEnrich(status, enrichCommand) {
34645
34662
  if (Array.isArray(value)) {
34646
34663
  return value.map(rewrite);
34647
34664
  }
34648
- if (!isRecord11(value)) {
34665
+ if (!isRecord12(value)) {
34649
34666
  return value;
34650
34667
  }
34651
34668
  const next = Object.fromEntries(
@@ -34654,7 +34671,7 @@ function rewriteGeneratedPlayRerunForEnrich(status, enrichCommand) {
34654
34671
  key === "rerunCommand" && typeof entry === "string" ? enrichCommand : rewrite(entry)
34655
34672
  ])
34656
34673
  );
34657
- if (isRecord11(next.next) && typeof next.next.run === "string") {
34674
+ if (isRecord12(next.next) && typeof next.next.run === "string") {
34658
34675
  next.next = { ...next.next, run: enrichCommand };
34659
34676
  }
34660
34677
  return next;
@@ -35136,7 +35153,7 @@ async function resolveWatchedGeneratedPlayStatus(input2) {
35136
35153
  }
35137
35154
  return input2.client.runs.get(runId, { full: true });
35138
35155
  }
35139
- function isRecord11(value) {
35156
+ function isRecord12(value) {
35140
35157
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
35141
35158
  }
35142
35159
  async function captureStdout(run, options = {}) {
@@ -35388,15 +35405,15 @@ function readFirstEnrichDatasetActions(value) {
35388
35405
  return null;
35389
35406
  }
35390
35407
  const record3 = candidate;
35391
- const actions = isRecord11(record3.actions) ? record3.actions : null;
35392
- const currentQuery = isRecord11(actions?.queryCurrentTable) ? actions.queryCurrentTable : null;
35393
- const legacyQuery = isRecord11(actions?.query) ? actions.query : null;
35408
+ const actions = isRecord12(record3.actions) ? record3.actions : null;
35409
+ const currentQuery = isRecord12(actions?.queryCurrentTable) ? actions.queryCurrentTable : null;
35410
+ const legacyQuery = isRecord12(actions?.query) ? actions.query : null;
35394
35411
  const query = currentQuery?.kind === "deepline_db_query" ? currentQuery : legacyQuery?.kind === "deepline_db_query" ? legacyQuery : null;
35395
35412
  if (query?.kind === "deepline_db_query") {
35396
35413
  return {
35397
35414
  dataset: record3,
35398
35415
  query,
35399
- ...isRecord11(actions?.exportCsv) ? { exportCsv: actions.exportCsv } : {}
35416
+ ...isRecord12(actions?.exportCsv) ? { exportCsv: actions.exportCsv } : {}
35400
35417
  };
35401
35418
  }
35402
35419
  if (options.allowLegacy && record3.kind === "dataset" && typeof record3.queryDatasetCommand === "string" && record3.queryDatasetCommand.trim()) {
@@ -35449,7 +35466,7 @@ function enrichCustomerDbJson(input2) {
35449
35466
  const dataset = actions.dataset;
35450
35467
  const sql = actionStringField(query, "sql") ?? parseSqlFromDbQueryCommand(actions.queryDatasetCommand);
35451
35468
  const datasetPath = actionStringField(query, "datasetPath") ?? actionStringField(dataset, "path") ?? actionStringField(dataset, "tableNamespace");
35452
- const api = isRecord11(query.api) ? query.api : null;
35469
+ const api = isRecord12(query.api) ? query.api : null;
35453
35470
  const apiPath = actionStringField(api ?? {}, "path") ?? "/api/v2/db/query";
35454
35471
  const apiMethod = actionStringField(api ?? {}, "method") ?? "POST";
35455
35472
  if (!datasetPath) {
@@ -35518,11 +35535,11 @@ function sqlStringLiteral(value) {
35518
35535
  return `'${value.replace(/'/g, "''")}'`;
35519
35536
  }
35520
35537
  function failureAliasFromCellMeta(cellMeta) {
35521
- if (!isRecord11(cellMeta)) {
35538
+ if (!isRecord12(cellMeta)) {
35522
35539
  return null;
35523
35540
  }
35524
35541
  for (const [alias, meta] of Object.entries(cellMeta)) {
35525
- if (!isRecord11(meta)) {
35542
+ if (!isRecord12(meta)) {
35526
35543
  continue;
35527
35544
  }
35528
35545
  const failure = failureCellFromMeta(meta, {});
@@ -36016,7 +36033,7 @@ function exportableSheetRow2(row, sourceRowStart = 0) {
36016
36033
  return fallback;
36017
36034
  }
36018
36035
  function failureCellFromMeta(meta, fallback) {
36019
- if (!isRecord11(meta)) {
36036
+ if (!isRecord12(meta)) {
36020
36037
  return null;
36021
36038
  }
36022
36039
  const status = typeof meta.status === "string" ? meta.status.trim().toLowerCase() : "";
@@ -36036,7 +36053,7 @@ function failureCellFromMeta(meta, fallback) {
36036
36053
  };
36037
36054
  }
36038
36055
  function applyFailureCellMeta(row, cellMeta, fallback) {
36039
- if (!isRecord11(cellMeta)) {
36056
+ if (!isRecord12(cellMeta)) {
36040
36057
  return;
36041
36058
  }
36042
36059
  for (const [field, meta] of Object.entries(cellMeta)) {
@@ -36264,7 +36281,7 @@ function stableRowSnapshot(value) {
36264
36281
  }
36265
36282
  function cellFailureError(value) {
36266
36283
  const parsed = parseMaybeJsonObject(value);
36267
- if (!isRecord11(parsed)) {
36284
+ if (!isRecord12(parsed)) {
36268
36285
  const text = typeof parsed === "string" ? parsed.trim() : "";
36269
36286
  if (/^(?:[A-Za-z0-9_:-]+:\s*)?(?:Error|TypeError|ReferenceError|SyntaxError|RangeError):\s+/.test(
36270
36287
  text
@@ -36272,12 +36289,12 @@ function cellFailureError(value) {
36272
36289
  return { message: text };
36273
36290
  }
36274
36291
  }
36275
- if (!isRecord11(parsed)) {
36292
+ if (!isRecord12(parsed)) {
36276
36293
  return null;
36277
36294
  }
36278
36295
  const status = typeof parsed.status === "string" ? parsed.status.trim().toLowerCase() : "";
36279
36296
  const directError = typeof parsed.error === "string" ? parsed.error.trim() : typeof parsed.last_error === "string" ? parsed.last_error.trim() : "";
36280
- const result = isRecord11(parsed.result) ? parsed.result : null;
36297
+ const result = isRecord12(parsed.result) ? parsed.result : null;
36281
36298
  const resultError = typeof result?.error === "string" ? result.error.trim() : typeof result?.message === "string" ? result.message.trim() : "";
36282
36299
  if (!directError && !resultError && status !== "error" && status !== "failed") {
36283
36300
  return null;
@@ -36347,7 +36364,7 @@ function assignFlattenedFailurePath(target, field, value) {
36347
36364
  let cursor = target;
36348
36365
  for (const part of normalized.slice(0, -1)) {
36349
36366
  const existing = cursor[part];
36350
- if (!isRecord11(existing)) {
36367
+ if (!isRecord12(existing)) {
36351
36368
  const next = {};
36352
36369
  cursor[part] = next;
36353
36370
  cursor = next;
@@ -36511,10 +36528,10 @@ function waterfallExecutionSignal(status, spec) {
36511
36528
  let everyChildStatOnlyConditionSkipped = true;
36512
36529
  const childAliasesWithStats = /* @__PURE__ */ new Set();
36513
36530
  for (const childAlias of childAliases) {
36514
- for (const stat5 of summaries.map((summary) => summary[childAlias]).filter(isRecord11)) {
36531
+ for (const stat5 of summaries.map((summary) => summary[childAlias]).filter(isRecord12)) {
36515
36532
  sawChildStats = true;
36516
36533
  childAliasesWithStats.add(childAlias);
36517
- const execution = isRecord11(stat5.execution) ? stat5.execution : null;
36534
+ const execution = isRecord12(stat5.execution) ? stat5.execution : null;
36518
36535
  const executedSummary = parseExecutionSummary(
36519
36536
  execution?.["completed:executed"]
36520
36537
  );
@@ -36544,7 +36561,7 @@ function waterfallExecutionSignal(status, spec) {
36544
36561
  }
36545
36562
  function emptyWaterfallStatsEvidence(status, spec) {
36546
36563
  const summaries = collectColumnStats(status);
36547
- const parentStats = summaries.map((summary) => summary[spec.alias]).filter(isRecord11);
36564
+ const parentStats = summaries.map((summary) => summary[spec.alias]).filter(isRecord12);
36548
36565
  for (const stat5 of parentStats) {
36549
36566
  const nonEmpty = parseExecutionSummary(stat5.non_empty);
36550
36567
  if (nonEmpty?.total && nonEmpty.count === 0) {
@@ -36558,7 +36575,7 @@ function emptyWaterfallStatsEvidence(status, spec) {
36558
36575
  let selectedRows = 0;
36559
36576
  let sawStatsForEveryChild = true;
36560
36577
  for (const childAlias of childAliases) {
36561
- const stat5 = summaries.map((summary) => summary[childAlias]).find(isRecord11);
36578
+ const stat5 = summaries.map((summary) => summary[childAlias]).find(isRecord12);
36562
36579
  if (!stat5) {
36563
36580
  sawStatsForEveryChild = false;
36564
36581
  break;
@@ -36567,7 +36584,7 @@ function emptyWaterfallStatsEvidence(status, spec) {
36567
36584
  if ((nonEmpty?.count ?? 0) > 0) {
36568
36585
  return null;
36569
36586
  }
36570
- const execution = isRecord11(stat5.execution) ? stat5.execution : null;
36587
+ const execution = isRecord12(stat5.execution) ? stat5.execution : null;
36571
36588
  const executed = parseExecutionSummary(execution?.["completed:executed"]);
36572
36589
  const reused = parseExecutionSummary(execution?.["completed:reused"]);
36573
36590
  const skipped = parseExecutionSummary(execution?.["skipped:condition"]);
@@ -36609,11 +36626,11 @@ function collectStatusFailureJobs(input2) {
36609
36626
  const jobs = [];
36610
36627
  aliases.forEach((spec, aliasIndex) => {
36611
36628
  const { alias } = spec;
36612
- const stat5 = summaries.map((summary) => summary[alias]).find(isRecord11);
36629
+ const stat5 = summaries.map((summary) => summary[alias]).find(isRecord12);
36613
36630
  if (!stat5) {
36614
36631
  return;
36615
36632
  }
36616
- const execution = isRecord11(stat5.execution) ? stat5.execution : null;
36633
+ const execution = isRecord12(stat5.execution) ? stat5.execution : null;
36617
36634
  const failedCount = Math.min(
36618
36635
  selectedRows,
36619
36636
  Math.max(
@@ -36720,10 +36737,10 @@ function collectColumnStats(status) {
36720
36737
  value.forEach(visit);
36721
36738
  return;
36722
36739
  }
36723
- if (!isRecord11(value)) {
36740
+ if (!isRecord12(value)) {
36724
36741
  return;
36725
36742
  }
36726
- if (isRecord11(value.columnStats)) {
36743
+ if (isRecord12(value.columnStats)) {
36727
36744
  summaries.push(value.columnStats);
36728
36745
  }
36729
36746
  Object.values(value).forEach(visit);
@@ -36735,12 +36752,12 @@ function firstAliasExecutionCounts(input2) {
36735
36752
  const aliases = collectConfigScalarAliasOrder(input2.config);
36736
36753
  const summaries = collectColumnStats(input2.status);
36737
36754
  for (const alias of aliases) {
36738
- const stat5 = summaries.map((summary) => summary[alias]).find(isRecord11);
36755
+ const stat5 = summaries.map((summary) => summary[alias]).find(isRecord12);
36739
36756
  if (!stat5) continue;
36740
36757
  if (input2.forceAliases.has(normalizeAlias2(alias))) {
36741
36758
  return { executed: input2.selectedRows, reused: 0 };
36742
36759
  }
36743
- const execution = isRecord11(stat5.execution) ? stat5.execution : null;
36760
+ const execution = isRecord12(stat5.execution) ? stat5.execution : null;
36744
36761
  if (!execution) continue;
36745
36762
  return {
36746
36763
  executed: parseExecutionCount(execution["completed:executed"]),
@@ -36767,14 +36784,14 @@ function rewriteEnrichJsonStatus(input2) {
36767
36784
  if (Array.isArray(value)) {
36768
36785
  return value.map(rewrite);
36769
36786
  }
36770
- if (!isRecord11(value)) {
36787
+ if (!isRecord12(value)) {
36771
36788
  return value;
36772
36789
  }
36773
36790
  const next = {};
36774
36791
  for (const [key, entry] of Object.entries(value)) {
36775
36792
  next[key] = rewrite(entry);
36776
36793
  }
36777
- if (isRecord11(next.progress)) {
36794
+ if (isRecord12(next.progress)) {
36778
36795
  next.progress = {
36779
36796
  ...next.progress,
36780
36797
  ...selectedRows > 0 ? { total: selectedRows } : {},
@@ -36783,8 +36800,8 @@ function rewriteEnrichJsonStatus(input2) {
36783
36800
  ...failedRows > 0 ? { failed: failedRows, pending: 0 } : {}
36784
36801
  };
36785
36802
  }
36786
- if (isRecord11(next.summary)) {
36787
- const rowCounts = isRecord11(next.summary.rowCounts) ? next.summary.rowCounts : null;
36803
+ if (isRecord12(next.summary)) {
36804
+ const rowCounts = isRecord12(next.summary.rowCounts) ? next.summary.rowCounts : null;
36788
36805
  if (failedRows > 0) {
36789
36806
  next.summary = {
36790
36807
  ...next.summary,
@@ -36797,11 +36814,11 @@ function rewriteEnrichJsonStatus(input2) {
36797
36814
  };
36798
36815
  }
36799
36816
  }
36800
- if (isRecord11(next.columnStats) && selectedRows > 0) {
36817
+ if (isRecord12(next.columnStats) && selectedRows > 0) {
36801
36818
  const columnStats = { ...next.columnStats };
36802
36819
  for (const alias of forcedAliases) {
36803
- const stat5 = isRecord11(columnStats[alias]) ? columnStats[alias] : null;
36804
- const execution = isRecord11(stat5?.execution) ? stat5.execution : null;
36820
+ const stat5 = isRecord12(columnStats[alias]) ? columnStats[alias] : null;
36821
+ const execution = isRecord12(stat5?.execution) ? stat5.execution : null;
36805
36822
  if (!stat5 || !execution) continue;
36806
36823
  columnStats[alias] = {
36807
36824
  ...stat5,
@@ -36820,14 +36837,14 @@ function rewriteEnrichJsonStatus(input2) {
36820
36837
  return next;
36821
36838
  };
36822
36839
  const rewritten = rewrite(input2.status);
36823
- if (failedRows === 0 || !isRecord11(rewritten)) {
36840
+ if (failedRows === 0 || !isRecord12(rewritten)) {
36824
36841
  return rewritten;
36825
36842
  }
36826
36843
  const partialStatus = selectedRows > 0 && failedRows < selectedRows ? "partial_success" : "failed";
36827
36844
  return {
36828
36845
  ...rewritten,
36829
36846
  ...rewritten.status === "completed" || rewritten.status === "failed" ? { status: partialStatus } : {},
36830
- ...isRecord11(rewritten.run) && (rewritten.run.status === "completed" || rewritten.run.status === "failed") ? { run: { ...rewritten.run, status: partialStatus } } : {}
36847
+ ...isRecord12(rewritten.run) && (rewritten.run.status === "completed" || rewritten.run.status === "failed") ? { run: { ...rewritten.run, status: partialStatus } } : {}
36831
36848
  };
36832
36849
  }
36833
36850
  function summarizeFailedJobError(value) {
@@ -37451,7 +37468,7 @@ function materializeCsvCellValue(value) {
37451
37468
  return value;
37452
37469
  }
37453
37470
  function compactArrayEnvelopeCompleteValue(value) {
37454
- if (!isRecord11(value) || value.kind !== "array") {
37471
+ if (!isRecord12(value) || value.kind !== "array") {
37455
37472
  return null;
37456
37473
  }
37457
37474
  if (!Array.isArray(value.preview)) {
@@ -37465,7 +37482,7 @@ function compactArrayEnvelopeCompleteValue(value) {
37465
37482
  }
37466
37483
  function disambiguateCompactAiInferencePayload(value) {
37467
37484
  const parsed = parseMaybeJsonObject(value);
37468
- if (!isRecord11(parsed) || !cellFailureError(parsed)) {
37485
+ if (!isRecord12(parsed) || !cellFailureError(parsed)) {
37469
37486
  return value;
37470
37487
  }
37471
37488
  return {
@@ -37474,14 +37491,14 @@ function disambiguateCompactAiInferencePayload(value) {
37474
37491
  };
37475
37492
  }
37476
37493
  function compactAiInferenceCellForCsv(value) {
37477
- if (!isRecord11(value)) {
37494
+ if (!isRecord12(value)) {
37478
37495
  return value;
37479
37496
  }
37480
37497
  const extractedJson = value.extracted_json;
37481
37498
  if (extractedJson !== null && extractedJson !== void 0) {
37482
37499
  return disambiguateCompactAiInferencePayload(extractedJson);
37483
37500
  }
37484
- const result = isRecord11(value.result) ? value.result : null;
37501
+ const result = isRecord12(value.result) ? value.result : null;
37485
37502
  const object = result?.object;
37486
37503
  if (object !== null && object !== void 0) {
37487
37504
  return disambiguateCompactAiInferencePayload(object);
@@ -37498,12 +37515,12 @@ function compactAiInferenceCellForCsv(value) {
37498
37515
  }
37499
37516
  function materializeEnrichAliasCellForCsv(row, alias, options) {
37500
37517
  const direct = row[alias];
37501
- if (isRecord11(direct)) {
37518
+ if (isRecord12(direct)) {
37502
37519
  const completeArray = compactArrayEnvelopeCompleteValue(direct);
37503
37520
  if (completeArray) {
37504
37521
  return materializeCsvCellValue(completeArray);
37505
37522
  }
37506
- if (options?.compactAiCell && direct.status === "completed" && (isRecord11(direct.result) || Object.prototype.hasOwnProperty.call(direct, "extracted_json") || typeof direct.output === "string")) {
37523
+ if (options?.compactAiCell && direct.status === "completed" && (isRecord12(direct.result) || Object.prototype.hasOwnProperty.call(direct, "extracted_json") || typeof direct.output === "string")) {
37507
37524
  return materializeCsvCellValue(compactAiInferenceCellForCsv(direct));
37508
37525
  }
37509
37526
  if (Object.prototype.hasOwnProperty.call(direct, "matched_result") || Object.prototype.hasOwnProperty.call(direct, "matchedResult") || Object.prototype.hasOwnProperty.call(direct, "result")) {
@@ -37644,11 +37661,11 @@ function normalizeEnrichRowsForCsvExport(rows, config, options) {
37644
37661
  }
37645
37662
  function legacyMetadataFromRow(row) {
37646
37663
  const direct = parseLegacyMetadataCell(row._metadata);
37647
- if (direct && isRecord11(direct.columns)) {
37664
+ if (direct && isRecord12(direct.columns)) {
37648
37665
  return direct;
37649
37666
  }
37650
37667
  const relocated = parseLegacyMetadataCell(row.metadata);
37651
- if (relocated && isRecord11(relocated.columns)) {
37668
+ if (relocated && isRecord12(relocated.columns)) {
37652
37669
  return relocated;
37653
37670
  }
37654
37671
  const flattenedColumns = parseLegacyMetadataCell(row["metadata.columns"]);
@@ -37665,7 +37682,7 @@ function legacyMetadataFromRow(row) {
37665
37682
  }
37666
37683
  function parseLegacyMetadataCell(value) {
37667
37684
  const parsed = parseMaybeJsonObject(value);
37668
- if (isRecord11(parsed)) {
37685
+ if (isRecord12(parsed)) {
37669
37686
  return parsed;
37670
37687
  }
37671
37688
  if (typeof value !== "string") {
@@ -37682,12 +37699,12 @@ function parseLegacyMetadataCell(value) {
37682
37699
  for (const candidate of candidates) {
37683
37700
  try {
37684
37701
  const decoded = JSON.parse(candidate);
37685
- if (isRecord11(decoded)) {
37702
+ if (isRecord12(decoded)) {
37686
37703
  return decoded;
37687
37704
  }
37688
37705
  if (typeof decoded === "string") {
37689
37706
  const nested = JSON.parse(decoded);
37690
- if (isRecord11(nested)) {
37707
+ if (isRecord12(nested)) {
37691
37708
  return nested;
37692
37709
  }
37693
37710
  }
@@ -37697,8 +37714,8 @@ function parseLegacyMetadataCell(value) {
37697
37714
  return null;
37698
37715
  }
37699
37716
  function mergeLegacyMetadataRecords(base, enriched) {
37700
- const baseColumns = isRecord11(base.columns) ? base.columns : null;
37701
- const enrichedColumns = isRecord11(enriched.columns) ? enriched.columns : null;
37717
+ const baseColumns = isRecord12(base.columns) ? base.columns : null;
37718
+ const enrichedColumns = isRecord12(enriched.columns) ? enriched.columns : null;
37702
37719
  const merged = {
37703
37720
  ...base,
37704
37721
  ...enriched
@@ -49514,6 +49531,18 @@ Examples:
49514
49531
 
49515
49532
  // src/cli/commands/tools.ts
49516
49533
  import { Option as Option4 } from "commander";
49534
+ import {
49535
+ chmodSync,
49536
+ existsSync as existsSync20,
49537
+ mkdirSync as mkdirSync17,
49538
+ mkdtempSync,
49539
+ readFileSync as readFileSync23,
49540
+ writeFileSync as writeFileSync21
49541
+ } from "fs";
49542
+ import { tmpdir as tmpdir6 } from "os";
49543
+ import { dirname as dirname21, join as join27, resolve as resolve20 } from "path";
49544
+
49545
+ // src/cli/tool-call-recovery.ts
49517
49546
  import { createHash as createHash7, randomUUID as randomUUID9 } from "crypto";
49518
49547
 
49519
49548
  // ../plays/row-identity.ts
@@ -49532,30 +49561,107 @@ function stableStringify(value) {
49532
49561
  return JSON.stringify(stableValue(value));
49533
49562
  }
49534
49563
 
49535
- // src/cli/commands/tools.ts
49564
+ // src/cli/tool-call-recovery.ts
49536
49565
  import {
49537
- chmodSync,
49538
49566
  existsSync as existsSync19,
49539
49567
  linkSync,
49540
- mkdirSync as mkdirSync16,
49541
- mkdtempSync,
49568
+ mkdirSync as mkdirSync15,
49542
49569
  readFileSync as readFileSync22,
49543
49570
  unlinkSync as unlinkSync4,
49544
- writeFileSync as writeFileSync20
49571
+ writeFileSync as writeFileSync19
49545
49572
  } from "fs";
49546
- import { tmpdir as tmpdir6 } from "os";
49547
- import { dirname as dirname20, join as join26, resolve as resolve20 } from "path";
49573
+ import { dirname as dirname19, join as join25 } from "path";
49574
+ var ToolCallRecovery = class _ToolCallRecovery {
49575
+ constructor(idempotencyKey, path) {
49576
+ this.idempotencyKey = idempotencyKey;
49577
+ this.path = path;
49578
+ }
49579
+ static open(input2) {
49580
+ if (!input2.recover || input2.idempotencyKey) {
49581
+ return new _ToolCallRecovery(input2.idempotencyKey, null);
49582
+ }
49583
+ const path = pendingToolExecutionPath(input2);
49584
+ return new _ToolCallRecovery(loadOrCreatePendingToolExecution(path), path);
49585
+ }
49586
+ async acknowledgeDelivery() {
49587
+ await completePendingToolExecution(this.path, this.idempotencyKey);
49588
+ }
49589
+ };
49590
+ function pendingToolExecutionPath(input2) {
49591
+ const config = resolveConfig();
49592
+ const fingerprint = createHash7("sha256").update(config.baseUrl).update("\0").update(createHash7("sha256").update(config.apiKey).digest("hex")).update("\0").update(input2.toolId).update("\0").update(stableStringify(input2.params)).update("\0").update(input2.responseIntent).digest("hex");
49593
+ return join25(
49594
+ sdkCliStateDirPath(config.baseUrl),
49595
+ `pending-tool-execution-${fingerprint}.json`
49596
+ );
49597
+ }
49598
+ function loadOrCreatePendingToolExecution(path) {
49599
+ mkdirSync15(dirname19(path), { recursive: true });
49600
+ if (existsSync19(path)) {
49601
+ return readPendingToolExecution(path);
49602
+ }
49603
+ const idempotencyKey = randomUUID9();
49604
+ const temporaryPath = `${path}.${process.pid}.${randomUUID9()}.tmp`;
49605
+ try {
49606
+ writeFileSync19(temporaryPath, `${JSON.stringify({ idempotencyKey })}
49607
+ `, {
49608
+ encoding: "utf8",
49609
+ flag: "wx",
49610
+ mode: 384
49611
+ });
49612
+ linkSync(temporaryPath, path);
49613
+ return idempotencyKey;
49614
+ } catch (error) {
49615
+ if (error.code !== "EEXIST") throw error;
49616
+ return readPendingToolExecution(path);
49617
+ } finally {
49618
+ if (existsSync19(temporaryPath)) unlinkSync4(temporaryPath);
49619
+ }
49620
+ }
49621
+ function readPendingToolExecution(path) {
49622
+ const saved = JSON.parse(readFileSync22(path, "utf8"));
49623
+ if (typeof saved.idempotencyKey !== "string") {
49624
+ throw new Error(
49625
+ `Cannot resume the saved tool execution at ${path}: invalid recovery key.`
49626
+ );
49627
+ }
49628
+ return saved.idempotencyKey;
49629
+ }
49630
+ async function completePendingToolExecution(path, idempotencyKey) {
49631
+ if (!path || !idempotencyKey || !existsSync19(path)) return;
49632
+ await new Promise((resolve22, reject) => {
49633
+ const onError = (error) => {
49634
+ process.stdout.off("error", onError);
49635
+ reject(error);
49636
+ };
49637
+ process.stdout.once("error", onError);
49638
+ process.stdout.write("", (error) => {
49639
+ process.stdout.off("error", onError);
49640
+ if (error) {
49641
+ reject(error);
49642
+ } else {
49643
+ resolve22();
49644
+ }
49645
+ });
49646
+ });
49647
+ try {
49648
+ if (readPendingToolExecution(path) !== idempotencyKey) return;
49649
+ unlinkSync4(path);
49650
+ } catch (error) {
49651
+ if (error.code !== "ENOENT") throw error;
49652
+ }
49653
+ }
49548
49654
 
49549
49655
  // src/tool-output.ts
49550
49656
  import {
49551
49657
  closeSync as closeSync3,
49552
- mkdirSync as mkdirSync15,
49658
+ mkdirSync as mkdirSync16,
49553
49659
  openSync as openSync3,
49554
- writeFileSync as writeFileSync19,
49660
+ writeFileSync as writeFileSync20,
49555
49661
  writeSync
49556
49662
  } from "fs";
49557
49663
  import { homedir as homedir13 } from "os";
49558
- import { dirname as dirname19, join as join25 } from "path";
49664
+ import { dirname as dirname20, join as join26 } from "path";
49559
49665
  function isPlainObject(value) {
49560
49666
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
49561
49667
  }
@@ -49682,19 +49788,19 @@ function projectRowOutput(conversion) {
49682
49788
  };
49683
49789
  }
49684
49790
  function ensureOutputDir() {
49685
- const outputDir = join25(homedir13(), ".local", "share", "deepline", "data");
49686
- mkdirSync15(outputDir, { recursive: true });
49791
+ const outputDir = join26(homedir13(), ".local", "share", "deepline", "data");
49792
+ mkdirSync16(outputDir, { recursive: true });
49687
49793
  return outputDir;
49688
49794
  }
49689
49795
  function writeJsonOutputFile(payload, stem) {
49690
49796
  const outputDir = ensureOutputDir();
49691
- const outputPath = join25(outputDir, `${stem}_${Date.now()}.json`);
49692
- writeFileSync19(outputPath, JSON.stringify(payload, null, 2), "utf-8");
49797
+ const outputPath = join26(outputDir, `${stem}_${Date.now()}.json`);
49798
+ writeFileSync20(outputPath, JSON.stringify(payload, null, 2), "utf-8");
49693
49799
  return outputPath;
49694
49800
  }
49695
49801
  function writeCsvOutputFile(rows, stem, options) {
49696
- const outputPath = options?.outPath ? options.outPath : join25(ensureOutputDir(), `${stem}_${Date.now()}.csv`);
49697
- mkdirSync15(dirname19(outputPath), { recursive: true });
49802
+ const outputPath = options?.outPath ? options.outPath : join26(ensureOutputDir(), `${stem}_${Date.now()}.csv`);
49803
+ mkdirSync16(dirname20(outputPath), { recursive: true });
49698
49804
  const columns = columnsForRows(rows);
49699
49805
  const escapeCell = (value) => {
49700
49806
  const normalized = value == null ? "" : typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : JSON.stringify(value);
@@ -50282,12 +50388,12 @@ async function listTools(category, options = {}) {
50282
50388
  }
50283
50389
  var SEARCH_REF_TTL_MS = 15 * 6e4;
50284
50390
  function lastSearchPath() {
50285
- return join26(sdkCliStateDirPath(resolveConfig().baseUrl), "last-search.json");
50391
+ return join27(sdkCliStateDirPath(resolveConfig().baseUrl), "last-search.json");
50286
50392
  }
50287
50393
  function rememberSearchRef(searchRef) {
50288
50394
  try {
50289
- mkdirSync16(dirname20(lastSearchPath()), { recursive: true });
50290
- writeFileSync20(
50395
+ mkdirSync17(dirname21(lastSearchPath()), { recursive: true });
50396
+ writeFileSync21(
50291
50397
  lastSearchPath(),
50292
50398
  JSON.stringify({ searchRef, at: Date.now() }),
50293
50399
  { mode: 384 }
@@ -50297,7 +50403,7 @@ function rememberSearchRef(searchRef) {
50297
50403
  }
50298
50404
  function recentSearchRef() {
50299
50405
  try {
50300
- const saved = JSON.parse(readFileSync22(lastSearchPath(), "utf8"));
50406
+ const saved = JSON.parse(readFileSync23(lastSearchPath(), "utf8"));
50301
50407
  return typeof saved.searchRef === "string" && typeof saved.at === "number" && Date.now() - saved.at < SEARCH_REF_TTL_MS ? saved.searchRef : void 0;
50302
50408
  } catch {
50303
50409
  return void 0;
@@ -50957,7 +51063,7 @@ function toolContractJsonForDescribe(tool, requestedToolId) {
50957
51063
  }
50958
51064
  function extractionContractEntries(entries) {
50959
51065
  return entries.flatMap((entry) => {
50960
- if (!isRecord12(entry)) return [];
51066
+ if (!isRecord13(entry)) return [];
50961
51067
  const name = stringField2(entry, "name");
50962
51068
  const expression = stringField2(entry, "expression");
50963
51069
  return name && expression ? [{ name, expression }] : [];
@@ -50978,7 +51084,7 @@ function printMonitorTypeFilters(tool) {
50978
51084
  }
50979
51085
  console.log("Deploy filters (set in the monitor payload):");
50980
51086
  for (const name of names) {
50981
- const field = isRecord12(properties[name]) ? properties[name] : {};
51087
+ const field = isRecord13(properties[name]) ? properties[name] : {};
50982
51088
  const star = required.has(name) ? "*" : "";
50983
51089
  const enumVals = arrayField2(field, "enum").filter(
50984
51090
  (v) => typeof v === "string"
@@ -50992,7 +51098,7 @@ function printMonitorTypeFilterExamples(tool) {
50992
51098
  const documentation = recordField2(tool, "documentation");
50993
51099
  const fields2 = recordField2(documentation, "fields");
50994
51100
  const examples = Object.entries(fields2).flatMap(([name, rawField]) => {
50995
- const grammar = recordField2(isRecord12(rawField) ? rawField : {}, "grammar");
51101
+ const grammar = recordField2(isRecord13(rawField) ? rawField : {}, "grammar");
50996
51102
  const example = stringField2(grammar, "example");
50997
51103
  const values = [
50998
51104
  ...arrayField2(grammar, "examples").filter(
@@ -51011,14 +51117,14 @@ function printMonitorTypeFilterExamples(tool) {
51011
51117
  }
51012
51118
  function printMonitorTypeStreams(tool) {
51013
51119
  const streams = arrayField2(tool, "streams", "output_streams").filter(
51014
- isRecord12
51120
+ isRecord13
51015
51121
  );
51016
51122
  if (!streams.length) return;
51017
51123
  console.log("");
51018
51124
  console.log("Filter columns (a play's sqlListeners.where, per stream):");
51019
51125
  for (const stream of streams) {
51020
51126
  const name = stringField2(stream, "stream");
51021
- const cols = arrayField2(stream, "columns").filter(isRecord12).map((col) => stringField2(col, "name")).filter(Boolean);
51127
+ const cols = arrayField2(stream, "columns").filter(isRecord13).map((col) => stringField2(col, "name")).filter(Boolean);
51022
51128
  console.log(`- ${name}: ${cols.join(", ")}`);
51023
51129
  }
51024
51130
  }
@@ -51036,7 +51142,7 @@ function printMonitorTypePricing(tool) {
51036
51142
  }
51037
51143
  console.log("Pricing (Deepline credits per accepted event):");
51038
51144
  for (const key of keys) {
51039
- const entry = isRecord12(byType[key]) ? byType[key] : {};
51145
+ const entry = isRecord13(byType[key]) ? byType[key] : {};
51040
51146
  const credits = numberField2(entry, "deepline_credits", "deeplineCredits");
51041
51147
  const display = stringField2(entry, "display");
51042
51148
  const shown = display || (credits !== null ? `${formatDecimal(credits)} credits/event` : "see --json");
@@ -51082,8 +51188,8 @@ function printCompactToolContract(tool, requestedToolId) {
51082
51188
  return;
51083
51189
  }
51084
51190
  const contract = toolContractJsonForDescribe(tool, requestedToolId);
51085
- const cost = isRecord12(contract.cost) ? contract.cost : {};
51086
- const getters = isRecord12(contract.getters) ? contract.getters : {};
51191
+ const cost = isRecord13(contract.cost) ? contract.cost : {};
51192
+ const getters = isRecord13(contract.getters) ? contract.getters : {};
51087
51193
  const listGetters = Array.isArray(getters.extractedLists) ? getters.extractedLists : [];
51088
51194
  const valueGetters = Array.isArray(getters.extractedValues) ? getters.extractedValues : [];
51089
51195
  const inputFields = recursiveToolInputFieldsForDisplay(
@@ -51100,7 +51206,7 @@ function printCompactToolContract(tool, requestedToolId) {
51100
51206
  printToolOutputArrayShape(contract);
51101
51207
  printToolExecutionHints(contract);
51102
51208
  if (contract.deprecated === true) {
51103
- const deprecation = isRecord12(contract.deprecation) ? contract.deprecation : {};
51209
+ const deprecation = isRecord13(contract.deprecation) ? contract.deprecation : {};
51104
51210
  const message = stringField2(deprecation, "message");
51105
51211
  const replacementToolId = stringField2(
51106
51212
  deprecation,
@@ -51127,7 +51233,7 @@ function printCompactToolContract(tool, requestedToolId) {
51127
51233
  console.log("");
51128
51234
  console.log("Inputs:");
51129
51235
  for (const field of inputFields) {
51130
- if (!isRecord12(field)) continue;
51236
+ if (!isRecord13(field)) continue;
51131
51237
  const name = stringField2(field, "name");
51132
51238
  if (!name) continue;
51133
51239
  const required = field.required ? "*" : "";
@@ -51147,7 +51253,7 @@ function printCompactToolContract(tool, requestedToolId) {
51147
51253
  }
51148
51254
  console.log("");
51149
51255
  printToolExamplesOnly(tool, requestedToolId, { includeSamples: false });
51150
- const starterScript = isRecord12(contract.starterScript) ? contract.starterScript : {};
51256
+ const starterScript = isRecord13(contract.starterScript) ? contract.starterScript : {};
51151
51257
  const starterPath = stringField2(starterScript, "path");
51152
51258
  if (starterPath) {
51153
51259
  console.log("");
@@ -51161,14 +51267,14 @@ function printCompactToolContract(tool, requestedToolId) {
51161
51267
  console.log("Getters:");
51162
51268
  if (listGetters.length) console.log("Lists:");
51163
51269
  for (const entry of listGetters) {
51164
- if (isRecord12(entry))
51270
+ if (isRecord13(entry))
51165
51271
  console.log(
51166
51272
  `- ${stringField2(entry, "name")}: ${playResultExpression(entry)}`
51167
51273
  );
51168
51274
  }
51169
51275
  if (valueGetters.length) console.log("Values:");
51170
51276
  for (const entry of valueGetters) {
51171
- if (isRecord12(entry))
51277
+ if (isRecord13(entry))
51172
51278
  console.log(
51173
51279
  `- ${stringField2(entry, "name")}: ${playResultExpression(entry)}`
51174
51280
  );
@@ -51185,7 +51291,7 @@ function printToolPricingOnly(tool, requestedToolId, options = {}) {
51185
51291
  return;
51186
51292
  }
51187
51293
  const contract = toolContractJsonForDescribe(tool, requestedToolId);
51188
- const cost = isRecord12(contract.cost) ? contract.cost : {};
51294
+ const cost = isRecord13(contract.cost) ? contract.cost : {};
51189
51295
  const pricingModel = stringField2(cost, "pricingModel") || "unknown";
51190
51296
  const billing = stringField2(cost, "billingSourceLabel") || stringField2(cost, "billingSource") || stringField2(cost, "billingMode") || "unknown";
51191
51297
  const explicitUnit = stringField2(cost, "unit");
@@ -51262,10 +51368,10 @@ function printToolExamplesOnly(tool, requestedToolId, options = {}) {
51262
51368
  ` input: ${JSON.stringify(sampleInput || {}, null, 2).replace(/\n/g, "\n ")},`
51263
51369
  );
51264
51370
  console.log("});");
51265
- const getters = isRecord12(contract.getters) ? contract.getters : {};
51371
+ const getters = isRecord13(contract.getters) ? contract.getters : {};
51266
51372
  const valueGetters = Array.isArray(getters.extractedValues) ? getters.extractedValues : [];
51267
51373
  const listGetters = Array.isArray(getters.extractedLists) ? getters.extractedLists : [];
51268
- const firstGetter = [...valueGetters, ...listGetters].find(isRecord12);
51374
+ const firstGetter = [...valueGetters, ...listGetters].find(isRecord13);
51269
51375
  if (firstGetter) {
51270
51376
  const name = stringField2(firstGetter, "name") || "value";
51271
51377
  const expression = stringField2(firstGetter, "expression");
@@ -51301,7 +51407,7 @@ function printPlayLikeToolUsage(tool, requestedToolId) {
51301
51407
  }
51302
51408
  function printToolGettersOnly(tool, requestedToolId) {
51303
51409
  const contract = toolContractJsonForDescribe(tool, requestedToolId);
51304
- const getters = isRecord12(contract.getters) ? contract.getters : {};
51410
+ const getters = isRecord13(contract.getters) ? contract.getters : {};
51305
51411
  const listGetters = Array.isArray(getters.extractedLists) ? getters.extractedLists : [];
51306
51412
  const valueGetters = Array.isArray(getters.extractedValues) ? getters.extractedValues : [];
51307
51413
  console.log(`Getters: ${contract.toolId}`);
@@ -51314,7 +51420,7 @@ function printToolGettersOnly(tool, requestedToolId) {
51314
51420
  if (listGetters.length) {
51315
51421
  console.log("Lists:");
51316
51422
  for (const entry of listGetters) {
51317
- if (isRecord12(entry))
51423
+ if (isRecord13(entry))
51318
51424
  console.log(
51319
51425
  `- ${stringField2(entry, "name")}: ${playResultExpression(entry)}`
51320
51426
  );
@@ -51323,7 +51429,7 @@ function printToolGettersOnly(tool, requestedToolId) {
51323
51429
  if (valueGetters.length) {
51324
51430
  console.log("Values:");
51325
51431
  for (const entry of valueGetters) {
51326
- if (isRecord12(entry))
51432
+ if (isRecord13(entry))
51327
51433
  console.log(
51328
51434
  `- ${stringField2(entry, "name")}: ${playResultExpression(entry)}`
51329
51435
  );
@@ -51349,7 +51455,7 @@ function sampleValueForField(field) {
51349
51455
  function samplePayloadForInputFields(fields2) {
51350
51456
  return Object.fromEntries(
51351
51457
  fields2.slice(0, 4).flatMap((field) => {
51352
- if (!isRecord12(field)) return [];
51458
+ if (!isRecord13(field)) return [];
51353
51459
  const name = stringField2(field, "name");
51354
51460
  if (!name) return [];
51355
51461
  return [[name, sampleValueForField(field)]];
@@ -51479,8 +51585,8 @@ function formatListedToolCost(tool) {
51479
51585
  }
51480
51586
  function toolInputFieldsForDisplay(inputSchema) {
51481
51587
  if (Array.isArray(inputSchema.fields)) {
51482
- const fields2 = inputSchema.fields.filter(isRecord12);
51483
- if (!isRecord12(inputSchema.jsonSchema)) return fields2;
51588
+ const fields2 = inputSchema.fields.filter(isRecord13);
51589
+ if (!isRecord13(inputSchema.jsonSchema)) return fields2;
51484
51590
  const jsonSchemaFields = new Map(
51485
51591
  recursiveToolInputFieldsForDisplay({
51486
51592
  jsonSchema: inputSchema.jsonSchema
@@ -51492,26 +51598,26 @@ function toolInputFieldsForDisplay(inputSchema) {
51492
51598
  const jsonSchemaField = typeof field.name === "string" ? jsonSchemaFields.get(field.name) : void 0;
51493
51599
  const minItems = typeof field.minItems === "number" ? field.minItems : jsonSchemaField?.minItems;
51494
51600
  const maxItems = typeof field.maxItems === "number" ? field.maxItems : jsonSchemaField?.maxItems;
51495
- const items = isRecord12(field.items) ? field.items : jsonSchemaField?.items;
51601
+ const items = isRecord13(field.items) ? field.items : jsonSchemaField?.items;
51496
51602
  return {
51497
51603
  ...field,
51498
- ...isRecord12(items) ? { items } : {},
51604
+ ...isRecord13(items) ? { items } : {},
51499
51605
  ...typeof minItems === "number" ? { minItems } : {},
51500
51606
  ...typeof maxItems === "number" ? { maxItems } : {}
51501
51607
  };
51502
51608
  });
51503
51609
  }
51504
- const jsonSchema = isRecord12(inputSchema.jsonSchema) ? inputSchema.jsonSchema : inputSchema;
51505
- const properties = isRecord12(jsonSchema.properties) ? jsonSchema.properties : {};
51610
+ const jsonSchema = isRecord13(inputSchema.jsonSchema) ? inputSchema.jsonSchema : inputSchema;
51611
+ const properties = isRecord13(jsonSchema.properties) ? jsonSchema.properties : {};
51506
51612
  const required = Array.isArray(jsonSchema.required) ? new Set(jsonSchema.required.map(String)) : /* @__PURE__ */ new Set();
51507
51613
  return Object.entries(properties).map(([name, value]) => {
51508
- const property = isRecord12(value) ? value : {};
51614
+ const property = isRecord13(value) ? value : {};
51509
51615
  return {
51510
51616
  name,
51511
51617
  type: typeof property.type === "string" ? property.type : "unknown",
51512
51618
  required: required.has(name),
51513
51619
  description: property.description,
51514
- ...isRecord12(property.items) ? { items: property.items } : {},
51620
+ ...isRecord13(property.items) ? { items: property.items } : {},
51515
51621
  ...typeof property.minItems === "number" ? { minItems: property.minItems } : {},
51516
51622
  ...typeof property.maxItems === "number" ? { maxItems: property.maxItems } : {},
51517
51623
  ...Object.prototype.hasOwnProperty.call(property, "default") ? { default: property.default } : {}
@@ -51528,7 +51634,7 @@ function toolOutputFieldsForDisplay(outputSchema) {
51528
51634
  }
51529
51635
  function printToolOutputArrayShape(tool) {
51530
51636
  const outputFields = toolOutputFieldsForDisplay(
51531
- recordField2(isRecord12(tool) ? tool : {}, "outputSchema", "output_schema")
51637
+ recordField2(isRecord13(tool) ? tool : {}, "outputSchema", "output_schema")
51532
51638
  );
51533
51639
  if (outputFields.length === 0) return;
51534
51640
  console.log(" Output array shape (declared schema):");
@@ -51543,10 +51649,10 @@ function printToolOutputArrayShape(tool) {
51543
51649
  }
51544
51650
  }
51545
51651
  function canonicalToolJsonSchema(inputSchema) {
51546
- return isRecord12(inputSchema.jsonSchema) ? inputSchema.jsonSchema : inputSchema;
51652
+ return isRecord13(inputSchema.jsonSchema) ? inputSchema.jsonSchema : inputSchema;
51547
51653
  }
51548
51654
  function declaredToolJsonSchema(inputSchema) {
51549
- if (isRecord12(inputSchema.jsonSchema)) {
51655
+ if (isRecord13(inputSchema.jsonSchema)) {
51550
51656
  return inputSchema.jsonSchema;
51551
51657
  }
51552
51658
  return Array.isArray(inputSchema.fields) ? null : inputSchema;
@@ -51571,7 +51677,7 @@ function publicToolInputSchemaForDescribe(inputSchema) {
51571
51677
  };
51572
51678
  const stripDescriptions = (value) => {
51573
51679
  if (Array.isArray(value)) return value.map(stripDescriptions);
51574
- if (!isRecord12(value)) return value;
51680
+ if (!isRecord13(value)) return value;
51575
51681
  return Object.fromEntries(
51576
51682
  Object.entries(value).flatMap(([key, nested]) => {
51577
51683
  if (key === "description" && typeof nested === "string" && exposesProviderSpend(nested)) {
@@ -51592,7 +51698,7 @@ function recursiveToolInputFieldsForDisplay(inputSchema) {
51592
51698
  for (const item of value) collectSchemaIds(item);
51593
51699
  return;
51594
51700
  }
51595
- if (!isRecord12(value)) return;
51701
+ if (!isRecord13(value)) return;
51596
51702
  if (typeof value.$id === "string" && value.$id.trim()) {
51597
51703
  schemasById.set(value.$id.trim(), value);
51598
51704
  }
@@ -51605,10 +51711,10 @@ function recursiveToolInputFieldsForDisplay(inputSchema) {
51605
51711
  let current = root;
51606
51712
  for (const rawSegment of ref.slice(2).split("/")) {
51607
51713
  const segment = rawSegment.replace(/~1/g, "/").replace(/~0/g, "~");
51608
- if (!isRecord12(current)) return schema;
51714
+ if (!isRecord13(current)) return schema;
51609
51715
  current = current[segment];
51610
51716
  }
51611
- return isRecord12(current) ? current : schema;
51717
+ return isRecord13(current) ? current : schema;
51612
51718
  };
51613
51719
  const addField = (field) => {
51614
51720
  const name = typeof field.name === "string" ? field.name : "";
@@ -51623,7 +51729,7 @@ function recursiveToolInputFieldsForDisplay(inputSchema) {
51623
51729
  if (ref && activeRefs.has(ref)) return;
51624
51730
  const schema = resolveRef(unresolvedSchema);
51625
51731
  const nextActiveRefs = ref ? /* @__PURE__ */ new Set([...activeRefs, ref]) : activeRefs;
51626
- const type = Array.isArray(schema.type) ? schema.type.map(String).join("|") : typeof schema.type === "string" ? schema.type : isRecord12(schema.properties) ? "object" : schema.items ? "array" : "unknown";
51732
+ const type = Array.isArray(schema.type) ? schema.type.map(String).join("|") : typeof schema.type === "string" ? schema.type : isRecord13(schema.properties) ? "object" : schema.items ? "array" : "unknown";
51627
51733
  if (path) {
51628
51734
  addField({
51629
51735
  name: path,
@@ -51631,18 +51737,18 @@ function recursiveToolInputFieldsForDisplay(inputSchema) {
51631
51737
  required,
51632
51738
  description: schema.description,
51633
51739
  ...Array.isArray(schema.enum) ? { enum: schema.enum } : {},
51634
- ...isRecord12(schema.items) ? { items: schema.items } : {},
51740
+ ...isRecord13(schema.items) ? { items: schema.items } : {},
51635
51741
  ...typeof schema.minItems === "number" ? { minItems: schema.minItems } : {},
51636
51742
  ...typeof schema.maxItems === "number" ? { maxItems: schema.maxItems } : {},
51637
51743
  ...Object.prototype.hasOwnProperty.call(schema, "default") ? { default: schema.default } : {}
51638
51744
  });
51639
51745
  }
51640
- const properties = isRecord12(schema.properties) ? schema.properties : {};
51746
+ const properties = isRecord13(schema.properties) ? schema.properties : {};
51641
51747
  const requiredNames = new Set(
51642
51748
  Array.isArray(schema.required) ? schema.required.map(String) : []
51643
51749
  );
51644
51750
  for (const [name, value] of Object.entries(properties)) {
51645
- if (!isRecord12(value)) continue;
51751
+ if (!isRecord13(value)) continue;
51646
51752
  visit(
51647
51753
  value,
51648
51754
  path ? `${path}.${name}` : name,
@@ -51650,13 +51756,13 @@ function recursiveToolInputFieldsForDisplay(inputSchema) {
51650
51756
  nextActiveRefs
51651
51757
  );
51652
51758
  }
51653
- if (isRecord12(schema.items)) {
51759
+ if (isRecord13(schema.items)) {
51654
51760
  visit(schema.items, `${path}[]`, false, nextActiveRefs);
51655
51761
  }
51656
51762
  for (const keyword of ["anyOf", "oneOf", "allOf"]) {
51657
51763
  const branches = Array.isArray(schema[keyword]) ? schema[keyword] : [];
51658
51764
  for (const branch of branches) {
51659
- if (isRecord12(branch)) {
51765
+ if (isRecord13(branch)) {
51660
51766
  visit(branch, path, required, nextActiveRefs);
51661
51767
  }
51662
51768
  }
@@ -51666,21 +51772,21 @@ function recursiveToolInputFieldsForDisplay(inputSchema) {
51666
51772
  return fields2.size ? [...fields2.values()] : toolInputFieldsForDisplay(inputSchema);
51667
51773
  }
51668
51774
  function inputFieldJsonForDescribe(field) {
51669
- const publicItems = isRecord12(field.items) ? publicToolInputSchemaForDescribe({ items: field.items }).items : void 0;
51775
+ const publicItems = isRecord13(field.items) ? publicToolInputSchemaForDescribe({ items: field.items }).items : void 0;
51670
51776
  return {
51671
51777
  name: field.name,
51672
51778
  type: field.type ?? "unknown",
51673
51779
  required: Boolean(field.required),
51674
51780
  ...field.description ? { description: field.description } : {},
51675
- ...isRecord12(publicItems) ? { items: publicItems } : {},
51781
+ ...isRecord13(publicItems) ? { items: publicItems } : {},
51676
51782
  ...typeof field.minItems === "number" ? { minItems: field.minItems } : {},
51677
51783
  ...typeof field.maxItems === "number" ? { maxItems: field.maxItems } : {},
51678
51784
  ...Object.prototype.hasOwnProperty.call(field, "default") ? { default: field.default } : {}
51679
51785
  };
51680
51786
  }
51681
51787
  function arrayItemBoundsSuffix(field) {
51682
- const itemSchema = isRecord12(field.items) ? field.items : null;
51683
- const itemType = itemSchema ? typeof itemSchema.type === "string" ? itemSchema.type : isRecord12(itemSchema.properties) ? "object" : "unknown" : null;
51788
+ const itemSchema = isRecord13(field.items) ? field.items : null;
51789
+ const itemType = itemSchema ? typeof itemSchema.type === "string" ? itemSchema.type : isRecord13(itemSchema.properties) ? "object" : "unknown" : null;
51684
51790
  const itemEnum = Array.isArray(itemSchema?.enum) ? ` enum=${itemSchema.enum.map(String).join("|")}` : "";
51685
51791
  const itemTypeSuffix = itemType && itemType !== "unknown" ? ` items=${itemType}${itemEnum}` : "";
51686
51792
  const minItems = typeof field.minItems === "number" && Number.isFinite(field.minItems) ? field.minItems : null;
@@ -51694,13 +51800,13 @@ function arrayItemBoundsSuffix(field) {
51694
51800
  }
51695
51801
  function printToolExecutionHints(value) {
51696
51802
  const batchCapabilityRecord = recordField2(
51697
- isRecord12(value) ? value : {},
51803
+ isRecord13(value) ? value : {},
51698
51804
  "batchCapability",
51699
51805
  "batch_capability"
51700
51806
  );
51701
51807
  const batchCapability = Object.keys(batchCapabilityRecord).length > 0 ? batchCapabilityRecord : null;
51702
51808
  const executionMetadata = recordField2(
51703
- isRecord12(value) ? value : {},
51809
+ isRecord13(value) ? value : {},
51704
51810
  "executionMetadata",
51705
51811
  "execution_metadata"
51706
51812
  );
@@ -51740,7 +51846,7 @@ function printToolExecutionHints(value) {
51740
51846
  executionMetadata,
51741
51847
  "configuredRateLimits",
51742
51848
  "configured_rate_limits"
51743
- ).filter(isRecord12);
51849
+ ).filter(isRecord13);
51744
51850
  if (configuredRateLimits.length > 0) {
51745
51851
  console.log("");
51746
51852
  console.log(
@@ -51805,17 +51911,17 @@ function printJsonPreview(label, payload) {
51805
51911
  }
51806
51912
  function samplePayload(samples, key) {
51807
51913
  const entry = samples[key];
51808
- if (!isRecord12(entry)) return void 0;
51914
+ if (!isRecord13(entry)) return void 0;
51809
51915
  return Object.prototype.hasOwnProperty.call(entry, "payload") ? entry.payload : entry;
51810
51916
  }
51811
51917
  function commandEnvelopeFromRawResponse(rawResponse) {
51812
- return isRecord12(rawResponse) ? { ...rawResponse } : { status: "completed", result: rawResponse };
51918
+ return isRecord13(rawResponse) ? { ...rawResponse } : { status: "completed", result: rawResponse };
51813
51919
  }
51814
51920
  function toolExecuteExitCode(envelope) {
51815
51921
  return envelope.status === "failed" || envelope.ok === false ? 1 : 0;
51816
51922
  }
51817
51923
  function extractToolExecutionWarningMessages(rawResponse) {
51818
- if (!isRecord12(rawResponse)) return [];
51924
+ if (!isRecord13(rawResponse)) return [];
51819
51925
  const candidates = [
51820
51926
  recordField2(recordField2(rawResponse, "toolResponse"), "meta"),
51821
51927
  recordField2(
@@ -51832,7 +51938,7 @@ function extractToolExecutionWarningMessages(rawResponse) {
51832
51938
  for (const warning of warnings) {
51833
51939
  if (typeof warning === "string" && warning.trim()) {
51834
51940
  messages.push(warning.trim());
51835
- } else if (isRecord12(warning)) {
51941
+ } else if (isRecord13(warning)) {
51836
51942
  const message = stringField2(warning, "message");
51837
51943
  if (message) messages.push(message);
51838
51944
  }
@@ -51841,7 +51947,7 @@ function extractToolExecutionWarningMessages(rawResponse) {
51841
51947
  return [...new Set(messages)];
51842
51948
  }
51843
51949
  function apifySyncRecoveryNext(rawResponse) {
51844
- if (!isRecord12(rawResponse) || rawResponse.status !== "running") return null;
51950
+ if (!isRecord13(rawResponse) || rawResponse.status !== "running") return null;
51845
51951
  const toolResponse = recordField2(rawResponse, "toolResponse");
51846
51952
  const raw = recordField2(toolResponse, "raw");
51847
51953
  if (raw.state !== "awaiting_apify") return null;
@@ -51864,7 +51970,7 @@ function apifySyncRecoveryNext(rawResponse) {
51864
51970
  }
51865
51971
  function listExtractorPathsFromUsageGuidance(tool) {
51866
51972
  const toolExecutionResult = tool.usageGuidance?.toolExecutionResult;
51867
- const extractedLists = Array.isArray(toolExecutionResult?.extractedLists) ? toolExecutionResult.extractedLists : isRecord12(toolExecutionResult?.extractedLists) ? Object.values(toolExecutionResult.extractedLists) : [];
51973
+ const extractedLists = Array.isArray(toolExecutionResult?.extractedLists) ? toolExecutionResult.extractedLists : isRecord13(toolExecutionResult?.extractedLists) ? Object.values(toolExecutionResult.extractedLists) : [];
51868
51974
  return extractedLists.flatMap((entry) => {
51869
51975
  const paths = entry.details?.candidatePaths ?? entry.details?.rawToolOutputPaths;
51870
51976
  if (!Array.isArray(paths)) return [];
@@ -51880,7 +51986,7 @@ function formatDecimal(value) {
51880
51986
  function formatUsd(value) {
51881
51987
  return `$${formatDecimal(value)}`;
51882
51988
  }
51883
- function isRecord12(value) {
51989
+ function isRecord13(value) {
51884
51990
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
51885
51991
  }
51886
51992
  function stringField2(source, ...keys) {
@@ -51907,7 +52013,7 @@ function arrayField2(source, ...keys) {
51907
52013
  function recordField2(source, ...keys) {
51908
52014
  for (const key of keys) {
51909
52015
  const value = source[key];
51910
- if (isRecord12(value)) return value;
52016
+ if (isRecord13(value)) return value;
51911
52017
  }
51912
52018
  return {};
51913
52019
  }
@@ -51930,10 +52036,10 @@ function normalizeOutputFormat(raw) {
51930
52036
  function resolveAtFilePath(rawPath) {
51931
52037
  const trimmed = rawPath.trim();
51932
52038
  const resolved = resolve20(trimmed);
51933
- if (existsSync19(resolved)) return resolved;
52039
+ if (existsSync20(resolved)) return resolved;
51934
52040
  if (process.platform !== "win32" && trimmed.includes("\\")) {
51935
52041
  const normalized = resolve20(trimmed.replace(/\\/g, "/"));
51936
- if (existsSync19(normalized)) return normalized;
52042
+ if (existsSync20(normalized)) return normalized;
51937
52043
  }
51938
52044
  return resolved;
51939
52045
  }
@@ -51944,7 +52050,7 @@ function readJsonArgument(raw, flagName) {
51944
52050
  throw new Error(`Invalid ${flagName} value: empty @file path.`);
51945
52051
  }
51946
52052
  try {
51947
- return readFileSync22(resolveAtFilePath(filePath), "utf8").replace(
52053
+ return readFileSync23(resolveAtFilePath(filePath), "utf8").replace(
51948
52054
  /^\uFEFF/,
51949
52055
  ""
51950
52056
  );
@@ -51973,7 +52079,7 @@ function parseJsonObjectArgument(raw, flagName) {
51973
52079
  }
51974
52080
  throw invalidJsonError(flagName, message);
51975
52081
  }
51976
- if (!isRecord12(parsed)) {
52082
+ if (!isRecord13(parsed)) {
51977
52083
  throw invalidJsonError(flagName, "expected an object.");
51978
52084
  }
51979
52085
  return parsed;
@@ -52080,70 +52186,6 @@ function parseToolExecuteTimeout(raw) {
52080
52186
  }
52081
52187
  return timeoutMs;
52082
52188
  }
52083
- function pendingToolExecutionPath(input2) {
52084
- const config = resolveConfig();
52085
- const fingerprint = createHash7("sha256").update(config.baseUrl).update("\0").update(createHash7("sha256").update(config.apiKey).digest("hex")).update("\0").update(input2.toolId).update("\0").update(stableStringify(input2.params)).update("\0").update(input2.responseIntent).digest("hex");
52086
- return join26(
52087
- sdkCliStateDirPath(resolveConfig().baseUrl),
52088
- `pending-tool-execution-${fingerprint}.json`
52089
- );
52090
- }
52091
- function loadOrCreatePendingToolExecution(path) {
52092
- mkdirSync16(dirname20(path), { recursive: true });
52093
- if (existsSync19(path)) {
52094
- return readPendingToolExecution(path);
52095
- }
52096
- const idempotencyKey = randomUUID9();
52097
- const temporaryPath = `${path}.${process.pid}.${randomUUID9()}.tmp`;
52098
- try {
52099
- writeFileSync20(temporaryPath, `${JSON.stringify({ idempotencyKey })}
52100
- `, {
52101
- encoding: "utf8",
52102
- flag: "wx",
52103
- mode: 384
52104
- });
52105
- linkSync(temporaryPath, path);
52106
- return idempotencyKey;
52107
- } catch (error) {
52108
- if (error.code !== "EEXIST") throw error;
52109
- return readPendingToolExecution(path);
52110
- } finally {
52111
- if (existsSync19(temporaryPath)) unlinkSync4(temporaryPath);
52112
- }
52113
- }
52114
- function readPendingToolExecution(path) {
52115
- const saved = JSON.parse(readFileSync22(path, "utf8"));
52116
- if (typeof saved.idempotencyKey !== "string") {
52117
- throw new Error(
52118
- `Cannot resume the saved tool execution at ${path}: invalid recovery key.`
52119
- );
52120
- }
52121
- return saved.idempotencyKey;
52122
- }
52123
- async function completePendingToolExecution(path, idempotencyKey) {
52124
- if (!path || !idempotencyKey || !existsSync19(path)) return;
52125
- await new Promise((resolve22, reject) => {
52126
- const onError = (error) => {
52127
- process.stdout.off("error", onError);
52128
- reject(error);
52129
- };
52130
- process.stdout.once("error", onError);
52131
- process.stdout.write("", (error) => {
52132
- process.stdout.off("error", onError);
52133
- if (error) {
52134
- reject(error);
52135
- } else {
52136
- resolve22();
52137
- }
52138
- });
52139
- });
52140
- try {
52141
- if (readPendingToolExecution(path) !== idempotencyKey) return;
52142
- unlinkSync4(path);
52143
- } catch (error) {
52144
- if (error.code !== "ENOENT") throw error;
52145
- }
52146
- }
52147
52189
  function safeFileStem(value) {
52148
52190
  return value.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "tool";
52149
52191
  }
@@ -52167,9 +52209,9 @@ function starterScriptJson(script) {
52167
52209
  function seedToolListScript(input2) {
52168
52210
  const stem = safeFileStem(input2.toolId);
52169
52211
  const fileName = `${stem}-workflow-seed-${Date.now()}.play.ts`;
52170
- const scriptDir = mkdtempSync(join26(tmpdir6(), "deepline-workflow-seed-"));
52212
+ const scriptDir = mkdtempSync(join27(tmpdir6(), "deepline-workflow-seed-"));
52171
52213
  chmodSync(scriptDir, 448);
52172
- const scriptPath = join26(scriptDir, fileName);
52214
+ const scriptPath = join27(scriptDir, fileName);
52173
52215
  const projectDir = `deepline/projects/${stem}-workflow`;
52174
52216
  const playName = `${stem}-workflow`;
52175
52217
  const sampleRows = input2.rows.length > 0 ? `${JSON.stringify(input2.rows.slice(0, 2)).replace(/\]$/, "")}, ...]` : "[]";
@@ -52212,7 +52254,7 @@ export default definePlay(${JSON.stringify(playName)}, async (ctx) => {
52212
52254
  description: ${JSON.stringify(`Seed ${input2.toolId} rows into a Deepline workflow-ready dataset.`)},
52213
52255
  });
52214
52256
  `;
52215
- writeFileSync20(scriptPath, script, { encoding: "utf-8", mode: 384 });
52257
+ writeFileSync21(scriptPath, script, { encoding: "utf-8", mode: 384 });
52216
52258
  return {
52217
52259
  path: scriptPath,
52218
52260
  sourceCode: script,
@@ -52239,7 +52281,7 @@ function buildToolExecuteBaseEnvelope(input2) {
52239
52281
  kind: summaryEntries.length > 0 ? "object" : "raw",
52240
52282
  summary: input2.summary
52241
52283
  };
52242
- const envelopeHasCanonicalOutput = isRecord12(envelope.toolResponse) && Object.prototype.hasOwnProperty.call(envelope.toolResponse, "raw");
52284
+ const envelopeHasCanonicalOutput = isRecord13(envelope.toolResponse) && Object.prototype.hasOwnProperty.call(envelope.toolResponse, "raw");
52243
52285
  const envelopeHasDeclaredOutput = Object.prototype.hasOwnProperty.call(
52244
52286
  envelope,
52245
52287
  "output"
@@ -52266,7 +52308,7 @@ function buildToolExecuteBaseEnvelope(input2) {
52266
52308
  return {
52267
52309
  ...envelope,
52268
52310
  ...input2.idempotencyKey ? { idempotency_key: input2.idempotencyKey } : {},
52269
- ...isRecord12(input2.rawResponse) && isRecord12(input2.rawResponse.executionRecovery) ? { execution_recovery: input2.rawResponse.executionRecovery } : {},
52311
+ ...isRecord13(input2.rawResponse) && isRecord13(input2.rawResponse.executionRecovery) ? { execution_recovery: input2.rawResponse.executionRecovery } : {},
52270
52312
  ...envelopeHasCanonicalOutput || envelopeHasDeclaredOutput ? { output_preview: outputPreview } : { output: outputPreview },
52271
52313
  ...summaryEntries.length > 0 ? { summary: input2.summary } : {},
52272
52314
  ...warningMessages.length > 0 ? { warnings: warningMessages } : {},
@@ -52325,7 +52367,7 @@ function buildToolExecuteRowArtifactEnvelope(input2) {
52325
52367
  void _render;
52326
52368
  void _next;
52327
52369
  void _local;
52328
- const billingLookup = isRecord12(input2.baseEnvelope.next) && typeof input2.baseEnvelope.next.billing === "string" ? input2.baseEnvelope.next.billing : null;
52370
+ const billingLookup = isRecord13(input2.baseEnvelope.next) && typeof input2.baseEnvelope.next.billing === "string" ? input2.baseEnvelope.next.billing : null;
52329
52371
  return {
52330
52372
  ...base,
52331
52373
  status: typeof base.status === "string" ? base.status : "completed",
@@ -52454,17 +52496,15 @@ async function executeTool(args) {
52454
52496
  }
52455
52497
  return 2;
52456
52498
  }
52457
- let idempotencyKey = parsed.idempotencyKey;
52458
- let pendingRecoveryPath = null;
52459
52499
  const responseIntent = parsed.outPath || parsed.outputFormat === "csv" || parsed.outputFormat === "csv_file" ? "row_artifact" : "raw";
52460
- if (parsed.recover && !idempotencyKey) {
52461
- pendingRecoveryPath = pendingToolExecutionPath({
52462
- toolId: parsed.toolId,
52463
- params: parsed.params,
52464
- responseIntent
52465
- });
52466
- idempotencyKey = loadOrCreatePendingToolExecution(pendingRecoveryPath);
52467
- }
52500
+ const recovery = ToolCallRecovery.open({
52501
+ toolId: parsed.toolId,
52502
+ params: parsed.params,
52503
+ responseIntent,
52504
+ recover: parsed.recover,
52505
+ idempotencyKey: parsed.idempotencyKey
52506
+ });
52507
+ const { idempotencyKey } = recovery;
52468
52508
  if (idempotencyKey) {
52469
52509
  console.error(`Tool execution recovery key: ${idempotencyKey}`);
52470
52510
  }
@@ -52489,42 +52529,12 @@ async function executeTool(args) {
52489
52529
  summary
52490
52530
  });
52491
52531
  const executeExitCode = toolExecuteExitCode(baseEnvelope);
52492
- if (!parsed.outPath && (parsed.outputFormat === "json" || parsed.outputFormat === "auto" && shouldEmitJson())) {
52493
- printCommandEnvelope(baseEnvelope, { json: true });
52494
- await completePendingToolExecution(pendingRecoveryPath, idempotencyKey);
52495
- return executeExitCode;
52496
- }
52497
- if (parsed.outputFormat === "json_file") {
52498
- const jsonPath = writeJsonOutputFile(
52499
- rawResponse,
52500
- `payload_${parsed.toolId}`
52501
- );
52502
- printCommandEnvelope(
52503
- {
52504
- ...baseEnvelope,
52505
- local: {
52506
- ...isRecord12(baseEnvelope.local) ? baseEnvelope.local : {},
52507
- payload_file: jsonPath
52508
- }
52509
- },
52510
- { json: true }
52511
- );
52512
- await completePendingToolExecution(pendingRecoveryPath, idempotencyKey);
52513
- return executeExitCode;
52514
- }
52515
- if (!listConversion) {
52516
- if (parsed.outPath) {
52517
- const error = new Error(
52518
- `${parsed.toolId} did not expose row-shaped output to write as CSV. Re-run with --json to inspect the raw tool response.`
52519
- );
52520
- if (argsWantJson(args)) {
52521
- printJsonError(error);
52522
- } else {
52523
- console.error(error.message);
52524
- }
52525
- return 1;
52532
+ const delivered = (() => {
52533
+ if (!parsed.outPath && (parsed.outputFormat === "json" || parsed.outputFormat === "auto" && shouldEmitJson())) {
52534
+ printCommandEnvelope(baseEnvelope, { json: true });
52535
+ return true;
52526
52536
  }
52527
- if (parsed.outputFormat === "csv" || parsed.outputFormat === "csv_file") {
52537
+ if (parsed.outputFormat === "json_file") {
52528
52538
  const jsonPath = writeJsonOutputFile(
52529
52539
  rawResponse,
52530
52540
  `payload_${parsed.toolId}`
@@ -52533,68 +52543,94 @@ async function executeTool(args) {
52533
52543
  {
52534
52544
  ...baseEnvelope,
52535
52545
  local: {
52546
+ ...isRecord13(baseEnvelope.local) ? baseEnvelope.local : {},
52536
52547
  payload_file: jsonPath
52537
52548
  }
52538
52549
  },
52539
- { json: parsed.outputFormat === "csv_file" || shouldEmitJson() }
52550
+ { json: true }
52540
52551
  );
52541
- await completePendingToolExecution(pendingRecoveryPath, idempotencyKey);
52542
- return executeExitCode;
52552
+ return true;
52543
52553
  }
52544
- printCommandEnvelope(baseEnvelope, { json: false });
52545
- await completePendingToolExecution(pendingRecoveryPath, idempotencyKey);
52546
- return executeExitCode;
52547
- }
52548
- const rowOutput = projectRowOutput(listConversion);
52549
- const csv = writeCsvOutputFile(
52550
- listConversion.rows,
52551
- `${parsed.toolId}_output`,
52552
- parsed.outPath ? { outPath: parsed.outPath } : void 0
52553
- );
52554
- const seededScript = seedToolListScript({
52555
- toolId: parsed.toolId,
52556
- payload: parsed.params,
52557
- rows: listConversion.rows
52558
- });
52559
- const materializedEnvelope = buildToolExecuteRowArtifactEnvelope({
52560
- baseEnvelope,
52561
- csv,
52562
- rowOutput,
52563
- summary,
52564
- seededScript
52565
- });
52566
- if (parsed.outputFormat === "csv_file") {
52567
- printCommandEnvelope(materializedEnvelope, { json: true });
52568
- await completePendingToolExecution(pendingRecoveryPath, idempotencyKey);
52569
- return executeExitCode;
52570
- }
52571
- if (parsed.outPath) {
52572
- printCommandEnvelope(materializedEnvelope, {
52573
- json: argsWantJson(args) || shouldEmitJson(),
52574
- text: `Wrote ${csv.rowCount} row(s) to ${csv.path}
52575
- `
52576
- });
52577
- await completePendingToolExecution(pendingRecoveryPath, idempotencyKey);
52578
- return executeExitCode;
52579
- }
52580
- if (parsed.noPreview) {
52581
- printCommandEnvelope(
52582
- {
52583
- ...materializedEnvelope,
52584
- local: {
52585
- ...materializedEnvelope.local ?? {},
52586
- output_path: csv.path
52554
+ if (!listConversion) {
52555
+ if (parsed.outPath) {
52556
+ const error = new Error(
52557
+ `${parsed.toolId} did not expose row-shaped output to write as CSV. Re-run with --json to inspect the raw tool response.`
52558
+ );
52559
+ if (argsWantJson(args)) {
52560
+ printJsonError(error);
52561
+ } else {
52562
+ console.error(error.message);
52587
52563
  }
52588
- },
52589
- { json: shouldEmitJson(), text: `${csv.path}
52590
- ` }
52564
+ return false;
52565
+ }
52566
+ if (parsed.outputFormat === "csv" || parsed.outputFormat === "csv_file") {
52567
+ const jsonPath = writeJsonOutputFile(
52568
+ rawResponse,
52569
+ `payload_${parsed.toolId}`
52570
+ );
52571
+ printCommandEnvelope(
52572
+ {
52573
+ ...baseEnvelope,
52574
+ local: {
52575
+ payload_file: jsonPath
52576
+ }
52577
+ },
52578
+ { json: parsed.outputFormat === "csv_file" || shouldEmitJson() }
52579
+ );
52580
+ return true;
52581
+ }
52582
+ printCommandEnvelope(baseEnvelope, { json: false });
52583
+ return true;
52584
+ }
52585
+ const rowOutput = projectRowOutput(listConversion);
52586
+ const csv = writeCsvOutputFile(
52587
+ listConversion.rows,
52588
+ `${parsed.toolId}_output`,
52589
+ parsed.outPath ? { outPath: parsed.outPath } : void 0
52591
52590
  );
52592
- await completePendingToolExecution(pendingRecoveryPath, idempotencyKey);
52593
- return executeExitCode;
52594
- }
52595
- printCommandEnvelope(materializedEnvelope, { json: false });
52596
- await completePendingToolExecution(pendingRecoveryPath, idempotencyKey);
52597
- return executeExitCode;
52591
+ const seededScript = seedToolListScript({
52592
+ toolId: parsed.toolId,
52593
+ payload: parsed.params,
52594
+ rows: listConversion.rows
52595
+ });
52596
+ const materializedEnvelope = buildToolExecuteRowArtifactEnvelope({
52597
+ baseEnvelope,
52598
+ csv,
52599
+ rowOutput,
52600
+ summary,
52601
+ seededScript
52602
+ });
52603
+ if (parsed.outputFormat === "csv_file") {
52604
+ printCommandEnvelope(materializedEnvelope, { json: true });
52605
+ return true;
52606
+ }
52607
+ if (parsed.outPath) {
52608
+ printCommandEnvelope(materializedEnvelope, {
52609
+ json: argsWantJson(args) || shouldEmitJson(),
52610
+ text: `Wrote ${csv.rowCount} row(s) to ${csv.path}
52611
+ `
52612
+ });
52613
+ return true;
52614
+ }
52615
+ if (parsed.noPreview) {
52616
+ printCommandEnvelope(
52617
+ {
52618
+ ...materializedEnvelope,
52619
+ local: {
52620
+ ...materializedEnvelope.local ?? {},
52621
+ output_path: csv.path
52622
+ }
52623
+ },
52624
+ { json: shouldEmitJson(), text: `${csv.path}
52625
+ ` }
52626
+ );
52627
+ return true;
52628
+ }
52629
+ printCommandEnvelope(materializedEnvelope, { json: false });
52630
+ return true;
52631
+ })();
52632
+ if (delivered) await recovery.acknowledgeDelivery();
52633
+ return delivered ? executeExitCode : 1;
52598
52634
  }
52599
52635
 
52600
52636
  // src/cli/commands/providers.ts
@@ -52676,7 +52712,7 @@ Examples:
52676
52712
 
52677
52713
  // src/cli/commands/workflow.ts
52678
52714
  import { mkdir as mkdir6, readFile as readFile7, writeFile as writeFile5 } from "fs/promises";
52679
- import { dirname as dirname21, join as join27, resolve as resolve21 } from "path";
52715
+ import { dirname as dirname22, join as join28, resolve as resolve21 } from "path";
52680
52716
 
52681
52717
  // src/cli/workflow-to-play.ts
52682
52718
  import { createHash as createHash8 } from "crypto";
@@ -52927,8 +52963,8 @@ async function transformOne(api, workflowId, outDir, publish) {
52927
52963
  revision.config,
52928
52964
  { workflowName: workflow.name, version: revision.version }
52929
52965
  );
52930
- const file = join27(resolve21(outDir), `${compiled.playName}.play.ts`);
52931
- await mkdir6(dirname21(file), { recursive: true });
52966
+ const file = join28(resolve21(outDir), `${compiled.playName}.play.ts`);
52967
+ await mkdir6(dirname22(file), { recursive: true });
52932
52968
  await writeFile5(file, compiled.sourceCode, "utf8");
52933
52969
  let published = false;
52934
52970
  if (publish) {
@@ -53474,8 +53510,8 @@ function topLevelCommandKnown(program, commandName) {
53474
53510
  );
53475
53511
  }
53476
53512
  async function runPlayRunnerHealthCheck() {
53477
- const dir = await mkdtemp4(join28(tmpdir7(), "deepline-health-play-"));
53478
- const file = join28(dir, "health-check.play.ts");
53513
+ const dir = await mkdtemp4(join29(tmpdir7(), "deepline-health-play-"));
53514
+ const file = join29(dir, "health-check.play.ts");
53479
53515
  try {
53480
53516
  await writeFile6(
53481
53517
  file,