@oddington/sdk 0.1.50 → 0.1.52

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
@@ -319,7 +319,6 @@ function validateRoutineSchemaValue(schema2, value, rejected) {
319
319
  check(schema2, value, "$");
320
320
  }
321
321
 
322
- var RECORD_READ_INPUT_LIMIT = 1024 * 1024, RECORD_CAPTURE_OUTPUT_LIMIT = 25 * 1024 * 1024;
323
322
  function validRecordRef(value) {
324
323
  return typeof value == "string" && value.length <= 512 && /^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(value);
325
324
  }
@@ -1118,7 +1117,7 @@ var schema = {
1118
1117
  boolean() {
1119
1118
  return declaration({ type: "boolean" });
1120
1119
  }
1121
- }, file = (options = {}) => (assertRoutineFields(options, ["storage", "path"]), declaration({ type: "file", ...options })), definitions = /* @__PURE__ */ new WeakMap(), defineRoutine = (definition) => {
1120
+ }, file = (options = {}) => (assertRoutineFields(options, ["storage", "path"]), declaration({ type: "file", ...options })), defineResponse = (value) => defineHandler(value), definitions = /* @__PURE__ */ new WeakMap(), defineRoutine = (definition) => {
1122
1121
  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
1122
  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
1123
  assertRoutineFields(definition.steps ?? {});
@@ -1163,7 +1162,23 @@ var schema = {
1163
1162
  ...definition,
1164
1163
  access,
1165
1164
  steps: Object.freeze(executable),
1166
- responses: Object.freeze(responses),
1165
+ responses: Object.freeze(responses.map((handler) => defineHandler({
1166
+ ...handler,
1167
+ async run(context, runtime) {
1168
+ let active2 = !0, capabilities = runtime ? createCapabilityRuntime(contract, runtime, () => active2, "Response") : void 0;
1169
+ try {
1170
+ return await handler.run(context, capabilities?.os);
1171
+ } catch (error) {
1172
+ throw active2 = !1, error;
1173
+ } finally {
1174
+ try {
1175
+ await capabilities?.drain();
1176
+ } finally {
1177
+ active2 = !1;
1178
+ }
1179
+ }
1180
+ }
1181
+ }))),
1167
1182
  ...definition.input === void 0 ? {} : { input: declaration(
1168
1183
  input.schema,
1169
1184
  Object.hasOwn(input, "default") ? { value: input.default } : void 0
@@ -1183,10 +1198,10 @@ function captureRoutineInput(definition, input) {
1183
1198
  let contract = inspectRoutineDefinition(definition);
1184
1199
  return capture2(contract.input, input === void 0 && Object.hasOwn(contract, "inputDefault") ? contract.inputDefault : input);
1185
1200
  }
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) => {
1201
+ function createCapabilityRuntime(contract, runtime, current2, owner) {
1202
+ let aiWork = /* @__PURE__ */ new Set(), generate = (kind, value) => {
1188
1203
  let operation2 = (async () => {
1189
- if (!active2 || broken || contract.access.ai !== !0) throw new AIError("access_denied");
1204
+ if (!current2() || contract.access.ai !== !0) throw new AIError("access_denied");
1190
1205
  if (!runtime.ai) throw new AIError("capability_unavailable");
1191
1206
  let request2;
1192
1207
  try {
@@ -1200,13 +1215,13 @@ async function executeRoutineDefinition(definition, input, runtime) {
1200
1215
  } catch (error) {
1201
1216
  throw error instanceof AIError ? error : new AIError("invalid_input");
1202
1217
  }
1203
- let result3 = await runtime.ai[kind](request2);
1204
- if (!active2 || broken) throw new AIError("access_denied");
1205
- return parseRoutineAIResult(request2, result3);
1218
+ let result2 = await runtime.ai[kind](request2);
1219
+ if (!current2()) throw new AIError("access_denied");
1220
+ return parseRoutineAIResult(request2, result2);
1206
1221
  })();
1207
1222
  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");
1223
+ }, guarded = (value, receiver) => typeof value == "function" ? (...args) => {
1224
+ if (!current2()) throw new Error(`${owner} authority ended`);
1210
1225
  return guarded(Reflect.apply(value, receiver, args));
1211
1226
  } : value && typeof value == "object" && !(value instanceof Promise) ? new Proxy({ ...value }, {
1212
1227
  // Copy the surface so wrapping a frozen host capability does not violate
@@ -1217,9 +1232,29 @@ async function executeRoutineDefinition(definition, input, runtime) {
1217
1232
  }) : value, validateHandlers = (value) => {
1218
1233
  for (let question2 of value.questions ?? []) if (question2.handler && !contract.responses.some((handler) => handler.id === question2.handler.id)) return invalid3();
1219
1234
  return value;
1220
- }, activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
1221
- ...guarded({
1222
- ...runtime,
1235
+ };
1236
+ return { os: Object.freeze({ ...guarded({
1237
+ data: runtime.data,
1238
+ files: runtime.files,
1239
+ ai: {
1240
+ generateText: (value) => generate("generateText", value),
1241
+ generateObject: (value) => generate("generateObject", value)
1242
+ },
1243
+ connections: { ...runtime.connections, get: async (identity) => {
1244
+ if (!current2() || !contract.access.connections?.includes(identity)) throw new Error("Connection unavailable");
1245
+ let value = await runtime.connections.get(identity);
1246
+ if (!current2()) throw new Error(`${owner} authority ended`);
1247
+ return value;
1248
+ } },
1249
+ inbox: { ...runtime.inbox, publishAsk: (value, options) => runtime.inbox.publishAsk(validateHandlers(value), options) }
1250
+ }) }), guarded, async drain() {
1251
+ for (; aiWork.size; ) await Promise.allSettled([...aiWork]);
1252
+ } };
1253
+ }
1254
+ async function executeRoutineDefinition(definition, input, runtime) {
1255
+ 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({
1256
+ ...capabilities.os,
1257
+ ...capabilities.guarded({
1223
1258
  run: freezeRoutineMetadata({ id: runtime.run.id, async progress(value) {
1224
1259
  assertRoutineFields(value, ["completed", "total"]);
1225
1260
  let { completed, total } = value, prior = activeStep ? progress2.get(activeStep) : void 0;
@@ -1227,17 +1262,7 @@ async function executeRoutineDefinition(definition, input, runtime) {
1227
1262
  let accepted = freezeRoutineMetadata({ step: activeStep, completed, total });
1228
1263
  await runtime.run.progress(accepted), progress2.set(activeStep, accepted);
1229
1264
  } }),
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) }
1265
+ ...runtime.artifact ? { artifact: runtime.artifact } : {}
1241
1266
  }),
1242
1267
  step(id3, ...input2) {
1243
1268
  let saved;
@@ -1271,8 +1296,7 @@ async function executeRoutineDefinition(definition, input, runtime) {
1271
1296
  } catch (error) {
1272
1297
  failure = error, broken = !0;
1273
1298
  }
1274
- for (accepting = !1, await work; aiWork.size; ) await Promise.allSettled([...aiWork]);
1275
- active2 = !1;
1299
+ accepting = !1, await work, await capabilities.drain(), active2 = !1;
1276
1300
  try {
1277
1301
  for (let step of contract.steps) reached.has(step.id) || await runtime.step(step.id, { status: "skipped" });
1278
1302
  } catch (error) {
@@ -1433,12 +1457,26 @@ function dataRecordLimitMessage(detail) {
1433
1457
  let scope = detail.collections.length === 1 ? ` from ${detail.collections[0]}` : ` across ${detail.collections.join(", ")}`;
1434
1458
  return `The routine tried to load more than ${detail.maxRecords.toLocaleString("en-US")} matching Records${scope}. Narrow the query or increase maxRecords.`;
1435
1459
  }
1460
+ function dataErrorMessage(code, effect) {
1461
+ 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." : {
1462
+ context_unavailable: "Data access is not available in this context.",
1463
+ unauthenticated: "Sign in to access this data.",
1464
+ access_denied: "You do not have permission to access this data.",
1465
+ invalid_query: "The data request is not valid.",
1466
+ request_too_large: "The data request is too large.",
1467
+ capacity: "The data service has reached its limit. Try again later.",
1468
+ unavailable: "We couldn\u2019t complete your request.",
1469
+ invalid_change: "These changes are not valid.",
1470
+ conflict: "The data changed before the operation finished.",
1471
+ apply_pending: ""
1472
+ }[code] + (effect === "unapplied" ? " No changes were saved." : effect === "applied" ? " Your changes were saved." : "");
1473
+ }
1436
1474
  var DataOperationError = class extends Error {
1437
1475
  constructor(code, retryable = !1, effect, component, detail) {
1438
1476
  let parsed = detail === void 0 ? void 0 : parseDataOperationDetail(detail);
1439
1477
  if (parsed && ("reason" in parsed ? code !== "invalid_change" : parsed.code === "record_limit_exceeded" && code !== "capacity"))
1440
1478
  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}`);
1479
+ 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
1480
  this.code = code;
1443
1481
  this.retryable = retryable;
1444
1482
  this.effect = effect;
@@ -1867,7 +1905,7 @@ var genericData = {
1867
1905
  return Promise.reject(error);
1868
1906
  }
1869
1907
  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(
1908
+ throw error instanceof DataOperationError && error.effect !== void 0 ? error : error instanceof DataOperationError ? explainDataValidation(new DataOperationError(
1871
1909
  error.code,
1872
1910
  error.retryable,
1873
1911
  error.effect ?? (["unavailable", "apply_pending"].includes(error.code) ? "uncertain" : "unapplied"),
@@ -4898,6 +4936,7 @@ export {
4898
4936
  continueAsk,
4899
4937
  data,
4900
4938
  defineHandler,
4939
+ defineResponse,
4901
4940
  defineRoutine,
4902
4941
  file,
4903
4942
  fileBlock,