@sprigr/apps-app-sdk 0.16.0 → 0.17.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
@@ -78,6 +78,7 @@ export default {
78
78
  - `parseActor` / `actorKey` / `ownerFromActorKey` — per-actor token scoping
79
79
  - `putAppFile` / `putAppFileStream` / `appFileUrl` / `getAppFile` / `listAppFiles` / `deleteAppFile` — durable app-scoped file storage from outside the injected bridge
80
80
  - `fetchFileBytes` / `fetchFileAsBase64` / `bytesToBase64` / `base64ToBytes` — file byte helpers
81
+ - `readableStoredKey(appKey, downloadUrl)` / `agentFileKeyFromUrl` — turn the install-relative key your app stored a file under into the absolute key the platform's `read_file` tool opens (read off the signed URL `appFileUrl` minted). Return it as a tool's `file_key` so an agent can open the file. `appKeyFromCallerKey` / `callerKeyRefusal` go the other way, for a key an agent hands back to your tool (0.17.0)
81
82
 
82
83
  Full platform semantics: [`docs/platform-reference.md`](../../docs/platform-reference.md).
83
84
 
package/dist/index.d.ts CHANGED
@@ -2472,6 +2472,79 @@ declare function connectDisconnect(env: WfpBridgeEnv, req: {
2472
2472
  deleted: number;
2473
2473
  }>;
2474
2474
 
2475
+ /**
2476
+ * Stored-file keys an agent can open (sprigr/sprigr-apps#2394).
2477
+ *
2478
+ * The platform hands an app its storage keys INSTALL-RELATIVE
2479
+ * (`drive/reads/<id>.docx`): that is the app's own view of its storage, and the
2480
+ * platform never names the install prefix or the per-user owner segment in a
2481
+ * files response. The platform tool read_file needs the ABSOLUTE key:
2482
+ *
2483
+ * `_apps/<installId>/<appKey>` (shared storage)
2484
+ * `_apps/<installId>/~u/<ownerHash>/<appKey>` (a manifest
2485
+ * actor_scoped_storage_prefixes key,
2486
+ * sprigr/sprigr-team#9621)
2487
+ *
2488
+ * A signed URL from env.SPRIGR.files.url carries exactly that key as its path,
2489
+ * so a tool that stores a file and mints a link can hand the agent a key that
2490
+ * opens. The github app found the same gap first (sprigr/sprigr-apps#2276,
2491
+ * deriveAgentFileKey); this version also accepts the owner segment.
2492
+ */
2493
+ /** Root every marketplace-app file lives under. */
2494
+ declare const APP_FILES_ROOT = "_apps/";
2495
+ /** The platform's per-user owner segment (sprigr/sprigr-team#9621). An app never
2496
+ * names it in a key it hands env.SPRIGR.files; the platform refuses that. */
2497
+ declare const APP_OWNER_SEGMENT = "~u";
2498
+ /**
2499
+ * The absolute key behind a minted download URL, for the app key it was minted
2500
+ * for. Returns null, never a guess, unless the URL path is exactly
2501
+ * `_apps/<one segment>/<appKey>` or `_apps/<one segment>/~u/<one segment>/<appKey>`:
2502
+ * a key handed to an agent as openable that is not the stored object's key is
2503
+ * worse than no key.
2504
+ */
2505
+ declare function agentFileKeyFromUrl(downloadUrl: string, appKey: string): string | null;
2506
+ /**
2507
+ * The key a tool returns as `file_key` for a file it stored under `appKey`
2508
+ * and minted `downloadUrl` for: the absolute key when it can be read off the
2509
+ * URL, otherwise the app key unchanged (the behaviour before sprigr/sprigr-apps#2394).
2510
+ */
2511
+ declare function readableStoredKey(appKey: string, downloadUrl: string): string;
2512
+ /** A caller-supplied stored-file key, resolved to this install's app key. */
2513
+ type CallerKeyResolution = {
2514
+ ok: true;
2515
+ /** The install-relative key to hand env.SPRIGR.files. */
2516
+ appKey: string;
2517
+ /** True when the caller passed the absolute form or a signed link. */
2518
+ wasAbsolute: boolean;
2519
+ } | {
2520
+ ok: false;
2521
+ /** `other_install`: an absolute key for a different install. `malformed`:
2522
+ * an `_apps/` key or a link with no file path after the prefix. */
2523
+ reason: 'other_install' | 'malformed';
2524
+ /** The install the key names, for `other_install`. */
2525
+ installId?: string;
2526
+ };
2527
+ /**
2528
+ * Accept a stored-file key in any form a tool may have handed out and return
2529
+ * the app-relative key for env.SPRIGR.files:
2530
+ * - the app-relative key itself (`drive/reads/<id>.docx`): unchanged;
2531
+ * - the absolute key (`_apps/<installId>/[~u/<hash>/]drive/reads/<id>.docx`);
2532
+ * - the signed download link, whose path is that absolute key.
2533
+ *
2534
+ * The owner segment is dropped, not checked: the platform re-derives the
2535
+ * owner from the call's verified actor (sprigr/sprigr-team#9621), so another user's
2536
+ * key resolves to the caller's own copy, which usually does not exist. An
2537
+ * absolute key naming a different install is refused when `ownInstallId` is
2538
+ * known, because the platform would otherwise read THIS install's file at the
2539
+ * same relative path. When it is unknown the key is accepted: the platform
2540
+ * still confines every read to this install.
2541
+ */
2542
+ declare function appKeyFromCallerKey(key: string, ownInstallId?: string | null): CallerKeyResolution;
2543
+ /** The sentence a refusal from appKeyFromCallerKey ends with, naming the key. */
2544
+ declare function callerKeyRefusal(key: string, r: Extract<CallerKeyResolution, {
2545
+ ok: false;
2546
+ }>): string;
2547
+
2475
2548
  /**
2476
2549
  * @sprigr/apps-app-sdk
2477
2550
  *
@@ -3027,4 +3100,4 @@ interface ExecutionContextLike {
3027
3100
  }
3028
3101
  type HandlerFn<TArgs, TResult> = (args: TArgs, env: Record<string, unknown>, ctx?: ExecutionContextLike) => Promise<TResult>;
3029
3102
 
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 };
3103
+ export { ACTOR_RETIRED_HOOK_TOOL, ACTOR_RETIRE_REASONS, APPROVAL_GRANTED_KEY, APP_FILES_ROOT, APP_OWNER_SEGMENT, 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 CallerKeyResolution, 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, agentFileKeyFromUrl, appFileUrl, appKeyFromCallerKey, applyConfirmationPolicies, approvalHash, archiveOfferRefusal, base64ToBytes, buildConfirmationPolicy, buildMarketplaceWebhookUrl, buildPartialUpdateBody, bytesToBase64, callerKeyRefusal, 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, readableStoredKey, 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
@@ -1684,10 +1684,88 @@ async function connectDisconnect(env, req) {
1684
1684
  if (!bridge) throw new Error("connectDisconnect: SPRIGR_PLATFORM_BASE / SPRIGR_INSTALL_TOKEN are not bound");
1685
1685
  return await installTokenPost(bridge, "/internal/wfp/connect/disconnect", req, { label: "connect disconnect" });
1686
1686
  }
1687
+
1688
+ // src/stored-file-keys.ts
1689
+ var APP_FILES_ROOT = "_apps/";
1690
+ var APP_OWNER_SEGMENT = "~u";
1691
+ function isSegment(s) {
1692
+ return typeof s === "string" && s.length > 0 && !s.includes("/");
1693
+ }
1694
+ function trimLeadingSlashes(key) {
1695
+ return key.replace(/^\/+/, "");
1696
+ }
1697
+ function parseAbsolute(key) {
1698
+ if (!key.startsWith(APP_FILES_ROOT)) return null;
1699
+ const parts = key.slice(APP_FILES_ROOT.length).split("/");
1700
+ const installId = parts[0];
1701
+ if (!isSegment(installId)) return null;
1702
+ let i = 1;
1703
+ let ownerHash = null;
1704
+ if (parts[1] === APP_OWNER_SEGMENT) {
1705
+ if (!isSegment(parts[2])) return null;
1706
+ ownerHash = parts[2];
1707
+ i = 3;
1708
+ }
1709
+ const rest = parts.slice(i).join("/");
1710
+ if (!rest || rest.split("/").some((seg) => seg === "")) return null;
1711
+ return { installId, ownerHash, rest };
1712
+ }
1713
+ function urlPathKey(url) {
1714
+ try {
1715
+ return trimLeadingSlashes(decodeURIComponent(new URL(url).pathname));
1716
+ } catch {
1717
+ return null;
1718
+ }
1719
+ }
1720
+ function agentFileKeyFromUrl(downloadUrl, appKey) {
1721
+ const rel = trimLeadingSlashes(appKey);
1722
+ if (!rel) return null;
1723
+ const path = urlPathKey(downloadUrl);
1724
+ if (!path) return null;
1725
+ const parsed = parseAbsolute(path);
1726
+ if (!parsed || parsed.rest !== rel) return null;
1727
+ return path;
1728
+ }
1729
+ function readableStoredKey(appKey, downloadUrl) {
1730
+ return agentFileKeyFromUrl(downloadUrl, appKey) ?? appKey;
1731
+ }
1732
+ function appKeyFromCallerKey(key, ownInstallId) {
1733
+ let candidate = key.trim();
1734
+ let wasAbsolute = false;
1735
+ if (/^https?:\/\//i.test(candidate)) {
1736
+ const path = urlPathKey(candidate);
1737
+ if (!path || !path.startsWith(APP_FILES_ROOT)) return { ok: false, reason: "malformed" };
1738
+ candidate = path;
1739
+ }
1740
+ candidate = trimLeadingSlashes(candidate);
1741
+ if (candidate.startsWith(APP_FILES_ROOT)) {
1742
+ const parsed = parseAbsolute(candidate);
1743
+ if (!parsed) return { ok: false, reason: "malformed" };
1744
+ if (ownInstallId && parsed.installId !== ownInstallId) {
1745
+ return { ok: false, reason: "other_install", installId: parsed.installId };
1746
+ }
1747
+ return { ok: true, appKey: parsed.rest, wasAbsolute: true };
1748
+ }
1749
+ const parts = candidate.split("/");
1750
+ if (parts[0] === APP_OWNER_SEGMENT) {
1751
+ const rest = parts.slice(2).join("/");
1752
+ if (!isSegment(parts[1]) || !rest) return { ok: false, reason: "malformed" };
1753
+ return { ok: true, appKey: rest, wasAbsolute: true };
1754
+ }
1755
+ return { ok: true, appKey: candidate, wasAbsolute };
1756
+ }
1757
+ function callerKeyRefusal(key, r) {
1758
+ if (r.reason === "other_install") {
1759
+ return `"${key}" is a stored file of a different app install (${r.installId}), not this one. Pass a file_key this app returned to you.`;
1760
+ }
1761
+ return `"${key}" is not a stored file key: it has no file path after the app storage prefix.`;
1762
+ }
1687
1763
  export {
1688
1764
  ACTOR_RETIRED_HOOK_TOOL,
1689
1765
  ACTOR_RETIRE_REASONS,
1690
1766
  APPROVAL_GRANTED_KEY,
1767
+ APP_FILES_ROOT,
1768
+ APP_OWNER_SEGMENT,
1691
1769
  DATA_PARTIAL_UPDATE_PATH,
1692
1770
  DEFAULT_EMIT_TIMEOUT_MS,
1693
1771
  DEFAULT_LOG_TIMEOUT_MS,
@@ -1712,7 +1790,9 @@ export {
1712
1790
  actorKey,
1713
1791
  actorRetiredHook,
1714
1792
  actorTool,
1793
+ agentFileKeyFromUrl,
1715
1794
  appFileUrl,
1795
+ appKeyFromCallerKey,
1716
1796
  applyConfirmationPolicies,
1717
1797
  approvalHash,
1718
1798
  archiveOfferRefusal,
@@ -1721,6 +1801,7 @@ export {
1721
1801
  buildMarketplaceWebhookUrl,
1722
1802
  buildPartialUpdateBody,
1723
1803
  bytesToBase64,
1804
+ callerKeyRefusal,
1724
1805
  canEmit,
1725
1806
  canLog,
1726
1807
  canPartialUpdate,
@@ -1760,6 +1841,7 @@ export {
1760
1841
  putAppFile,
1761
1842
  putAppFileStream,
1762
1843
  randomHex,
1844
+ readableStoredKey,
1763
1845
  recreatedWarning,
1764
1846
  refuseWithoutForce,
1765
1847
  requireApproval,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-app-sdk",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",