@runappsai/sdk 0.0.0-stage → 0.3.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.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +274 -2
  3. package/dist/activity-tracker.d.ts +113 -0
  4. package/dist/activity-tracker.d.ts.map +1 -0
  5. package/dist/activity-tracker.js +176 -0
  6. package/dist/activity-tracker.js.map +1 -0
  7. package/dist/audio.d.ts +129 -0
  8. package/dist/audio.d.ts.map +1 -0
  9. package/dist/audio.js +267 -0
  10. package/dist/audio.js.map +1 -0
  11. package/dist/browser-auth.d.ts +179 -0
  12. package/dist/browser-auth.d.ts.map +1 -0
  13. package/dist/browser-auth.js +1361 -0
  14. package/dist/browser-auth.js.map +1 -0
  15. package/dist/chat.d.ts +221 -0
  16. package/dist/chat.d.ts.map +1 -0
  17. package/dist/chat.js +155 -0
  18. package/dist/chat.js.map +1 -0
  19. package/dist/client.d.ts +155 -0
  20. package/dist/client.d.ts.map +1 -0
  21. package/dist/client.js +157 -0
  22. package/dist/client.js.map +1 -0
  23. package/dist/computer.d.ts +57 -0
  24. package/dist/computer.d.ts.map +1 -0
  25. package/dist/computer.js +21 -0
  26. package/dist/computer.js.map +1 -0
  27. package/dist/embeddings.d.ts +64 -0
  28. package/dist/embeddings.d.ts.map +1 -0
  29. package/dist/embeddings.js +30 -0
  30. package/dist/embeddings.js.map +1 -0
  31. package/dist/errors.d.ts +24 -0
  32. package/dist/errors.d.ts.map +1 -0
  33. package/dist/errors.js +29 -0
  34. package/dist/errors.js.map +1 -0
  35. package/dist/event-wrap.d.ts +59 -0
  36. package/dist/event-wrap.d.ts.map +1 -0
  37. package/dist/event-wrap.js +142 -0
  38. package/dist/event-wrap.js.map +1 -0
  39. package/dist/events.d.ts +119 -0
  40. package/dist/events.d.ts.map +1 -0
  41. package/dist/events.js +87 -0
  42. package/dist/events.js.map +1 -0
  43. package/dist/files.d.ts +218 -0
  44. package/dist/files.d.ts.map +1 -0
  45. package/dist/files.js +212 -0
  46. package/dist/files.js.map +1 -0
  47. package/dist/image.d.ts +185 -0
  48. package/dist/image.d.ts.map +1 -0
  49. package/dist/image.js +148 -0
  50. package/dist/image.js.map +1 -0
  51. package/dist/index.d.ts +30 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +26 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/media.d.ts +56 -0
  56. package/dist/media.d.ts.map +1 -0
  57. package/dist/media.js +133 -0
  58. package/dist/media.js.map +1 -0
  59. package/dist/model_options.d.ts +165 -0
  60. package/dist/model_options.d.ts.map +1 -0
  61. package/dist/model_options.js +59 -0
  62. package/dist/model_options.js.map +1 -0
  63. package/dist/models.d.ts +88 -0
  64. package/dist/models.d.ts.map +1 -0
  65. package/dist/models.js +55 -0
  66. package/dist/models.js.map +1 -0
  67. package/dist/sdk.umd.js +4 -0
  68. package/dist/sdk.umd.js.map +1 -0
  69. package/dist/transport.d.ts +120 -0
  70. package/dist/transport.d.ts.map +1 -0
  71. package/dist/transport.js +214 -0
  72. package/dist/transport.js.map +1 -0
  73. package/dist/types.d.ts +31 -0
  74. package/dist/types.d.ts.map +1 -0
  75. package/dist/types.js +2 -0
  76. package/dist/types.js.map +1 -0
  77. package/dist/validate.d.ts +16 -0
  78. package/dist/validate.d.ts.map +1 -0
  79. package/dist/validate.js +329 -0
  80. package/dist/validate.js.map +1 -0
  81. package/dist/video.d.ts +134 -0
  82. package/dist/video.d.ts.map +1 -0
  83. package/dist/video.js +60 -0
  84. package/dist/video.js.map +1 -0
  85. package/package.json +54 -4
  86. package/src/activity-tracker.ts +251 -0
  87. package/src/audio.ts +440 -0
  88. package/src/browser-auth.ts +1529 -0
  89. package/src/chat.ts +368 -0
  90. package/src/client.ts +250 -0
  91. package/src/computer.ts +80 -0
  92. package/src/embeddings.ts +97 -0
  93. package/src/errors.ts +29 -0
  94. package/src/event-wrap.ts +168 -0
  95. package/src/events.ts +172 -0
  96. package/src/files.ts +347 -0
  97. package/src/image.ts +339 -0
  98. package/src/index.ts +151 -0
  99. package/src/media.ts +147 -0
  100. package/src/model_options.ts +220 -0
  101. package/src/models.ts +121 -0
  102. package/src/transport.ts +292 -0
  103. package/src/types.ts +31 -0
  104. package/src/validate.ts +364 -0
  105. package/src/video.ts +215 -0
@@ -0,0 +1,185 @@
1
+ import type { Transport } from "./transport.js";
2
+ import type { Usage } from "./types.js";
3
+ import type { SDKEvents } from "./events.js";
4
+ /**
5
+ * Image generation request.
6
+ *
7
+ * Sizing: prefer the 2-axis `resolution` + `aspect_ratio` controls —
8
+ * the gateway translates them into a concrete WxH from the target
9
+ * model's declared size enum. `size` is the legacy explicit override;
10
+ * when set, it wins over `(resolution, aspect_ratio)`. When none of
11
+ * the three is set, the gateway / upstream applies its own default.
12
+ */
13
+ export interface ImageGenerateParams {
14
+ prompt: string;
15
+ /** Legacy explicit "WxH" override. Prefer `resolution` +
16
+ * `aspect_ratio` for new code. */
17
+ size?: string;
18
+ /** Short-side pixel tier — "512P" | "1K" | "2K" | "4K".
19
+ * Model-specific subset; `/v1/models` advertises which tiers each
20
+ * image model supports. */
21
+ resolution?: string;
22
+ /** Output shape — "1:1" | "9:16" | "16:9" | "3:4" | "4:3" | "3:2"
23
+ * | "2:3" | "5:4" | "4:5" | "21:9" | "adaptive". Model-specific
24
+ * subset; see `/v1/models`. */
25
+ aspect_ratio?: string;
26
+ n?: number;
27
+ style?: string;
28
+ reference_image_urls?: string[];
29
+ user?: string;
30
+ /**
31
+ * Pass-through for provider-specific knobs.
32
+ *
33
+ * Note: `quality` (OpenAI's render-quality preset
34
+ * — "low"/"medium"/"high"/"auto") was removed from the canonical
35
+ * surface. Only one upstream used it and its own default ("auto") is
36
+ * already optimal; the field caused naming confusion with the
37
+ * "画质" resolution-tier control. The gateway silently drops it
38
+ * from inbound requests, so legacy callers keep working.
39
+ */
40
+ [extra: string]: unknown;
41
+ }
42
+ /**
43
+ * Single generated image. `url` carries the bytes via one of two
44
+ * transport modes — `<img src={url}>` works for both:
45
+ * - "https://api.runapps.ai/v1/blobs/<id>" — async / hosted blob
46
+ * - "data:<mime>;base64,<payload>" — sync / inline
47
+ *
48
+ * `decodeMediaUrl(url)` resolves either shape into `Uint8Array` +
49
+ * mime type when raw bytes are wanted (file save, post-process).
50
+ *
51
+ * `size` is the actual dimensions of this image — Seedream sequential
52
+ * generation may produce results different from the requested size.
53
+ */
54
+ export interface ImageResult {
55
+ url: string;
56
+ revised_prompt?: string;
57
+ size?: string;
58
+ /**
59
+ * Human-readable credit line that the client SHOULD display
60
+ * alongside the image. Populated by stock-library models (Pexels)
61
+ * whose terms of service require crediting the photographer;
62
+ * AI-generation models leave it empty. Render verbatim — don't
63
+ * try to parse the format.
64
+ *
65
+ * Example: "Photo by Jane Doe on Pexels (https://www.pexels.com/photo/12345/)"
66
+ */
67
+ attribution?: string;
68
+ }
69
+ export interface ImageUsage extends Usage {
70
+ generated_images?: number;
71
+ output_tokens?: number;
72
+ total_tokens?: number;
73
+ /** Tool name → invocation count (e.g. Seedream 5.0 lite web_search). */
74
+ tool_usage?: Record<string, number>;
75
+ }
76
+ export interface ImageResponse {
77
+ created: number;
78
+ data: ImageResult[];
79
+ usage: ImageUsage;
80
+ }
81
+ /**
82
+ * Status payload returned by the resumable async-image endpoints
83
+ * (`/v1/async/images/generations` and friends). Returned verbatim by
84
+ * `submitGenerate()` (job is still queued / running), and again by
85
+ * `getAsyncStatus()` (status may now be terminal — `data[]` is
86
+ * populated when `status === 'succeeded'`).
87
+ *
88
+ * The fully-managed `generateAsync()` hides this type behind an
89
+ * `ImageResponse`; `submitGenerate` + `getAsyncStatus` expose it for
90
+ * callers who need to PERSIST the job id (e.g. resume polling across
91
+ * a page refresh, drive their own UI progress, etc.).
92
+ */
93
+ export interface AsyncImageJob {
94
+ id: string;
95
+ status: "queued" | "running" | "succeeded" | "failed" | (string & {});
96
+ data?: ImageResult[];
97
+ usage?: ImageUsage;
98
+ error?: string;
99
+ /** Unix epoch seconds — same semantics as VideoStatus.created_at /
100
+ * current_time. Pair to compute server-truth elapsed. */
101
+ created_at?: number;
102
+ current_time?: number;
103
+ }
104
+ /** Minimal interface for an image / mask file passed to `edit()`. */
105
+ export interface ImageFileInput {
106
+ /** File contents — Blob, ArrayBuffer, Uint8Array, or string. */
107
+ data: Blob | ArrayBuffer | Uint8Array | string;
108
+ /** File name including extension (sent in the multipart field). */
109
+ filename: string;
110
+ /** Optional MIME type — inferred from the extension when omitted. */
111
+ contentType?: string;
112
+ }
113
+ export interface ImageEditParams {
114
+ image: ImageFileInput;
115
+ mask?: ImageFileInput;
116
+ prompt: string;
117
+ size?: string;
118
+ n?: number;
119
+ user?: string;
120
+ }
121
+ export declare class ImageService {
122
+ private readonly transport;
123
+ private readonly events;
124
+ constructor(transport: Transport, events: SDKEvents);
125
+ /**
126
+ * Generate images from a text prompt via the synchronous endpoint.
127
+ * For long-running requests (large Seedream batches, slow upstreams)
128
+ * use `generateAsync()` to avoid 100-second origin timeouts.
129
+ */
130
+ generate(model: string, params: ImageGenerateParams, init?: {
131
+ signal?: AbortSignal;
132
+ }): Promise<ImageResponse>;
133
+ /**
134
+ * Async equivalent of `generate()`. Submits a job to
135
+ * `/v1/async/images/generations`, polls `/v1/async/images/generations/:id`
136
+ * until terminal, then resolves to a sync-shape `ImageResponse`. Use
137
+ * this when a request may exceed the ~100s origin timeout (Cloudflare
138
+ * otherwise replaces the real upstream error with its own 502 page).
139
+ *
140
+ * Implementation is `submitGenerate` + `getAsyncStatus` poll loop, so
141
+ * the path layout matches the rest of the async API (`/v1/async/...`
142
+ * everywhere). The caller's `signal` aborts both the submit and the
143
+ * poll wait; `pollIntervalMs` defaults to 2s.
144
+ */
145
+ generateAsync(model: string, params: ImageGenerateParams, init?: {
146
+ signal?: AbortSignal;
147
+ pollIntervalMs?: number;
148
+ }): Promise<ImageResponse>;
149
+ /**
150
+ * Submit-only variant of `generate()`. Returns the gateway's job
151
+ * descriptor (`id`, `status`, `usage`) without polling. Use this
152
+ * when you want to PERSIST the job id and resume polling later
153
+ * (e.g. across page reloads, in a separate worker process). Pair
154
+ * with `getAsyncStatus(id)` to drive the polling loop yourself.
155
+ *
156
+ * For a one-shot "submit and wait" call site, use `generateAsync()`
157
+ * — that wraps the same underlying endpoint with a built-in poll.
158
+ *
159
+ * Telemetry note: only the SUBMIT step fires start/end on
160
+ * `client.events` — the per-call latency reflects the gateway
161
+ * accepting the job, NOT how long the upstream takes to render.
162
+ * Track render progress via your own poll loop's status responses.
163
+ */
164
+ submitGenerate(model: string, params: ImageGenerateParams, init?: {
165
+ signal?: AbortSignal;
166
+ }): Promise<AsyncImageJob>;
167
+ /**
168
+ * Single poll of an in-flight async image job. Returns the same
169
+ * shape `submitGenerate()` returned, with `data[]` populated once
170
+ * `status` flips to `succeeded`. Caller decides cadence + bail-out;
171
+ * the gateway's per-poll `current_time` / `created_at` together
172
+ * give a server-truth elapsed reading regardless of client clock skew.
173
+ */
174
+ getAsyncStatus(id: string, init?: {
175
+ signal?: AbortSignal;
176
+ }): Promise<AsyncImageJob>;
177
+ /**
178
+ * Edit an image (inpaint / outpaint / variations) via multipart upload.
179
+ * Provider-dependent — only available on `gpt-image-1` and similar.
180
+ */
181
+ edit(model: string, params: ImageEditParams, init?: {
182
+ signal?: AbortSignal;
183
+ }): Promise<ImageResponse>;
184
+ }
185
+ //# sourceMappingURL=image.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../src/image.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAG7C;;;;;;;;GAQG;AACH,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf;uCACmC;IACnC,IAAI,CAAC,EAAE,MAAM,C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AC;IAazB;;;;;;OAMG;IACG,cAAc,CAClB,EAAE,EAAE,MAAM,EACV,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAC9B,OAAO,CAAC,aAAa,CAAC;IAOzB;;;OAGG;IACG,IAAI,CACR,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,eAAe,EACvB,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAC9B,OAAO,CAAC,aAAa,CAAC;CAc1B"}
package/dist/image.js ADDED
@@ -0,0 +1,148 @@
1
+ import { wrapEvents } from "./event-wrap.js";
2
+ /* ------------------------------------------------------------------ */
3
+ export class ImageService {
4
+ transport;
5
+ events;
6
+ constructor(transport, events) {
7
+ this.transport = transport;
8
+ this.events = events;
9
+ }
10
+ /**
11
+ * Generate images from a text prompt via the synchronous endpoint.
12
+ * For long-running requests (large Seedream batches, slow upstreams)
13
+ * use `generateAsync()` to avoid 100-second origin timeouts.
14
+ */
15
+ async generate(model, params, init) {
16
+ return wrapEvents(this.events, { model, capability: "image_generation" }, () => this.transport.postJSON("/v1/images/generations", { model, ...params }, init), (r) => ({ costUSD: r.usage?.total_cost }));
17
+ }
18
+ /**
19
+ * Async equivalent of `generate()`. Submits a job to
20
+ * `/v1/async/images/generations`, polls `/v1/async/images/generations/:id`
21
+ * until terminal, then resolves to a sync-shape `ImageResponse`. Use
22
+ * this when a request may exceed the ~100s origin timeout (Cloudflare
23
+ * otherwise replaces the real upstream error with its own 502 page).
24
+ *
25
+ * Implementation is `submitGenerate` + `getAsyncStatus` poll loop, so
26
+ * the path layout matches the rest of the async API (`/v1/async/...`
27
+ * everywhere). The caller's `signal` aborts both the submit and the
28
+ * poll wait; `pollIntervalMs` defaults to 2s.
29
+ */
30
+ async generateAsync(model, params, init) {
31
+ const interval = init?.pollIntervalMs ?? 2000;
32
+ const signal = init?.signal;
33
+ return wrapEvents(this.events, { model, capability: "image_generation" }, async () => {
34
+ const job = await this.transport.postJSON("/v1/async/images/generations", { model, ...params }, { signal });
35
+ let current = job;
36
+ while (current.status !== "succeeded" && current.status !== "failed") {
37
+ await sleep(interval, signal);
38
+ current = await this.getAsyncStatus(current.id, { signal });
39
+ }
40
+ if (current.status === "failed") {
41
+ throw new Error(current.error ?? "image generation failed");
42
+ }
43
+ return {
44
+ created: current.created_at ?? Math.floor(Date.now() / 1000),
45
+ data: current.data ?? [],
46
+ usage: current.usage ?? { total_cost: 0 },
47
+ };
48
+ }, (r) => ({ costUSD: r.usage?.total_cost }));
49
+ }
50
+ /**
51
+ * Submit-only variant of `generate()`. Returns the gateway's job
52
+ * descriptor (`id`, `status`, `usage`) without polling. Use this
53
+ * when you want to PERSIST the job id and resume polling later
54
+ * (e.g. across page reloads, in a separate worker process). Pair
55
+ * with `getAsyncStatus(id)` to drive the polling loop yourself.
56
+ *
57
+ * For a one-shot "submit and wait" call site, use `generateAsync()`
58
+ * — that wraps the same underlying endpoint with a built-in poll.
59
+ *
60
+ * Telemetry note: only the SUBMIT step fires start/end on
61
+ * `client.events` — the per-call latency reflects the gateway
62
+ * accepting the job, NOT how long the upstream takes to render.
63
+ * Track render progress via your own poll loop's status responses.
64
+ */
65
+ async submitGenerate(model, params, init) {
66
+ return wrapEvents(this.events, { model, capability: "image_generation" }, () => this.transport.postJSON("/v1/async/images/generations", { model, ...params }, init));
67
+ }
68
+ /**
69
+ * Single poll of an in-flight async image job. Returns the same
70
+ * shape `submitGenerate()` returned, with `data[]` populated once
71
+ * `status` flips to `succeeded`. Caller decides cadence + bail-out;
72
+ * the gateway's per-poll `current_time` / `created_at` together
73
+ * give a server-truth elapsed reading regardless of client clock skew.
74
+ */
75
+ async getAsyncStatus(id, init) {
76
+ return this.transport.getJSON(`/v1/async/images/generations/${encodeURIComponent(id)}`, init);
77
+ }
78
+ /**
79
+ * Edit an image (inpaint / outpaint / variations) via multipart upload.
80
+ * Provider-dependent — only available on `gpt-image-1` and similar.
81
+ */
82
+ async edit(model, params, init) {
83
+ const form = buildEditForm(model, params);
84
+ return wrapEvents(this.events, { model, capability: "image_edit" }, () => this.transport.postMultipart("/v1/images/edits", form, init), (r) => ({ costUSD: r.usage?.total_cost }));
85
+ }
86
+ }
87
+ function sleep(ms, signal) {
88
+ return new Promise((resolve, reject) => {
89
+ if (signal?.aborted) {
90
+ reject(signal.reason ?? new Error("aborted"));
91
+ return;
92
+ }
93
+ const timer = setTimeout(() => {
94
+ signal?.removeEventListener("abort", onAbort);
95
+ resolve();
96
+ }, ms);
97
+ const onAbort = () => {
98
+ clearTimeout(timer);
99
+ reject(signal.reason ?? new Error("aborted"));
100
+ };
101
+ signal?.addEventListener("abort", onAbort, { once: true });
102
+ });
103
+ }
104
+ function buildEditForm(model, params) {
105
+ const form = new FormData();
106
+ form.set("model", model);
107
+ form.set("prompt", params.prompt);
108
+ if (params.size)
109
+ form.set("size", params.size);
110
+ if (params.n !== undefined)
111
+ form.set("n", String(params.n));
112
+ if (params.user)
113
+ form.set("user", params.user);
114
+ form.set("image", toBlob(params.image), params.image.filename);
115
+ if (params.mask)
116
+ form.set("mask", toBlob(params.mask), params.mask.filename);
117
+ return form;
118
+ }
119
+ /** Internal: coerce ImageFileInput to a Blob the multipart layer accepts. */
120
+ function toBlob(input) {
121
+ const ct = input.contentType ?? guessMime(input.filename);
122
+ if (input.data instanceof Blob) {
123
+ return input.data.type === ct ? input.data : new Blob([input.data], { type: ct });
124
+ }
125
+ if (typeof input.data === "string") {
126
+ return new Blob([input.data], { type: ct });
127
+ }
128
+ // ArrayBuffer | Uint8Array — wrap in Blob. Cast widens TS's strict
129
+ // Uint8Array<ArrayBuffer> back to BlobPart (it's accepted at runtime).
130
+ return new Blob([input.data], { type: ct });
131
+ }
132
+ function guessMime(filename) {
133
+ const ext = filename.toLowerCase().split(".").pop() ?? "";
134
+ switch (ext) {
135
+ case "png":
136
+ return "image/png";
137
+ case "jpg":
138
+ case "jpeg":
139
+ return "image/jpeg";
140
+ case "webp":
141
+ return "image/webp";
142
+ case "gif":
143
+ return "image/gif";
144
+ default:
145
+ return "application/octet-stream";
146
+ }
147
+ }
148
+ //# sourceMappingURL=image.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image.js","sourceRoot":"","sources":["../src/image.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AA8H7C,wEAAwE;AAExE,MAAM,OAAO,YAAY;IAEJ;IACA;IAFnB,YACmB,SAAoB,EACpB,MAAiB;QADjB,cAAS,GAAT,SAAS,CAAW;QACpB,WAAM,GAAN,MAAM,CAAW;IACjC,CAAC;IAEJ;;;;OAIG;IACH,KAAK,CAAC,QAAQ,CACZ,KAAa,EACb,MAA2B,EAC3B,IAA+B;QAE/B,OAAO,UAAU,CACf,IAAI,CAAC,MAAM,EACX,EAAE,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,EACzC,GAAG,EAAE,CACH,IAAI,CAAC,SAAS,CAAC,QAAQ,CACrB,wBAAwB,EACxB,EAAE,KAAK,EAAE,GAAG,MAAM,EAAE,EACpB,IAAI,CACL,EACH,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC,CAC1C,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;OAWG;IACH,KAAK,CAAC,aAAa,CACjB,KAAa,EACb,MAA2B,EAC3B,IAAwD;QAExD,MAAM,QAAQ,GAAG,IAAI,EAAE,cAAc,IAAI,IAAI,CAAC;QAC9C,MAAM,MAAM,GAAG,IAAI,EAAE,MAAM,CAAC;QAC5B,OAAO,UAAU,CACf,IAAI,CAAC,MAAM,EACX,EAAE,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,EACzC,KAAK,IAAI,EAAE;YACT,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,QAAQ,CACvC,8BAA8B,EAC9B,EAAE,KAAK,EAAE,GAAG,MAAM,EA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,CAAC,IAAI,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;IACpF,CAAC;IACD,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QACnC,OAAO,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;IAC9C,CAAC;IACD,mEAAmE;IACnE,uEAAuE;IACvE,OAAO,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,IAAgB,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,SAAS,CAAC,QAAgB;IACjC,MAAM,GAAG,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;IAC1D,QAAQ,GAAG,EAAE,CAAC;QACZ,KAAK,KAAK;YACR,OAAO,WAAW,CAAC;QACrB,KAAK,KAAK,CAAC;QACX,KAAK,MAAM;YACT,OAAO,YAAY,CAAC;QACtB,KAAK,MAAM;YACT,OAAO,YAAY,CAAC;QACtB,KAAK,KAAK;YACR,OAAO,WAAW,CAAC;QACrB;YACE,OAAO,0BAA0B,CAAC;IACtC,CAAC;AACH,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * RunApps SDK for JavaScript / TypeScript.
3
+ *
4
+ * Top-level entry point — exports the `RunApps` client class plus all
5
+ * public types so callers can write strongly-typed wrappers without
6
+ * reaching into per-service modules.
7
+ */
8
+ export { RunApps, RunApps as Client, RunApps as RunJobs, type ClientOptions, type AuthProvider } from "./client.js";
9
+ export { SDKEvents, newRequestId, type RequestStartEvent, type RequestStreamDeltaEvent, type RequestEndEvent, type RequestErrorEvent, type SDKEventMap, type SDKCapability, type Unsubscribe, } from "./events.js";
10
+ export { ActivityTracker, type ActiveCall, type CompletedCall, type SessionStats, type ActivitySnapshot, } from "./activity-tracker.js";
11
+ export { BrowserAuth, type BrowserAuthOptions, type BrowserUser } from "./browser-auth.js";
12
+ export { APIError } from "./errors.js";
13
+ export type { Usage } from "./types.js";
14
+ export type { ChatMessage, ContentPart, ChatTool, StreamOptions, ChatCompletionParams, ChatToolCall, ChatChoiceMessage, ChatChoice, ChatCompletion, ChatChunkDelta, ChatChunkChoice, ChatCompletionChunk, } from "./chat.js";
15
+ export { userMessage, systemMessage, assistantMessage, toolResultMessage, userMessageParts, textPart, imagePart, videoPart, audioPart, } from "./chat.js";
16
+ export type { Model, ModelListOptions, Tag } from "./models.js";
17
+ export { hasCapabilityTag, acceptsModality, supportsVoiceClone, supportsInstructText, defaultVoice, } from "./models.js";
18
+ export type { Schema, FieldSchema, Constraint, ConstraintKind, Catalog, } from "./model_options.js";
19
+ export { getOptionsSchema, acceptsField, requiresField, allowedValuesFor, } from "./model_options.js";
20
+ export type { ValidationError } from "./validate.js";
21
+ export { validateRequest } from "./validate.js";
22
+ export type { ImageGenerateParams, ImageResult, ImageUsage, ImageResponse, ImageEditParams, ImageFileInput, AsyncImageJob, } from "./image.js";
23
+ export type { SpeechParams, SpeechResponse, TranscribeParams, TranscribeResponse, AudioFileInput, } from "./audio.js";
24
+ export type { VideoGenerateParams, VideoTask, VideoStatus, VideoUsageTokens, WaitOptions, } from "./video.js";
25
+ export { encodeImageUrl, decodeMediaUrl } from "./media.js";
26
+ export type { ComputerStepParams, ComputerContentBlock, ComputerResponse, } from "./computer.js";
27
+ export type { FileObject, FileListResult, PutOptions as FilePutOptions, ListOptions as FileListOptions, PutFromURLOptions as FilePutFromURLOptions, BatchOp as FileBatchOp, BatchResult as FileBatchResult, } from "./files.js";
28
+ export type { EmbeddingsParams, Embedding, EmbeddingsUsage, EmbeddingsResponse, } from "./embeddings.js";
29
+ export { ServerTools, type ServerToolName } from "./chat.js";
30
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,OAAO,IAAI,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAOpH,OAAO,EACL,SAAS,EACT,YAAY,EACZ,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,WAAW,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,eAAe,EACf,KAAK,UAAU,EACf,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,gBAAgB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC3F,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,YAAY,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAGxC,YAAY,EACV,WAAW,EACX,WAAW,EACX,QAAQ,EACR,aAAa,EACb,oBAAoB,EACpB,YAAY,EACZ,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,cAAc,EACd,eAAe,EACf,mBAAmB,GACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,QAAQ,EACR,SAAS,EACT,SAAS,EACT,SAAS,GACV,MAAM,WAAW,CAAC;AAGnB,YAAY,EAAE,KAAK,EAAE,gBAAgB,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EACL,gBAAgB,EACh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
4
+ * Top-level entry point — exports the `RunApps` client class plus all
5
+ * public types so callers can write strongly-typed wrappers without
6
+ * reaching into per-service modules.
7
+ */
8
+ export { RunApps, RunApps as Client, RunApps as RunJobs } from "./client.js";
9
+ // SDK telemetry — `client.events` fires these around every LLM-ish
10
+ // service call so UI overlays (the badge being the canonical example)
11
+ // can render real-time state. The ActivityTracker turns the raw
12
+ // stream into the snapshot the badge reads each frame; exported
13
+ // alongside the bus so power users can build their own status UI.
14
+ export { SDKEvents, newRequestId, } from "./events.js";
15
+ export { ActivityTracker, } from "./activity-tracker.js";
16
+ export { BrowserAuth } from "./browser-auth.js";
17
+ export { APIError } from "./errors.js";
18
+ export { userMessage, systemMessage, assistantMessage, toolResultMessage, userMessageParts, textPart, imagePart, videoPart, audioPart, } from "./chat.js";
19
+ export { hasCapabilityTag, acceptsModality, supportsVoiceClone, supportsInstructText, defaultVoice, } from "./models.js";
20
+ export { getOptionsSchema, acceptsField, requiresField, allowedValuesFor, } from "./model_options.js";
21
+ export { validateRequest } from "./validate.js";
22
+ // Media helpers (shared by image + video + chat-multimodal)
23
+ export { encodeImageUrl, decodeMediaUrl } from "./media.js";
24
+ // Server-tool names for chat.create({ server_tools }), with autocomplete.
25
+ export { ServerTools } from "./chat.js";
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,OAAO,IAAI,OAAO,EAAyC,MAAM,aAAa,CAAC;AAEpH,mEAAmE;AACnE,sEAAsE;AACtE,gEAAgE;AAChE,gEAAgE;AAChE,kEAAkE;AAClE,OAAO,EACL,SAAS,EACT,YAAY,GAQb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,eAAe,GAKhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAA6C,MAAM,mBAAmB,CAAC;AAC3F,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAkBvC,OAAO,EACL,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,QAAQ,EACR,SAAS,EACT,SAAS,EACT,SAAS,GACV,MAAM,WAAW,CAAC;AAInB,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,aAAa,CAAC;AAUrB,OAAO,EACL,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AA+BhD,4DAA4D;AAC5D,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AA4B5D,0EAA0E;AAC1E,OAAO,EAAE,WAAW,EAAuB,MAAM,WAAW,CAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Media helpers shared by image / video / chat-multimodal endpoints.
3
+ *
4
+ * The gateway accepts media payloads as `data:<mime>;base64,<payload>`
5
+ * URIs on every `*_url` field — `encodeImageUrl` is the bridge from
6
+ * raw bytes to that wire format. Replaces the deprecated `*_b64` SDK
7
+ * fields, which were removed in favour of routing every payload
8
+ * through `*_url`.
9
+ */
10
+ /**
11
+ * Wrap raw image bytes as a `data:<mime>;base64,<payload>` URI.
12
+ *
13
+ * MIME is sniffed from the magic bytes (PNG / JPEG / GIF / WebP). On
14
+ * unrecognised input we default to `application/octet-stream` — most
15
+ * upstreams accept and re-sniff server-side.
16
+ *
17
+ * @param bytes Image bytes — `Uint8Array`, `ArrayBuffer`, or `Blob`.
18
+ * @returns A data: URI suitable for any `*_url` field on the gateway.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { encodeImageUrl } from "@runjobs/sdk";
23
+ * const png = await fs.readFile("frame.png");
24
+ * await client.video.generate("Veo 3.1", {
25
+ * prompt: "...",
26
+ * first_frame_url: encodeImageUrl(png),
27
+ * });
28
+ * ```
29
+ */
30
+ export declare function encodeImageUrl(bytes: Uint8Array | ArrayBuffer | Blob): string;
31
+ /**
32
+ * Resolve a media URL to raw bytes plus the declared mime label.
33
+ *
34
+ * Inverse of `encodeImageUrl`. Two transport modes handled:
35
+ * - "data:<mime>;base64,<payload>" — decode the inline payload
36
+ * - "https://...", "http://..." — `fetch()` + `.arrayBuffer()`,
37
+ * mime from the response's
38
+ * `Content-Type` header
39
+ *
40
+ * Returns `{bytes: Uint8Array, contentType: string}`. Pairs with
41
+ * `encodeImageUrl` so callers can round-trip bytes through the gateway
42
+ * without thinking about which transport mode the response chose.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * import { decodeMediaUrl } from "@runjobs/sdk";
47
+ * const job = await client.image.generateAsync("Seedream 5.0", {...});
48
+ * const { bytes, contentType } = await decodeMediaUrl(job.data[0].url);
49
+ * await fs.writeFile("out.png", bytes);
50
+ * ```
51
+ */
52
+ export declare function decodeMediaUrl(url: string): Promise<{
53
+ bytes: Uint8Array;
54
+ contentType: string;
55
+ }>;
56
+ //# sourceMappingURL=media.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.d.ts","sourceRoot":"","sources":["../src/media.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,UAAU,GAAG,WAAW,GAAG,IAAI,GACrC,MAAM,CA4BR;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,MAAM,GACV,OAAO,CAAC;IAAE,KAAK,EAAE,UAAU,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC,CAwBrD"}
package/dist/media.js ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Media helpers shared by image / video / chat-multimodal endpoints.
3
+ *
4
+ * The gateway accepts media payloads as `data:<mime>;base64,<payload>`
5
+ * URIs on every `*_url` field — `encodeImageUrl` is the bridge from
6
+ * raw bytes to that wire format. Replaces the deprecated `*_b64` SDK
7
+ * fields, which were removed in favour of routing every payload
8
+ * through `*_url`.
9
+ */
10
+ /**
11
+ * Wrap raw image bytes as a `data:<mime>;base64,<payload>` URI.
12
+ *
13
+ * MIME is sniffed from the magic bytes (PNG / JPEG / GIF / WebP). On
14
+ * unrecognised input we default to `application/octet-stream` — most
15
+ * upstreams accept and re-sniff server-side.
16
+ *
17
+ * @param bytes Image bytes — `Uint8Array`, `ArrayBuffer`, or `Blob`.
18
+ * @returns A data: URI suitable for any `*_url` field on the gateway.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { encodeImageUrl } from "@runjobs/sdk";
23
+ * const png = await fs.readFile("frame.png");
24
+ * await client.video.generate("Veo 3.1", {
25
+ * prompt: "...",
26
+ * first_frame_url: encodeImageUrl(png),
27
+ * });
28
+ * ```
29
+ */
30
+ export function encodeImageUrl(bytes) {
31
+ // Normalize to Uint8Array so the rest of the function is uniform.
32
+ if (bytes instanceof Blob) {
33
+ throw new Error("encodeImageUrl: Blob input requires async; await blob.arrayBuffer() and pass the result instead");
34
+ }
35
+ const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
36
+ const mime = sniffImageMime(u8);
37
+ // btoa(String.fromCharCode(...u8)) blows the stack on large arrays;
38
+ // chunk to keep arg count bounded. 0x8000 is the conventional safe
39
+ // limit on JS engines.
40
+ const CHUNK = 0x8000;
41
+ let binary = "";
42
+ for (let i = 0; i < u8.length; i += CHUNK) {
43
+ binary += String.fromCharCode.apply(null, Array.from(u8.subarray(i, i + CHUNK)));
44
+ }
45
+ // btoa is browser-native and shimmed in Node ≥ 16 globalThis.
46
+ const b64 = globalThis.btoa
47
+ ? globalThis.btoa(binary)
48
+ : Buffer.from(binary, "binary").toString("base64");
49
+ return `data:${mime};base64,${b64}`;
50
+ }
51
+ /**
52
+ * Resolve a media URL to raw bytes plus the declared mime label.
53
+ *
54
+ * Inverse of `encodeImageUrl`. Two transport modes handled:
55
+ * - "data:<mime>;base64,<payload>" — decode the inline payload
56
+ * - "https://...", "http://..." — `fetch()` + `.arrayBuffer()`,
57
+ * mime from the response's
58
+ * `Content-Type` header
59
+ *
60
+ * Returns `{bytes: Uint8Array, contentType: string}`. Pairs with
61
+ * `encodeImageUrl` so callers can round-trip bytes through the gateway
62
+ * without thinking about which transport mode the response chose.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { decodeMediaUrl } from "@runjobs/sdk";
67
+ * const job = await client.image.generateAsync("Seedream 5.0", {...});
68
+ * const { bytes, contentType } = await decodeMediaUrl(job.data[0].url);
69
+ * await fs.writeFile("out.png", bytes);
70
+ * ```
71
+ */
72
+ export async function decodeMediaUrl(url) {
73
+ if (url.startsWith("data:")) {
74
+ const rest = url.slice(5);
75
+ const semi = rest.indexOf(";");
76
+ const comma = rest.indexOf(",");
77
+ if (semi === -1 || comma === -1 || comma < semi) {
78
+ throw new Error("decodeMediaUrl: malformed data URI");
79
+ }
80
+ const mime = rest.slice(0, semi);
81
+ const b64 = rest.slice(comma + 1);
82
+ return { bytes: base64ToBytes(b64), contentType: mime };
83
+ }
84
+ if (url.startsWith("http://") || url.startsWith("https://")) {
85
+ const resp = await fetch(url);
86
+ if (!resp.ok) {
87
+ throw new Error(`decodeMediaUrl: upstream ${resp.status}`);
88
+ }
89
+ const buf = await resp.arrayBuffer();
90
+ return {
91
+ bytes: new Uint8Array(buf),
92
+ contentType: resp.headers.get("Content-Type") ?? "",
93
+ };
94
+ }
95
+ throw new Error(`decodeMediaUrl: unsupported url scheme: ${url.slice(0, 32)}`);
96
+ }
97
+ /** Decode standard base64 to Uint8Array. Browser `atob` + Node `Buffer`
98
+ * fallback — same impl as the audio service uses internally. */
99
+ function base64ToBytes(b64) {
100
+ if (typeof Buffer !== "undefined") {
101
+ return new Uint8Array(Buffer.from(b64, "base64"));
102
+ }
103
+ const bin = atob(b64);
104
+ const out = new Uint8Array(bin.length);
105
+ for (let i = 0; i < bin.length; i++)
106
+ out[i] = bin.charCodeAt(i);
107
+ return out;
108
+ }
109
+ /**
110
+ * Sniff a small set of image mimes from magic bytes. Mirrors the
111
+ * gateway's own sniff so encode / decode round-trip lands on the same
112
+ * label.
113
+ */
114
+ function sniffImageMime(b) {
115
+ if (b.length >= 8 &&
116
+ b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) {
117
+ return "image/png";
118
+ }
119
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) {
120
+ return "image/jpeg";
121
+ }
122
+ if (b.length >= 6 &&
123
+ b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38) {
124
+ return "image/gif";
125
+ }
126
+ if (b.length >= 12 &&
127
+ b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 &&
128
+ b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) {
129
+ return "image/webp";
130
+ }
131
+ return "application/octet-stream";
132
+ }
133
+ //# sourceMappingURL=media.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.js","sourceRoot":"","sources":["../src/media.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,cAAc,CAC5B,KAAsC;IAEtC,kEAAkE;IAClE,IAAI,KAAK,YAAY,IAAI,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CACb,iGAAiG,CAClG,CAAC;IACJ,CAAC;IACD,MAAM,EAAE,GAAG,KAAK,YAAY,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IAEvE,MAAM,IAAI,GAAG,cAAc,CAAC,EAAE,CAAC,CAAC;IAEhC,oEAAoE;IACpE,mEAAmE;IACnE,uBAAuB;IACvB,MAAM,KAAK,GAA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