@inferencebureau/apps-sdk 0.16.13 → 0.16.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1014,6 +1014,11 @@ export type Api = ModelClients & {
1014
1014
  * throws ApiError 429 `rate_limit_exceeded`.
1015
1015
  */
1016
1016
  asCaller(key: string): Api;
1017
+ /**
1018
+ * The same API with its calls marked as an AI agent's (`x-ib-agent: 1`), for a route that serves an agent: the
1019
+ * actions they run see `agent: true`, and can refuse or hold what an agent shouldn't do alone.
1020
+ */
1021
+ asAgent(): Api;
1017
1022
  /**
1018
1023
  * A limit of the app's own: counts one call against `key` and answers whether it's within `limit` per
1019
1024
  * `windowSeconds` (up to a day). For what the app decides to limit, in a page, a route or an action:
@@ -1257,6 +1262,8 @@ export interface ClientOptions {
1257
1262
  caller?: string;
1258
1263
  /** The visitor's IP, which calls are counted by when they're for no user, customer or named caller (`serveRecords` sets it). */
1259
1264
  callerIp?: string;
1265
+ /** Marks every call as an AI agent's (`x-ib-agent: 1`): actions it runs see `agent` (see `Api.asAgent`). */
1266
+ agent?: boolean;
1260
1267
  }
1261
1268
  /** The app's API. In an app's deployment every option comes from its environment variables. */
1262
1269
  export declare function createClient(o?: ClientOptions): Api;
@@ -1326,6 +1333,10 @@ export type RecordsRequest = {
1326
1333
  models: string[];
1327
1334
  cursor?: string | null;
1328
1335
  };
1336
+ /** A records request the browser marked as an AI agent's (the components' agent tools, `RecordsClient.asAgent`). */
1337
+ export type AgentRecordsRequest = RecordsRequest & {
1338
+ agent?: boolean;
1339
+ };
1329
1340
  export interface ServeRecordsOptions {
1330
1341
  /** The models the route answers for; every model when unset. */
1331
1342
  models?: string[];
@@ -1790,6 +1801,12 @@ export interface ActionContext<P = Record<string, unknown>> {
1790
1801
  * staff in the store's admin (verifyShopifySession's), a shopper. Null for the app's own calls, webhooks and jobs.
1791
1802
  */
1792
1803
  caller: ActionCaller | null;
1804
+ /**
1805
+ * Whether an AI agent made the call: through an MCP server (Inference Bureau's, or the app's own for its users), the
1806
+ * Apps assistant, or a request with the `x-ib-agent: 1` header. An action can refuse, or hold for a person to
1807
+ * confirm, what an agent asks for: `if (agent) throw new Error("Ask a person to delete quotes.")`.
1808
+ */
1809
+ agent: boolean;
1793
1810
  /**
1794
1811
  * Models through Inference Bureau's gateway, billed to the team: `ai.generateText({ model, prompt })`, `ai.embed`,
1795
1812
  * or `createInferenceBureau(ai)` for the AI SDK. Its calls appear under the run in Logs, and stop with it.
package/dist/index.js CHANGED
@@ -228,6 +228,7 @@ export function createClient(o = {}) {
228
228
  ...(role && o.session ? { "x-ib-session": JSON.stringify({ userId: o.session.userId ?? null, customerId: o.session.customerId ?? null, ...(o.session.customerRecordId ? { customerRecordId: o.session.customerRecordId } : {}), ...(o.session.accountId ? { accountId: o.session.accountId } : {}) }) } : {}),
229
229
  // Who the calls are for, so they count against that caller's own limit (#285).
230
230
  ...(o.caller ? { "x-ib-caller": o.caller } : {}), ...(o.callerIp ? { "x-ib-caller-ip": o.callerIp } : {}),
231
+ ...(o.agent ? { "x-ib-agent": "1" } : {}),
231
232
  };
232
233
  /**
233
234
  * A call with a JSON body (or none); `raw` sends bytes as they are, with their type when known. A call turned away
@@ -375,6 +376,7 @@ export function createClient(o = {}) {
375
376
  const forShop = (shop) => createClient({ ...o, url, token, app, environment, fetch: f, shop });
376
377
  const asRole = (role, session) => createClient({ ...o, url, token, app, environment, fetch: f, role, ...(session ? { session } : {}) });
377
378
  const asCaller = (caller) => createClient({ ...o, url, token, app, environment, fetch: f, caller });
379
+ const asAgent = () => (o.agent ? self : createClient({ ...o, url, token, app, environment, fetch: f, agent: true }));
378
380
  const rateLimit = (key, q) => call("POST", "/rate-limit", { key, limit: q.limit, windowSeconds: q.windowSeconds });
379
381
  const $transaction = (run, q) => runTransaction(self, (commit) => call("POST", "/transactions", commit), run, q);
380
382
  const self = new Proxy({}, {
@@ -383,6 +385,8 @@ export function createClient(o = {}) {
383
385
  return $transaction;
384
386
  if (prop === "asCaller")
385
387
  return asCaller;
388
+ if (prop === "asAgent")
389
+ return asAgent;
386
390
  if (prop === "rateLimit")
387
391
  return rateLimit;
388
392
  if (prop === CALLER_IP)
@@ -447,6 +451,10 @@ export async function serveRecords(request, api, o = {}) {
447
451
  }
448
452
  if (!body || typeof body !== "object" || typeof body.op !== "string")
449
453
  return errorBody(400, "invalid_request", "The body names no op.");
454
+ // An AI agent's call (the components' agent tools): marked so the actions it runs see `agent`. It only ever adds the
455
+ // mark, so a browser claiming it gains nothing.
456
+ if (body.agent === true)
457
+ api = api.asAgent();
450
458
  const str = (v) => typeof v === "string" && v.length > 0;
451
459
  const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
452
460
  try {
package/dist/react.d.ts CHANGED
@@ -71,6 +71,11 @@ export interface RecordsClient {
71
71
  enqueue?<A extends ActionName>(action: A, params?: ParamsOf<A>, options?: RecordsEnqueueOptions): Promise<Job>;
72
72
  /** Called with a model's name whenever a write through this client changed its records; returns the unsubscribe. */
73
73
  subscribe(listener: (model: string) => void): () => void;
74
+ /**
75
+ * The same client with its calls marked as an AI agent's: the actions they run see `agent: true`. The components'
76
+ * agent tools write through it; listeners and live queries are shared with this client.
77
+ */
78
+ asAgent?(): RecordsClient;
74
79
  /**
75
80
  * Called with the models that changed whenever records of any of `models` do, by anyone (live queries); returns
76
81
  * the unsubscribe. One watch on the route serves every listener.
@@ -252,7 +257,46 @@ export interface AutoFormOptions {
252
257
  defaultValues?: Record<string, unknown>;
253
258
  /** After a write succeeds, with the record as written. */
254
259
  onSuccess?(record: AppRecord | null, result?: unknown): void;
260
+ /**
261
+ * Offers the form to AI agents in the browser as WebMCP tools where the page has `navigator.modelContext`:
262
+ * `<name>_read` (the fields, their values and errors), `<name>_fill` (`{ values }`) and `<name>_submit`. The submit
263
+ * is marked as an agent's, so the action it runs sees `agent: true`. `name` is `<model>_form` by default
264
+ * (`<model>_edit` with `id`, `<model>_<action>` with `action`). Experimental: WebMCP is a draft standard.
265
+ */
266
+ agent?: boolean | {
267
+ name?: string;
268
+ description?: string;
269
+ };
255
270
  }
271
+ /** A tool as WebMCP takes it (`navigator.modelContext.registerTool`). */
272
+ export interface AgentTool {
273
+ name: string;
274
+ description: string;
275
+ inputSchema: Record<string, unknown>;
276
+ annotations?: {
277
+ readOnlyHint?: boolean;
278
+ };
279
+ execute(input: Record<string, unknown>): Promise<{
280
+ content: {
281
+ type: "text";
282
+ text: string;
283
+ }[];
284
+ }>;
285
+ }
286
+ interface ModelContext {
287
+ registerTool?(tool: AgentTool): {
288
+ unregister?(): void;
289
+ } | void;
290
+ unregisterTool?(name: string): void;
291
+ }
292
+ /** The page's WebMCP surface, when the browser or an agent's extension offers one; a draft, so read defensively. */
293
+ export declare function modelContext(): ModelContext | null;
294
+ /**
295
+ * Offers `tools` to agents through the page's WebMCP surface while the component is mounted, and takes them back
296
+ * after; nothing where there's none. Each call runs the tools as the latest render made them. `key` null offers
297
+ * nothing; a new key offers them again.
298
+ */
299
+ export declare function useAgentTools(tools: () => AgentTool[], key: string | null): void;
256
300
  export interface AutoFormField extends FormFieldSpec {
257
301
  value: FormValue;
258
302
  set(value: FormValue): void;
package/dist/react.js CHANGED
@@ -29,8 +29,8 @@ export function createRecordsClient(o = {}) {
29
29
  const changed = (model) => { for (const l of listeners)
30
30
  l(model); };
31
31
  const descriptions = new Map();
32
- async function call(body, signal) {
33
- const res = await send(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
32
+ async function call(body, signal, agent = false) {
33
+ const res = await send(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(agent ? { ...body, agent: true } : body), ...(signal ? { signal } : {}) });
34
34
  const text = await res.text();
35
35
  let json = {};
36
36
  try {
@@ -44,7 +44,7 @@ export function createRecordsClient(o = {}) {
44
44
  return json;
45
45
  }
46
46
  const writes = (model, p) => p.then((v) => { changed(model); return v; });
47
- const model = (name) => ({
47
+ const model = (name, agent = false) => ({
48
48
  describe() {
49
49
  if (!descriptions.has(name))
50
50
  descriptions.set(name, call({ op: "describe", model: name }).catch((e) => { descriptions.delete(name); throw e; }));
@@ -62,11 +62,11 @@ export function createRecordsClient(o = {}) {
62
62
  throw e;
63
63
  }
64
64
  },
65
- create: (values) => writes(name, call({ op: "create", model: name, values })),
66
- update: (id, values) => writes(name, call({ op: "update", model: name, id, values })),
67
- delete: (id) => writes(name, call({ op: "delete", model: name, id })).then(() => undefined),
68
- bulkDelete: (ids) => writes(name, call({ op: "bulkDelete", model: name, ids })),
69
- run: (action, q = {}) => writes(name, call({ op: "run", model: name, action, ...(q.id ? { id: q.id } : {}), params: q.params ?? {} })),
65
+ create: (values) => writes(name, call({ op: "create", model: name, values }, undefined, agent)),
66
+ update: (id, values) => writes(name, call({ op: "update", model: name, id, values }, undefined, agent)),
67
+ delete: (id) => writes(name, call({ op: "delete", model: name, id }, undefined, agent)).then(() => undefined),
68
+ bulkDelete: (ids) => writes(name, call({ op: "bulkDelete", model: name, ids }, undefined, agent)),
69
+ run: (action, q = {}) => writes(name, call({ op: "run", model: name, action, ...(q.id ? { id: q.id } : {}), params: q.params ?? {} }, undefined, agent)),
70
70
  async upload(field, file, q = {}) {
71
71
  const fileName = q.fileName ?? (typeof File !== "undefined" && file instanceof File ? file.name : undefined);
72
72
  const up = await call({ op: "createUpload", model: name, field, size: file.size, ...(fileName ? { fileName } : {}), ...(file.type ? { mimeType: file.type } : {}) });
@@ -126,10 +126,17 @@ export function createRecordsClient(o = {}) {
126
126
  })();
127
127
  }
128
128
  const models = new Map();
129
- return {
129
+ const agentModels = new Map();
130
+ const client = {
130
131
  model: ((name) => { if (!models.has(name))
131
132
  models.set(name, model(name)); return models.get(name); }),
132
133
  global: (action, params) => call({ op: "global", action, params: (params ?? {}) }),
134
+ asAgent: () => ({
135
+ ...client,
136
+ model: ((name) => { if (!agentModels.has(name))
137
+ agentModels.set(name, model(name, true)); return agentModels.get(name); }),
138
+ global: (action, params) => call({ op: "global", action, params: (params ?? {}) }, undefined, true),
139
+ }),
133
140
  enqueue: (action, params, { runAt, ...q } = {}) => call({ op: "enqueue", action, params: (params ?? {}), options: { ...q, ...(runAt ? { runAt: runAt instanceof Date ? runAt.toISOString() : runAt } : {}) } }),
134
141
  subscribe: (l) => { listeners.add(l); return () => { listeners.delete(l); }; },
135
142
  watch(names, l) {
@@ -146,6 +153,7 @@ export function createRecordsClient(o = {}) {
146
153
  };
147
154
  },
148
155
  };
156
+ return client;
149
157
  }
150
158
  const Context = createContext(null);
151
159
  let fallback = null;
@@ -404,6 +412,48 @@ export function useAutoTable(model, o = {}) {
404
412
  refetch: page.refetch,
405
413
  };
406
414
  }
415
+ /** The page's WebMCP surface, when the browser or an agent's extension offers one; a draft, so read defensively. */
416
+ export function modelContext() {
417
+ if (typeof navigator === "undefined")
418
+ return null;
419
+ const mc = navigator.modelContext;
420
+ return mc && typeof mc.registerTool === "function" ? mc : null;
421
+ }
422
+ /**
423
+ * Offers `tools` to agents through the page's WebMCP surface while the component is mounted, and takes them back
424
+ * after; nothing where there's none. Each call runs the tools as the latest render made them. `key` null offers
425
+ * nothing; a new key offers them again.
426
+ */
427
+ export function useAgentTools(tools, key) {
428
+ const latest = useRef(tools);
429
+ latest.current = tools;
430
+ useEffect(() => {
431
+ const mc = key === null ? null : modelContext();
432
+ if (!mc)
433
+ return;
434
+ const undo = [];
435
+ for (const t of latest.current()) {
436
+ const tool = { ...t, execute: (input) => (latest.current().find((x) => x.name === t.name) ?? t).execute(input ?? {}) };
437
+ try {
438
+ const r = mc.registerTool(tool);
439
+ undo.push(() => { try {
440
+ if (r && typeof r.unregister === "function")
441
+ r.unregister();
442
+ else
443
+ mc.unregisterTool?.(t.name);
444
+ }
445
+ catch { /* already gone */ } });
446
+ }
447
+ catch (e) {
448
+ console.warn(`Couldn't offer ${t.name} to agents: ${e.message}`);
449
+ }
450
+ }
451
+ return () => { for (const u of undo)
452
+ u(); };
453
+ }, [key]);
454
+ }
455
+ const toolText = (v) => ({ content: [{ type: "text", text: typeof v === "string" ? v : JSON.stringify(v, null, 2) }] });
456
+ const nextRender = () => new Promise((done) => setTimeout(done, 0));
407
457
  /** What a form for the model shows and does, for a renderer to draw. */
408
458
  export function useAutoForm(model, o = {}) {
409
459
  const client = useRecordsClient();
@@ -463,10 +513,12 @@ export function useAutoForm(model, o = {}) {
463
513
  };
464
514
  });
465
515
  const dirty = specs.some((s) => !unchanged(value(s.name), initial[s.name] ?? null));
466
- async function submit(event) {
467
- event?.preventDefault();
468
- if (submitting || !described.data)
469
- return;
516
+ /** Sends the form: through the agent-marked client when an agent's tool submits it. */
517
+ async function send(asAgent) {
518
+ if (submitting)
519
+ return { ok: false, problems: {}, error: "The form is already being sent." };
520
+ if (!described.data)
521
+ return { ok: false, problems: {}, error: "The form hasn't loaded yet." };
470
522
  const out = {};
471
523
  const problems = {};
472
524
  for (const s of specs) {
@@ -488,12 +540,12 @@ export function useAutoForm(model, o = {}) {
488
540
  setErrors(problems);
489
541
  if (Object.keys(problems).length) {
490
542
  setError(null);
491
- return;
543
+ return { ok: false, problems, error: null };
492
544
  }
493
545
  setSubmitting(true);
494
546
  setError(null);
495
547
  try {
496
- const m = untyped(client, model);
548
+ const m = untyped(asAgent && client.asAgent ? client.asAgent() : client, model);
497
549
  for (const s of specs) {
498
550
  const v = value(s.name);
499
551
  if (s.kind === "file" && typeof File !== "undefined" && v instanceof File)
@@ -512,6 +564,7 @@ export function useAutoForm(model, o = {}) {
512
564
  setErrors({});
513
565
  }
514
566
  o.onSuccess?.(written, result);
567
+ return { ok: true, record: written, ...(result !== undefined ? { result } : {}), problems: {}, error: null };
515
568
  }
516
569
  catch (e) {
517
570
  const err = asApiError(e);
@@ -526,19 +579,74 @@ export function useAutoForm(model, o = {}) {
526
579
  other.push(`${p.field} ${p.message}`);
527
580
  }
528
581
  setErrors(byField);
529
- setError(other.length ? other.join("; ") : Object.keys(byField).length ? null : err.message);
582
+ const message = other.length ? other.join("; ") : Object.keys(byField).length ? null : err.message;
583
+ setError(message);
584
+ return { ok: false, problems: byField, error: message };
530
585
  }
531
586
  finally {
532
587
  setSubmitting(false);
533
588
  }
534
589
  }
590
+ async function submit(event) {
591
+ event?.preventDefault();
592
+ await send(false);
593
+ }
594
+ // An edit waits for its record, so the fields never show empty first.
595
+ const loading = described.fetching || (!!o.id && existing.data === undefined && !existing.error);
596
+ const formError = error ?? described.error?.message ?? existing.error?.message ?? (o.id && !existing.fetching && specs.length && existing.data === null ? "There's no such record, or it can't be read here." : null);
597
+ // The form as agent tools (WebMCP), when asked for: what it shows, filling it, and sending it as an agent's call.
598
+ const agentName = !o.agent ? null : (typeof o.agent === "object" && o.agent.name) || `${model}_${o.id ? "edit" : o.action ?? "form"}`;
599
+ const snapshot = () => ({
600
+ model, ...(o.id ? { id: o.id } : {}), ...(o.action ? { action: o.action } : {}), isNew: !o.id, loading, saved, error: formError,
601
+ fields: fields.map((f) => ({
602
+ name: f.name, label: f.label, kind: f.kind, required: f.required,
603
+ value: f.kind === "password" ? (f.value ? "(set)" : null) : f.kind === "file" ? (f.value instanceof Object && "name" in f.value ? f.value.name : f.current?.fileName ?? null) : f.value,
604
+ ...(f.options.length ? { options: f.options } : {}), ...(f.choices.length ? { choices: f.choices.slice(0, 50) } : {}), ...(f.error ? { error: f.error } : {}),
605
+ })),
606
+ });
607
+ const latestSnapshot = useRef(snapshot);
608
+ latestSnapshot.current = snapshot;
609
+ const what = (typeof o.agent === "object" && o.agent.description) || `the ${o.action ? `${o.action} ` : ""}${model} form on this page${o.id ? ` (editing ${o.id})` : ""}`;
610
+ useAgentTools(() => !agentName ? [] : [
611
+ {
612
+ name: `${agentName}_read`, description: `Read ${what}: each field's name, label, kind, whether it's required, its value, its options or choices, and any error.`,
613
+ inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true },
614
+ execute: async () => toolText(latestSnapshot.current()),
615
+ },
616
+ {
617
+ name: `${agentName}_fill`, description: `Fill fields of ${what} by name; it isn't sent until ${agentName}_submit. A person can see and change what you fill. File fields are left to the person.`,
618
+ inputSchema: { type: "object", properties: { values: { type: "object", description: "Values by field name." } }, required: ["values"] },
619
+ execute: async (input) => {
620
+ const values = input.values && typeof input.values === "object" ? input.values : {};
621
+ const skipped = [];
622
+ for (const [name, v] of Object.entries(values)) {
623
+ const f = fields.find((x) => x.name === name);
624
+ if (!f || f.kind === "file") {
625
+ skipped.push(name);
626
+ continue;
627
+ }
628
+ f.set(initialValue(f, v));
629
+ }
630
+ await nextRender();
631
+ return toolText({ ...(skipped.length ? { skipped: skipped.map((n) => fields.some((x) => x.name === n) ? `${n} (a file: a person chooses it)` : `${n} (no such field)`) } : {}), form: latestSnapshot.current() });
632
+ },
633
+ },
634
+ {
635
+ name: `${agentName}_submit`, description: `Send ${what} as it's filled now. The app sees the call as an AI agent's and may refuse what it leaves to a person.`,
636
+ inputSchema: { type: "object", properties: {} },
637
+ execute: async () => {
638
+ const r = await send(true);
639
+ await nextRender();
640
+ return toolText({ ok: r.ok, ...(r.record ? { record: r.record } : {}), ...(r.result !== undefined ? { result: r.result } : {}), ...(Object.keys(r.problems).length ? { problems: r.problems } : {}), ...(r.error ? { error: r.error } : {}), form: latestSnapshot.current() });
641
+ },
642
+ },
643
+ ], agentName);
535
644
  return {
536
645
  description: described.data,
537
646
  fields,
538
- // An edit waits for its record, so the fields never show empty first.
539
- loading: described.fetching || (!!o.id && existing.data === undefined && !existing.error),
647
+ loading,
540
648
  submitting,
541
- error: error ?? described.error?.message ?? existing.error?.message ?? (o.id && !existing.fetching && specs.length && existing.data === null ? "There's no such record, or it can't be read here." : null),
649
+ error: formError,
542
650
  saved,
543
651
  dirty,
544
652
  submit,
package/dist/runtime.d.ts CHANGED
@@ -23,6 +23,8 @@ export interface ActionRequest {
23
23
  background?: boolean;
24
24
  /** Who called, when the call was held to a role. */
25
25
  caller?: ActionCaller | null;
26
+ /** An AI agent made the call (an MCP server, the assistant, or `x-ib-agent: 1`). */
27
+ agent?: boolean;
26
28
  /** The run's event in Logs: the action's `ai` calls sit under it. */
27
29
  event?: string;
28
30
  }
package/dist/runtime.js CHANGED
@@ -220,7 +220,7 @@ export async function runAction(req, registry, o = {}) {
220
220
  const ctx = {
221
221
  params: req.params ?? {}, record, api: stagingApi(scopedApi(o.api ?? createClient({ ...(o.token ? { token: o.token } : {}), ...withFetch }), req.shop), handed), logger,
222
222
  model: req.model, action: req.action, environment: req.environment, signal,
223
- caller: req.caller ?? null, shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, { ...(o.token ? { token: o.token } : {}), ...withFetch, ...(req.background ? { priority: "background" } : {}) })) : null,
223
+ caller: req.caller ?? null, agent: req.agent === true, shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, { ...(o.token ? { token: o.token } : {}), ...withFetch, ...(req.background ? { priority: "background" } : {}) })) : null,
224
224
  ai: o.ai ?? createAiClient({ ...(o.token ? { token: o.token } : {}), ...withFetch, ...(req.event ? { event: req.event } : {}), signal }),
225
225
  };
226
226
  if (req.phase === "onSuccess") {
package/dist/test.d.ts CHANGED
@@ -239,7 +239,8 @@ export interface RunOptions {
239
239
  id?: string;
240
240
  params?: Record<string, unknown>;
241
241
  shop?: string; /** The record's updatedAt as read: the run happens only while it still stands. */
242
- ifUpdatedAt?: string;
242
+ ifUpdatedAt?: string; /** Run it as an AI agent's call would be: the action's `agent` is true. */
243
+ agent?: boolean;
243
244
  }
244
245
  /**
245
246
  * Who a call is for: a role in permissions.ib.ts and the caller's session (what `{ $session: … }` in a grant's filter
package/dist/test.js CHANGED
@@ -2518,7 +2518,7 @@ export function createTestApp(o = {}) {
2518
2518
  const late = new Promise((_, reject) => {
2519
2519
  timer = setTimeout(() => reject(new ApiError(`The action took longer than ${Math.round(timeout / 1000)} seconds.`, 503, "dependency_unavailable")), timeout);
2520
2520
  });
2521
- const req = { phase: p, model, action, params, record: rec, isNew, environment, shop, caller: how.caller ?? null, ...(how.background ? { background: true } : {}) };
2521
+ const req = { phase: p, model, action, params, record: rec, isNew, environment, shop, caller: how.caller ?? null, ...(input.agent ? { agent: true } : {}), ...(how.background ? { background: true } : {}) };
2522
2522
  try {
2523
2523
  return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, ai: ai.client(), echo: o.echo ?? false, sentry: false }), late]);
2524
2524
  }
@@ -2626,7 +2626,7 @@ export function createTestApp(o = {}) {
2626
2626
  await canRun(scope, model, action, q.id ?? null);
2627
2627
  const shop = scopedShop(scope, q.shop ?? null);
2628
2628
  const { shop: _given, ...rest } = q;
2629
- return run(model, action, { ...rest, ...(shop ? { shop } : {}) }, { caller: scope.role ? { role: scope.role, ...scope.session } : null });
2629
+ return run(model, action, { ...rest, ...(shop ? { shop } : {}), ...(scope.agent ? { agent: true } : {}) }, { caller: scope.role ? { role: scope.role, ...scope.session } : null });
2630
2630
  }
2631
2631
  // As through the API, a scope narrows what a call reaches: a store to its records of store-owned models (api.forShop,
2632
2632
  // an action's api), a role to what permissions.ib.ts grants it (api.asRole).
@@ -2965,6 +2965,8 @@ export function createTestApp(o = {}) {
2965
2965
  // A caller's own limit is the API's to keep; under test the calls go through as they are.
2966
2966
  if (prop === "asCaller")
2967
2967
  return () => made;
2968
+ if (prop === "asAgent")
2969
+ return () => (scope.agent ? made : apiFor({ ...scope, agent: true }));
2968
2970
  if (prop === "rateLimit")
2969
2971
  return rateLimit;
2970
2972
  if (prop === "shopifySync")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.16.13",
3
+ "version": "0.16.14",
4
4
  "description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client, React hooks with AutoTable and AutoForm, and a test harness for its actions.",
5
5
  "license": "UNLICENSED",
6
6
  "keywords": [