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