deepline 0.3.294 → 0.3.295

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/bundling-sources/sdk/src/compat.ts +35 -7
  2. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  3. package/dist/bundling-sources/shared_libs/play-runtime/tool-http-errors.ts +14 -1
  4. package/dist/cli/auth-EDTRERZP.mjs +31 -0
  5. package/dist/cli/auth-TDHKB277.js +31 -0
  6. package/dist/cli/billing-ELIDPILY.js +1749 -0
  7. package/dist/cli/billing-EXGXJVAU.mjs +1749 -0
  8. package/dist/cli/chunk-2S5Y3TZP.js +5688 -0
  9. package/dist/cli/chunk-3KC45UVF.js +150 -0
  10. package/dist/cli/chunk-3XX5TEA4.js +15 -0
  11. package/dist/cli/chunk-4MBOJQPL.mjs +0 -0
  12. package/dist/cli/chunk-4NEFYBF7.js +2240 -0
  13. package/dist/cli/chunk-5JLQPVNX.js +3056 -0
  14. package/dist/cli/chunk-5KDKFHZI.js +1269 -0
  15. package/dist/cli/chunk-6A3TJUWC.js +76 -0
  16. package/dist/cli/chunk-6O5YZOVN.mjs +890 -0
  17. package/dist/cli/chunk-7P5AA3SN.js +344 -0
  18. package/dist/cli/chunk-AYHLUHE5.js +52 -0
  19. package/dist/cli/chunk-CBVIJSHF.mjs +560 -0
  20. package/dist/cli/chunk-CFVVCN4A.js +735 -0
  21. package/dist/cli/chunk-COGTRVWW.js +30 -0
  22. package/dist/cli/chunk-D4AZUZO4.js +190 -0
  23. package/dist/cli/chunk-DLIRSHV6.mjs +28 -0
  24. package/dist/cli/chunk-EACVZI6N.mjs +1995 -0
  25. package/dist/cli/chunk-EDWJY6T4.mjs +3056 -0
  26. package/dist/cli/chunk-EXMLR72R.mjs +0 -0
  27. package/dist/cli/chunk-F35VOIQL.js +890 -0
  28. package/dist/cli/chunk-GAMFK2ZP.mjs +148 -0
  29. package/dist/cli/chunk-GHRQQPW2.mjs +2240 -0
  30. package/dist/cli/chunk-GONRLVV3.js +3440 -0
  31. package/dist/cli/chunk-GVUJJJ5G.mjs +76 -0
  32. package/dist/cli/chunk-H7HIDGZ7.mjs +150 -0
  33. package/dist/cli/chunk-HUZXWOSK.mjs +503 -0
  34. package/dist/cli/chunk-I5YZLGMG.js +1 -0
  35. package/dist/cli/chunk-ITOFSXIU.mjs +15 -0
  36. package/dist/cli/chunk-J5NA2TTX.js +503 -0
  37. package/dist/cli/chunk-JCS5TPNY.mjs +3440 -0
  38. package/dist/cli/chunk-JNNOCMQY.js +47 -0
  39. package/dist/cli/chunk-KRD6H754.mjs +30 -0
  40. package/dist/cli/chunk-LA46MMTL.js +560 -0
  41. package/dist/cli/chunk-LDWT7RJK.mjs +190 -0
  42. package/dist/cli/chunk-M2V26OR5.js +499 -0
  43. package/dist/cli/chunk-MIMASXO4.mjs +389 -0
  44. package/dist/cli/chunk-MROPCKW2.mjs +190 -0
  45. package/dist/cli/chunk-NXDRDJ4K.js +389 -0
  46. package/dist/cli/chunk-NXGCO4JB.mjs +344 -0
  47. package/dist/cli/chunk-OG64RBAC.js +6 -0
  48. package/dist/cli/chunk-OQYEC4GL.mjs +34 -0
  49. package/dist/cli/chunk-OWJZUE3Y.mjs +103 -0
  50. package/dist/cli/chunk-SDK3ZA2C.js +103 -0
  51. package/dist/cli/chunk-SFLARO4Y.mjs +47 -0
  52. package/dist/cli/chunk-SVIIIYIQ.js +923 -0
  53. package/dist/cli/chunk-TAC3JIFE.mjs +354 -0
  54. package/dist/cli/chunk-U3PI7HBM.js +34 -0
  55. package/dist/cli/chunk-UFS752TU.mjs +52 -0
  56. package/dist/cli/chunk-UI37DQE7.mjs +499 -0
  57. package/dist/cli/chunk-UNEMDKXN.js +1 -0
  58. package/dist/cli/chunk-WB6Z2Q44.mjs +1622 -0
  59. package/dist/cli/chunk-WJYPBHTE.js +148 -0
  60. package/dist/cli/chunk-WOHBA5PV.js +354 -0
  61. package/dist/cli/chunk-WQICC2B3.js +190 -0
  62. package/dist/cli/chunk-WZYKRD7T.mjs +6 -0
  63. package/dist/cli/chunk-XL2FO6CW.mjs +5688 -0
  64. package/dist/cli/chunk-XNYIZMNQ.js +28 -0
  65. package/dist/cli/chunk-XRK2TZT5.js +1995 -0
  66. package/dist/cli/chunk-YJYPL5OK.mjs +1269 -0
  67. package/dist/cli/chunk-YWNDYCXR.mjs +735 -0
  68. package/dist/cli/chunk-YWWAF7KZ.mjs +923 -0
  69. package/dist/cli/chunk-ZDO3TO3M.js +1622 -0
  70. package/dist/cli/client-4JVOYVC5.js +20 -0
  71. package/dist/cli/client-EEN2IJN2.mjs +20 -0
  72. package/dist/cli/csv-BOHBEP2I.mjs +585 -0
  73. package/dist/cli/csv-S5NYRUEX.js +585 -0
  74. package/dist/cli/db-CLODWCOB.mjs +486 -0
  75. package/dist/cli/db-F6PKFOOV.js +486 -0
  76. package/dist/cli/executions-5TQAKLJU.js +28 -0
  77. package/dist/cli/executions-MAKW6QOY.mjs +28 -0
  78. package/dist/cli/feedback-GV4QJFEN.js +107 -0
  79. package/dist/cli/feedback-XY24TW7H.mjs +107 -0
  80. package/dist/cli/getting-started.js +18 -76
  81. package/dist/cli/getting-started.mjs +10 -37
  82. package/dist/cli/git-6S2C22T5.js +23 -0
  83. package/dist/cli/git-OZLBD5HH.mjs +23 -0
  84. package/dist/cli/index.js +291 -54294
  85. package/dist/cli/index.mjs +209 -54352
  86. package/dist/cli/legacy-noops-LLCGDPQE.js +157 -0
  87. package/dist/cli/legacy-noops-TYH3TW2D.mjs +157 -0
  88. package/dist/cli/monitors-CABMB4DW.js +3251 -0
  89. package/dist/cli/monitors-TTD55HMK.mjs +3251 -0
  90. package/dist/cli/org-MSF3RG76.js +849 -0
  91. package/dist/cli/org-SFJ77MWY.mjs +849 -0
  92. package/dist/cli/play-NXHJSCKL.mjs +18439 -0
  93. package/dist/cli/play-OKSFNNO4.js +18439 -0
  94. package/dist/cli/providers-QC2ERERL.js +95 -0
  95. package/dist/cli/providers-TIIAZEUA.mjs +95 -0
  96. package/dist/cli/proxy-env-EBANZHPV.js +161 -0
  97. package/dist/cli/proxy-env-M4ZHXHRL.mjs +161 -0
  98. package/dist/cli/quickstart-ICANHLMI.js +69 -0
  99. package/dist/cli/quickstart-KWUOP3FI.mjs +69 -0
  100. package/dist/cli/search-U5H2FDOO.mjs +18 -0
  101. package/dist/cli/search-XQRQOLWS.js +18 -0
  102. package/dist/cli/secrets-3J6YTWFA.mjs +400 -0
  103. package/dist/cli/secrets-YNMNZNOM.js +400 -0
  104. package/dist/cli/sessions-CLEES4L6.mjs +15 -0
  105. package/dist/cli/sessions-J6VR47FG.js +15 -0
  106. package/dist/cli/settings-EEKZMTY4.js +846 -0
  107. package/dist/cli/settings-UVLOQZRH.mjs +846 -0
  108. package/dist/cli/setup-DLMDXPGJ.mjs +1257 -0
  109. package/dist/cli/setup-HC4Q7QM4.js +1257 -0
  110. package/dist/cli/skills-33PHFBSB.mjs +28 -0
  111. package/dist/cli/skills-LFRY3KPX.js +28 -0
  112. package/dist/cli/tools-3COEPKML.mjs +2955 -0
  113. package/dist/cli/tools-QXEVCN45.js +2955 -0
  114. package/dist/cli/update-LSAC4FF5.mjs +28 -0
  115. package/dist/cli/update-NXHSPYXA.js +28 -0
  116. package/dist/cli/workflow-7S44OECF.mjs +1936 -0
  117. package/dist/cli/workflow-QPZWYSZE.js +1936 -0
  118. package/dist/helpers.js +6 -32
  119. package/dist/helpers.mjs +2 -0
  120. package/dist/index.js +1972 -12825
  121. package/dist/index.mjs +1910 -12672
  122. package/dist/install-integrity.json +110 -0
  123. package/dist/monitor-fleet-contract.js +31 -730
  124. package/dist/monitor-fleet-contract.mjs +18 -667
  125. package/dist/monitor-input-contract.js +10 -390
  126. package/dist/monitor-input-contract.mjs +7 -348
  127. package/dist/plays/bundle-play-file.mjs +13 -5178
  128. package/dist/plays/csv-data-input.js +5 -3132
  129. package/dist/plays/csv-data-input.mjs +5 -3105
  130. package/dist/plays/run-request.js +56 -664
  131. package/dist/plays/run-request.mjs +30 -588
  132. package/dist/release.d.mts +1 -1
  133. package/dist/release.d.ts +1 -1
  134. package/dist/release.js +5 -212
  135. package/dist/release.mjs +5 -185
  136. package/package.json +1 -1
@@ -0,0 +1,1995 @@
1
+ import {
2
+ apiErrorCodeFromResponse,
3
+ apiErrorMessage
4
+ } from "./chunk-DLIRSHV6.mjs";
5
+ import {
6
+ SDK_RELEASE
7
+ } from "./chunk-LDWT7RJK.mjs";
8
+ import {
9
+ DeeplineError,
10
+ TOOL_EXECUTION_ERROR_SCHEMA_VERSION,
11
+ ToolExecutionError,
12
+ brandAsProviderTransientError,
13
+ brandAsToolExecutionError,
14
+ deserializeToolExecutionFailure,
15
+ isProviderTransientFailure,
16
+ serializeToolExecutionFailure
17
+ } from "./chunk-NXGCO4JB.mjs";
18
+
19
+ // src/errors.ts
20
+ var AuthError = class extends DeeplineError {
21
+ /** Constructed by the SDK when Deepline rejects the caller's credentials. */
22
+ constructor(message = "Authentication failed. Check your DEEPLINE_API_KEY.") {
23
+ super(message, 401, "AUTH_ERROR");
24
+ this.name = "AuthError";
25
+ }
26
+ };
27
+ var RateLimitError = class extends DeeplineError {
28
+ /** Milliseconds to wait before retrying, from the `Retry-After` response header. Defaults to 5000. */
29
+ retryAfterMs;
30
+ /** Constructed by the SDK after exhausting HTTP-level rate-limit retries. */
31
+ constructor(retryAfterMs = 5e3, message) {
32
+ super(
33
+ message ?? `Rate limited. Retry after ${retryAfterMs}ms.`,
34
+ 429,
35
+ "RATE_LIMIT"
36
+ );
37
+ this.name = "RateLimitError";
38
+ this.retryAfterMs = retryAfterMs;
39
+ }
40
+ };
41
+ var ToolRateLimitError = class extends RateLimitError {
42
+ /** Public tool id passed to `tools.execute`. */
43
+ toolId;
44
+ /** Provider responsible for the operation, or `null`. */
45
+ provider;
46
+ /** Provider operation name, or `null`. */
47
+ operation;
48
+ /** Stable machine-readable failure code when one exists. */
49
+ code;
50
+ /** Boundary responsible for the failure. */
51
+ origin;
52
+ /** Stable reason family for policy and diagnostics. */
53
+ category;
54
+ /** Whether repeating the same semantic call is delivery-safe. */
55
+ retryable;
56
+ /** Provider or Deepline request id, or `null`. */
57
+ requestId;
58
+ /** Network failure kind, or `null` for non-network failures. */
59
+ networkKind;
60
+ /** Network boundary that failed, or `null` for non-network failures. */
61
+ networkScope;
62
+ /** Explicitly allowlisted diagnostics safe for SDK callers. */
63
+ publicDetails;
64
+ /** Constructed by the SDK after a structured tool HTTP 429. */
65
+ constructor(message, options) {
66
+ super(options.retryAfterMs ?? 5e3, message);
67
+ this.name = "ToolRateLimitError";
68
+ this.statusCode = options.statusCode ?? 429;
69
+ this.code = options.code ?? void 0;
70
+ this.toolId = options.toolId;
71
+ this.provider = options.provider;
72
+ this.operation = options.operation;
73
+ this.origin = options.origin;
74
+ this.category = options.category;
75
+ this.retryable = options.retryable;
76
+ this.requestId = options.requestId;
77
+ this.networkKind = options.networkKind;
78
+ this.networkScope = options.networkScope;
79
+ this.publicDetails = options.publicDetails ?? null;
80
+ this.details = options.details;
81
+ brandAsToolExecutionError(this);
82
+ if (isProviderTransientFailure(this)) {
83
+ brandAsProviderTransientError(this);
84
+ }
85
+ }
86
+ };
87
+ var ConfigError = class extends DeeplineError {
88
+ /** Construct a local SDK configuration failure. */
89
+ constructor(message) {
90
+ super(message, void 0, "CONFIG_ERROR");
91
+ this.name = "ConfigError";
92
+ }
93
+ };
94
+
95
+ // src/config.ts
96
+ import {
97
+ existsSync,
98
+ mkdirSync,
99
+ readdirSync,
100
+ realpathSync,
101
+ readFileSync,
102
+ statSync,
103
+ writeFileSync
104
+ } from "fs";
105
+ import { homedir } from "os";
106
+ import { dirname, isAbsolute, join, resolve } from "path";
107
+ var HOST_URL_ENV = "DEEPLINE_HOST_URL";
108
+ var API_KEY_ENV = "DEEPLINE_API_KEY";
109
+ var ACTIVE_ORG_ID_ENV = "DEEPLINE_ACTIVE_ORG_ID";
110
+ var ACTIVE_ORG_NAME_ENV = "DEEPLINE_ACTIVE_ORG_NAME";
111
+ var FEATURES_ENV = "DEEPLINE_FEATURES";
112
+ var PROD_URL = "https://code.deepline.com";
113
+ var DEFAULT_TIMEOUT = 6e4;
114
+ var DEFAULT_MAX_RETRIES = 3;
115
+ var PROJECT_DEEPLINE_ENV_FILE = ".env.deepline";
116
+ var COWORK_IGNORED_WORKSPACE_DIRS = /* @__PURE__ */ new Set([
117
+ ".auto-memory",
118
+ ".claude",
119
+ ".remote-plugins",
120
+ "outputs",
121
+ "plugins",
122
+ "uploads"
123
+ ]);
124
+ var COWORK_PROJECT_MARKERS = [
125
+ ".deepline",
126
+ ".env.deepline",
127
+ ".git",
128
+ "AGENTS.md",
129
+ "package.json",
130
+ "pyproject.toml"
131
+ ];
132
+ var CLI_ENV_ALLOWED_KEYS = /* @__PURE__ */ new Set([
133
+ HOST_URL_ENV,
134
+ API_KEY_ENV,
135
+ ACTIVE_ORG_ID_ENV,
136
+ ACTIVE_ORG_NAME_ENV,
137
+ FEATURES_ENV
138
+ ]);
139
+ function featureEnvValues(data) {
140
+ if (!Array.isArray(data.features)) return {};
141
+ return {
142
+ [FEATURES_ENV]: data.features.filter(
143
+ (key) => typeof key === "string" && key.trim() !== ""
144
+ ).map((key) => key.trim()).join(",")
145
+ };
146
+ }
147
+ function storedHostApiKey(baseUrl) {
148
+ return loadCliEnv(normalizeBaseUrl(baseUrl) || baseUrl)[API_KEY_ENV] ?? "";
149
+ }
150
+ function storedHostFeatures(baseUrl) {
151
+ return loadCliEnv(normalizeBaseUrl(baseUrl) || baseUrl)[FEATURES_ENV];
152
+ }
153
+ function baseUrlSlug(baseUrl) {
154
+ let url;
155
+ try {
156
+ url = new URL(baseUrl);
157
+ } catch {
158
+ return "unknown";
159
+ }
160
+ const host = url.hostname || "unknown";
161
+ const port = url.port ? Number.parseInt(url.port, 10) : null;
162
+ let slug = host.replace(/[^a-zA-Z0-9]/g, "-");
163
+ if (port && port !== 80 && port !== 443) {
164
+ slug = `${slug}-${port}`;
165
+ }
166
+ return slug.toLowerCase().replace(/^-+|-+$/g, "");
167
+ }
168
+ function parseEnvFile(filePath) {
169
+ if (!existsSync(filePath)) return {};
170
+ const env = {};
171
+ const content = readFileSync(filePath, "utf-8");
172
+ for (const line of content.split(/\r?\n/)) {
173
+ const trimmed = line.trim();
174
+ if (!trimmed || trimmed.startsWith("#")) continue;
175
+ const eqIndex = trimmed.indexOf("=");
176
+ if (eqIndex < 0) continue;
177
+ const key = trimmed.slice(0, eqIndex).trim();
178
+ let value = trimmed.slice(eqIndex + 1).trim();
179
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
180
+ try {
181
+ value = JSON.parse(value);
182
+ } catch {
183
+ value = value.slice(1, -1);
184
+ }
185
+ } else if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
186
+ value = value.slice(1, -1);
187
+ }
188
+ if (key && value) {
189
+ env[key] = value;
190
+ }
191
+ }
192
+ return env;
193
+ }
194
+ function findNearestEnvFile(name, startDir = process.cwd()) {
195
+ let current = resolve(startDir);
196
+ while (true) {
197
+ const filePath = join(current, name);
198
+ if (existsSync(filePath)) return filePath;
199
+ const parent = dirname(current);
200
+ if (parent === current) return null;
201
+ current = parent;
202
+ }
203
+ }
204
+ function isDirectory(path) {
205
+ try {
206
+ return statSync(path).isDirectory();
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
211
+ function canonicalPath(path) {
212
+ try {
213
+ return realpathSync(path);
214
+ } catch {
215
+ return resolve(path);
216
+ }
217
+ }
218
+ function isTruthy(value) {
219
+ return /^(1|true|yes|on)$/i.test(value?.trim() ?? "");
220
+ }
221
+ function sessionRootFromPath(path) {
222
+ const trimmed = path?.trim();
223
+ if (!trimmed) return null;
224
+ const match = /^\/sessions\/[^/]+(?=\/|$)/.exec(trimmed);
225
+ return match?.[0] ?? null;
226
+ }
227
+ function coworkSessionRoot() {
228
+ const home = process.env.HOME?.trim();
229
+ const homeSessionRoot = sessionRootFromPath(home);
230
+ if (homeSessionRoot && isDirectory(join(homeSessionRoot, "mnt"))) {
231
+ return homeSessionRoot;
232
+ }
233
+ const cwdSessionRoot = sessionRootFromPath(process.cwd());
234
+ if (cwdSessionRoot && isDirectory(join(cwdSessionRoot, "mnt"))) {
235
+ return cwdSessionRoot;
236
+ }
237
+ if (isTruthy(process.env.CLAUDE_CODE_REMOTE) && home) {
238
+ const mountedRoot = join(home, "mnt");
239
+ if (isDirectory(mountedRoot)) return resolve(home);
240
+ }
241
+ return null;
242
+ }
243
+ function isCoworkLikeSandbox() {
244
+ const home = process.env.HOME?.trim();
245
+ return isTruthy(process.env.CLAUDE_CODE_REMOTE) || sessionRootFromPath(home) !== null || sessionRootFromPath(process.cwd()) !== null;
246
+ }
247
+ function coworkProjectScore(path) {
248
+ let score = 0;
249
+ for (const marker of COWORK_PROJECT_MARKERS) {
250
+ if (existsSync(join(path, marker))) score += 1;
251
+ }
252
+ return score;
253
+ }
254
+ function listCoworkWorkspaceDirCandidates() {
255
+ if (!isCoworkLikeSandbox()) {
256
+ return [];
257
+ }
258
+ const explicitProjectDir = process.env.CLAUDE_PROJECT_DIR?.trim();
259
+ if (explicitProjectDir && isDirectory(explicitProjectDir)) {
260
+ return [resolve(explicitProjectDir)];
261
+ }
262
+ const sessionRoot = coworkSessionRoot();
263
+ if (!sessionRoot) return [];
264
+ const mountedRoot = join(sessionRoot, "mnt");
265
+ if (!isDirectory(mountedRoot)) return [];
266
+ let names;
267
+ try {
268
+ names = readdirSync(mountedRoot).sort();
269
+ } catch {
270
+ return [];
271
+ }
272
+ const candidates = [];
273
+ for (const name of names) {
274
+ if (name.startsWith(".") || COWORK_IGNORED_WORKSPACE_DIRS.has(name)) {
275
+ continue;
276
+ }
277
+ const candidate = join(mountedRoot, name);
278
+ if (isDirectory(candidate)) candidates.push(candidate);
279
+ }
280
+ if (candidates.length <= 1) return candidates;
281
+ const projectLike = candidates.filter(
282
+ (candidate) => coworkProjectScore(candidate) > 0
283
+ );
284
+ return projectLike.length > 0 ? projectLike : candidates;
285
+ }
286
+ function isInIgnoredCoworkMount(path) {
287
+ const sessionRoot = coworkSessionRoot();
288
+ if (!sessionRoot) return false;
289
+ const mountedRoot = canonicalPath(join(sessionRoot, "mnt"));
290
+ const resolvedPath = canonicalPath(path);
291
+ const prefix = `${mountedRoot}/`;
292
+ if (!resolvedPath.startsWith(prefix)) return false;
293
+ const relativePath = resolvedPath.slice(prefix.length);
294
+ const mountName = relativePath.split("/")[0];
295
+ return mountName.startsWith(".") || COWORK_IGNORED_WORKSPACE_DIRS.has(mountName);
296
+ }
297
+ function detectCoworkWorkspaceDir() {
298
+ const candidates = listCoworkWorkspaceDirCandidates();
299
+ return candidates.length === 1 ? candidates[0] : null;
300
+ }
301
+ function loadProjectEnvCandidates(startDir = process.cwd()) {
302
+ const filePaths = [];
303
+ const sources = /* @__PURE__ */ new Map();
304
+ const nearestFile = findNearestEnvFile(PROJECT_DEEPLINE_ENV_FILE, startDir);
305
+ if (nearestFile && !isInIgnoredCoworkMount(nearestFile)) {
306
+ filePaths.push(nearestFile);
307
+ sources.set(resolve(nearestFile), "nearest");
308
+ }
309
+ const coworkWorkspaceDir = detectCoworkWorkspaceDir();
310
+ if (coworkWorkspaceDir) {
311
+ const coworkFile = join(coworkWorkspaceDir, PROJECT_DEEPLINE_ENV_FILE);
312
+ if (existsSync(coworkFile) && !filePaths.some((filePath) => resolve(filePath) === resolve(coworkFile))) {
313
+ filePaths.push(coworkFile);
314
+ sources.set(resolve(coworkFile), "cowork");
315
+ }
316
+ }
317
+ return filePaths.map((filePath) => ({
318
+ filePath,
319
+ env: parseEnvFile(filePath),
320
+ source: sources.get(resolve(filePath)) ?? "nearest"
321
+ }));
322
+ }
323
+ function normalizeBaseUrl(baseUrl) {
324
+ const trimmed = baseUrl?.trim().replace(/\/+$/, "") ?? "";
325
+ if (!trimmed) return "";
326
+ try {
327
+ const parsed = new URL(trimmed);
328
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
329
+ return "";
330
+ }
331
+ return parsed.toString().replace(/\/+$/, "");
332
+ } catch {
333
+ return "";
334
+ }
335
+ }
336
+ function firstNonEmpty(...values) {
337
+ for (const value of values) {
338
+ const trimmed = value?.trim();
339
+ if (trimmed) return trimmed;
340
+ }
341
+ return "";
342
+ }
343
+ function formatEnvFileValue(value) {
344
+ return /^[a-zA-Z0-9_./:@%+=,-]+$/.test(value) ? value : JSON.stringify(value);
345
+ }
346
+ function mergePersistedEnvValues(existing, values) {
347
+ const merged = { ...existing, ...values };
348
+ const nextApiKey = values[API_KEY_ENV];
349
+ if (nextApiKey !== void 0 && nextApiKey !== existing[API_KEY_ENV] && values[ACTIVE_ORG_ID_ENV] === void 0) {
350
+ delete merged[ACTIVE_ORG_ID_ENV];
351
+ delete merged[ACTIVE_ORG_NAME_ENV];
352
+ delete merged[FEATURES_ENV];
353
+ }
354
+ if (values[FEATURES_ENV] === "") {
355
+ delete merged[FEATURES_ENV];
356
+ }
357
+ return merged;
358
+ }
359
+ function persistedEnvLines(values) {
360
+ return Object.entries(values).filter(
361
+ ([key, value]) => CLI_ENV_ALLOWED_KEYS.has(key) && value.trim() !== ""
362
+ ).map(([key, value]) => `${key}=${formatEnvFileValue(value)}`);
363
+ }
364
+ function sdkCliConfigDir(baseUrl) {
365
+ const home = process.env.HOME?.trim() || homedir();
366
+ return join(home, ".local", "deepline", baseUrlSlug(baseUrl || PROD_URL));
367
+ }
368
+ function sdkCliStateDirPath(baseUrl, homeDir = process.env.HOME?.trim() || homedir()) {
369
+ return join(
370
+ homeDir,
371
+ ".local",
372
+ "deepline",
373
+ baseUrlSlug(baseUrl || PROD_URL),
374
+ "sdk-cli"
375
+ );
376
+ }
377
+ function sdkCliEnvFilePath(baseUrl) {
378
+ return join(sdkCliConfigDir(baseUrl), ".env");
379
+ }
380
+ function loadCliEnv(baseUrl = PROD_URL) {
381
+ return parseEnvFile(sdkCliEnvFilePath(baseUrl));
382
+ }
383
+ function hostConfigDirPath(baseUrl) {
384
+ return sdkCliConfigDir(baseUrl);
385
+ }
386
+ function hostEnvFilePath(baseUrl) {
387
+ return sdkCliEnvFilePath(baseUrl);
388
+ }
389
+ function saveHostEnvValues(baseUrl, values) {
390
+ const filePath = sdkCliEnvFilePath(baseUrl);
391
+ const dir = dirname(filePath);
392
+ if (!existsSync(dir)) {
393
+ mkdirSync(dir, { recursive: true });
394
+ }
395
+ const existing = parseEnvFile(filePath);
396
+ const merged = mergePersistedEnvValues(existing, values);
397
+ const lines = persistedEnvLines(merged);
398
+ writeFileSync(filePath, `${lines.join("\n")}
399
+ `, "utf-8");
400
+ }
401
+ function loadGlobalCliEnv() {
402
+ return loadCliEnv(PROD_URL);
403
+ }
404
+ function autoDetectBaseUrl() {
405
+ const projectEnvs = loadProjectEnvCandidates();
406
+ const globalEnv = loadGlobalCliEnv();
407
+ return normalizeBaseUrl(process.env[HOST_URL_ENV] ?? "") || firstNonEmpty(
408
+ ...projectEnvs.map(({ env }) => normalizeBaseUrl(env[HOST_URL_ENV]))
409
+ ) || normalizeBaseUrl(globalEnv[HOST_URL_ENV] ?? "") || PROD_URL;
410
+ }
411
+ function resolveApiKeyForBaseUrl(baseUrl, explicitApiKey) {
412
+ const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
413
+ const projectEnvs = loadProjectEnvCandidates();
414
+ const cliEnv = loadCliEnv(normalizedBaseUrl || baseUrl);
415
+ return firstNonEmpty(
416
+ explicitApiKey,
417
+ process.env[API_KEY_ENV],
418
+ ...projectEnvs.map(({ env }) => {
419
+ const projectBaseUrl = normalizeBaseUrl(env[HOST_URL_ENV] ?? "");
420
+ return projectBaseUrl === normalizedBaseUrl ? env[API_KEY_ENV] : "";
421
+ }),
422
+ cliEnv[API_KEY_ENV]
423
+ );
424
+ }
425
+ function resolveProjectApiKeyForBaseUrl(baseUrl, startDir = process.cwd()) {
426
+ const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
427
+ return firstNonEmpty(
428
+ ...loadProjectEnvCandidates(startDir).map(({ env }) => {
429
+ const projectBaseUrl = normalizeBaseUrl(env[HOST_URL_ENV] ?? "");
430
+ return projectBaseUrl === normalizedBaseUrl ? env[API_KEY_ENV] : "";
431
+ })
432
+ );
433
+ }
434
+ function resolveGlobalApiKeyForBaseUrl(baseUrl) {
435
+ return firstNonEmpty(
436
+ process.env[API_KEY_ENV],
437
+ loadCliEnv(normalizeBaseUrl(baseUrl) || baseUrl)[API_KEY_ENV]
438
+ );
439
+ }
440
+ function getResolvedProjectAuthSource(baseUrl, apiKey, startDir = process.cwd()) {
441
+ const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
442
+ const normalizedApiKey = apiKey.trim();
443
+ if (!normalizedBaseUrl || !normalizedApiKey) return null;
444
+ return loadProjectEnvCandidates(startDir).find(({ env }) => {
445
+ const projectBaseUrl = normalizeBaseUrl(env[HOST_URL_ENV] ?? "");
446
+ return projectBaseUrl === normalizedBaseUrl && (env[API_KEY_ENV] ?? "").trim() === normalizedApiKey;
447
+ }) ?? null;
448
+ }
449
+ function resolveBaseUrlOnly(options) {
450
+ const baseUrl = normalizeBaseUrl(
451
+ options?.baseUrl?.trim() || autoDetectBaseUrl()
452
+ );
453
+ if (!baseUrl) {
454
+ throw new ConfigError(
455
+ `Invalid ${HOST_URL_ENV}. Expected an http(s) URL such as https://code.deepline.com.`
456
+ );
457
+ }
458
+ return baseUrl;
459
+ }
460
+ function resolveConfig(options) {
461
+ const baseUrl = normalizeBaseUrl(
462
+ options?.baseUrl?.trim() || autoDetectBaseUrl()
463
+ );
464
+ if (!baseUrl) {
465
+ throw new ConfigError(
466
+ `Invalid ${HOST_URL_ENV}. Expected an http(s) URL such as https://code.deepline.com.`
467
+ );
468
+ }
469
+ const apiKey = resolveApiKeyForBaseUrl(baseUrl, options?.apiKey);
470
+ if (!apiKey) {
471
+ throw new ConfigError(
472
+ `No API key found. Set ${API_KEY_ENV}, add it to .env.deepline, or run: deepline auth register`
473
+ );
474
+ }
475
+ return {
476
+ apiKey,
477
+ baseUrl,
478
+ timeout: options?.timeout ?? DEFAULT_TIMEOUT,
479
+ maxRetries: options?.maxRetries ?? DEFAULT_MAX_RETRIES,
480
+ // Pass through untouched: the transport owns case-insensitive merging so
481
+ // there is exactly one place that decides which header wins.
482
+ ...options?.headers ? { headers: { ...options.headers } } : {}
483
+ };
484
+ }
485
+ function mergeProjectEnvFile(filePath, values) {
486
+ const existing = parseEnvFile(filePath);
487
+ const merged = mergePersistedEnvValues(existing, values);
488
+ const dir = dirname(filePath);
489
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
490
+ ensureProjectEnvIsIgnored(dir);
491
+ const lines = persistedEnvLines(merged);
492
+ writeFileSync(filePath, `${lines.join("\n")}
493
+ `, "utf-8");
494
+ }
495
+ function ensureProjectEnvIsIgnored(dir) {
496
+ ensureProjectPrivatePathsIgnored(dir, [
497
+ PROJECT_DEEPLINE_ENV_FILE,
498
+ ".deepline/"
499
+ ]);
500
+ }
501
+ function ensureProjectPrivatePathsIgnored(dir, entries) {
502
+ const gitDir = findNearestGitCommonDir(dir);
503
+ if (gitDir) {
504
+ const excludePath = join(gitDir, "info", "exclude");
505
+ const existing2 = existsSync(excludePath) ? readFileSync(excludePath, "utf-8") : "";
506
+ const existingEntries2 = new Set(
507
+ existing2.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
508
+ );
509
+ const missing2 = entries.filter(
510
+ (entry) => !existingEntries2.has(entry) && !existingEntries2.has(`/${entry}`)
511
+ );
512
+ if (missing2.length === 0) return;
513
+ mkdirSync(dirname(excludePath), { recursive: true });
514
+ const prefix2 = existing2 && !existing2.endsWith("\n") ? "\n" : "";
515
+ writeFileSync(
516
+ excludePath,
517
+ `${existing2}${prefix2}${missing2.join("\n")}
518
+ `,
519
+ "utf-8"
520
+ );
521
+ return;
522
+ }
523
+ const gitignorePath = join(dir, ".gitignore");
524
+ const existing = existsSync(gitignorePath) ? readFileSync(gitignorePath, "utf-8") : "";
525
+ const existingEntries = new Set(
526
+ existing.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
527
+ );
528
+ const missing = entries.filter(
529
+ (entry) => !existingEntries.has(entry) && !existingEntries.has(`/${entry}`)
530
+ );
531
+ if (missing.length === 0) return;
532
+ const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
533
+ writeFileSync(
534
+ gitignorePath,
535
+ `${existing}${prefix}${missing.join("\n")}
536
+ `,
537
+ "utf-8"
538
+ );
539
+ }
540
+ function findNearestGitCommonDir(startDir) {
541
+ let current = resolve(startDir);
542
+ while (true) {
543
+ const candidate = join(current, ".git");
544
+ if (existsSync(candidate)) {
545
+ try {
546
+ const stat = statSync(candidate);
547
+ if (stat.isDirectory()) return candidate;
548
+ if (stat.isFile()) {
549
+ const match = readFileSync(candidate, "utf8").match(
550
+ /^gitdir:\s*(.+)$/m
551
+ );
552
+ const rawGitDir = match?.[1]?.trim();
553
+ if (rawGitDir) {
554
+ const gitDir = isAbsolute(rawGitDir) ? rawGitDir : resolve(dirname(candidate), rawGitDir);
555
+ const commonDirPath = join(gitDir, "commondir");
556
+ if (!existsSync(commonDirPath)) return gitDir;
557
+ const rawCommonDir = readFileSync(commonDirPath, "utf8").trim();
558
+ return rawCommonDir ? isAbsolute(rawCommonDir) ? rawCommonDir : resolve(gitDir, rawCommonDir) : gitDir;
559
+ }
560
+ }
561
+ } catch {
562
+ return null;
563
+ }
564
+ }
565
+ const parent = dirname(current);
566
+ if (parent === current) return null;
567
+ current = parent;
568
+ }
569
+ }
570
+ function saveProjectDeeplineEnvValues(values, startDir = process.cwd()) {
571
+ const target = resolveProjectPinTarget(startDir);
572
+ if (!target.ok) {
573
+ throw new ConfigError(
574
+ `Cowork project folder is ambiguous. Candidate folders: ${target.candidates.join(
575
+ ", "
576
+ )}. Set CLAUDE_PROJECT_DIR or cd into the intended project folder before running this command.`
577
+ );
578
+ }
579
+ const filePath = join(target.dir, PROJECT_DEEPLINE_ENV_FILE);
580
+ mergeProjectEnvFile(filePath, values);
581
+ return [filePath];
582
+ }
583
+ function resolveProjectPinTarget(startDir = process.cwd()) {
584
+ const nearestFile = findNearestEnvFile(PROJECT_DEEPLINE_ENV_FILE, startDir);
585
+ if (nearestFile && !isInIgnoredCoworkMount(nearestFile)) {
586
+ return { ok: true, dir: dirname(nearestFile), source: "nearest" };
587
+ }
588
+ const coworkCandidates = listCoworkWorkspaceDirCandidates();
589
+ if (coworkCandidates.length === 1) {
590
+ return { ok: true, dir: coworkCandidates[0], source: "cowork" };
591
+ }
592
+ if (coworkCandidates.length > 1) {
593
+ const resolvedStartDir = canonicalPath(startDir);
594
+ const cwdCandidate = coworkCandidates.find((candidate) => {
595
+ const resolvedCandidate = canonicalPath(candidate);
596
+ return resolvedStartDir === resolvedCandidate || resolvedStartDir.startsWith(`${resolvedCandidate}/`);
597
+ });
598
+ if (cwdCandidate) {
599
+ return { ok: true, dir: cwdCandidate, source: "cowork" };
600
+ }
601
+ return {
602
+ ok: false,
603
+ reason: "ambiguous_cowork_project",
604
+ candidates: coworkCandidates
605
+ };
606
+ }
607
+ return { ok: true, dir: resolve(startDir), source: "cwd" };
608
+ }
609
+ function getActiveProjectAuthSource(startDir = process.cwd()) {
610
+ return loadProjectEnvCandidates(startDir)[0] ?? null;
611
+ }
612
+ function findNearestProjectMarkerDir(startDir) {
613
+ let current = resolve(startDir);
614
+ while (true) {
615
+ if (COWORK_PROJECT_MARKERS.some((marker) => existsSync(join(current, marker)))) {
616
+ return current;
617
+ }
618
+ const parent = dirname(current);
619
+ if (parent === current) return null;
620
+ current = parent;
621
+ }
622
+ }
623
+ function resolveCliAuthProvenance(config, startDir = process.cwd()) {
624
+ const envApiKey = process.env[API_KEY_ENV]?.trim();
625
+ const folderAuth = getResolvedProjectAuthSource(
626
+ config.baseUrl,
627
+ config.apiKey,
628
+ startDir
629
+ );
630
+ const pinTarget = resolveProjectPinTarget(startDir);
631
+ const markerDir = findNearestProjectMarkerDir(startDir);
632
+ const project = !pinTarget.ok ? {
633
+ state: "ambiguous_cowork_project",
634
+ candidates: pinTarget.candidates
635
+ } : folderAuth ? {
636
+ state: "project",
637
+ dir: dirname(folderAuth.filePath),
638
+ pinPath: folderAuth.filePath,
639
+ source: "folder"
640
+ } : pinTarget.source === "cowork" ? {
641
+ state: "project",
642
+ dir: pinTarget.dir,
643
+ pinPath: join(pinTarget.dir, PROJECT_DEEPLINE_ENV_FILE),
644
+ source: "cowork"
645
+ } : markerDir ? {
646
+ state: "project",
647
+ dir: markerDir,
648
+ pinPath: join(markerDir, PROJECT_DEEPLINE_ENV_FILE),
649
+ source: "marker"
650
+ } : { state: "not_project" };
651
+ return {
652
+ scope: envApiKey ? "env" : folderAuth ? "folder" : "global",
653
+ project,
654
+ folderAuthPath: folderAuth?.filePath ?? null
655
+ };
656
+ }
657
+ function activeOrganizationFromEnv(env) {
658
+ const orgId = env[ACTIVE_ORG_ID_ENV]?.trim();
659
+ if (!orgId) return null;
660
+ const orgName = env[ACTIVE_ORG_NAME_ENV]?.trim() || null;
661
+ return { org_id: orgId, org_name: orgName };
662
+ }
663
+ function resolveCliCommandContext(inputConfig, requestedScope) {
664
+ let config = inputConfig;
665
+ if (!config) {
666
+ try {
667
+ config = resolveConfig();
668
+ } catch {
669
+ return {
670
+ active_organization: null,
671
+ auth_scope: null,
672
+ metadata_source: null
673
+ };
674
+ }
675
+ }
676
+ const contextForScope = (scope) => {
677
+ if (scope === "env") {
678
+ const processApiKey = process.env[API_KEY_ENV]?.trim();
679
+ return processApiKey && processApiKey === config.apiKey ? {
680
+ active_organization: activeOrganizationFromEnv(process.env),
681
+ auth_scope: "env",
682
+ metadata_source: "process_env"
683
+ } : null;
684
+ }
685
+ if (scope === "folder") {
686
+ const projectAuth = getResolvedProjectAuthSource(
687
+ config.baseUrl,
688
+ config.apiKey
689
+ );
690
+ return projectAuth ? {
691
+ active_organization: activeOrganizationFromEnv(projectAuth.env),
692
+ auth_scope: "folder",
693
+ metadata_source: "folder_env"
694
+ } : null;
695
+ }
696
+ const hostEnv = loadCliEnv(config.baseUrl);
697
+ return (hostEnv[API_KEY_ENV] ?? "").trim() === config.apiKey ? {
698
+ active_organization: activeOrganizationFromEnv(hostEnv),
699
+ auth_scope: "global",
700
+ metadata_source: "host_env"
701
+ } : null;
702
+ };
703
+ const processContext = contextForScope("env");
704
+ if (processContext) return processContext;
705
+ if (requestedScope) {
706
+ return contextForScope(requestedScope) ?? {
707
+ active_organization: null,
708
+ auth_scope: requestedScope,
709
+ metadata_source: null
710
+ };
711
+ }
712
+ for (const scope of ["folder", "global"]) {
713
+ const context = contextForScope(scope);
714
+ if (context) return context;
715
+ }
716
+ return {
717
+ active_organization: null,
718
+ auth_scope: null,
719
+ metadata_source: null
720
+ };
721
+ }
722
+
723
+ // src/version.ts
724
+ var SDK_VERSION = SDK_RELEASE.version;
725
+ var SDK_API_MAJOR = SDK_RELEASE.contracts.api.currentMajor;
726
+ var SDK_API_CONTRACT = SDK_RELEASE.contracts.api.legacyWireIds[0] ?? `api-v${SDK_API_MAJOR}`;
727
+
728
+ // src/agent-runtime.ts
729
+ import { homedir as homedir2 } from "os";
730
+ var EXPLICIT_AGENT_RUNTIMES = /* @__PURE__ */ new Set([
731
+ "claude_code",
732
+ "claude_cowork",
733
+ "codex",
734
+ "cline",
735
+ "cursor",
736
+ "gemini",
737
+ "antigravity",
738
+ "windsurf",
739
+ "unknown"
740
+ ]);
741
+ function truthyEnv(name) {
742
+ return ["1", "true", "yes", "on"].includes(
743
+ String(process.env[name] ?? "").trim().toLowerCase()
744
+ );
745
+ }
746
+ function normalizeAgentRuntime(value) {
747
+ const explicit = value?.trim().toLowerCase().replace(/-/g, "_");
748
+ if (!explicit) return null;
749
+ if (explicit === "gemini_cli") return "gemini";
750
+ return EXPLICIT_AGENT_RUNTIMES.has(explicit) ? explicit : null;
751
+ }
752
+ function isCoworkLikeSandbox2() {
753
+ const pluginMode = truthyEnv("DEEPLINE_PLUGIN_MODE");
754
+ const claudeRemote = truthyEnv("CLAUDE_CODE_REMOTE");
755
+ const projectDir = Boolean(process.env.CLAUDE_PROJECT_DIR?.trim());
756
+ const pluginRoot = Boolean(process.env.DEEPLINE_PLUGIN_ROOT?.trim());
757
+ const home = process.env.HOME?.trim() || homedir2();
758
+ const sessionHome = home === "/sessions" || home.startsWith("/sessions/");
759
+ return claudeRemote || sessionHome || (pluginMode || pluginRoot) && projectDir;
760
+ }
761
+ function detectAgentRuntime(options = {}) {
762
+ const explicit = normalizeAgentRuntime(process.env.DEEPLINE_AGENT_RUNTIME);
763
+ if (explicit) return explicit;
764
+ if (process.env.CODEX_THREAD_ID?.trim()) return "codex";
765
+ if (options.detectCowork !== false && isCoworkLikeSandbox2()) {
766
+ return "claude_cowork";
767
+ }
768
+ if (process.env.CLAUDECODE?.trim() === "1") return "claude_code";
769
+ if (process.env.CLINE_ACTIVE?.trim().toLowerCase() === "true") return "cline";
770
+ if (process.env.CURSOR_TRACE_ID?.trim() || process.env.CURSOR_AGENT?.trim()) {
771
+ return "cursor";
772
+ }
773
+ if (process.env.WINDSURF?.trim() || process.env.CASCADE?.trim()) {
774
+ return "windsurf";
775
+ }
776
+ if (process.env.ANTIGRAVITY?.trim() || process.env.ANTIGRAVITY_CLI?.trim() || process.env.ANTIGRAVITY_AGENT?.trim() || process.env.ANTIGRAVITY_WORKSPACE?.trim()) {
777
+ return "antigravity";
778
+ }
779
+ if (process.env.GEMINI_CLI?.trim() || process.env.GEMINI_CLI_VERSION?.trim() || process.env.GEMINI_SANDBOX?.trim() || process.env.GEMINI_CONFIG_DIR?.trim()) {
780
+ return "gemini";
781
+ }
782
+ return options.defaultRuntime ?? "unknown";
783
+ }
784
+
785
+ // src/skills-version.ts
786
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
787
+ import { dirname as dirname2, join as join2 } from "path";
788
+ function activePluginSkillsDir() {
789
+ const pluginMode = process.env.DEEPLINE_PLUGIN_MODE?.trim().toLowerCase();
790
+ if (pluginMode !== "true" && pluginMode !== "1" && pluginMode !== "yes" && pluginMode !== "on") {
791
+ return "";
792
+ }
793
+ const dir = process.env.DEEPLINE_PLUGIN_SKILLS_DIR?.trim() ?? "";
794
+ return dir && existsSync2(dir) ? dir : "";
795
+ }
796
+ function hasActivePluginSkills() {
797
+ return Boolean(activePluginSkillsDir());
798
+ }
799
+ function readPluginSkillsVersion() {
800
+ const dir = activePluginSkillsDir();
801
+ if (!dir) return "";
802
+ try {
803
+ return readFileSync2(join2(dir, ".version"), "utf-8").trim();
804
+ } catch {
805
+ return "";
806
+ }
807
+ }
808
+ var KNOWN_SKILL_AGENTS = [
809
+ "antigravity",
810
+ "claude-code",
811
+ "cline",
812
+ "codex",
813
+ "cursor",
814
+ "gemini-cli",
815
+ "windsurf"
816
+ ];
817
+ var DEFAULT_SKILL_AGENTS = [
818
+ "codex",
819
+ "claude-code",
820
+ "cursor",
821
+ "gemini-cli",
822
+ "antigravity"
823
+ ];
824
+ function skillsAgentPathSegment(agent) {
825
+ if (agent === "*") return "all";
826
+ const slug = agent.replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "");
827
+ return slug || "agent";
828
+ }
829
+ function sdkSkillsVersionPath(baseUrl, agents = []) {
830
+ const suffix = agents.length > 0 ? `-${agents.map(skillsAgentPathSegment).join("-")}` : "";
831
+ return join2(sdkCliStateDirPath(baseUrl), `skills${suffix}-version`);
832
+ }
833
+ function legacySdkSkillsVersionPath(baseUrl) {
834
+ return join2(dirname2(sdkCliStateDirPath(baseUrl)), "sdk-skills", ".version");
835
+ }
836
+ function readSkillsVersionFile(path) {
837
+ try {
838
+ return readFileSync2(path, "utf-8").trim();
839
+ } catch {
840
+ return "";
841
+ }
842
+ }
843
+ function resolveAutoSyncSkillAgents() {
844
+ switch (detectAgentRuntime()) {
845
+ case "codex":
846
+ return ["codex"];
847
+ case "claude_code":
848
+ return ["claude-code"];
849
+ case "cursor":
850
+ return ["cursor"];
851
+ case "gemini":
852
+ return ["gemini-cli"];
853
+ case "antigravity":
854
+ return ["antigravity"];
855
+ case "unknown":
856
+ return [...DEFAULT_SKILL_AGENTS];
857
+ default:
858
+ return [];
859
+ }
860
+ }
861
+ function readSdkSkillsLocalVersion(baseUrl) {
862
+ const pluginVersion = readPluginSkillsVersion();
863
+ if (pluginVersion) return pluginVersion;
864
+ const agents = resolveAutoSyncSkillAgents();
865
+ if (agents.length > 1) {
866
+ const versions = agents.map(
867
+ (agent) => readSkillsVersionFile(sdkSkillsVersionPath(baseUrl, [agent]))
868
+ );
869
+ const first = versions[0];
870
+ return first && versions.every((version) => version === first) ? first : "";
871
+ }
872
+ const scopedPath = sdkSkillsVersionPath(baseUrl, agents);
873
+ if (agents.length > 0 && existsSync2(scopedPath)) {
874
+ try {
875
+ return readFileSync2(scopedPath, "utf-8").trim();
876
+ } catch {
877
+ return "";
878
+ }
879
+ }
880
+ if (agents.length > 0) {
881
+ const legacyPath = legacySdkSkillsVersionPath(baseUrl);
882
+ if (!existsSync2(legacyPath)) return "";
883
+ try {
884
+ return readFileSync2(legacyPath, "utf-8").trim();
885
+ } catch {
886
+ return "";
887
+ }
888
+ }
889
+ const path = existsSync2(sdkSkillsVersionPath(baseUrl)) ? sdkSkillsVersionPath(baseUrl) : legacySdkSkillsVersionPath(baseUrl);
890
+ if (!existsSync2(path)) return "";
891
+ try {
892
+ return readFileSync2(path, "utf-8").trim();
893
+ } catch {
894
+ return "";
895
+ }
896
+ }
897
+ function writeSdkSkillsLocalVersion(baseUrl, version, agents) {
898
+ const targets = agents.length > 1 ? agents.map((agent) => [agent]) : [agents];
899
+ let complete = true;
900
+ for (const target of targets) {
901
+ const path = sdkSkillsVersionPath(baseUrl, target);
902
+ try {
903
+ mkdirSync2(dirname2(path), { recursive: true });
904
+ writeFileSync2(path, `${version}
905
+ `, "utf-8");
906
+ } catch {
907
+ complete = false;
908
+ }
909
+ }
910
+ return complete;
911
+ }
912
+
913
+ // ../play-runtime/coordinator-headers.ts
914
+ var COORDINATOR_INTERNAL_TOKEN_HEADER = "x-deepline-internal-token";
915
+ var COORDINATOR_URL_OVERRIDE_HEADER = "x-deepline-coordinator-url";
916
+ var WORKER_CALLBACK_URL_OVERRIDE_HEADER = "x-deepline-worker-callback-url";
917
+ var RUNTIME_SCHEDULER_SCHEMA_OVERRIDE_HEADER = "x-deepline-runtime-scheduler-schema";
918
+ var RUNTIME_ENVIRONMENT_TOKEN_HEADER = "x-deepline-runtime-environment-token";
919
+ var RETAINED_PIPELINE_RECEIVERS_HEADER = "x-deepline-retained-pipeline-receivers";
920
+ var ABSURD_RELEASE_OVERRIDE_HEADER = "x-deepline-absurd-release";
921
+ var PREFERRED_RECEIPT_GATEWAY_MACHINE_ID_HEADER = "x-deepline-preferred-receipt-gateway-machine-id";
922
+ var SYNTHETIC_RUN_HEADER = "x-deepline-synthetic-run";
923
+
924
+ // src/deployment-protection.ts
925
+ function deploymentProtectionHeaders() {
926
+ const token = typeof process !== "undefined" ? process.env?.VERCEL_PROTECTION_BYPASS_TOKEN : void 0;
927
+ return token ? { "x-vercel-protection-bypass": token } : {};
928
+ }
929
+ var fetchWithDeploymentProtection = (input, init) => {
930
+ const headers = new Headers(
931
+ input instanceof Request ? input.headers : void 0
932
+ );
933
+ new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
934
+ for (const [name, value] of Object.entries(deploymentProtectionHeaders())) {
935
+ headers.set(name, value);
936
+ }
937
+ return fetch(input, { ...init, headers });
938
+ };
939
+
940
+ // ../play-runtime/runtime-incident-drills.ts
941
+ var RUNTIME_TEST_FAULT_IDS = [
942
+ "receipt_complete_write_fail",
943
+ "receipt_fail_write_fail",
944
+ "worker_receipt_complete_write_fail",
945
+ "invocation_response_delivery_abort",
946
+ "execution_upstream_response_loss",
947
+ "receipt_gateway_hold_ms",
948
+ "receipt_claim_query_hold_once_ms",
949
+ "receipt_claim_response_timeout",
950
+ "modal_sandbox_create_resource_exhausted",
951
+ "runtime_sheet_page_tail_hold_ms"
952
+ ];
953
+ var LOCAL_TOPOLOGY = ["local_daytona"];
954
+ var LOCAL_AND_PREVIEW_TOPOLOGIES = [
955
+ "local_daytona",
956
+ "preview_fly",
957
+ "preview_direct_modal"
958
+ ];
959
+ var MODAL_PREVIEW_TOPOLOGY = ["preview_direct_modal"];
960
+ var RUNTIME_INCIDENT_DRILL_CATALOG = [
961
+ {
962
+ id: "local_worker_process_outage",
963
+ description: "Interrupt the scheduler worker in the selected non-production runtime topology.",
964
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
965
+ control: {
966
+ kind: "process",
967
+ component: "worker",
968
+ modes: ["pause", "crash"]
969
+ },
970
+ expected: {
971
+ outcome: "The same logical run stays durable through the worker outage and completes after the selected topology recovers.",
972
+ safetyFacts: ["same_logical_run", "no_false_success"]
973
+ },
974
+ verification: {
975
+ kind: "local_black_box",
976
+ target: "local-component-outage-recovery-e2e"
977
+ }
978
+ },
979
+ {
980
+ id: "local_gateway_process_outage",
981
+ description: "Interrupt the receipt gateway in the selected non-production runtime topology.",
982
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
983
+ control: {
984
+ kind: "process",
985
+ component: "gateway",
986
+ modes: ["pause", "crash"]
987
+ },
988
+ expected: {
989
+ outcome: "In-flight work recovers only at a safe receipt boundary and the same logical run completes after the gateway recovers.",
990
+ safetyFacts: [
991
+ "same_logical_run",
992
+ "no_false_success",
993
+ "bounded_provider_execution"
994
+ ]
995
+ },
996
+ verification: {
997
+ kind: "local_black_box",
998
+ target: "local-component-outage-recovery-e2e"
999
+ }
1000
+ },
1001
+ {
1002
+ id: "local_runtime_process_outage",
1003
+ description: "Interrupt both runtime components in the selected non-production topology.",
1004
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
1005
+ control: { kind: "process", component: "all", modes: ["pause", "crash"] },
1006
+ expected: {
1007
+ outcome: "Durable work waits through the combined outage; it never becomes a false success or creates a second logical run.",
1008
+ safetyFacts: ["same_logical_run", "no_false_success"]
1009
+ },
1010
+ verification: {
1011
+ kind: "local_black_box",
1012
+ target: "local-component-outage-recovery-e2e"
1013
+ }
1014
+ },
1015
+ {
1016
+ id: "receipt_complete_write_fail",
1017
+ description: "Fail the next durable receipt-completion write.",
1018
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
1019
+ control: {
1020
+ kind: "runtime_test_fault",
1021
+ defaultValue: 1,
1022
+ valueMeaning: "occurrence"
1023
+ },
1024
+ expected: {
1025
+ outcome: "The failed run is loud, and a later bounded recovery may repeat the affected provider operation if its prior completion was not durable.",
1026
+ safetyFacts: ["retry_or_explicit_recovery", "bounded_provider_execution"]
1027
+ },
1028
+ verification: {
1029
+ kind: "local_black_box",
1030
+ target: "receipt-persist-failure-run-fatal-e2e"
1031
+ }
1032
+ },
1033
+ {
1034
+ id: "receipt_fail_write_fail",
1035
+ description: "Fail the next durable receipt-failure write.",
1036
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
1037
+ control: {
1038
+ kind: "runtime_test_fault",
1039
+ defaultValue: 1,
1040
+ valueMeaning: "occurrence"
1041
+ },
1042
+ expected: {
1043
+ outcome: "The failure is loud; recovery remains bounded and may repeat an operation whose prior outcome was not durably recorded.",
1044
+ safetyFacts: ["retry_or_explicit_recovery", "bounded_provider_execution"]
1045
+ },
1046
+ verification: {
1047
+ kind: "focused_regression",
1048
+ target: "tests/lib/plays/runtime-test-fault-registry.test.ts"
1049
+ }
1050
+ },
1051
+ {
1052
+ id: "worker_receipt_complete_write_fail",
1053
+ description: "Fail the worker-side receipt-completion write once.",
1054
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
1055
+ control: {
1056
+ kind: "runtime_test_fault",
1057
+ defaultValue: 1,
1058
+ valueMeaning: "occurrence"
1059
+ },
1060
+ expected: {
1061
+ outcome: "The worker reports the persistence failure loudly; bounded recovery may repeat work whose completion was not durable.",
1062
+ safetyFacts: ["retry_or_explicit_recovery", "bounded_provider_execution"]
1063
+ },
1064
+ verification: {
1065
+ kind: "focused_regression",
1066
+ target: "tests/lib/plays/runtime-test-fault-registry.test.ts"
1067
+ }
1068
+ },
1069
+ {
1070
+ id: "invocation_response_delivery_abort",
1071
+ description: "Abort one receipt-gateway response after invocation delivery.",
1072
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
1073
+ control: {
1074
+ kind: "runtime_test_fault",
1075
+ defaultValue: 1,
1076
+ valueMeaning: "occurrence"
1077
+ },
1078
+ expected: {
1079
+ outcome: "The same logical run completes through terminal-cache replay; any provider retry is governed by its separate operation policy.",
1080
+ safetyFacts: ["same_logical_run", "bounded_provider_execution"]
1081
+ },
1082
+ verification: {
1083
+ kind: "local_black_box",
1084
+ target: "invocation-delivery-replay-e2e"
1085
+ }
1086
+ },
1087
+ {
1088
+ id: "execution_upstream_response_loss",
1089
+ description: "Lose the first response of each keyed execution after the upstream app durably stores it.",
1090
+ topologies: ["preview_fly"],
1091
+ control: {
1092
+ kind: "runtime_test_fault",
1093
+ defaultValue: 1,
1094
+ valueMeaning: "occurrence"
1095
+ },
1096
+ expected: {
1097
+ outcome: "The same invocation recovers the stored response without repeating provider work or customer charges, and every row retains its usable result.",
1098
+ safetyFacts: [
1099
+ "same_logical_run",
1100
+ "bounded_provider_execution",
1101
+ "all_rows_settle_once",
1102
+ "no_false_success"
1103
+ ]
1104
+ },
1105
+ verification: {
1106
+ kind: "preview_black_box",
1107
+ target: "101-agent-heavy-gateway-load-e2e"
1108
+ }
1109
+ },
1110
+ {
1111
+ id: "receipt_gateway_hold_ms",
1112
+ description: "Hold one checked-out receipt-gateway scheduler client.",
1113
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
1114
+ control: {
1115
+ kind: "runtime_test_fault",
1116
+ defaultValue: 500,
1117
+ valueMeaning: "milliseconds"
1118
+ },
1119
+ expected: {
1120
+ outcome: "The request is delayed inside the real gateway pool and either completes within its deadline or follows bounded transport recovery.",
1121
+ safetyFacts: ["bounded_provider_execution"]
1122
+ },
1123
+ verification: {
1124
+ kind: "local_black_box",
1125
+ target: "agent-heavy-gateway-load-e2e"
1126
+ }
1127
+ },
1128
+ {
1129
+ id: "receipt_claim_query_hold_once_ms",
1130
+ description: "Hold one physical receipt-claim query.",
1131
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
1132
+ control: {
1133
+ kind: "runtime_test_fault",
1134
+ defaultValue: 500,
1135
+ valueMeaning: "milliseconds"
1136
+ },
1137
+ expected: {
1138
+ outcome: "The checked-out claim either completes or times out through bounded recovery; an ambiguous outcome may be retried within its budget.",
1139
+ safetyFacts: ["bounded_provider_execution"]
1140
+ },
1141
+ verification: {
1142
+ kind: "local_black_box",
1143
+ target: "receipt-claim-deadline-recovery-e2e"
1144
+ }
1145
+ },
1146
+ {
1147
+ id: "receipt_claim_response_timeout",
1148
+ description: "Report one fully received receipt-claim response as timed out.",
1149
+ topologies: LOCAL_AND_PREVIEW_TOPOLOGIES,
1150
+ control: {
1151
+ kind: "runtime_test_fault",
1152
+ defaultValue: 1,
1153
+ valueMeaning: "occurrence"
1154
+ },
1155
+ expected: {
1156
+ outcome: "The same logical run completes by replaying the committed receipt response or uses bounded recovery if that response is unavailable.",
1157
+ safetyFacts: ["same_logical_run", "bounded_provider_execution"]
1158
+ },
1159
+ verification: {
1160
+ kind: "local_black_box",
1161
+ target: "receipt-ambiguous-response-recovery-e2e"
1162
+ }
1163
+ },
1164
+ {
1165
+ id: "modal_sandbox_create_resource_exhausted",
1166
+ description: "Make Modal sandbox creation return RESOURCE_EXHAUSTED before user code.",
1167
+ topologies: MODAL_PREVIEW_TOPOLOGY,
1168
+ control: {
1169
+ kind: "runtime_test_fault",
1170
+ defaultValue: 1,
1171
+ valueMeaning: "occurrence"
1172
+ },
1173
+ expected: {
1174
+ outcome: "The same logical run enters bounded pre-code defer/recovery and later retries sandbox startup; no user code or provider call precedes the retry.",
1175
+ safetyFacts: [
1176
+ "same_logical_run",
1177
+ "no_user_code_before_recovery",
1178
+ "bounded_provider_execution"
1179
+ ]
1180
+ },
1181
+ verification: {
1182
+ kind: "preview_black_box",
1183
+ target: "modal-sandbox-recovery-e2e"
1184
+ }
1185
+ },
1186
+ {
1187
+ id: "runtime_sheet_page_tail_hold_ms",
1188
+ description: "Hold one runtime-sheet tail-page operation.",
1189
+ topologies: LOCAL_TOPOLOGY,
1190
+ control: {
1191
+ kind: "runtime_test_fault",
1192
+ defaultValue: 500,
1193
+ valueMeaning: "milliseconds"
1194
+ },
1195
+ expected: {
1196
+ outcome: "Page-tail work stays pending during the bounded hold, then completes without losing or duplicating rows.",
1197
+ safetyFacts: ["all_rows_settle_once"]
1198
+ },
1199
+ verification: {
1200
+ kind: "local_black_box",
1201
+ target: "page-tail-sheet-write-hold-e2e"
1202
+ }
1203
+ }
1204
+ ];
1205
+ function isRuntimeTestFaultDrill(drill) {
1206
+ return drill.control.kind === "runtime_test_fault" && RUNTIME_TEST_FAULT_IDS.some((faultId) => faultId === drill.id);
1207
+ }
1208
+ function runtimeTestFaultDrills() {
1209
+ return RUNTIME_INCIDENT_DRILL_CATALOG.filter(isRuntimeTestFaultDrill);
1210
+ }
1211
+
1212
+ // ../play-runtime/test-runtime-seams.ts
1213
+ var PLAY_RUNTIME_TEST_FAULT_HEADER = "x-deepline-test-fault";
1214
+ var SUPPORTED_RUNTIME_TEST_FAULTS = new Set(
1215
+ runtimeTestFaultDrills().map(({ id }) => id)
1216
+ );
1217
+ var MAX_RUNTIME_TEST_POLICY_MS = 10 * 6e4;
1218
+
1219
+ // src/http.ts
1220
+ var MAX_DIAGNOSTIC_HEADER_LENGTH = 120;
1221
+ var COWORK_NETWORK_HINT = "Claude Cowork appears to be running Deepline in a network-restricted sandbox. In Claude Desktop, open Settings > Capabilities, turn on Allow network egress, and set Domain allowlist to All domains for the Cowork session.";
1222
+ var REQUEST_TIMEOUT_MARKER = Symbol("deeplineRequestTimeout");
1223
+ var REQUEST_ABORT_MARKER = Symbol("deeplineRequestAbort");
1224
+ function requestCancelledError(signal) {
1225
+ const error = withErrorCause(new Error("Request aborted"), signal.reason);
1226
+ error[REQUEST_ABORT_MARKER] = true;
1227
+ return error;
1228
+ }
1229
+ function normalizeRequestAbortError(error, input) {
1230
+ const normalized = error instanceof Error ? error : new Error(String(error));
1231
+ const tagged = normalized;
1232
+ if (input.timedOut) {
1233
+ tagged[REQUEST_TIMEOUT_MARKER] = input.timeoutMs;
1234
+ } else if (isAbortLikeError(normalized)) {
1235
+ tagged[REQUEST_ABORT_MARKER] = true;
1236
+ }
1237
+ return normalized;
1238
+ }
1239
+ function applyExplicitHeaders(headers, explicit) {
1240
+ if (!explicit) return headers;
1241
+ for (const [rawName, value] of Object.entries(explicit)) {
1242
+ const name = rawName.trim().toLowerCase();
1243
+ if (!name) continue;
1244
+ for (const existing of Object.keys(headers)) {
1245
+ if (existing.toLowerCase() === name) delete headers[existing];
1246
+ }
1247
+ headers[rawName.trim()] = value;
1248
+ }
1249
+ return headers;
1250
+ }
1251
+ function isAbortLikeError(error) {
1252
+ const name = error.name.toLowerCase();
1253
+ const message = error.message.toLowerCase();
1254
+ return name === "aborterror" || message.includes("operation was aborted") || message === "aborted";
1255
+ }
1256
+ function withErrorCause(error, cause) {
1257
+ if (cause !== null && cause !== void 0) {
1258
+ Object.defineProperty(error, "cause", {
1259
+ value: cause,
1260
+ configurable: true,
1261
+ writable: true
1262
+ });
1263
+ }
1264
+ return error;
1265
+ }
1266
+ function mapNetworkError(baseUrl, error, targetLabel) {
1267
+ const tagged = error;
1268
+ const timeoutMs = tagged?.[REQUEST_TIMEOUT_MARKER];
1269
+ if (typeof timeoutMs === "number") {
1270
+ return {
1271
+ message: `Request to ${targetLabel} timed out after ${timeoutMs}ms while waiting for a response.`,
1272
+ code: "NETWORK_TIMEOUT",
1273
+ details: { timeoutMs, target: targetLabel }
1274
+ };
1275
+ }
1276
+ if (tagged?.[REQUEST_ABORT_MARKER]) {
1277
+ return {
1278
+ message: `Request to ${targetLabel} was aborted before it completed.`,
1279
+ code: "NETWORK_ABORTED"
1280
+ };
1281
+ }
1282
+ return {
1283
+ message: error?.message ? `Unable to connect to ${baseUrl}. ${error.message}` : `Unable to connect to ${baseUrl}. Is the computer able to access the url?`,
1284
+ code: "NETWORK_ERROR"
1285
+ };
1286
+ }
1287
+ function describeRequestTarget(path) {
1288
+ const toolExecuteMatch = path.match(
1289
+ /^\/api\/v2\/integrations\/([^/?#]+)\/execute(?:[/?#]|$)/
1290
+ );
1291
+ if (toolExecuteMatch) {
1292
+ return providerLabelFromToolId(decodeURIComponent(toolExecuteMatch[1]));
1293
+ }
1294
+ return "Deepline";
1295
+ }
1296
+ function networkDiagnosticUrl(value) {
1297
+ try {
1298
+ const url = new URL(value);
1299
+ if (url.protocol !== "https:" && url.protocol !== "http:") return void 0;
1300
+ return `${url.origin}${url.pathname}`;
1301
+ } catch {
1302
+ return void 0;
1303
+ }
1304
+ }
1305
+ function providerLabelFromToolId(toolId) {
1306
+ const normalized = toolId.trim().toLowerCase();
1307
+ const provider = normalized.split(/[_:./-]+/)[0];
1308
+ return provider || normalized || "provider";
1309
+ }
1310
+ function isRecord(value) {
1311
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1312
+ }
1313
+ var HttpClient = class {
1314
+ constructor(config) {
1315
+ this.config = config;
1316
+ }
1317
+ cleanDiagnosticHeader(value) {
1318
+ const normalized = String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, MAX_DIAGNOSTIC_HEADER_LENGTH);
1319
+ return normalized || null;
1320
+ }
1321
+ readSkillsVersionHeader() {
1322
+ const explicit = this.cleanDiagnosticHeader(
1323
+ process.env.DEEPLINE_SKILLS_VERSION
1324
+ );
1325
+ if (explicit) return explicit;
1326
+ try {
1327
+ return this.cleanDiagnosticHeader(
1328
+ readSdkSkillsLocalVersion(this.config.baseUrl)
1329
+ );
1330
+ } catch {
1331
+ return null;
1332
+ }
1333
+ }
1334
+ authHeaders(extra) {
1335
+ const transportHeaders = {
1336
+ Authorization: `Bearer ${this.config.apiKey}`,
1337
+ "User-Agent": `deepline-ts-sdk/${SDK_VERSION}`,
1338
+ "X-Deepline-Client-Family": "sdk",
1339
+ "X-Deepline-CLI-Family": "sdk",
1340
+ "X-Deepline-Agent-Runtime": detectAgentRuntime(),
1341
+ "X-Deepline-CLI-Version": SDK_VERSION,
1342
+ "X-Deepline-SDK-Version": SDK_VERSION,
1343
+ "X-Deepline-API-Contract": SDK_API_CONTRACT,
1344
+ "X-Deepline-Run-Result-Shape": "canonical"
1345
+ };
1346
+ const headers = deploymentProtectionHeaders();
1347
+ const skillsVersion = this.readSkillsVersionHeader();
1348
+ if (skillsVersion) {
1349
+ headers["X-Deepline-Skills-Version"] = skillsVersion;
1350
+ }
1351
+ const playArtifactR2Prefix = typeof process !== "undefined" ? process.env?.DEEPLINE_PLAY_ARTIFACT_R2_PREFIX : void 0;
1352
+ if (playArtifactR2Prefix) {
1353
+ headers["x-deepline-play-artifact-r2-prefix"] = playArtifactR2Prefix;
1354
+ }
1355
+ const coordinatorUrl = typeof process !== "undefined" ? process.env?.DEEPLINE_COORDINATOR_URL : void 0;
1356
+ const coordinatorInternalToken = typeof process !== "undefined" ? process.env?.DEEPLINE_INTERNAL_TOKEN : void 0;
1357
+ const absurdReleaseOverride = typeof process !== "undefined" ? process.env?.DEEPLINE_ABSURD_RELEASE : void 0;
1358
+ const preferredReceiptGatewayMachineId = typeof process !== "undefined" ? process.env?.DEEPLINE_PREFERRED_RECEIPT_GATEWAY_MACHINE_ID : void 0;
1359
+ if (coordinatorUrl?.trim()) {
1360
+ headers[COORDINATOR_URL_OVERRIDE_HEADER] = coordinatorUrl.trim();
1361
+ }
1362
+ const workerCallbackUrl = typeof process !== "undefined" ? process.env?.DEEPLINE_WORKER_CALLBACK_URL : void 0;
1363
+ if (workerCallbackUrl?.trim()) {
1364
+ headers[WORKER_CALLBACK_URL_OVERRIDE_HEADER] = workerCallbackUrl.trim();
1365
+ }
1366
+ const runtimeSchedulerSchema = typeof process !== "undefined" ? process.env?.DEEPLINE_RUNTIME_SCHEDULER_SCHEMA : void 0;
1367
+ if (runtimeSchedulerSchema?.trim()) {
1368
+ headers[RUNTIME_SCHEDULER_SCHEMA_OVERRIDE_HEADER] = runtimeSchedulerSchema.trim();
1369
+ }
1370
+ const syntheticRun = typeof process !== "undefined" ? process.env?.DEEPLINE_SYNTHETIC_RUN : void 0;
1371
+ if (syntheticRun && syntheticRun.trim() && syntheticRun.trim() !== "0") {
1372
+ headers[SYNTHETIC_RUN_HEADER] = "1";
1373
+ }
1374
+ const runtimeTestFault = typeof process !== "undefined" ? process.env?.DEEPLINE_TEST_RUNTIME_FAULT : void 0;
1375
+ if (runtimeTestFault?.trim()) {
1376
+ headers[PLAY_RUNTIME_TEST_FAULT_HEADER] = runtimeTestFault.trim();
1377
+ }
1378
+ const retainedReceivers = typeof process !== "undefined" ? process.env?.DEEPLINE_RUNTIME_RETAINED_PIPELINE_RECEIVERS?.trim() : void 0;
1379
+ if (retainedReceivers && coordinatorInternalToken?.trim()) {
1380
+ headers[RETAINED_PIPELINE_RECEIVERS_HEADER] = retainedReceivers;
1381
+ headers[COORDINATOR_INTERNAL_TOKEN_HEADER] = coordinatorInternalToken.trim();
1382
+ }
1383
+ if (absurdReleaseOverride?.trim() && coordinatorInternalToken?.trim()) {
1384
+ headers[ABSURD_RELEASE_OVERRIDE_HEADER] = absurdReleaseOverride.trim();
1385
+ }
1386
+ if (preferredReceiptGatewayMachineId?.trim() && coordinatorInternalToken?.trim()) {
1387
+ headers[PREFERRED_RECEIPT_GATEWAY_MACHINE_ID_HEADER] = preferredReceiptGatewayMachineId.trim();
1388
+ }
1389
+ if (coordinatorInternalToken?.trim() && (coordinatorUrl?.trim() || workerCallbackUrl?.trim() || runtimeTestFault?.trim() || absurdReleaseOverride?.trim() || preferredReceiptGatewayMachineId?.trim())) {
1390
+ headers[COORDINATOR_INTERNAL_TOKEN_HEADER] = coordinatorInternalToken.trim();
1391
+ }
1392
+ return applyExplicitHeaders(
1393
+ applyExplicitHeaders(
1394
+ applyExplicitHeaders(transportHeaders, extra),
1395
+ headers
1396
+ ),
1397
+ this.config.headers
1398
+ );
1399
+ }
1400
+ /**
1401
+ * Send an HTTP request with automatic retries and error handling.
1402
+ *
1403
+ * @typeParam T - Expected response body type
1404
+ * @param path - API path (e.g. `"/api/v2/tools"`)
1405
+ * @param options - HTTP method, body, headers, and timeout
1406
+ * @returns Parsed JSON response body
1407
+ * @throws {@link AuthError} on Deepline-auth HTTP 401/403 (immediate, no retry)
1408
+ * @throws {@link RateLimitError} on HTTP 429 after all retries exhausted
1409
+ * @throws {@link DeeplineError} on other API errors or connection failures
1410
+ */
1411
+ async request(path, options) {
1412
+ const baseUrl = this.config.baseUrl;
1413
+ const url = `${baseUrl}${path}`;
1414
+ const method = options?.method ?? "GET";
1415
+ const requestStartedAt = Date.now();
1416
+ let fetchAttempts = 0;
1417
+ let lastRequestUrl = url;
1418
+ let networkFailedAt;
1419
+ let networkPhase = "before_request";
1420
+ const headers = this.authHeaders(options?.headers);
1421
+ if (options?.body !== void 0) {
1422
+ applyExplicitHeaders(headers, { "Content-Type": "application/json" });
1423
+ }
1424
+ let lastError = null;
1425
+ const candidateUrls = options?.exactUrlOnly ? [url] : buildCandidateUrls(url);
1426
+ let retryAfterDelayMs = null;
1427
+ const maxRetries = options?.maxRetries ?? this.config.maxRetries;
1428
+ requestAttempts: for (let attempt = 0; attempt <= maxRetries; attempt++) {
1429
+ if (options?.signal?.aborted) {
1430
+ lastError = requestCancelledError(options.signal);
1431
+ networkFailedAt = Date.now();
1432
+ break;
1433
+ }
1434
+ if (attempt > 0) {
1435
+ const backoffMs = Math.min(1e3 * Math.pow(2, attempt - 1), 3e4);
1436
+ const delayMs = retryAfterDelayMs === null ? backoffMs : Math.max(backoffMs, retryAfterDelayMs);
1437
+ retryAfterDelayMs = null;
1438
+ networkPhase = "retry_wait";
1439
+ try {
1440
+ await sleep(delayMs, options?.signal);
1441
+ } catch (error) {
1442
+ lastError = error instanceof Error ? error : new Error(String(error));
1443
+ networkFailedAt = Date.now();
1444
+ break;
1445
+ }
1446
+ }
1447
+ for (const candidateUrl of candidateUrls) {
1448
+ if (options?.signal?.aborted) {
1449
+ lastError = requestCancelledError(options.signal);
1450
+ networkFailedAt = Date.now();
1451
+ break requestAttempts;
1452
+ }
1453
+ const controller = new AbortController();
1454
+ const timeoutMs = options?.timeout ?? this.config.timeout;
1455
+ let requestTimedOut = false;
1456
+ const timeoutId = setTimeout(() => {
1457
+ requestTimedOut = true;
1458
+ controller.abort();
1459
+ }, timeoutMs);
1460
+ const abortRequest = () => controller.abort();
1461
+ options?.signal?.addEventListener("abort", abortRequest, {
1462
+ once: true
1463
+ });
1464
+ networkPhase = "before_request";
1465
+ try {
1466
+ const requestBody = options?.formData !== void 0 ? typeof options.formData === "function" ? options.formData() : options.formData : options?.body !== void 0 ? JSON.stringify(options.body) : void 0;
1467
+ fetchAttempts += 1;
1468
+ lastRequestUrl = candidateUrl;
1469
+ networkPhase = "awaiting_headers";
1470
+ const response = await fetch(candidateUrl, {
1471
+ method,
1472
+ headers,
1473
+ body: requestBody,
1474
+ signal: controller.signal
1475
+ });
1476
+ networkPhase = "reading_body";
1477
+ options?.onResponse?.(response);
1478
+ if (response.status === 404 && options?.allowNotFound) {
1479
+ clearTimeout(timeoutId);
1480
+ return null;
1481
+ }
1482
+ const body = await response.text();
1483
+ clearTimeout(timeoutId);
1484
+ const parsed = parseResponseBody(body);
1485
+ const structuredToolError = options?.toolId && !response.ok ? deserializeToolExecutionFailure(
1486
+ apiErrorMessage(parsed, response.status),
1487
+ isRecord(parsed) ? parsed.tool_error : null,
1488
+ TOOL_EXECUTION_ERROR_SCHEMA_VERSION
1489
+ ) : null;
1490
+ if (structuredToolError) {
1491
+ if (response.status === 429) {
1492
+ const retryAfter = parseRetryAfter(response);
1493
+ const failure = serializeToolExecutionFailure(structuredToolError);
1494
+ lastError = failure === null ? structuredToolError : new ToolRateLimitError(structuredToolError.message, {
1495
+ ...failure,
1496
+ retryAfterMs: failure.retryAfterMs ?? Math.max(0, retryAfter)
1497
+ });
1498
+ if (attempt < maxRetries) {
1499
+ retryAfterDelayMs = retryAfter;
1500
+ break;
1501
+ }
1502
+ throw lastError;
1503
+ }
1504
+ throw structuredToolError;
1505
+ }
1506
+ if (response.status === 429) {
1507
+ if (options?.preserveRateLimitResponse && isMonitorRateLimitEnvelope(parsed)) {
1508
+ throw new DeeplineError(
1509
+ apiErrorMessage(parsed, response.status),
1510
+ response.status,
1511
+ apiErrorCodeFromResponse(parsed),
1512
+ { response: parsed }
1513
+ );
1514
+ }
1515
+ const retryAfter = parseRetryAfter(response);
1516
+ lastError = new RateLimitError(retryAfter);
1517
+ if (attempt < maxRetries) {
1518
+ retryAfterDelayMs = retryAfter;
1519
+ break;
1520
+ }
1521
+ throw lastError;
1522
+ }
1523
+ if (response.status === 401 && !isProviderOriginatedHttpError(parsed)) {
1524
+ throw new AuthError(apiErrorMessage(parsed, response.status));
1525
+ }
1526
+ if (!response.ok) {
1527
+ const retryableApiError = options?.retryApiErrors === true && isRetryableApiErrorResponse(response.status);
1528
+ const htmlError = detectHtmlErrorBody(
1529
+ body,
1530
+ response.headers.get("content-type")
1531
+ );
1532
+ if (htmlError) {
1533
+ lastError = new DeeplineError(
1534
+ htmlError.message(response.status),
1535
+ response.status,
1536
+ "API_ERROR",
1537
+ {
1538
+ htmlErrorPage: true,
1539
+ ...htmlError.title ? { title: htmlError.title } : {},
1540
+ ...htmlError.workerThrewException ? { workerThrewException: true } : {}
1541
+ }
1542
+ );
1543
+ if (retryableApiError && attempt < maxRetries) {
1544
+ retryAfterDelayMs = parseOptionalRetryAfter(response);
1545
+ break;
1546
+ }
1547
+ throw lastError;
1548
+ }
1549
+ const errorValue = typeof parsed === "object" && parsed && "error" in parsed ? parsed.error : void 0;
1550
+ const msg = typeof errorValue === "string" ? errorValue : errorValue && typeof errorValue === "object" && "message" in errorValue && typeof errorValue.message === "string" ? errorValue.message : typeof parsed === "object" && parsed && "message" in parsed && typeof parsed.message === "string" ? parsed.message : `HTTP ${response.status}`;
1551
+ const apiErrorCode = apiErrorCodeFromResponse(parsed);
1552
+ lastError = new DeeplineError(msg, response.status, apiErrorCode, {
1553
+ response: parsed
1554
+ });
1555
+ if (retryableApiError && attempt < maxRetries) {
1556
+ retryAfterDelayMs = parseOptionalRetryAfter(response);
1557
+ break;
1558
+ }
1559
+ throw lastError;
1560
+ }
1561
+ if (typeof parsed === "string") {
1562
+ const interstitial = detectHtmlErrorBody(
1563
+ body,
1564
+ response.headers.get("content-type")
1565
+ );
1566
+ if (interstitial) {
1567
+ throw new DeeplineError(
1568
+ `${this.config.baseUrl} returned a deployment-protection page instead of JSON. Set VERCEL_PROTECTION_BYPASS_TOKEN, or run \`vercel login\` if the CLI session expired.`,
1569
+ response.status,
1570
+ "DEPLOYMENT_PROTECTED",
1571
+ { htmlErrorPage: true }
1572
+ );
1573
+ }
1574
+ }
1575
+ return parsed;
1576
+ } catch (error) {
1577
+ clearTimeout(timeoutId);
1578
+ networkFailedAt = Date.now();
1579
+ if (options?.signal?.aborted) {
1580
+ lastError = requestCancelledError(options.signal);
1581
+ break requestAttempts;
1582
+ }
1583
+ if (error instanceof AuthError || error instanceof DeeplineError) {
1584
+ throw error;
1585
+ }
1586
+ if (error instanceof RateLimitError) {
1587
+ lastError = error;
1588
+ break;
1589
+ }
1590
+ lastError = normalizeRequestAbortError(error, {
1591
+ timeoutMs,
1592
+ timedOut: requestTimedOut
1593
+ });
1594
+ } finally {
1595
+ clearTimeout(timeoutId);
1596
+ options?.signal?.removeEventListener("abort", abortRequest);
1597
+ }
1598
+ }
1599
+ if (attempt < maxRetries) continue;
1600
+ }
1601
+ if (lastError instanceof DeeplineError) {
1602
+ throw lastError;
1603
+ }
1604
+ const mappedNetworkError = mapNetworkError(
1605
+ baseUrl,
1606
+ lastError,
1607
+ describeRequestTarget(path)
1608
+ );
1609
+ const failedAt = networkFailedAt ?? Date.now();
1610
+ const diagnosticUrl = networkDiagnosticUrl(lastRequestUrl);
1611
+ const networkDetails = {
1612
+ ...mappedNetworkError.details,
1613
+ request: {
1614
+ method,
1615
+ ...diagnosticUrl === void 0 ? {} : { url: diagnosticUrl },
1616
+ failedAtUtc: new Date(failedAt).toISOString(),
1617
+ // Elapsed time covers the entire logical request, including retries.
1618
+ elapsedMs: Math.max(0, failedAt - requestStartedAt),
1619
+ attempts: fetchAttempts,
1620
+ phase: networkPhase
1621
+ }
1622
+ };
1623
+ if (options?.toolId) {
1624
+ const code = mappedNetworkError.code;
1625
+ throw withErrorCause(
1626
+ new ToolExecutionError(
1627
+ withCoworkNetworkHint(mappedNetworkError.message),
1628
+ {
1629
+ toolId: options.toolId,
1630
+ provider: providerLabelFromToolId(options.toolId),
1631
+ operation: options.toolId,
1632
+ code,
1633
+ origin: "deepline",
1634
+ category: "network",
1635
+ // A direct client timeout has ambiguous delivery. Fail closed unless
1636
+ // the server returns the authoritative action delivery contract.
1637
+ retryable: false,
1638
+ statusCode: null,
1639
+ requestId: null,
1640
+ retryAfterMs: null,
1641
+ networkKind: code === "NETWORK_TIMEOUT" ? "timeout" : code === "NETWORK_ABORTED" ? "unknown" : "unavailable",
1642
+ networkScope: "client_to_deepline",
1643
+ details: networkDetails,
1644
+ publicDetails: options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : null
1645
+ }
1646
+ ),
1647
+ lastError
1648
+ );
1649
+ }
1650
+ throw withErrorCause(
1651
+ new DeeplineError(
1652
+ withCoworkNetworkHint(mappedNetworkError.message),
1653
+ void 0,
1654
+ mappedNetworkError.code,
1655
+ networkDetails
1656
+ ),
1657
+ lastError
1658
+ );
1659
+ }
1660
+ /**
1661
+ * Send a GET request.
1662
+ *
1663
+ * @typeParam T - Expected response body type
1664
+ * @param path - API path (e.g. `"/api/v2/tools"`)
1665
+ */
1666
+ async get(path, options) {
1667
+ return this.request(path, {
1668
+ method: "GET",
1669
+ retryApiErrors: true,
1670
+ ...options
1671
+ });
1672
+ }
1673
+ async *streamSse(path, options) {
1674
+ const url = `${this.config.baseUrl}${path}`;
1675
+ const method = options?.method ?? "GET";
1676
+ const headers = this.authHeaders({
1677
+ Accept: "text/event-stream",
1678
+ ...options?.headers
1679
+ });
1680
+ if (options?.body !== void 0) {
1681
+ applyExplicitHeaders(headers, { "Content-Type": "application/json" });
1682
+ }
1683
+ let lastError = null;
1684
+ for (const candidateUrl of buildCandidateUrls(url)) {
1685
+ try {
1686
+ const response = await fetch(candidateUrl, {
1687
+ method,
1688
+ headers,
1689
+ body: options?.body !== void 0 ? JSON.stringify(options.body) : void 0,
1690
+ signal: options?.signal
1691
+ });
1692
+ if (!response.ok) {
1693
+ const body = await response.text();
1694
+ const parsed = parseResponseBody(body);
1695
+ if (response.status === 401 && !isProviderOriginatedHttpError(parsed)) {
1696
+ throw new AuthError(apiErrorMessage(parsed, response.status));
1697
+ }
1698
+ const htmlError = detectHtmlErrorBody(
1699
+ body,
1700
+ response.headers.get("content-type")
1701
+ );
1702
+ if (htmlError) {
1703
+ throw new DeeplineError(
1704
+ htmlError.message(response.status),
1705
+ response.status,
1706
+ "API_ERROR",
1707
+ {
1708
+ htmlErrorPage: true,
1709
+ ...htmlError.title ? { title: htmlError.title } : {},
1710
+ ...htmlError.workerThrewException ? { workerThrewException: true } : {}
1711
+ }
1712
+ );
1713
+ }
1714
+ throw new DeeplineError(
1715
+ apiErrorMessage(parsed, response.status),
1716
+ response.status,
1717
+ apiErrorCodeFromResponse(parsed),
1718
+ { response: parsed }
1719
+ );
1720
+ }
1721
+ if (!response.body) {
1722
+ throw new DeeplineError("SSE response did not include a body.");
1723
+ }
1724
+ yield* decodeSseStream(response.body);
1725
+ return;
1726
+ } catch (error) {
1727
+ if (error instanceof AuthError || error instanceof DeeplineError) {
1728
+ throw error;
1729
+ }
1730
+ const normalized = error instanceof Error ? error : new Error(String(error));
1731
+ if (isAbortLikeError(normalized) && options?.signal?.aborted) {
1732
+ throw new DeeplineError(
1733
+ `Stream from ${this.config.baseUrl} was aborted by the caller.`,
1734
+ void 0,
1735
+ "ABORTED"
1736
+ );
1737
+ }
1738
+ lastError = normalized;
1739
+ }
1740
+ }
1741
+ if (lastError && isAbortLikeError(lastError)) {
1742
+ throw new DeeplineError(
1743
+ withCoworkNetworkHint(
1744
+ `Unable to stream from ${this.config.baseUrl}. The remote stream was interrupted.`
1745
+ ),
1746
+ void 0,
1747
+ "PLAY_STREAM_NETWORK_ABORTED"
1748
+ );
1749
+ }
1750
+ throw new DeeplineError(
1751
+ withCoworkNetworkHint(
1752
+ lastError?.message ? `Unable to stream from ${this.config.baseUrl}. ${lastError.message}` : `Unable to stream from ${this.config.baseUrl}.`
1753
+ )
1754
+ );
1755
+ }
1756
+ /**
1757
+ * Send a POST request with a JSON body.
1758
+ *
1759
+ * @typeParam T - Expected response body type
1760
+ * @param path - API path
1761
+ * @param body - Request body (will be JSON-serialized)
1762
+ */
1763
+ async post(path, body, headers, options) {
1764
+ return this.request(path, {
1765
+ method: "POST",
1766
+ body,
1767
+ headers,
1768
+ ...options
1769
+ });
1770
+ }
1771
+ async postFormData(path, formData, headers) {
1772
+ return this.request(path, {
1773
+ method: "POST",
1774
+ formData,
1775
+ headers
1776
+ });
1777
+ }
1778
+ /**
1779
+ * Send a PATCH request with a JSON body.
1780
+ *
1781
+ * @typeParam T - Expected response body type
1782
+ * @param path - API path
1783
+ * @param body - JSON-serializable request body
1784
+ */
1785
+ async patch(path, body, headers) {
1786
+ return this.request(path, {
1787
+ method: "PATCH",
1788
+ body,
1789
+ headers
1790
+ });
1791
+ }
1792
+ async put(path, body, headers) {
1793
+ return this.request(path, { method: "PUT", body, headers });
1794
+ }
1795
+ /**
1796
+ * Send a DELETE request.
1797
+ *
1798
+ * @typeParam T - Expected response body type
1799
+ * @param path - API path
1800
+ */
1801
+ async delete(path) {
1802
+ return this.request(path, { method: "DELETE" });
1803
+ }
1804
+ };
1805
+ function parseResponseBody(body) {
1806
+ try {
1807
+ return JSON.parse(body);
1808
+ } catch {
1809
+ return body;
1810
+ }
1811
+ }
1812
+ function isProviderOriginatedHttpError(parsed) {
1813
+ const response = asRecord(parsed);
1814
+ const error = asRecord(response?.error);
1815
+ const failureOrigin = error?.failure_origin ?? response?.failure_origin;
1816
+ const code = error?.code ?? response?.code;
1817
+ return failureOrigin === "provider" || code === "UPSTREAM_BLOCKED";
1818
+ }
1819
+ function isMonitorRateLimitEnvelope(parsed) {
1820
+ const response = asRecord(parsed);
1821
+ const error = asRecord(response?.error);
1822
+ return error?.code === "monitor_upstream_rate_limited" && typeof error.message === "string";
1823
+ }
1824
+ function asRecord(value) {
1825
+ return typeof value === "object" && value !== null ? value : null;
1826
+ }
1827
+ function isRetryableApiErrorResponse(status) {
1828
+ return status === 408 || status === 425 || status >= 500 && status < 600;
1829
+ }
1830
+ function detectHtmlErrorBody(body, contentType) {
1831
+ const trimmed = body.trim();
1832
+ const lower = trimmed.toLowerCase();
1833
+ const isHtml = (contentType ?? "").toLowerCase().includes("text/html") || lower.startsWith("<!doctype") || lower.startsWith("<html");
1834
+ if (!isHtml) {
1835
+ return null;
1836
+ }
1837
+ const titleMatch = trimmed.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
1838
+ const title = titleMatch?.[1]?.replace(/\s+/g, " ").trim() || void 0;
1839
+ const workerThrewException = /worker threw exception/i.test(trimmed);
1840
+ return {
1841
+ title,
1842
+ workerThrewException,
1843
+ message: (status) => {
1844
+ const segments = [`HTTP ${status}`];
1845
+ if (workerThrewException) {
1846
+ segments.push("Worker threw exception");
1847
+ }
1848
+ if (title) {
1849
+ segments.push(title);
1850
+ }
1851
+ return `${segments.join(": ")} (Cloudflare HTML error page suppressed)`;
1852
+ }
1853
+ };
1854
+ }
1855
+ function parseRetryAfter(response) {
1856
+ return parseOptionalRetryAfter(response) ?? 5e3;
1857
+ }
1858
+ function parseOptionalRetryAfter(response) {
1859
+ const header = response.headers.get("retry-after");
1860
+ if (header) {
1861
+ const seconds = Number(header);
1862
+ if (Number.isFinite(seconds) && seconds > 0) {
1863
+ return seconds * 1e3;
1864
+ }
1865
+ }
1866
+ return null;
1867
+ }
1868
+ function buildCandidateUrls(url) {
1869
+ try {
1870
+ const parsed = new URL(url);
1871
+ const candidates = [url];
1872
+ if (parsed.hostname === "localhost") {
1873
+ const loopback = new URL(url);
1874
+ loopback.hostname = "127.0.0.1";
1875
+ candidates.push(loopback.toString());
1876
+ }
1877
+ return [...new Set(candidates)];
1878
+ } catch {
1879
+ return [url];
1880
+ }
1881
+ }
1882
+ async function* decodeSseStream(body) {
1883
+ const reader = body.getReader();
1884
+ const decoder = new TextDecoder();
1885
+ let buffered = "";
1886
+ try {
1887
+ while (true) {
1888
+ const { value, done } = await reader.read();
1889
+ if (done) break;
1890
+ buffered += decoder.decode(value, { stream: true });
1891
+ const frames = buffered.split(/\r?\n\r?\n/);
1892
+ buffered = frames.pop() ?? "";
1893
+ for (const frame of frames) {
1894
+ const event2 = decodeSseFrame(frame);
1895
+ if (event2) {
1896
+ yield event2;
1897
+ }
1898
+ }
1899
+ }
1900
+ buffered += decoder.decode();
1901
+ const event = decodeSseFrame(buffered);
1902
+ if (event) {
1903
+ yield event;
1904
+ }
1905
+ } finally {
1906
+ reader.releaseLock();
1907
+ }
1908
+ }
1909
+ function decodeSseFrame(frame) {
1910
+ const data = frame.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice("data:".length).trimStart()).join("\n").trim();
1911
+ if (!data) {
1912
+ return null;
1913
+ }
1914
+ const parsed = JSON.parse(data);
1915
+ if (!parsed || typeof parsed !== "object" || typeof parsed.cursor !== "string" || typeof parsed.streamId !== "string" || typeof parsed.scope !== "string" || typeof parsed.type !== "string" || typeof parsed.at !== "string") {
1916
+ return null;
1917
+ }
1918
+ return parsed;
1919
+ }
1920
+ function sleep(ms, signal) {
1921
+ return new Promise((resolve2, reject) => {
1922
+ if (signal?.aborted) {
1923
+ reject(requestCancelledError(signal));
1924
+ return;
1925
+ }
1926
+ const timeoutId = setTimeout(() => {
1927
+ signal?.removeEventListener("abort", abort);
1928
+ resolve2();
1929
+ }, ms);
1930
+ const abort = () => {
1931
+ clearTimeout(timeoutId);
1932
+ signal?.removeEventListener("abort", abort);
1933
+ reject(requestCancelledError(signal));
1934
+ };
1935
+ signal?.addEventListener("abort", abort, { once: true });
1936
+ });
1937
+ }
1938
+ function withCoworkNetworkHint(message) {
1939
+ if (!isCoworkLikeSandbox2() || message.includes(COWORK_NETWORK_HINT)) {
1940
+ return message;
1941
+ }
1942
+ return `${message}
1943
+ ${COWORK_NETWORK_HINT}`;
1944
+ }
1945
+
1946
+ export {
1947
+ AuthError,
1948
+ RateLimitError,
1949
+ ToolRateLimitError,
1950
+ ConfigError,
1951
+ HOST_URL_ENV,
1952
+ API_KEY_ENV,
1953
+ ACTIVE_ORG_ID_ENV,
1954
+ ACTIVE_ORG_NAME_ENV,
1955
+ FEATURES_ENV,
1956
+ PROD_URL,
1957
+ featureEnvValues,
1958
+ storedHostApiKey,
1959
+ storedHostFeatures,
1960
+ baseUrlSlug,
1961
+ sdkCliStateDirPath,
1962
+ hostConfigDirPath,
1963
+ hostEnvFilePath,
1964
+ saveHostEnvValues,
1965
+ autoDetectBaseUrl,
1966
+ resolveApiKeyForBaseUrl,
1967
+ resolveProjectApiKeyForBaseUrl,
1968
+ resolveGlobalApiKeyForBaseUrl,
1969
+ getResolvedProjectAuthSource,
1970
+ resolveBaseUrlOnly,
1971
+ resolveConfig,
1972
+ ensureProjectPrivatePathsIgnored,
1973
+ saveProjectDeeplineEnvValues,
1974
+ resolveProjectPinTarget,
1975
+ getActiveProjectAuthSource,
1976
+ resolveCliAuthProvenance,
1977
+ resolveCliCommandContext,
1978
+ SDK_VERSION,
1979
+ SDK_API_MAJOR,
1980
+ SDK_API_CONTRACT,
1981
+ detectAgentRuntime,
1982
+ hasActivePluginSkills,
1983
+ KNOWN_SKILL_AGENTS,
1984
+ DEFAULT_SKILL_AGENTS,
1985
+ skillsAgentPathSegment,
1986
+ resolveAutoSyncSkillAgents,
1987
+ readSdkSkillsLocalVersion,
1988
+ writeSdkSkillsLocalVersion,
1989
+ deploymentProtectionHeaders,
1990
+ fetchWithDeploymentProtection,
1991
+ COORDINATOR_INTERNAL_TOKEN_HEADER,
1992
+ RUNTIME_ENVIRONMENT_TOKEN_HEADER,
1993
+ RETAINED_PIPELINE_RECEIVERS_HEADER,
1994
+ HttpClient
1995
+ };