@acosmi/sdk-ts 1.0.2 → 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.
- package/CHANGELOG.md +34 -0
- package/README.md +72 -5
- package/dist/browser/index.mjs +501 -3
- package/dist/browser/index.mjs.map +1 -1
- package/dist/index.mjs +501 -3
- package/dist/index.mjs.map +1 -1
- package/dist/node/adapters/anthropic.d.cts +1 -1
- package/dist/node/adapters/anthropic.d.ts +1 -1
- package/dist/node/adapters/openai.d.cts +1 -1
- package/dist/node/adapters/openai.d.ts +1 -1
- package/dist/node/{index-C3Z_84Bv.d.cts → index-BI8EgBXu.d.cts} +1 -1
- package/dist/node/{index-C3Z_84Bv.d.ts → index-BI8EgBXu.d.ts} +1 -1
- package/dist/node/index.cjs +502 -2
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.d.cts +210 -7
- package/dist/node/index.d.ts +210 -7
- package/dist/node/index.mjs +501 -3
- package/dist/node/index.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as ProviderAdapter, aj as ProviderFormat,
|
|
1
|
+
import { P as ProviderAdapter, aj as ProviderFormat, c as ModelCapabilities, d as ChatRequest, e as ChatResponse, f as StreamEvent } from '../index-BI8EgBXu.cjs';
|
|
2
2
|
|
|
3
3
|
/** 实现 ProviderAdapter, 用于 Anthropic 原生模型 */
|
|
4
4
|
declare class AnthropicAdapter implements ProviderAdapter {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as ProviderAdapter, aj as ProviderFormat,
|
|
1
|
+
import { P as ProviderAdapter, aj as ProviderFormat, c as ModelCapabilities, d as ChatRequest, e as ChatResponse, f as StreamEvent } from '../index-BI8EgBXu.js';
|
|
2
2
|
|
|
3
3
|
/** 实现 ProviderAdapter, 用于 Anthropic 原生模型 */
|
|
4
4
|
declare class AnthropicAdapter implements ProviderAdapter {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as ProviderAdapter, aj as ProviderFormat,
|
|
1
|
+
import { P as ProviderAdapter, aj as ProviderFormat, c as ModelCapabilities, d as ChatRequest, e as ChatResponse, f as StreamEvent, A as AnthropicResponse } from '../index-BI8EgBXu.cjs';
|
|
2
2
|
|
|
3
3
|
/** 实现 ProviderAdapter, 用于所有非 Anthropic 厂商 */
|
|
4
4
|
declare class OpenAIAdapter implements ProviderAdapter {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as ProviderAdapter, aj as ProviderFormat,
|
|
1
|
+
import { P as ProviderAdapter, aj as ProviderFormat, c as ModelCapabilities, d as ChatRequest, e as ChatResponse, f as StreamEvent, A as AnthropicResponse } from '../index-BI8EgBXu.js';
|
|
2
2
|
|
|
3
3
|
/** 实现 ProviderAdapter, 用于所有非 Anthropic 厂商 */
|
|
4
4
|
declare class OpenAIAdapter implements ProviderAdapter {
|
|
@@ -989,4 +989,4 @@ declare function getAdapter(provider: string): ProviderAdapter;
|
|
|
989
989
|
*/
|
|
990
990
|
declare function getAdapterForModel(m: ManagedModel): ProviderAdapter;
|
|
991
991
|
|
|
992
|
-
export { type ConsumeRecord as $, type AnthropicResponse as A, type BalanceDetail as B, type ClientRegistration as C, type DeviceRegistration as D, type EntitlementBalance as E, type NotificationPreference as F, type GenerateSkillRequest as G, type WSEvent as H, type APIResponse as I, type AnthropicContentBlock as J, type AnthropicUsage as K, BucketClassCommercial as L, type
|
|
992
|
+
export { type ConsumeRecord as $, type AnthropicResponse as A, type BalanceDetail as B, type ClientRegistration as C, type DeviceRegistration as D, type EntitlementBalance as E, type NotificationPreference as F, type GenerateSkillRequest as G, type WSEvent as H, type APIResponse as I, type AnthropicContentBlock as J, type AnthropicUsage as K, BucketClassCommercial as L, type ManagedModel as M, type NotificationList as N, type Order as O, type ProviderAdapter as P, type QuotaSummary as Q, BucketClassGeneric as R, type ServerMetadata as S, type TokenResponse as T, type BucketInfo as U, type BucketRow as V, type WalletStats as W, BusinessError as X, type ChatContentBlock as Y, type ChatMessage as Z, type ChatUsage as _, type TokenSet as a, type EffortConfig as a0, type GeoLoc as a1, HTTPError as a2, ModelNotFoundError as a3, NetworkError as a4, type Notification as a5, type NotificationUnreadCount as a6, type OpenAIChatChoice as a7, type OpenAIChatMessage as a8, type OpenAIChatResponse as a9, anthropicResponseTextContent as aA, anthropicResponseThinkingContent as aB, anthropicResponseToolUseBlocks as aC, apiResponseBusinessError as aD, apiResponseGetMessage as aE, bucketInfoIsCommercial as aF, bucketRowIsCommercial as aG, getAdapter as aH, getAdapterForModel as aI, newThinkingConfig as aJ, newWebSearchTool as aK, parseNotificationEvent as aL, parseSettlement as aM, parseSourcesEvent as aN, tokenSetIsExpired as aO, type OpenAIFunctionCall as aa, type OpenAIStreamChoice as ab, type OpenAIStreamChunk as ac, type OpenAIStreamDelta as ad, type OpenAIStreamToolCall as ae, type OpenAIToolCall as af, type OpenAIUsage as ag, OrderTerminalError as ah, type OutputConfig as ai, ProviderFormat as aj, RateLimitError as ak, type ServerTool as al, ServerToolTypeWebSearch as am, type SkillStoreListItem as an, StreamError as ao, type ThinkingConfig as ap, ThinkingHigh as aq, ThinkingHighMinMaxTokens as ar, ThinkingMax as as, ThinkingMaxFallbackMaxTokens as at, ThinkingOff as au, type ToolListResponse as av, type ToolProvider as aw, type WebSearchConfig as ax, type WebSearchSource as ay, type YudaoPageResult as az, type ModelCoefficient as b, type ModelCapabilities as c, type ChatRequest as d, type ChatResponse as e, type StreamEvent as f, type SourcesEvent as g, type StreamSettlement as h, type EntitlementItem as i, type ConsumeRecordPage as j, type ModelByQuotaResponse as k, type ModelBucket as l, type TokenPackage as m, type PayPayload as n, type OrderStatus as o, type Transaction as p, type SkillStoreQuery as q, type SkillStoreItem as r, type SkillBrowseResponse as s, type SkillBrowseListResponse as t, type SkillSummary as u, type CertificationStatus as v, type GenerateSkillResult as w, type OptimizeSkillRequest as x, type OptimizeSkillResult as y, type ToolView as z };
|
|
@@ -989,4 +989,4 @@ declare function getAdapter(provider: string): ProviderAdapter;
|
|
|
989
989
|
*/
|
|
990
990
|
declare function getAdapterForModel(m: ManagedModel): ProviderAdapter;
|
|
991
991
|
|
|
992
|
-
export { type ConsumeRecord as $, type AnthropicResponse as A, type BalanceDetail as B, type ClientRegistration as C, type DeviceRegistration as D, type EntitlementBalance as E, type NotificationPreference as F, type GenerateSkillRequest as G, type WSEvent as H, type APIResponse as I, type AnthropicContentBlock as J, type AnthropicUsage as K, BucketClassCommercial as L, type
|
|
992
|
+
export { type ConsumeRecord as $, type AnthropicResponse as A, type BalanceDetail as B, type ClientRegistration as C, type DeviceRegistration as D, type EntitlementBalance as E, type NotificationPreference as F, type GenerateSkillRequest as G, type WSEvent as H, type APIResponse as I, type AnthropicContentBlock as J, type AnthropicUsage as K, BucketClassCommercial as L, type ManagedModel as M, type NotificationList as N, type Order as O, type ProviderAdapter as P, type QuotaSummary as Q, BucketClassGeneric as R, type ServerMetadata as S, type TokenResponse as T, type BucketInfo as U, type BucketRow as V, type WalletStats as W, BusinessError as X, type ChatContentBlock as Y, type ChatMessage as Z, type ChatUsage as _, type TokenSet as a, type EffortConfig as a0, type GeoLoc as a1, HTTPError as a2, ModelNotFoundError as a3, NetworkError as a4, type Notification as a5, type NotificationUnreadCount as a6, type OpenAIChatChoice as a7, type OpenAIChatMessage as a8, type OpenAIChatResponse as a9, anthropicResponseTextContent as aA, anthropicResponseThinkingContent as aB, anthropicResponseToolUseBlocks as aC, apiResponseBusinessError as aD, apiResponseGetMessage as aE, bucketInfoIsCommercial as aF, bucketRowIsCommercial as aG, getAdapter as aH, getAdapterForModel as aI, newThinkingConfig as aJ, newWebSearchTool as aK, parseNotificationEvent as aL, parseSettlement as aM, parseSourcesEvent as aN, tokenSetIsExpired as aO, type OpenAIFunctionCall as aa, type OpenAIStreamChoice as ab, type OpenAIStreamChunk as ac, type OpenAIStreamDelta as ad, type OpenAIStreamToolCall as ae, type OpenAIToolCall as af, type OpenAIUsage as ag, OrderTerminalError as ah, type OutputConfig as ai, ProviderFormat as aj, RateLimitError as ak, type ServerTool as al, ServerToolTypeWebSearch as am, type SkillStoreListItem as an, StreamError as ao, type ThinkingConfig as ap, ThinkingHigh as aq, ThinkingHighMinMaxTokens as ar, ThinkingMax as as, ThinkingMaxFallbackMaxTokens as at, ThinkingOff as au, type ToolListResponse as av, type ToolProvider as aw, type WebSearchConfig as ax, type WebSearchSource as ay, type YudaoPageResult as az, type ModelCoefficient as b, type ModelCapabilities as c, type ChatRequest as d, type ChatResponse as e, type StreamEvent as f, type SourcesEvent as g, type StreamSettlement as h, type EntitlementItem as i, type ConsumeRecordPage as j, type ModelByQuotaResponse as k, type ModelBucket as l, type TokenPackage as m, type PayPayload as n, type OrderStatus as o, type Transaction as p, type SkillStoreQuery as q, type SkillStoreItem as r, type SkillBrowseResponse as s, type SkillBrowseListResponse as t, type SkillSummary as u, type CertificationStatus as v, type GenerateSkillResult as w, type OptimizeSkillRequest as x, type OptimizeSkillResult as y, type ToolView as z };
|
package/dist/node/index.cjs
CHANGED
|
@@ -1974,8 +1974,25 @@ function extractAnthropicBlockMeta(eventType, data, blockTypeMap) {
|
|
|
1974
1974
|
}
|
|
1975
1975
|
}
|
|
1976
1976
|
|
|
1977
|
-
// src/
|
|
1978
|
-
|
|
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();
|
|
1979
1996
|
|
|
1980
1997
|
// src/client.ts
|
|
1981
1998
|
init_types();
|
|
@@ -3256,6 +3273,487 @@ async function sleep(ms, signal) {
|
|
|
3256
3273
|
});
|
|
3257
3274
|
}
|
|
3258
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
|
+
|
|
3259
3757
|
// src/client/entitlements.ts
|
|
3260
3758
|
Client.prototype.getBalance = async function(signal) {
|
|
3261
3759
|
const resp = await this.doJSON(
|
|
@@ -4080,6 +4578,8 @@ Client.prototype.getBugReport = async function(bugID, signal) {
|
|
|
4080
4578
|
return resp.data;
|
|
4081
4579
|
};
|
|
4082
4580
|
|
|
4581
|
+
exports.AgentRunStreamError = AgentRunStreamError;
|
|
4582
|
+
exports.AgentRunsClient = AgentRunsClient;
|
|
4083
4583
|
exports.Client = Client;
|
|
4084
4584
|
exports.DefaultRetryPolicy = DefaultRetryPolicy;
|
|
4085
4585
|
exports.ErrAuthDenied = ErrAuthDenied;
|