@cmdop/sdk 2.0.0 → 3.0.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/dist/index.js CHANGED
@@ -1,626 +1,8 @@
1
- import { existsSync, chmodSync } from 'fs';
2
- import { join, dirname, resolve } from 'path';
3
- import { fileURLToPath } from 'url';
4
- import { toBinary, create } from '@bufbuild/protobuf';
5
- import { messageDesc, fileDesc } from '@bufbuild/protobuf/codegenv2';
6
- import { spawn } from 'child_process';
7
- import { sizeDelimitedDecodeStream, sizeDelimitedEncode } from '@bufbuild/protobuf/wire';
8
-
9
- // src/config.ts
10
- var DEFAULT_TIMEOUT_MS = 3e4;
11
- function resolveConfig(opts = {}) {
12
- const env = typeof process !== "undefined" && process.env ? process.env : {};
13
- const timeoutMs = opts.timeoutMs ?? (env.CMDOP_TIMEOUT_MS ? Number(env.CMDOP_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS);
14
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
15
- throw new Error("timeoutMs must be greater than zero");
16
- }
17
- const rawBase = opts.baseUrl ?? env.CMDOP_BASE_URL;
18
- return {
19
- token: opts.token ?? env.CMDOP_TOKEN ?? void 0,
20
- baseUrl: rawBase ? rawBase.replace(/\/+$/, "") : void 0,
21
- timeoutMs
22
- };
23
- }
24
- var SUPPORTED_PLATFORMS = /* @__PURE__ */ new Set([
25
- "darwin-arm64",
26
- "darwin-x64",
27
- "linux-x64",
28
- "linux-arm64",
29
- "win32-x64"
30
- ]);
31
- function binaryName() {
32
- const key = `${process.platform}-${process.arch}`;
33
- const exe = process.platform === "win32" ? ".exe" : "";
34
- return `cmdop-core-${key}${exe}`;
35
- }
36
- function moduleDir() {
37
- try {
38
- const metaUrl = import.meta?.url;
39
- if (metaUrl) return dirname(fileURLToPath(metaUrl));
40
- } catch {
41
- }
42
- if (typeof __dirname !== "undefined") return __dirname;
43
- return resolve(".");
44
- }
45
- function packageBinDir() {
46
- const here = moduleDir();
47
- const candidates = [
48
- join(here, "bin"),
49
- // module sits at package root (unbundled / tests)
50
- join(here, "..", "bin"),
51
- // module sits in dist/ (the published bundle)
52
- join(here, "..", "..", "bin")
53
- ];
54
- for (const c of candidates) {
55
- if (existsSync(c)) return c;
56
- }
57
- return join(here, "..", "bin");
58
- }
59
- function locateBinary() {
60
- const override = process.env.CMDOP_CORE_BINARY;
61
- if (override) {
62
- if (!existsSync(override)) {
63
- throw new Error(`CMDOP_CORE_BINARY points at a missing file: ${override}`);
64
- }
65
- makeExecutable(override);
66
- return override;
67
- }
68
- const key = `${process.platform}-${process.arch}`;
69
- if (!SUPPORTED_PLATFORMS.has(key)) {
70
- throw new Error(
71
- `cmdop-core has no prebuilt binary for ${key}. Set CMDOP_CORE_BINARY to a \`go build -o /path/cmdop-core ./cmd/cmdop-core\` output.`
72
- );
73
- }
74
- const binPath = join(packageBinDir(), binaryName());
75
- if (!existsSync(binPath)) {
76
- throw new Error(
77
- `cmdop-core binary not found at ${binPath}. Reinstall @cmdop/sdk (the 5 baked binaries ship in its bin/ dir), or set CMDOP_CORE_BINARY to a local \`go build\` output.`
78
- );
79
- }
80
- makeExecutable(binPath);
81
- return binPath;
82
- }
83
- function makeExecutable(path) {
84
- if (process.platform === "win32") return;
85
- try {
86
- chmodSync(path, 493);
87
- } catch {
88
- }
89
- }
90
- var file_cmdop_core_v2_contract = /* @__PURE__ */ fileDesc("ChxjbWRvcC9jb3JlL3YyL2NvbnRyYWN0LnByb3RvEg1jbWRvcC5jb3JlLnYyIukGCghFbnZlbG9wZRIKCgJpZBgBIAEoBBIqCgRraW5kGAIgASgOMhwuY21kb3AuY29yZS52Mi5FbnZlbG9wZS5LaW5kEkUKFHN5c3RlbV9ib290c3RyYXBfcmVxGAogASgLMiUuY21kb3AuY29yZS52Mi5TeXN0ZW1Cb290c3RyYXBSZXF1ZXN0SAASRwoVc3lzdGVtX2Jvb3RzdHJhcF9yZXNwGAsgASgLMiYuY21kb3AuY29yZS52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klFRBAAEikKJUFTS19TVFJFQU1fRVJST1JfQ09ERV9NQUNISU5FX09GRkxJTkUQARIkCiBBU0tfU1RSRUFNX0VSUk9SX0NPREVfTk9fVEFSR0VUUxACEiIKHkFTS19TVFJFQU1fRVJST1JfQ09ERV9JTlRFUk5BTBADEiQKIEFTS19TVFJFQU1fRVJST1JfQ09ERV9QSU5fREVOSUVEEAQqgAMKCUVycm9yQ29kZRIaChZFUlJPUl9DT0RFX1VOU1BFQ0lGSUVEEAASHwobRVJST1JfQ09ERV9JTlZBTElEX0FSR1VNRU5UEAESHgoaRVJST1JfQ09ERV9VTkFVVEhFTlRJQ0FURUQQAhIgChxFUlJPUl9DT0RFX1BFUk1JU1NJT05fREVOSUVEEAMSGAoURVJST1JfQ09ERV9OT1RfRk9VTkQQBBIXChNFUlJPUl9DT0RFX0NPTkZMSUNUEAUSGwoXRVJST1JfQ09ERV9SQVRFX0xJTUlURUQQBhIXChNFUlJPUl9DT0RFX0lOVEVSTkFMEAcSGgoWRVJST1JfQ09ERV9VTkFWQUlMQUJMRRAIEiAKHEVSUk9SX0NPREVfREVBRExJTkVfRVhDRUVERUQQCRIYChRFUlJPUl9DT0RFX1RSQU5TUE9SVBAKEhoKFkVSUk9SX0NPREVfVU5TVVBQT1JURUQQCxIXChNFUlJPUl9DT0RFX1BST1RPQ09MEAxCtgEKEWNvbS5jbWRvcC5jb3JlLnYyQg1Db250cmFjdFByb3RvUAFaPGdpdGh1Yi5jb20vY21kb3AvY21kb3AvZ28vcGtnL2NvcmVwcm90by9jbWRvcC9jb3JlL3YyO2NvcmV2MqICA0NDWKoCDUNtZG9wLkNvcmUuVjLKAg1DbWRvcFxDb3JlXFYy4gIZQ21kb3BcQ29yZVxWMlxHUEJNZXRhZGF0YeoCD0NtZG9wOjpDb3JlOjpWMmIGcHJvdG8z");
91
- var EnvelopeSchema = /* @__PURE__ */ messageDesc(file_cmdop_core_v2_contract, 0);
92
-
93
- // src/resources/base.ts
94
- var BaseResource = class {
95
- constructor(client) {
96
- this.client = client;
97
- this.t = client._t;
98
- }
99
- client;
100
- t;
101
- unary(request) {
102
- return this.t.callUnary(request);
103
- }
104
- request(payload) {
105
- return create(EnvelopeSchema, { payload });
106
- }
107
- };
108
-
109
- // src/resources/machines.ts
110
- var MachinesResource = class extends BaseResource {
111
- async list() {
112
- const response = await this.unary(
113
- this.request({ case: "listMachinesReq", value: {} })
114
- );
115
- if (response.payload.case !== "machineRosterSnapshot") {
116
- throw new Error("cmdop-core returned the wrong roster response arm");
117
- }
118
- return response.payload.value;
119
- }
120
- ask(machineId, prompt = "", options = {}) {
121
- const attachmentIds = [...options.attachmentIds ?? []];
122
- if (!prompt && attachmentIds.length === 0) {
123
- throw new Error("prompt or at least one attachmentId is required");
124
- }
125
- return this.t.callStream(
126
- this.request({
127
- case: "askMachineReq",
128
- value: {
129
- machineId,
130
- prompt,
131
- options: {
132
- pin: options.pin,
133
- session: options.session,
134
- attachmentIds,
135
- engine: options.engine,
136
- workingDir: options.workingDir,
137
- projectRootId: options.projectRootId,
138
- model: options.model
139
- }
140
- }
141
- })
142
- );
143
- }
144
- async messages(machineId, options = {}) {
145
- if (options.limit !== void 0 && (options.limit < 1 || options.limit > 500)) {
146
- throw new Error("limit must be between 1 and 500");
147
- }
148
- const response = await this.unary(
149
- this.request({
150
- case: "listMachineMessagesReq",
151
- value: { machineId, session: options.session, limit: options.limit }
152
- })
153
- );
154
- if (response.payload.case !== "machineMessageList") {
155
- throw new Error("cmdop-core returned the wrong messages response arm");
156
- }
157
- return response.payload.value;
158
- }
159
- };
160
-
161
- // src/resources/system.ts
162
- var SystemResource = class extends BaseResource {
163
- async bootstrap() {
164
- const response = await this.unary(
165
- this.request({ case: "systemBootstrapReq", value: {} })
166
- );
167
- if (response.payload.case !== "systemBootstrapResp") {
168
- throw new Error("cmdop-core returned the wrong bootstrap response arm");
169
- }
170
- return response.payload.value;
171
- }
172
- };
173
-
174
- // src/errors.ts
175
- var CmdopError = class extends Error {
176
- constructor(message, code = "internal", status, retryable = false, details) {
177
- super(message);
178
- this.code = code;
179
- this.status = status;
180
- this.details = details;
181
- this.name = new.target.name;
182
- this.retryable = retryable;
183
- Object.setPrototypeOf(this, new.target.prototype);
184
- }
185
- code;
186
- status;
187
- details;
188
- retryable;
189
- };
190
- var AuthError = class extends CmdopError {
191
- };
192
- var PermissionError = class extends CmdopError {
193
- };
194
- var NotFoundError = class extends CmdopError {
195
- };
196
- var ConflictError = class extends CmdopError {
197
- };
198
- var ValidationError = class extends CmdopError {
199
- };
200
- var RateLimitError = class extends CmdopError {
201
- };
202
- var ServerError = class extends CmdopError {
203
- };
204
- var ConnectionError = class extends CmdopError {
205
- };
206
- var TimeoutError = class extends ConnectionError {
207
- };
208
- var UnavailableError = class extends CmdopError {
209
- };
210
- var UnsupportedError = class extends CmdopError {
211
- };
212
- var ProtocolError = class extends CmdopError {
213
- };
214
- var AgentStreamError = class extends CmdopError {
215
- };
216
- var NAMES = {
217
- [0 /* UNSPECIFIED */]: "unspecified",
218
- [1 /* INVALID_ARGUMENT */]: "invalid_argument",
219
- [2 /* UNAUTHENTICATED */]: "unauthenticated",
220
- [3 /* PERMISSION_DENIED */]: "permission_denied",
221
- [4 /* NOT_FOUND */]: "not_found",
222
- [5 /* CONFLICT */]: "conflict",
223
- [6 /* RATE_LIMITED */]: "rate_limited",
224
- [7 /* INTERNAL */]: "internal",
225
- [8 /* UNAVAILABLE */]: "unavailable",
226
- [9 /* DEADLINE_EXCEEDED */]: "deadline_exceeded",
227
- [10 /* TRANSPORT */]: "transport",
228
- [11 /* UNSUPPORTED */]: "unsupported",
229
- [12 /* PROTOCOL */]: "protocol"
230
- };
231
- var TYPES = {
232
- invalid_argument: ValidationError,
233
- unauthenticated: AuthError,
234
- permission_denied: PermissionError,
235
- not_found: NotFoundError,
236
- conflict: ConflictError,
237
- rate_limited: RateLimitError,
238
- internal: ServerError,
239
- unavailable: UnavailableError,
240
- deadline_exceeded: TimeoutError,
241
- transport: ConnectionError,
242
- unsupported: UnsupportedError,
243
- protocol: ProtocolError
244
- };
245
- function mapCoreError(info) {
246
- const code = NAMES[info.code] ?? "internal";
247
- let details = info.detailsJson;
248
- if (info.detailsJson) {
249
- try {
250
- details = JSON.parse(info.detailsJson);
251
- } catch {
252
- }
253
- }
254
- const ErrorType = TYPES[code] ?? CmdopError;
255
- return new ErrorType(
256
- info.message || code.replaceAll("_", " "),
257
- code,
258
- info.httpStatus,
259
- info.retryable,
260
- details
261
- );
262
- }
263
-
264
- // src/streaming.ts
265
- var STREAM_ERROR_NAMES = {
266
- [0 /* UNSPECIFIED */]: "unspecified",
267
- [1 /* MACHINE_OFFLINE */]: "machine_offline",
268
- [2 /* NO_TARGETS */]: "no_targets",
269
- [3 /* INTERNAL */]: "internal",
270
- [4 /* PIN_DENIED */]: "pin_denied"
271
- };
272
- var AskStream = class {
273
- constructor(source, timeoutMs) {
274
- this.source = source;
275
- this.timeoutMs = timeoutMs;
276
- }
277
- source;
278
- timeoutMs;
279
- #consumed = false;
280
- async *[Symbol.asyncIterator]() {
281
- if (this.#consumed) throw new Error("an AskStream can only be consumed once");
282
- this.#consumed = true;
283
- const iterator = this.source.envelopes();
284
- for (; ; ) {
285
- const result = await withTimeout(iterator.next(), this.timeoutMs);
286
- if (result.done) return;
287
- const env = result.value;
288
- if (env.kind === 3 /* EVENT */ && env.payload.case === "askEvent") {
289
- let payload = env.payload.value.payloadJson;
290
- try {
291
- payload = JSON.parse(env.payload.value.payloadJson);
292
- } catch {
293
- }
294
- yield {
295
- type: "event",
296
- eventType: env.payload.value.eventType,
297
- payload,
298
- machineId: env.payload.value.machineId
299
- };
300
- } else if (env.kind === 3 /* EVENT */ && env.payload.case === "askStreamError") {
301
- yield {
302
- type: "error",
303
- code: STREAM_ERROR_NAMES[env.payload.value.code] ?? "internal",
304
- message: env.payload.value.message
305
- };
306
- } else if (env.kind === 4 /* DONE */ && env.payload.case === "askDone") {
307
- const value = env.payload.value;
308
- yield { type: "done", ...value };
309
- }
310
- }
311
- }
312
- async collect() {
313
- let text = "";
314
- let streamError;
315
- for await (const frame of this) {
316
- if (frame.type === "event") {
317
- const payload = frame.payload;
318
- text += payload?.delta ?? payload?.text ?? "";
319
- } else if (frame.type === "error") {
320
- streamError = frame;
321
- } else if (!frame.success) {
322
- throw new AgentStreamError(
323
- frame.error ?? streamError?.message ?? "agent run failed",
324
- streamError?.code ?? "internal",
325
- frame.upstreamStatus
326
- );
327
- } else {
328
- return frame.text || text;
329
- }
330
- }
331
- return text;
332
- }
333
- };
334
- async function withTimeout(promise, timeoutMs) {
335
- let timer;
336
- try {
337
- return await Promise.race([
338
- promise,
339
- new Promise((_, reject) => {
340
- timer = setTimeout(
341
- () => reject(new TimeoutError("agent stream timed out", "deadline_exceeded", void 0, true)),
342
- timeoutMs
343
- );
344
- })
345
- ]);
346
- } finally {
347
- if (timer) clearTimeout(timer);
348
- }
349
- }
350
-
351
- // src/transport.ts
352
- var MAX_QUEUED_FRAMES = 256;
353
- var MAX_REQUEST_FRAME_BYTES = 4 * 1024 * 1024;
354
- var FrameQueue = class {
355
- #frames = [];
356
- #wait;
357
- #done = false;
358
- #error;
359
- push(envelope) {
360
- if (this.#done) return;
361
- if (this.#wait) {
362
- const waiter = this.#wait;
363
- this.#wait = void 0;
364
- waiter({ value: envelope, done: false });
365
- return;
366
- }
367
- if (this.#frames.length >= MAX_QUEUED_FRAMES) {
368
- this.fail(new ConnectionError("agent stream consumer is too slow", "transport"));
369
- return;
370
- }
371
- this.#frames.push(envelope);
372
- }
373
- end() {
374
- this.#done = true;
375
- this.#wakeDone();
376
- }
377
- fail(error) {
378
- this.#error = error;
379
- this.#done = true;
380
- this.#wakeDone();
381
- }
382
- #wakeDone() {
383
- if (this.#wait) {
384
- const waiter = this.#wait;
385
- this.#wait = void 0;
386
- waiter({ value: void 0, done: true });
387
- }
388
- }
389
- async *iterate() {
390
- for (; ; ) {
391
- if (this.#error) throw this.#error;
392
- if (this.#frames.length) {
393
- yield this.#frames.shift();
394
- continue;
395
- }
396
- if (this.#done) return;
397
- const result = await new Promise((resolve2) => {
398
- this.#wait = resolve2;
399
- });
400
- if (this.#error) throw this.#error;
401
- if (result.done) return;
402
- yield result.value;
403
- }
404
- }
405
- };
406
- var Transport = class {
407
- constructor(config, binaryPath) {
408
- this.config = config;
409
- this.binaryPath = binaryPath;
410
- }
411
- config;
412
- binaryPath;
413
- #child;
414
- #stdin;
415
- #pending = /* @__PURE__ */ new Map();
416
- #nextId = 1n;
417
- #closed = false;
418
- #starting;
419
- /** @internal test seam */
420
- attachStreamsForTest(stdin, stdout) {
421
- this.#stdin = stdin;
422
- this.#child = { stdin };
423
- this.#startReader(stdout);
424
- }
425
- async #ensureStarted() {
426
- if (this.#child) return;
427
- if (this.#starting) return this.#starting;
428
- this.#starting = this.#spawn();
429
- try {
430
- await this.#starting;
431
- } finally {
432
- this.#starting = void 0;
433
- }
434
- }
435
- async #spawn() {
436
- const env = { ...process.env };
437
- if (this.config.token) env.CMDOP_TOKEN = this.config.token;
438
- else delete env.CMDOP_TOKEN;
439
- if (this.config.baseUrl) env.CMDOP_BASE_URL = this.config.baseUrl;
440
- else delete env.CMDOP_BASE_URL;
441
- const child = spawn(this.binaryPath, ["--stdio"], {
442
- stdio: ["pipe", "pipe", "pipe"],
443
- env,
444
- windowsHide: true
445
- });
446
- this.#child = child;
447
- this.#stdin = child.stdin;
448
- child.stderr.on("data", () => {
449
- });
450
- child.on("exit", () => this.#failAll(new ConnectionError("cmdop-core exited", "transport")));
451
- child.on(
452
- "error",
453
- (error) => this.#failAll(new ConnectionError(`cmdop-core spawn failed: ${error.message}`, "transport"))
454
- );
455
- this.#startReader(child.stdout);
456
- }
457
- #startReader(stdout) {
458
- void (async () => {
459
- try {
460
- for await (const envelope of sizeDelimitedDecodeStream(EnvelopeSchema, stdout)) {
461
- this.#dispatch(envelope);
462
- }
463
- this.#failAll(new ConnectionError("cmdop-core stdout closed", "transport"));
464
- } catch (error) {
465
- this.#failAll(
466
- new ConnectionError(
467
- `core read failed: ${error instanceof Error ? error.message : String(error)}`,
468
- "transport"
469
- )
470
- );
471
- }
472
- })();
473
- }
474
- #dispatch(envelope) {
475
- const pending = this.#pending.get(envelope.id);
476
- if (!pending) return;
477
- if (pending.kind === "unary") {
478
- if (envelope.kind === 2 /* RESPONSE */) {
479
- this.#pending.delete(envelope.id);
480
- clearTimeout(pending.timer);
481
- pending.resolve(envelope);
482
- } else if (envelope.kind === 5 /* ERROR */ && envelope.payload.case === "error") {
483
- this.#pending.delete(envelope.id);
484
- clearTimeout(pending.timer);
485
- pending.reject(mapCoreError(envelope.payload.value));
486
- }
487
- return;
488
- }
489
- if (envelope.kind === 3 /* EVENT */) {
490
- pending.queue.push(envelope);
491
- } else if (envelope.kind === 4 /* DONE */) {
492
- this.#pending.delete(envelope.id);
493
- pending.queue.push(envelope);
494
- pending.queue.end();
495
- } else if (envelope.kind === 5 /* ERROR */ && envelope.payload.case === "error") {
496
- this.#pending.delete(envelope.id);
497
- pending.queue.fail(mapCoreError(envelope.payload.value));
498
- }
499
- }
500
- #failAll(error) {
501
- const pending = this.#pending;
502
- this.#pending = /* @__PURE__ */ new Map();
503
- for (const call of pending.values()) {
504
- if (call.kind === "unary") {
505
- clearTimeout(call.timer);
506
- call.reject(error);
507
- } else {
508
- call.queue.fail(error);
509
- }
510
- }
511
- }
512
- #write(envelope) {
513
- if (!this.#stdin) throw new ConnectionError("cmdop-core is not running", "transport");
514
- if (toBinary(EnvelopeSchema, envelope).byteLength > MAX_REQUEST_FRAME_BYTES) {
515
- throw new ConnectionError(
516
- `request frame exceeds ${MAX_REQUEST_FRAME_BYTES} bytes`,
517
- "transport"
518
- );
519
- }
520
- this.#stdin.write(sizeDelimitedEncode(EnvelopeSchema, envelope));
521
- }
522
- async callUnary(request) {
523
- await this.#ensureStarted();
524
- request.id = this.#nextId++;
525
- request.kind = 1 /* REQUEST */;
526
- return new Promise((resolve2, reject) => {
527
- const timer = setTimeout(() => {
528
- this.#pending.delete(request.id);
529
- reject(new TimeoutError("cmdop-core request timed out", "deadline_exceeded", void 0, true));
530
- }, this.config.timeoutMs);
531
- this.#pending.set(request.id, { kind: "unary", resolve: resolve2, reject, timer });
532
- try {
533
- this.#write(request);
534
- } catch (error) {
535
- clearTimeout(timer);
536
- this.#pending.delete(request.id);
537
- reject(error);
538
- }
539
- });
540
- }
541
- callStream(request) {
542
- const transport = this;
543
- let started = false;
544
- const source = {
545
- async *envelopes() {
546
- if (started) throw new Error("an AskStream can only be consumed once");
547
- started = true;
548
- await transport.#ensureStarted();
549
- request.id = transport.#nextId++;
550
- request.kind = 1 /* REQUEST */;
551
- const queue = new FrameQueue();
552
- transport.#pending.set(request.id, { kind: "stream", queue });
553
- try {
554
- transport.#write(request);
555
- yield* queue.iterate();
556
- } finally {
557
- transport.#pending.delete(request.id);
558
- }
559
- }
560
- };
561
- return new AskStream(source, this.config.timeoutMs);
562
- }
563
- async close() {
564
- if (this.#closed) return;
565
- this.#closed = true;
566
- const child = this.#child;
567
- if (!child) return;
568
- this.#stdin?.end();
569
- if (typeof child.once === "function" && typeof child.kill === "function") {
570
- await new Promise((resolve2) => {
571
- let finished = false;
572
- const done = () => {
573
- if (!finished) {
574
- finished = true;
575
- resolve2();
576
- }
577
- };
578
- child.once("exit", done);
579
- setTimeout(() => {
580
- if (!finished) child.kill();
581
- done();
582
- }, 5e3);
583
- });
584
- }
585
- this.#failAll(new ConnectionError("client closed", "transport"));
586
- }
587
- };
588
-
589
- // src/client.ts
590
- var Client = class _Client {
591
- config;
592
- /** @internal */
593
- _t;
594
- constructor(opts = {}) {
595
- const resolved = typeof opts === "string" ? { token: opts } : opts;
596
- this.config = resolveConfig(resolved);
597
- this._t = new Transport(this.config, resolved.binaryPath ?? locateBinary());
598
- }
599
- static fromEnv() {
600
- return new _Client();
601
- }
602
- get baseUrl() {
603
- return this.config.baseUrl;
604
- }
605
- #system;
606
- get system() {
607
- return this.#system ??= new SystemResource(this);
608
- }
609
- #machines;
610
- get machines() {
611
- return this.#machines ??= new MachinesResource(this);
612
- }
613
- async close() {
614
- await this._t.close();
615
- }
616
- async [Symbol.asyncDispose]() {
617
- await this.close();
618
- }
619
- };
620
-
621
- // src/types.ts
622
- var types_exports = {};
623
-
624
- export { AgentStreamError, AskStream, AuthError, Client, CmdopError, ConflictError, ConnectionError, DEFAULT_TIMEOUT_MS, NotFoundError, PermissionError, ProtocolError, RateLimitError, ServerError, TimeoutError, UnavailableError, UnsupportedError, ValidationError, resolveConfig, types_exports as types };
625
- //# sourceMappingURL=index.js.map
626
- //# sourceMappingURL=index.js.map
1
+ export { CmdopError, connect, urlOf, } from "./client.js";
2
+ export { CarrierError } from "./carriers/carrier.js";
3
+ export { httpCarrier } from "./carriers/http.js";
4
+ export { memoryCarrier } from "./carriers/memory.js";
5
+ export * from "./generated/tools.gen.js";
6
+ export * from "./generated/call.gen.js";
7
+ export { decodeImage, toScreenshot } from "./screen.js";
8
+ export { anthropicToCalls, openaiToCalls, performCalls, UnsupportedAction } from "./vendor.js";
@@ -0,0 +1,19 @@
1
+ /** A screenshot as bytes (@dev/completed/computer-use/10_computer_use.md, D7): the machine answers base64 PNG inside the JSON; this decodes it. */
2
+ import type { Geometry, Image, ScreenCaptureOut } from "./generated/tools.gen.ts";
3
+ /** A decoded picture: `bytes` are the encoded file (PNG), ready for `new Blob([bytes], { type: mime })` or a file. */
4
+ export interface DecodedImage {
5
+ bytes: Uint8Array;
6
+ mime: string;
7
+ width: number;
8
+ height: number;
9
+ }
10
+ /** What `client.screenshot` returns. Pixel coordinates of every pointer tool are pixels of `image` (see `geometry`). */
11
+ export interface Screenshot {
12
+ image: DecodedImage;
13
+ geometry: Geometry;
14
+ /** Id of the audit line and the saved copy on the machine. */
15
+ auditId: string;
16
+ }
17
+ /** Decodes the base64 `data` of a machine picture. Throws on a format this SDK does not know, rather than guess a mime. */
18
+ export declare function decodeImage(image: Image): DecodedImage;
19
+ export declare function toScreenshot(out: ScreenCaptureOut): Screenshot;
package/dist/screen.js ADDED
@@ -0,0 +1,16 @@
1
+ /** A screenshot as bytes (@dev/completed/computer-use/10_computer_use.md, D7): the machine answers base64 PNG inside the JSON; this decodes it. */
2
+ const MIME = { png: "image/png", jpeg: "image/jpeg", jpg: "image/jpeg", webp: "image/webp" };
3
+ /** Decodes the base64 `data` of a machine picture. Throws on a format this SDK does not know, rather than guess a mime. */
4
+ export function decodeImage(image) {
5
+ const mime = MIME[image.format.toLowerCase()];
6
+ if (!mime)
7
+ throw new Error(`unknown image format ${JSON.stringify(image.format)}`);
8
+ const raw = atob(image.data);
9
+ const bytes = new Uint8Array(raw.length);
10
+ for (let i = 0; i < raw.length; i += 1)
11
+ bytes[i] = raw.charCodeAt(i);
12
+ return { bytes, mime, width: image.width, height: image.height };
13
+ }
14
+ export function toScreenshot(out) {
15
+ return { image: decodeImage(out.image), geometry: out.geometry, auditId: out.audit_id };
16
+ }