theokit 0.28.0 → 0.30.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 (28) hide show
  1. package/dist/{actions-virtual-module-JB5ZTS5U.js → actions-virtual-module-PBLLMJY4.js} +3 -3
  2. package/dist/{app-typed-client-VMSRQGKL.js → app-typed-client-EXHUWPOI.js} +3 -3
  3. package/dist/{chunk-R4VVXLKZ.js → chunk-EHUT4FMG.js} +10 -10
  4. package/dist/chunk-RBRDTYOO.js +470 -0
  5. package/dist/chunk-RBRDTYOO.js.map +1 -0
  6. package/dist/{chunk-H243MR3F.js → chunk-TGTNRUH3.js} +2 -2
  7. package/dist/{chunk-W4XWVTN4.js → chunk-UYFZ6DDW.js} +2 -2
  8. package/dist/{chunk-Z5IGLBWE.js → chunk-WFNLNIJX.js} +1 -1
  9. package/dist/client/core.d.ts +294 -0
  10. package/dist/client/core.js +22 -0
  11. package/dist/client/index.d.ts +10 -229
  12. package/dist/client/index.js +18 -386
  13. package/dist/client/index.js.map +1 -1
  14. package/dist/index.js +6 -6
  15. package/dist/{internal-api-KPULK7ZK.js → internal-api-JIR3HRKF.js} +3 -3
  16. package/dist/internal-api-JIR3HRKF.js.map +1 -0
  17. package/dist/server/http/index.js +2 -2
  18. package/dist/server/index.js +3 -3
  19. package/dist/server/observability/index.js +1 -1
  20. package/dist/vite-plugin/index.js +6 -6
  21. package/package.json +5 -1
  22. /package/dist/{actions-virtual-module-JB5ZTS5U.js.map → actions-virtual-module-PBLLMJY4.js.map} +0 -0
  23. /package/dist/{app-typed-client-VMSRQGKL.js.map → app-typed-client-EXHUWPOI.js.map} +0 -0
  24. /package/dist/{chunk-R4VVXLKZ.js.map → chunk-EHUT4FMG.js.map} +0 -0
  25. /package/dist/{chunk-H243MR3F.js.map → chunk-TGTNRUH3.js.map} +0 -0
  26. /package/dist/{chunk-W4XWVTN4.js.map → chunk-UYFZ6DDW.js.map} +0 -0
  27. /package/dist/{chunk-Z5IGLBWE.js.map → chunk-WFNLNIJX.js.map} +0 -0
  28. /package/dist/{internal-api-KPULK7ZK.js.map → client/core.js.map} +0 -0
@@ -1,3 +1,13 @@
1
+ import {
2
+ AgentClient,
3
+ ChannelTransport,
4
+ HttpTransport,
5
+ InProcessTransport,
6
+ consumeChunkStream,
7
+ consumeUIMessageStream,
8
+ createAgentClient,
9
+ responseToChunkStream
10
+ } from "../chunk-RBRDTYOO.js";
1
11
  import {
2
12
  buildUseTheoQueryConfig,
3
13
  stableQueryKey
@@ -384,237 +394,8 @@ function createAppClient(baseUrlOrOptions, legacyFetchImpl) {
384
394
  return makeProxy({ segments: [], baseUrl, fetchImpl });
385
395
  }
386
396
 
387
- // src/client/consume-ui-message-stream.ts
388
- async function consumeUIMessageStream(response, onMessage) {
389
- const chunkStream = await responseToChunkStream(response);
390
- await consumeChunkStream(chunkStream, onMessage);
391
- }
392
- async function responseToChunkStream(response) {
393
- if (response.body === null) {
394
- return new ReadableStream({
395
- start(controller) {
396
- controller.close();
397
- }
398
- });
399
- }
400
- const { parseJsonEventStream, uiMessageChunkSchema } = await import("ai");
401
- const parsed = parseJsonEventStream({ stream: response.body, schema: uiMessageChunkSchema });
402
- return new ReadableStream({
403
- async start(controller) {
404
- for await (const result of parsed) {
405
- if (result.success) controller.enqueue(result.value);
406
- }
407
- controller.close();
408
- }
409
- });
410
- }
411
- async function consumeChunkStream(stream, onMessage) {
412
- const { readUIMessageStream } = await import("ai");
413
- for await (const message of readUIMessageStream({ stream })) {
414
- onMessage(message);
415
- }
416
- }
417
-
418
397
  // src/client/use-agent.ts
419
398
  import { useMemo, useRef, useSyncExternalStore } from "react";
420
-
421
- // src/client/agent-client.ts
422
- function inputToText(input) {
423
- if (typeof input === "object" && input !== null && typeof input.message === "string") {
424
- return input.message;
425
- }
426
- if (typeof input === "string") return input;
427
- return JSON.stringify(input);
428
- }
429
- function buildUserMessage(input) {
430
- return {
431
- id: crypto.randomUUID(),
432
- role: "user",
433
- parts: [{ type: "text", text: inputToText(input) }]
434
- };
435
- }
436
- var AgentClient = class {
437
- #transport;
438
- #chatId = crypto.randomUUID();
439
- #listeners = /* @__PURE__ */ new Set();
440
- #messages = [];
441
- #status = "idle";
442
- #error;
443
- #controller = null;
444
- #snapshot = { messages: [], status: "idle", error: void 0 };
445
- constructor(transport) {
446
- this.#transport = transport;
447
- }
448
- /** Subscribe to state changes; returns an unsubscribe fn. */
449
- subscribe = (listener) => {
450
- this.#listeners.add(listener);
451
- return () => {
452
- this.#listeners.delete(listener);
453
- };
454
- };
455
- /** The current immutable snapshot (stable reference until the next emit). */
456
- getSnapshot = () => this.#snapshot;
457
- #emit() {
458
- this.#snapshot = { messages: this.#messages, status: this.#status, error: this.#error };
459
- for (const listener of this.#listeners) listener();
460
- }
461
- #upsert(message) {
462
- const next = [...this.#messages];
463
- const idx = next.findIndex((existing) => existing.id === message.id);
464
- if (idx >= 0) next[idx] = message;
465
- else next.push(message);
466
- this.#messages = next;
467
- }
468
- async #drive(open, controller) {
469
- const aborted = () => controller.signal.aborted;
470
- try {
471
- const stream = await open();
472
- if (aborted()) return;
473
- if (stream === null) {
474
- this.#status = this.#messages.length > 0 ? "done" : "idle";
475
- this.#emit();
476
- return;
477
- }
478
- await consumeChunkStream(stream, (message) => {
479
- if (aborted()) return;
480
- this.#upsert(message);
481
- this.#emit();
482
- });
483
- if (aborted()) return;
484
- this.#status = "done";
485
- this.#emit();
486
- } catch (err) {
487
- if (aborted()) return;
488
- this.#error = err instanceof Error ? err : new Error(String(err));
489
- this.#status = "error";
490
- this.#emit();
491
- }
492
- }
493
- /** Send a typed input; opens a fresh stream (replaces prior messages). */
494
- send = (input) => {
495
- this.abort();
496
- const controller = new AbortController();
497
- this.#controller = controller;
498
- this.#messages = [];
499
- this.#error = void 0;
500
- this.#status = "streaming";
501
- this.#emit();
502
- void this.#drive(
503
- () => this.#transport.sendMessages({
504
- trigger: "submit-message",
505
- chatId: this.#chatId,
506
- messageId: void 0,
507
- messages: [buildUserMessage(input)],
508
- abortSignal: controller.signal,
509
- // Only object inputs flow as the request `body` (the turn text is always in `messages`);
510
- // a primitive input is carried by the user message, never spread into the body.
511
- body: typeof input === "object" && input !== null ? input : void 0
512
- }),
513
- controller
514
- );
515
- };
516
- /** Resume an interrupted stream via the transport's `reconnectToStream` (no-op when unavailable). */
517
- reconnect = () => {
518
- const controller = new AbortController();
519
- this.#controller = controller;
520
- this.#status = "streaming";
521
- this.#emit();
522
- void this.#drive(() => this.#transport.reconnectToStream({ chatId: this.#chatId }), controller);
523
- };
524
- /** Abort an in-flight stream (not an error — leaves messages as-is). */
525
- abort = () => {
526
- this.#controller?.abort();
527
- this.#controller = null;
528
- };
529
- /** Clear messages + error, back to idle. */
530
- reset = () => {
531
- this.abort();
532
- this.#messages = [];
533
- this.#error = void 0;
534
- this.#status = "idle";
535
- this.#emit();
536
- };
537
- /** Settle a paused HITL approval via the transport's HITL path (HTTP POST or inline callback). */
538
- approve = async (approvalId, decision) => {
539
- await this.#transport.approve?.(approvalId, decision);
540
- };
541
- };
542
-
543
- // src/client/http-transport.ts
544
- function toRecord(headers) {
545
- if (headers === void 0) return {};
546
- if (headers instanceof Headers) return Object.fromEntries(headers.entries());
547
- return headers;
548
- }
549
- var HttpTransport = class {
550
- #api;
551
- #headers;
552
- #fetch;
553
- /** Server-minted id of the last run (from `x-theokit-run-id`) — the reconnect key. */
554
- #lastRunId;
555
- constructor(options) {
556
- this.#api = options.api;
557
- this.#headers = options.headers ?? {};
558
- this.#fetch = options.fetch ?? globalThis.fetch;
559
- }
560
- /** Resolve the configured headers per request (a resolver evaluates now — dynamic auth is never stale). */
561
- #resolveHeaders() {
562
- return (typeof this.#headers === "function" ? this.#headers() : this.#headers) ?? {};
563
- }
564
- async sendMessages(options) {
565
- const { messages, abortSignal, headers, body } = options;
566
- const extra = typeof body === "object" ? body : void 0;
567
- const response = await this.#fetch(this.#api, {
568
- method: "POST",
569
- headers: {
570
- "content-type": "application/json",
571
- accept: "text/event-stream",
572
- "X-Theo-Action": "1",
573
- ...this.#resolveHeaders(),
574
- ...toRecord(headers)
575
- },
576
- body: JSON.stringify({ ...extra, messages }),
577
- signal: abortSignal
578
- });
579
- if (!response.ok) {
580
- throw new Error(
581
- `Agent request to ${this.#api} failed: ${response.status} ${response.statusText}`
582
- );
583
- }
584
- this.#lastRunId = response.headers.get("x-theokit-run-id") ?? void 0;
585
- return responseToChunkStream(response);
586
- }
587
- async reconnectToStream(options) {
588
- if (this.#lastRunId === void 0) return null;
589
- const response = await this.#fetch(`${this.#api}/runs/${this.#lastRunId}/stream`, {
590
- method: "GET",
591
- headers: { ...this.#resolveHeaders(), ...toRecord(options.headers) }
592
- });
593
- if (response.status === 404) return null;
594
- if (!response.ok) {
595
- throw new Error(
596
- `Agent reconnect to run ${this.#lastRunId} failed: ${response.status} ${response.statusText}`
597
- );
598
- }
599
- return responseToChunkStream(response);
600
- }
601
- async approve(approvalId, decision) {
602
- const response = await this.#fetch(`${this.#api}/approve/${approvalId}`, {
603
- method: "POST",
604
- headers: {
605
- "content-type": "application/json",
606
- "X-Theo-Action": "1",
607
- ...this.#resolveHeaders()
608
- },
609
- body: JSON.stringify(decision)
610
- });
611
- if (!response.ok) {
612
- throw new Error(`Approve ${approvalId} failed: ${response.status} ${response.statusText}`);
613
- }
614
- }
615
- };
616
-
617
- // src/client/use-agent.ts
618
399
  function useAgent(pathOrTransport, options = {}) {
619
400
  const optionsRef = useRef(options);
620
401
  optionsRef.current = options;
@@ -624,9 +405,14 @@ function useAgent(pathOrTransport, options = {}) {
624
405
  api: pathOrTransport,
625
406
  headers: () => optionsRef.current.headers,
626
407
  fetch: optionsRef.current.fetch
627
- }) : pathOrTransport
408
+ }) : pathOrTransport,
409
+ // M43 — resolve context live from the ref each send/reconnect (never stale). A value or a resolver.
410
+ () => {
411
+ const ctx = optionsRef.current.context;
412
+ return typeof ctx === "function" ? ctx() : ctx;
413
+ }
628
414
  ),
629
- // Identity is the binding; headers are resolved live via optionsRef, fetch captured at creation.
415
+ // Identity is the binding; headers/context are resolved live via optionsRef, fetch captured at creation.
630
416
  [pathOrTransport]
631
417
  );
632
418
  const state = useSyncExternalStore(client.subscribe, client.getSnapshot, client.getSnapshot);
@@ -642,161 +428,6 @@ function useAgent(pathOrTransport, options = {}) {
642
428
  };
643
429
  }
644
430
 
645
- // src/client/last-user-text.ts
646
- function extractLastUserText(messages) {
647
- for (let i = messages.length - 1; i >= 0; i--) {
648
- const message = messages[i];
649
- if (message.role !== "user") continue;
650
- const text = message.parts.filter((part) => part.type === "text").map((part) => part.text).join("");
651
- if (text.length > 0) return text;
652
- }
653
- return "";
654
- }
655
-
656
- // src/client/in-process-transport.ts
657
- function generatorToStream(gen) {
658
- return new ReadableStream({
659
- async pull(controller) {
660
- try {
661
- const result = await gen.next();
662
- if (result.done === true) {
663
- controller.close();
664
- return;
665
- }
666
- controller.enqueue(result.value);
667
- } catch (err) {
668
- controller.error(err);
669
- }
670
- },
671
- async cancel() {
672
- await gen.return(void 0);
673
- }
674
- });
675
- }
676
- var InProcessTransport = class {
677
- #run;
678
- /** Pending inline approvals: approvalId → resolver of the parked `awaitApproval` promise. */
679
- #pending = /* @__PURE__ */ new Map();
680
- constructor(options) {
681
- this.#run = options.run;
682
- }
683
- #awaitApproval = (req) => new Promise((resolve, reject) => {
684
- if (this.#pending.has(req.approvalId)) {
685
- reject(new Error(`Duplicate pending approval id '${req.approvalId}' \u2014 ids must be unique.`));
686
- return;
687
- }
688
- this.#pending.set(req.approvalId, resolve);
689
- });
690
- sendMessages(options) {
691
- const { messages, abortSignal } = options;
692
- const generator = this.#run({
693
- message: extractLastUserText(messages),
694
- signal: abortSignal ?? void 0,
695
- awaitApproval: this.#awaitApproval
696
- });
697
- return Promise.resolve(generatorToStream(generator));
698
- }
699
- reconnectToStream() {
700
- return Promise.resolve(null);
701
- }
702
- approve(approvalId, decision) {
703
- const resolve = this.#pending.get(approvalId);
704
- if (resolve === void 0) {
705
- return Promise.reject(
706
- new Error(`No pending approval '${approvalId}' (unknown or already settled).`)
707
- );
708
- }
709
- this.#pending.delete(approvalId);
710
- resolve(decision);
711
- return Promise.resolve();
712
- }
713
- };
714
-
715
- // src/client/channel-transport.ts
716
- var ChannelTransport = class {
717
- #source;
718
- constructor(options) {
719
- this.#source = options.source;
720
- }
721
- sendMessages(options) {
722
- const { messages, abortSignal } = options;
723
- const message = extractLastUserText(messages);
724
- const source = this.#source;
725
- let closed = false;
726
- let teardown = () => void 0;
727
- let detachAbort = () => void 0;
728
- const stream = new ReadableStream({
729
- start(controller) {
730
- const finish = (settle) => {
731
- if (closed) return;
732
- closed = true;
733
- detachAbort();
734
- settle();
735
- };
736
- teardown = source.start(
737
- { message },
738
- {
739
- onLine: (line) => {
740
- if (closed) return;
741
- let parsed;
742
- try {
743
- parsed = JSON.parse(line);
744
- } catch {
745
- return;
746
- }
747
- if (typeof parsed !== "object" || parsed === null || typeof parsed.type !== "string") {
748
- return;
749
- }
750
- controller.enqueue(parsed);
751
- },
752
- onClose: () => {
753
- finish(() => {
754
- controller.close();
755
- });
756
- },
757
- onError: (err) => {
758
- finish(() => {
759
- controller.error(err);
760
- });
761
- }
762
- }
763
- );
764
- if (abortSignal !== void 0) {
765
- const onAbort = () => {
766
- finish(() => {
767
- teardown();
768
- controller.close();
769
- });
770
- };
771
- if (abortSignal.aborted) onAbort();
772
- else {
773
- abortSignal.addEventListener("abort", onAbort);
774
- detachAbort = () => {
775
- abortSignal.removeEventListener("abort", onAbort);
776
- };
777
- }
778
- }
779
- },
780
- cancel() {
781
- if (closed) return;
782
- closed = true;
783
- detachAbort();
784
- teardown();
785
- }
786
- });
787
- return Promise.resolve(stream);
788
- }
789
- reconnectToStream() {
790
- return Promise.resolve(null);
791
- }
792
- async approve(approvalId, decision) {
793
- if (this.#source.settle === void 0) {
794
- throw new Error(`This channel source has no HITL settle \u2014 cannot approve '${approvalId}'.`);
795
- }
796
- await this.#source.settle(approvalId, decision);
797
- }
798
- };
799
-
800
431
  // src/client/link.tsx
801
432
  import {
802
433
  Link as RouterLink
@@ -947,6 +578,7 @@ export {
947
578
  buildUseTheoQueryConfig,
948
579
  consumeChunkStream,
949
580
  consumeUIMessageStream,
581
+ createAgentClient,
950
582
  createAppClient,
951
583
  createBatcher,
952
584
  createGuestMessageHandler,