foldkit-agent-native 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,27 +1,57 @@
1
1
  # `foldkit-agent-native`
2
2
 
3
- Compiles a [`foldkit-agent`](https://github.com/doeixd/foldkit-plus/tree/main/packages/agent) contract into
4
- [Agent Native](https://github.com/BuilderIO/agent-native) actions.
5
-
6
- Agent Native is a framework for describing what an application can do as
7
- registered **actions** an agent host can call. This package derives those
8
- actions from the contract, so the capabilities an agent gets are exactly the
9
- Messages `update` already handles, and the generated `run` only dispatches.
3
+ Compiles a [`foldkit-agent`](../agent) contract into [Agent Native](https://github.com/BuilderIO/agent-native)
4
+ actions.
5
+
6
+ Use it when the host application already uses Agent Native's action registry and
7
+ you want those actions to be the **same capabilities** your Foldkit application
8
+ already exposes. The generated action delegates validation, availability,
9
+ authorization, dispatch, and completion back to a bound `AgentRuntime`; it does
10
+ not reimplement application behavior.
11
+
12
+ ```text
13
+ Foldkit application
14
+ |
15
+ v
16
+ AssistantAgent protocol-neutral contract
17
+ |
18
+ | AgentBuilder.bind(...)
19
+ v
20
+ AgentRuntime live Model + dispatch + policy
21
+ ^
22
+ |
23
+ resolveRuntime(ctx)
24
+ |
25
+ foldkit-agent-native adapter
26
+ |
27
+ v
28
+ Agent Native action registry
29
+ ```
10
30
 
11
- It is checked against `@agent-native/core@0.177.1`; the integration suite uses
12
- the real package registry, tool runtime, and schema wrapper. Full HTTP/MCP/A2A
13
- deployments remain outside this package's test suite.
31
+ Application behavior still ends in the existing Foldkit Message and `update`.
32
+ This package is an adapter, not a second agent architecture.
14
33
 
15
34
  ## Install
16
35
 
17
36
  ```bash
18
- pnpm add foldkit-agent foldkit-agent-native
37
+ pnpm add foldkit-agent foldkit-agent-native @agent-native/core
19
38
  ```
20
39
 
21
40
  `foldkit`, `effect`, `foldkit-agent`, and `@agent-native/core` are peer
22
41
  dependencies.
23
42
 
24
- ## What it does
43
+ ## Sixty seconds: generate actions
44
+
45
+ Assume the application already declared a protocol-neutral contract:
46
+
47
+ ```ts
48
+ const AgentBuilder = Agent.forApplication(App).withPrincipal<Principal>()
49
+ const AssistantAgent = AgentBuilder.make({ ... })
50
+ ```
51
+
52
+ Agent Native needs a static action registry, but the live Model and principal
53
+ belong to the caller. Register the contract once and resolve the bound runtime
54
+ per invocation:
25
55
 
26
56
  ```ts
27
57
  import { AgentNative } from 'foldkit-agent-native'
@@ -29,127 +59,215 @@ import { registerPackageActions } from '@agent-native/core/server'
29
59
 
30
60
  registerPackageActions(
31
61
  AgentNative.actions({
32
- definition: AppAgent,
33
- resolveRuntime: ctx => runtimeFor(ctx),
62
+ definition: AssistantAgent,
63
+ resolveRuntime: context => runtimeFor(context),
34
64
  }),
35
65
  )
36
66
  ```
37
67
 
38
- One exposed capability becomes one entry, keyed by capability name, with its
39
- description, advertised parameters and schema taken from the contract. Each
40
- entry states `http: POST`, `requiresAuth: true`, and `readOnly: false` — a
41
- capability dispatches a Message, so it is a write, and claiming otherwise would
42
- let plan mode run it for real.
68
+ `runtimeFor(context)` returns an `AgentRuntime` already bound to the correct live
69
+ application and principal:
43
70
 
44
- Nothing is written to disk. A registry has no file to go stale, so a removed
45
- capability cannot leave behind an action that is still callable.
71
+ ```ts
72
+ const runtimeFor = (context: HostContext) =>
73
+ AgentBuilder.bind({
74
+ definition: AssistantAgent,
75
+ host: hostFor(context),
76
+ principal: () => principalFor(context),
77
+ })
78
+ ```
46
79
 
47
- `resolveRuntime` is called **per invocation**, not once at registration, because
48
- which Model a caller means depends on who is calling. The Runtime it returns must
49
- already be bound for that caller: when a contract declares `authorize`,
50
- `Agent.bind` requires a `principal` provider, so the identity mapping stays with
51
- the application rather than being guessed from `userEmail`.
80
+ That distinction is the heart of this adapter:
81
+
82
+ ```text
83
+ static
84
+ AssistantAgent
85
+ |
86
+ v
87
+ Agent Native action descriptions
88
+
89
+ per invocation
90
+ verified host caller/context
91
+ |
92
+ v
93
+ resolveRuntime(ctx)
94
+ |
95
+ v
96
+ AgentRuntime
97
+ |
98
+ v
99
+ availability -> authorization -> Message -> update
100
+ ```
52
101
 
53
- ## The dependency direction
102
+ The registry describes capabilities. The bound runtime decides whether a
103
+ particular caller may use one **right now**.
54
104
 
55
- Foldkit stays the source of truth. A generated `run` **only dispatches** —
56
- application behaviour stays in `update`, which is the entire reason for
57
- generating these rather than writing a second action layer beside the state
58
- machine.
105
+ ## What a capability becomes
59
106
 
60
- The action layer adds no authority of its own either. Availability,
61
- authorization and input validation all still happen in the contract, and the
62
- tests assert that an action refuses exactly what the contract refuses.
107
+ One exposed capability becomes one Agent Native action keyed by capability
108
+ name:
109
+
110
+ | `foldkit-agent` | Agent Native |
111
+ | --- | --- |
112
+ | capability name | action name |
113
+ | description | action description |
114
+ | encoded input Schema | action parameter schema |
115
+ | `AgentRuntime` dispatch | `run` |
116
+ | completion contract | returned success/failure outcome |
117
+
118
+ Each generated entry declares `http: POST`, `requiresAuth: true`, and
119
+ `readOnly: false`. A capability can dispatch a Message, so advertising it as
120
+ read-only could let a planning surface execute real application behavior under
121
+ the wrong assumption.
122
+
123
+ Nothing is written to disk. The adapter returns the action record Agent Native
124
+ expects; the host decides how that registry is loaded and deployed.
125
+
126
+ ## Runtime and identity
127
+
128
+ `resolveRuntime` runs **per invocation**, not once when actions are registered.
129
+ That is necessary because the action description is static while the Model and
130
+ principal are caller-specific.
131
+
132
+ When a contract declares `authorize`, the runtime must be bound with a principal
133
+ provider of the matching type. This adapter intentionally does not infer
134
+ application identity from arbitrary Agent Native context fields such as an email
135
+ address. Mapping an authenticated host caller to your application principal
136
+ belongs to the host/application boundary.
137
+
138
+ Availability is dynamic too. A capability can remain present in the static Agent
139
+ Native registry while being unavailable in the current Model; the bound runtime
140
+ refuses it at call time.
63
141
 
64
142
  ## What `run` returns
65
143
 
66
- `run` never throws for a contract failure. Unavailable, unauthorized, a failed
67
- completion, or input the runtime itself rejects all resolve to
68
- `{ ok: false, message }`; Agent Native records the call as completed and
69
- serializes that object as the tool output. A surface that decides success from
70
- the action's status alone therefore reads a refusal as a success -- read `ok`
71
- instead. Only a host defect is caught, and it is flattened to a generic message
72
- so application internals never reach the caller.
144
+ Application refusals are returned as application output, not thrown as adapter
145
+ crashes:
146
+
147
+ ```ts
148
+ { ok: false, message: '…' }
149
+ ```
150
+
151
+ That includes unavailable, unauthorized, cancelled, invalid-input, and failed
152
+ completion outcomes.
153
+
154
+ A successful dispatch/completion returns `ok: true`. Agent Native may consider
155
+ the framework-level action invocation itself complete, so consumers should read
156
+ the returned `ok` value rather than assuming framework completion means the
157
+ application accepted or completed the operation.
158
+
159
+ Only host/adapter defects are flattened to a generic failure message. Internal
160
+ application errors are not exposed to the caller.
161
+
162
+ ## Why generate actions instead of writing them twice?
163
+
164
+ The dependency direction stays one-way:
165
+
166
+ ```text
167
+ Foldkit Message + update
168
+ |
169
+ foldkit-agent capability
170
+ |
171
+ Agent Native action
172
+ ```
173
+
174
+ Availability, authorization, input validation, and completion remain in the
175
+ contract/runtime. The generated action adds no authority and no second
176
+ implementation of the transition.
73
177
 
74
- ## The schema bridge
178
+ If the contract changes, the generated registry changes with it instead of
179
+ leaving a hand-written action beside the application that can drift.
75
180
 
76
- The adapter exposes the encoded input schema as a Standard Schema validator,
77
- rejecting undeclared fields. It preserves encoded values for `dispatchUnknown`
78
- to decode once, including transforming schemas such as `NumberFromString`.
181
+ An application-local Agent Native action can still override an inherited/package
182
+ action according to Agent Native's own registry rules.
79
183
 
80
- The subtlety is which conversion, and it fails silently:
184
+ ## Schema bridge
81
185
 
82
- | | `validate` | advertised parameters |
186
+ This section is implementation/compatibility detail; it is not required to use
187
+ the adapter.
188
+
189
+ The adapter exposes the capability's **encoded** input Schema as a Standard
190
+ Schema validator and advertises the corresponding JSON Schema to Agent Native.
191
+ That preserves the same boundary `foldkit-agent` uses for transforming schemas
192
+ such as `NumberFromString`: Agent Native validates the encoded input, then the
193
+ bound runtime performs the application's single decode before dispatch.
194
+
195
+ Agent Native's current schema integration needs validation and JSON Schema
196
+ metadata on the same schema object. With Effect, the two conversion helpers
197
+ provide different halves:
198
+
199
+ | Conversion | `validate` | advertised parameters |
83
200
  | --- | --- | --- |
84
- | `toStandardSchemaV1` | yes | **empty** |
201
+ | `toStandardSchemaV1` | yes | empty |
85
202
  | `toStandardJSONSchemaV1` | no | full |
86
- | the two copied together | yes | **empty** |
87
- | both, called in turn on the same schema | yes | full |
203
+ | copied into a fresh object | yes | empty |
204
+ | both called on the same schema object | yes | full |
205
+
206
+ The adapter therefore calls both helpers on the same Effect schema object so its
207
+ identity—and the metadata associated with it—survives.
208
+
209
+ Extra input fields are rejected. Only object input schemas are supported because
210
+ that is the shape Agent Native currently includes in its tool list.
88
211
 
89
- All four are accepted without complaint, and three produce a tool an agent sees
90
- as taking no input. Copying fails because the conversion reads the Effect schema
91
- itself, so identity has to survive — and both helpers return that same schema,
92
- sharing one `~standard`, so calling them in turn leaves a single object carrying
93
- `jsonSchema` and `validate` alike. That is what this package does.
212
+ ## Compatibility proof
94
213
 
95
- ## What it proves
214
+ The adapter is checked against `@agent-native/core@0.177.1` using the real Agent
215
+ Native registry, tool runtime, and schema wrapper rather than stand-ins.
216
+
217
+ Run from the repository root:
218
+
219
+ ```bash
220
+ pnpm exec vitest run packages/agent-native/test/framework.test.ts
221
+ ```
96
222
 
97
- Run `pnpm exec vitest run packages/agent-native/test/framework.test.ts` at the
98
- repository root. No LLM credentials or network server are needed. The suite uses
99
- an in-memory PGlite database for the framework's internal metadata lookups.
223
+ No LLM credentials or network server are required; the suite uses an in-memory
224
+ PGlite database for Agent Native's internal metadata lookups.
100
225
 
101
- | Framework surface | Executable evidence |
226
+ | Framework surface | What the test proves |
102
227
  | --- | --- |
103
- | Package registry | `registerPackageActions` + `autoDiscoverActions` discovers the adapter entry. An actual app-local action file wins a name collision. |
228
+ | Package registry | `registerPackageActions` + `autoDiscoverActions` discovers the generated entry; an app-local action file wins a name collision. |
104
229
  | Agent tool runtime | `actionsToEngineTools` advertises the encoded schema; `executeAgentToolCall` changes the Foldkit Model for an authorized caller and refuses another caller. |
105
- | Schema wrapper | `defineAction` derives parameters, preserves transforming input for one decode in Foldkit, and rejects extra fields. |
230
+ | Schema wrapper | `defineAction` derives parameters, preserves transforming input for the one decode in Foldkit, and rejects excess fields. |
106
231
 
107
- The framework is a development dependency and a pinned peer of this adapter.
108
- It is not a dependency of `foldkit-agent`. The public adapter types are checked
109
- against the real `ActionTool` type; only object input schemas are supported,
110
- because the framework omits other input shapes from its tool list.
232
+ The public adapter types are checked against Agent Native's real `ActionTool`
233
+ type. Agent Native remains a peer/development dependency of this adapter rather
234
+ than a dependency of core `foldkit-agent`.
111
235
 
112
- ## Limits and reuse decision
236
+ ## Limits
113
237
 
114
- The registry and agent tool runtime can be reused without replacing Foldkit's
115
- state machine. HTTP, MCP, A2A, CLI, UI queries, auth sessions, and deep links
116
- still need their framework host and deployment wiring; this suite does not
117
- claim an end-to-end test of those surfaces. Keep the independent MCP/A2A
118
- adapters and direct WebMCP adapter.
238
+ This package integrates the Agent Native **action registry and tool runtime**. It
239
+ does not claim to replace every Agent Native subsystem. HTTP deployment, MCP,
240
+ A2A, CLI, UI queries, authentication sessions, and deep links remain concerns of
241
+ the Agent Native host or Foldkit Plus's dedicated adapters.
119
242
 
120
- The registry is static: it describes all declared capabilities, while Foldkit
121
- checks availability at invocation time. The application maps a verified caller
122
- to a principal when binding a server-held Runtime. Page-local state still belongs
123
- to WebMCP; no browser RPC bridge is introduced.
243
+ Page-local browser state still belongs to WebMCP; this package does not add a
244
+ browser RPC bridge.
124
245
 
125
- The framework's package registry retains the first registration of a name and
126
- skips names inherited from `Object.prototype`, including `__proto__`. Avoid
127
- those names and restart the host after changing a registered contract. The
128
- adapter's own returned record preserves these keys, but cannot fix that
129
- downstream registry behavior.
246
+ The Agent Native registry keeps the first registration of a name and skips names
247
+ inherited from `Object.prototype`, including `__proto__`. Avoid those names and
248
+ restart the host after changing a registered contract. The record produced here
249
+ preserves such keys, but cannot change downstream registry behavior.
130
250
 
131
- This completes the bounded proof of concept in
251
+ Full HTTP/MCP/A2A deployment tests are outside this package's test suite. This
252
+ is the bounded integration originally tracked in
132
253
  [issue #22](https://github.com/doeixd/foldkit-plus/issues/22), not a claim that
133
- every Agent Native subsystem is independently reusable. A full deployment test
134
- of the HTTP, MCP, A2A, CLI, auth, and UI surfaces remains future work.
254
+ every Agent Native subsystem is independently reusable.
135
255
 
136
256
  ## Choosing an adapter
137
257
 
138
- All four serve the same contract, so serving two at once is two calls, not two
139
- definitions.
258
+ All four adapters serve the same `AssistantAgent` contract. Multiple adapters
259
+ mean multiple protocol interpretations of one definition, not multiple
260
+ capability declarations.
140
261
 
141
262
  | Where the agent runs | Adapter |
142
263
  | --- | --- |
143
- | In the page, beside the user | [`foldkit-agent-webmcp`](https://github.com/doeixd/foldkit-plus/tree/main/packages/agent-webmcp) |
144
- | An external MCP client, over stdio or HTTP | [`foldkit-agent-mcp`](https://github.com/doeixd/foldkit-plus/tree/main/packages/agent-mcp) |
145
- | Another agent, over A2A | [`foldkit-agent-a2a`](https://github.com/doeixd/foldkit-plus/tree/main/packages/agent-a2a) |
146
- | An Agent Native host | [`foldkit-agent-native`](https://github.com/doeixd/foldkit-plus/tree/main/packages/agent-native) |
264
+ | In the page, beside the user | [`foldkit-agent-webmcp`](../agent-webmcp) |
265
+ | An external MCP client, over stdio or HTTP | [`foldkit-agent-mcp`](../agent-mcp) |
266
+ | Another agent, over A2A | [`foldkit-agent-a2a`](../agent-a2a) |
267
+ | An Agent Native host | `foldkit-agent-native` |
147
268
 
148
269
  ## See also
149
270
 
150
- - [The agents guide](https://github.com/doeixd/foldkit-plus/blob/main/docs/agents.md) — what an agent may see and
151
- do, and why a capability is a Message.
152
- - [`foldkit-agent`](https://github.com/doeixd/foldkit-plus/tree/main/packages/agent) — the contract this adapter
153
- serves, and where `Agent.bind` produces the runtime it takes.
154
- - [`examples/todo`](https://github.com/doeixd/foldkit-plus/tree/main/examples/todo) — a worked contract with a
155
- hand-written host.
271
+ - [Agents guide](../../docs/agents.md) — builder → contract → runtime and the authority model.
272
+ - [`foldkit-agent`](../agent) — the protocol-neutral contract and runtime.
273
+ - [`examples/todo`](../../examples/todo) — a focused contract served through adapters.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Agent } from "foldkit-agent";
2
2
  import { ActionTool } from "@agent-native/core/server";
3
- import { StandardSchemaV1 } from "effect/StandardSchema";
3
+ import { StandardJSONSchemaV1, StandardSchemaV1 } from "effect/StandardSchema";
4
4
  //#region src/actions.d.ts
5
5
  type AgentRuntime = Agent.AgentRuntime<any, any, any, any, any>;
6
6
  /**
@@ -31,7 +31,8 @@ interface ActionEntry {
31
31
  readonly parameters: NonNullable<ActionTool['parameters']>;
32
32
  };
33
33
  readonly run: (args: unknown, context?: ActionRunContext) => Promise<ActionResult>;
34
- readonly schema: StandardSchemaV1<unknown, unknown>;
34
+ /** Validates input and carries the JSON Schema its parameters are advertised from. */
35
+ readonly schema: StandardSchemaV1<unknown, unknown> & StandardJSONSchemaV1<unknown, unknown>;
35
36
  readonly http: {
36
37
  readonly method: 'POST';
37
38
  };
@@ -47,8 +48,8 @@ interface ActionEntry {
47
48
  */
48
49
  readonly readOnly: false;
49
50
  }
50
- interface ActionsOptions {
51
- readonly definition: Agent.Definition<any, any, any, any, any>;
51
+ interface ActionsOptions<ByName = Record<string, unknown>> {
52
+ readonly definition: Agent.Definition<any, any, any, ByName, any>;
52
53
  /**
53
54
  * Resolves the Runtime for one request.
54
55
  *
@@ -83,10 +84,15 @@ interface ActionsOptions {
83
84
  * )
84
85
  * ```
85
86
  */
86
- declare const actions: (options: ActionsOptions) => Record<string, ActionEntry>;
87
+ /**
88
+ * The registry, keyed by the contract's capability names when they are known,
89
+ * so a registered name needs no lookup check and a mistyped one does not compile.
90
+ */
91
+ type ActionRegistry<ByName = Record<string, unknown>> = string extends keyof ByName ? Record<string, ActionEntry> : { readonly [Name in keyof ByName]: ActionEntry; };
92
+ declare const actions: <ByName = Record<string, unknown>>(options: ActionsOptions<ByName>) => ActionRegistry<ByName>;
87
93
  declare namespace agentNative_d_exports {
88
- export { ActionEntry, ActionResult, ActionRunContext, ActionsOptions, actions };
94
+ export { ActionEntry, ActionRegistry, ActionResult, ActionRunContext, ActionsOptions, actions };
89
95
  }
90
96
  //#endregion
91
- export { type ActionEntry, type ActionResult, type ActionRunContext, type ActionsOptions, agentNative_d_exports as AgentNative };
97
+ export { type ActionEntry, type ActionRegistry, type ActionResult, type ActionRunContext, type ActionsOptions, agentNative_d_exports as AgentNative };
92
98
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/actions.ts","../src/agentNative.ts"],"mappings":";;;;KAKK,eAAe,MAAM;;;;;;;;;UAUT;WACN;WACA;;;UAIM;WACN;;WAEA;;WAEA;WACA;;;UAIM;WACN;aACE;aACA,YAAY,YAAY;;WAE1B,MAAM,eAAe,UAAU,qBAAqB,QAAQ;WAC5D,QAAQ;WACR;aAAiB;;;WAEjB;;;;;;;;;WASA;;UA0BM;WACN,YAAY,MAAM;;;;;;;;;;WAWlB,iBAAiB,SAAS,qBAAqB,eAAe,QAAQ;;WAGtE;;;;;;;;;;;;;;;;;;;;;;;cAwBE,UAAW,SAAS,mBAAiB,eAAe"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/actions.ts","../src/agentNative.ts"],"mappings":";;;;KAKK,eAAe,MAAM;;;;;;;;;UAUT;WACN;WACA;;;UAIM;WACN;;WAEA;;WAEA;WACA;;;UAIM;WACN;aACE;aACA,YAAY,YAAY;;WAE1B,MAAM,eAAe,UAAU,qBAAqB,QAAQ;;WAE5D,QAAQ,qCAAqC;WAC7C;aAAiB;;;WAEjB;;;;;;;;;WASA;;UAwBM,eAAe,SAAS;WAC9B,YAAY,MAAM,0BAA0B;;;;;;;;;;WAW5C,iBAAiB,SAAS,qBAAqB,eAAe,QAAQ;;WAGtE;;;;;;;;;;;;;;;;;;;;;;;;;;;KA4BC,eAAe,SAAS,gDAAgD,SAChF,eAAe,2BACH,cAAc,SAAS;cAE1B,UAAW,SAAS,yBAC/B,SAAS,eAAe,YACvB,eAAe"}
package/dist/index.mjs CHANGED
@@ -15,32 +15,7 @@ import { Effect, Schema } from "effect";
15
15
  * turn leaves a single object carrying both. Copying them into a new object
16
16
  * would not work: the conversion reads the Effect schema, so identity matters.
17
17
  */
18
- const describedSchema = (schema) => {
19
- const described = Schema.toStandardJSONSchemaV1(schema);
20
- Schema.toStandardSchemaV1(schema, { parseOptions: { onExcessProperty: "error" } });
21
- return described;
22
- };
23
- /**
24
- * Compiles the exposed capabilities into a package action registry.
25
- *
26
- * Hand the result to `registerPackageActions` from `@agent-native/core/server`,
27
- * which merges it into the registry every surface reads. Nothing is written to
28
- * disk, so no generated action can outlive the capability it came from.
29
- *
30
- * `run` only dispatches. Application behaviour stays in `update`, and the action
31
- * adds no authority of its own: availability, authorization and input
32
- * validation all still happen in the contract.
33
- *
34
- * @example
35
- * ```ts
36
- * registerPackageActions(
37
- * AgentNative.actions({
38
- * definition: AppAgent,
39
- * resolveRuntime: ctx => runtimeFor(ctx),
40
- * }),
41
- * )
42
- * ```
43
- */
18
+ const describedSchema = (schema) => Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema), { parseOptions: { onExcessProperty: "error" } });
44
19
  const actions = (options) => {
45
20
  const transport = options.transport ?? "agent-native";
46
21
  const entries = Object.create(null);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/actions.ts","../src/agentNative.ts"],"sourcesContent":["import { Agent } from 'foldkit-agent'\nimport type { ActionTool } from '@agent-native/core/server'\nimport { Effect, Schema } from 'effect'\nimport type { StandardSchemaV1 } from 'effect/StandardSchema'\n\ntype AgentRuntime = Agent.AgentRuntime<any, any, any, any, any>\n\n/**\n * The request context Agent Native hands an action.\n *\n * Deliberately narrower than the framework's own `ActionRunContext`: the\n * adapter promises only the identity a principal mapper needs, so its public\n * surface does not grow with the framework's context. The framework still\n * passes its full context through at runtime.\n */\nexport interface ActionRunContext {\n readonly userEmail?: string | undefined\n readonly orgId?: string | null | undefined\n}\n\n/** What an action reports back. `run` never decides anything itself. */\nexport interface ActionResult {\n readonly ok: boolean\n /** The Message tag that was dispatched, when one was. */\n readonly tag?: string | undefined\n /** How the operation finished, when the capability declares completion. */\n readonly completion?: 'completed' | 'failed' | undefined\n readonly message: string\n}\n\n/** One entry of the record `registerPackageActions` takes. */\nexport interface ActionEntry {\n readonly tool: {\n readonly description: string\n readonly parameters: NonNullable<ActionTool['parameters']>\n }\n readonly run: (args: unknown, context?: ActionRunContext) => Promise<ActionResult>\n readonly schema: StandardSchemaV1<unknown, unknown>\n readonly http: { readonly method: 'POST' }\n /** Defaults to true in the framework; stated so it is not left to a default. */\n readonly requiresAuth: boolean\n /**\n * Always false. A capability dispatches a Message into `update`, so it is a\n * write however little it changes.\n *\n * This feeds plan-mode classification, where the dangerous direction is\n * claiming read-only: plan mode would then run it for real. A resource read\n * would be the read-only case, and resources are not exposed as actions yet.\n */\n readonly readOnly: false\n}\n\n/**\n * A Standard Schema that both validates and advertises its shape.\n *\n * Neither Effect helper does both alone, and the difference is silent:\n * `toStandardSchemaV1` carries `validate` but no `jsonSchema`, and\n * `defineAction` accepts it while advertising a tool that takes **no input**;\n * `toStandardJSONSchemaV1` carries the `jsonSchema` those parameters come from\n * but no `validate`.\n *\n * Both return the schema itself and share one `~standard`, so calling them in\n * turn leaves a single object carrying both. Copying them into a new object\n * would not work: the conversion reads the Effect schema, so identity matters.\n */\nconst describedSchema = (\n schema: Parameters<typeof Schema.toStandardSchemaV1>[0],\n): StandardSchemaV1<unknown, unknown> => {\n const described = Schema.toStandardJSONSchemaV1(schema as never)\n // Stripping fields here would hide invalid input from dispatch's strict decoder.\n Schema.toStandardSchemaV1(schema, { parseOptions: { onExcessProperty: 'error' } })\n\n return described as unknown as StandardSchemaV1<unknown, unknown>\n}\n\nexport interface ActionsOptions {\n readonly definition: Agent.Definition<any, any, any, any, any>\n\n /**\n * Resolves the Runtime for one request.\n *\n * Called per invocation, because which Model a caller means depends on who is\n * calling. The Runtime it returns must already be bound for that caller: when\n * a contract declares `authorize`, `Agent.bind` requires a `principal`\n * provider, so the identity mapping stays with the application instead of\n * being guessed here from `userEmail`.\n */\n readonly resolveRuntime: (context: ActionRunContext) => AgentRuntime | Promise<AgentRuntime>\n\n /** Recorded on the invocation, so an audit log can tell these apart. */\n readonly transport?: string | undefined\n}\n\n/**\n * Compiles the exposed capabilities into a package action registry.\n *\n * Hand the result to `registerPackageActions` from `@agent-native/core/server`,\n * which merges it into the registry every surface reads. Nothing is written to\n * disk, so no generated action can outlive the capability it came from.\n *\n * `run` only dispatches. Application behaviour stays in `update`, and the action\n * adds no authority of its own: availability, authorization and input\n * validation all still happen in the contract.\n *\n * @example\n * ```ts\n * registerPackageActions(\n * AgentNative.actions({\n * definition: AppAgent,\n * resolveRuntime: ctx => runtimeFor(ctx),\n * }),\n * )\n * ```\n */\nexport const actions = (options: ActionsOptions): Record<string, ActionEntry> => {\n const transport = options.transport ?? 'agent-native'\n const entries: Record<string, ActionEntry> = Object.create(null)\n\n for (const variant of options.definition.messages.variants) {\n if (variant.inputJsonSchema.type !== 'object') {\n throw new Error(`Agent Native capability \"${variant.name}\" requires an object input schema`)\n }\n entries[variant.name] = {\n tool: {\n description: variant.description,\n parameters: {\n properties: {},\n ...variant.inputJsonSchema,\n } as NonNullable<ActionTool['parameters']>,\n },\n // Validated on the *encoded* side. The framework hands `run` whatever\n // this schema parsed, and `run` hands that to `dispatchUnknown`, which\n // decodes. A decoding schema here would decode a transforming input\n // twice, so the contract would then reject its own validated value.\n schema: describedSchema(Schema.toEncoded(variant.inputSchema)),\n http: { method: 'POST' },\n requiresAuth: true,\n readOnly: false,\n\n run: async (args: unknown, context?: ActionRunContext): Promise<ActionResult> => {\n // Resolution is the application's code, and its throw is deliberate --\n // a principal mapper refusing an unauthenticated caller, say. Let it\n // through rather than reporting it as this capability failing.\n const agent = await options.resolveRuntime(context ?? {})\n\n let outcome\n try {\n outcome = await Effect.runPromise(\n Effect.result(agent.messages.dispatchUnknown(variant.name, args, { transport })),\n )\n } catch {\n // `Effect.result` captures expected failures but not defects, and a\n // defect's text may carry application internals.\n return { ok: false, message: `Capability \"${variant.name}\" failed unexpectedly` }\n }\n\n if (outcome._tag === 'Failure') {\n return { ok: false, message: outcome.failure.message }\n }\n\n const result = outcome.success\n const summary = Agent.summarize(result)\n return {\n ok: summary.ok,\n tag: result.tag,\n ...(result.completion === undefined ? {} : { completion: result.completion.status }),\n message: summary.text,\n }\n },\n }\n }\n\n return entries\n}\n","export {\n actions,\n type ActionEntry,\n type ActionResult,\n type ActionRunContext,\n type ActionsOptions,\n} from './actions.js'\n"],"mappings":";;;;;;;;;;;;;;;;;AAiEA,MAAM,mBACJ,WACuC;CACvC,MAAM,YAAY,OAAO,uBAAuB,MAAe;CAE/D,OAAO,mBAAmB,QAAQ,EAAE,cAAc,EAAE,kBAAkB,QAAQ,EAAE,CAAC;CAEjF,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,WAAW,YAAyD;CAC/E,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,UAAuC,OAAO,OAAO,IAAI;CAE/D,KAAK,MAAM,WAAW,QAAQ,WAAW,SAAS,UAAU;EAC1D,IAAI,QAAQ,gBAAgB,SAAS,UACnC,MAAM,IAAI,MAAM,4BAA4B,QAAQ,KAAK,kCAAkC;EAE7F,QAAQ,QAAQ,QAAQ;GACtB,MAAM;IACJ,aAAa,QAAQ;IACrB,YAAY;KACV,YAAY,CAAC;KACb,GAAG,QAAQ;IACb;GACF;GAKA,QAAQ,gBAAgB,OAAO,UAAU,QAAQ,WAAW,CAAC;GAC7D,MAAM,EAAE,QAAQ,OAAO;GACvB,cAAc;GACd,UAAU;GAEV,KAAK,OAAO,MAAe,YAAsD;IAI/E,MAAM,QAAQ,MAAM,QAAQ,eAAe,WAAW,CAAC,CAAC;IAExD,IAAI;IACJ,IAAI;KACF,UAAU,MAAM,OAAO,WACrB,OAAO,OAAO,MAAM,SAAS,gBAAgB,QAAQ,MAAM,MAAM,EAAE,UAAU,CAAC,CAAC,CACjF;IACF,QAAQ;KAGN,OAAO;MAAE,IAAI;MAAO,SAAS,eAAe,QAAQ,KAAK;KAAuB;IAClF;IAEA,IAAI,QAAQ,SAAS,WACnB,OAAO;KAAE,IAAI;KAAO,SAAS,QAAQ,QAAQ;IAAQ;IAGvD,MAAM,SAAS,QAAQ;IACvB,MAAM,UAAU,MAAM,UAAU,MAAM;IACtC,OAAO;KACL,IAAI,QAAQ;KACZ,KAAK,OAAO;KACZ,GAAI,OAAO,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,OAAO,WAAW,OAAO;KAClF,SAAS,QAAQ;IACnB;GACF;EACF;CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/actions.ts","../src/agentNative.ts"],"sourcesContent":["import { Agent } from 'foldkit-agent'\nimport type { ActionTool } from '@agent-native/core/server'\nimport { Effect, Schema } from 'effect'\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from 'effect/StandardSchema'\n\ntype AgentRuntime = Agent.AgentRuntime<any, any, any, any, any>\n\n/**\n * The request context Agent Native hands an action.\n *\n * Deliberately narrower than the framework's own `ActionRunContext`: the\n * adapter promises only the identity a principal mapper needs, so its public\n * surface does not grow with the framework's context. The framework still\n * passes its full context through at runtime.\n */\nexport interface ActionRunContext {\n readonly userEmail?: string | undefined\n readonly orgId?: string | null | undefined\n}\n\n/** What an action reports back. `run` never decides anything itself. */\nexport interface ActionResult {\n readonly ok: boolean\n /** The Message tag that was dispatched, when one was. */\n readonly tag?: string | undefined\n /** How the operation finished, when the capability declares completion. */\n readonly completion?: 'completed' | 'failed' | undefined\n readonly message: string\n}\n\n/** One entry of the record `registerPackageActions` takes. */\nexport interface ActionEntry {\n readonly tool: {\n readonly description: string\n readonly parameters: NonNullable<ActionTool['parameters']>\n }\n readonly run: (args: unknown, context?: ActionRunContext) => Promise<ActionResult>\n /** Validates input and carries the JSON Schema its parameters are advertised from. */\n readonly schema: StandardSchemaV1<unknown, unknown> & StandardJSONSchemaV1<unknown, unknown>\n readonly http: { readonly method: 'POST' }\n /** Defaults to true in the framework; stated so it is not left to a default. */\n readonly requiresAuth: boolean\n /**\n * Always false. A capability dispatches a Message into `update`, so it is a\n * write however little it changes.\n *\n * This feeds plan-mode classification, where the dangerous direction is\n * claiming read-only: plan mode would then run it for real. A resource read\n * would be the read-only case, and resources are not exposed as actions yet.\n */\n readonly readOnly: false\n}\n\n/**\n * A Standard Schema that both validates and advertises its shape.\n *\n * Neither Effect helper does both alone, and the difference is silent:\n * `toStandardSchemaV1` carries `validate` but no `jsonSchema`, and\n * `defineAction` accepts it while advertising a tool that takes **no input**;\n * `toStandardJSONSchemaV1` carries the `jsonSchema` those parameters come from\n * but no `validate`.\n *\n * Both return the schema itself and share one `~standard`, so calling them in\n * turn leaves a single object carrying both. Copying them into a new object\n * would not work: the conversion reads the Effect schema, so identity matters.\n */\nconst describedSchema = (\n schema: Schema.Codec<unknown, unknown>,\n): StandardSchemaV1<unknown, unknown> & StandardJSONSchemaV1<unknown, unknown> =>\n // Stripping fields here would hide invalid input from dispatch's strict decoder.\n Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema), {\n parseOptions: { onExcessProperty: 'error' },\n })\n\nexport interface ActionsOptions<ByName = Record<string, unknown>> {\n readonly definition: Agent.Definition<any, any, any, ByName, any>\n\n /**\n * Resolves the Runtime for one request.\n *\n * Called per invocation, because which Model a caller means depends on who is\n * calling. The Runtime it returns must already be bound for that caller: when\n * a contract declares `authorize`, `Agent.bind` requires a `principal`\n * provider, so the identity mapping stays with the application instead of\n * being guessed here from `userEmail`.\n */\n readonly resolveRuntime: (context: ActionRunContext) => AgentRuntime | Promise<AgentRuntime>\n\n /** Recorded on the invocation, so an audit log can tell these apart. */\n readonly transport?: string | undefined\n}\n\n/**\n * Compiles the exposed capabilities into a package action registry.\n *\n * Hand the result to `registerPackageActions` from `@agent-native/core/server`,\n * which merges it into the registry every surface reads. Nothing is written to\n * disk, so no generated action can outlive the capability it came from.\n *\n * `run` only dispatches. Application behaviour stays in `update`, and the action\n * adds no authority of its own: availability, authorization and input\n * validation all still happen in the contract.\n *\n * @example\n * ```ts\n * registerPackageActions(\n * AgentNative.actions({\n * definition: AppAgent,\n * resolveRuntime: ctx => runtimeFor(ctx),\n * }),\n * )\n * ```\n */\n/**\n * The registry, keyed by the contract's capability names when they are known,\n * so a registered name needs no lookup check and a mistyped one does not compile.\n */\nexport type ActionRegistry<ByName = Record<string, unknown>> = string extends keyof ByName\n ? Record<string, ActionEntry>\n : { readonly [Name in keyof ByName]: ActionEntry }\n\nexport const actions = <ByName = Record<string, unknown>>(\n options: ActionsOptions<ByName>,\n): ActionRegistry<ByName> => {\n const transport = options.transport ?? 'agent-native'\n const entries: Record<string, ActionEntry> = Object.create(null)\n\n for (const variant of options.definition.messages.variants) {\n if (variant.inputJsonSchema.type !== 'object') {\n throw new Error(`Agent Native capability \"${variant.name}\" requires an object input schema`)\n }\n entries[variant.name] = {\n tool: {\n description: variant.description,\n parameters: {\n properties: {},\n ...variant.inputJsonSchema,\n } as NonNullable<ActionTool['parameters']>,\n },\n // Validated on the *encoded* side. The framework hands `run` whatever\n // this schema parsed, and `run` hands that to `dispatchUnknown`, which\n // decodes. A decoding schema here would decode a transforming input\n // twice, so the contract would then reject its own validated value.\n schema: describedSchema(Schema.toEncoded(variant.inputSchema)),\n http: { method: 'POST' },\n requiresAuth: true,\n readOnly: false,\n\n run: async (args: unknown, context?: ActionRunContext): Promise<ActionResult> => {\n // Resolution is the application's code, and its throw is deliberate --\n // a principal mapper refusing an unauthenticated caller, say. Let it\n // through rather than reporting it as this capability failing.\n const agent = await options.resolveRuntime(context ?? {})\n\n let outcome\n try {\n outcome = await Effect.runPromise(\n Effect.result(agent.messages.dispatchUnknown(variant.name, args, { transport })),\n )\n } catch {\n // `Effect.result` captures expected failures but not defects, and a\n // defect's text may carry application internals.\n return { ok: false, message: `Capability \"${variant.name}\" failed unexpectedly` }\n }\n\n if (outcome._tag === 'Failure') {\n return { ok: false, message: outcome.failure.message }\n }\n\n const result = outcome.success\n const summary = Agent.summarize(result)\n return {\n ok: summary.ok,\n tag: result.tag,\n ...(result.completion === undefined ? {} : { completion: result.completion.status }),\n message: summary.text,\n }\n },\n }\n }\n\n // Keyed by exactly the exposed names, which is what ByName records.\n return entries as ActionRegistry<ByName>\n}\n","export {\n actions,\n type ActionEntry,\n type ActionRegistry,\n type ActionResult,\n type ActionRunContext,\n type ActionsOptions,\n} from './actions.js'\n"],"mappings":";;;;;;;;;;;;;;;;;AAkEA,MAAM,mBACJ,WAGA,OAAO,mBAAmB,OAAO,uBAAuB,MAAM,GAAG,EAC/D,cAAc,EAAE,kBAAkB,QAAQ,EAC5C,CAAC;AAiDH,MAAa,WACX,YAC2B;CAC3B,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,UAAuC,OAAO,OAAO,IAAI;CAE/D,KAAK,MAAM,WAAW,QAAQ,WAAW,SAAS,UAAU;EAC1D,IAAI,QAAQ,gBAAgB,SAAS,UACnC,MAAM,IAAI,MAAM,4BAA4B,QAAQ,KAAK,kCAAkC;EAE7F,QAAQ,QAAQ,QAAQ;GACtB,MAAM;IACJ,aAAa,QAAQ;IACrB,YAAY;KACV,YAAY,CAAC;KACb,GAAG,QAAQ;IACb;GACF;GAKA,QAAQ,gBAAgB,OAAO,UAAU,QAAQ,WAAW,CAAC;GAC7D,MAAM,EAAE,QAAQ,OAAO;GACvB,cAAc;GACd,UAAU;GAEV,KAAK,OAAO,MAAe,YAAsD;IAI/E,MAAM,QAAQ,MAAM,QAAQ,eAAe,WAAW,CAAC,CAAC;IAExD,IAAI;IACJ,IAAI;KACF,UAAU,MAAM,OAAO,WACrB,OAAO,OAAO,MAAM,SAAS,gBAAgB,QAAQ,MAAM,MAAM,EAAE,UAAU,CAAC,CAAC,CACjF;IACF,QAAQ;KAGN,OAAO;MAAE,IAAI;MAAO,SAAS,eAAe,QAAQ,KAAK;KAAuB;IAClF;IAEA,IAAI,QAAQ,SAAS,WACnB,OAAO;KAAE,IAAI;KAAO,SAAS,QAAQ,QAAQ;IAAQ;IAGvD,MAAM,SAAS,QAAQ;IACvB,MAAM,UAAU,MAAM,UAAU,MAAM;IACtC,OAAO;KACL,IAAI,QAAQ;KACZ,KAAK,OAAO;KACZ,GAAI,OAAO,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,OAAO,WAAW,OAAO;KAClF,SAAS,QAAQ;IACnB;GACF;EACF;CACF;CAGA,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-agent-native",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Agent Native adapter for foldkit-agent. Compiles an exposed Foldkit contract into Agent Native actions.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -40,7 +40,7 @@
40
40
  "@agent-native/core": "0.177.1",
41
41
  "effect": "^4.0.0-rc.112",
42
42
  "foldkit": "^0.158.2",
43
- "foldkit-agent": "^0.2.1"
43
+ "foldkit-agent": "^0.3.0"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@agent-native/core": "0.177.1",
@@ -48,7 +48,7 @@
48
48
  "foldkit": "0.158.2",
49
49
  "tsdown": "^0.23.0",
50
50
  "typescript": "^5.7.2",
51
- "foldkit-agent": "0.2.1"
51
+ "foldkit-agent": "0.3.0"
52
52
  },
53
53
  "scripts": {
54
54
  "build": "tsdown",