@m8tes/sdk 0.1.0-alpha.1 → 0.1.0-alpha.2

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,5 +1,5 @@
1
- import { createNormalizer, createSseDecoder, initialConversationState, accumulate, RunFailedError, APIError, parseRetryAfter, parseErrorEnvelope, errorClassForStatus } from './chunk-UFQQNUFE.js';
2
- export { APIError, AuthenticationError, BillingError, ConflictError, M8tesApiError, NotFoundError, PROTOCOL_VERSION, PermissionDeniedError, RateLimitError, RunFailedError, RunNotStreamingError, TERMINAL_EVENT_TYPES, ValidationError, accumulate, createAccumulator, createNormalizer, createSseDecoder, errorClassForStatus, errorFromResponse, initialConversationState, isTerminalEvent, parseErrorEnvelope, parseRetryAfter, parseSse, splitConcatenatedJson } from './chunk-UFQQNUFE.js';
1
+ import { createNormalizer, createSseDecoder, initialConversationState, accumulate, RunFailedError, APIError, parseRetryAfter, ConflictError, NotFoundError, AuthenticationError, PermissionDeniedError, ValidationError, seg, parseErrorEnvelope, errorClassForStatus } from './chunk-CURNMC4F.js';
2
+ export { APIError, AuthenticationError, BillingError, ConflictError, M8tesApiError, NotFoundError, PROTOCOL_VERSION, PermissionDeniedError, RateLimitError, RunFailedError, RunNotStreamingError, TERMINAL_EVENT_TYPES, ValidationError, accumulate, createAccumulator, createNormalizer, createSseDecoder, errorClassForStatus, errorFromResponse, initialConversationState, isTerminalEvent, parseErrorEnvelope, parseRetryAfter, parseSse, seg, splitConcatenatedJson } from './chunk-CURNMC4F.js';
3
3
  import { createHmac, timingSafeEqual } from 'crypto';
4
4
 
5
5
  // src/http.ts
@@ -8,6 +8,23 @@ var MAX_ATTEMPTS = 3;
8
8
  var INITIAL_BACKOFF_MS = 500;
9
9
  var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
10
10
  var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
11
+ var IDEMPOTENCY_HEADER = "idempotency-key";
12
+ var REPLAY_HEADER = "idempotent-replay";
13
+ var IDEMPOTENT_POST_PATHS = [
14
+ /^\/runs\/?$/,
15
+ /^\/runs\/with-files\/?$/,
16
+ /^\/runs\/\d+\/reply\/?$/,
17
+ /^\/runs\/\d+\/reply\/with-files\/?$/,
18
+ /^\/tasks\/\d+\/runs\/?$/
19
+ ];
20
+ function isIdempotentRoute(path) {
21
+ const clean = path.split("?")[0] ?? "";
22
+ return IDEMPOTENT_POST_PATHS.some((re) => re.test(clean));
23
+ }
24
+ function isRetryable(method, path, headers) {
25
+ if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;
26
+ return IDEMPOTENCY_HEADER in headers && isIdempotentRoute(path);
27
+ }
11
28
  function backoff(ms, signal) {
12
29
  if (signal?.aborted) return Promise.resolve();
13
30
  return new Promise((resolve) => {
@@ -68,14 +85,22 @@ function createHttp(options = {}) {
68
85
  const message = diagnose(res, text, body, url) ?? (body ? parsed.message : text || parsed.message);
69
86
  return new (errorClassForStatus(res.status, errOpts))(message, parsed.fields);
70
87
  }
88
+ function mergeHeaders(...sources) {
89
+ const out = {};
90
+ for (const src of sources) {
91
+ for (const [k, v] of Object.entries(src ?? {})) out[k.toLowerCase()] = v;
92
+ }
93
+ return out;
94
+ }
71
95
  async function attempt(method, url, opts) {
72
- const headers = {
73
- authorization: `Bearer ${apiKey}`,
74
- ...options.headers,
75
- ...opts.headers
76
- };
96
+ const headers = mergeHeaders(options.headers, opts.headers, {
97
+ authorization: `Bearer ${apiKey}`
98
+ });
77
99
  const init = { method, headers };
78
- if (opts.body !== void 0) {
100
+ if (opts.form !== void 0) {
101
+ delete headers["content-type"];
102
+ init.body = opts.form;
103
+ } else if (opts.body !== void 0) {
79
104
  headers["content-type"] = "application/json";
80
105
  init.body = JSON.stringify(opts.body);
81
106
  }
@@ -85,7 +110,7 @@ function createHttp(options = {}) {
85
110
  }
86
111
  async function send(method, path, opts, errOpts = {}) {
87
112
  const url = `${baseUrl}${path}${opts.query ?? ""}`;
88
- const idempotent = IDEMPOTENT_METHODS.has(method.toUpperCase());
113
+ const idempotent = isRetryable(method, path, mergeHeaders(options.headers, opts.headers));
89
114
  let lastNetworkError;
90
115
  for (let i = 0; i < MAX_ATTEMPTS; i++) {
91
116
  const isLast = i === MAX_ATTEMPTS - 1;
@@ -133,6 +158,11 @@ function createHttp(options = {}) {
133
158
  },
134
159
  async *stream(method, path, opts = {}) {
135
160
  const res = await send(method, path, opts, { conflictIsNotStreaming: true });
161
+ if (opts.onReplay && res.headers.get(REPLAY_HEADER)) {
162
+ const run = await res.json();
163
+ yield* opts.onReplay(run);
164
+ return;
165
+ }
136
166
  if (!res.body) return;
137
167
  const normalizer = opts.normalizer ?? createNormalizer();
138
168
  const decoder = createSseDecoder({ onMalformed: options.onMalformed });
@@ -246,68 +276,537 @@ function createAgentsResource(http) {
246
276
  return fetchPage({ ...params });
247
277
  },
248
278
  get(agentId, params = {}) {
249
- return http.request("GET", `/agents/${agentId}`, { query: toQuery(params) });
279
+ return http.request("GET", `/agents/${seg(agentId)}`, { query: toQuery(params) });
250
280
  },
251
281
  update(agentId, params) {
252
282
  const { user_id, ...patch } = params;
253
- return http.request("PATCH", `/agents/${agentId}`, {
283
+ return http.request("PATCH", `/agents/${seg(agentId)}`, {
254
284
  body: toBody(patch),
255
285
  query: toQuery({ user_id })
256
286
  });
257
287
  },
258
288
  async delete(agentId, params = {}) {
259
- await http.request("DELETE", `/agents/${agentId}`, { query: toQuery(params) });
289
+ await http.request("DELETE", `/agents/${seg(agentId)}`, { query: toQuery(params) });
260
290
  },
261
- enableWebhook(agentId) {
262
- return http.request("POST", `/agents/${agentId}/webhook`, { body: {} });
291
+ enableWebhook(agentId, params = {}) {
292
+ return http.request("POST", `/agents/${seg(agentId)}/webhook`, {
293
+ body: {},
294
+ query: toQuery(params)
295
+ });
263
296
  },
264
- async disableWebhook(agentId) {
265
- await http.request("DELETE", `/agents/${agentId}/webhook`);
297
+ async disableWebhook(agentId, params = {}) {
298
+ await http.request("DELETE", `/agents/${seg(agentId)}/webhook`, { query: toQuery(params) });
266
299
  },
267
- enableEmailInbox(agentId) {
268
- return http.request("POST", `/agents/${agentId}/email-inbox`, { body: {} });
300
+ enableEmailInbox(agentId, params = {}) {
301
+ return http.request("POST", `/agents/${seg(agentId)}/email-inbox`, {
302
+ body: {},
303
+ query: toQuery(params)
304
+ });
269
305
  },
270
- async disableEmailInbox(agentId) {
271
- await http.request("DELETE", `/agents/${agentId}/email-inbox`);
306
+ async disableEmailInbox(agentId, params = {}) {
307
+ await http.request("DELETE", `/agents/${seg(agentId)}/email-inbox`, { query: toQuery(params) });
272
308
  }
273
309
  };
274
310
  }
275
311
 
276
312
  // src/resources/apps.ts
277
313
  function createAppsResource(http) {
278
- const slug = (name) => encodeURIComponent(name);
314
+ const list = async (params = {}) => {
315
+ const res = await http.request("GET", "/apps/", {
316
+ query: toQuery({ user_id: params.user_id })
317
+ });
318
+ return new Page(res?.data ?? [], res?.has_more ?? false);
319
+ };
279
320
  return {
280
- async list(params = {}) {
281
- const res = await http.request("GET", "/apps/", {
282
- query: toQuery({ user_id: params.user_id })
283
- });
284
- return new Page(res?.data ?? [], res?.has_more ?? false);
285
- },
321
+ list,
286
322
  async isConnected(appName, params = {}) {
287
- const { data } = await this.list(params);
323
+ const { data } = await list(params);
288
324
  return data.find((a) => a.name === appName)?.connected ?? false;
289
325
  },
290
326
  connectOauth(appName, params) {
291
- return http.request("POST", `/apps/${slug(appName)}/connect`, {
327
+ return http.request("POST", `/apps/${seg(appName)}/connect`, {
292
328
  body: toBody({ ...params })
293
329
  });
294
330
  },
295
331
  connectApiKey(appName, params) {
296
- return http.request("POST", `/apps/${slug(appName)}/connect/api-key`, {
332
+ return http.request("POST", `/apps/${seg(appName)}/connect/api-key`, {
297
333
  body: toBody({ ...params })
298
334
  });
299
335
  },
300
336
  connectComplete(appName, params) {
301
- return http.request("POST", `/apps/${slug(appName)}/connect/complete`, {
337
+ return http.request("POST", `/apps/${seg(appName)}/connect/complete`, {
302
338
  body: toBody({ ...params })
303
339
  });
304
340
  },
305
341
  async disconnect(appName, params = {}) {
306
- await http.request("DELETE", `/apps/${slug(appName)}/connections`, { query: toQuery(params) });
342
+ await http.request("DELETE", `/apps/${seg(appName)}/connections`, { query: toQuery(params) });
343
+ }
344
+ };
345
+ }
346
+
347
+ // src/resources/account.ts
348
+ function createAccountResource(http) {
349
+ return {
350
+ export() {
351
+ return http.request("GET", "/account/export");
352
+ },
353
+ delete() {
354
+ return http.request("DELETE", "/account");
355
+ }
356
+ };
357
+ }
358
+
359
+ // src/resources/users.ts
360
+ function pager(http, path) {
361
+ const fetchPage = async (p) => {
362
+ const res = await http.request("GET", path, {
363
+ query: toQuery(p)
364
+ });
365
+ return new Page(
366
+ res?.data ?? [],
367
+ res?.has_more ?? false,
368
+ (starting_after) => fetchPage({ ...p, starting_after })
369
+ );
370
+ };
371
+ return fetchPage;
372
+ }
373
+ function createUsersResource(http) {
374
+ return {
375
+ create(params) {
376
+ return http.request("POST", "/users/", { body: toBody({ ...params }) });
377
+ },
378
+ list(params = {}) {
379
+ return pager(http, "/users/")({ ...params });
380
+ },
381
+ get(userId) {
382
+ return http.request("GET", `/users/${seg(userId)}`);
383
+ },
384
+ update(userId, params) {
385
+ return http.request("PATCH", `/users/${seg(userId)}`, {
386
+ body: toBody({ ...params })
387
+ });
388
+ },
389
+ async delete(userId) {
390
+ await http.request("DELETE", `/users/${seg(userId)}`);
391
+ },
392
+ usage(params = {}) {
393
+ return pager(http, "/usage/end-users")({ ...params });
307
394
  }
308
395
  };
309
396
  }
310
397
 
398
+ // src/resources/billing.ts
399
+ function createBillingResource(http) {
400
+ return {
401
+ usage() {
402
+ return http.request("GET", "/usage/");
403
+ },
404
+ usageTimeseries(params = {}) {
405
+ const { agent_id, teammate_id, ...rest } = params;
406
+ const query = toQuery(
407
+ toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) })
408
+ );
409
+ return http.request("GET", "/usage/timeseries", { query });
410
+ },
411
+ receipts(params = {}) {
412
+ return pager(http, "/billing/receipts")({ ...params });
413
+ },
414
+ plans() {
415
+ return http.request("GET", "/billing/plans");
416
+ },
417
+ setOverage(params) {
418
+ return http.request("PATCH", "/billing/overage", { body: toBody({ ...params }) });
419
+ },
420
+ balance() {
421
+ return http.request("GET", "/billing/balance");
422
+ },
423
+ async topup(params) {
424
+ const res = await http.request("POST", "/billing/topup", {
425
+ body: toBody({ ...params })
426
+ });
427
+ return res.checkout_url;
428
+ },
429
+ setAutoReload(params) {
430
+ return http.request("PATCH", "/billing/auto-reload", {
431
+ body: toBody({ ...params })
432
+ });
433
+ },
434
+ setAlertThreshold(params) {
435
+ return http.request("PATCH", "/billing/alert-settings", {
436
+ body: toBody({ ...params })
437
+ });
438
+ }
439
+ };
440
+ }
441
+
442
+ // src/resources/memories.ts
443
+ function createMemoriesResource(http) {
444
+ return {
445
+ create(params) {
446
+ return http.request("POST", "/memories/", { body: toBody({ ...params }) });
447
+ },
448
+ list(params = {}) {
449
+ return pager(http, "/memories/")({ ...params });
450
+ },
451
+ update(memoryId, { user_id, content }) {
452
+ return http.request("PATCH", `/memories/${seg(memoryId)}`, {
453
+ query: toQuery({ user_id }),
454
+ body: toBody({ content })
455
+ });
456
+ },
457
+ async delete(memoryId, params = {}) {
458
+ await http.request("DELETE", `/memories/${seg(memoryId)}`, {
459
+ query: toQuery({ user_id: params.user_id })
460
+ });
461
+ }
462
+ };
463
+ }
464
+
465
+ // src/resources/models.ts
466
+ function createModelsResource(http) {
467
+ return {
468
+ async list() {
469
+ const res = await http.request("GET", "/models/");
470
+ return new Page(res?.data ?? [], res?.has_more ?? false);
471
+ }
472
+ };
473
+ }
474
+
475
+ // src/resources/model-connections.ts
476
+ function createModelConnectionsResource(http) {
477
+ return {
478
+ async list() {
479
+ const res = await http.request("GET", "/model-connections/");
480
+ return res?.data ?? [];
481
+ },
482
+ authorize(provider) {
483
+ return http.request(
484
+ "POST",
485
+ `/model-connections/${seg(provider)}/authorizations`
486
+ );
487
+ },
488
+ authorizationStatus(provider, state) {
489
+ return http.request(
490
+ "GET",
491
+ `/model-connections/${seg(provider)}/authorizations/${seg(state)}`
492
+ );
493
+ },
494
+ completeAuthorization(provider, state, params) {
495
+ return http.request(
496
+ "POST",
497
+ `/model-connections/${seg(provider)}/authorizations/${seg(state)}`,
498
+ { body: { code: params.code } }
499
+ );
500
+ },
501
+ async cancelAuthorization(provider, state) {
502
+ await http.request("DELETE", `/model-connections/${seg(provider)}/authorizations/${seg(state)}`);
503
+ },
504
+ disconnect(provider) {
505
+ return http.request("DELETE", `/model-connections/${seg(provider)}`);
506
+ }
507
+ };
508
+ }
509
+
510
+ // src/resources/permissions.ts
511
+ function createPermissionsResource(http) {
512
+ return {
513
+ create(params) {
514
+ return http.request("POST", "/permissions/", {
515
+ body: toBody({ ...params })
516
+ });
517
+ },
518
+ list(params) {
519
+ return pager(http, "/permissions/")({ ...params });
520
+ },
521
+ async delete(permissionId, params) {
522
+ await http.request("DELETE", `/permissions/${seg(permissionId)}`, {
523
+ query: toQuery({ user_id: params.user_id })
524
+ });
525
+ }
526
+ };
527
+ }
528
+
529
+ // src/mime.ts
530
+ var EXTENSION_TYPES = Object.assign(/* @__PURE__ */ Object.create(null), {
531
+ // Images (the agent can actually see these via its Read tool)
532
+ jpg: "image/jpeg",
533
+ jpeg: "image/jpeg",
534
+ png: "image/png",
535
+ gif: "image/gif",
536
+ webp: "image/webp",
537
+ // Documents
538
+ pdf: "application/pdf",
539
+ txt: "text/plain",
540
+ md: "text/markdown",
541
+ markdown: "text/markdown",
542
+ html: "text/html",
543
+ htm: "text/html",
544
+ // Code
545
+ py: "text/x-python",
546
+ js: "application/javascript",
547
+ mjs: "application/javascript",
548
+ cjs: "application/javascript",
549
+ json: "application/json",
550
+ ts: "text/typescript",
551
+ tsx: "text/typescript",
552
+ css: "text/css",
553
+ c: "text/x-c",
554
+ h: "text/x-c",
555
+ java: "text/x-java-source",
556
+ go: "text/x-go",
557
+ sql: "application/sql",
558
+ // Data / config
559
+ csv: "text/csv",
560
+ tsv: "text/csv",
561
+ xml: "application/xml",
562
+ yaml: "text/yaml",
563
+ yml: "text/yaml",
564
+ // Archives
565
+ zip: "application/zip",
566
+ gz: "application/gzip",
567
+ tgz: "application/gzip",
568
+ tar: "application/x-tar",
569
+ // Office
570
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
571
+ xls: "application/vnd.ms-excel",
572
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
573
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
574
+ ppt: "application/vnd.ms-powerpoint"
575
+ });
576
+ var UPLOADABLE_EXTENSIONS = Object.keys(EXTENSION_TYPES);
577
+ function mimeTypeForFilename(name) {
578
+ const ext = name.includes(".") ? name.slice(name.lastIndexOf(".") + 1).toLowerCase() : "";
579
+ return EXTENSION_TYPES[ext];
580
+ }
581
+ function unknownTypeMessage(name) {
582
+ return `@m8tes/sdk: cannot infer a content type for "${name}", and the upload endpoint rejects files whose type it does not recognise. Pass it explicitly \u2014 { name: "${name}", data, type: "text/plain" } \u2014 or rename the file with a known extension (${UPLOADABLE_EXTENSIONS.slice(0, 12).join(", ")}, ...).`;
583
+ }
584
+
585
+ // src/polling.ts
586
+ function isPermanent(err) {
587
+ return err instanceof AuthenticationError || err instanceof PermissionDeniedError || err instanceof NotFoundError || err instanceof ValidationError;
588
+ }
589
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "closed"]);
590
+ var BENIGN_GATE_REFUSAL_CODES = /* @__PURE__ */ new Set(["gate_cancelled", "run_not_active"]);
591
+ var AUTO_CONTINUED_MESSAGE = "auto_continued";
592
+ function isBenignGateRefusal(err) {
593
+ if (err.errorCode !== void 0) return BENIGN_GATE_REFUSAL_CODES.has(err.errorCode);
594
+ return err instanceof ConflictError && err.message === AUTO_CONTINUED_MESSAGE;
595
+ }
596
+ var RunTimeoutError = class extends Error {
597
+ runId;
598
+ timeoutSeconds;
599
+ /** The last error seen while polling, if any. Without it a timeout hides the
600
+ * transient failure that actually caused it. */
601
+ cause;
602
+ /** The run's status when the deadline hit, when one was ever observed. */
603
+ lastStatus;
604
+ constructor(runId, timeoutSeconds, cause, lastStatus) {
605
+ const advice = lastStatus === "awaiting_approval" ? `The run is waiting for a human and will never finish on its own: use runs.wait() with onApproval/onQuestion, or resolve it yourself via runs.permissions(${runId}).` : `Raise the timeout, or stream the run instead of polling it.`;
606
+ super(
607
+ `Run ${runId} did not reach a terminal status within ${timeoutSeconds}s` + (lastStatus ? ` (last status: ${lastStatus})` : "") + `. ${advice}` + (cause instanceof Error ? ` Last error while polling: ${cause.message}` : "")
608
+ );
609
+ this.name = "RunTimeoutError";
610
+ this.runId = runId;
611
+ this.timeoutSeconds = timeoutSeconds;
612
+ this.cause = cause;
613
+ if (lastStatus !== void 0) this.lastStatus = lastStatus;
614
+ }
615
+ };
616
+ var RunPausedError = class extends Error {
617
+ runId;
618
+ request;
619
+ constructor(runId, request, hint) {
620
+ super(`Run ${runId} is waiting for a human: ${hint}`);
621
+ this.name = "RunPausedError";
622
+ this.runId = runId;
623
+ this.request = request;
624
+ }
625
+ };
626
+ function plan(options) {
627
+ const interval = options.interval ?? 2;
628
+ const timeout = options.timeout ?? 300;
629
+ for (const [name, value] of [["interval", interval], ["timeout", timeout]]) {
630
+ if (!Number.isFinite(value) || value < 0) {
631
+ throw new TypeError(
632
+ `@m8tes/sdk: ${name} must be a finite, non-negative number of seconds (got ${String(value)}).`
633
+ );
634
+ }
635
+ }
636
+ return { interval, timeout, deadline: now() + timeout * 1e3, signal: options.signal };
637
+ }
638
+ function napUntil(interval, deadline, signal) {
639
+ const remaining = Math.max(0, deadline - now()) / 1e3;
640
+ return sleep(Math.min(interval, remaining), signal);
641
+ }
642
+ async function withDeadline(start, deadline, signal, onExpired) {
643
+ const remaining = deadline - now();
644
+ if (remaining <= 0) throw onExpired();
645
+ const work = start();
646
+ let timer;
647
+ let onAbort;
648
+ try {
649
+ return await Promise.race([
650
+ work,
651
+ new Promise((_, reject) => {
652
+ timer = setTimeout(() => reject(onExpired()), remaining);
653
+ if (signal) {
654
+ onAbort = () => reject(onExpired());
655
+ signal.addEventListener("abort", onAbort, { once: true });
656
+ }
657
+ })
658
+ ]);
659
+ } finally {
660
+ if (timer) clearTimeout(timer);
661
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
662
+ }
663
+ }
664
+ function sleep(seconds, signal) {
665
+ if (signal?.aborted) return Promise.resolve();
666
+ return new Promise((resolve) => {
667
+ const timer = setTimeout(done, seconds * 1e3);
668
+ function done() {
669
+ clearTimeout(timer);
670
+ signal?.removeEventListener("abort", done);
671
+ resolve();
672
+ }
673
+ signal?.addEventListener("abort", done, { once: true });
674
+ });
675
+ }
676
+ function isPlanApproval(request) {
677
+ if (request.tool_name !== "AskUserQuestion") return false;
678
+ const questions = request.tool_input?.questions;
679
+ return Array.isArray(questions) && questions.some((q) => q?.header === "Plan Approval");
680
+ }
681
+ function planText(request) {
682
+ if (!isPlanApproval(request)) return null;
683
+ const questions = request.tool_input?.questions;
684
+ return questions?.find((q) => q?.header === "Plan Approval")?.question ?? null;
685
+ }
686
+ var now = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
687
+ var RunWaitAbortedError = class extends Error {
688
+ /**
689
+ * The run being waited on — `undefined` when the abort landed BEFORE any run
690
+ * was created, which is the one case where there is nothing to go back to.
691
+ * Previously this path passed a literal 0, producing "Waiting on run 0 was
692
+ * aborted" and pointing the reader at a run that never existed.
693
+ */
694
+ runId;
695
+ constructor(runId) {
696
+ super(
697
+ runId === void 0 ? "Aborted before the run was created; nothing was started and nothing was billed." : `Waiting on run ${runId} was aborted. The run is still executing \u2014 poll it later with runs.get(${runId}), or stop it with runs.cancel(${runId}).`
698
+ );
699
+ this.name = "RunWaitAbortedError";
700
+ if (runId !== void 0) this.runId = runId;
701
+ }
702
+ };
703
+ async function pollRun(deps, runId, options = {}) {
704
+ const { interval, timeout, deadline, signal } = plan(options);
705
+ if (signal?.aborted) throw new RunWaitAbortedError(runId);
706
+ let lastError;
707
+ let lastStatus;
708
+ for (; ; ) {
709
+ let run;
710
+ try {
711
+ run = await withDeadline(
712
+ () => deps.get(runId, signal),
713
+ deadline,
714
+ signal,
715
+ () => signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus)
716
+ );
717
+ } catch (err) {
718
+ if (err instanceof RunTimeoutError || err instanceof RunWaitAbortedError) throw err;
719
+ if (signal?.aborted) throw new RunWaitAbortedError(runId);
720
+ if (isPermanent(err)) throw err;
721
+ lastError = err;
722
+ if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);
723
+ await napUntil(interval, deadline, signal);
724
+ if (signal?.aborted) throw new RunWaitAbortedError(runId);
725
+ if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);
726
+ continue;
727
+ }
728
+ lastStatus = run.status;
729
+ if (TERMINAL_STATUSES.has(run.status)) return run;
730
+ if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);
731
+ await napUntil(interval, deadline, signal);
732
+ if (signal?.aborted) throw new RunWaitAbortedError(runId);
733
+ if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);
734
+ }
735
+ }
736
+ async function waitForRun(deps, runId, options = {}) {
737
+ const { interval, timeout, deadline, signal } = plan(options);
738
+ if (signal?.aborted) throw new RunWaitAbortedError(runId);
739
+ let lastError;
740
+ let lastStatus;
741
+ const answered = /* @__PURE__ */ new Set();
742
+ for (; ; ) {
743
+ let run;
744
+ try {
745
+ run = await withDeadline(
746
+ () => deps.get(runId, signal),
747
+ deadline,
748
+ signal,
749
+ () => signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus)
750
+ );
751
+ } catch (err) {
752
+ if (err instanceof RunTimeoutError || err instanceof RunWaitAbortedError) throw err;
753
+ if (signal?.aborted) throw new RunWaitAbortedError(runId);
754
+ if (isPermanent(err)) throw err;
755
+ lastError = err;
756
+ if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);
757
+ await napUntil(interval, deadline, signal);
758
+ if (signal?.aborted) throw new RunWaitAbortedError(runId);
759
+ if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);
760
+ continue;
761
+ }
762
+ lastStatus = run.status;
763
+ if (TERMINAL_STATUSES.has(run.status)) return run;
764
+ if (run.status === "awaiting_approval") {
765
+ const expired = () => signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus);
766
+ const bound = (start) => withDeadline(start, deadline, signal, expired);
767
+ const resolveGate = async (start) => {
768
+ try {
769
+ await bound(start);
770
+ } catch (err) {
771
+ if (!(err instanceof ConflictError) && !(err instanceof NotFoundError)) throw err;
772
+ if (!isBenignGateRefusal(err)) throw err;
773
+ }
774
+ };
775
+ const pending = (await bound(() => deps.permissions(runId, signal))).filter(
776
+ (r) => r.status === "pending" && !answered.has(r.request_id)
777
+ );
778
+ for (const request of pending) {
779
+ answered.add(request.request_id);
780
+ if (request.tool_name === "AskUserQuestion") {
781
+ if (!options.onQuestion) {
782
+ throw new RunPausedError(
783
+ runId,
784
+ request,
785
+ "the agent asked a question. Pass onQuestion to answer it, or call runs.answer() yourself."
786
+ );
787
+ }
788
+ const answers = await bound(async () => options.onQuestion(request));
789
+ await resolveGate(() => deps.answer(runId, { answers }, signal));
790
+ } else {
791
+ if (!options.onApproval) {
792
+ throw new RunPausedError(
793
+ runId,
794
+ request,
795
+ `the tool "${request.tool_name}" needs a decision. Pass onApproval, or call runs.approve() yourself.`
796
+ );
797
+ }
798
+ const decision = await bound(async () => options.onApproval(request));
799
+ await resolveGate(() => deps.approve(runId, { request_id: request.request_id, decision }, signal));
800
+ }
801
+ }
802
+ }
803
+ if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);
804
+ await napUntil(interval, deadline, signal);
805
+ if (signal?.aborted) throw new RunWaitAbortedError(runId);
806
+ if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);
807
+ }
808
+ }
809
+
311
810
  // src/streaming.ts
312
811
  var RunStream = class {
313
812
  source;
@@ -386,29 +885,114 @@ var RunStream = class {
386
885
  };
387
886
 
388
887
  // src/resources/runs.ts
888
+ function withRunId(err, runId) {
889
+ if (err && typeof err === "object" && !("runId" in err)) {
890
+ Object.defineProperty(err, "runId", { value: runId, enumerable: true, configurable: true });
891
+ const e = err;
892
+ if (typeof e.message === "string" && !e.message.includes(String(runId))) {
893
+ e.message = `${e.message} (while waiting on run ${runId}, which is still executing)`;
894
+ }
895
+ }
896
+ return err;
897
+ }
389
898
  function items(payload) {
390
899
  return Array.isArray(payload) ? payload : payload?.data ?? [];
391
900
  }
901
+ function idempotencyHeaders(key) {
902
+ return { [IDEMPOTENCY_HEADER]: key ?? crypto.randomUUID() };
903
+ }
904
+ function replayJoin(http) {
905
+ return async function* (run) {
906
+ if (TERMINAL_STATUSES.has(run.status)) {
907
+ throw new ConflictError(
908
+ `Run ${run.id} was already created by an earlier attempt with this idempotency key and has finished (status=${run.status}), so there is no stream to join. You were charged once. Fetch the result with runs.get(${run.id}).`,
909
+ {
910
+ type: "invalid_request_error",
911
+ code: 409,
912
+ status: 409,
913
+ details: { error_code: "idempotent_replay_terminal", run_id: run.id, status: run.status }
914
+ }
915
+ );
916
+ }
917
+ yield* http.stream("GET", `/runs/${seg(run.id)}/stream`);
918
+ };
919
+ }
392
920
  function createRunsResource(http) {
393
921
  const createBody = (p, stream) => {
394
- const { agent_id, teammate_id, ...rest } = p;
922
+ const { agent_id, teammate_id, files, idempotencyKey, ...rest } = p;
395
923
  return toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id), stream });
396
924
  };
925
+ const createForm = (p, stream) => {
926
+ const form = new FormData();
927
+ form.append("payload", JSON.stringify(createBody(p, stream)));
928
+ for (const f of p.files ?? []) {
929
+ const blobType = f.data instanceof Blob && f.data.type ? f.data.type : void 0;
930
+ const type = f.type ?? blobType ?? mimeTypeForFilename(f.name);
931
+ if (!type) throw new TypeError(unknownTypeMessage(f.name));
932
+ const blob = f.data instanceof Blob && f.data.type === type ? f.data : new Blob([f.data], { type });
933
+ form.append("files", blob, f.name);
934
+ }
935
+ return form;
936
+ };
937
+ const hasFiles = (p) => (p.files?.length ?? 0) > 0;
938
+ const deps = {
939
+ get: (runId, signal) => http.request("GET", `/runs/${seg(runId)}`, { signal }),
940
+ permissions: async (runId, signal) => items(await http.request("GET", `/runs/${seg(runId)}/permissions`, { signal })),
941
+ approve: (runId, params, signal) => http.request("POST", `/runs/${seg(runId)}/approve`, { body: { remember: false, ...params }, signal }),
942
+ answer: (runId, params, signal) => http.request("POST", `/runs/${seg(runId)}/answer`, { body: params, signal })
943
+ };
944
+ const createAsync = async (params) => {
945
+ const headers = idempotencyHeaders(params.idempotencyKey);
946
+ return hasFiles(params) ? http.request("POST", "/runs/with-files", { form: createForm(params, false), headers }) : http.request("POST", "/runs", { body: createBody(params, false), headers });
947
+ };
397
948
  return {
398
949
  create(params, options) {
399
- return new RunStream(http.stream("POST", "/runs", { body: createBody(params, true) }), options);
950
+ const headers = idempotencyHeaders(params.idempotencyKey);
951
+ const init = hasFiles(params) ? { form: createForm(params, true), headers } : { body: createBody(params, true), headers };
952
+ const path = hasFiles(params) ? "/runs/with-files" : "/runs";
953
+ return new RunStream(
954
+ http.stream("POST", path, { ...init, onReplay: replayJoin(http) }),
955
+ options
956
+ );
957
+ },
958
+ createAsync,
959
+ async createAndWait(params, options = {}) {
960
+ if (options.signal?.aborted) throw new RunWaitAbortedError();
961
+ const started = await createAsync(params);
962
+ try {
963
+ return await waitForRun(deps, started.id, options);
964
+ } catch (err) {
965
+ throw withRunId(err, started.id);
966
+ }
400
967
  },
401
- createAsync(params) {
402
- return http.request("POST", "/runs", { body: createBody(params, false) });
968
+ poll(runId, options) {
969
+ return pollRun(deps, runId, options);
970
+ },
971
+ wait(runId, options) {
972
+ return waitForRun(deps, runId, options);
973
+ },
974
+ // `confirm` is a QUERY param and the route takes no body (verified against
975
+ // fastapi/app/routers/v2/runs.py::retry_run), so send neither.
976
+ retry(runId, params = {}) {
977
+ return http.request("POST", `/runs/${seg(runId)}/retry`, {
978
+ query: params.confirm ? toQuery({ confirm: true }) : ""
979
+ });
403
980
  },
404
981
  stream(runId, options) {
405
- return new RunStream(http.stream("GET", `/runs/${runId}/stream`), options);
982
+ return new RunStream(http.stream("GET", `/runs/${seg(runId)}/stream`), options);
406
983
  },
407
984
  reply(runId, message, options) {
408
- return new RunStream(http.stream("POST", `/runs/${runId}/reply`, { body: { message } }), options);
985
+ return new RunStream(
986
+ http.stream("POST", `/runs/${seg(runId)}/reply`, {
987
+ body: { message },
988
+ headers: idempotencyHeaders(options?.idempotencyKey),
989
+ onReplay: replayJoin(http)
990
+ }),
991
+ options
992
+ );
409
993
  },
410
994
  get(runId) {
411
- return http.request("GET", `/runs/${runId}`);
995
+ return http.request("GET", `/runs/${seg(runId)}`);
412
996
  },
413
997
  async list(params = {}) {
414
998
  const { agent_id, teammate_id, ...rest } = params;
@@ -426,29 +1010,29 @@ function createRunsResource(http) {
426
1010
  return fetchPage(q);
427
1011
  },
428
1012
  cancel(runId) {
429
- return http.request("POST", `/runs/${runId}/cancel`, { body: {} });
1013
+ return http.request("POST", `/runs/${seg(runId)}/cancel`, { body: {} });
430
1014
  },
431
1015
  approve(runId, params) {
432
- return http.request("POST", `/runs/${runId}/approve`, {
1016
+ return http.request("POST", `/runs/${seg(runId)}/approve`, {
433
1017
  body: { remember: false, ...params }
434
1018
  });
435
1019
  },
436
1020
  answer(runId, params) {
437
- return http.request("POST", `/runs/${runId}/answer`, {
1021
+ return http.request("POST", `/runs/${seg(runId)}/answer`, {
438
1022
  body: { answers: params.answers }
439
1023
  });
440
1024
  },
441
1025
  async permissions(runId) {
442
- return items(await http.request("GET", `/runs/${runId}/permissions`));
1026
+ return items(await http.request("GET", `/runs/${seg(runId)}/permissions`));
443
1027
  },
444
1028
  outcome(runId) {
445
- return http.request("GET", `/runs/${runId}/outcome`);
1029
+ return http.request("GET", `/runs/${seg(runId)}/outcome`);
446
1030
  },
447
1031
  async files(runId) {
448
- return items(await http.request("GET", `/runs/${runId}/files`));
1032
+ return items(await http.request("GET", `/runs/${seg(runId)}/files`));
449
1033
  },
450
1034
  async downloadFile(runId, filename) {
451
- const res = await http.raw("GET", `/runs/${runId}/files/${encodeURIComponent(filename)}/download`, {
1035
+ const res = await http.raw("GET", `/runs/${seg(runId)}/files/${seg(filename)}/download`, {
452
1036
  headers: { accept: "application/octet-stream" }
453
1037
  });
454
1038
  return res.arrayBuffer();
@@ -473,24 +1057,30 @@ function createSettingsResource(http) {
473
1057
  function createTasksResource(http) {
474
1058
  const triggers = {
475
1059
  create(taskId, params) {
476
- return http.request("POST", `/tasks/${taskId}/triggers/`, {
477
- body: toBody({ timezone: "UTC", ...params })
1060
+ return http.request("POST", `/tasks/${seg(taskId)}/triggers/`, {
1061
+ body: toBody({ timezone: "UTC", ...params }),
1062
+ query: toQuery({ user_id: params.user_id })
478
1063
  });
479
1064
  },
480
- async list(taskId) {
1065
+ async list(taskId, params = {}) {
481
1066
  const res = await http.request(
482
1067
  "GET",
483
- `/tasks/${taskId}/triggers/`
1068
+ `/tasks/${seg(taskId)}/triggers/`,
1069
+ { query: toQuery(params) }
484
1070
  );
485
1071
  return Array.isArray(res) ? res : res?.data ?? [];
486
1072
  },
487
1073
  update(taskId, triggerId, params) {
488
- return http.request("PATCH", `/tasks/${taskId}/triggers/${triggerId}`, {
489
- body: toBody({ ...params })
1074
+ const { user_id, ...patch } = params;
1075
+ return http.request("PATCH", `/tasks/${seg(taskId)}/triggers/${seg(triggerId)}`, {
1076
+ body: toBody(patch),
1077
+ query: toQuery({ user_id })
490
1078
  });
491
1079
  },
492
- async delete(taskId, triggerId) {
493
- await http.request("DELETE", `/tasks/${taskId}/triggers/${triggerId}`);
1080
+ async delete(taskId, triggerId, params = {}) {
1081
+ await http.request("DELETE", `/tasks/${seg(taskId)}/triggers/${seg(triggerId)}`, {
1082
+ query: toQuery(params)
1083
+ });
494
1084
  }
495
1085
  };
496
1086
  return {
@@ -517,73 +1107,46 @@ function createTasksResource(http) {
517
1107
  return fetchPage(q);
518
1108
  },
519
1109
  get(taskId, params = {}) {
520
- return http.request("GET", `/tasks/${taskId}`, { query: toQuery(params) });
1110
+ return http.request("GET", `/tasks/${seg(taskId)}`, { query: toQuery(params) });
521
1111
  },
522
1112
  update(taskId, params) {
523
1113
  const { user_id, ...patch } = params;
524
- return http.request("PATCH", `/tasks/${taskId}`, {
1114
+ return http.request("PATCH", `/tasks/${seg(taskId)}`, {
525
1115
  body: toBody(patch),
526
1116
  query: toQuery({ user_id })
527
1117
  });
528
1118
  },
529
1119
  async delete(taskId, params = {}) {
530
- await http.request("DELETE", `/tasks/${taskId}`, { query: toQuery(params) });
1120
+ await http.request("DELETE", `/tasks/${seg(taskId)}`, { query: toQuery(params) });
531
1121
  },
532
1122
  run(taskId, params = {}, options) {
1123
+ const { idempotencyKey, ...rest } = params;
533
1124
  return new RunStream(
534
- http.stream("POST", `/tasks/${taskId}/runs`, { body: toBody({ ...params, stream: true }) }),
1125
+ http.stream("POST", `/tasks/${seg(taskId)}/runs`, {
1126
+ body: toBody({ ...rest, stream: true }),
1127
+ headers: idempotencyHeaders(idempotencyKey),
1128
+ // Shares the create path's replay handling, so a fix on one side can
1129
+ // never silently miss the other.
1130
+ onReplay: replayJoin(http)
1131
+ }),
535
1132
  options
536
1133
  );
537
1134
  },
538
1135
  runAsync(taskId, params = {}) {
539
- return http.request("POST", `/tasks/${taskId}/runs`, {
540
- body: toBody({ ...params, stream: false })
1136
+ const { idempotencyKey, ...rest } = params;
1137
+ return http.request("POST", `/tasks/${seg(taskId)}/runs`, {
1138
+ body: toBody({ ...rest, stream: false }),
1139
+ headers: idempotencyHeaders(idempotencyKey)
541
1140
  });
542
1141
  },
543
- enableWebhook(taskId) {
544
- return http.request("POST", `/tasks/${taskId}/webhook`, { body: {} });
545
- },
546
- async disableWebhook(taskId) {
547
- await http.request("DELETE", `/tasks/${taskId}/webhook`);
548
- }
549
- };
550
- }
551
-
552
- // src/resources/users.ts
553
- function pager(http, path) {
554
- const fetchPage = async (p) => {
555
- const res = await http.request("GET", path, {
556
- query: toQuery(p)
557
- });
558
- return new Page(
559
- res?.data ?? [],
560
- res?.has_more ?? false,
561
- (starting_after) => fetchPage({ ...p, starting_after })
562
- );
563
- };
564
- return fetchPage;
565
- }
566
- function createUsersResource(http) {
567
- return {
568
- create(params) {
569
- return http.request("POST", "/users/", { body: toBody({ ...params }) });
570
- },
571
- list(params = {}) {
572
- return pager(http, "/users/")({ ...params });
573
- },
574
- get(userId) {
575
- return http.request("GET", `/users/${encodeURIComponent(userId)}`);
576
- },
577
- update(userId, params) {
578
- return http.request("PATCH", `/users/${encodeURIComponent(userId)}`, {
579
- body: toBody({ ...params })
1142
+ enableWebhook(taskId, params = {}) {
1143
+ return http.request("POST", `/tasks/${seg(taskId)}/webhook`, {
1144
+ body: {},
1145
+ query: toQuery(params)
580
1146
  });
581
1147
  },
582
- async delete(userId) {
583
- await http.request("DELETE", `/users/${encodeURIComponent(userId)}`);
584
- },
585
- usage(params = {}) {
586
- return pager(http, "/usage/end-users")({ ...params });
1148
+ async disableWebhook(taskId, params = {}) {
1149
+ await http.request("DELETE", `/tasks/${seg(taskId)}/webhook`, { query: toQuery(params) });
587
1150
  }
588
1151
  };
589
1152
  }
@@ -607,8 +1170,8 @@ function verifySignature(body, headers, secret, options = {}) {
607
1170
  if (options.toleranceSeconds !== void 0) {
608
1171
  const ts = Number.parseInt(timestamp, 10);
609
1172
  if (!Number.isFinite(ts)) return false;
610
- const now = options.now ? options.now() : Math.floor(Date.now() / 1e3);
611
- if (Math.abs(now - ts) > options.toleranceSeconds) return false;
1173
+ const now2 = options.now ? options.now() : Math.floor(Date.now() / 1e3);
1174
+ if (Math.abs(now2 - ts) > options.toleranceSeconds) return false;
612
1175
  }
613
1176
  const raw = typeof body === "string" ? body : new TextDecoder().decode(body);
614
1177
  const expected = `v1=${createHmac("sha256", secret).update(`${webhookId}.${timestamp}.${raw}`).digest("hex")}`;
@@ -626,22 +1189,22 @@ function createWebhooksResource(http) {
626
1189
  return pager(http, "/webhooks/")({ ...params });
627
1190
  },
628
1191
  get(webhookId) {
629
- return http.request("GET", `/webhooks/${webhookId}`);
1192
+ return http.request("GET", `/webhooks/${seg(webhookId)}`);
630
1193
  },
631
1194
  update(webhookId, params) {
632
- return http.request("PATCH", `/webhooks/${webhookId}`, { body: toBody({ ...params }) });
1195
+ return http.request("PATCH", `/webhooks/${seg(webhookId)}`, { body: toBody({ ...params }) });
633
1196
  },
634
1197
  async delete(webhookId) {
635
- await http.request("DELETE", `/webhooks/${webhookId}`);
1198
+ await http.request("DELETE", `/webhooks/${seg(webhookId)}`);
636
1199
  },
637
1200
  listDeliveries(webhookId, params = {}) {
638
- return pager(http, `/webhooks/${webhookId}/deliveries`)({ ...params });
1201
+ return pager(http, `/webhooks/${seg(webhookId)}/deliveries`)({ ...params });
639
1202
  }
640
1203
  };
641
1204
  }
642
1205
 
643
1206
  // src/index.ts
644
- var M8TES_SDK_VERSION = "0.1.0-alpha.1";
1207
+ var M8TES_SDK_VERSION = "0.1.0-alpha.2";
645
1208
  var M8tes = class {
646
1209
  runs;
647
1210
  agents;
@@ -652,6 +1215,12 @@ var M8tes = class {
652
1215
  apps;
653
1216
  webhooks;
654
1217
  settings;
1218
+ memories;
1219
+ permissions;
1220
+ models;
1221
+ modelConnections;
1222
+ billing;
1223
+ account;
655
1224
  /** The underlying transport. Use it to call an endpoint this version does not wrap yet. */
656
1225
  http;
657
1226
  constructor(options = {}) {
@@ -664,9 +1233,15 @@ var M8tes = class {
664
1233
  this.apps = createAppsResource(this.http);
665
1234
  this.webhooks = createWebhooksResource(this.http);
666
1235
  this.settings = createSettingsResource(this.http);
1236
+ this.memories = createMemoriesResource(this.http);
1237
+ this.permissions = createPermissionsResource(this.http);
1238
+ this.models = createModelsResource(this.http);
1239
+ this.modelConnections = createModelConnectionsResource(this.http);
1240
+ this.billing = createBillingResource(this.http);
1241
+ this.account = createAccountResource(this.http);
667
1242
  }
668
1243
  };
669
1244
 
670
- export { DEFAULT_BASE_URL, M8TES_SDK_VERSION, M8tes, Page, RunStream, createHttp, verifySignature };
1245
+ export { DEFAULT_BASE_URL, M8TES_SDK_VERSION, M8tes, Page, RunPausedError, RunStream, RunTimeoutError, RunWaitAbortedError, TERMINAL_STATUSES, createHttp, isPlanApproval, planText, pollRun, verifySignature, waitForRun };
671
1246
  //# sourceMappingURL=index.js.map
672
1247
  //# sourceMappingURL=index.js.map