@usecontextlayer/sdk 0.15.0 → 0.16.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 803 Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,27 +1,25 @@
1
1
  # @usecontextlayer/sdk
2
2
 
3
- ContextLayer integration for React Router apps: the shared document Layout, Tools and Databases capabilities. Local tool calls use the signed-in developer's personal accounts and current-folder connection bindings. Hosted calls use pushed requirements and platform-stored viewer/app-Owner assignments.
3
+ ContextLayer integration for slates: the app's shared document Layout, a Worker serving app routes and MCP tools, and Tools and Databases capabilities. The [domain model](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#domain-model) defines slates, declarations, resources, Owners, and assignments.
4
4
 
5
- Use Node.js 24 or newer, pnpm, and Git with configured author identity. Start with login, then create and run your app:
5
+ Use Node.js 24 or newer, pnpm, and Git with configured author identity. Start with login, then create and run your slate:
6
6
 
7
7
  ```sh
8
8
  npx @usecontextlayer/cli login
9
- npx @usecontextlayer/cli init my-app
10
- cd my-app
9
+ npx @usecontextlayer/cli init my-slate
10
+ cd my-slate
11
11
  pnpm dev
12
12
  ```
13
13
 
14
- The CLI installs this package and configures a development-only Cloudflare Worker and native service binding. Open the local URL printed by the development server. Initialization prints your dashboard link, hosted URL, and Git publication steps; the hosted URL becomes usable after deployment succeeds. Use `npx @usecontextlayer/cli` for subsequent CLI commands. First-party `@usecontextlayer/*` packages are exempt from pnpm's release-age policy in generated projects.
14
+ The CLI installs this package and configures local development. Open the local URL printed by the development server. Initialization prints your dashboard link, hosted URL, and Git deployment steps; the hosted URL becomes usable after deployment succeeds. Use `npx @usecontextlayer/cli` for subsequent CLI commands. First-party `@usecontextlayer/*` packages are exempt from pnpm's release-age policy in generated checkouts.
15
15
 
16
16
  ## Local login and assignment
17
17
 
18
- Declare resources in `public/slate.json` and `agents/<name>/slate.json`, using the same Slate schema and shared resource names. Local commands read only the current app folder. Use `npx @usecontextlayer/cli connections --help` and `npx @usecontextlayer/cli connection --help` for listing, personal account authorization, and assignment syntax. Local listing needs no login or push; choosing an account requires a matching `npx @usecontextlayer/cli login`. Account choices are saved in ignored `.contextlayer/connections.json` rather than production assignments.
18
+ Declare resources in `public/slate.json` and `agents/<name>/slate.json`, following the [resource invariants](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#resource-configuration-and-execution--principles). Use `npx @usecontextlayer/cli connections --help` and `npx @usecontextlayer/cli connection --help` for listing, connecting personal accounts, and assignment syntax. Local assignments are saved in ignored `.contextlayer/connections.json`.
19
19
 
20
- Local development always uses your personal accounts, including owner-mode requirements in organization-owned apps. Local secrets read environment variables with exactly their declared names; local databases use native SQLite-backed Durable Objects persisted in `.contextlayer/databases`. Tooling ignores `.contextlayer/` in Git. Current-checkout SQL migrations are applied before local execution.
20
+ For local tool calls, assign your personal connected accounts even when the hosted declaration uses `owner` mode or the slate belongs to an organization. Keep `.contextlayer/` ignored in Git. Local database state lives in `.contextlayer/databases`; local secret values come from environment variables with their declared names.
21
21
 
22
- When `pnpm dev` starts, `contextlayer(env)` from `@usecontextlayer/sdk/vite` configures the Cloudflare Vite plugin and calls the CLI-owned `getLocalResourcesBindings` helper. This helper assembles the complete current-folder configuration before selecting the app consumer through `resourcesForConsumer`. The app’s resolved connections, Git-origin AppID and CLI credential become trusted native Tools props when connections are required. Selected database references become separate Databases props; the full collected migration history is applied during native startup. Agent-only connections, secret values, database configuration, and local declarations are not sent to platform or browser code. The AppID supplies app access/subscription/usage context independently of personal credential ownership.
23
-
24
- The auxiliary resource Worker exports `LocalTools` as `Tools`, `LocalDatabases` as `Databases`, `LocalDatabaseSetup` as `DatabaseSetup`, and the native `AppDatabase` class. Tools resolves the requested slug to the startup account ID and declaration toolkit, then calls the personal concrete-account endpoint. An undeclared local slug is a configuration error; a declared slug without an assigned account produces the shared setup response locally. There is no production-assignment fallback. The refresh token stays in `~/.contextlayer/auth.json`; the Composio project key stays on platform. Restart `pnpm dev` when the access token expires or declarations/local configuration change.
22
+ When the app declares connections, Vite startup needs a matching CLI login and the generated Git origin to identify the slate. This also applies when running a local agent because that command starts Vite. Restart `pnpm dev` after changing declarations, assignments, secret values, or migrations, and when the startup access token expires. The [local resource architecture](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#resource-configuration-and-execution--principles) describes preparation and credential boundaries.
25
23
 
26
24
  ## App Layout
27
25
 
@@ -31,15 +29,11 @@ The generated `app/root.tsx` re-exports the SDK's document Layout:
31
29
  export { Layout } from "@usecontextlayer/sdk/react"
32
30
  ```
33
31
 
34
- The Layout owns the HTML document, React Router's metadata, links, scripts, scroll restoration, and hosted ContextLayer header. Native Vite development detection disables the header locally, so local configuration never enters the platform frame. The app owns its routes, root component, error boundary, stylesheet, and font links. The trusted header supplies hosted connection configuration for Owners the viewer can manage.
35
-
36
- Platform serves the header and connection tray in a cross-origin iframe on `slate.usecontextlayer.com`. Platform owns their presentation and data loading; the parent receives only presentation messages. The app's Tailwind/shadcn setup is independent; there is no SDK stylesheet export or chrome root loader.
37
-
38
- The frame authenticates directly with the native web session. Its cookie always uses Secure, HttpOnly, and SameSite=None, in every environment. When browser third-party-cookie policy permits delivery, the existing web login authenticates the header automatically, without a separate sign-in or frame cookie. Web logout revokes subsequent frame authentication. The surrounding authored page receives neither credentials nor chrome data.
32
+ Keep this re-export when editing the app's root component, error boundary, stylesheet, and font links. Layout supplies React Router's document elements and mounts the [chrome](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#slate-chrome) outside Vite development. Use the chrome's header to configure hosted connections, then refresh the page. Use CLI assignments during local development.
39
33
 
40
34
  ## A loader that reads Gmail
41
35
 
42
- The first argument is the connection requirement slug in `public/slate.json`, such as `work-email`. Locally it selects your saved personal account; in hosted execution the pushed declaration selects the acting user's assignment (`viewer`) or the app's owning user or organization's assignment (`owner`):
36
+ Pass the connection slug from `public/slate.json` as the first argument to `tools.call`, followed by the tool name and its arguments:
43
37
 
44
38
  ```ts
45
39
  import { toolsContext } from "@usecontextlayer/sdk"
@@ -55,43 +49,39 @@ export async function loader({ context }: LoaderFunctionArgs) {
55
49
  }
56
50
  ```
57
51
 
58
- Calls return `{ data, logId }`. Validate the tool-specific `data` in your loader. The [Gmail route](examples/gmail/app/routes/home.tsx) validates the response with Zod and renders a message list. Its [Slate declaration](examples/gmail/public/slate.json) declares `work-email` as viewer-mode Gmail. The example follows the same `app/routes/home.tsx` and `public/slate.json` layout as your app.
52
+ Calls return `{ data, logId }`. Validate the tool-specific `data` in your loader. The [Gmail route](examples/gmail/app/routes/home.tsx) validates the response with Zod and renders a message list. Its [declaration](examples/gmail/public/slate.json) declares `work-email` as viewer-mode Gmail. The example follows the same `app/routes/home.tsx` and `public/slate.json` layout as your checkout.
59
53
 
60
- From a newly generated app's root, copy both files from the installed SDK:
54
+ From a newly generated checkout's root, copy both files from the installed SDK:
61
55
 
62
56
  ```sh
63
57
  cp node_modules/@usecontextlayer/sdk/examples/gmail/app/routes/home.tsx app/routes/home.tsx
64
58
  cp node_modules/@usecontextlayer/sdk/examples/gmail/public/slate.json public/slate.json
65
59
  ```
66
60
 
67
- If Gmail is not connected yet, request authorization:
61
+ If you have no connected Gmail account yet, connect one:
68
62
 
69
63
  ```sh
70
64
  npx @usecontextlayer/cli connections add gmail
71
65
  ```
72
66
 
73
- Open the printed link and approve access in your browser. Authorization connects Gmail to ContextLayer. Next, assign the connected account to this app's `work-email` requirement through the chooser, then start development. If Gmail is already connected, begin with assignment:
67
+ Open the printed link to connect your Gmail account in your browser. Next, assign the connected account to this slate's `work-email` connection, then start development. If your Gmail account is already connected, begin with assignment:
74
68
 
75
69
  ```sh
76
70
  npx @usecontextlayer/cli connection local assign work-email
77
71
  pnpm dev
78
72
  ```
79
73
 
80
- Open the local URL printed by the development server to see your inbox. If development is already running, restart it after copying the declaration and assigning the account so startup reads the new configuration.
81
-
82
- If the declared connection has no account assigned yet, the generated app’s error boundary shows account-setup guidance. Locally, follow its assignment command and restart `pnpm dev`. In a hosted app, open the connections menu in the ContextLayer header, choose an account, and refresh the page. The Gmail route uses the generated root's error boundary.
83
-
84
- ## Runtime ownership
74
+ Open the local URL printed by the development server to see your inbox. If development is already running, restart it after copying the declaration and assigning the connected account so startup reads the new configuration.
85
75
 
86
- The package root exports `Tools`/`toolsContext` and `Databases`/`databasesContext`, plus `database` for native Drizzle queries. `@usecontextlayer/sdk/react` exports the shared document Layout, which mounts platform's chrome iframe only outside development. `@usecontextlayer/sdk/local` exports the local Tools and Databases entrypoints, DatabaseSetup and AppDatabase; dispatcher separately exports hosted Tools and Databases. Both tool entrypoints share result/error semantics and preserve the authored `tools.call` interface. `@usecontextlayer/sdk/worker` exports `createApp`, which creates the React Router request handler and supplies Tools and Databases from local bindings or production request props. `@usecontextlayer/sdk/vite` owns the `contextlayer` integration. The CLI package owns the Node startup helper and saved-login handling. The generated application supplies its virtual server-build import, mode, and development flag through thin Worker wiring. The Cloudflare Vite plugin runs the auxiliary Worker only in development; production bundles exclude it and its service binding. Profile and connection reads belong to the trusted chrome frame; the SDK exposes no Viewer or Connections capability.
76
+ If the declared connection has no assignment yet, the generated app's error boundary shows guidance for the unassigned connection. Locally, follow its assignment command and restart `pnpm dev`. In a hosted slate, open the connections menu in the chrome's header, assign a connected account, and refresh the page. Join the slate before executing a viewer-mode resource; see [membership and provisioning](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#slate-forking-membership-and-resource-ownership).
87
77
 
88
- In hosted apps, the dispatcher supplies `ctx.props.tools` as a request-scoped RPC handle. Its methods call platform’s private `Execution` entrypoint through the dispatcher’s `EXECUTION` service binding; the app cannot read the underlying viewer credential. Platform verifies that viewer session and applies viewing and billing policy before execution. That session authenticates the caller, while the coherent pushed declaration's mode selects the viewer or app Owner's assignment for the app and slug. Viewer-mode execution requires explicit app membership and uses that member's production assignment. Connection configuration remains available before joining; owner-mode execution requires viewing permission without membership. Local connection choices remain separate even when the developer is also a production viewer. Owner-mode requirements use the app Owner's configured account. Local access-token bindings are not included in production builds.
78
+ ## Handling tool errors
89
79
 
90
- An undeclared hosted resource returns `not-declared`, and a hosted viewer-mode resource used before joining returns `membership-required`. These are ordinary Errors with those exact messages. An undeclared local connection is a configuration error; a declared connection with no account assignment is a setup condition. Hosted execution returns the typed `connection-required` outcome with its slug; Tools maps it to a native HTTP 409 Response with the shared `{ reason: "connection-required", slug }` payload. Tools carries a native Response over RPC; `createApp` throws it inside the authored app for React Router to handle. The package root exports `connectionRequiredSchema` so the app's error boundary can recognize this setup response through `isRouteErrorResponse(error)` and `error.data`. The generated root already does this. The response contains no account ID, profile, or credential. Successful authored `Tools.call` results remain `{ data, logId }`, and unrelated failures retain their existing error handling.
80
+ For a custom error boundary, use React Router's `isRouteErrorResponse(error)` and the SDK's `connectionRequiredSchema.safeParse(error.data)` to recognize the HTTP 409 payload `{ reason: "connection-required", slug }`. The generated root already handles this response. See the [execution boundary](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#resource-configuration-and-execution--principles) for authorization and credential handling.
91
81
 
92
- ## Vite configuration
82
+ ## Vite and Worker configuration
93
83
 
94
- ContextLayer's Vite integration for Cloudflare React Router apps. Compose it with the app's React Router and Tailwind plugins:
84
+ Compose `contextlayer` with the app's React Router and Tailwind plugins:
95
85
 
96
86
  ```ts
97
87
  import { contextlayer } from "@usecontextlayer/sdk/vite"
@@ -105,21 +95,13 @@ export default defineConfig((env) => ({
105
95
  }))
106
96
  ```
107
97
 
108
- This integration supplies the Cloudflare plugin; do not add a second instance. It uses the generated `workers/local-resources/wrangler.jsonc` to start the local resource Worker and supplies development-only Tools/Databases service bindings. At development startup, the CLI assembles current-checkout resources and reads Git origin/login when app connections require them. The restart prerequisites are described under [Local login and assignment](#local-login-and-assignment). Production builds exclude local credentials and the auxiliary Worker.
109
-
110
- The app retains its routes, `public/slate.json`, and thin Worker/configuration files. `@usecontextlayer/sdk/worker` owns the React Router request handler and capability context setup.
111
-
112
- ## App requirements and saved assignments
113
-
114
- The platform frame loader reads the browser viewer's profile and requirement/assignment rows through the shared app-connection listing operation. Signed-in viewers can inspect their required services and select accounts through each row's controls. These data stay in the trusted frame; anonymous viewers receive no account controls.
115
-
116
- The Slate schema and viewer/owner requirements live in `@usecontextlayer/shared/slate`. The neutral requirement/assignment response in `@usecontextlayer/shared/app-connections` is shared by platform and CLI. Use the hosted header to authorize or select accounts, then refresh the authored app’s data after configuration changes. Chrome is disabled during local development. Vite does not expose local configuration or app identity through a browser configuration plugin; the selected local connection inputs and credentials remain behind the Tools service binding. Restart development after editing requirements or bindings.
98
+ This integration supplies the Cloudflare plugin; do not add a second instance. Keep the generated `workers/local-resources/wrangler.jsonc` and `workers/local-resources/index.ts` for local development. Follow the [startup and restart prerequisites](#local-login-and-assignment) when changing resources.
117
99
 
118
- `createApp` returns the exported `App` type from `@usecontextlayer/sdk/worker`, derived from Cloudflare's native `ExportedHandler` fetch contract. The SDK owns its local binding and request-props types. This gives the generated Worker a portable public declaration under the Cloudflare scaffold's composite TypeScript configuration.
100
+ Keep the generated `workers/app.ts` wiring to `createSlateWorker` from `@usecontextlayer/sdk/worker`. It supplies the virtual React Router server build, Vite mode and development flag, and authored MCP modules. `createSlateWorker` returns the exported `SlateWorker` type. The [runtime architecture](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#resource-configuration-and-execution--principles) owns capability wiring and trust boundaries.
119
101
 
120
102
  ## A loader that queries cached data
121
103
 
122
- Declare a database slug in `public/slate.json` and the same slug in `agents/<name>/slate.json` when both should share data. Store its authored SQL migrations under `databases/<name>/migrations`. The template supplies Drizzle configuration and query schema; `pnpm db:migration --config databases/<name>/drizzle.config.ts --name <change>` scaffolds a blank migration for you to write explicitly. Commit the SQL and native `meta/_journal.json` together. The TypeScript schema supplies query typing, never generated DDL.
104
+ Declare a database slug in `public/slate.json` and the same slug in `agents/<name>/slate.json` when both should share data, following the [resource invariants](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#resource-configuration-and-execution--principles). Store its authored SQL migrations under `databases/<slug>/migrations`. The template supplies Drizzle configuration and query schema; `pnpm db:migration --config databases/<slug>/drizzle.config.ts --name <change>` scaffolds a blank migration for you to write explicitly. Commit the SQL and native `meta/_journal.json` together. Update the TypeScript schema for query types alongside the migration; it does not create tables.
123
105
 
124
106
  ```ts
125
107
  import { database, databasesContext } from "@usecontextlayer/sdk"
@@ -133,4 +115,4 @@ export async function loader({ context }: LoaderFunctionArgs) {
133
115
  }
134
116
  ```
135
117
 
136
- The loader receives a request-scoped SQL capability. Hosted platform derives the database from the app, authorized actor and declared mode; local execution uses prepared developer-local SQLite state. App and agent declarations selecting the same resource share rows. For direct SQL, use `context.get(databasesContext).query("updates", sql, params)`. Agents use `database_query`; writes persist immediately, and sandbox files remain scratch data. Local startup applies the current checkout’s migrations before queries. Hosted publication applies pending committed migrations for existing members; joining applies the full history for the joining member. Queries and agent preparation do not apply migrations.
118
+ For direct SQL, use `context.get(databasesContext).query("updates", sql, params)`. Agents use `database_query` for persistent data. Restart local development after adding migrations, and push committed migrations to `main` for hosted provisioning. See [database ownership and provisioning](https://github.com/usecontextlayer/contextlayer/blob/main/ARCHITECTURE.md#slate-databases-and-authored-migrations) for the lifecycle and isolation rules.
package/dist/local.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { i as DatabaseMigrations, o as SqlValue } from "./tools-BLXbCgQU-D3L2WEEd.js";
2
2
  import { z } from "zod";
3
3
  import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
4
- //#region ../shared/dist/app-resources-CJH87mYB.d.mts
4
+ //#region ../shared/dist/slate-resources-zjMlTUWg.d.mts
5
5
  declare const localResourceConfigurationSchema: z.ZodObject<{
6
6
  connections: z.ZodRecord<z.ZodString, z.ZodObject<{
7
7
  mode: z.ZodEnum<{
@@ -59,8 +59,8 @@ type LocalResourceConfiguration = z.infer<typeof localResourceConfigurationSchem
59
59
  //#endregion
60
60
  //#region ../shared/dist/database-worker.d.mts
61
61
  //#region lib/database-worker.d.ts
62
- export declare class AppDatabase extends DurableObject {
63
- setup(migrations: DatabaseMigrations): Promise<void>;
62
+ export declare class SlateDatabase extends DurableObject {
63
+ migrate(migrations: DatabaseMigrations): Promise<void>;
64
64
  query(sql: string, params?: SqlValue[]): Promise<{
65
65
  columns: string[];
66
66
  rows: (string | number | null)[][];
@@ -69,7 +69,7 @@ export declare class AppDatabase extends DurableObject {
69
69
  }>;
70
70
  }
71
71
  declare class LocalDatabases extends WorkerEntrypoint<{
72
- DATABASE_STORAGE: DurableObjectNamespace<AppDatabase>;
72
+ DATABASE_STORAGE: DurableObjectNamespace<SlateDatabase>;
73
73
  }, {
74
74
  databases: LocalResourceConfiguration["databases"];
75
75
  }> {
@@ -81,8 +81,8 @@ declare class LocalDatabases extends WorkerEntrypoint<{
81
81
  rowsWritten: number;
82
82
  } & Disposable>;
83
83
  }
84
- declare class LocalDatabaseSetup extends WorkerEntrypoint<{
85
- DATABASE_STORAGE: DurableObjectNamespace<AppDatabase>;
84
+ declare class LocalDatabaseProvisioning extends WorkerEntrypoint<{
85
+ DATABASE_STORAGE: DurableObjectNamespace<SlateDatabase>;
86
86
  }, {
87
87
  databases: LocalResourceConfiguration["databases"];
88
88
  }> {
@@ -92,7 +92,7 @@ declare class LocalDatabaseSetup extends WorkerEntrypoint<{
92
92
  //#endregion
93
93
  //#region ../shared/dist/tools-worker.d.mts
94
94
  interface LocalToolsProps {
95
- appId: string;
95
+ slateId: string;
96
96
  connections: LocalResourceConfiguration["connections"];
97
97
  credential: {
98
98
  token: string;
@@ -109,5 +109,5 @@ declare class LocalTools extends WorkerEntrypoint<{
109
109
  }
110
110
  //#endregion
111
111
  //#endregion
112
- export { LocalDatabaseSetup as DatabaseSetup, LocalDatabases as Databases, LocalTools as Tools };
112
+ export { LocalDatabaseProvisioning as DatabaseProvisioning, LocalDatabases as Databases, LocalTools as Tools };
113
113
  //# sourceMappingURL=local.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"local.d.ts","names":[],"sources":["../../shared/dist/app-resources-CJH87mYB.d.mts","../../shared/dist/database-worker.d.mts","../../shared/dist/tools-worker.d.mts"],"mappings":";;;;cAiIc,kCAAkC,EAAE;EAChD,aAAa,EAAE,UAAU,EAAE,WAAW,EAAE;IACtC,MAAM,EAAE;MACN;MACA;;IAEF,SAAS,EAAE;IACX,WAAW,EAAE,SAAS,EAAE,uBAAuB,EAAE;MAC/C,MAAM,EAAE;OACP,EAAE,KAAK,UAAU,EAAE;MACpB,MAAM,EAAE;MACR,MAAM,EAAE;OACP,EAAE,KAAK;IACV,eAAe,EAAE,YAAY,EAAE;KAC9B,EAAE,KAAK;EACV,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE;IACpC,MAAM,EAAE;MACN;MACA;;IAEF,WAAW,EAAE,SAAS,EAAE,uBAAuB,EAAE;MAC/C,MAAM,EAAE;OACP,EAAE,KAAK,UAAU,EAAE;MACpB,MAAM,EAAE;MACR,MAAM,EAAE;OACP,EAAE,KAAK;IACV,eAAe,EAAE;IACjB,YAAY,EAAE;MACZ,SAAS,EAAE;QACT,SAAS,EAAE,SAAS,EAAE;UACpB,aAAa,EAAE;UACf,KAAK,EAAE;UACP,KAAK,EAAE;UACP,MAAM,EAAE;WACP,EAAE,KAAK;SACT,EAAE,KAAK;MACV,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE;OACtC,EAAE,KAAK;KACT,EAAE,KAAK;EACV,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE;IAClC,MAAM,EAAE;MACN;MACA;;IAEF,WAAW,EAAE,SAAS,EAAE,uBAAuB,EAAE;MAC/C,MAAM,EAAE;OACP,EAAE,KAAK,UAAU,EAAE;MACpB,MAAM,EAAE;MACR,MAAM,EAAE;OACP,EAAE,KAAK;IACV,OAAO,EAAE,YAAY,EAAE;KACtB,EAAE,KAAK;GACT,EAAE,KAAK;KACL,6BAA6B,EAAE,aAAa;;;;qBClL5B,oBAAoB;EACvC,MAAM,YAAY,qBAAqB;EACvC,MAAM,aAAa,SAAS,aAAa;IACvC;IACA;IACA;IACA;;;cAGiB,uBAAuB;EAC1C,kBAAkB,uBAAuB;;EAEzC,WAAW;;EAEX,MAAM,SAAS,UAAU,QAAQ;EACjC,MAAM,cAAc,aAAa,SAAS,aAAa;IACrD;IACA;IACA;IACA;MACE;;cAEe,2BAA2B;EAC9C,kBAAkB,uBAAuB;;EAEzC,WAAW;;EAEX,SAAS,QAAQ;;;;;UCIF;EACf;EACA,aAAa;EACb;IACE;IACA;;;cAWiB,mBAAmB;EACtC;GACC;EACD,KAAK,cAAc,kBAAkB,MAAM,0BAA0B,QAAQ;IAC3E,MAAM;IACN"}
1
+ {"version":3,"file":"local.d.ts","names":[],"sources":["../../shared/dist/slate-resources-zjMlTUWg.d.mts","../../shared/dist/database-worker.d.mts","../../shared/dist/tools-worker.d.mts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;;EAEzC,WAAW;;EAEX,MAAM,SAAS,UAAU,QAAQ;EACjC,MAAM,cAAc,aAAa,SAAS,aAAa;IACrD;IACA;IACA;IACA;MACE;;cAEe,kCAAkC;EACrD,kBAAkB,uBAAuB;;EAEzC,WAAW;;EAEX,SAAS,QAAQ;;;;;UCIF;EACf;EACA,aAAa;EACb;IACE;IACA;;;cAWiB,mBAAmB;EACtC;GACC;EACD,KAAK,cAAc,kBAAkB,MAAM,0BAA0B,QAAQ;IAC3E,MAAM;IACN"}
package/dist/local.js CHANGED
@@ -32,8 +32,8 @@ const databaseResultSchema = z.object({
32
32
  });
33
33
  //#endregion
34
34
  //#region ../shared/dist/database-worker.mjs
35
- var AppDatabase = class extends DurableObject {
36
- async setup(migrations) {
35
+ var SlateDatabase = class extends DurableObject {
36
+ async migrate(migrations) {
37
37
  await migrate(drizzle(this.ctx.storage), databaseMigrationsSchema.parse(migrations));
38
38
  }
39
39
  async query(sql, params = []) {
@@ -58,9 +58,9 @@ var LocalDatabases = class extends WorkerEntrypoint {
58
58
  return this.env.DATABASE_STORAGE.getByName(database.instance_name).query(sql, params);
59
59
  }
60
60
  };
61
- var LocalDatabaseSetup = class extends WorkerEntrypoint {
61
+ var LocalDatabaseProvisioning = class extends WorkerEntrypoint {
62
62
  async fetch() {
63
- for (const database of Object.values(this.ctx.props.databases)) await this.env.DATABASE_STORAGE.getByName(database.instance_name).setup(database.migrations);
63
+ for (const database of Object.values(this.ctx.props.databases)) await this.env.DATABASE_STORAGE.getByName(database.instance_name).migrate(database.migrations);
64
64
  return new Response(null, { status: 204 });
65
65
  }
66
66
  };
@@ -68,14 +68,14 @@ var LocalDatabaseSetup = class extends WorkerEntrypoint {
68
68
  //#region ../shared/dist/tools-worker.mjs
69
69
  var LocalTools = class extends WorkerEntrypoint {
70
70
  async call(slug, toolSlug, args) {
71
- const { appId, connections, credential } = this.ctx.props;
71
+ const { slateId, connections, credential } = this.ctx.props;
72
72
  const connection = new Map(Object.entries(connections)).get(slug);
73
73
  if (!connection) throw new Error("not-declared");
74
74
  if (connection.connection_id === null) return connectionRequiredResponse(slug);
75
75
  return executeToolRequest(new Request(new URL(`/api/connections/${encodeURIComponent(connection.connection_id)}/tools/call`, this.env.CTX_PLATFORM_URL), {
76
76
  body: JSON.stringify({
77
- app_id: appId,
78
77
  arguments: args,
78
+ slate_id: slateId,
79
79
  tool: toolSlug,
80
80
  toolkit: connection.toolkit
81
81
  }),
@@ -111,6 +111,6 @@ function connectionRequiredResponse(slug) {
111
111
  });
112
112
  }
113
113
  //#endregion
114
- export { AppDatabase, LocalDatabaseSetup as DatabaseSetup, LocalDatabases as Databases, LocalTools as Tools };
114
+ export { LocalDatabaseProvisioning as DatabaseProvisioning, LocalDatabases as Databases, SlateDatabase, LocalTools as Tools };
115
115
 
116
116
  //# sourceMappingURL=local.js.map
package/dist/local.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"local.js","names":[],"sources":["../../shared/dist/databases.mjs","../../shared/dist/database-worker.mjs","../../shared/dist/tools-worker.mjs"],"sourcesContent":["import { z } from \"zod\";\n\n//#region lib/databases.ts\nconst databaseJournalSchema = z.object({ entries: z.array(z.object({\n\tbreakpoints: z.boolean(),\n\tidx: z.number().int().nonnegative(),\n\ttag: z.string().min(1),\n\twhen: z.number()\n})) });\nconst databaseMigrationsSchema = z.object({\n\tjournal: databaseJournalSchema,\n\tmigrations: z.record(z.string(), z.string())\n});\nasync function readDatabaseMigrations(slug, read) {\n\tconst directory = `databases/${slug}/migrations`;\n\tconst contents = await read(`${directory}/meta/_journal.json`);\n\tif (contents === null) return {\n\t\tjournal: { entries: [] },\n\t\tmigrations: {}\n\t};\n\tconst journal = databaseJournalSchema.parse(JSON.parse(contents));\n\tconst migrations = await Promise.all(journal.entries.map(async (entry) => {\n\t\tconst sql = await read(`${directory}/${entry.tag}.sql`);\n\t\tif (sql === null) throw new Error(`Missing database migration: ${slug}/${entry.tag}.sql`);\n\t\treturn [`m${entry.idx.toString().padStart(4, \"0\")}`, sql];\n\t}));\n\treturn {\n\t\tjournal,\n\t\tmigrations: Object.fromEntries(migrations)\n\t};\n}\nconst sqlValueSchema = z.union([\n\tz.string(),\n\tz.number(),\n\tz.null()\n]);\nconst databaseQuerySchema = z.strictObject({\n\tparams: z.array(sqlValueSchema).default([]),\n\tslug: z.string().min(1),\n\tsql: z.string().min(1)\n});\nconst databaseResultSchema = z.object({\n\tcolumns: z.array(z.string()),\n\trows: z.array(z.array(sqlValueSchema)),\n\trowsRead: z.number(),\n\trowsWritten: z.number()\n});\n\n//#endregion\nexport { databaseJournalSchema, databaseMigrationsSchema, databaseQuerySchema, databaseResultSchema, readDatabaseMigrations, sqlValueSchema };","import { databaseMigrationsSchema, databaseQuerySchema, databaseResultSchema } from \"./databases.mjs\";\nimport { DurableObject, WorkerEntrypoint } from \"cloudflare:workers\";\nimport { drizzle } from \"drizzle-orm/durable-sqlite\";\nimport { migrate } from \"drizzle-orm/durable-sqlite/migrator\";\n\n//#region lib/database-worker.ts\nvar AppDatabase = class extends DurableObject {\n\tasync setup(migrations) {\n\t\tawait migrate(drizzle(this.ctx.storage), databaseMigrationsSchema.parse(migrations));\n\t}\n\tasync query(sql, params = []) {\n\t\tconst cursor = this.ctx.storage.sql.exec(sql, ...params);\n\t\tconst rows = Array.from(cursor.raw());\n\t\treturn databaseResultSchema.parse({\n\t\t\tcolumns: cursor.columnNames,\n\t\t\trows,\n\t\t\trowsRead: cursor.rowsRead,\n\t\t\trowsWritten: cursor.rowsWritten\n\t\t});\n\t}\n};\nvar LocalDatabases = class extends WorkerEntrypoint {\n\tasync fetch(request) {\n\t\tconst { slug, sql, params } = databaseQuerySchema.parse(await request.json());\n\t\treturn Response.json(await this.query(slug, sql, params));\n\t}\n\tasync query(slug, sql, params = []) {\n\t\tconst database = this.ctx.props.databases[slug];\n\t\tif (!database) throw new Error(`No local database requirement for \"${slug}\"`);\n\t\treturn this.env.DATABASE_STORAGE.getByName(database.instance_name).query(sql, params);\n\t}\n};\nvar LocalDatabaseSetup = class extends WorkerEntrypoint {\n\tasync fetch() {\n\t\tfor (const database of Object.values(this.ctx.props.databases)) await this.env.DATABASE_STORAGE.getByName(database.instance_name).setup(database.migrations);\n\t\treturn new Response(null, { status: 204 });\n\t}\n};\n\n//#endregion\nexport { AppDatabase, LocalDatabaseSetup, LocalDatabases };","import { connectionRequiredSchema, toolResultSchema } from \"./tools.mjs\";\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\n\n//#region lib/tools-worker.ts\nfunction readHostedExecutionResult(result) {\n\tif (!result.allowed) throw new Error(\"message\" in result ? result.message : result.reason);\n\treturn result.result;\n}\nvar Tools = class extends WorkerEntrypoint {\n\tasync call(slug, toolSlug, args) {\n\t\tconst { appId, credential } = this.ctx.props;\n\t\tconst result = await this.env.EXECUTION.callTool(appId, credential.token, {\n\t\t\targuments: args,\n\t\t\tslug,\n\t\t\ttool: toolSlug\n\t\t});\n\t\tif (!result.allowed && result.reason === \"connection-required\") return connectionRequiredResponse(result.slug);\n\t\treturn readToolResult(toolResultSchema.parse(readHostedExecutionResult(result)));\n\t}\n};\nvar LocalTools = class extends WorkerEntrypoint {\n\tasync call(slug, toolSlug, args) {\n\t\tconst { appId, connections, credential } = this.ctx.props;\n\t\tconst connection = new Map(Object.entries(connections)).get(slug);\n\t\tif (!connection) throw new Error(\"not-declared\");\n\t\tif (connection.connection_id === null) return connectionRequiredResponse(slug);\n\t\treturn executeToolRequest(new Request(new URL(`/api/connections/${encodeURIComponent(connection.connection_id)}/tools/call`, this.env.CTX_PLATFORM_URL), {\n\t\t\tbody: JSON.stringify({\n\t\t\t\tapp_id: appId,\n\t\t\t\targuments: args,\n\t\t\t\ttool: toolSlug,\n\t\t\t\ttoolkit: connection.toolkit\n\t\t\t}),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${credential.token}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t},\n\t\t\tmethod: \"POST\"\n\t\t}));\n\t}\n};\nasync function executeToolRequest(request) {\n\tconst response = await fetch(request);\n\tif (response.status === 409) return connectionRequiredResponse(connectionRequiredSchema.parse(await response.json()).slug);\n\tif (response.status === 402) throw new Error(await response.text());\n\tif (!response.ok) throw new Error(`Tool call failed: HTTP ${response.status}`);\n\treturn readToolResult(toolResultSchema.parse(await response.json()));\n}\nfunction readToolResult(result) {\n\tif (result.error !== null) throw new Error(`${result.error} (log: ${result.logId})`);\n\treturn {\n\t\tdata: result.data,\n\t\tlogId: result.logId\n\t};\n}\nfunction connectionRequiredResponse(slug) {\n\treturn Response.json({\n\t\treason: \"connection-required\",\n\t\tslug\n\t}, {\n\t\tstatus: 409,\n\t\tstatusText: \"Connection required\"\n\t});\n}\n\n//#endregion\nexport { LocalTools, Tools, readHostedExecutionResult };"],"mappings":";;;;;;AAGA,MAAM,wBAAwB,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO;CAClE,aAAa,EAAE,QAAQ;CACvB,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY;CAClC,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACrB,MAAM,EAAE,OAAO;AAChB,CAAC,CAAC,EAAE,CAAC;AACL,MAAM,2BAA2B,EAAE,OAAO;CACzC,SAAS;CACT,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;AAC5C,CAAC;AAmBD,MAAM,iBAAiB,EAAE,MAAM;CAC9B,EAAE,OAAO;CACT,EAAE,OAAO;CACT,EAAE,KAAK;AACR,CAAC;AACD,MAAM,sBAAsB,EAAE,aAAa;CAC1C,QAAQ,EAAE,MAAM,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC;CAC1C,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACtB,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AACtB,CAAC;AACD,MAAM,uBAAuB,EAAE,OAAO;CACrC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC;C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EACR,YAAY;CACb,CAAC;AACF"}
1
+ {"version":3,"file":"local.js","names":[],"sources":["../../shared/dist/databases.mjs","../../shared/dist/database-worker.mjs","../../shared/dist/tools-worker.mjs"],"sourcesContent":["import { z } from \"zod\";\n\n//#region lib/databases.ts\nconst databaseJournalSchema = z.object({ entries: z.array(z.object({\n\tbreakpoints: z.boolean(),\n\tidx: z.number().int().nonnegative(),\n\ttag: z.string().min(1),\n\twhen: z.number()\n})) });\nconst databaseMigrationsSchema = z.object({\n\tjournal: databaseJournalSchema,\n\tmigrations: z.record(z.string(), z.string())\n});\nasync function readDatabaseMigrations(slug, read) {\n\tconst directory = `databases/${slug}/migrations`;\n\tconst contents = await read(`${directory}/meta/_journal.json`);\n\tif (contents === null) return {\n\t\tjournal: { entries: [] },\n\t\tmigrations: {}\n\t};\n\tconst journal = databaseJournalSchema.parse(JSON.parse(contents));\n\tconst migrations = await Promise.all(journal.entries.map(async (entry) => {\n\t\tconst sql = await read(`${directory}/${entry.tag}.sql`);\n\t\tif (sql === null) throw new Error(`Missing database migration: ${slug}/${entry.tag}.sql`);\n\t\treturn [`m${entry.idx.toString().padStart(4, \"0\")}`, sql];\n\t}));\n\treturn {\n\t\tjournal,\n\t\tmigrations: Object.fromEntries(migrations)\n\t};\n}\nconst sqlValueSchema = z.union([\n\tz.string(),\n\tz.number(),\n\tz.null()\n]);\nconst databaseQuerySchema = z.strictObject({\n\tparams: z.array(sqlValueSchema).default([]),\n\tslug: z.string().min(1),\n\tsql: z.string().min(1)\n});\nconst databaseResultSchema = z.object({\n\tcolumns: z.array(z.string()),\n\trows: z.array(z.array(sqlValueSchema)),\n\trowsRead: z.number(),\n\trowsWritten: z.number()\n});\n\n//#endregion\nexport { databaseJournalSchema, databaseMigrationsSchema, databaseQuerySchema, databaseResultSchema, readDatabaseMigrations, sqlValueSchema };","import { databaseMigrationsSchema, databaseQuerySchema, databaseResultSchema } from \"./databases.mjs\";\nimport { DurableObject, WorkerEntrypoint } from \"cloudflare:workers\";\nimport { drizzle } from \"drizzle-orm/durable-sqlite\";\nimport { migrate } from \"drizzle-orm/durable-sqlite/migrator\";\n\n//#region lib/database-worker.ts\nvar SlateDatabase = class extends DurableObject {\n\tasync migrate(migrations) {\n\t\tawait migrate(drizzle(this.ctx.storage), databaseMigrationsSchema.parse(migrations));\n\t}\n\tasync query(sql, params = []) {\n\t\tconst cursor = this.ctx.storage.sql.exec(sql, ...params);\n\t\tconst rows = Array.from(cursor.raw());\n\t\treturn databaseResultSchema.parse({\n\t\t\tcolumns: cursor.columnNames,\n\t\t\trows,\n\t\t\trowsRead: cursor.rowsRead,\n\t\t\trowsWritten: cursor.rowsWritten\n\t\t});\n\t}\n};\nvar LocalDatabases = class extends WorkerEntrypoint {\n\tasync fetch(request) {\n\t\tconst { slug, sql, params } = databaseQuerySchema.parse(await request.json());\n\t\treturn Response.json(await this.query(slug, sql, params));\n\t}\n\tasync query(slug, sql, params = []) {\n\t\tconst database = this.ctx.props.databases[slug];\n\t\tif (!database) throw new Error(`No local database requirement for \"${slug}\"`);\n\t\treturn this.env.DATABASE_STORAGE.getByName(database.instance_name).query(sql, params);\n\t}\n};\nvar LocalDatabaseProvisioning = class extends WorkerEntrypoint {\n\tasync fetch() {\n\t\tfor (const database of Object.values(this.ctx.props.databases)) await this.env.DATABASE_STORAGE.getByName(database.instance_name).migrate(database.migrations);\n\t\treturn new Response(null, { status: 204 });\n\t}\n};\n\n//#endregion\nexport { LocalDatabaseProvisioning, LocalDatabases, SlateDatabase };","import { connectionRequiredSchema, toolResultSchema } from \"./tools.mjs\";\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\n\n//#region lib/tools-worker.ts\nfunction readHostedExecutionResult(result) {\n\tif (!result.allowed) throw new Error(\"message\" in result ? result.message : result.reason);\n\treturn result.result;\n}\nvar Tools = class extends WorkerEntrypoint {\n\tasync call(slug, toolSlug, args) {\n\t\tconst { slateId, credential } = this.ctx.props;\n\t\tconst result = await this.env.EXECUTION.callTool(slateId, credential.token, {\n\t\t\targuments: args,\n\t\t\tslug,\n\t\t\ttool: toolSlug\n\t\t});\n\t\tif (!result.allowed && result.reason === \"connection-required\") return connectionRequiredResponse(result.slug);\n\t\treturn readToolResult(toolResultSchema.parse(readHostedExecutionResult(result)));\n\t}\n};\nvar LocalTools = class extends WorkerEntrypoint {\n\tasync call(slug, toolSlug, args) {\n\t\tconst { slateId, connections, credential } = this.ctx.props;\n\t\tconst connection = new Map(Object.entries(connections)).get(slug);\n\t\tif (!connection) throw new Error(\"not-declared\");\n\t\tif (connection.connection_id === null) return connectionRequiredResponse(slug);\n\t\treturn executeToolRequest(new Request(new URL(`/api/connections/${encodeURIComponent(connection.connection_id)}/tools/call`, this.env.CTX_PLATFORM_URL), {\n\t\t\tbody: JSON.stringify({\n\t\t\t\targuments: args,\n\t\t\t\tslate_id: slateId,\n\t\t\t\ttool: toolSlug,\n\t\t\t\ttoolkit: connection.toolkit\n\t\t\t}),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${credential.token}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t},\n\t\t\tmethod: \"POST\"\n\t\t}));\n\t}\n};\nasync function executeToolRequest(request) {\n\tconst response = await fetch(request);\n\tif (response.status === 409) return connectionRequiredResponse(connectionRequiredSchema.parse(await response.json()).slug);\n\tif (response.status === 402) throw new Error(await response.text());\n\tif (!response.ok) throw new Error(`Tool call failed: HTTP ${response.status}`);\n\treturn readToolResult(toolResultSchema.parse(await response.json()));\n}\nfunction readToolResult(result) {\n\tif (result.error !== null) throw new Error(`${result.error} (log: ${result.logId})`);\n\treturn {\n\t\tdata: result.data,\n\t\tlogId: result.logId\n\t};\n}\nfunction connectionRequiredResponse(slug) {\n\treturn Response.json({\n\t\treason: \"connection-required\",\n\t\tslug\n\t}, {\n\t\tstatus: 409,\n\t\tstatusText: \"Connection required\"\n\t});\n}\n\n//#endregion\nexport { LocalTools, Tools, readHostedExecutionResult };"],"mappings":";;;;;;AAGA,MAAM,wBAAwB,EA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;GACD,SAAS;IACR,eAAe,UAAU,WAAW;IACpC,gBAAgB;GACjB;GACA,QAAQ;EACT,CAAC,CAAC;CACH;AACD;AACA,eAAe,mBAAmB,SAAS;CAC1C,MAAM,WAAW,MAAM,MAAM,OAAO;CACpC,IAAI,SAAS,WAAW,KAAK,OAAO,2BAA2B,yBAAyB,MAAM,MAAM,SAAS,KAAK,CAAC,CAAC,CAAC,IAAI;CACzH,IAAI,SAAS,WAAW,KAAK,MAAM,IAAI,MAAM,MAAM,SAAS,KAAK,CAAC;CAClE,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,MAAM,0BAA0B,SAAS,QAAQ;CAC7E,OAAO,eAAe,iBAAiB,MAAM,MAAM,SAAS,KAAK,CAAC,CAAC;AACpE;AACA,SAAS,eAAe,QAAQ;CAC/B,IAAI,OAAO,UAAU,MAAM,MAAM,IAAI,MAAM,GAAG,OAAO,MAAM,SAAS,OAAO,MAAM,EAAE;CACnF,OAAO;EACN,MAAM,OAAO;EACb,OAAO,OAAO;CACf;AACD;AACA,SAAS,2BAA2B,MAAM;CACzC,OAAO,SAAS,KAAK;EACpB,QAAQ;EACR;CACD,GAAG;EACF,QAAQ;EACR,YAAY;CACb,CAAC;AACF"}
package/dist/react.js CHANGED
@@ -10,7 +10,7 @@ const chromeHeightSchema = z.object({
10
10
  });
11
11
  //#endregion
12
12
  //#region browser-env.ts
13
- const browserEnv = z.object({ CTX_PLATFORM_URL: z.url().default("https://slate.usecontextlayer.com") }).parse({ CTX_PLATFORM_URL: import.meta.env.CTX_PLATFORM_URL });
13
+ const browserEnv = z.object({ CTX_PLATFORM_URL: z.url().default("https://platform.usecontextlayer.com") }).parse({ CTX_PLATFORM_URL: import.meta.env.CTX_PLATFORM_URL });
14
14
  //#endregion
15
15
  //#region react.tsx
16
16
  function Chrome() {
@@ -19,7 +19,7 @@ function Chrome() {
19
19
  const [height, setHeight] = useState(30);
20
20
  useEffect(() => {
21
21
  const target = window.location.hostname;
22
- const url = new URL(`${chromePath}/apps/${encodeURIComponent(target)}`, browserEnv.CTX_PLATFORM_URL);
22
+ const url = new URL(`${chromePath}/slates/${encodeURIComponent(target)}`, browserEnv.CTX_PLATFORM_URL);
23
23
  url.searchParams.set("parentOrigin", window.location.origin);
24
24
  function resize(event) {
25
25
  if (event.origin !== url.origin || event.source !== frame.current?.contentWindow) return;
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":[],"sources":["../../shared/dist/chrome.mjs","../browser-env.ts","../react.tsx"],"sourcesContent":["import { z } from \"zod\";\n\n//#region lib/chrome.ts\nconst chromePath = \"/dashboard/chrome\";\nconst chromeHeightSchema = z.object({\n\theight: z.number().finite().nonnegative(),\n\ttype: z.literal(\"ctx:chrome:height\")\n});\n\n//#endregion\nexport { chromeHeightSchema, chromePath };","import { z } from \"zod\"\n\nexport const browserEnv = z\n\t.object({\n\t\tCTX_PLATFORM_URL: z.url().default(\"https://slate.usecontextlayer.com\"),\n\t})\n\t.parse({\n\t\tCTX_PLATFORM_URL: import.meta.env.CTX_PLATFORM_URL,\n\t})\n","import { chromeHeightSchema, chromePath } from \"@usecontextlayer/shared/chrome\"\nimport { type ReactNode, useEffect, useRef, useState } from \"react\"\nimport { Links, Meta, Scripts, ScrollRestoration } from \"react-router\"\nimport { browserEnv } from \"@/browser-env\"\n\nfunction Chrome() {\n\tconst frame = useRef<HTMLIFrameElement>(null)\n\tconst [src, setSrc] = useState<string>()\n\tconst [height, setHeight] = useState(30)\n\tuseEffect(() => {\n\t\tconst target = window.location.hostname\n\t\tconst url = new URL(\n\t\t\t`${chromePath}/apps/${encodeURIComponent(target)}`,\n\t\t\tbrowserEnv.CTX_PLATFORM_URL,\n\t\t)\n\t\turl.searchParams.set(\"parentOrigin\", window.location.origin)\n\t\tfunction resize(event: MessageEvent) {\n\t\t\tif (event.origin !== url.origin || event.source !== frame.current?.contentWindow)\n\t\t\t\treturn\n\t\t\tconst message = chromeHeightSchema.safeParse(event.data)\n\t\t\tif (message.success) setHeight(message.data.height)\n\t\t}\n\t\twindow.addEventListener(\"message\", resize)\n\t\tsetSrc(url.href)\n\t\treturn () => window.removeEventListener(\"message\", resize)\n\t}, [])\n\treturn (\n\t\t<iframe\n\t\t\tref={frame}\n\t\t\tsrc={src}\n\t\t\ttitle=\"ContextLayer\"\n\t\t\tstyle={{\n\t\t\t\tbackgroundColor: \"oklch(96.8% 0.007 247.896)\",\n\t\t\t\tborder: 0,\n\t\t\t\tborderBottom: \"1px solid oklch(92.9% 0.013 255.508)\",\n\t\t\t\tdisplay: \"block\",\n\t\t\t\theight,\n\t\t\t\twidth: \"100%\",\n\t\t\t}}\n\t\t/>\n\t)\n}\n\nexport function Layout({ children }: { children: ReactNode }) {\n\treturn (\n\t\t<html lang=\"en\">\n\t\t\t<head>\n\t\t\t\t<meta charSet=\"utf-8\" />\n\t\t\t\t<meta\n\t\t\t\t\tname=\"viewport\"\n\t\t\t\t\tcontent=\"width=device-width, initial-scale=1\"\n\t\t\t\t/>\n\t\t\t\t<Meta />\n\t\t\t\t<Links />\n\t\t\t</head>\n\t\t\t<body>\n\t\t\t\t{!import.meta.env.DEV && <Chrome />}\n\t\t\t\t{children}\n\t\t\t\t<ScrollRestoration />\n\t\t\t\t<Scripts />\n\t\t\t</body>\n\t\t</html>\n\t)\n}\n"],"mappings":";;;;;AAGA,MAAM,aAAa;AACnB,MAAM,qBAAqB,EAAE,OAAO;CACnC,QAAQ,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,YAAY;CACxC,MAAM,EAAE,QAAQ,mBAAmB;AACpC,CAAC;;;ACLD,MAAa,aAAa,EACxB,OAAO,EACP,kBAAkB,EAAE,IAAI,CAAC,CAAC,QAAQ,mCAAmC,EACtE,CAAC,CAAC,CACD,MAAM,EACN,kBAAkB,YAAY,IAAI,iBACnC,CAAC;;;ACHF,SAAS,SAAS;CACjB,MAAM,QAAQ,OAA0B,IAAI;CAC5C,MAAM,CAAC,KAAK,UAAU,SAAiB;CACvC,MAAM,CAAC,QAAQ,aAAa,SAAS,EAAE;CACvC,gBAAgB;EACf,MAAM,SAAS,OAAO,SAAS;EAC/B,MAAM,MAAM,IAAI,IACf,GAAG,WAAW,QAAQ,mBAAmB,MAAM,KAC/C,WAAW,gBACZ;EACA,IAAI,aAAa,IAAI,gBAAgB,OAAO,SAAS,MAAM;EAC3D,SAAS,OAAO,OAAqB;GACpC,IAAI,MAAM,WAAW,IAAI,UAAU,MAAM,WAAW,MAAM,SAAS,eAClE;GACD,MAAM,UAAU,mBAAmB,UAAU,MAAM,IAAI;GACvD,IAAI,QAAQ,SAAS,UAAU,QAAQ,KAAK,MAAM;EACnD;EACA,OAAO,iBAAiB,WAAW,MAAM;EACzC,OAAO,IAAI,IAAI;EACf,aAAa,OAAO,oBAAoB,WAAW,MAAM;CAC1D,GAAG,CAAC,CAAC;CACL,OACC,oBAAC,UAAD;EACC,KAAK;EACA;EACL,OAAM;EACN,OAAO;GACN,iBAAiB;GACjB,QAAQ;GACR,cAAc;GACd,SAAS;GACT;GACA,OAAO;EACR;CACA,CAAA;AAEH;AAEA,SAAgB,OAAO,EAAE,YAAqC;CAC7D,OACC,qBAAC,QAAD;EAAM,MAAK;EAAX,UAAA,CACC,qBAAC,QAAD,EAAA,UAAA;GACC,oBAAC,QAAD,EAAM,SAAQ,QAAS,CAAA;GACvB,oBAAC,QAAD;IACC,MAAK;IACL,SAAQ;GACR,CAAA;GACD,oBAAC,MAAD,CAAO,CAAA;GACP,oBAAC,OAAD,CAAQ,CAAA;EACH,EAAA,CAAA,GACN,qBAAC,QAAD,EAAA,UAAA;GACE,CAAC,YAAY,IAAI,OAAO,oBAAC,QAAD,CAAS,CAAA;GACjC;GACD,oBAAC,mBAAD,CAAoB,CAAA;GACpB,oBAAC,SAAD,CAAU,CAAA;EACL,EAAA,CAAA,CACD;;AAER"}
1
+ {"version":3,"file":"react.js","names":[],"sources":["../../shared/dist/chrome.mjs","../browser-env.ts","../react.tsx"],"sourcesContent":["import { z } from \"zod\";\n\n//#region lib/chrome.ts\nconst chromePath = \"/dashboard/chrome\";\nconst chromeHeightSchema = z.object({\n\theight: z.number().finite().nonnegative(),\n\ttype: z.literal(\"ctx:chrome:height\")\n});\n\n//#endregion\nexport { chromeHeightSchema, chromePath };","import { z } from \"zod\"\n\nexport const browserEnv = z\n\t.object({\n\t\tCTX_PLATFORM_URL: z.url().default(\"https://platform.usecontextlayer.com\"),\n\t})\n\t.parse({\n\t\tCTX_PLATFORM_URL: import.meta.env.CTX_PLATFORM_URL,\n\t})\n","import { chromeHeightSchema, chromePath } from \"@usecontextlayer/shared/chrome\"\nimport { type ReactNode, useEffect, useRef, useState } from \"react\"\nimport { Links, Meta, Scripts, ScrollRestoration } from \"react-router\"\nimport { browserEnv } from \"@/browser-env\"\n\nfunction Chrome() {\n\tconst frame = useRef<HTMLIFrameElement>(null)\n\tconst [src, setSrc] = useState<string>()\n\tconst [height, setHeight] = useState(30)\n\tuseEffect(() => {\n\t\tconst target = window.location.hostname\n\t\tconst url = new URL(\n\t\t\t`${chromePath}/slates/${encodeURIComponent(target)}`,\n\t\t\tbrowserEnv.CTX_PLATFORM_URL,\n\t\t)\n\t\turl.searchParams.set(\"parentOrigin\", window.location.origin)\n\t\tfunction resize(event: MessageEvent) {\n\t\t\tif (event.origin !== url.origin || event.source !== frame.current?.contentWindow)\n\t\t\t\treturn\n\t\t\tconst message = chromeHeightSchema.safeParse(event.data)\n\t\t\tif (message.success) setHeight(message.data.height)\n\t\t}\n\t\twindow.addEventListener(\"message\", resize)\n\t\tsetSrc(url.href)\n\t\treturn () => window.removeEventListener(\"message\", resize)\n\t}, [])\n\treturn (\n\t\t<iframe\n\t\t\tref={frame}\n\t\t\tsrc={src}\n\t\t\ttitle=\"ContextLayer\"\n\t\t\tstyle={{\n\t\t\t\tbackgroundColor: \"oklch(96.8% 0.007 247.896)\",\n\t\t\t\tborder: 0,\n\t\t\t\tborderBottom: \"1px solid oklch(92.9% 0.013 255.508)\",\n\t\t\t\tdisplay: \"block\",\n\t\t\t\theight,\n\t\t\t\twidth: \"100%\",\n\t\t\t}}\n\t\t/>\n\t)\n}\n\nexport function Layout({ children }: { children: ReactNode }) {\n\treturn (\n\t\t<html lang=\"en\">\n\t\t\t<head>\n\t\t\t\t<meta charSet=\"utf-8\" />\n\t\t\t\t<meta\n\t\t\t\t\tname=\"viewport\"\n\t\t\t\t\tcontent=\"width=device-width, initial-scale=1\"\n\t\t\t\t/>\n\t\t\t\t<Meta />\n\t\t\t\t<Links />\n\t\t\t</head>\n\t\t\t<body>\n\t\t\t\t{!import.meta.env.DEV && <Chrome />}\n\t\t\t\t{children}\n\t\t\t\t<ScrollRestoration />\n\t\t\t\t<Scripts />\n\t\t\t</body>\n\t\t</html>\n\t)\n}\n"],"mappings":";;;;;AAGA,MAAM,aAAa;AACnB,MAAM,qBAAqB,EAAE,OAAO;CACnC,QAAQ,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,YAAY;CACxC,MAAM,EAAE,QAAQ,mBAAmB;AACpC,CAAC;;;ACLD,MAAa,aAAa,EACxB,OAAO,EACP,kBAAkB,EAAE,IAAI,CAAC,CAAC,QAAQ,sCAAsC,EACzE,CAAC,CAAC,CACD,MAAM,EACN,kBAAkB,YAAY,IAAI,iBACnC,CAAC;;;ACHF,SAAS,SAAS;CACjB,MAAM,QAAQ,OAA0B,IAAI;CAC5C,MAAM,CAAC,KAAK,UAAU,SAAiB;CACvC,MAAM,CAAC,QAAQ,aAAa,SAAS,EAAE;CACvC,gBAAgB;EACf,MAAM,SAAS,OAAO,SAAS;EAC/B,MAAM,MAAM,IAAI,IACf,GAAG,WAAW,UAAU,mBAAmB,MAAM,KACjD,WAAW,gBACZ;EACA,IAAI,aAAa,IAAI,gBAAgB,OAAO,SAAS,MAAM;EAC3D,SAAS,OAAO,OAAqB;GACpC,IAAI,MAAM,WAAW,IAAI,UAAU,MAAM,WAAW,MAAM,SAAS,eAClE;GACD,MAAM,UAAU,mBAAmB,UAAU,MAAM,IAAI;GACvD,IAAI,QAAQ,SAAS,UAAU,QAAQ,KAAK,MAAM;EACnD;EACA,OAAO,iBAAiB,WAAW,MAAM;EACzC,OAAO,IAAI,IAAI;EACf,aAAa,OAAO,oBAAoB,WAAW,MAAM;CAC1D,GAAG,CAAC,CAAC;CACL,OACC,oBAAC,UAAD;EACC,KAAK;EACA;EACL,OAAM;EACN,OAAO;GACN,iBAAiB;GACjB,QAAQ;GACR,cAAc;GACd,SAAS;GACT;GACA,OAAO;EACR;CACA,CAAA;AAEH;AAEA,SAAgB,OAAO,EAAE,YAAqC;CAC7D,OACC,qBAAC,QAAD;EAAM,MAAK;EAAX,UAAA,CACC,qBAAC,QAAD,EAAA,UAAA;GACC,oBAAC,QAAD,EAAM,SAAQ,QAAS,CAAA;GACvB,oBAAC,QAAD;IACC,MAAK;IACL,SAAQ;GACR,CAAA;GACD,oBAAC,MAAD,CAAO,CAAA;GACP,oBAAC,OAAD,CAAQ,CAAA;EACH,EAAA,CAAA,GACN,qBAAC,QAAD,EAAA,UAAA;GACE,CAAC,YAAY,IAAI,OAAO,oBAAC,QAAD,CAAS,CAAA;GACjC;GACD,oBAAC,mBAAD,CAAoB,CAAA;GACpB,oBAAC,SAAD,CAAU,CAAA;EACL,EAAA,CAAA,CACD;;AAER"}
@@ -1 +1 @@
1
- {"version":3,"file":"vite.d.ts","names":[],"sources":["../vite.ts"],"mappings":";;wBAKsB,eAAe,WAAW,YAAS,wBAAA,+BAAA"}
1
+ {"version":3,"file":"vite.d.ts","names":[],"sources":["../vite.ts"],"mappings":";;wBAQsB,eAAe,WAAW,YAAS,wBAAA,+BAAA"}
package/dist/vite.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { z } from "zod";
2
2
  import { cloudflare } from "@cloudflare/vite-plugin";
3
- import { getLocalResourcesBindings, localDatabaseSetup } from "@usecontextlayer/cli/vite";
3
+ import { getLocalResourcesBindings, localDatabaseProvisioning } from "@usecontextlayer/cli/vite";
4
4
  import { glob, readFile } from "node:fs/promises";
5
5
  import { dirname, join, relative } from "node:path";
6
6
  import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
7
7
  import { ResourceSchema, ToolSchema } from "@modelcontextprotocol/core";
8
8
  import { build, createServer, createServerModuleRunner } from "vite";
9
9
  import { viteSingleFile } from "vite-plugin-singlefile";
10
- //#region ../shared/dist/slate.mjs
10
+ //#region ../shared/dist/declaration.mjs
11
11
  const credentialModeSchema = z.enum(["viewer", "owner"]);
12
12
  const connectionRequirementSchema = z.strictObject({
13
13
  mode: credentialModeSchema,
@@ -16,23 +16,23 @@ const connectionRequirementSchema = z.strictObject({
16
16
  const secretNameSchema = z.string().regex(/^[A-Z_][A-Z0-9_]*$/);
17
17
  const secretRequirementSchema = z.strictObject({ mode: credentialModeSchema });
18
18
  const databaseRequirementSchema = z.strictObject({ mode: credentialModeSchema });
19
- const databaseNameSchema = z.string().min(1).regex(/^(?!\.{1,2}$)[^/\\]+$/);
20
- const slateSchema = z.strictObject({
19
+ const databaseSlugSchema = z.string().min(1).regex(/^(?!\.{1,2}$)[^/\\]+$/);
20
+ const declarationSchema = z.strictObject({
21
21
  connections: z.record(z.string().min(1), connectionRequirementSchema),
22
- databases: z.record(databaseNameSchema, databaseRequirementSchema).default({}),
22
+ databases: z.record(databaseSlugSchema, databaseRequirementSchema).default({}),
23
23
  secrets: z.record(secretNameSchema, secretRequirementSchema).default({})
24
24
  });
25
25
  z.strictObject({
26
- agents: z.record(z.string().min(1), slateSchema),
27
- app: slateSchema
26
+ agents: z.record(z.string().min(1), declarationSchema),
27
+ app: declarationSchema
28
28
  });
29
29
  const resourceConsumerSchema = z.discriminatedUnion("type", [z.strictObject({ type: z.literal("app") }), z.strictObject({
30
30
  name: z.string().min(1),
31
31
  type: z.literal("agent")
32
32
  })]);
33
- slateSchema.extend({
33
+ declarationSchema.extend({
34
34
  connections: z.record(z.string().min(1), connectionRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) })),
35
- databases: z.record(databaseNameSchema, databaseRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) })),
35
+ databases: z.record(databaseSlugSchema, databaseRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) })),
36
36
  secrets: z.record(secretNameSchema, secretRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) }))
37
37
  });
38
38
  //#endregion
@@ -40,7 +40,7 @@ slateSchema.extend({
40
40
  const MCP_MANIFEST_PATH = "/mcp.json";
41
41
  const mcpManifestSchema = z.object({
42
42
  resources: z.array(ResourceSchema.extend({ path: z.string() })),
43
- tools: z.array(ToolSchema.extend({ slate: slateSchema }))
43
+ tools: z.array(ToolSchema.extend({ declaration: declarationSchema }))
44
44
  });
45
45
  //#endregion
46
46
  //#region mcp-vite.ts
@@ -60,13 +60,13 @@ function mcpApps() {
60
60
  const tools = [];
61
61
  for await (const file of glob("mcp/*/index.ts", { cwd: root })) {
62
62
  const { tool } = await runner.import(join(root, file));
63
- const slate = slateSchema.parse(JSON.parse(await readFile(join(root, dirname(file), "slate.json"), "utf8")));
64
- if (Object.keys(slate.connections).length || Object.keys(slate.databases).length || Object.keys(slate.secrets).length) throw new Error(`${file}: MCP resource consumers are not implemented yet`);
63
+ const declaration = declarationSchema.parse(JSON.parse(await readFile(join(root, dirname(file), "slate.json"), "utf8")));
64
+ if (Object.keys(declaration.connections).length || Object.keys(declaration.databases).length || Object.keys(declaration.secrets).length) throw new Error(`${file}: MCP resource consumers are not implemented yet`);
65
65
  tools.push({
66
66
  ...tool,
67
+ declaration,
67
68
  inputSchema: z.toJSONSchema(tool.inputSchema),
68
- outputSchema: tool.outputSchema ? z.toJSONSchema(tool.outputSchema) : void 0,
69
- slate
69
+ outputSchema: tool.outputSchema ? z.toJSONSchema(tool.outputSchema) : void 0
70
70
  });
71
71
  }
72
72
  const assets = [];
@@ -163,7 +163,7 @@ async function contextlayer({ command }) {
163
163
  persistState: { path: ".contextlayer/databases" },
164
164
  viteEnvironment: { name: "ssr" }
165
165
  }),
166
- bindings ? localDatabaseSetup(bindings) : void 0
166
+ bindings ? localDatabaseProvisioning(bindings) : void 0
167
167
  ];
168
168
  }
169
169
  //#endregion
package/dist/vite.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vite.js","names":[],"sources":["../../shared/dist/slate.mjs","../../shared/dist/mcp.mjs","../mcp-vite.ts","../vite.ts"],"sourcesContent":["import { z } from \"zod\";\n\n//#region lib/slate.ts\nconst credentialModeSchema = z.enum([\"viewer\", \"owner\"]);\nconst connectionRequirementSchema = z.strictObject({\n\tmode: credentialModeSchema,\n\ttoolkit: z.string().min(1)\n});\nconst secretNameSchema = z.string().regex(/^[A-Z_][A-Z0-9_]*$/);\nconst secretRequirementSchema = z.strictObject({ mode: credentialModeSchema });\nconst databaseRequirementSchema = z.strictObject({ mode: credentialModeSchema });\nconst databaseNameSchema = z.string().min(1).regex(/^(?!\\.{1,2}$)[^/\\\\]+$/);\nconst slateSchema = z.strictObject({\n\tconnections: z.record(z.string().min(1), connectionRequirementSchema),\n\tdatabases: z.record(databaseNameSchema, databaseRequirementSchema).default({}),\n\tsecrets: z.record(secretNameSchema, secretRequirementSchema).default({})\n});\nconst appSlatesSchema = z.strictObject({\n\tagents: z.record(z.string().min(1), slateSchema),\n\tapp: slateSchema\n});\nconst resourceConsumerSchema = z.discriminatedUnion(\"type\", [z.strictObject({ type: z.literal(\"app\") }), z.strictObject({\n\tname: z.string().min(1),\n\ttype: z.literal(\"agent\")\n})]);\nconst resourcesSchema = slateSchema.extend({\n\tconnections: z.record(z.string().min(1), connectionRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) })),\n\tdatabases: z.record(databaseNameSchema, databaseRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) })),\n\tsecrets: z.record(secretNameSchema, secretRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) }))\n});\nfunction hasViewerResources(resources) {\n\treturn Object.values(resources).some((requirements) => Object.values(requirements).some(({ mode }) => mode === \"viewer\"));\n}\nfunction collectAppResources(slates) {\n\tconst declarations = [{\n\t\tconsumer: { type: \"app\" },\n\t\tslate: slates.app\n\t}, ...Object.entries(slates.agents).map(([name, slate]) => ({\n\t\tconsumer: {\n\t\t\tname,\n\t\t\ttype: \"agent\"\n\t\t},\n\t\tslate\n\t}))];\n\treturn {\n\t\tconnections: collectRequirements(\"connections\", declarations, (slate) => slate.connections),\n\t\tdatabases: collectRequirements(\"databases\", declarations, (slate) => slate.databases),\n\t\tsecrets: collectRequirements(\"secrets\", declarations, (slate) => slate.secrets)\n\t};\n}\nfunction resourcesForConsumer(resources, consumer) {\n\treturn {\n\t\tconnections: filterRequirements(resources.connections, consumer),\n\t\tdatabases: filterRequirements(resources.databases, consumer),\n\t\tsecrets: filterRequirements(resources.secrets, consumer)\n\t};\n}\nfunction filterRequirements(requirements, consumer) {\n\treturn Object.fromEntries(Object.entries(requirements).filter(([, requirement]) => requirement.consumers.some((declared) => declared.type === consumer.type && (consumer.type === \"app\" || declared.type === \"agent\" && declared.name === consumer.name))));\n}\nfunction collectRequirements(category, declarations, select) {\n\tconst resources = /* @__PURE__ */ new Map();\n\tfor (const { consumer, slate } of declarations) for (const [name, requirement] of Object.entries(select(slate))) {\n\t\tconst existing = resources.get(name);\n\t\tif (!existing) {\n\t\t\tresources.set(name, {\n\t\t\t\t...requirement,\n\t\t\t\tconsumers: [consumer]\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (existing.mode !== requirement.mode || existing.toolkit !== requirement.toolkit) throw new z.ZodError([{\n\t\t\tcode: \"custom\",\n\t\t\tmessage: `Conflicting ${category} requirement \"${name}\": declarations must agree on mode${category === \"connections\" ? \" and toolkit\" : \"\"}`,\n\t\t\tpath: [\n\t\t\t\t...consumer.type === \"app\" ? [\"app\"] : [\"agents\", consumer.name],\n\t\t\t\tcategory,\n\t\t\t\tname\n\t\t\t]\n\t\t}]);\n\t\texisting.consumers.push(consumer);\n\t}\n\treturn Object.fromEntries(resources);\n}\n\n//#endregion\nexport { appSlatesSchema, collectAppResources, connectionRequirementSchema, credentialModeSchema, databaseNameSchema, databaseRequirementSchema, hasViewerResources, resourceConsumerSchema, resourcesForConsumer, resourcesSchema, secretNameSchema, secretRequirementSchema, slateSchema };","import { slateSchema } from \"./slate.mjs\";\nimport { z } from \"zod\";\nimport { ResourceSchema, ToolSchema } from \"@modelcontextprotocol/core\";\n\n//#region lib/mcp.ts\nconst MCP_MANIFEST_PATH = \"/mcp.json\";\nconst mcpManifestSchema = z.object({\n\tresources: z.array(ResourceSchema.extend({ path: z.string() })),\n\ttools: z.array(ToolSchema.extend({ slate: slateSchema }))\n});\n\n//#endregion\nexport { MCP_MANIFEST_PATH, mcpManifestSchema };","import { glob, readFile } from \"node:fs/promises\"\nimport { dirname, join, relative } from \"node:path\"\nimport { RESOURCE_MIME_TYPE } from \"@modelcontextprotocol/ext-apps/server\"\nimport { MCP_MANIFEST_PATH, mcpManifestSchema } from \"@usecontextlayer/shared/mcp\"\nimport { slateSchema } from \"@usecontextlayer/shared/slate\"\nimport { build, createServer, createServerModuleRunner, type Plugin } from \"vite\"\nimport { viteSingleFile } from \"vite-plugin-singlefile\"\nimport { z } from \"zod\"\nimport type { McpToolModule } from \"@/worker\"\n\nexport function mcpApps(): Plugin {\n\tlet root: string\n\tlet compiled: ReturnType<typeof compile>\n\n\tasync function compile() {\n\t\tconst server = await createServer({\n\t\t\tappType: \"custom\",\n\t\t\tconfigFile: false,\n\t\t\tresolve: { tsconfigPaths: true },\n\t\t\troot,\n\t\t\tserver: { middlewareMode: true },\n\t\t})\n\t\tconst runner = createServerModuleRunner(server.environments.ssr)\n\t\ttry {\n\t\t\tconst tools = []\n\t\t\tfor await (const file of glob(\"mcp/*/index.ts\", { cwd: root })) {\n\t\t\t\tconst { tool } = await runner.import<McpToolModule>(join(root, file))\n\t\t\t\tconst slate = slateSchema.parse(\n\t\t\t\t\tJSON.parse(await readFile(join(root, dirname(file), \"slate.json\"), \"utf8\")),\n\t\t\t\t)\n\t\t\t\tif (\n\t\t\t\t\tObject.keys(slate.connections).length ||\n\t\t\t\t\tObject.keys(slate.databases).length ||\n\t\t\t\t\tObject.keys(slate.secrets).length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`${file}: MCP resource consumers are not implemented yet`)\n\t\t\t\t}\n\t\t\t\ttools.push({\n\t\t\t\t\t...tool,\n\t\t\t\t\tinputSchema: z.toJSONSchema(tool.inputSchema),\n\t\t\t\t\toutputSchema: tool.outputSchema ? z.toJSONSchema(tool.outputSchema) : undefined,\n\t\t\t\t\tslate,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst assets = []\n\t\t\tconst resources = []\n\t\t\tfor await (const file of glob(\"mcp-ui/*/index.html\", { cwd: root })) {\n\t\t\t\tconst name = relative(\"mcp-ui\", dirname(file))\n\t\t\t\tconst result = await build({\n\t\t\t\t\tbuild: { rolldownOptions: { input: join(root, file) }, write: false },\n\t\t\t\t\tconfigFile: false,\n\t\t\t\t\tplugins: [viteSingleFile()],\n\t\t\t\t\tpublicDir: false,\n\t\t\t\t\tresolve: { tsconfigPaths: true },\n\t\t\t\t\troot,\n\t\t\t\t})\n\t\t\t\tif (Array.isArray(result) || !(\"output\" in result)) {\n\t\t\t\t\tthrow new Error(\"MCP View build must produce one bundle\")\n\t\t\t\t}\n\t\t\t\tconst html = result.output.find(\n\t\t\t\t\t(asset) => asset.type === \"asset\" && asset.fileName.endsWith(\".html\"),\n\t\t\t\t)\n\t\t\t\tif (html?.type !== \"asset\") throw new Error(`${file}: missing built HTML`)\n\t\t\t\tconst path = `/mcp-ui/${name}`\n\t\t\t\tassets.push({\n\t\t\t\t\tfileName: `${path.slice(1)}.html`,\n\t\t\t\t\tsource: html.source,\n\t\t\t\t\ttype: \"asset\" as const,\n\t\t\t\t})\n\t\t\t\tresources.push({\n\t\t\t\t\tmimeType: RESOURCE_MIME_TYPE,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\turi: `ui://${name}/index.html`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst manifest = mcpManifestSchema.parse({ resources, tools })\n\t\t\tassets.push({\n\t\t\t\tfileName: MCP_MANIFEST_PATH.slice(1),\n\t\t\t\tsource: JSON.stringify(manifest),\n\t\t\t\ttype: \"asset\" as const,\n\t\t\t})\n\t\t\treturn assets\n\t\t} finally {\n\t\t\tawait runner.close()\n\t\t\tawait server.close()\n\t\t}\n\t}\n\n\treturn {\n\t\tconfigResolved(config) {\n\t\t\troot = config.root\n\t\t},\n\t\tasync generateBundle() {\n\t\t\tif (this.environment.config.consumer !== \"client\") return\n\t\t\tcompiled ??= compile()\n\t\t\tfor (const asset of await compiled) this.emitFile(asset)\n\t\t},\n\t\tname: \"contextlayer-mcp-apps\",\n\t}\n}\n","import { cloudflare } from \"@cloudflare/vite-plugin\"\nimport { getLocalResourcesBindings, localDatabaseSetup } from \"@usecontextlayer/cli/vite\"\nimport type { ConfigEnv } from \"vite\"\nimport { mcpApps } from \"@/mcp-vite\"\n\nexport async function contextlayer({ command }: ConfigEnv) {\n\tconst bindings = command === \"serve\" ? await getLocalResourcesBindings() : undefined\n\treturn [\n\t\tmcpApps(),\n\t\tcloudflare({\n\t\t\tauxiliaryWorkers: [\n\t\t\t\t{\n\t\t\t\t\tconfig: bindings ? { name: bindings.workerName, vars: bindings.vars } : {},\n\t\t\t\t\tconfigPath: \"workers/local-resources/wrangler.jsonc\",\n\t\t\t\t\tdevOnly: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\tconfig: {\n\t\t\t\tassets: { run_worker_first: [\"/*\", \"!/mcp.json\", \"!/mcp-ui/*\"] },\n\t\t\t\t...(bindings\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tservices: [\n\t\t\t\t\t\t\t\t...(bindings.props\n\t\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tbinding: \"TOOLS\",\n\t\t\t\t\t\t\t\t\t\t\t\tentrypoint: \"Tools\",\n\t\t\t\t\t\t\t\t\t\t\t\tprops: bindings.props,\n\t\t\t\t\t\t\t\t\t\t\t\tservice: bindings.workerName,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t: []),\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tbinding: \"DATABASES\",\n\t\t\t\t\t\t\t\t\tentrypoint: \"Databases\",\n\t\t\t\t\t\t\t\t\tprops: bindings.databaseProps,\n\t\t\t\t\t\t\t\t\tservice: bindings.workerName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tpersistState: { path: \".contextlayer/databases\" },\n\t\t\tviteEnvironment: { name: \"ssr\" },\n\t\t}),\n\t\tbindings ? localDatabaseSetup(bindings) : undefined,\n\t]\n}\n"],"mappings":";;;;;;;;;;AAGA,MAAM,uBAAuB,EAAE,KAAK,CAAC,UAAU,OAAO,CAAC;AACvD,MAAM,8BAA8B,EAAE,aAAa;CAClD,MAAM;CACN,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AAC1B,CAAC;AACD,MAAM,mBAAmB,EAAE,OAAO,CAAC,CAAC,MAAM,oBAAoB;AAC9D,MAAM,0BAA0B,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC7E,MAAM,4BAA4B,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC/E,MAAM,qBAAqB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,uBAAuB;AAC1E,MAAM,cAAc,EAAE,aAAa;CAClC,aAAa,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,2BAA2B;CACpE,WAAW,EAAE,OAAO,oBAAoB,yBAAyB,CAAC,CAAC,QAAQ,CAAC,CAAC;CAC7E,SAAS,EAAE,OAAO,kBAAkB,uBAAuB,CAAC,CA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,MAAM,MAAM;EAChC,CAAC;EACD,WAAW,mBAAmB,QAAQ,IAAI,KAAA;CAC3C;AACD"}
1
+ {"version":3,"file":"vite.js","names":[],"sources":["../../shared/dist/declaration.mjs","../../shared/dist/mcp.mjs","../mcp-vite.ts","../vite.ts"],"sourcesContent":["import { z } from \"zod\";\n\n//#region lib/declaration.ts\nconst credentialModeSchema = z.enum([\"viewer\", \"owner\"]);\nconst connectionRequirementSchema = z.strictObject({\n\tmode: credentialModeSchema,\n\ttoolkit: z.string().min(1)\n});\nconst secretNameSchema = z.string().regex(/^[A-Z_][A-Z0-9_]*$/);\nconst secretRequirementSchema = z.strictObject({ mode: credentialModeSchema });\nconst databaseRequirementSchema = z.strictObject({ mode: credentialModeSchema });\nconst databaseSlugSchema = z.string().min(1).regex(/^(?!\\.{1,2}$)[^/\\\\]+$/);\nconst declarationSchema = z.strictObject({\n\tconnections: z.record(z.string().min(1), connectionRequirementSchema),\n\tdatabases: z.record(databaseSlugSchema, databaseRequirementSchema).default({}),\n\tsecrets: z.record(secretNameSchema, secretRequirementSchema).default({})\n});\nconst slateDeclarationsSchema = z.strictObject({\n\tagents: z.record(z.string().min(1), declarationSchema),\n\tapp: declarationSchema\n});\nconst resourceConsumerSchema = z.discriminatedUnion(\"type\", [z.strictObject({ type: z.literal(\"app\") }), z.strictObject({\n\tname: z.string().min(1),\n\ttype: z.literal(\"agent\")\n})]);\nconst resourcesSchema = declarationSchema.extend({\n\tconnections: z.record(z.string().min(1), connectionRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) })),\n\tdatabases: z.record(databaseSlugSchema, databaseRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) })),\n\tsecrets: z.record(secretNameSchema, secretRequirementSchema.extend({ consumers: z.array(resourceConsumerSchema) }))\n});\nfunction hasViewerResources(resources) {\n\treturn Object.values(resources).some((requirements) => Object.values(requirements).some(({ mode }) => mode === \"viewer\"));\n}\nfunction collectSlateResources(slateDeclarations) {\n\tconst declarations = [{\n\t\tconsumer: { type: \"app\" },\n\t\tdeclaration: slateDeclarations.app\n\t}, ...Object.entries(slateDeclarations.agents).map(([name, declaration]) => ({\n\t\tconsumer: {\n\t\t\tname,\n\t\t\ttype: \"agent\"\n\t\t},\n\t\tdeclaration\n\t}))];\n\treturn {\n\t\tconnections: collectRequirements(\"connections\", declarations, (declaration) => declaration.connections),\n\t\tdatabases: collectRequirements(\"databases\", declarations, (declaration) => declaration.databases),\n\t\tsecrets: collectRequirements(\"secrets\", declarations, (declaration) => declaration.secrets)\n\t};\n}\nfunction resourcesForConsumer(resources, consumer) {\n\treturn {\n\t\tconnections: filterRequirements(resources.connections, consumer),\n\t\tdatabases: filterRequirements(resources.databases, consumer),\n\t\tsecrets: filterRequirements(resources.secrets, consumer)\n\t};\n}\nfunction filterRequirements(requirements, consumer) {\n\treturn Object.fromEntries(Object.entries(requirements).filter(([, requirement]) => requirement.consumers.some((declared) => declared.type === consumer.type && (consumer.type === \"app\" || declared.type === \"agent\" && declared.name === consumer.name))));\n}\nfunction collectRequirements(category, declarations, select) {\n\tconst resources = /* @__PURE__ */ new Map();\n\tfor (const { consumer, declaration } of declarations) for (const [key, requirement] of Object.entries(select(declaration))) {\n\t\tconst existing = resources.get(key);\n\t\tif (!existing) {\n\t\t\tresources.set(key, {\n\t\t\t\t...requirement,\n\t\t\t\tconsumers: [consumer]\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (existing.mode !== requirement.mode || existing.toolkit !== requirement.toolkit) throw new z.ZodError([{\n\t\t\tcode: \"custom\",\n\t\t\tmessage: `Conflicting ${category} requirement \"${key}\": declarations must agree on mode${category === \"connections\" ? \" and toolkit\" : \"\"}`,\n\t\t\tpath: [\n\t\t\t\t...consumer.type === \"app\" ? [\"app\"] : [\"agents\", consumer.name],\n\t\t\t\tcategory,\n\t\t\t\tkey\n\t\t\t]\n\t\t}]);\n\t\texisting.consumers.push(consumer);\n\t}\n\treturn Object.fromEntries(resources);\n}\n\n//#endregion\nexport { collectSlateResources, connectionRequirementSchema, credentialModeSchema, databaseRequirementSchema, databaseSlugSchema, declarationSchema, hasViewerResources, resourceConsumerSchema, resourcesForConsumer, resourcesSchema, secretNameSchema, secretRequirementSchema, slateDeclarationsSchema };","import { declarationSchema } from \"./declaration.mjs\";\nimport { z } from \"zod\";\nimport { ResourceSchema, ToolSchema } from \"@modelcontextprotocol/core\";\n\n//#region lib/mcp.ts\nconst MCP_MANIFEST_PATH = \"/mcp.json\";\nconst mcpManifestSchema = z.object({\n\tresources: z.array(ResourceSchema.extend({ path: z.string() })),\n\ttools: z.array(ToolSchema.extend({ declaration: declarationSchema }))\n});\n\n//#endregion\nexport { MCP_MANIFEST_PATH, mcpManifestSchema };","import { glob, readFile } from \"node:fs/promises\"\nimport { dirname, join, relative } from \"node:path\"\nimport { RESOURCE_MIME_TYPE } from \"@modelcontextprotocol/ext-apps/server\"\nimport { declarationSchema } from \"@usecontextlayer/shared/declaration\"\nimport { MCP_MANIFEST_PATH, mcpManifestSchema } from \"@usecontextlayer/shared/mcp\"\nimport { build, createServer, createServerModuleRunner, type Plugin } from \"vite\"\nimport { viteSingleFile } from \"vite-plugin-singlefile\"\nimport { z } from \"zod\"\nimport type { McpToolModule } from \"@/worker\"\n\nexport function mcpApps(): Plugin {\n\tlet root: string\n\tlet compiled: ReturnType<typeof compile>\n\n\tasync function compile() {\n\t\tconst server = await createServer({\n\t\t\tappType: \"custom\",\n\t\t\tconfigFile: false,\n\t\t\tresolve: { tsconfigPaths: true },\n\t\t\troot,\n\t\t\tserver: { middlewareMode: true },\n\t\t})\n\t\tconst runner = createServerModuleRunner(server.environments.ssr)\n\t\ttry {\n\t\t\tconst tools = []\n\t\t\tfor await (const file of glob(\"mcp/*/index.ts\", { cwd: root })) {\n\t\t\t\tconst { tool } = await runner.import<McpToolModule>(join(root, file))\n\t\t\t\tconst declaration = declarationSchema.parse(\n\t\t\t\t\tJSON.parse(await readFile(join(root, dirname(file), \"slate.json\"), \"utf8\")),\n\t\t\t\t)\n\t\t\t\tif (\n\t\t\t\t\tObject.keys(declaration.connections).length ||\n\t\t\t\t\tObject.keys(declaration.databases).length ||\n\t\t\t\t\tObject.keys(declaration.secrets).length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`${file}: MCP resource consumers are not implemented yet`)\n\t\t\t\t}\n\t\t\t\ttools.push({\n\t\t\t\t\t...tool,\n\t\t\t\t\tdeclaration,\n\t\t\t\t\tinputSchema: z.toJSONSchema(tool.inputSchema),\n\t\t\t\t\toutputSchema: tool.outputSchema ? z.toJSONSchema(tool.outputSchema) : undefined,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst assets = []\n\t\t\tconst resources = []\n\t\t\tfor await (const file of glob(\"mcp-ui/*/index.html\", { cwd: root })) {\n\t\t\t\tconst name = relative(\"mcp-ui\", dirname(file))\n\t\t\t\tconst result = await build({\n\t\t\t\t\tbuild: { rolldownOptions: { input: join(root, file) }, write: false },\n\t\t\t\t\tconfigFile: false,\n\t\t\t\t\tplugins: [viteSingleFile()],\n\t\t\t\t\tpublicDir: false,\n\t\t\t\t\tresolve: { tsconfigPaths: true },\n\t\t\t\t\troot,\n\t\t\t\t})\n\t\t\t\tif (Array.isArray(result) || !(\"output\" in result)) {\n\t\t\t\t\tthrow new Error(\"MCP View build must produce one bundle\")\n\t\t\t\t}\n\t\t\t\tconst html = result.output.find(\n\t\t\t\t\t(asset) => asset.type === \"asset\" && asset.fileName.endsWith(\".html\"),\n\t\t\t\t)\n\t\t\t\tif (html?.type !== \"asset\") throw new Error(`${file}: missing built HTML`)\n\t\t\t\tconst path = `/mcp-ui/${name}`\n\t\t\t\tassets.push({\n\t\t\t\t\tfileName: `${path.slice(1)}.html`,\n\t\t\t\t\tsource: html.source,\n\t\t\t\t\ttype: \"asset\" as const,\n\t\t\t\t})\n\t\t\t\tresources.push({\n\t\t\t\t\tmimeType: RESOURCE_MIME_TYPE,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\turi: `ui://${name}/index.html`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst manifest = mcpManifestSchema.parse({ resources, tools })\n\t\t\tassets.push({\n\t\t\t\tfileName: MCP_MANIFEST_PATH.slice(1),\n\t\t\t\tsource: JSON.stringify(manifest),\n\t\t\t\ttype: \"asset\" as const,\n\t\t\t})\n\t\t\treturn assets\n\t\t} finally {\n\t\t\tawait runner.close()\n\t\t\tawait server.close()\n\t\t}\n\t}\n\n\treturn {\n\t\tconfigResolved(config) {\n\t\t\troot = config.root\n\t\t},\n\t\tasync generateBundle() {\n\t\t\tif (this.environment.config.consumer !== \"client\") return\n\t\t\tcompiled ??= compile()\n\t\t\tfor (const asset of await compiled) this.emitFile(asset)\n\t\t},\n\t\tname: \"contextlayer-mcp-apps\",\n\t}\n}\n","import { cloudflare } from \"@cloudflare/vite-plugin\"\nimport {\n\tgetLocalResourcesBindings,\n\tlocalDatabaseProvisioning,\n} from \"@usecontextlayer/cli/vite\"\nimport type { ConfigEnv } from \"vite\"\nimport { mcpApps } from \"@/mcp-vite\"\n\nexport async function contextlayer({ command }: ConfigEnv) {\n\tconst bindings = command === \"serve\" ? await getLocalResourcesBindings() : undefined\n\treturn [\n\t\tmcpApps(),\n\t\tcloudflare({\n\t\t\tauxiliaryWorkers: [\n\t\t\t\t{\n\t\t\t\t\tconfig: bindings ? { name: bindings.workerName, vars: bindings.vars } : {},\n\t\t\t\t\tconfigPath: \"workers/local-resources/wrangler.jsonc\",\n\t\t\t\t\tdevOnly: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\tconfig: {\n\t\t\t\tassets: { run_worker_first: [\"/*\", \"!/mcp.json\", \"!/mcp-ui/*\"] },\n\t\t\t\t...(bindings\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tservices: [\n\t\t\t\t\t\t\t\t...(bindings.props\n\t\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tbinding: \"TOOLS\",\n\t\t\t\t\t\t\t\t\t\t\t\tentrypoint: \"Tools\",\n\t\t\t\t\t\t\t\t\t\t\t\tprops: bindings.props,\n\t\t\t\t\t\t\t\t\t\t\t\tservice: bindings.workerName,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t: []),\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tbinding: \"DATABASES\",\n\t\t\t\t\t\t\t\t\tentrypoint: \"Databases\",\n\t\t\t\t\t\t\t\t\tprops: bindings.databaseProps,\n\t\t\t\t\t\t\t\t\tservice: bindings.workerName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tpersistState: { path: \".contextlayer/databases\" },\n\t\t\tviteEnvironment: { name: \"ssr\" },\n\t\t}),\n\t\tbindings ? localDatabaseProvisioning(bindings) : undefined,\n\t]\n}\n"],"mappings":";;;;;;;;;;AAGA,MAAM,uBAAuB,EAAE,KAAK,CAAC,UAAU,OAAO,CAAC;AACvD,MAAM,8BAA8B,EAAE,aAAa;CAClD,MAAM;CACN,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AAC1B,CAAC;AACD,MAAM,mBAAmB,EAAE,OAAO,CAAC,CAAC,MAAM,oBAAoB;AAC9D,MAAM,0BAA0B,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC7E,MAAM,4BAA4B,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC/E,MAAM,qBAAqB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,uBAAuB;AAC1E,MAAM,oBAAoB,EAAE,aAAa;CACxC,aAAa,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,2BAA2B;CACpE,WAAW,EAAE,OAAO,oBAAoB,yBAAyB,CAAC,CAAC,QAAQ,CAAC,CAAC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C;GACL;GACA,cAAc,EAAE,MAAM,0BAA0B;GAChD,iBAAiB,EAAE,MAAM,MAAM;EAChC,CAAC;EACD,WAAW,0BAA0B,QAAQ,IAAI,KAAA;CAClD;AACD"}
package/dist/worker.d.ts CHANGED
@@ -9,7 +9,7 @@ interface LocalBindings {
9
9
  DATABASES: Databases;
10
10
  TOOLS: ToolsBinding;
11
11
  }
12
- interface AppProps {
12
+ interface SlateWorkerProps {
13
13
  databases: Databases;
14
14
  tools: ToolsBinding;
15
15
  mcpTool?: string;
@@ -22,12 +22,12 @@ export interface McpToolModule {
22
22
  };
23
23
  handler(args: unknown, tools: Tools): CallToolResult | Promise<CallToolResult>;
24
24
  }
25
- export type App = Required<Pick<ExportedHandler<LocalBindings, unknown, unknown, AppProps>, "fetch">>;
26
- export declare function createApp({ build, mode, development, mcp }: {
25
+ export type SlateWorker = Required<Pick<ExportedHandler<LocalBindings, unknown, unknown, SlateWorkerProps>, "fetch">>;
26
+ export declare function createSlateWorker({ build, mode, development, mcp }: {
27
27
  build: Parameters<typeof createRequestHandler>[0];
28
28
  mode: string;
29
29
  development: boolean;
30
30
  mcp?: Record<string, McpToolModule>;
31
- }): App;
31
+ }): SlateWorker;
32
32
  //#endregion
33
33
  //# sourceMappingURL=worker.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker.d.ts","names":[],"sources":["../worker.ts"],"mappings":";;;;;;;UAOU;EACT,WAAW;EACX,OAAO;;UAGE;EACT,WAAW;EACX,OAAO;EACP;;iBAGgB;EAChB,MAAM,KAAK;IACV;IACA,aAAa,EAAE;IACf,eAAe,EAAE;;EAElB,QAAQ,eAAe,OAAO,QAAQ,iBAAiB,QAAQ;;YAGpD,MAAM,SACjB,KAAK,gBAAgB,iCAAiC;wBAGvC,YACf,OACA,MACA,aACA;EAEA,OAAO,kBAAkB;EACzB;EACA;EACA,MAAM,eAAe;IAClB"}
1
+ {"version":3,"file":"worker.d.ts","names":[],"sources":["../worker.ts"],"mappings":";;;;;;;UAOU;EACT,WAAW;EACX,OAAO;;UAGE;EACT,WAAW;EACX,OAAO;EACP;;iBAGgB;EAChB,MAAM,KAAK;IACV;IACA,aAAa,EAAE;IACf,eAAe,EAAE;;EAElB,QAAQ,eAAe,OAAO,QAAQ,iBAAiB,QAAQ;;YAGpD,cAAc,SACzB,KAAK,gBAAgB,iCAAiC;wBAGvC,oBACf,OACA,MACA,aACA;EAEA,OAAO,kBAAkB;EACzB;EACA;EACA,MAAM,eAAe;IAClB"}
package/dist/worker.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { n as toolsContext, t as databasesContext } from "./sdk-BMmzPuDi.js";
2
2
  import { RouterContextProvider, createRequestHandler } from "react-router";
3
3
  //#region worker.ts
4
- function createApp({ build, mode, development, mcp = {} }) {
4
+ function createSlateWorker({ build, mode, development, mcp = {} }) {
5
5
  const requestHandler = createRequestHandler(build, mode);
6
6
  return { async fetch(request, env, ctx) {
7
7
  if (ctx.props.mcpTool) {
@@ -24,6 +24,6 @@ function createTools(binding) {
24
24
  } };
25
25
  }
26
26
  //#endregion
27
- export { createApp };
27
+ export { createSlateWorker };
28
28
 
29
29
  //# sourceMappingURL=worker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","names":[],"sources":["../worker.ts"],"sourcesContent":["import type { ToolConfig } from \"@modelcontextprotocol/ext-apps/server\"\nimport type { CallToolResult } from \"@modelcontextprotocol/server\"\nimport type { ToolsBinding } from \"@usecontextlayer/shared/tools\"\nimport { createRequestHandler, RouterContextProvider } from \"react-router\"\nimport type { z } from \"zod\"\nimport { type Databases, databasesContext, type Tools, toolsContext } from \"@/index\"\n\ninterface LocalBindings {\n\tDATABASES: Databases\n\tTOOLS: ToolsBinding\n}\n\ninterface AppProps {\n\tdatabases: Databases\n\ttools: ToolsBinding\n\tmcpTool?: string\n}\n\nexport interface McpToolModule {\n\ttool: Omit<ToolConfig, \"inputSchema\" | \"outputSchema\"> & {\n\t\tname: string\n\t\tinputSchema: z.ZodType\n\t\toutputSchema?: z.ZodType\n\t}\n\thandler(args: unknown, tools: Tools): CallToolResult | Promise<CallToolResult>\n}\n\nexport type App = Required<\n\tPick<ExportedHandler<LocalBindings, unknown, unknown, AppProps>, \"fetch\">\n>\n\nexport function createApp({\n\tbuild,\n\tmode,\n\tdevelopment,\n\tmcp = {},\n}: {\n\tbuild: Parameters<typeof createRequestHandler>[0]\n\tmode: string\n\tdevelopment: boolean\n\tmcp?: Record<string, McpToolModule>\n}): App {\n\tconst requestHandler = createRequestHandler(build, mode)\n\treturn {\n\t\tasync fetch(request, env, ctx) {\n\t\t\tif (ctx.props.mcpTool) {\n\t\t\t\tconst module = Object.values(mcp).find(\n\t\t\t\t\t({ tool }) => tool.name === ctx.props.mcpTool,\n\t\t\t\t)\n\t\t\t\tif (!module) throw new Error(`Unknown MCP tool: ${ctx.props.mcpTool}`)\n\t\t\t\tconst args = await module.tool.inputSchema.parseAsync(await request.json())\n\t\t\t\treturn Response.json(await module.handler(args, createTools(ctx.props.tools)))\n\t\t\t}\n\t\t\tconst context = new RouterContextProvider()\n\t\t\tcontext.set(databasesContext, development ? env.DATABASES : ctx.props.databases)\n\t\t\tcontext.set(toolsContext, createTools(development ? env.TOOLS : ctx.props.tools))\n\t\t\treturn requestHandler(request, context)\n\t\t},\n\t}\n}\n\nfunction createTools(binding: ToolsBinding): Tools {\n\treturn {\n\t\tasync call(...args) {\n\t\t\tconst result = await binding.call(...args)\n\t\t\tif (result instanceof Response) throw result\n\t\t\treturn result\n\t\t},\n\t}\n}\n"],"mappings":";;;AA+BA,SAAgB,UAAU,EACzB,OACA,MACA,aACA,MAAM,CAAC,KAMA;CACP,MAAM,iBAAiB,qBAAqB,OAAO,IAAI;CACvD,OAAO,EACN,MAAM,MAAM,SAAS,KAAK,KAAK;EAC9B,IAAI,IAAI,MAAM,SAAS;GACtB,MAAM,SAAS,OAAO,OAAO,GAAG,CAAC,CAAC,MAChC,EAAE,WAAW,KAAK,SAAS,IAAI,MAAM,OACvC;GACA,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,qBAAqB,IAAI,MAAM,SAAS;GACrE,MAAM,OAAO,MAAM,OAAO,KAAK,YAAY,WAAW,MAAM,QAAQ,KAAK,CAAC;GAC1E,OAAO,SAAS,KAAK,MAAM,OAAO,QAAQ,MAAM,YAAY,IAAI,MAAM,KAAK,CAAC,CAAC;EAC9E;EACA,MAAM,UAAU,IAAI,sBAAsB;EAC1C,QAAQ,IAAI,kBAAkB,cAAc,IAAI,YAAY,IAAI,MAAM,SAAS;EAC/E,QAAQ,IAAI,cAAc,YAAY,cAAc,IAAI,QAAQ,IAAI,MAAM,KAAK,CAAC;EAChF,OAAO,eAAe,SAAS,OAAO;CACvC,EACD;AACD;AAEA,SAAS,YAAY,SAA8B;CAClD,OAAO,EACN,MAAM,KAAK,GAAG,MAAM;EACnB,MAAM,SAAS,MAAM,QAAQ,KAAK,GAAG,IAAI;EACzC,IAAI,kBAAkB,UAAU,MAAM;EACtC,OAAO;CACR,EACD;AACD"}
1
+ {"version":3,"file":"worker.js","names":[],"sources":["../worker.ts"],"sourcesContent":["import type { ToolConfig } from \"@modelcontextprotocol/ext-apps/server\"\nimport type { CallToolResult } from \"@modelcontextprotocol/server\"\nimport type { ToolsBinding } from \"@usecontextlayer/shared/tools\"\nimport { createRequestHandler, RouterContextProvider } from \"react-router\"\nimport type { z } from \"zod\"\nimport { type Databases, databasesContext, type Tools, toolsContext } from \"@/index\"\n\ninterface LocalBindings {\n\tDATABASES: Databases\n\tTOOLS: ToolsBinding\n}\n\ninterface SlateWorkerProps {\n\tdatabases: Databases\n\ttools: ToolsBinding\n\tmcpTool?: string\n}\n\nexport interface McpToolModule {\n\ttool: Omit<ToolConfig, \"inputSchema\" | \"outputSchema\"> & {\n\t\tname: string\n\t\tinputSchema: z.ZodType\n\t\toutputSchema?: z.ZodType\n\t}\n\thandler(args: unknown, tools: Tools): CallToolResult | Promise<CallToolResult>\n}\n\nexport type SlateWorker = Required<\n\tPick<ExportedHandler<LocalBindings, unknown, unknown, SlateWorkerProps>, \"fetch\">\n>\n\nexport function createSlateWorker({\n\tbuild,\n\tmode,\n\tdevelopment,\n\tmcp = {},\n}: {\n\tbuild: Parameters<typeof createRequestHandler>[0]\n\tmode: string\n\tdevelopment: boolean\n\tmcp?: Record<string, McpToolModule>\n}): SlateWorker {\n\tconst requestHandler = createRequestHandler(build, mode)\n\treturn {\n\t\tasync fetch(request, env, ctx) {\n\t\t\tif (ctx.props.mcpTool) {\n\t\t\t\tconst module = Object.values(mcp).find(\n\t\t\t\t\t({ tool }) => tool.name === ctx.props.mcpTool,\n\t\t\t\t)\n\t\t\t\tif (!module) throw new Error(`Unknown MCP tool: ${ctx.props.mcpTool}`)\n\t\t\t\tconst args = await module.tool.inputSchema.parseAsync(await request.json())\n\t\t\t\treturn Response.json(await module.handler(args, createTools(ctx.props.tools)))\n\t\t\t}\n\t\t\tconst context = new RouterContextProvider()\n\t\t\tcontext.set(databasesContext, development ? env.DATABASES : ctx.props.databases)\n\t\t\tcontext.set(toolsContext, createTools(development ? env.TOOLS : ctx.props.tools))\n\t\t\treturn requestHandler(request, context)\n\t\t},\n\t}\n}\n\nfunction createTools(binding: ToolsBinding): Tools {\n\treturn {\n\t\tasync call(...args) {\n\t\t\tconst result = await binding.call(...args)\n\t\t\tif (result instanceof Response) throw result\n\t\t\treturn result\n\t\t},\n\t}\n}\n"],"mappings":";;;AA+BA,SAAgB,kBAAkB,EACjC,OACA,MACA,aACA,MAAM,CAAC,KAMQ;CACf,MAAM,iBAAiB,qBAAqB,OAAO,IAAI;CACvD,OAAO,EACN,MAAM,MAAM,SAAS,KAAK,KAAK;EAC9B,IAAI,IAAI,MAAM,SAAS;GACtB,MAAM,SAAS,OAAO,OAAO,GAAG,CAAC,CAAC,MAChC,EAAE,WAAW,KAAK,SAAS,IAAI,MAAM,OACvC;GACA,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,qBAAqB,IAAI,MAAM,SAAS;GACrE,MAAM,OAAO,MAAM,OAAO,KAAK,YAAY,WAAW,MAAM,QAAQ,KAAK,CAAC;GAC1E,OAAO,SAAS,KAAK,MAAM,OAAO,QAAQ,MAAM,YAAY,IAAI,MAAM,KAAK,CAAC,CAAC;EAC9E;EACA,MAAM,UAAU,IAAI,sBAAsB;EAC1C,QAAQ,IAAI,kBAAkB,cAAc,IAAI,YAAY,IAAI,MAAM,SAAS;EAC/E,QAAQ,IAAI,cAAc,YAAY,cAAc,IAAI,QAAQ,IAAI,MAAM,KAAK,CAAC;EAChF,OAAO,eAAe,SAAS,OAAO;CACvC,EACD;AACD;AAEA,SAAS,YAAY,SAA8B;CAClD,OAAO,EACN,MAAM,KAAK,GAAG,MAAM;EACnB,MAAM,SAAS,MAAM,QAAQ,KAAK,GAAG,IAAI;EACzC,IAAI,kBAAkB,UAAU,MAAM;EACtC,OAAO;CACR,EACD;AACD"}
@@ -1,4 +1,4 @@
1
- // This example's public/slate.json declares the connection; follow the SDK README to copy the app files and assign a Gmail account.
1
+ // This example's public/slate.json declares the connection; follow the SDK README to copy the app files and assign a connected Gmail account.
2
2
  import { toolsContext } from "@usecontextlayer/sdk"
3
3
  import { type LoaderFunctionArgs, useLoaderData } from "react-router"
4
4
  import { z } from "zod"
@@ -32,7 +32,7 @@ export default function Home() {
32
32
  <main className="mx-auto max-w-3xl p-8">
33
33
  <h1 className="text-2xl font-semibold">Your Gmail inbox</h1>
34
34
  <p className="mt-2 text-sm text-gray-500">
35
- Fetched by this page's server loader through your assigned Gmail connection.
35
+ Fetched by this page's server loader through your connected Gmail account.
36
36
  </p>
37
37
  <ul className="mt-6 divide-y divide-gray-200">
38
38
  {loaderData.messages.map((message) => (
package/package.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "drizzle-orm": "0.45.3",
8
8
  "vite-plugin-singlefile": "2.3.3",
9
9
  "zod": "^4.6.5",
10
- "@usecontextlayer/cli": "0.15.0"
10
+ "@usecontextlayer/cli": "0.16.1"
11
11
  },
12
12
  "devDependencies": {
13
13
  "@cloudflare/vite-plugin": "^1.62.4",
@@ -22,7 +22,7 @@
22
22
  "typescript": "latest",
23
23
  "vite": "^8.3.2",
24
24
  "vitest": "^4.1.11",
25
- "@usecontextlayer/shared": "0.15.0"
25
+ "@usecontextlayer/shared": "0.16.1"
26
26
  },
27
27
  "exports": {
28
28
  ".": {
@@ -50,6 +50,7 @@
50
50
  "dist",
51
51
  "examples"
52
52
  ],
53
+ "license": "MIT",
53
54
  "name": "@usecontextlayer/sdk",
54
55
  "peerDependencies": {
55
56
  "@cloudflare/vite-plugin": "^1.62.4",
@@ -59,7 +60,7 @@
59
60
  "vite": "^8.3.2"
60
61
  },
61
62
  "type": "module",
62
- "version": "0.15.0",
63
+ "version": "0.16.1",
63
64
  "scripts": {
64
65
  "build": "tsdown",
65
66
  "dev:watch": "tsdown --watch",