@sprigr/apps-app-sdk 0.15.1 → 0.16.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
@@ -44,6 +44,28 @@ export default { list_things: actorTool(async (env, actor, args) => { /* ... */
44
44
 
45
45
  **Why this is in the SDK:** every app hand-rolled this, and one shipped a version that fell back to "the first connected actor on the install" when the caller had none. One person's consent then exposed their account to every agent on that install, in production.
46
46
 
47
+ ## Retiring a person or agent: `on_actor_retired`
48
+
49
+ A per-actor app must forget a person when the platform does. When a member is removed, an agent is deleted, a companion's bound user id is corrected, or an operator retires an orphaned key, the platform POSTs `/__sprigr/tool/on_actor_retired` to every install that declares a tool of that name (sprigr-team decision 0154). Run the same revoke-and-purge your own disconnect tool runs, for that key only.
50
+
51
+ ```ts
52
+ import { actorRetiredHook } from '@sprigr/apps-app-sdk';
53
+
54
+ export default {
55
+ on_actor_retired: actorRetiredHook<MyEnv>(async (env, retired) => {
56
+ // retired.actor is shaped like a stamped actor: actorKey(retired.actor) === retired.actorKey
57
+ await revokeAndPurge(env, retired.actor, { cutoff: retired.requestedAt, ownerRef: retired.storageOwnerRef });
58
+ return { done: true };
59
+ }),
60
+ };
61
+ ```
62
+
63
+ - Declare it in `tools[]` with `"internal": true`. The platform never lets an agent or the app bridge call it.
64
+ - `actorRetiredHook` refuses a call that carries `args.actor` (the platform's dispatch never does) and a malformed body, by throwing. It never turns a throw into `{ ok: false }`: the platform reads `done`, and a swallowed error would read as finished. A throw is retried.
65
+ - Return `{ done: true }` when finished or durably queued by the app; `{ done: false, remaining }` to be called again (1 min up to 12 h, 8 deliveries). Be idempotent.
66
+ - `successorKey` is audit only: never move the grant or the data to it. Delete only what existed by `requestedAt`.
67
+ - `storageOwnerRef` is the `owner_ref` a no-actor maintenance `env.SPRIGR.files.list` reports for this person's per-user stored files; pass it to a no-actor `files.delete(key, { owner_ref })`.
68
+
47
69
  ## Webhook callback URLs
48
70
 
49
71
  - `resolvePlatformWebhookBase(env)` / `buildMarketplaceWebhookUrl(env, installId, topicPath)` — env-correct platform host, so a staging install never registers prod-pointing subscriptions.
package/dist/index.d.ts CHANGED
@@ -1185,6 +1185,113 @@ declare function createToolWrappers<Env>(opts?: ToolWrapperOptions): {
1185
1185
  actorTool: <A, R>(fn: (env: Env, actor: Actor, args: A) => Promise<R>) => (args: A, env: Env) => Promise<ToolResult<R>>;
1186
1186
  };
1187
1187
 
1188
+ /**
1189
+ * The `on_actor_retired` lifecycle hook (sprigr-team decision 0154,
1190
+ * sprigr/sprigr-team#10109).
1191
+ *
1192
+ * A per-actor app keys a person's connection, tokens and data on the key
1193
+ * `actorKey()` derives: `u:<platformUserId>`, else `a:<agentId>`. When that
1194
+ * identity goes away (a member is removed, an agent is deleted, a companion's
1195
+ * bound user id is corrected, or an operator retires an orphan), the platform
1196
+ * POSTs `/__sprigr/tool/on_actor_retired` to every install that declares a
1197
+ * tool of that name. The app should run its own self-disconnect
1198
+ * revoke-and-purge for that key and nothing else.
1199
+ *
1200
+ * // src/handlers/index.ts
1201
+ * import { actorRetiredHook } from '@sprigr/apps-app-sdk';
1202
+ * export default {
1203
+ * on_actor_retired: actorRetiredHook<MyEnv>(async (env, retired) => {
1204
+ * await revokeAndPurge(env, retired.actor, { cutoff: retired.requestedAt, ownerRef: retired.storageOwnerRef });
1205
+ * return { done: true };
1206
+ * }),
1207
+ * };
1208
+ *
1209
+ * Manifest: declare the tool with `"internal": true`. The platform keeps it
1210
+ * off every agent tool list and refuses it on the app-bridge invoke route
1211
+ * either way, because its body names whose grant to revoke.
1212
+ *
1213
+ * Contract:
1214
+ * - The dispatch carries NO actor. `actorRetiredHook` throws when `args.actor`
1215
+ * is present (a call that did not come from this hook), and when the body
1216
+ * is malformed. A throw reaches the platform as a 500, which it retries
1217
+ * and finally logs, so a contract mismatch is loud rather than a silent
1218
+ * "done".
1219
+ * - Return `{ done: true }` when finished, or when the rest is durably
1220
+ * queued by the app itself. Return `{ done: false, remaining }` to be
1221
+ * called again later (1 min, 5 min, 15 min, 1 h, 3 h, 6 h, 12 h; 8
1222
+ * deliveries in all). A thrown error is retried the same way.
1223
+ * - Idempotent: a second delivery for a key already purged must return
1224
+ * `{ done: true }`.
1225
+ * - `successorKey` is audit only. Never move the grant or the data to it.
1226
+ * - Delete only what existed by `requestedAt`.
1227
+ * - `storageOwnerRef` is the `owner_ref` a no-actor maintenance
1228
+ * `env.SPRIGR.files.list` reports for this person's per-user stored files;
1229
+ * pass it to a no-actor `env.SPRIGR.files.delete(key, { owner_ref })`.
1230
+ * Only the platform can derive it.
1231
+ */
1232
+
1233
+ /** The manifest tool name the platform dispatches. */
1234
+ declare const ACTOR_RETIRED_HOOK_TOOL = "on_actor_retired";
1235
+ /** Why the key is being retired. */
1236
+ type ActorRetireReason = 'member_removed' | 'agent_deleted' | 'user_id_superseded' | 'admin_removed';
1237
+ declare const ACTOR_RETIRE_REASONS: readonly ActorRetireReason[];
1238
+ /** The wire body, exactly as the platform POSTs it (snake_case). */
1239
+ interface ActorRetiredHookBody {
1240
+ trigger: 'actor_retired';
1241
+ install_id: string;
1242
+ company_id: string;
1243
+ /** `u:<platform_user_id>` or `a:<agent_id>`. */
1244
+ actor_key: string;
1245
+ platform_user_id?: string;
1246
+ agent_id?: string;
1247
+ reason: ActorRetireReason;
1248
+ /** Audit only. */
1249
+ successor_key?: string;
1250
+ /** 32 hex chars: the per-user storage owner (`owner_ref`). */
1251
+ storage_owner_ref: string;
1252
+ requested_by?: string;
1253
+ /** ISO time; purge only what existed by then. */
1254
+ requested_at: string;
1255
+ /** 1 on the first delivery. */
1256
+ attempt: number;
1257
+ }
1258
+ /** The parsed body a handler receives. */
1259
+ interface ActorRetired {
1260
+ installId: string;
1261
+ companyId: string;
1262
+ /** The app-side key, equal to `actorKey(actor)`. */
1263
+ actorKey: string;
1264
+ /** The retired identity, shaped like a stamped actor so existing per-actor
1265
+ * helpers (token stores, walk keys) can be called with it. */
1266
+ actor: Actor;
1267
+ reason: ActorRetireReason;
1268
+ successorKey?: string;
1269
+ storageOwnerRef: string;
1270
+ requestedBy?: string;
1271
+ /** Epoch ms of `requested_at`. */
1272
+ requestedAt: number;
1273
+ attempt: number;
1274
+ }
1275
+ /** What the handler returns. */
1276
+ interface ActorRetiredResult {
1277
+ done: boolean;
1278
+ /** Anything that says what is left, for the platform's log. */
1279
+ remaining?: unknown;
1280
+ [extra: string]: unknown;
1281
+ }
1282
+ /**
1283
+ * Parse and check the hook body. Throws an Error naming the first problem;
1284
+ * never returns a partial value.
1285
+ */
1286
+ declare function parseActorRetiredArgs(args: unknown): ActorRetired;
1287
+ /**
1288
+ * Wrap an `on_actor_retired` handler in the wrapper's `(args, env)` calling
1289
+ * convention. Unlike `tool()` it does NOT turn a throw into `{ ok: false }`:
1290
+ * the platform reads the returned `done`, and a swallowed error would read as
1291
+ * finished. A throw becomes a 500 the platform retries.
1292
+ */
1293
+ declare function actorRetiredHook<Env>(fn: (env: Env, retired: ActorRetired) => Promise<ActorRetiredResult>): (args: unknown, env: Env) => Promise<ActorRetiredResult>;
1294
+
1188
1295
  /**
1189
1296
  * App-scoped R2 file storage (platform feature, 2026-06).
1190
1297
  *
@@ -2516,6 +2623,21 @@ interface SprigrDataIndexOpts {
2516
2623
  /** LOGICAL index name (a `data_indexes` key). See {@link SprigrDataSearchOpts.index}. */
2517
2624
  index?: string;
2518
2625
  }
2626
+ /** Options for `env.SPRIGR.data.import`. */
2627
+ interface SprigrDataImportOpts extends SprigrDataIndexOpts {
2628
+ /**
2629
+ * Write to the app's reserved ACL file index
2630
+ * (`<companyId>-app-<slug>-acl-files`) instead of its data index. Every
2631
+ * object must then carry `acl_principals`, a non-empty list of valid
2632
+ * principals, or the platform rejects the WHOLE batch. Cannot be combined
2633
+ * with `index` (the platform answers 400
2634
+ * `acl_index_combination_unsupported`), and is refused for apps that
2635
+ * declare `data_indexes`. Reads of that index (`search` / `get` with
2636
+ * `withAcl`) are refused over the install bridge (403 `acl_actor_required`),
2637
+ * so they are not modelled here; `delete` and `partialUpdate` accept it.
2638
+ */
2639
+ withAcl?: boolean;
2640
+ }
2519
2641
  /** Options for `env.SPRIGR.data.partialUpdate`. */
2520
2642
  interface SprigrDataPartialUpdateOpts extends SprigrDataIndexOpts {
2521
2643
  /**
@@ -2590,7 +2712,7 @@ interface SprigrDataApi {
2590
2712
  import(objects: Array<{
2591
2713
  objectID: string;
2592
2714
  [key: string]: unknown;
2593
- }>, opts?: SprigrDataIndexOpts): Promise<{
2715
+ }>, opts?: SprigrDataImportOpts): Promise<{
2594
2716
  ok: boolean;
2595
2717
  indexed: number;
2596
2718
  index: string;
@@ -2905,4 +3027,4 @@ interface ExecutionContextLike {
2905
3027
  }
2906
3028
  type HandlerFn<TArgs, TResult> = (args: TArgs, env: Record<string, unknown>, ctx?: ExecutionContextLike) => Promise<TResult>;
2907
3029
 
2908
- export { APPROVAL_GRANTED_KEY, type Actor, type AppApprovalEnvelope, type AppFileListItem, type AppFileUrlArgs, type AppFileUrlResult, type AppFilesEnv, type AppToolEffectsDeclaration, type AppUndoEnvelope, type ApplyPoliciesOptions, type ApprovalGateOptions, type ApprovalSpec, type ArchiveOfferOptions, type ArchiveOfferRefusal, type CaptureJournal, type ConfirmCondition, type ConfirmRule, type ConfirmationPolicy, type ConnectCompleteRequest, type ConnectCompleteResult, type D1Like, type D1PreparedStatementLike, DATA_PARTIAL_UPDATE_PATH, DEFAULT_EMIT_TIMEOUT_MS, DEFAULT_LOG_TIMEOUT_MS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MONEY_FIELDS, DEFAULT_WRITE_PREFIXES, type DerivePolicyOptions, type DerivedPolicy, type DispatcherApprovalGate, type DispatcherApprovalOptions, type EmitMarketplaceEventOptions, type EmitResult, type EmitTransport, type EventArgs, type ExecutionContextLike, type FetchFileResult, type FetchWithRetryOptions, type GetAppFileResult, type HandlerFn, INBOX_SEND_CONTRACT_V1, type InboxAddress, type InboxAppendRequest, type InboxAppendResult, type InboxChannelDeclaration, type InboxFoldersRequest, type InboxFoldersResult, type InboxOwner, type InboxSendConnection, type InboxSendHandlerImpl, InboxSendRefusal, type InboxSendSupports, type InboxSendV1Args, type InboxSendV1Result, type InstallBridge, InvalidUndoEnvelopeError, type JournalRowLike, type LogToPlatformOptions, type ManifestDispatchBlock, type ManifestLike, type ManifestToolLike, type MarketplaceEventEmitOpts, type MarketplaceEventSourceIntegration, NotConnectedError, type OAuthBouncerSignals, type OAuthState, type OfferUndoArgs, type PartialUpdateDataOptions, type PlatformHostEnv, type PolicyCheckInput, type PolicySource, type PutAppFileArgs, type PutAppFileResult, type PutAppFileStreamArgs, type RequireApprovalOptions, type ResolveViewerOptions, type RestoreResult, type RestoreSpec, SPRIGR_DATA_MAX_OBJECTS_PER_CALL, SPRIGR_LOG_LEVELS, SPRIGR_LOG_LIMITS, type ScheduleArgs, type SprigrDataAggregationCell, type SprigrDataAggregationResult, type SprigrDataAggregationSpec, type SprigrDataApi, type SprigrDataIndexOpts, type SprigrDataPartialUpdateBody, type SprigrDataPartialUpdateOpts, type SprigrDataPartialUpdateResult, type SprigrDataPatch, type SprigrDataSearchOpts, type SprigrDataSearchResult, SprigrDataValidationError, type SprigrFilesApi, type SprigrFilesApiWithEdit, type SprigrFilesCreateInput, type SprigrFilesCreateResult, type SprigrFilesEditInput, type SprigrFilesEditResult, type SprigrFilesJobResult, type SprigrFilesListItem, type SprigrFilesListResult, type SprigrInboxApi, type SprigrLogEntry, type SprigrLogFn, type SprigrLogLevel, type SprigrLogResult, SprigrLogValidationError, type SyncedAttachment, type SyncedMessage, type ToolArgs, type ToolHandler, type ToolResult, type ToolWrapperOptions, UNIT_SEP, type UndoApplyOptions, type UndoApplyResult, type UndoCaptureSpec, type UndoFidelity, VIEWER_ANONYMOUS, VIEWER_CONTEXT_HEADER, VIEWER_PLATFORM_USER_ID_HEADER, VIEWER_ROLE_HEADER, VIEWER_USER_ID_HEADER, type VerbRule, type ViewerContext, type ViewerContextFailure, type ViewerContextVerification, type ViewerEnv, type WebhookArgs, type WfpBridgeEnv, type WfpEmitReply, actorKey, actorTool, appFileUrl, applyConfirmationPolicies, approvalHash, archiveOfferRefusal, base64ToBytes, buildConfirmationPolicy, buildMarketplaceWebhookUrl, buildPartialUpdateBody, bytesToBase64, canEmit, canLog, canPartialUpdate, checkConfirmationPolicy, commonDestructiveVerbs, connectComplete, connectDisconnect, constantTimeEqual, createMarketplaceEmitter, createToolWrappers, decodeState, defineInboxSendHandler, deleteAppFile, deriveConfirmationPolicy, describeMissingBridge, dispatcherApproval, emitMarketplaceEvent, encodeState, fetchFileAsBase64, fetchFileBytes, fetchWithRetry, fullWarning, getAppFile, hmacSha256Hex, installTokenPost, isNotConnectedError, isStagingHost, listAppFiles, logToPlatform, manifestIsFresh, offerUndo, overlaySprigr, ownerFromActorKey, parseActor, partialUpdateData, putAppFile, putAppFileStream, randomHex, recreatedWarning, refuseWithoutForce, requireApproval, resolveInstallBridge, resolveOAuthBouncerBase, resolveOAuthBouncerCallbackUrl, resolvePlatformWebhookBase, resolveViewerContext, resolveViewerUserId, runUndoApply, safeCapture, seq, serializeManifest, set, tool, undoEnvelope, validateLogEntries, validateLogEntry, verifyViewerToken, withSprigrEmitFallback, withSprigrInboxFallback, withSprigrLogFallback };
3030
+ export { ACTOR_RETIRED_HOOK_TOOL, ACTOR_RETIRE_REASONS, APPROVAL_GRANTED_KEY, type Actor, type ActorRetireReason, type ActorRetired, type ActorRetiredHookBody, type ActorRetiredResult, type AppApprovalEnvelope, type AppFileListItem, type AppFileUrlArgs, type AppFileUrlResult, type AppFilesEnv, type AppToolEffectsDeclaration, type AppUndoEnvelope, type ApplyPoliciesOptions, type ApprovalGateOptions, type ApprovalSpec, type ArchiveOfferOptions, type ArchiveOfferRefusal, type CaptureJournal, type ConfirmCondition, type ConfirmRule, type ConfirmationPolicy, type ConnectCompleteRequest, type ConnectCompleteResult, type D1Like, type D1PreparedStatementLike, DATA_PARTIAL_UPDATE_PATH, DEFAULT_EMIT_TIMEOUT_MS, DEFAULT_LOG_TIMEOUT_MS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MONEY_FIELDS, DEFAULT_WRITE_PREFIXES, type DerivePolicyOptions, type DerivedPolicy, type DispatcherApprovalGate, type DispatcherApprovalOptions, type EmitMarketplaceEventOptions, type EmitResult, type EmitTransport, type EventArgs, type ExecutionContextLike, type FetchFileResult, type FetchWithRetryOptions, type GetAppFileResult, type HandlerFn, INBOX_SEND_CONTRACT_V1, type InboxAddress, type InboxAppendRequest, type InboxAppendResult, type InboxChannelDeclaration, type InboxFoldersRequest, type InboxFoldersResult, type InboxOwner, type InboxSendConnection, type InboxSendHandlerImpl, InboxSendRefusal, type InboxSendSupports, type InboxSendV1Args, type InboxSendV1Result, type InstallBridge, InvalidUndoEnvelopeError, type JournalRowLike, type LogToPlatformOptions, type ManifestDispatchBlock, type ManifestLike, type ManifestToolLike, type MarketplaceEventEmitOpts, type MarketplaceEventSourceIntegration, NotConnectedError, type OAuthBouncerSignals, type OAuthState, type OfferUndoArgs, type PartialUpdateDataOptions, type PlatformHostEnv, type PolicyCheckInput, type PolicySource, type PutAppFileArgs, type PutAppFileResult, type PutAppFileStreamArgs, type RequireApprovalOptions, type ResolveViewerOptions, type RestoreResult, type RestoreSpec, SPRIGR_DATA_MAX_OBJECTS_PER_CALL, SPRIGR_LOG_LEVELS, SPRIGR_LOG_LIMITS, type ScheduleArgs, type SprigrDataAggregationCell, type SprigrDataAggregationResult, type SprigrDataAggregationSpec, type SprigrDataApi, type SprigrDataImportOpts, type SprigrDataIndexOpts, type SprigrDataPartialUpdateBody, type SprigrDataPartialUpdateOpts, type SprigrDataPartialUpdateResult, type SprigrDataPatch, type SprigrDataSearchOpts, type SprigrDataSearchResult, SprigrDataValidationError, type SprigrFilesApi, type SprigrFilesApiWithEdit, type SprigrFilesCreateInput, type SprigrFilesCreateResult, type SprigrFilesEditInput, type SprigrFilesEditResult, type SprigrFilesJobResult, type SprigrFilesListItem, type SprigrFilesListResult, type SprigrInboxApi, type SprigrLogEntry, type SprigrLogFn, type SprigrLogLevel, type SprigrLogResult, SprigrLogValidationError, type SyncedAttachment, type SyncedMessage, type ToolArgs, type ToolHandler, type ToolResult, type ToolWrapperOptions, UNIT_SEP, type UndoApplyOptions, type UndoApplyResult, type UndoCaptureSpec, type UndoFidelity, VIEWER_ANONYMOUS, VIEWER_CONTEXT_HEADER, VIEWER_PLATFORM_USER_ID_HEADER, VIEWER_ROLE_HEADER, VIEWER_USER_ID_HEADER, type VerbRule, type ViewerContext, type ViewerContextFailure, type ViewerContextVerification, type ViewerEnv, type WebhookArgs, type WfpBridgeEnv, type WfpEmitReply, actorKey, actorRetiredHook, actorTool, appFileUrl, applyConfirmationPolicies, approvalHash, archiveOfferRefusal, base64ToBytes, buildConfirmationPolicy, buildMarketplaceWebhookUrl, buildPartialUpdateBody, bytesToBase64, canEmit, canLog, canPartialUpdate, checkConfirmationPolicy, commonDestructiveVerbs, connectComplete, connectDisconnect, constantTimeEqual, createMarketplaceEmitter, createToolWrappers, decodeState, defineInboxSendHandler, deleteAppFile, deriveConfirmationPolicy, describeMissingBridge, dispatcherApproval, emitMarketplaceEvent, encodeState, fetchFileAsBase64, fetchFileBytes, fetchWithRetry, fullWarning, getAppFile, hmacSha256Hex, installTokenPost, isNotConnectedError, isStagingHost, listAppFiles, logToPlatform, manifestIsFresh, offerUndo, overlaySprigr, ownerFromActorKey, parseActor, parseActorRetiredArgs, partialUpdateData, putAppFile, putAppFileStream, randomHex, recreatedWarning, refuseWithoutForce, requireApproval, resolveInstallBridge, resolveOAuthBouncerBase, resolveOAuthBouncerCallbackUrl, resolvePlatformWebhookBase, resolveViewerContext, resolveViewerUserId, runUndoApply, safeCapture, seq, serializeManifest, set, tool, undoEnvelope, validateLogEntries, validateLogEntry, verifyViewerToken, withSprigrEmitFallback, withSprigrInboxFallback, withSprigrLogFallback };
package/dist/index.js CHANGED
@@ -840,6 +840,74 @@ function createToolWrappers(opts = {}) {
840
840
  };
841
841
  }
842
842
 
843
+ // src/lifecycle.ts
844
+ var ACTOR_RETIRED_HOOK_TOOL = "on_actor_retired";
845
+ var ACTOR_RETIRE_REASONS = [
846
+ "member_removed",
847
+ "agent_deleted",
848
+ "user_id_superseded",
849
+ "admin_removed"
850
+ ];
851
+ var OWNER_REF_RE = /^[0-9a-f]{32}$/;
852
+ var KEY_RE = /^([ua]):([A-Za-z0-9_\-.:@]{1,200})$/;
853
+ function parseActorRetiredArgs(args) {
854
+ if (!args || typeof args !== "object") throw new Error("on_actor_retired: body is not an object");
855
+ const b = args;
856
+ if (b.actor !== void 0 && b.actor !== null) {
857
+ throw new Error("on_actor_retired: refused, the call carries an actor; only the platform hook may call this");
858
+ }
859
+ if (b.trigger !== "actor_retired") throw new Error(`on_actor_retired: trigger must be actor_retired, got ${String(b.trigger)}`);
860
+ const str = (k) => {
861
+ const v = b[k];
862
+ if (typeof v !== "string" || v === "") throw new Error(`on_actor_retired: ${k} is required`);
863
+ return v;
864
+ };
865
+ const installId = str("install_id");
866
+ const companyId = str("company_id");
867
+ const key = str("actor_key");
868
+ const m = KEY_RE.exec(key);
869
+ if (!m) throw new Error(`on_actor_retired: actor_key must be u:<id> or a:<id>, got ${key.slice(0, 80)}`);
870
+ const actor = m[1] === "u" ? { platformUserId: m[2] } : { agentId: m[2] };
871
+ if (m[1] === "u" && b.platform_user_id !== void 0 && b.platform_user_id !== m[2]) {
872
+ throw new Error("on_actor_retired: platform_user_id does not match actor_key");
873
+ }
874
+ if (m[1] === "a" && b.agent_id !== void 0 && b.agent_id !== m[2]) {
875
+ throw new Error("on_actor_retired: agent_id does not match actor_key");
876
+ }
877
+ if (actorKey(actor) !== key) throw new Error("on_actor_retired: actor_key does not round-trip");
878
+ const reason = b.reason;
879
+ if (typeof reason !== "string" || !ACTOR_RETIRE_REASONS.includes(reason)) {
880
+ throw new Error(`on_actor_retired: unknown reason ${String(reason)}`);
881
+ }
882
+ const storageOwnerRef = str("storage_owner_ref");
883
+ if (!OWNER_REF_RE.test(storageOwnerRef)) throw new Error("on_actor_retired: storage_owner_ref must be 32 lowercase hex characters");
884
+ const requestedAt = Date.parse(str("requested_at"));
885
+ if (!Number.isFinite(requestedAt)) throw new Error("on_actor_retired: requested_at is not a date");
886
+ const attempt = typeof b.attempt === "number" && b.attempt >= 1 ? b.attempt : 1;
887
+ return {
888
+ installId,
889
+ companyId,
890
+ actorKey: key,
891
+ actor,
892
+ reason,
893
+ ...typeof b.successor_key === "string" && b.successor_key ? { successorKey: b.successor_key } : {},
894
+ storageOwnerRef,
895
+ ...typeof b.requested_by === "string" && b.requested_by ? { requestedBy: b.requested_by } : {},
896
+ requestedAt,
897
+ attempt
898
+ };
899
+ }
900
+ function actorRetiredHook(fn) {
901
+ return async (args, env) => {
902
+ const retired = parseActorRetiredArgs(args);
903
+ const result = await fn(env, retired);
904
+ if (!result || typeof result.done !== "boolean") {
905
+ throw new Error("on_actor_retired: the handler must return { done: boolean }");
906
+ }
907
+ return result;
908
+ };
909
+ }
910
+
843
911
  // src/app-files.ts
844
912
  var DEFAULT_PLATFORM_BASE = "https://webhooks.sprigr.com";
845
913
  function platformBase(env) {
@@ -1617,6 +1685,8 @@ async function connectDisconnect(env, req) {
1617
1685
  return await installTokenPost(bridge, "/internal/wfp/connect/disconnect", req, { label: "connect disconnect" });
1618
1686
  }
1619
1687
  export {
1688
+ ACTOR_RETIRED_HOOK_TOOL,
1689
+ ACTOR_RETIRE_REASONS,
1620
1690
  APPROVAL_GRANTED_KEY,
1621
1691
  DATA_PARTIAL_UPDATE_PATH,
1622
1692
  DEFAULT_EMIT_TIMEOUT_MS,
@@ -1640,6 +1710,7 @@ export {
1640
1710
  VIEWER_ROLE_HEADER,
1641
1711
  VIEWER_USER_ID_HEADER,
1642
1712
  actorKey,
1713
+ actorRetiredHook,
1643
1714
  actorTool,
1644
1715
  appFileUrl,
1645
1716
  applyConfirmationPolicies,
@@ -1684,6 +1755,7 @@ export {
1684
1755
  overlaySprigr,
1685
1756
  ownerFromActorKey,
1686
1757
  parseActor,
1758
+ parseActorRetiredArgs,
1687
1759
  partialUpdateData,
1688
1760
  putAppFile,
1689
1761
  putAppFileStream,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-app-sdk",
3
- "version": "0.15.1",
3
+ "version": "0.16.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",