@oddington/sdk 0.1.50 → 0.1.51

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
@@ -221,9 +221,17 @@ each execution retains the existing 15-minute temporary capability/connection
221
221
  bound. Lost ownership fails the Attempt without repeating customer code.
222
222
 
223
223
  ```ts
224
- import { defineHandler, resolveAsk, routinePublicationClient } from '@oddington/sdk';
224
+ import { defineResponse, respond, resolveAsk } from '@oddington/sdk';
225
225
 
226
- const inbox = routinePublicationClient();
226
+ // List this action in the owning defineRoutine({ responses: [setStatus], access, ... }).
227
+ // The routine's single access declaration governs both its run and its actions.
228
+ const setStatus = defineResponse<{ recordRef: string; status: string }>({ id: 'set-status', async run({ input }, os) {
229
+ const changes = os.data.repository('general').changes();
230
+ changes.update(input.recordRef, { status: input.status });
231
+ await changes.publish();
232
+ return resolveAsk({ outcome: 'Status updated' });
233
+ } });
234
+ // Attach to a published Question with handler: respond(setStatus, { recordRef, status: 'complete' }).
227
235
  ```
228
236
 
229
237
  The SDK owns browser provider setup, email/passcode actions, persisted restoration,
package/dist/browser.js CHANGED
@@ -1118,7 +1118,7 @@ var schema = {
1118
1118
  boolean() {
1119
1119
  return declaration({ type: "boolean" });
1120
1120
  }
1121
- }, file = (options = {}) => (assertRoutineFields(options, ["storage", "path"]), declaration({ type: "file", ...options })), definitions = /* @__PURE__ */ new WeakMap(), defineRoutine = (definition) => {
1121
+ }, file = (options = {}) => (assertRoutineFields(options, ["storage", "path"]), declaration({ type: "file", ...options })), defineResponse = (value) => defineHandler(value), definitions = /* @__PURE__ */ new WeakMap(), defineRoutine = (definition) => {
1122
1122
  if (assertRoutineFields(definition, ["id", "title", "input", "steps", "result", "access", "responses", "run"]), !isAppRoutineName(definition.id) || definition.title !== void 0 && !routineTitle(definition.title) || typeof definition.run != "function") return invalidContract3();
1123
1123
  let input = definition.input === void 0 ? { schema: empty, default: {} } : schemaMetadata(definition.input), result2 = definition.result === void 0 ? void 0 : schemaMetadata(definition.result).schema, access = parseRoutineAccess(definition.access);
1124
1124
  assertRoutineFields(definition.steps ?? {});
@@ -1163,7 +1163,23 @@ var schema = {
1163
1163
  ...definition,
1164
1164
  access,
1165
1165
  steps: Object.freeze(executable),
1166
- responses: Object.freeze(responses),
1166
+ responses: Object.freeze(responses.map((handler) => defineHandler({
1167
+ ...handler,
1168
+ async run(context, runtime) {
1169
+ let active2 = !0, capabilities = runtime ? createCapabilityRuntime(contract, runtime, () => active2, "Response") : void 0;
1170
+ try {
1171
+ return await handler.run(context, capabilities?.os);
1172
+ } catch (error) {
1173
+ throw active2 = !1, error;
1174
+ } finally {
1175
+ try {
1176
+ await capabilities?.drain();
1177
+ } finally {
1178
+ active2 = !1;
1179
+ }
1180
+ }
1181
+ }
1182
+ }))),
1167
1183
  ...definition.input === void 0 ? {} : { input: declaration(
1168
1184
  input.schema,
1169
1185
  Object.hasOwn(input, "default") ? { value: input.default } : void 0
@@ -1183,10 +1199,10 @@ function captureRoutineInput(definition, input) {
1183
1199
  let contract = inspectRoutineDefinition(definition);
1184
1200
  return capture2(contract.input, input === void 0 && Object.hasOwn(contract, "inputDefault") ? contract.inputDefault : input);
1185
1201
  }
1186
- async function executeRoutineDefinition(definition, input, runtime) {
1187
- let captured = captureRoutineInput(definition, input), { contract, steps, run } = definitions.get(definition), active2 = !0, accepting = !0, broken = !1, outputFailure, work = Promise.resolve(), aiWork = /* @__PURE__ */ new Set(), generate = (kind, value) => {
1202
+ function createCapabilityRuntime(contract, runtime, current2, owner) {
1203
+ let aiWork = /* @__PURE__ */ new Set(), generate = (kind, value) => {
1188
1204
  let operation2 = (async () => {
1189
- if (!active2 || broken || contract.access.ai !== !0) throw new AIError("access_denied");
1205
+ if (!current2() || contract.access.ai !== !0) throw new AIError("access_denied");
1190
1206
  if (!runtime.ai) throw new AIError("capability_unavailable");
1191
1207
  let request2;
1192
1208
  try {
@@ -1200,13 +1216,13 @@ async function executeRoutineDefinition(definition, input, runtime) {
1200
1216
  } catch (error) {
1201
1217
  throw error instanceof AIError ? error : new AIError("invalid_input");
1202
1218
  }
1203
- let result3 = await runtime.ai[kind](request2);
1204
- if (!active2 || broken) throw new AIError("access_denied");
1205
- return parseRoutineAIResult(request2, result3);
1219
+ let result2 = await runtime.ai[kind](request2);
1220
+ if (!current2()) throw new AIError("access_denied");
1221
+ return parseRoutineAIResult(request2, result2);
1206
1222
  })();
1207
1223
  return aiWork.add(operation2), operation2.then(() => aiWork.delete(operation2), () => aiWork.delete(operation2)), operation2;
1208
- }, called = /* @__PURE__ */ new Set(), reached = /* @__PURE__ */ new Set(), guarded = (value, receiver) => typeof value == "function" ? (...args) => {
1209
- if (!active2 || broken) throw new Error("Run authority ended");
1224
+ }, guarded = (value, receiver) => typeof value == "function" ? (...args) => {
1225
+ if (!current2()) throw new Error(`${owner} authority ended`);
1210
1226
  return guarded(Reflect.apply(value, receiver, args));
1211
1227
  } : value && typeof value == "object" && !(value instanceof Promise) ? new Proxy({ ...value }, {
1212
1228
  // Copy the surface so wrapping a frozen host capability does not violate
@@ -1217,9 +1233,29 @@ async function executeRoutineDefinition(definition, input, runtime) {
1217
1233
  }) : value, validateHandlers = (value) => {
1218
1234
  for (let question2 of value.questions ?? []) if (question2.handler && !contract.responses.some((handler) => handler.id === question2.handler.id)) return invalid3();
1219
1235
  return value;
1220
- }, activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
1221
- ...guarded({
1222
- ...runtime,
1236
+ };
1237
+ return { os: Object.freeze({ ...guarded({
1238
+ data: runtime.data,
1239
+ files: runtime.files,
1240
+ ai: {
1241
+ generateText: (value) => generate("generateText", value),
1242
+ generateObject: (value) => generate("generateObject", value)
1243
+ },
1244
+ connections: { ...runtime.connections, get: async (identity) => {
1245
+ if (!current2() || !contract.access.connections?.includes(identity)) throw new Error("Connection unavailable");
1246
+ let value = await runtime.connections.get(identity);
1247
+ if (!current2()) throw new Error(`${owner} authority ended`);
1248
+ return value;
1249
+ } },
1250
+ inbox: { ...runtime.inbox, publishAsk: (value, options) => runtime.inbox.publishAsk(validateHandlers(value), options) }
1251
+ }) }), guarded, async drain() {
1252
+ for (; aiWork.size; ) await Promise.allSettled([...aiWork]);
1253
+ } };
1254
+ }
1255
+ async function executeRoutineDefinition(definition, input, runtime) {
1256
+ let captured = captureRoutineInput(definition, input), { contract, steps, run } = definitions.get(definition), active2 = !0, accepting = !0, broken = !1, outputFailure, work = Promise.resolve(), capabilities = createCapabilityRuntime(contract, runtime, () => active2 && !broken, "Run"), called = /* @__PURE__ */ new Set(), reached = /* @__PURE__ */ new Set(), activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
1257
+ ...capabilities.os,
1258
+ ...capabilities.guarded({
1223
1259
  run: freezeRoutineMetadata({ id: runtime.run.id, async progress(value) {
1224
1260
  assertRoutineFields(value, ["completed", "total"]);
1225
1261
  let { completed, total } = value, prior = activeStep ? progress2.get(activeStep) : void 0;
@@ -1227,17 +1263,7 @@ async function executeRoutineDefinition(definition, input, runtime) {
1227
1263
  let accepted = freezeRoutineMetadata({ step: activeStep, completed, total });
1228
1264
  await runtime.run.progress(accepted), progress2.set(activeStep, accepted);
1229
1265
  } }),
1230
- ai: {
1231
- generateText: (value) => generate("generateText", value),
1232
- generateObject: (value) => generate("generateObject", value)
1233
- },
1234
- connections: { ...runtime.connections, get: async (identity) => {
1235
- if (!active2 || broken || !contract.access.connections?.includes(identity)) throw new Error("Connection unavailable");
1236
- let value = await runtime.connections.get(identity);
1237
- if (!active2 || broken) throw new Error("Run authority ended");
1238
- return value;
1239
- } },
1240
- inbox: { ...runtime.inbox, publishAsk: (value, options) => runtime.inbox.publishAsk(validateHandlers(value), options) }
1266
+ ...runtime.artifact ? { artifact: runtime.artifact } : {}
1241
1267
  }),
1242
1268
  step(id3, ...input2) {
1243
1269
  let saved;
@@ -1271,8 +1297,7 @@ async function executeRoutineDefinition(definition, input, runtime) {
1271
1297
  } catch (error) {
1272
1298
  failure = error, broken = !0;
1273
1299
  }
1274
- for (accepting = !1, await work; aiWork.size; ) await Promise.allSettled([...aiWork]);
1275
- active2 = !1;
1300
+ accepting = !1, await work, await capabilities.drain(), active2 = !1;
1276
1301
  try {
1277
1302
  for (let step of contract.steps) reached.has(step.id) || await runtime.step(step.id, { status: "skipped" });
1278
1303
  } catch (error) {
@@ -1433,12 +1458,26 @@ function dataRecordLimitMessage(detail) {
1433
1458
  let scope = detail.collections.length === 1 ? ` from ${detail.collections[0]}` : ` across ${detail.collections.join(", ")}`;
1434
1459
  return `The routine tried to load more than ${detail.maxRecords.toLocaleString("en-US")} matching Records${scope}. Narrow the query or increase maxRecords.`;
1435
1460
  }
1461
+ function dataErrorMessage(code, effect) {
1462
+ return effect === "uncertain" ? "We couldn\u2019t confirm whether your changes were saved." : code === "unavailable" && effect === "unapplied" ? "Your changes could not be saved." : code === "apply_pending" ? effect === "applied" ? "Your changes were saved, but confirmation is still pending." : effect === "unapplied" ? "Your changes have not been saved yet." : "We couldn\u2019t confirm whether your changes were saved." : {
1463
+ context_unavailable: "Data access is not available in this context.",
1464
+ unauthenticated: "Sign in to access this data.",
1465
+ access_denied: "You do not have permission to access this data.",
1466
+ invalid_query: "The data request is not valid.",
1467
+ request_too_large: "The data request is too large.",
1468
+ capacity: "The data service has reached its limit. Try again later.",
1469
+ unavailable: "We couldn\u2019t complete your request.",
1470
+ invalid_change: "These changes are not valid.",
1471
+ conflict: "The data changed before the operation finished.",
1472
+ apply_pending: ""
1473
+ }[code] + (effect === "unapplied" ? " No changes were saved." : effect === "applied" ? " Your changes were saved." : "");
1474
+ }
1436
1475
  var DataOperationError = class extends Error {
1437
1476
  constructor(code, retryable = !1, effect, component, detail) {
1438
1477
  let parsed = detail === void 0 ? void 0 : parseDataOperationDetail(detail);
1439
1478
  if (parsed && ("reason" in parsed ? code !== "invalid_change" : parsed.code === "record_limit_exceeded" && code !== "capacity"))
1440
1479
  throw new Error("Invalid Data operation detail");
1441
- super(parsed && "code" in parsed && parsed.code === "local_data_publication_failed" ? dataPublicationFailureMessage(parsed) : code === "capacity" && parsed && "code" in parsed && parsed.code === "record_limit_exceeded" ? dataRecordLimitMessage(parsed) : `Data operation failed: ${code}`);
1480
+ super(parsed && "code" in parsed && parsed.code === "local_data_publication_failed" ? dataPublicationFailureMessage(parsed) : code === "capacity" && parsed && "code" in parsed && parsed.code === "record_limit_exceeded" ? dataRecordLimitMessage(parsed) : dataErrorMessage(code, effect));
1442
1481
  this.code = code;
1443
1482
  this.retryable = retryable;
1444
1483
  this.effect = effect;
@@ -1867,7 +1906,7 @@ var genericData = {
1867
1906
  return Promise.reject(error);
1868
1907
  }
1869
1908
  method = operation2, applyId ??= routineTransport()?.key("data") ?? crypto.randomUUID(), pending = send3({ operation: operation2, ...captured, applyId }).then((result2) => (confirmed = structuredClone(result2), result2)).catch((error) => {
1870
- throw error instanceof DataOperationError ? explainDataValidation(new DataOperationError(
1909
+ throw error instanceof DataOperationError && error.effect !== void 0 ? error : error instanceof DataOperationError ? explainDataValidation(new DataOperationError(
1871
1910
  error.code,
1872
1911
  error.retryable,
1873
1912
  error.effect ?? (["unavailable", "apply_pending"].includes(error.code) ? "uncertain" : "unapplied"),
@@ -4898,6 +4937,7 @@ export {
4898
4937
  continueAsk,
4899
4938
  data,
4900
4939
  defineHandler,
4940
+ defineResponse,
4901
4941
  defineRoutine,
4902
4942
  file,
4903
4943
  fileBlock,