@acosmi/sdk-ts 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1405,9 +1405,18 @@ function skillScopes() {
1405
1405
  }
1406
1406
 
1407
1407
  // src/store.ts
1408
+ var fileLockDefaults = {
1409
+ /** 获取锁的超时上限 (毫秒). refresh 流程含网络 < 30s, 30s 已远超正常完成时间. */
1410
+ acquireTimeoutMs: 3e4,
1411
+ /** 旧锁判定阈值 (毫秒). 锁文件 mtime 早于此值视为 stale 进程崩溃残留, 自动 break. */
1412
+ staleMs: 6e4,
1413
+ /** 重试间隔基数 (毫秒). 真实间隔 = base + random(0, jitter). */
1414
+ retryBaseMs: 30,
1415
+ retryJitterMs: 70
1416
+ };
1408
1417
  var FileTokenStore = class {
1409
1418
  path;
1410
- /** 简单串行化锁 (替代 Go sync.Mutex) */
1419
+ /** 进程内串行化 (Promise chain) — 与跨进程 flock 配合, 避免单进程内并发持锁产生死锁式互等. */
1411
1420
  chain = Promise.resolve();
1412
1421
  constructor(path) {
1413
1422
  if (typeof process === "undefined" || !process.versions || !process.versions.node) {
@@ -1426,7 +1435,9 @@ var FileTokenStore = class {
1426
1435
  this.path = path.join(os.homedir(), ".acosmi", "tokens.json");
1427
1436
  return this.path;
1428
1437
  }
1429
- withLock(fn) {
1438
+ /** 进程内串行 (维持 v1.0.1 单进程语义). flock 之外另一层防御: 如果用户自己就是单进程
1439
+ * 并发场景, 不必每次都进 flock 旁路文件 IO. */
1440
+ withChain(fn) {
1430
1441
  const next = this.chain.then(fn, fn);
1431
1442
  this.chain = next.then(
1432
1443
  () => void 0,
@@ -1434,19 +1445,106 @@ var FileTokenStore = class {
1434
1445
  );
1435
1446
  return next;
1436
1447
  }
1448
+ /**
1449
+ * 跨进程临界区. 用 sidecar `<path>.lock` 文件 + O_EXCL 创建语义实现互斥:
1450
+ * - 创建成功 = 持有锁; 写入 pid+timestamp 便于诊断
1451
+ * - 创建失败 (EEXIST) = 别的进程持锁, backoff 重试
1452
+ * - 锁文件 mtime > staleMs = 进程崩溃残留, unlink 后重试
1453
+ * - acquireTimeoutMs 超时 = 抛错 (caller 应作为 transient error 处理, 上层 retry)
1454
+ *
1455
+ * 注意: O_EXCL 在 NFS 上不保证原子; FileTokenStore 适用于本地文件系统 (典型用户家目录).
1456
+ * 真要跨机共享 token, 应实现自定义 Keychain / 数据库 store, 不要用 FileTokenStore.
1457
+ */
1458
+ async withLock(fn) {
1459
+ const fs = await import('fs/promises');
1460
+ const pathMod = await import('path');
1461
+ const p = await this.resolvePath();
1462
+ const lockPath = `${p}.lock`;
1463
+ const dir = pathMod.dirname(p);
1464
+ await fs.mkdir(dir, { recursive: true, mode: 448 });
1465
+ const startMs = Date.now();
1466
+ let release = null;
1467
+ while (true) {
1468
+ try {
1469
+ const fh = await fs.open(lockPath, "wx", 384);
1470
+ try {
1471
+ await fh.writeFile(`${process.pid}
1472
+ ${Date.now()}
1473
+ `, "utf8");
1474
+ } finally {
1475
+ await fh.close();
1476
+ }
1477
+ release = async () => {
1478
+ try {
1479
+ await fs.unlink(lockPath);
1480
+ } catch {
1481
+ }
1482
+ };
1483
+ break;
1484
+ } catch (e) {
1485
+ if (!isAlreadyExistsError(e)) throw e;
1486
+ let stale = false;
1487
+ try {
1488
+ const st = await fs.stat(lockPath);
1489
+ if (Date.now() - st.mtimeMs > fileLockDefaults.staleMs) stale = true;
1490
+ } catch {
1491
+ continue;
1492
+ }
1493
+ if (stale) {
1494
+ try {
1495
+ await fs.unlink(lockPath);
1496
+ } catch {
1497
+ }
1498
+ continue;
1499
+ }
1500
+ if (Date.now() - startMs > fileLockDefaults.acquireTimeoutMs) {
1501
+ throw new Error(
1502
+ `acquire token file lock timeout (${fileLockDefaults.acquireTimeoutMs}ms): ${lockPath}`
1503
+ );
1504
+ }
1505
+ const waitMs = fileLockDefaults.retryBaseMs + Math.random() * fileLockDefaults.retryJitterMs;
1506
+ await new Promise((r) => setTimeout(r, waitMs));
1507
+ }
1508
+ }
1509
+ try {
1510
+ return await fn();
1511
+ } finally {
1512
+ if (release) await release();
1513
+ }
1514
+ }
1515
+ /**
1516
+ * 写入 token. 流程:
1517
+ * 1. mkdir -p (默认路径目录)
1518
+ * 2. 写入 `<path>.tmp.<pid>`
1519
+ * 3. fsync 后 rename 到正式路径 (POSIX 上 rename(2) 同分区原子, Windows 上 ReplaceFile)
1520
+ *
1521
+ * 选择 atomic rename 而非直接 writeFile: 多进程并发或本进程崩溃时, 读端永远看到的是
1522
+ * 完整的旧/新 JSON, 不会读到截断半文件 (Client.create.store.load 可能在另一进程
1523
+ * 写入中间触发, atomic rename 避免它解析失败).
1524
+ */
1437
1525
  save(tokens) {
1438
- return this.withLock(async () => {
1526
+ return this.withChain(async () => {
1439
1527
  const fs = await import('fs/promises');
1440
- const path = await import('path');
1528
+ const pathMod = await import('path');
1441
1529
  const p = await this.resolvePath();
1442
- const dir = path.dirname(p);
1530
+ const dir = pathMod.dirname(p);
1443
1531
  await fs.mkdir(dir, { recursive: true, mode: 448 });
1532
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}.${Math.floor(Math.random() * 1e6)}`;
1444
1533
  const data = JSON.stringify(tokens, null, 2);
1445
- await fs.writeFile(p, data, { encoding: "utf8", mode: 384 });
1534
+ await fs.writeFile(tmp, data, { encoding: "utf8", mode: 384 });
1535
+ try {
1536
+ await fs.rename(tmp, p);
1537
+ } catch (e) {
1538
+ try {
1539
+ await fs.unlink(tmp);
1540
+ } catch {
1541
+ }
1542
+ throw e;
1543
+ }
1446
1544
  });
1447
1545
  }
1448
1546
  load() {
1449
- return this.withLock(async () => {
1547
+ return this.withChain(async () => {
1450
1548
  const fs = await import('fs/promises');
1451
1549
  const p = await this.resolvePath();
1452
1550
  try {
@@ -1461,7 +1559,7 @@ var FileTokenStore = class {
1461
1559
  });
1462
1560
  }
1463
1561
  clear() {
1464
- return this.withLock(async () => {
1562
+ return this.withChain(async () => {
1465
1563
  const fs = await import('fs/promises');
1466
1564
  const p = await this.resolvePath();
1467
1565
  try {
@@ -1479,6 +1577,12 @@ function isNotExistError(e) {
1479
1577
  }
1480
1578
  return false;
1481
1579
  }
1580
+ function isAlreadyExistsError(e) {
1581
+ if (typeof e === "object" && e !== null && "code" in e) {
1582
+ return e.code === "EEXIST";
1583
+ }
1584
+ return false;
1585
+ }
1482
1586
  function newFileTokenStore(path) {
1483
1587
  return new FileTokenStore(path);
1484
1588
  }
@@ -1870,8 +1974,25 @@ function extractAnthropicBlockMeta(eventType, data, blockTypeMap) {
1870
1974
  }
1871
1975
  }
1872
1976
 
1873
- // src/index.ts
1874
- init_betas();
1977
+ // src/agent-runs-types.ts
1978
+ var AgentRunStreamError = class extends Error {
1979
+ event;
1980
+ code;
1981
+ stage;
1982
+ retryable;
1983
+ constructor(event) {
1984
+ const err = event.error;
1985
+ super(err.stage ? `agent run failed: ${err.stage}: ${err.message}` : `agent run failed: ${err.message}`);
1986
+ this.name = "AgentRunStreamError";
1987
+ this.event = event;
1988
+ this.code = err.code ?? "";
1989
+ this.stage = err.stage ?? "";
1990
+ this.retryable = err.retryable ?? false;
1991
+ }
1992
+ };
1993
+
1994
+ // src/client/agent-runs.ts
1995
+ init_types();
1875
1996
 
1876
1997
  // src/client.ts
1877
1998
  init_types();
@@ -2345,61 +2466,67 @@ var Client = class _Client {
2345
2466
  if (!tokenSetIsExpired(tokens)) {
2346
2467
  return tokens.access_token;
2347
2468
  }
2348
- return this.withMu(async () => {
2349
- if (this.tokens == null) {
2350
- throw new Error("not authorized, call login() first");
2351
- }
2352
- if (!tokenSetIsExpired(this.tokens)) {
2353
- return this.tokens.access_token;
2354
- }
2355
- if (this.meta == null) {
2469
+ return this.withMu(
2470
+ () => this.storeWithLock(async () => {
2471
+ await this.syncFromDisk();
2472
+ if (this.tokens == null) {
2473
+ throw new Error("not authorized, call login() first");
2474
+ }
2475
+ if (!tokenSetIsExpired(this.tokens)) {
2476
+ return this.tokens.access_token;
2477
+ }
2478
+ if (this.meta == null) {
2479
+ try {
2480
+ this.meta = await discover(this.serverURL, signal);
2481
+ } catch (e) {
2482
+ throw new Error(
2483
+ `discover for refresh: ${e instanceof Error ? e.message : String(e)}`
2484
+ );
2485
+ }
2486
+ }
2487
+ let tokenResp;
2356
2488
  try {
2357
- this.meta = await discover(this.serverURL, signal);
2489
+ tokenResp = await refreshToken(this.meta, this.tokens.client_id, this.tokens.refresh_token, signal);
2358
2490
  } catch (e) {
2359
- throw new Error(
2360
- `discover for refresh: ${e instanceof Error ? e.message : String(e)}`
2361
- );
2491
+ throw new Error(`refresh token: ${e instanceof Error ? e.message : String(e)}`);
2362
2492
  }
2363
- }
2364
- let tokenResp;
2365
- try {
2366
- tokenResp = await refreshToken(this.meta, this.tokens.client_id, this.tokens.refresh_token, signal);
2367
- } catch (e) {
2368
- throw new Error(`refresh token: ${e instanceof Error ? e.message : String(e)}`);
2369
- }
2370
- this.tokens = newTokenSet(tokenResp, this.tokens.client_id, this.serverURL);
2371
- try {
2372
- await this.store.save(this.tokens);
2373
- } catch (e) {
2374
- console.warn(`[acosmi-sdk] warning: save refreshed token failed: ${e instanceof Error ? e.message : String(e)}`);
2375
- }
2376
- return this.tokens.access_token;
2377
- });
2493
+ this.tokens = newTokenSet(tokenResp, this.tokens.client_id, this.serverURL);
2494
+ try {
2495
+ await this.store.save(this.tokens);
2496
+ } catch (e) {
2497
+ console.warn(`[acosmi-sdk] warning: save refreshed token failed: ${e instanceof Error ? e.message : String(e)}`);
2498
+ }
2499
+ return this.tokens.access_token;
2500
+ })
2501
+ );
2378
2502
  }
2379
2503
  /** 强制刷新 token (用于 401 重试) */
2380
2504
  async forceRefresh(signal) {
2381
- return this.withMu(async () => {
2382
- if (this.tokens == null) {
2383
- throw new Error("no tokens to refresh");
2384
- }
2385
- if (this.meta == null) {
2386
- this.meta = await discover(this.serverURL, signal);
2387
- }
2388
- const tokenResp = await refreshToken(
2389
- this.meta,
2390
- this.tokens.client_id,
2391
- this.tokens.refresh_token,
2392
- signal
2393
- );
2394
- this.tokens = newTokenSet(tokenResp, this.tokens.client_id, this.serverURL);
2395
- try {
2396
- await this.store.save(this.tokens);
2397
- } catch (e) {
2398
- console.warn(
2399
- `[acosmi-sdk] warning: save refreshed token failed: ${e instanceof Error ? e.message : String(e)}`
2505
+ return this.withMu(
2506
+ () => this.storeWithLock(async () => {
2507
+ await this.syncFromDisk();
2508
+ if (this.tokens == null) {
2509
+ throw new Error("no tokens to refresh");
2510
+ }
2511
+ if (this.meta == null) {
2512
+ this.meta = await discover(this.serverURL, signal);
2513
+ }
2514
+ const tokenResp = await refreshToken(
2515
+ this.meta,
2516
+ this.tokens.client_id,
2517
+ this.tokens.refresh_token,
2518
+ signal
2400
2519
  );
2401
- }
2402
- });
2520
+ this.tokens = newTokenSet(tokenResp, this.tokens.client_id, this.serverURL);
2521
+ try {
2522
+ await this.store.save(this.tokens);
2523
+ } catch (e) {
2524
+ console.warn(
2525
+ `[acosmi-sdk] warning: save refreshed token failed: ${e instanceof Error ? e.message : String(e)}`
2526
+ );
2527
+ }
2528
+ })
2529
+ );
2403
2530
  }
2404
2531
  /** 互斥锁 helper (替代 Go sync.Mutex) */
2405
2532
  withMu(fn) {
@@ -2410,6 +2537,29 @@ var Client = class _Client {
2410
2537
  );
2411
2538
  return next;
2412
2539
  }
2540
+ /** v1.0.2: 跨进程临界区 helper. store.withLock 可选, 缺省则直接调用 fn (LocalStorage /
2541
+ * InMemory 单进程无需). */
2542
+ async storeWithLock(fn) {
2543
+ const lock = this.store.withLock;
2544
+ if (typeof lock === "function") {
2545
+ return lock.call(this.store, fn);
2546
+ }
2547
+ return fn();
2548
+ }
2549
+ /** v1.0.2: 从磁盘同步 token (refresh 前). 别的进程 rotation 后磁盘 refresh_token 已变,
2550
+ * 本进程内存仍是旧 R0; 不同步直接 refresh 必撞网关 400. load 失败保留内存继续 (容错). */
2551
+ async syncFromDisk() {
2552
+ let onDisk = null;
2553
+ try {
2554
+ onDisk = await this.store.load();
2555
+ } catch {
2556
+ return;
2557
+ }
2558
+ if (!onDisk) return;
2559
+ if (this.tokens == null || onDisk.refresh_token !== this.tokens.refresh_token) {
2560
+ this.tokens = onDisk;
2561
+ }
2562
+ }
2413
2563
  // ===========================================================================
2414
2564
  // Managed Models
2415
2565
  // ===========================================================================
@@ -3123,6 +3273,487 @@ async function sleep(ms, signal) {
3123
3273
  });
3124
3274
  }
3125
3275
 
3276
+ // src/client/agent-runs.ts
3277
+ var agentRunsByClient = /* @__PURE__ */ new WeakMap();
3278
+ Object.defineProperty(Client.prototype, "agentRuns", {
3279
+ configurable: true,
3280
+ enumerable: false,
3281
+ get() {
3282
+ let existing = agentRunsByClient.get(this);
3283
+ if (!existing) {
3284
+ existing = new AgentRunsClient(this);
3285
+ agentRunsByClient.set(this, existing);
3286
+ }
3287
+ return existing;
3288
+ }
3289
+ });
3290
+ var AgentRunsClient = class {
3291
+ constructor(client) {
3292
+ this.client = client;
3293
+ }
3294
+ client;
3295
+ async create(req, signal) {
3296
+ const resp = await this.requestAPI(
3297
+ "POST",
3298
+ "/agent-runs",
3299
+ toWireCreateRequest(req),
3300
+ signal,
3301
+ { retryOn401: false }
3302
+ );
3303
+ return fromWireCreateResponse(resp);
3304
+ }
3305
+ get(runId, signal) {
3306
+ return this.requestAPI(
3307
+ "GET",
3308
+ `/agent-runs/${encodeURIComponent(runId)}`,
3309
+ null,
3310
+ signal,
3311
+ { retryOn401: true }
3312
+ ).then(fromWireRun);
3313
+ }
3314
+ stream(runId, opts = {}, signal) {
3315
+ return {
3316
+ [Symbol.asyncIterator]: () => this.streamGen(runId, opts, signal)
3317
+ };
3318
+ }
3319
+ cancel(runId, signal) {
3320
+ return this.requestAPI(
3321
+ "POST",
3322
+ `/agent-runs/${encodeURIComponent(runId)}/cancel`,
3323
+ {},
3324
+ signal,
3325
+ { retryOn401: false }
3326
+ ).then(fromWireRun);
3327
+ }
3328
+ listArtifacts(runId, signal) {
3329
+ return this.requestAPI(
3330
+ "GET",
3331
+ `/agent-runs/${encodeURIComponent(runId)}/artifacts`,
3332
+ null,
3333
+ signal,
3334
+ { retryOn401: true }
3335
+ ).then((r) => (r.artifacts ?? []).map(fromWireArtifact));
3336
+ }
3337
+ async downloadArtifact(runId, artifactId, signal) {
3338
+ const resp = await this.requestRaw(
3339
+ "GET",
3340
+ `/agent-runs/${encodeURIComponent(runId)}/artifacts/${encodeURIComponent(artifactId)}`,
3341
+ null,
3342
+ signal,
3343
+ { retryOn401: true }
3344
+ );
3345
+ const contentType = resp.headers.get("Content-Type") ?? void 0;
3346
+ const filename = filenameFromContentDisposition(resp.headers.get("Content-Disposition")) ?? artifactId;
3347
+ const data = await readLimited(resp.body, maxDownloadSize);
3348
+ return { data, filename, contentType };
3349
+ }
3350
+ submitLocalToolResult(runId, result, signal) {
3351
+ return this.requestAPI(
3352
+ "POST",
3353
+ `/agent-runs/${encodeURIComponent(runId)}/local-tool-results`,
3354
+ toWireLocalToolResult(result),
3355
+ signal,
3356
+ { retryOn401: false }
3357
+ ).then(fromWireRun);
3358
+ }
3359
+ run(req, opts = {}, signal) {
3360
+ return {
3361
+ [Symbol.asyncIterator]: () => this.runGen(req, opts, signal)
3362
+ };
3363
+ }
3364
+ runWithLocalTools(req, handlers, opts = {}, signal) {
3365
+ return {
3366
+ [Symbol.asyncIterator]: () => this.runWithLocalToolsGen(req, handlers, opts, signal)
3367
+ };
3368
+ }
3369
+ async *runGen(req, opts, signal) {
3370
+ const created = await this.create(req, signal);
3371
+ yield* this.stream(created.runId, opts, signal);
3372
+ }
3373
+ async *runWithLocalToolsGen(req, handlers, opts, signal) {
3374
+ let currentRunId = "";
3375
+ for await (const event of this.run(req, opts, signal)) {
3376
+ if (event.type === "run_started") {
3377
+ currentRunId = event.runId;
3378
+ }
3379
+ if (opts.onEvent) await opts.onEvent(event);
3380
+ let localToolTask;
3381
+ if (event.type === "local_tool_request") {
3382
+ if (currentRunId === "") {
3383
+ throw new Error("local tool request arrived before run_started");
3384
+ }
3385
+ localToolTask = this.invokeLocalTool(currentRunId, event, handlers, opts.timeoutMs, signal).then(async (result) => {
3386
+ await this.submitLocalToolResult(currentRunId, result, signal);
3387
+ });
3388
+ }
3389
+ yield event;
3390
+ if (localToolTask) await localToolTask;
3391
+ }
3392
+ }
3393
+ async invokeLocalTool(runId, event, handlers, timeoutMs = 3e4, signal) {
3394
+ const handler = handlers[event.name];
3395
+ if (!handler) {
3396
+ return {
3397
+ requestId: event.requestId,
3398
+ ok: false,
3399
+ error: `local tool rejected: no handler for ${event.name}`
3400
+ };
3401
+ }
3402
+ const ctl = new AbortController();
3403
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
3404
+ let parentAbort;
3405
+ if (signal) {
3406
+ if (signal.aborted) ctl.abort();
3407
+ else {
3408
+ parentAbort = () => ctl.abort();
3409
+ signal.addEventListener("abort", parentAbort);
3410
+ }
3411
+ }
3412
+ try {
3413
+ const content = await handler(event.input, {
3414
+ runId,
3415
+ requestId: event.requestId,
3416
+ name: event.name,
3417
+ signal: ctl.signal
3418
+ });
3419
+ return { requestId: event.requestId, ok: true, content };
3420
+ } catch (e) {
3421
+ if (signal?.aborted) throw e;
3422
+ const timedOut = ctl.signal.aborted;
3423
+ return {
3424
+ requestId: event.requestId,
3425
+ ok: false,
3426
+ error: timedOut ? `local tool timed out after ${timeoutMs}ms` : errorMessage(e)
3427
+ };
3428
+ } finally {
3429
+ clearTimeout(timer);
3430
+ if (parentAbort && signal) signal.removeEventListener("abort", parentAbort);
3431
+ }
3432
+ }
3433
+ async *streamGen(runId, opts, signal) {
3434
+ const resp = await this.requestRaw(
3435
+ "GET",
3436
+ `/agent-runs/${encodeURIComponent(runId)}/stream`,
3437
+ null,
3438
+ signal,
3439
+ { retryOn401: true, accept: "text/event-stream" }
3440
+ );
3441
+ if (!resp.body) {
3442
+ throw new Error("agent run stream: empty response body");
3443
+ }
3444
+ for await (const event of readAgentRunEvents(resp.body)) {
3445
+ if (event.type === "error" && opts.throwOnError !== false) {
3446
+ throw new AgentRunStreamError(event);
3447
+ }
3448
+ yield event;
3449
+ }
3450
+ }
3451
+ async requestAPI(method, path, body, signal, opts) {
3452
+ const resp = await this.requestRaw(method, path, body, signal, opts);
3453
+ const text = await resp.text();
3454
+ const result = JSON.parse(text);
3455
+ const bizErr = apiResponseBusinessError(result);
3456
+ if (bizErr) throw bizErr;
3457
+ return result.data;
3458
+ }
3459
+ async requestRaw(method, path, body, signal, opts, retried = false) {
3460
+ const token = await this.client.ensureToken(signal);
3461
+ const url = this.client.apiURL(path);
3462
+ const headers = {
3463
+ Authorization: `Bearer ${token}`,
3464
+ Accept: opts.accept ?? "application/json"
3465
+ };
3466
+ let bodyStr;
3467
+ if (body != null) {
3468
+ bodyStr = typeof body === "string" ? body : JSON.stringify(body);
3469
+ headers["Content-Type"] = "application/json";
3470
+ }
3471
+ const resp = await this.client.doRequest({ method, url, headers, body: bodyStr }, signal);
3472
+ if (resp.status === 401 && opts.retryOn401 && !retried) {
3473
+ try {
3474
+ await resp.body?.cancel();
3475
+ } catch {
3476
+ }
3477
+ await this.client.forceRefresh(signal);
3478
+ return this.requestRaw(method, path, body, signal, opts, true);
3479
+ }
3480
+ if (resp.status < 200 || resp.status >= 300) {
3481
+ const bodyBytes = resp.body ? await readLimited(resp.body, maxErrorBodySize) : new Uint8Array();
3482
+ throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
3483
+ }
3484
+ return resp;
3485
+ }
3486
+ };
3487
+ function toWireCreateRequest(req) {
3488
+ return {
3489
+ app_id: req.appId,
3490
+ mode: req.mode,
3491
+ session_id: req.sessionId,
3492
+ input: req.input,
3493
+ messages: req.messages,
3494
+ model: req.model,
3495
+ active_skill_ids: req.activeSkillIds,
3496
+ knowledge_base_ids: req.knowledgeBaseIds,
3497
+ metadata: req.metadata,
3498
+ local_context_policy: req.localContextPolicy ? {
3499
+ enabled: req.localContextPolicy.enabled,
3500
+ readonly: req.localContextPolicy.readonly,
3501
+ max_bytes: req.localContextPolicy.maxBytes,
3502
+ allowed_tools: req.localContextPolicy.allowedTools
3503
+ } : void 0,
3504
+ artifact_policy: req.artifactPolicy ? {
3505
+ enabled: req.artifactPolicy.enabled,
3506
+ max_files: req.artifactPolicy.maxFiles
3507
+ } : void 0
3508
+ };
3509
+ }
3510
+ function toWireLocalToolResult(result) {
3511
+ return {
3512
+ request_id: result.requestId,
3513
+ ok: result.ok,
3514
+ content: result.content,
3515
+ error: result.error
3516
+ };
3517
+ }
3518
+ function fromWireCreateResponse(resp) {
3519
+ return {
3520
+ runId: resp.run_id ?? "",
3521
+ sessionId: resp.session_id ?? "",
3522
+ status: toStatus(resp.status)
3523
+ };
3524
+ }
3525
+ function fromWireRun(resp) {
3526
+ return {
3527
+ runId: resp.run_id ?? "",
3528
+ sessionId: resp.session_id ?? "",
3529
+ appId: resp.app_id,
3530
+ mode: resp.mode,
3531
+ status: toStatus(resp.status),
3532
+ createdAt: resp.created_at,
3533
+ startedAt: resp.started_at,
3534
+ completedAt: resp.completed_at,
3535
+ error: normalizeError(resp.error),
3536
+ metadata: resp.metadata
3537
+ };
3538
+ }
3539
+ function fromWireArtifact(resp) {
3540
+ return {
3541
+ id: resp.id ?? resp.artifact_id ?? "",
3542
+ filename: resp.filename ?? resp.name ?? resp.id ?? resp.artifact_id ?? "artifact",
3543
+ contentType: resp.content_type ?? resp.mime_type,
3544
+ size: typeof resp.size === "number" ? resp.size : void 0,
3545
+ type: resp.type,
3546
+ metadata: resp.metadata
3547
+ };
3548
+ }
3549
+ async function* readAgentRunEvents(body) {
3550
+ let eventName = "";
3551
+ let dataLines = [];
3552
+ const flush = () => {
3553
+ if (dataLines.length === 0) return null;
3554
+ const data = dataLines.join("\n");
3555
+ dataLines = [];
3556
+ if (data === "[DONE]") return null;
3557
+ return parseAgentRunEvent(eventName, data);
3558
+ };
3559
+ for await (const line of iterSSELines(body)) {
3560
+ if (line === "") {
3561
+ const event2 = flush();
3562
+ eventName = "";
3563
+ if (event2) yield event2;
3564
+ continue;
3565
+ }
3566
+ if (line.startsWith(":")) continue;
3567
+ if (line.startsWith("event:")) {
3568
+ eventName = line.slice("event:".length).trim();
3569
+ continue;
3570
+ }
3571
+ if (line.startsWith("data:")) {
3572
+ dataLines.push(line.slice("data:".length).trimStart());
3573
+ }
3574
+ }
3575
+ const event = flush();
3576
+ if (event) yield event;
3577
+ }
3578
+ function parseAgentRunEvent(eventName, data) {
3579
+ const payload = JSON.parse(data);
3580
+ const obj = isRecord(payload) ? payload : { type: eventName, data: payload };
3581
+ const type = stringField(obj, "type") || eventName;
3582
+ switch (type) {
3583
+ case "run_started":
3584
+ return {
3585
+ type: "run_started",
3586
+ runId: stringField(obj, "run_id", "runId"),
3587
+ sessionId: stringField(obj, "session_id", "sessionId")
3588
+ };
3589
+ case "status":
3590
+ return {
3591
+ type: "status",
3592
+ status: stringField(obj, "status"),
3593
+ message: optionalStringField(obj, "message")
3594
+ };
3595
+ case "text_delta":
3596
+ return { type: "text_delta", text: stringField(obj, "text") };
3597
+ case "reasoning_delta":
3598
+ return { type: "reasoning_delta", text: stringField(obj, "text") };
3599
+ case "tool_call":
3600
+ return {
3601
+ type: "tool_call",
3602
+ id: stringField(obj, "id"),
3603
+ name: stringField(obj, "name"),
3604
+ input: obj.input
3605
+ };
3606
+ case "tool_result":
3607
+ return {
3608
+ type: "tool_result",
3609
+ id: stringField(obj, "id"),
3610
+ name: optionalStringField(obj, "name"),
3611
+ result: obj.result,
3612
+ error: optionalStringField(obj, "error")
3613
+ };
3614
+ case "local_tool_request":
3615
+ return {
3616
+ type: "local_tool_request",
3617
+ requestId: stringField(obj, "request_id", "requestId"),
3618
+ name: stringField(obj, "name"),
3619
+ input: obj.input
3620
+ };
3621
+ case "artifact":
3622
+ return {
3623
+ type: "artifact",
3624
+ artifact: fromWireArtifact(isRecord(obj.artifact) ? obj.artifact : obj)
3625
+ };
3626
+ case "sources":
3627
+ return { type: "sources", sources: obj.sources };
3628
+ case "usage":
3629
+ return {
3630
+ type: "usage",
3631
+ usage: normalizeUsage(isRecord(obj.usage) ? obj.usage : obj)
3632
+ };
3633
+ case "settle":
3634
+ return {
3635
+ type: "settle",
3636
+ settlement: normalizeSettlement(isRecord(obj.settlement) ? obj.settlement : obj)
3637
+ };
3638
+ case "error":
3639
+ return { type: "error", error: normalizeError(obj.error) ?? normalizeError(obj) };
3640
+ case "done":
3641
+ return {
3642
+ type: "done",
3643
+ runId: stringField(obj, "run_id", "runId"),
3644
+ status: stringField(obj, "status")
3645
+ };
3646
+ default:
3647
+ return {
3648
+ type: "error",
3649
+ error: {
3650
+ code: "unknown_event",
3651
+ message: `unknown agent run event: ${type}`,
3652
+ raw: obj
3653
+ }
3654
+ };
3655
+ }
3656
+ }
3657
+ function normalizeUsage(value) {
3658
+ return {
3659
+ ...value,
3660
+ inputTokens: numberField(value, "input_tokens", "inputTokens"),
3661
+ outputTokens: numberField(value, "output_tokens", "outputTokens"),
3662
+ totalTokens: numberField(value, "total_tokens", "totalTokens"),
3663
+ cacheReadTokens: numberField(value, "cache_read_tokens", "cacheReadTokens"),
3664
+ cacheCreateTokens: numberField(value, "cache_create_tokens", "cacheCreateTokens"),
3665
+ exact: booleanField(value, "exact"),
3666
+ source: optionalStringField(value, "source")
3667
+ };
3668
+ }
3669
+ function normalizeSettlement(value) {
3670
+ return {
3671
+ ...value,
3672
+ requestId: optionalStringField(value, "request_id", "requestId"),
3673
+ status: optionalStringField(value, "status"),
3674
+ consumeStatus: optionalStringField(value, "consume_status", "consumeStatus"),
3675
+ inputTokens: numberField(value, "input_tokens", "inputTokens"),
3676
+ outputTokens: numberField(value, "output_tokens", "outputTokens"),
3677
+ totalTokens: numberField(value, "total_tokens", "totalTokens"),
3678
+ cacheReadTokens: numberField(value, "cache_read_tokens", "cacheReadTokens"),
3679
+ cacheCreateTokens: numberField(value, "cache_create_tokens", "cacheCreateTokens"),
3680
+ tokenRemaining: numberField(value, "token_remaining", "tokenRemaining"),
3681
+ callRemaining: numberField(value, "call_remaining", "callRemaining"),
3682
+ retryQueued: booleanField(value, "retry_queued", "retryQueued"),
3683
+ exact: booleanField(value, "exact")
3684
+ };
3685
+ }
3686
+ function normalizeError(value) {
3687
+ if (value == null) return void 0;
3688
+ if (typeof value === "string") return { message: value, raw: value };
3689
+ if (!isRecord(value)) return { message: String(value), raw: value };
3690
+ return {
3691
+ code: optionalStringField(value, "code", "error_code", "errorCode"),
3692
+ message: stringField(value, "message", "error") || "agent run failed",
3693
+ stage: optionalStringField(value, "stage"),
3694
+ retryable: typeof value.retryable === "boolean" ? value.retryable : void 0,
3695
+ raw: value
3696
+ };
3697
+ }
3698
+ function toStatus(status) {
3699
+ switch (status) {
3700
+ case "running":
3701
+ case "completed":
3702
+ case "failed":
3703
+ case "cancelled":
3704
+ return status;
3705
+ default:
3706
+ return "queued";
3707
+ }
3708
+ }
3709
+ function isRecord(value) {
3710
+ return value != null && typeof value === "object" && !Array.isArray(value);
3711
+ }
3712
+ function stringField(obj, ...keys) {
3713
+ for (const key of keys) {
3714
+ const value = obj[key];
3715
+ if (typeof value === "string") return value;
3716
+ }
3717
+ return "";
3718
+ }
3719
+ function optionalStringField(obj, ...keys) {
3720
+ const value = stringField(obj, ...keys);
3721
+ return value === "" ? void 0 : value;
3722
+ }
3723
+ function numberField(obj, ...keys) {
3724
+ for (const key of keys) {
3725
+ const value = obj[key];
3726
+ if (typeof value === "number" && Number.isFinite(value)) return value;
3727
+ }
3728
+ return void 0;
3729
+ }
3730
+ function booleanField(obj, ...keys) {
3731
+ for (const key of keys) {
3732
+ const value = obj[key];
3733
+ if (typeof value === "boolean") return value;
3734
+ }
3735
+ return void 0;
3736
+ }
3737
+ function filenameFromContentDisposition(value) {
3738
+ if (!value) return null;
3739
+ const utf8 = /filename\*=UTF-8''([^;]+)/i.exec(value);
3740
+ if (utf8?.[1]) {
3741
+ try {
3742
+ return decodeURIComponent(utf8[1]);
3743
+ } catch {
3744
+ return utf8[1];
3745
+ }
3746
+ }
3747
+ const plain = /filename="?([^";]+)"?/i.exec(value);
3748
+ return plain?.[1] ?? null;
3749
+ }
3750
+ function errorMessage(e) {
3751
+ return e instanceof Error ? e.message : String(e);
3752
+ }
3753
+
3754
+ // src/index.ts
3755
+ init_betas();
3756
+
3126
3757
  // src/client/entitlements.ts
3127
3758
  Client.prototype.getBalance = async function(signal) {
3128
3759
  const resp = await this.doJSON(
@@ -3947,6 +4578,8 @@ Client.prototype.getBugReport = async function(bugID, signal) {
3947
4578
  return resp.data;
3948
4579
  };
3949
4580
 
4581
+ exports.AgentRunStreamError = AgentRunStreamError;
4582
+ exports.AgentRunsClient = AgentRunsClient;
3950
4583
  exports.Client = Client;
3951
4584
  exports.DefaultRetryPolicy = DefaultRetryPolicy;
3952
4585
  exports.ErrAuthDenied = ErrAuthDenied;
@@ -4002,6 +4635,7 @@ exports.discover = discover;
4002
4635
  exports.effectivePolicy = effectivePolicy;
4003
4636
  exports.exchangeCode = exchangeCode;
4004
4637
  exports.extractAnthropicBlockMeta = extractAnthropicBlockMeta;
4638
+ exports.fileLockDefaults = fileLockDefaults;
4005
4639
  exports.getAdapter = getAdapter;
4006
4640
  exports.getAdapterForModel = getAdapterForModel;
4007
4641
  exports.isSSLError = isSSLError;