@oddington/sdk 0.1.49 → 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';
225
-
226
- const inbox = routinePublicationClient();
224
+ import { defineResponse, respond, resolveAsk } from '@oddington/sdk';
225
+
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,
@@ -606,7 +614,7 @@ links retain their ordinary Data shapes.
606
614
  `source.location.dropbox({ connection, file, revision?, path?, url? })` build flat
607
615
  Locations from successful provider responses. Use
608
616
  `source.locations.merge(existingLocations, incomingLocations)` in an ordinary
609
- guarded Data update. Known objects match by OS File ID, Gmail connection/message/
617
+ Data field update. Known objects match by OS File ID, Gmail connection/message/
610
618
  attachment, or Dropbox connection/File ID; newer Locations replace old path,
611
619
  revision and URL facts. Distinct objects and custom provider values remain.
612
620
  Helpers need no initialization and perform no I/O, choose no ref, and add no
@@ -846,7 +854,21 @@ continues to mean a day/month without a timezone.
846
854
  For reads, only `capacity` and `unavailable` are retryable; an error never includes private
847
855
  server details. Server boundaries own query bounds and authorization.
848
856
 
849
- Schema-driven creates, guarded updates and guarded deletions use the same handle
857
+ Response handlers receive the same `data` interface as routines. They execute
858
+ in a fresh managed runtime and use the pinned deployment's repository access,
859
+ even when the originating routine ran locally. Read current hosted Records when
860
+ business logic needs them; assigning known fields needs no preliminary read:
861
+
862
+ ```ts
863
+ async run({ data }) {
864
+ const changes = data.repository('general').changes();
865
+ changes.update('transactions/one', { bookingstate: 'booked' });
866
+ await changes.publish();
867
+ return resolveAsk({ outcome: 'Booking recorded' });
868
+ }
869
+ ```
870
+
871
+ Schema-driven creates, direct field updates and guarded deletions use the same handle
850
872
  in immediate and captured local routines:
851
873
 
852
874
  ```ts
@@ -855,25 +877,27 @@ changes.create({
855
877
  $ref: 'invoices/INV-124', $filing: { year: '2026' },
856
878
  type: 'invoice', number: 'INV-124', status: 'draft', amount: 1200,
857
879
  });
858
- changes.update(first.invoices[0], { amount: 30 });
880
+ changes.update(first.invoices[0].$ref, { amount: 30 });
859
881
  changes.delete(first.invoices[1]);
860
- await changes.validate();
861
882
  const applied = await changes.apply();
862
883
  ```
863
884
 
885
+ `apply()` validates before writing. Call `validate()` separately only when you
886
+ want to check a proposed change without applying it.
887
+
864
888
  Use reserved `$body` to author a Record's Markdown content independently of its
865
- schema fields, in the same guarded change:
889
+ schema fields, in the same change set:
866
890
 
867
891
  ```ts
868
892
  changes.create({ $ref: 'emails/email-123', type: 'email', subject: 'Invoice',
869
893
  $body: 'Hello,\n\nPlease find our invoice attached.\n' });
870
- changes.update(existingEmail, { $body: revisedMarkdown }); // body-only change
894
+ changes.update(existingEmail.$ref, { $body: revisedMarkdown }); // body-only change
871
895
  ```
872
896
 
873
897
  Omitted `$body` on create means empty; omitted on update preserves the existing
874
898
  body exactly. A string deliberately replaces it, `''` clears it, and `null` is
875
899
  invalid. Body-only edits preserve front matter, field-only edits preserve the
876
- body, and both share the Record's exact-byte version guard. Bodies round-trip
900
+ body. Ordinary updates take a ref and do not require a version. Bodies round-trip
877
901
  without Markdown interpretation, formatting, trimming, or fence semantics.
878
902
  Selections and search return structured fields only. Exact reads remain
879
903
  body-free unless they explicitly request the body:
@@ -895,7 +919,10 @@ Creation captures a complete Record and stable `$ref`, without I/O or a caller
895
919
  path. OS resolves exactly one collection and its schema-declared filing path.
896
920
  Optional `$filing` supplies only unresolved named safe components and is never
897
921
  stored or returned as Record data; missing components reject by name. Updates
898
- capture only `$ref`, `$version` and explicit fields. Deletion captures only the
922
+ capture only the ref string and explicit fields. The caller need not read first.
923
+ OS assigns those fields on the current Record, preserving unspecified fields.
924
+ Objects and arrays replace the named field as a whole; the last successful
925
+ commit wins when writers assign the same field. Deletion captures only the
899
926
  selected `$ref` and `$version`. For hosted Data, links within the deletion set
900
927
  are allowed; schema-declared links from any committed Record outside it refuse
901
928
  the whole group, even if a proposed update removes that link. Hosted validation
@@ -907,7 +934,7 @@ Deleted identities keep their captured versions; deletion creates no new Record
907
934
  version or tombstone. A Source deletion removes only that guarded Record, retaining
908
935
  its File, enrichments and existing durable uses.
909
936
  During a local Run, `changes.apply()` validates the touched Records, paths,
910
- authored links and captured versions without auditing unrelated Record
937
+ authored links and deletion versions without auditing unrelated Record
911
938
  contents, then writes individual complete files atomically. Completed paths
912
939
  remain after a later filesystem failure. `validate()` grants no later
913
940
  permission to write; subsequent operations read the current checkout. There is
@@ -1012,7 +1039,7 @@ App-started local routines use the same current-checkout and live-effects owner.
1012
1039
 
1013
1040
  Retain evidence with shared `files.create({ file: bytes, name: 'evidence.txt' })`
1014
1041
  and put the returned File into `fileBlock({ label, files })`. Inbox has no byte
1015
- intake API. Local publication uploads that same File before exposing the item. Use `data.repository(name)` for Record reads and `changes()` for guarded
1042
+ intake API. Local publication uploads that same File before exposing the item. Use `data.repository(name)` for Record reads and `changes()` for direct field updates and guarded
1016
1043
  creates, updates and deletions. Local Runs read current checkout files and leave
1017
1044
  completed Data writes as ordinary uncommitted files for review, even after later
1018
1045
  failure. Inbox publication has no Record methods;
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;
@@ -1584,16 +1623,20 @@ function captureDataDelete(record4) {
1584
1623
  return !validRecordRef(identity.$ref) || typeof identity.$version != "string" || !identity.$version.length || identity.$version.length > 512 ? invalidChange() : { ref: identity.$ref, expectedVersion: identity.$version };
1585
1624
  }
1586
1625
  function captureDataUpdate(record4, set) {
1587
- let identity = captureDataDelete(record4), input = mapping(set), { $body, ...fields3 } = input, body = Object.hasOwn(input, "$body");
1588
- return body && !validRecordBody($body) || !Object.keys(fields3).length && !body || Object.keys(fields3).some((key) => key.startsWith("$") || ["id", "type"].includes(key)) ? invalidChange() : { ...identity, set: captureValue(fields3), ...body ? { body: $body } : {} };
1626
+ if (!validRecordRef(record4)) return invalidChange();
1627
+ let input = mapping(set), { $body, ...fields3 } = input, body = Object.hasOwn(input, "$body");
1628
+ return body && !validRecordBody($body) || !Object.keys(fields3).length && !body || Object.keys(fields3).some((key) => key.startsWith("$") || ["id", "type"].includes(key)) ? invalidChange() : { ref: record4, set: captureValue(fields3), ...body ? { body: $body } : {} };
1589
1629
  }
1590
1630
  function captureIdentities(value, update, allowEmpty = !0) {
1591
1631
  if (!Array.isArray(value) || !allowEmpty && !value.length || value.length > 1e4) return invalidChange();
1592
1632
  let captured = value.map((item) => {
1593
1633
  let row = mapping(item);
1594
- if (Object.keys(row).filter((key) => !update || key !== "body").sort().join(",") !== (update ? "expectedVersion,ref,set" : "expectedVersion,ref")) return invalidChange();
1634
+ if (Object.keys(row).filter((key) => !update || !["body", "expectedVersion"].includes(key)).sort().join(",") !== (update ? "ref,set" : "expectedVersion,ref")) return invalidChange();
1595
1635
  let identity = { $ref: row.ref, $version: row.expectedVersion };
1596
- return update && Object.keys(mapping(row.set)).some((key) => key.startsWith("$")) ? invalidChange() : update ? captureDataUpdate(identity, { ...mapping(row.set), ...Object.hasOwn(row, "body") ? { $body: row.body } : {} }) : captureDataDelete(identity);
1636
+ if (update && Object.keys(mapping(row.set)).some((key) => key.startsWith("$"))) return invalidChange();
1637
+ if (!update) return captureDataDelete(identity);
1638
+ let captured2 = captureDataUpdate(row.ref, { ...mapping(row.set), ...Object.hasOwn(row, "body") ? { $body: row.body } : {} });
1639
+ return Object.hasOwn(row, "expectedVersion") ? { ...captured2, expectedVersion: captureDataDelete(identity).expectedVersion } : captured2;
1597
1640
  });
1598
1641
  return new Set(captured.map((item) => item.ref)).size !== captured.length ? invalidChange() : captured;
1599
1642
  }
@@ -1863,7 +1906,7 @@ var genericData = {
1863
1906
  return Promise.reject(error);
1864
1907
  }
1865
1908
  method = operation2, applyId ??= routineTransport()?.key("data") ?? crypto.randomUUID(), pending = send3({ operation: operation2, ...captured, applyId }).then((result2) => (confirmed = structuredClone(result2), result2)).catch((error) => {
1866
- throw error instanceof DataOperationError ? explainDataValidation(new DataOperationError(
1909
+ throw error instanceof DataOperationError && error.effect !== void 0 ? error : error instanceof DataOperationError ? explainDataValidation(new DataOperationError(
1867
1910
  error.code,
1868
1911
  error.retryable,
1869
1912
  error.effect ?? (["unavailable", "apply_pending"].includes(error.code) ? "uncertain" : "unapplied"),
@@ -4894,6 +4937,7 @@ export {
4894
4937
  continueAsk,
4895
4938
  data,
4896
4939
  defineHandler,
4940
+ defineResponse,
4897
4941
  defineRoutine,
4898
4942
  file,
4899
4943
  fileBlock,