theokit 0.12.0 → 0.13.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 (131) hide show
  1. package/dist/{actions-virtual-module-SQDY3V5X.js → actions-virtual-module-3CDQTWOC.js} +6 -6
  2. package/dist/{actions-virtual-module-PNPRCEOS.js → actions-virtual-module-EIPXX4ZB.js} +3 -3
  3. package/dist/adapters/web-shim.d.ts +67 -0
  4. package/dist/adapters/ws-shim.d.ts +55 -0
  5. package/dist/agent-events-DosDXkSV.d.ts +94 -0
  6. package/dist/agents-typed-client-SAWAAH7K.js +142 -0
  7. package/dist/agents-typed-client-SAWAAH7K.js.map +1 -0
  8. package/dist/agents-typed-client-UTEQUA63.js +143 -0
  9. package/dist/agents-typed-client-UTEQUA63.js.map +1 -0
  10. package/dist/{app-typed-client-5GYEOYP3.js → app-typed-client-7PBFWZUE.js} +3 -3
  11. package/dist/{app-typed-client-QG7BVZYW.js → app-typed-client-CSOK7NPC.js} +6 -6
  12. package/dist/audit-log-BQWM5YLG.d.ts +60 -0
  13. package/dist/body-parser-web-FV5HWCY3.js +71 -0
  14. package/dist/body-parser-web-FV5HWCY3.js.map +1 -0
  15. package/dist/boot/index.d.ts +39 -0
  16. package/dist/{build-QFRLSEZ4.js → build-HXND27XG.js} +11 -11
  17. package/dist/{chunk-223EFY5X.js → chunk-2J7XU3PW.js} +68 -27
  18. package/dist/chunk-2J7XU3PW.js.map +1 -0
  19. package/dist/{chunk-RESN62GB.js → chunk-2KZQPDYR.js} +5 -48
  20. package/dist/chunk-2KZQPDYR.js.map +1 -0
  21. package/dist/chunk-3S3BNW5K.js +445 -0
  22. package/dist/chunk-3S3BNW5K.js.map +1 -0
  23. package/dist/{chunk-6FYD34NX.js → chunk-BQDGES7C.js} +28 -28
  24. package/dist/{chunk-6FYD34NX.js.map → chunk-BQDGES7C.js.map} +1 -1
  25. package/dist/chunk-EXP56GFQ.js +52 -0
  26. package/dist/chunk-EXP56GFQ.js.map +1 -0
  27. package/dist/chunk-F4YUPDJ2.js +115 -0
  28. package/dist/chunk-F4YUPDJ2.js.map +1 -0
  29. package/dist/{chunk-NAZ4E2GT.js → chunk-KXA37ONC.js} +2 -2
  30. package/dist/chunk-NHJMZCAS.js +32 -0
  31. package/dist/chunk-NHJMZCAS.js.map +1 -0
  32. package/dist/{chunk-43D6XNDR.js → chunk-O62MW4MT.js} +91 -18
  33. package/dist/chunk-O62MW4MT.js.map +1 -0
  34. package/dist/chunk-RSVN727G.js +1 -0
  35. package/dist/{chunk-7CBRKNQA.js → chunk-RYTZYFSD.js} +198 -6
  36. package/dist/chunk-RYTZYFSD.js.map +1 -0
  37. package/dist/chunk-UNLA45FY.js +235 -0
  38. package/dist/chunk-UNLA45FY.js.map +1 -0
  39. package/dist/{chunk-GFMQJHXX.js → chunk-WR4F4EEZ.js} +1082 -1074
  40. package/dist/chunk-WR4F4EEZ.js.map +1 -0
  41. package/dist/{chunk-AD74EAK3.js → chunk-ZSTZXR2D.js} +1 -30
  42. package/dist/chunk-ZSTZXR2D.js.map +1 -0
  43. package/dist/cli/index.js +5 -5
  44. package/dist/client/index.d.ts +418 -0
  45. package/dist/client/index.js +84 -3
  46. package/dist/client/index.js.map +1 -1
  47. package/dist/csrf-BBrEZSBW.d.ts +107 -0
  48. package/dist/csrf-readiness-store-CjIoub3U.d.ts +43 -0
  49. package/dist/define-websocket-CdK94O-D.d.ts +64 -0
  50. package/dist/{dev-GBXOTXUP.js → dev-OWW4XVIH.js} +10 -10
  51. package/dist/{dev-emit-FEFEDLZF.js → dev-emit-5MDSBP5D.js} +3 -3
  52. package/dist/{dev-emit-O4EGOSNV.js → dev-emit-QH2YGZXN.js} +2 -2
  53. package/dist/devtools/entry.d.ts +5 -0
  54. package/dist/error-envelope-BsNzzAV5.d.ts +62 -0
  55. package/dist/health-route-C0hk64_U.d.ts +57 -0
  56. package/dist/index-B40qUSrQ.d.ts +575 -0
  57. package/dist/index.d.ts +361 -0
  58. package/dist/index.js +6 -4
  59. package/dist/index.js.map +1 -1
  60. package/dist/internal-api-4YTJDITC.js +83 -0
  61. package/dist/internal-api-EFKZWIYZ.js +66 -0
  62. package/dist/internal-api-EFKZWIYZ.js.map +1 -0
  63. package/dist/job-backend-CgC8Xf33.d.ts +68 -0
  64. package/dist/match-CfbEFRG4.d.ts +26 -0
  65. package/dist/{openapi-VR6AFBLJ.js → openapi-FHY6HC6I.js} +7 -7
  66. package/dist/plugin-runner-BGBkzgi0.d.ts +95 -0
  67. package/dist/plugin-types-DNJGxr4Z.d.ts +79 -0
  68. package/dist/rate-limit-BdNDZ3vt.d.ts +58 -0
  69. package/dist/rate-limit-store-BEJnhWdw.d.ts +72 -0
  70. package/dist/react-query/index.d.ts +33 -0
  71. package/dist/{registry-Q2TZQLUH.js → registry-34LL7NF4.js} +1 -1
  72. package/dist/{routes-LRYOIIAI.js → routes-EW7TP7NJ.js} +2 -2
  73. package/dist/schema-BpH6ivDY.d.ts +74 -0
  74. package/dist/server/agent/index.d.ts +229 -0
  75. package/dist/server/agent/index.js +2 -1
  76. package/dist/server/auth/index.d.ts +419 -0
  77. package/dist/server/cost/index.d.ts +177 -0
  78. package/dist/server/cron/index.d.ts +208 -0
  79. package/dist/server/define/index.d.ts +313 -0
  80. package/dist/server/define/index.js +4 -2
  81. package/dist/server/http/index.d.ts +11 -0
  82. package/dist/server/index.d.ts +848 -0
  83. package/dist/server/index.js +9 -294
  84. package/dist/server/index.js.map +1 -1
  85. package/dist/server/jobs/index.d.ts +348 -0
  86. package/dist/server/observability/index.d.ts +324 -0
  87. package/dist/server/plugins/index.d.ts +17 -0
  88. package/dist/server/rate-limit/index.d.ts +105 -0
  89. package/dist/server/realtime/index.d.ts +15 -0
  90. package/dist/server/scan/index.d.ts +126 -0
  91. package/dist/server/scan/index.js +1 -1
  92. package/dist/server/security/index.d.ts +193 -0
  93. package/dist/server/storage/index.d.ts +22 -0
  94. package/dist/server/webhook/index.d.ts +148 -0
  95. package/dist/{start-3ZHAXSJE.js → start-KIQ5TTLR.js} +76 -13
  96. package/dist/start-KIQ5TTLR.js.map +1 -0
  97. package/dist/storage-manager-C4jsO0Tp.d.ts +89 -0
  98. package/dist/storage-types-DsDTCPbp.d.ts +96 -0
  99. package/dist/vite-plugin/index.d.ts +115 -0
  100. package/dist/vite-plugin/index.js +6 -4
  101. package/dist/{vite-plugin-WO72VLYR.js → vite-plugin-RK66K26Z.js} +7 -7
  102. package/dist/vite-plugin-RK66K26Z.js.map +1 -0
  103. package/package.json +4 -4
  104. package/dist/chunk-223EFY5X.js.map +0 -1
  105. package/dist/chunk-3LVRAGAZ.js +0 -73
  106. package/dist/chunk-3LVRAGAZ.js.map +0 -1
  107. package/dist/chunk-43D6XNDR.js.map +0 -1
  108. package/dist/chunk-7CBRKNQA.js.map +0 -1
  109. package/dist/chunk-AD74EAK3.js.map +0 -1
  110. package/dist/chunk-GFMQJHXX.js.map +0 -1
  111. package/dist/chunk-PBEH6NXR.js +0 -44
  112. package/dist/chunk-PBEH6NXR.js.map +0 -1
  113. package/dist/chunk-PIVX3DYW.js +0 -142
  114. package/dist/chunk-PIVX3DYW.js.map +0 -1
  115. package/dist/chunk-PPPR5DGR.js +0 -1
  116. package/dist/chunk-RESN62GB.js.map +0 -1
  117. package/dist/start-3ZHAXSJE.js.map +0 -1
  118. /package/dist/{actions-virtual-module-SQDY3V5X.js.map → actions-virtual-module-3CDQTWOC.js.map} +0 -0
  119. /package/dist/{actions-virtual-module-PNPRCEOS.js.map → actions-virtual-module-EIPXX4ZB.js.map} +0 -0
  120. /package/dist/{app-typed-client-5GYEOYP3.js.map → app-typed-client-7PBFWZUE.js.map} +0 -0
  121. /package/dist/{app-typed-client-QG7BVZYW.js.map → app-typed-client-CSOK7NPC.js.map} +0 -0
  122. /package/dist/{build-QFRLSEZ4.js.map → build-HXND27XG.js.map} +0 -0
  123. /package/dist/{chunk-NAZ4E2GT.js.map → chunk-KXA37ONC.js.map} +0 -0
  124. /package/dist/{chunk-PPPR5DGR.js.map → chunk-RSVN727G.js.map} +0 -0
  125. /package/dist/{dev-GBXOTXUP.js.map → dev-OWW4XVIH.js.map} +0 -0
  126. /package/dist/{dev-emit-FEFEDLZF.js.map → dev-emit-5MDSBP5D.js.map} +0 -0
  127. /package/dist/{dev-emit-O4EGOSNV.js.map → dev-emit-QH2YGZXN.js.map} +0 -0
  128. /package/dist/{vite-plugin-WO72VLYR.js.map → internal-api-4YTJDITC.js.map} +0 -0
  129. /package/dist/{openapi-VR6AFBLJ.js.map → openapi-FHY6HC6I.js.map} +0 -0
  130. /package/dist/{registry-Q2TZQLUH.js.map → registry-34LL7NF4.js.map} +0 -0
  131. /package/dist/{routes-LRYOIIAI.js.map → routes-EW7TP7NJ.js.map} +0 -0
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
- import "./chunk-NAZ4E2GT.js";
4
- import "./chunk-GFMQJHXX.js";
5
- import "./chunk-HGZL5EOI.js";
6
- import "./chunk-3LVRAGAZ.js";
3
+ import "./chunk-KXA37ONC.js";
4
+ import "./chunk-WR4F4EEZ.js";
5
+ import "./chunk-F4YUPDJ2.js";
7
6
  import {
8
7
  scanServerActionsEnriched
9
- } from "./chunk-6FYD34NX.js";
8
+ } from "./chunk-BQDGES7C.js";
9
+ import "./chunk-HGZL5EOI.js";
10
10
 
11
11
  // src/vite-plugin/actions-virtual-module.ts
12
12
  import { existsSync, mkdirSync, renameSync, watch as fsWatch, writeFileSync } from "fs";
@@ -209,4 +209,4 @@ export const actions = manifest
209
209
  export {
210
210
  actionsVirtualModule
211
211
  };
212
- //# sourceMappingURL=actions-virtual-module-SQDY3V5X.js.map
212
+ //# sourceMappingURL=actions-virtual-module-3CDQTWOC.js.map
@@ -1,4 +1,4 @@
1
- import "./chunk-PPPR5DGR.js";
1
+ import "./chunk-RSVN727G.js";
2
2
  import "./chunk-TGTNRUH3.js";
3
3
  import "./chunk-GY5Q27BJ.js";
4
4
  import "./chunk-5QW7IQQU.js";
@@ -8,7 +8,7 @@ import "./chunk-VMEWD57H.js";
8
8
  import "./chunk-JQSKBMXP.js";
9
9
  import {
10
10
  scanServerActionsEnriched
11
- } from "./chunk-223EFY5X.js";
11
+ } from "./chunk-2J7XU3PW.js";
12
12
  import "./chunk-WSJKACWB.js";
13
13
  import "./chunk-ZEGYW52B.js";
14
14
  import "./chunk-JBCHWRKF.js";
@@ -221,4 +221,4 @@ export const actions = manifest
221
221
  export {
222
222
  actionsVirtualModule
223
223
  };
224
- //# sourceMappingURL=actions-virtual-module-PNPRCEOS.js.map
224
+ //# sourceMappingURL=actions-virtual-module-EIPXX4ZB.js.map
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Web-to-Node bridge used by adapters whose runtimes provide a `Request`
3
+ * (Web Standard) but where TheoKit's `executeRoute` expects a Node-style
4
+ * IncomingMessage/ServerResponse pair.
5
+ *
6
+ * Used by adapters that target Node-compatible runtimes (Bun, Netlify
7
+ * Functions, AWS Lambda Node). Cloudflare uses an inline version of the same
8
+ * pattern — long-term it should consolidate here too.
9
+ *
10
+ * NOT used by Deno Deploy: Deno's stdlib does not have `Buffer`/`node:http`
11
+ * by default and forcing the shim there bloats the bundle. Deno wiring is
12
+ * tracked separately and will likely require executeRoute to accept Web
13
+ * Standard Request directly.
14
+ */
15
+ interface ShimRequest {
16
+ method: string;
17
+ url: string;
18
+ headers: Record<string, string>;
19
+ socket: {
20
+ remoteAddress: string;
21
+ };
22
+ on: (event: 'data' | 'end' | 'error', cb: (chunk?: unknown) => void) => unknown;
23
+ }
24
+ interface ShimResponse {
25
+ statusCode: number;
26
+ headersSent: boolean;
27
+ writableEnded: boolean;
28
+ writeHead: (status: number, headers?: Record<string, string>) => void;
29
+ setHeader: (key: string, value: string) => void;
30
+ getHeader: (key: string) => string | undefined;
31
+ write: (chunk: Uint8Array | string) => boolean;
32
+ end: (body?: Uint8Array | string) => void;
33
+ }
34
+ interface ShimContext {
35
+ req: ShimRequest;
36
+ res: ShimResponse;
37
+ /** Resolves to a Web Standard Response once `res.end()` is called. */
38
+ toResponse: () => Promise<Response>;
39
+ }
40
+ interface CreateWebShimOptions {
41
+ /**
42
+ * CR-018 fix: how to resolve the client IP from forwarded headers.
43
+ *
44
+ * - `'platform'` (default for `cf-connecting-ip`): trust runtime-injected
45
+ * headers only (`cf-connecting-ip` on Cloudflare, `x-real-ip` on
46
+ * Netlify/Vercel when the platform writes it). Ignores
47
+ * `x-forwarded-for` because clients can spoof it.
48
+ * - `'trusted-proxy'`: read the **rightmost** entry of `x-forwarded-for`.
49
+ * Only safe when the request literally went through a trusted proxy
50
+ * that strips client-set headers and appends the real client IP last.
51
+ * - `'none'`: skip all forwarded-header lookups and report
52
+ * `'0.0.0.0'`. Force this when the adapter has no reliable way to
53
+ * identify the client (rate-limiters then must use a different key).
54
+ *
55
+ * Default: `'platform'`.
56
+ */
57
+ trustedProxy?: 'platform' | 'trusted-proxy' | 'none';
58
+ }
59
+ /**
60
+ * Build Node-style req/res objects around a Web Standard Request.
61
+ * `toResponse()` returns a Promise that resolves when `res.end()` has been
62
+ * invoked, materializing a Web Standard Response with the accumulated body
63
+ * + headers + status.
64
+ */
65
+ declare function createWebShim(request: Request, options?: CreateWebShimOptions): ShimContext;
66
+
67
+ export { type CreateWebShimOptions, type ShimContext, type ShimRequest, type ShimResponse, createWebShim };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * T3.1 — WebSocket cross-runtime bridges.
3
+ *
4
+ * Exports 4 bridges (Node `ws` package, Bun.serve, Deno.upgradeWebSocket,
5
+ * Cloudflare WebSocketPair) that adapt each runtime's native WebSocket API
6
+ * to a common `WebSocketLike` interface that user handlers (`defineWebSocket`)
7
+ * can consume uniformly.
8
+ */
9
+ interface WebSocketLike {
10
+ send(data: string | Uint8Array | ArrayBuffer): void;
11
+ close(code?: number, reason?: string): void;
12
+ on(event: 'message' | 'close' | 'error', cb: (data?: unknown) => void): void;
13
+ }
14
+ interface WsHandler {
15
+ onOpen?: (ws: WebSocketLike) => void;
16
+ onMessage?: (ws: WebSocketLike, data: unknown) => void;
17
+ onClose?: (ws: WebSocketLike, code?: number, reason?: string) => void;
18
+ onError?: (ws: WebSocketLike, err: unknown) => void;
19
+ }
20
+ interface NodeWsLike {
21
+ on(event: string, cb: (arg?: unknown) => void): unknown;
22
+ send(data: unknown): void;
23
+ close(code?: number, reason?: string): void;
24
+ }
25
+ declare function createNodeWsBridge(handler: WsHandler): {
26
+ attach(nativeWs: NodeWsLike): WebSocketLike;
27
+ };
28
+ interface BunWsContext {
29
+ send(data: unknown): void;
30
+ close(code?: number, reason?: string): void;
31
+ }
32
+ interface BunWebSocketConfig {
33
+ open: (ws: BunWsContext) => void;
34
+ message: (ws: BunWsContext, message: unknown) => void;
35
+ close: (ws: BunWsContext, code?: number, reason?: string) => void;
36
+ }
37
+ declare function createBunWsBridge(handler: WsHandler): BunWebSocketConfig;
38
+ interface DenoLike {
39
+ upgradeWebSocket(req: Request): {
40
+ response: Response;
41
+ socket: {
42
+ send(data: unknown): void;
43
+ close(code?: number, reason?: string): void;
44
+ addEventListener(event: string, cb: (e: unknown) => void): void;
45
+ };
46
+ };
47
+ }
48
+ declare function createDenoWsBridge(handler: WsHandler, denoNs: DenoLike): {
49
+ handle(request: Request): Response;
50
+ };
51
+ declare function createCloudflareWsBridge(handler: WsHandler): {
52
+ handle(request: Request): Response;
53
+ };
54
+
55
+ export { type BunWebSocketConfig, type WebSocketLike, type WsHandler, createBunWsBridge, createCloudflareWsBridge, createDenoWsBridge, createNodeWsBridge };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * core/contracts/agent-events.ts
3
+ *
4
+ * Canonical home for the AgentEvent wire-format contract (T2.2 of
5
+ * architecture-cleanup plan; ADR-0001 v3 invariant #3 exception).
6
+ *
7
+ * Server emits via SSE; client consumes. Discriminated union by `type`.
8
+ * Both `server/agent/*` and `client/*` import from here.
9
+ *
10
+ * Per ADR-0001 v3: `cache → core/contracts`, `client → core/contracts`,
11
+ * `devtools → core/contracts` are LEGAL direct imports (this is the
12
+ * documented exception to the `no-cross-module-deep-import` rule).
13
+ */
14
+ /**
15
+ * Discriminated union for AgentRunError codes (Phase 1 — Production-Readiness #3).
16
+ *
17
+ * Mirrors `@theokit/sdk`'s `AgentRunErrorCode` without hard-importing the SDK
18
+ * type (D2 decoupling). EC-7 forward-compat: `(string & {})` fallback preserves
19
+ * autocompletion for the known codes while accepting future codes the SDK may
20
+ * introduce — autocomplete works AND TS doesn't reject unknown codes.
21
+ */
22
+ type AgentRunErrorCode = 'auth' | 'rate_limit' | 'quota_exceeded' | 'invalid_model' | 'invalid_request' | 'invalid_input' | 'context_too_large' | 'safety_blocked' | 'provider_unreachable' | 'tool_runtime_error' | 'aborted' | 'unknown' | (string & {});
23
+ interface AgentMessageEvent {
24
+ type: 'message';
25
+ content: string;
26
+ /** Optional id for client-side dedup / animation keys. */
27
+ id?: string;
28
+ }
29
+ interface AgentToolCallEvent {
30
+ type: 'tool_call';
31
+ name: string;
32
+ args: Record<string, unknown>;
33
+ id?: string;
34
+ }
35
+ interface AgentToolResultEvent {
36
+ type: 'tool_result';
37
+ name: string;
38
+ data: unknown;
39
+ id?: string;
40
+ }
41
+ /**
42
+ * Error event emitted via SSE.
43
+ *
44
+ * Phase 1 — Production-Readiness #3:
45
+ * New optional fields `code/provider/retriable/retryAfterMs` discriminate
46
+ * error classes for client-side handling (auth → sign-in CTA; rate_limit →
47
+ * countdown; quota_exceeded → upsell; etc.).
48
+ *
49
+ * Backward compat (D4): all new fields are optional. Existing clients that
50
+ * read only `event.message` keep working unchanged. New clients can safely
51
+ * `switch (event.code)` — `undefined` (legacy server) is a valid case.
52
+ *
53
+ * EC-15 (DOCUMENT): `message` is *trusted* to not contain secrets. SDK's
54
+ * `AgentRunError.message` is propagated verbatim. The SDK's `providerError`
55
+ * is NEVER serialized into this event — quarantined to prevent leakage.
56
+ */
57
+ interface AgentErrorEvent {
58
+ type: 'error';
59
+ message: string;
60
+ id?: string;
61
+ /** Discriminated error class — see AgentRunErrorCode. */
62
+ code?: AgentRunErrorCode;
63
+ /** Provider id (e.g., 'openai', 'anthropic', 'openrouter'). */
64
+ provider?: string;
65
+ /** Whether the SAME request can be retried as-is. */
66
+ retriable?: boolean;
67
+ /** Hint from provider's Retry-After header (milliseconds). Zero is valid (immediate retry). */
68
+ retryAfterMs?: number;
69
+ }
70
+ /**
71
+ * Extended thinking / reasoning event.
72
+ *
73
+ * Carries the model's reasoning text (when the model supports extended
74
+ * thinking). Mirrors the `@theokit/agents` stream-layer `ThinkingEvent`
75
+ * (`packages/agents/src/bridge/agent-stream-events.ts`) so the two layers
76
+ * agree on the wire form; defined here (not imported) to keep `core/contracts`
77
+ * free of a dependency on `@theokit/agents` (G1 dependency direction).
78
+ *
79
+ * Consumers that switch only on the other variants are unaffected (additive);
80
+ * a consumer that wants to surface reasoning opts in by handling `'thinking'`.
81
+ */
82
+ interface AgentThinkingEvent {
83
+ type: 'thinking';
84
+ content: string;
85
+ /** Optional id for client-side dedup / animation keys. */
86
+ id?: string;
87
+ }
88
+ /**
89
+ * Runtime AgentEvent — discriminated union of the 5 variants emitted by
90
+ * agent endpoints. Server produces; client consumes.
91
+ */
92
+ type AgentEvent = AgentMessageEvent | AgentToolCallEvent | AgentToolResultEvent | AgentErrorEvent | AgentThinkingEvent;
93
+
94
+ export type { AgentEvent as A, AgentErrorEvent as a, AgentMessageEvent as b, AgentThinkingEvent as c, AgentToolCallEvent as d, AgentToolResultEvent as e, AgentRunErrorCode as f };
@@ -0,0 +1,142 @@
1
+ import "./chunk-DGUM43GV.js";
2
+
3
+ // src/vite-plugin/agents-typed-client.ts
4
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
5
+ import { dirname, posix } from "path";
6
+ var FILE_HEADER = `// AUTO-GENERATED by theokit \u2014 do not edit.
7
+ // Source: theokit/packages/theo/src/vite-plugin/agents-typed-client.ts (M2).
8
+ // To refresh: \`pnpm dev\` or \`pnpm build\` regenerates this on every agents/ change.
9
+
10
+ /* eslint-disable */
11
+ `;
12
+ function aliasFor(name) {
13
+ return `_agent_${name.replace(/[^\w$]/g, "_")}`;
14
+ }
15
+ function importPath(dtsOutPath, projectRoot, filePath) {
16
+ const fromDir = dirname(dtsOutPath).replace(/\\/g, "/");
17
+ const abs = posix.join(projectRoot.replace(/\\/g, "/"), filePath.replace(/\\/g, "/"));
18
+ const noExt = abs.replace(/\.[jt]sx?$/, "");
19
+ let rel = posix.relative(fromDir, noExt);
20
+ if (!rel.startsWith(".")) rel = `./${rel}`;
21
+ return rel;
22
+ }
23
+ function generateAgentsDts({
24
+ manifest,
25
+ dtsOutPath,
26
+ projectRoot
27
+ }) {
28
+ const agents = manifest.agents ?? [];
29
+ const imports = [];
30
+ const entries = [];
31
+ for (const agent of agents) {
32
+ const alias = aliasFor(agent.name);
33
+ imports.push(
34
+ ` import type ${alias} from '${importPath(dtsOutPath, projectRoot, agent.filePath)}'`
35
+ );
36
+ entries.push(` '${agent.name}': { input: InferAgentInput<${alias}> }`);
37
+ }
38
+ const body = entries.length > 0 ? `{
39
+ ${entries.join("\n")}
40
+ }` : `{
41
+ // No agents detected \u2014 add \`agents/*.ts\` to populate this binding.
42
+ }`;
43
+ const importBlock = imports.length > 0 ? `${imports.join("\n")}
44
+ ` : "";
45
+ return `${FILE_HEADER}
46
+ declare module '@theo/agents' {
47
+ import type { InferAgentInput } from '@theokit/agents'
48
+ import type { UseAgentReturn } from 'theokit/client'
49
+ ${importBlock}
50
+ export interface AppAgents ${body}
51
+
52
+ export function useAgent<K extends keyof AppAgents>(
53
+ name: K,
54
+ ): UseAgentReturn<AppAgents[K]['input']>
55
+ }
56
+ `;
57
+ }
58
+ var VIRTUAL_AGENTS_ID = "@theo/agents";
59
+ var RESOLVED_AGENTS_ID = "\0@theo/agents";
60
+ function writeIfChanged(filePath, content) {
61
+ if (existsSync(filePath)) {
62
+ try {
63
+ if (readFileSync(filePath, "utf-8") === content) return;
64
+ } catch {
65
+ }
66
+ }
67
+ mkdirSync(dirname(filePath), { recursive: true });
68
+ const tmp = `${filePath}.${process.pid}.tmp`;
69
+ writeFileSync(tmp, content);
70
+ renameSync(tmp, filePath);
71
+ }
72
+ function emitAgentsDts(opts) {
73
+ const dtsOutPath = posix.join(opts.distDir.replace(/\\/g, "/"), "agents.d.ts");
74
+ const content = generateAgentsDts({
75
+ manifest: opts.scanManifest(opts.projectRoot),
76
+ dtsOutPath,
77
+ projectRoot: opts.projectRoot
78
+ });
79
+ writeIfChanged(dtsOutPath, content);
80
+ return dtsOutPath;
81
+ }
82
+ function agentsTypedClientPlugin(opts) {
83
+ let debounce;
84
+ let viteServer;
85
+ const scheduleEmit = () => {
86
+ if (debounce) clearTimeout(debounce);
87
+ debounce = setTimeout(() => {
88
+ try {
89
+ emitAgentsDts(opts);
90
+ if (viteServer) {
91
+ const mod = viteServer.moduleGraph.getModuleById(RESOLVED_AGENTS_ID);
92
+ if (mod) viteServer.moduleGraph.invalidateModule(mod);
93
+ }
94
+ } catch (err) {
95
+ console.error("[theokit:agents-typed-client] codegen error:", err);
96
+ }
97
+ }, 100);
98
+ };
99
+ return {
100
+ name: "theokit:agents-typed-client",
101
+ enforce: "post",
102
+ configResolved() {
103
+ try {
104
+ emitAgentsDts(opts);
105
+ } catch (err) {
106
+ console.error("[theokit:agents-typed-client] initial codegen error:", err);
107
+ }
108
+ },
109
+ buildEnd() {
110
+ try {
111
+ emitAgentsDts(opts);
112
+ } catch (err) {
113
+ console.error("[theokit:agents-typed-client] buildEnd codegen error:", err);
114
+ }
115
+ },
116
+ configureServer(server) {
117
+ viteServer = server;
118
+ const agentsGlob = posix.join(opts.projectRoot.replace(/\\/g, "/"), "agents");
119
+ const onFile = (file) => {
120
+ if (file.replace(/\\/g, "/").startsWith(agentsGlob)) scheduleEmit();
121
+ };
122
+ server.watcher.on("add", onFile);
123
+ server.watcher.on("change", onFile);
124
+ server.watcher.on("unlink", onFile);
125
+ },
126
+ resolveId(id) {
127
+ return id === VIRTUAL_AGENTS_ID ? RESOLVED_AGENTS_ID : null;
128
+ },
129
+ load(id) {
130
+ if (id === RESOLVED_AGENTS_ID) {
131
+ return `export { useAgent } from 'theokit/client'
132
+ `;
133
+ }
134
+ return null;
135
+ }
136
+ };
137
+ }
138
+ export {
139
+ agentsTypedClientPlugin,
140
+ generateAgentsDts
141
+ };
142
+ //# sourceMappingURL=agents-typed-client-SAWAAH7K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vite-plugin/agents-typed-client.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Codegen-time fs ops: all paths derive from `opts.projectRoot` / `opts.distDir`\n * (vite plugin opts — trusted, set by the framework's CLI). Never serves HTTP input.\n */\n/**\n * M2 (theokit-ai-first) — end-to-end typed binding for the `agents/*.ts` convention.\n *\n * Sibling of `app-typed-client.ts` (kept separate so the `@theo/client` output stays\n * byte-unchanged). Two parts:\n *\n * 1. `generateAgentsDts({ manifest, dtsOutPath, projectRoot })` — pure function emitting\n * `.theokit/agents.d.ts` (the virtual `@theo/agents` module) with `AppAgents` mapping\n * each scanned agent to `InferAgentInput` of its `defineAgent({ input })` schema, plus a\n * typed `useAgent` signature — so the client binds to `/api/agents/<name>` with the right\n * request type and ZERO manual wiring (DoD line 2).\n * 2. `agentsTypedClientPlugin(opts)` — Vite plugin that emits (1), rewrites on `agents/*`\n * changes, and serves the virtual `@theo/agents` runtime (`useAgent` from `theokit/client`).\n */\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, posix } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport type { TheoManifest } from '../server/internal-api.js'\n\nconst FILE_HEADER = `// AUTO-GENERATED by theokit — do not edit.\n// Source: theokit/packages/theo/src/vite-plugin/agents-typed-client.ts (M2).\n// To refresh: \\`pnpm dev\\` or \\`pnpm build\\` regenerates this on every agents/ change.\n\n/* eslint-disable */\n`\n\n/** A safe TS identifier alias for an agent (name may contain path separators). */\nfunction aliasFor(name: string): string {\n return `_agent_${name.replace(/[^\\w$]/g, '_')}`\n}\n\n/** Relative `import type` path from the .d.ts dir to the agent source (extension stripped). */\nfunction importPath(dtsOutPath: string, projectRoot: string, filePath: string): string {\n const fromDir = dirname(dtsOutPath).replace(/\\\\/g, '/')\n const abs = posix.join(projectRoot.replace(/\\\\/g, '/'), filePath.replace(/\\\\/g, '/'))\n const noExt = abs.replace(/\\.[jt]sx?$/, '')\n let rel = posix.relative(fromDir, noExt)\n if (!rel.startsWith('.')) rel = `./${rel}`\n return rel\n}\n\nexport interface GenerateAgentsDtsOptions {\n manifest: TheoManifest\n /** Absolute path to the .d.ts that will be emitted (drives the import paths). */\n dtsOutPath: string\n /** Absolute project root — agents live at `<projectRoot>/agents`. */\n projectRoot: string\n}\n\nexport function generateAgentsDts({\n manifest,\n dtsOutPath,\n projectRoot,\n}: GenerateAgentsDtsOptions): string {\n const agents = manifest.agents ?? []\n const imports: string[] = []\n const entries: string[] = []\n for (const agent of agents) {\n const alias = aliasFor(agent.name)\n imports.push(\n ` import type ${alias} from '${importPath(dtsOutPath, projectRoot, agent.filePath)}'`,\n )\n entries.push(` '${agent.name}': { input: InferAgentInput<${alias}> }`)\n }\n\n const body =\n entries.length > 0\n ? `{\\n${entries.join('\\n')}\\n }`\n : `{\\n // No agents detected — add \\`agents/*.ts\\` to populate this binding.\\n }`\n\n const importBlock = imports.length > 0 ? `${imports.join('\\n')}\\n` : ''\n\n return `${FILE_HEADER}\ndeclare module '@theo/agents' {\n import type { InferAgentInput } from '@theokit/agents'\n import type { UseAgentReturn } from 'theokit/client'\n${importBlock}\n export interface AppAgents ${body}\n\n export function useAgent<K extends keyof AppAgents>(\n name: K,\n ): UseAgentReturn<AppAgents[K]['input']>\n}\n`\n}\n\n// ─── Vite plugin ─────────────────────────────────────────────────────────────\n\nconst VIRTUAL_AGENTS_ID = '@theo/agents'\nconst RESOLVED_AGENTS_ID = '\\0@theo/agents'\n\nexport interface AgentsTypedClientPluginOptions {\n /** Absolute project root (agents live at `<projectRoot>/agents`). */\n projectRoot: string\n /** Absolute `.theokit/` output dir (where `agents.d.ts` lands). */\n distDir: string\n /** Injects the scanned agents; returns the current manifest-shaped agent list. */\n scanManifest: (projectRoot: string) => TheoManifest\n}\n\n/** Atomic write via tmp + rename; skips when content is unchanged. */\nfunction writeIfChanged(filePath: string, content: string): void {\n if (existsSync(filePath)) {\n try {\n if (readFileSync(filePath, 'utf-8') === content) return\n } catch {\n /* fall through to write */\n }\n }\n mkdirSync(dirname(filePath), { recursive: true })\n const tmp = `${filePath}.${process.pid}.tmp`\n writeFileSync(tmp, content)\n renameSync(tmp, filePath)\n}\n\nfunction emitAgentsDts(opts: AgentsTypedClientPluginOptions): string {\n const dtsOutPath = posix.join(opts.distDir.replace(/\\\\/g, '/'), 'agents.d.ts')\n const content = generateAgentsDts({\n manifest: opts.scanManifest(opts.projectRoot),\n dtsOutPath,\n projectRoot: opts.projectRoot,\n })\n writeIfChanged(dtsOutPath, content)\n return dtsOutPath\n}\n\nexport function agentsTypedClientPlugin(opts: AgentsTypedClientPluginOptions): Plugin {\n let debounce: NodeJS.Timeout | undefined\n let viteServer: ViteDevServer | undefined\n\n const scheduleEmit = (): void => {\n if (debounce) clearTimeout(debounce)\n debounce = setTimeout(() => {\n try {\n emitAgentsDts(opts)\n if (viteServer) {\n const mod = viteServer.moduleGraph.getModuleById(RESOLVED_AGENTS_ID)\n if (mod) viteServer.moduleGraph.invalidateModule(mod)\n }\n } catch (err) {\n console.error('[theokit:agents-typed-client] codegen error:', err)\n }\n }, 100)\n }\n\n return {\n name: 'theokit:agents-typed-client',\n enforce: 'post',\n configResolved() {\n try {\n emitAgentsDts(opts)\n } catch (err) {\n console.error('[theokit:agents-typed-client] initial codegen error:', err)\n }\n },\n buildEnd() {\n try {\n emitAgentsDts(opts)\n } catch (err) {\n console.error('[theokit:agents-typed-client] buildEnd codegen error:', err)\n }\n },\n configureServer(server) {\n viteServer = server\n const agentsGlob = posix.join(opts.projectRoot.replace(/\\\\/g, '/'), 'agents')\n const onFile = (file: string): void => {\n if (file.replace(/\\\\/g, '/').startsWith(agentsGlob)) scheduleEmit()\n }\n server.watcher.on('add', onFile)\n server.watcher.on('change', onFile)\n server.watcher.on('unlink', onFile)\n },\n resolveId(id) {\n return id === VIRTUAL_AGENTS_ID ? RESOLVED_AGENTS_ID : null\n },\n load(id) {\n if (id === RESOLVED_AGENTS_ID) {\n return `export { useAgent } from 'theokit/client'\\n`\n }\n return null\n },\n }\n}\n"],"mappings":";;;AAkBA,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,SAAS,aAAa;AAM/B,IAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAQpB,SAAS,SAAS,MAAsB;AACtC,SAAO,UAAU,KAAK,QAAQ,WAAW,GAAG,CAAC;AAC/C;AAGA,SAAS,WAAW,YAAoB,aAAqB,UAA0B;AACrF,QAAM,UAAU,QAAQ,UAAU,EAAE,QAAQ,OAAO,GAAG;AACtD,QAAM,MAAM,MAAM,KAAK,YAAY,QAAQ,OAAO,GAAG,GAAG,SAAS,QAAQ,OAAO,GAAG,CAAC;AACpF,QAAM,QAAQ,IAAI,QAAQ,cAAc,EAAE;AAC1C,MAAI,MAAM,MAAM,SAAS,SAAS,KAAK;AACvC,MAAI,CAAC,IAAI,WAAW,GAAG,EAAG,OAAM,KAAK,GAAG;AACxC,SAAO;AACT;AAUO,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AACF,GAAqC;AACnC,QAAM,SAAS,SAAS,UAAU,CAAC;AACnC,QAAM,UAAoB,CAAC;AAC3B,QAAM,UAAoB,CAAC;AAC3B,aAAW,SAAS,QAAQ;AAC1B,UAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,YAAQ;AAAA,MACN,iBAAiB,KAAK,UAAU,WAAW,YAAY,aAAa,MAAM,QAAQ,CAAC;AAAA,IACrF;AACA,YAAQ,KAAK,QAAQ,MAAM,IAA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iB,GAAG;AAAA,QACtD;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,MAAM,gDAAgD,GAAG;AAAA,MACnE;AAAA,IACF,GAAG,GAAG;AAAA,EACR;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,iBAAiB;AACf,UAAI;AACF,sBAAc,IAAI;AAAA,MACpB,SAAS,KAAK;AACZ,gBAAQ,MAAM,wDAAwD,GAAG;AAAA,MAC3E;AAAA,IACF;AAAA,IACA,WAAW;AACT,UAAI;AACF,sBAAc,IAAI;AAAA,MACpB,SAAS,KAAK;AACZ,gBAAQ,MAAM,yDAAyD,GAAG;AAAA,MAC5E;AAAA,IACF;AAAA,IACA,gBAAgB,QAAQ;AACtB,mBAAa;AACb,YAAM,aAAa,MAAM,KAAK,KAAK,YAAY,QAAQ,OAAO,GAAG,GAAG,QAAQ;AAC5E,YAAM,SAAS,CAAC,SAAuB;AACrC,YAAI,KAAK,QAAQ,OAAO,GAAG,EAAE,WAAW,UAAU,EAAG,cAAa;AAAA,MACpE;AACA,aAAO,QAAQ,GAAG,OAAO,MAAM;AAC/B,aAAO,QAAQ,GAAG,UAAU,MAAM;AAClC,aAAO,QAAQ,GAAG,UAAU,MAAM;AAAA,IACpC;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,oBAAoB,qBAAqB;AAAA,IACzD;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,oBAAoB;AAC7B,eAAO;AAAA;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ import "tsx/esm";
3
+
4
+ // src/vite-plugin/agents-typed-client.ts
5
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
6
+ import { dirname, posix } from "path";
7
+ var FILE_HEADER = `// AUTO-GENERATED by theokit \u2014 do not edit.
8
+ // Source: theokit/packages/theo/src/vite-plugin/agents-typed-client.ts (M2).
9
+ // To refresh: \`pnpm dev\` or \`pnpm build\` regenerates this on every agents/ change.
10
+
11
+ /* eslint-disable */
12
+ `;
13
+ function aliasFor(name) {
14
+ return `_agent_${name.replace(/[^\w$]/g, "_")}`;
15
+ }
16
+ function importPath(dtsOutPath, projectRoot, filePath) {
17
+ const fromDir = dirname(dtsOutPath).replace(/\\/g, "/");
18
+ const abs = posix.join(projectRoot.replace(/\\/g, "/"), filePath.replace(/\\/g, "/"));
19
+ const noExt = abs.replace(/\.[jt]sx?$/, "");
20
+ let rel = posix.relative(fromDir, noExt);
21
+ if (!rel.startsWith(".")) rel = `./${rel}`;
22
+ return rel;
23
+ }
24
+ function generateAgentsDts({
25
+ manifest,
26
+ dtsOutPath,
27
+ projectRoot
28
+ }) {
29
+ const agents = manifest.agents ?? [];
30
+ const imports = [];
31
+ const entries = [];
32
+ for (const agent of agents) {
33
+ const alias = aliasFor(agent.name);
34
+ imports.push(
35
+ ` import type ${alias} from '${importPath(dtsOutPath, projectRoot, agent.filePath)}'`
36
+ );
37
+ entries.push(` '${agent.name}': { input: InferAgentInput<${alias}> }`);
38
+ }
39
+ const body = entries.length > 0 ? `{
40
+ ${entries.join("\n")}
41
+ }` : `{
42
+ // No agents detected \u2014 add \`agents/*.ts\` to populate this binding.
43
+ }`;
44
+ const importBlock = imports.length > 0 ? `${imports.join("\n")}
45
+ ` : "";
46
+ return `${FILE_HEADER}
47
+ declare module '@theo/agents' {
48
+ import type { InferAgentInput } from '@theokit/agents'
49
+ import type { UseAgentReturn } from 'theokit/client'
50
+ ${importBlock}
51
+ export interface AppAgents ${body}
52
+
53
+ export function useAgent<K extends keyof AppAgents>(
54
+ name: K,
55
+ ): UseAgentReturn<AppAgents[K]['input']>
56
+ }
57
+ `;
58
+ }
59
+ var VIRTUAL_AGENTS_ID = "@theo/agents";
60
+ var RESOLVED_AGENTS_ID = "\0@theo/agents";
61
+ function writeIfChanged(filePath, content) {
62
+ if (existsSync(filePath)) {
63
+ try {
64
+ if (readFileSync(filePath, "utf-8") === content) return;
65
+ } catch {
66
+ }
67
+ }
68
+ mkdirSync(dirname(filePath), { recursive: true });
69
+ const tmp = `${filePath}.${process.pid}.tmp`;
70
+ writeFileSync(tmp, content);
71
+ renameSync(tmp, filePath);
72
+ }
73
+ function emitAgentsDts(opts) {
74
+ const dtsOutPath = posix.join(opts.distDir.replace(/\\/g, "/"), "agents.d.ts");
75
+ const content = generateAgentsDts({
76
+ manifest: opts.scanManifest(opts.projectRoot),
77
+ dtsOutPath,
78
+ projectRoot: opts.projectRoot
79
+ });
80
+ writeIfChanged(dtsOutPath, content);
81
+ return dtsOutPath;
82
+ }
83
+ function agentsTypedClientPlugin(opts) {
84
+ let debounce;
85
+ let viteServer;
86
+ const scheduleEmit = () => {
87
+ if (debounce) clearTimeout(debounce);
88
+ debounce = setTimeout(() => {
89
+ try {
90
+ emitAgentsDts(opts);
91
+ if (viteServer) {
92
+ const mod = viteServer.moduleGraph.getModuleById(RESOLVED_AGENTS_ID);
93
+ if (mod) viteServer.moduleGraph.invalidateModule(mod);
94
+ }
95
+ } catch (err) {
96
+ console.error("[theokit:agents-typed-client] codegen error:", err);
97
+ }
98
+ }, 100);
99
+ };
100
+ return {
101
+ name: "theokit:agents-typed-client",
102
+ enforce: "post",
103
+ configResolved() {
104
+ try {
105
+ emitAgentsDts(opts);
106
+ } catch (err) {
107
+ console.error("[theokit:agents-typed-client] initial codegen error:", err);
108
+ }
109
+ },
110
+ buildEnd() {
111
+ try {
112
+ emitAgentsDts(opts);
113
+ } catch (err) {
114
+ console.error("[theokit:agents-typed-client] buildEnd codegen error:", err);
115
+ }
116
+ },
117
+ configureServer(server) {
118
+ viteServer = server;
119
+ const agentsGlob = posix.join(opts.projectRoot.replace(/\\/g, "/"), "agents");
120
+ const onFile = (file) => {
121
+ if (file.replace(/\\/g, "/").startsWith(agentsGlob)) scheduleEmit();
122
+ };
123
+ server.watcher.on("add", onFile);
124
+ server.watcher.on("change", onFile);
125
+ server.watcher.on("unlink", onFile);
126
+ },
127
+ resolveId(id) {
128
+ return id === VIRTUAL_AGENTS_ID ? RESOLVED_AGENTS_ID : null;
129
+ },
130
+ load(id) {
131
+ if (id === RESOLVED_AGENTS_ID) {
132
+ return `export { useAgent } from 'theokit/client'
133
+ `;
134
+ }
135
+ return null;
136
+ }
137
+ };
138
+ }
139
+ export {
140
+ agentsTypedClientPlugin,
141
+ generateAgentsDts
142
+ };
143
+ //# sourceMappingURL=agents-typed-client-UTEQUA63.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vite-plugin/agents-typed-client.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Codegen-time fs ops: all paths derive from `opts.projectRoot` / `opts.distDir`\n * (vite plugin opts — trusted, set by the framework's CLI). Never serves HTTP input.\n */\n/**\n * M2 (theokit-ai-first) — end-to-end typed binding for the `agents/*.ts` convention.\n *\n * Sibling of `app-typed-client.ts` (kept separate so the `@theo/client` output stays\n * byte-unchanged). Two parts:\n *\n * 1. `generateAgentsDts({ manifest, dtsOutPath, projectRoot })` — pure function emitting\n * `.theokit/agents.d.ts` (the virtual `@theo/agents` module) with `AppAgents` mapping\n * each scanned agent to `InferAgentInput` of its `defineAgent({ input })` schema, plus a\n * typed `useAgent` signature — so the client binds to `/api/agents/<name>` with the right\n * request type and ZERO manual wiring (DoD line 2).\n * 2. `agentsTypedClientPlugin(opts)` — Vite plugin that emits (1), rewrites on `agents/*`\n * changes, and serves the virtual `@theo/agents` runtime (`useAgent` from `theokit/client`).\n */\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, posix } from 'node:path'\n\nimport type { Plugin, ViteDevServer } from 'vite'\n\nimport type { TheoManifest } from '../server/internal-api.js'\n\nconst FILE_HEADER = `// AUTO-GENERATED by theokit — do not edit.\n// Source: theokit/packages/theo/src/vite-plugin/agents-typed-client.ts (M2).\n// To refresh: \\`pnpm dev\\` or \\`pnpm build\\` regenerates this on every agents/ change.\n\n/* eslint-disable */\n`\n\n/** A safe TS identifier alias for an agent (name may contain path separators). */\nfunction aliasFor(name: string): string {\n return `_agent_${name.replace(/[^\\w$]/g, '_')}`\n}\n\n/** Relative `import type` path from the .d.ts dir to the agent source (extension stripped). */\nfunction importPath(dtsOutPath: string, projectRoot: string, filePath: string): string {\n const fromDir = dirname(dtsOutPath).replace(/\\\\/g, '/')\n const abs = posix.join(projectRoot.replace(/\\\\/g, '/'), filePath.replace(/\\\\/g, '/'))\n const noExt = abs.replace(/\\.[jt]sx?$/, '')\n let rel = posix.relative(fromDir, noExt)\n if (!rel.startsWith('.')) rel = `./${rel}`\n return rel\n}\n\nexport interface GenerateAgentsDtsOptions {\n manifest: TheoManifest\n /** Absolute path to the .d.ts that will be emitted (drives the import paths). */\n dtsOutPath: string\n /** Absolute project root — agents live at `<projectRoot>/agents`. */\n projectRoot: string\n}\n\nexport function generateAgentsDts({\n manifest,\n dtsOutPath,\n projectRoot,\n}: GenerateAgentsDtsOptions): string {\n const agents = manifest.agents ?? []\n const imports: string[] = []\n const entries: string[] = []\n for (const agent of agents) {\n const alias = aliasFor(agent.name)\n imports.push(\n ` import type ${alias} from '${importPath(dtsOutPath, projectRoot, agent.filePath)}'`,\n )\n entries.push(` '${agent.name}': { input: InferAgentInput<${alias}> }`)\n }\n\n const body =\n entries.length > 0\n ? `{\\n${entries.join('\\n')}\\n }`\n : `{\\n // No agents detected — add \\`agents/*.ts\\` to populate this binding.\\n }`\n\n const importBlock = imports.length > 0 ? `${imports.join('\\n')}\\n` : ''\n\n return `${FILE_HEADER}\ndeclare module '@theo/agents' {\n import type { InferAgentInput } from '@theokit/agents'\n import type { UseAgentReturn } from 'theokit/client'\n${importBlock}\n export interface AppAgents ${body}\n\n export function useAgent<K extends keyof AppAgents>(\n name: K,\n ): UseAgentReturn<AppAgents[K]['input']>\n}\n`\n}\n\n// ─── Vite plugin ─────────────────────────────────────────────────────────────\n\nconst VIRTUAL_AGENTS_ID = '@theo/agents'\nconst RESOLVED_AGENTS_ID = '\\0@theo/agents'\n\nexport interface AgentsTypedClientPluginOptions {\n /** Absolute project root (agents live at `<projectRoot>/agents`). */\n projectRoot: string\n /** Absolute `.theokit/` output dir (where `agents.d.ts` lands). */\n distDir: string\n /** Injects the scanned agents; returns the current manifest-shaped agent list. */\n scanManifest: (projectRoot: string) => TheoManifest\n}\n\n/** Atomic write via tmp + rename; skips when content is unchanged. */\nfunction writeIfChanged(filePath: string, content: string): void {\n if (existsSync(filePath)) {\n try {\n if (readFileSync(filePath, 'utf-8') === content) return\n } catch {\n /* fall through to write */\n }\n }\n mkdirSync(dirname(filePath), { recursive: true })\n const tmp = `${filePath}.${process.pid}.tmp`\n writeFileSync(tmp, content)\n renameSync(tmp, filePath)\n}\n\nfunction emitAgentsDts(opts: AgentsTypedClientPluginOptions): string {\n const dtsOutPath = posix.join(opts.distDir.replace(/\\\\/g, '/'), 'agents.d.ts')\n const content = generateAgentsDts({\n manifest: opts.scanManifest(opts.projectRoot),\n dtsOutPath,\n projectRoot: opts.projectRoot,\n })\n writeIfChanged(dtsOutPath, content)\n return dtsOutPath\n}\n\nexport function agentsTypedClientPlugin(opts: AgentsTypedClientPluginOptions): Plugin {\n let debounce: NodeJS.Timeout | undefined\n let viteServer: ViteDevServer | undefined\n\n const scheduleEmit = (): void => {\n if (debounce) clearTimeout(debounce)\n debounce = setTimeout(() => {\n try {\n emitAgentsDts(opts)\n if (viteServer) {\n const mod = viteServer.moduleGraph.getModuleById(RESOLVED_AGENTS_ID)\n if (mod) viteServer.moduleGraph.invalidateModule(mod)\n }\n } catch (err) {\n console.error('[theokit:agents-typed-client] codegen error:', err)\n }\n }, 100)\n }\n\n return {\n name: 'theokit:agents-typed-client',\n enforce: 'post',\n configResolved() {\n try {\n emitAgentsDts(opts)\n } catch (err) {\n console.error('[theokit:agents-typed-client] initial codegen error:', err)\n }\n },\n buildEnd() {\n try {\n emitAgentsDts(opts)\n } catch (err) {\n console.error('[theokit:agents-typed-client] buildEnd codegen error:', err)\n }\n },\n configureServer(server) {\n viteServer = server\n const agentsGlob = posix.join(opts.projectRoot.replace(/\\\\/g, '/'), 'agents')\n const onFile = (file: string): void => {\n if (file.replace(/\\\\/g, '/').startsWith(agentsGlob)) scheduleEmit()\n }\n server.watcher.on('add', onFile)\n server.watcher.on('change', onFile)\n server.watcher.on('unlink', onFile)\n },\n resolveId(id) {\n return id === VIRTUAL_AGENTS_ID ? RESOLVED_AGENTS_ID : null\n },\n load(id) {\n if (id === RESOLVED_AGENTS_ID) {\n return `export { useAgent } from 'theokit/client'\\n`\n }\n return null\n },\n }\n}\n"],"mappings":";;;;AAkBA,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,SAAS,aAAa;AAM/B,IAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAQpB,SAAS,SAAS,MAAsB;AACtC,SAAO,UAAU,KAAK,QAAQ,WAAW,GAAG,CAAC;AAC/C;AAGA,SAAS,WAAW,YAAoB,aAAqB,UAA0B;AACrF,QAAM,UAAU,QAAQ,UAAU,EAAE,QAAQ,OAAO,GAAG;AACtD,QAAM,MAAM,MAAM,KAAK,YAAY,QAAQ,OAAO,GAAG,GAAG,SAAS,QAAQ,OAAO,GAAG,CAAC;AACpF,QAAM,QAAQ,IAAI,QAAQ,cAAc,EAAE;AAC1C,MAAI,MAAM,MAAM,SAAS,SAAS,KAAK;AACvC,MAAI,CAAC,IAAI,WAAW,GAAG,EAAG,OAAM,KAAK,GAAG;AACxC,SAAO;AACT;AAUO,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AACF,GAAqC;AACnC,QAAM,SAAS,SAAS,UAAU,CAAC;AACnC,QAAM,UAAoB,CAAC;AAC3B,QAAM,UAAoB,CAAC;AAC3B,aAAW,SAAS,QAAQ;AAC1B,UAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,YAAQ;AAAA,MACN,iBAAiB,KAAK,UAAU,WAAW,YAAY,aAAa,M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H.js";
8
8
  import "./chunk-JQSKBMXP.js";
9
9
  import {
10
10
  generateManifest
11
- } from "./chunk-223EFY5X.js";
11
+ } from "./chunk-2J7XU3PW.js";
12
12
  import {
13
13
  HTTP_METHODS
14
14
  } from "./chunk-WSJKACWB.js";
@@ -296,4 +296,4 @@ export {
296
296
  emitClientDts,
297
297
  generateClientDts
298
298
  };
299
- //# sourceMappingURL=app-typed-client-5GYEOYP3.js.map
299
+ //# sourceMappingURL=app-typed-client-7PBFWZUE.js.map
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
- import "./chunk-NAZ4E2GT.js";
4
- import "./chunk-GFMQJHXX.js";
5
- import "./chunk-HGZL5EOI.js";
3
+ import "./chunk-KXA37ONC.js";
4
+ import "./chunk-WR4F4EEZ.js";
6
5
  import {
7
6
  generateManifest
8
- } from "./chunk-3LVRAGAZ.js";
7
+ } from "./chunk-F4YUPDJ2.js";
9
8
  import {
10
9
  HTTP_METHODS
11
- } from "./chunk-6FYD34NX.js";
10
+ } from "./chunk-BQDGES7C.js";
11
+ import "./chunk-HGZL5EOI.js";
12
12
 
13
13
  // src/vite-plugin/app-typed-client.ts
14
14
  import { mkdirSync, readFileSync, renameSync, writeFileSync, existsSync } from "fs";
@@ -284,4 +284,4 @@ export {
284
284
  emitClientDts,
285
285
  generateClientDts
286
286
  };
287
- //# sourceMappingURL=app-typed-client-QG7BVZYW.js.map
287
+ //# sourceMappingURL=app-typed-client-CSOK7NPC.js.map