@fungi.computer/oyster 0.47.4 → 0.48.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.
Files changed (41) hide show
  1. package/README.md +8 -0
  2. package/dist/apps/index.d.ts +1 -0
  3. package/dist/apps/index.js +1 -0
  4. package/dist/apps/install-confirmation.d.ts +26 -0
  5. package/dist/apps/install-confirmation.js +28 -0
  6. package/dist/apps/installation.d.ts +6 -0
  7. package/dist/apps/installation.js +12 -7
  8. package/dist/boot-host-script.js +1 -1
  9. package/dist/build/job-log.d.ts +2 -0
  10. package/dist/build/job-log.js +16 -1
  11. package/dist/cloudflare.d.ts +11 -1
  12. package/dist/cloudflare.js +5 -4
  13. package/dist/embed-metafiles.js +2 -2
  14. package/dist/embed-scripts.js +1 -1
  15. package/dist/frame-failure.d.ts +47 -0
  16. package/dist/frame-failure.js +75 -0
  17. package/dist/hello-app-script.js +1 -1
  18. package/dist/host.d.ts +5 -1
  19. package/dist/host.js +61 -15
  20. package/dist/install-release-cli.d.ts +1 -1
  21. package/dist/install-release-cli.js +73 -24
  22. package/dist/pack.d.ts +52 -1
  23. package/dist/pack.js +54 -11
  24. package/dist/page/app-permissions.js +2 -5
  25. package/dist/page/mount.js +2 -5
  26. package/dist/page-script.js +2 -2
  27. package/dist/standalone/agents.d.ts +1 -1
  28. package/dist/standalone/agents.js +1 -4
  29. package/dist/standalone/computer.d.ts +10 -0
  30. package/dist/standalone/computer.js +43 -1
  31. package/dist/starter-agent.d.ts +1 -3
  32. package/dist/starter-agent.js +4 -8
  33. package/dist/workers.d.ts +4 -0
  34. package/dist/workers.js +28 -1
  35. package/docs/api/apps.md +53 -0
  36. package/docs/api/cloudflare.md +151 -4
  37. package/docs/api/host.md +2 -0
  38. package/docs/api/pack.md +131 -3
  39. package/docs/api/workers-git.md +1 -1
  40. package/docs/api/workers.md +13 -0
  41. package/package.json +12 -12
package/dist/host.d.ts CHANGED
@@ -23,7 +23,7 @@ import { type ResourceOption } from "./apps/permissions.js";
23
23
  import type { AppToolPolicy } from "./apps/tools.js";
24
24
  import type { LiveOysterKey } from "./keys.js";
25
25
  import { type ServedTable, type RouteDeclaration, type Routes } from "./authorization.js";
26
- import { type AppMethodReply } from "@fungi.computer/agar/backend";
26
+ import { type AppFailureReason, type AppMethodReply } from "@fungi.computer/agar/backend";
27
27
  import type { AppCapabilityId, HostActor } from "@fungi.computer/puffball/app";
28
28
  import { type CapabilityDescriptor } from "./capability-descriptor.js";
29
29
  export { capabilityDescriptorSchema, capabilityMethodKindSchema, capabilityMethodSchema, type CapabilityDescriptor, type CapabilityMethodKind, } from "./capability-descriptor.js";
@@ -90,6 +90,10 @@ export type InstanceResult<T> = Readonly<{
90
90
  code: AppInstanceErrorCode | "failed";
91
91
  /** Closed host diagnostic; absent when the execution owner did not supply one. */
92
92
  causeClass?: "Error" | "TypeError" | "RangeError" | "SyntaxError" | "AbortError" | "TimeoutError" | "Other";
93
+ /** Why a `failed` execution failed, when the execution owner recorded it. */
94
+ reason?: AppFailureReason;
95
+ /** Names the owner's log line for that failure; shown to the person who reports it. */
96
+ ref?: string;
93
97
  }>;
94
98
  /** One running App Instance, wherever the host runs it. */
95
99
  export type InstanceHandle = Readonly<{
package/dist/host.js CHANGED
@@ -24,14 +24,14 @@ import * as Result from "effect/Result";
24
24
  import { emptyAppDeclaration } from "@fungi.computer/puffball/app";
25
25
  import { applyInstallationCommand, carryGrant, installationIdSchema, } from "./apps/installation.js";
26
26
  import { admits, scopedBindings, grantsFor } from "./apps/gate.js";
27
- import { appCallTargetName, appPermissionPageSchema, permissionSaveSchema, } from "./apps/permissions.js";
27
+ import { appCallTargetName, appPermissionPageSchema, pendingCapabilities, permissionSaveSchema, } from "./apps/permissions.js";
28
28
  import { app as appRoute, apps as appsRoute, door, member, oysterPrincipalIsOwner, owner, publicRoute, authorityOf, hostAuthorityPorts, reachesInstallation, routes, serveCapability, serveHost, } from "./authorization.js";
29
29
  import { deriveDeclaredOperations, appCallOperation, } from "./apps/operations.js";
30
30
  import { appMethodRefusalStatus, } from "@fungi.computer/agar/backend";
31
31
  import { appCallsDescriptor, } from "./capability-descriptor.js";
32
32
  export { capabilityDescriptorSchema, capabilityMethodKindSchema, capabilityMethodSchema, } from "./capability-descriptor.js";
33
33
  import { selectionOf, } from "./index.js";
34
- import { parseRelease, readCachedVerified, sha256, } from "./release.js";
34
+ import { parseRelease, readCachedVerified, ReleaseError, sha256, verifyRelease, } from "./release.js";
35
35
  import { createGitDoor } from "./git.js";
36
36
  import { maxStorageWatches, storageWatchSchema } from "./storage-watch-wire.js";
37
37
  import { getCookie } from "hono/cookie";
@@ -98,8 +98,13 @@ function installationOperationRefusal(cause) {
98
98
  function noStoreRefusal(status, error) {
99
99
  return Response.json({ error }, { status, headers: { "Cache-Control": "no-store" } });
100
100
  }
101
- function instanceRefusal(code, causeClass) {
101
+ function instanceRefusal({ code, causeClass, reason, ref, }) {
102
102
  if (code === "failed") {
103
+ // The owner recorded why: say it in the closed body Apps' pages decode.
104
+ if (reason !== undefined)
105
+ return Response.json(ref === undefined
106
+ ? { error: "App execution unavailable", reason }
107
+ : { error: "App execution unavailable", reason, ref }, { status: 502 });
103
108
  if (causeClass === undefined)
104
109
  console.error("AppInstance failure", {
105
110
  stage: "instance_execution",
@@ -661,7 +666,7 @@ export function oysterRouteTable(host) {
661
666
  const result = await host.instances
662
667
  .get(selectionOf(installation).instanceId, limits)
663
668
  .prepare({ ...selectionOf(installation), status: installation.status }, installation.release);
664
- return result.ok ? null : instanceRefusal(result.code, result.causeClass);
669
+ return result.ok ? null : instanceRefusal(result);
665
670
  };
666
671
  const apply = async (installation, verifiedRelease) => {
667
672
  if (verifiedRelease.backend === null)
@@ -669,8 +674,48 @@ export function oysterRouteTable(host) {
669
674
  const result = await host.instances
670
675
  .get(selectionOf(installation).instanceId, limits)
671
676
  .apply({ ...selectionOf(installation), status: installation.status }, installation.release);
672
- return result.ok ? null : instanceRefusal(result.code, result.causeClass);
677
+ return result.ok ? null : instanceRefusal(result);
673
678
  };
679
+ // What installing this Release would ask for, before anything is installed;
680
+ // the CLI shows it once and the owner confirms. The artifacts are already
681
+ // uploaded, and verification is the same one install runs. Over an existing
682
+ // installation the install keeps its current grants, so `update` names only
683
+ // what would newly wait for approval.
684
+ table.post("/api/installations/preview", owner("direct"), async (context) => {
685
+ let release;
686
+ let installationId;
687
+ try {
688
+ const request = Schema.decodeUnknownSync(installRequestSchema)(await context.req.json());
689
+ release = parseRelease(request.release);
690
+ installationId =
691
+ request.installationId ?? release.appId.replaceAll("_", "-");
692
+ }
693
+ catch {
694
+ return refusal(400, "Invalid install request");
695
+ }
696
+ try {
697
+ const verified = await verifyRelease(host.artifacts, release);
698
+ const declaration = verified.declaration ?? emptyAppDeclaration;
699
+ const existing = await host.installations.get(installationId);
700
+ return Response.json({
701
+ name: release.appId,
702
+ capabilities: declaration.capabilities,
703
+ update:
704
+ // A deleted id is retired: installing it again is a fresh install.
705
+ existing === null || existing.status === "deleted"
706
+ ? null
707
+ : {
708
+ installationId,
709
+ needsApproval: pendingCapabilities(existing.authority, declaration, await deriveDeclaredOperations(verified.release, declaration, host.capabilities ?? [])),
710
+ },
711
+ });
712
+ }
713
+ catch (cause) {
714
+ if (cause instanceof ReleaseError)
715
+ return refusal(422, cause.code);
716
+ throw cause;
717
+ }
718
+ });
674
719
  table.post("/api/installations", owner("direct-or-app"), async (context, { origin, principal }) => {
675
720
  let request;
676
721
  let release;
@@ -852,7 +897,7 @@ export function oysterRouteTable(host) {
852
897
  return noStoreRefusal(409, "Stale copy authority");
853
898
  const opened = await copyOwned.copies.open(copyOwned.authority, form.requestId);
854
899
  if (!opened.ok)
855
- return instanceRefusal(opened.code, opened.causeClass);
900
+ return instanceRefusal(opened);
856
901
  return new Response(null, {
857
902
  status: 303,
858
903
  headers: {
@@ -875,7 +920,7 @@ export function oysterRouteTable(host) {
875
920
  return noStoreRefusal(409, "Stale copy authority");
876
921
  const discarded = await copyOwned.copies.discard(copyOwned.authority, form.copyId);
877
922
  if (!discarded.ok)
878
- return instanceRefusal(discarded.code, discarded.causeClass);
923
+ return instanceRefusal(discarded);
879
924
  return new Response(null, {
880
925
  status: 303,
881
926
  headers: { Location: "/recovery", "Cache-Control": "no-store" },
@@ -887,7 +932,7 @@ export function oysterRouteTable(host) {
887
932
  return copyOwned;
888
933
  const observed = await copyOwned.copies.inspect(copyOwned.authority);
889
934
  if (!observed.ok)
890
- return instanceRefusal(observed.code, observed.causeClass);
935
+ return instanceRefusal(observed);
891
936
  if (observed.value?.copyId !== context.req.param("copyId"))
892
937
  return noStoreRefusal(404, "Test copy expired or discarded");
893
938
  return appTestCopyPage(copyOwned.installation.installationId, observed.value, (await releaseOf(copyOwned.installation.release)).declaration, (await assets()).page.path);
@@ -937,9 +982,7 @@ export function oysterRouteTable(host) {
937
982
  if (admitted.kind === "refused")
938
983
  return noStoreRefusal(admitted.code === "invalid_input" ? 400 : 403, admitted.code);
939
984
  const result = await copyOwned.copies.call(copyOwned.authority, copyId.data, name, input, invocationCallerContext(copyOwned.principal, null, host.tenantId));
940
- return result.ok
941
- ? methodResponse(result.value)
942
- : instanceRefusal(result.code, result.causeClass);
985
+ return result.ok ? methodResponse(result.value) : instanceRefusal(result);
943
986
  });
944
987
  table.get("/api/installations/:installationId/recovery", owner("direct"), async (context) => {
945
988
  if (!sameOriginReadRequest(context.req.raw))
@@ -1337,7 +1380,7 @@ export function oysterRouteTable(host) {
1337
1380
  release.backend === null)
1338
1381
  return refusal(404, "Gill is not declared");
1339
1382
  if (installation.instanceId === null)
1340
- return instanceRefusal("invalid_invocation_facts");
1383
+ return instanceRefusal({ code: "invalid_invocation_facts" });
1341
1384
  const params = request.params ?? {};
1342
1385
  const declared = gill.params ?? [];
1343
1386
  if (Object.keys(params).some((key) => !declared.some((param) => param.key === key)))
@@ -1406,13 +1449,16 @@ export function oysterRouteTable(host) {
1406
1449
  .get(facts.instanceId, limits)
1407
1450
  .gill(facts, release.api, source, { id: viewId, ...selectors });
1408
1451
  if (!result.ok)
1409
- return instanceRefusal(result.code, result.causeClass);
1452
+ return instanceRefusal(result);
1410
1453
  try {
1411
1454
  const reply = decodeGillReply(result.value);
1412
1455
  return Response.json("viewId" in reply ? decodeDeclaredGillResponse(reply, gill) : reply);
1413
1456
  }
1414
1457
  catch (error) {
1415
- return instanceRefusal("failed", causeClass(error));
1458
+ return instanceRefusal({
1459
+ code: "failed",
1460
+ causeClass: causeClass(error),
1461
+ });
1416
1462
  }
1417
1463
  });
1418
1464
  const executeMethod = async (installation, release, principal, name, request, recheck) => {
@@ -1454,7 +1500,7 @@ export function oysterRouteTable(host) {
1454
1500
  .get(selectionOf(installation).instanceId, limits)
1455
1501
  .call(await admittedMethodCallerFacts(host, installation, release, invocationCallerContext(principal, host.computerId ?? null, host.tenantId), decision.grants, { name, effect: method.effect }), release.api, name, input);
1456
1502
  if (!result.ok)
1457
- return instanceRefusal(result.code, result.causeClass);
1503
+ return instanceRefusal(result);
1458
1504
  return methodResponse(result.value);
1459
1505
  };
1460
1506
  table.post("/apps/:installationId/methods/:name", appRoute(), async (context, { principal }) => {
@@ -1,3 +1,3 @@
1
1
  import { Cli } from "@fungi.computer/lantern";
2
- export declare const installReleaseUsage = "Usage: oyster install <directory|release.json> [--installation-id <name>]";
2
+ export declare const installReleaseUsage = "Usage: oyster install <directory|release.json>... [--installation-id <name>] [--yes]";
3
3
  export declare function installReleaseCommand(args: readonly string[], ui?: Cli): Promise<void>;
@@ -4,8 +4,9 @@ import { basename, dirname, resolve } from "node:path";
4
4
  import process from "node:process";
5
5
  import { parseArgs } from "node:util";
6
6
  import { Cli } from "@fungi.computer/lantern";
7
- import { installRelease } from "./pack.js";
8
- export const installReleaseUsage = "Usage: oyster install <directory|release.json> [--installation-id <name>]";
7
+ import { installConfirmation, permissionCatalog } from "./apps/index.js";
8
+ import { installRelease, previewRelease } from "./pack.js";
9
+ export const installReleaseUsage = "Usage: oyster install <directory|release.json>... [--installation-id <name>] [--yes]";
9
10
  export async function installReleaseCommand(args,
10
11
  // Progress goes to stderr so stdout stays the installation result.
11
12
  ui = new Cli({ brand: "fungi", output: process.stderr })) {
@@ -15,40 +16,88 @@ ui = new Cli({ brand: "fungi", output: process.stderr })) {
15
16
  strict: true,
16
17
  options: {
17
18
  "installation-id": { type: "string" },
19
+ yes: { type: "boolean", short: "y" },
18
20
  help: { type: "boolean", short: "h" },
19
21
  },
20
22
  });
21
23
  if (values.help) {
22
24
  process.stdout.write(installReleaseUsage +
23
- "\nUpload a built Release and install it using OYSTER_URL and OYSTER_OWNER_KEY.\n");
25
+ "\nUpload built Releases and install them using OYSTER_URL and OYSTER_OWNER_KEY.\nYou confirm the Apps' permissions once for the whole install; --yes confirms without asking.\n");
24
26
  return;
25
27
  }
26
- const [source] = positionals;
27
- if (positionals.length !== 1 || source === undefined)
28
+ if (positionals.length === 0 ||
29
+ (positionals.length > 1 && values["installation-id"] !== undefined))
28
30
  throw new Error(installReleaseUsage);
29
31
  const url = process.env.OYSTER_URL;
30
32
  const key = process.env.OYSTER_OWNER_KEY;
31
33
  if (!url || !key)
32
34
  throw new Error("Set OYSTER_URL and OYSTER_OWNER_KEY for the target Oyster. " +
33
35
  installReleaseUsage);
34
- const path = resolve(source);
35
- const info = await stat(path);
36
- if (!info.isDirectory() &&
37
- (!info.isFile() || basename(path) !== "release.json"))
38
- throw new Error("Expected a Release directory or release.json");
39
- ui.welcome("Oyster: install a Release");
40
- const body = await ui.task(`Installing ${basename(path)}`, async () => {
41
- const response = await installRelease({
42
- directory: info.isDirectory() ? path : dirname(path),
43
- url,
44
- key,
45
- installationId: values["installation-id"],
46
- });
47
- const text = await response.text();
48
- if (!response.ok)
49
- throw new Error("Installation failed (" + String(response.status) + "): " + text);
50
- return text;
36
+ const directories = await Promise.all(positionals.map(async (source) => {
37
+ const path = resolve(source);
38
+ const info = await stat(path);
39
+ if (!info.isDirectory() &&
40
+ (!info.isFile() || basename(path) !== "release.json"))
41
+ throw new Error("Expected a Release directory or release.json");
42
+ return info.isDirectory() ? path : dirname(path);
43
+ }));
44
+ ui.welcome("Oyster: install Releases");
45
+ // One list for the whole install, from the rule the install itself applies.
46
+ const previews = await ui.task("Checking what the Apps ask for", async () => {
47
+ const found = [];
48
+ for (const directory of directories)
49
+ found.push({
50
+ directory,
51
+ ...(await previewRelease({
52
+ directory,
53
+ url,
54
+ key,
55
+ installationId: values["installation-id"],
56
+ })),
57
+ });
58
+ return found;
51
59
  });
52
- process.stdout.write(body.trim() + "\n");
53
- ui.outro(`Open ${url}/ to use it.`);
60
+ // A fresh install grants by the shared rule; an update keeps its current
61
+ // grants, so it lists only what newly waits for approval.
62
+ const confirmation = installConfirmation("owner", previews.filter(({ update }) => update === null));
63
+ const lines = (rows) => rows.map((row) => `${row.label}: ${row.description}${row.warning === null ? "" : ` ${row.warning}`} (${row.apps.join(", ")})`);
64
+ if (confirmation.granted.length > 0)
65
+ ui.note(`Installing ${previews
66
+ .filter(({ update }) => update === null)
67
+ .map(({ name }) => name)
68
+ .join(", ")} lets them:`, lines(confirmation.granted));
69
+ if (confirmation.needsApproval.length > 0)
70
+ ui.note("Not granted by installing; approve in Settings > Permissions:", lines(confirmation.needsApproval));
71
+ for (const { name, update } of previews)
72
+ if (update !== null)
73
+ ui.note(`Updating ${update.installationId} (${name}) keeps its current permissions:`, update.needsApproval.length === 0
74
+ ? ["Nothing new is requested."]
75
+ : [
76
+ "Newly requested, waiting for approval in Settings > Permissions:",
77
+ ...update.needsApproval.map((capability) => permissionCatalog[capability].label),
78
+ ]);
79
+ if (values.yes !== true) {
80
+ const answer = await ui.confirm({
81
+ message: `Install ${String(previews.length)} App${previews.length === 1 ? "" : "s"} with these permissions?`,
82
+ });
83
+ if (answer !== true)
84
+ throw new Error("Install cancelled; nothing was installed. Run with --yes to confirm without asking.");
85
+ }
86
+ for (const { directory, release } of previews) {
87
+ const body = await ui.task(`Installing ${basename(directory)}`, async () => {
88
+ const response = await installRelease({
89
+ directory,
90
+ uploaded: release,
91
+ url,
92
+ key,
93
+ installationId: values["installation-id"],
94
+ });
95
+ const text = await response.text();
96
+ if (!response.ok)
97
+ throw new Error("Installation failed (" + String(response.status) + "): " + text);
98
+ return text;
99
+ });
100
+ process.stdout.write(body.trim() + "\n");
101
+ }
102
+ ui.outro(`Open ${url}/ to use ${directories.length === 1 ? "it" : "them"}.`);
54
103
  }
package/dist/pack.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type InstallationCompletion, type InstallationObservationBudget } from "./installation-client.js";
2
- import { type ArtifactRef, type Release } from "@fungi.computer/puffball";
2
+ import { type ArtifactRef, type Release, type Sha256Digest } from "@fungi.computer/puffball";
3
3
  import { type AppPublisherCoreConfigInput } from "./build.js";
4
4
  import type { InstallationOperation } from "./installation-operations.js";
5
5
  export { InstallationObservationError, type InstallationCompletion, } from "./installation-client.js";
@@ -58,6 +58,55 @@ export declare function installFromSource(input: Readonly<{
58
58
  key: string;
59
59
  installationId: string;
60
60
  }> & InstallationObservationBudget): Promise<Response>;
61
+ /** Read a built Release directory and upload its artifacts; uploads are idempotent. */
62
+ declare function uploadRelease(input: Readonly<{
63
+ directory: string;
64
+ url: string;
65
+ key: string;
66
+ signal: AbortSignal;
67
+ }>): Promise<{
68
+ readonly releaseId: import("@fungi.computer/puffball").ReleaseId;
69
+ readonly appId: import("@fungi.computer/puffball").AppId;
70
+ readonly artifact: {
71
+ readonly artifactRef: ArtifactRef;
72
+ readonly artifactDigest: Sha256Digest;
73
+ readonly provenance: {
74
+ readonly sourceRevision: import("@fungi.computer/puffball").SourceRevision;
75
+ readonly sourceTreeDigest: Sha256Digest;
76
+ readonly buildRecipeDigest: Sha256Digest;
77
+ };
78
+ };
79
+ }>;
80
+ /**
81
+ * Upload one built Release and ask the Oyster what installing it would
82
+ * request, so an owner can confirm several Releases once before any install.
83
+ */
84
+ export declare function previewRelease(input: Readonly<{
85
+ directory: string;
86
+ url: string;
87
+ key: string;
88
+ installationId?: string | undefined;
89
+ }>): Promise<{
90
+ release: {
91
+ readonly releaseId: import("@fungi.computer/puffball").ReleaseId;
92
+ readonly appId: import("@fungi.computer/puffball").AppId;
93
+ readonly artifact: {
94
+ readonly artifactRef: ArtifactRef;
95
+ readonly artifactDigest: Sha256Digest;
96
+ readonly provenance: {
97
+ readonly sourceRevision: import("@fungi.computer/puffball").SourceRevision;
98
+ readonly sourceTreeDigest: Sha256Digest;
99
+ readonly buildRecipeDigest: Sha256Digest;
100
+ };
101
+ };
102
+ };
103
+ name: string;
104
+ capabilities: readonly ("computer.list" | "computer.readFile" | "computer.writeFile" | "computer.execute" | "approvals" | "agent.list" | "agent.manage" | "agent.rename" | "agent.avatar" | "agent.instructions" | "agent.toolPolicy" | "agent.read" | "agent.send" | "llm.generation" | "media.generation" | "media.share" | "games:servers" | "git.repository" | "apps.open" | "apps.call" | "app.storage" | "app.events.emit" | "team.workbenchHost" | "marketplace.browse" | "marketplace.purchase" | "workflow.run" | "workflow.publish" | "workflow.arm" | "world" | "channels.read" | "channels.personal.manage")[];
105
+ update: {
106
+ readonly installationId: string;
107
+ readonly needsApproval: readonly ("computer.list" | "computer.readFile" | "computer.writeFile" | "computer.execute" | "approvals" | "agent.list" | "agent.manage" | "agent.rename" | "agent.avatar" | "agent.instructions" | "agent.toolPolicy" | "agent.read" | "agent.send" | "llm.generation" | "media.generation" | "media.share" | "games:servers" | "git.repository" | "apps.open" | "apps.call" | "app.storage" | "app.events.emit" | "team.workbenchHost" | "marketplace.browse" | "marketplace.purchase" | "workflow.run" | "workflow.publish" | "workflow.arm" | "world" | "channels.read" | "channels.personal.manage")[];
108
+ } | null;
109
+ }>;
61
110
  /**
62
111
  * Upload a packed Release to an Oyster and install it. The host installs a
63
112
  * new installation (201) or switches an existing one to this Release (200),
@@ -73,6 +122,8 @@ export declare function installRelease(input: Readonly<{
73
122
  /** The Oyster owner key. */
74
123
  key: string;
75
124
  installationId?: string;
125
+ /** The Release `previewRelease` already read and uploaded; skips both. */
126
+ uploaded?: Awaited<ReturnType<typeof uploadRelease>>;
76
127
  /** Report owner-correlated admission without shortening the completion wait. */
77
128
  onAdmitted?: (operation: InstallationOperation) => void;
78
129
  /** Runs once with the completed operation, before the response is made. */
package/dist/pack.js CHANGED
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
5
5
  import * as Cause from "effect/Cause";
6
6
  import * as Exit from "effect/Exit";
7
7
  import * as Schema from "effect/Schema";
8
+ import { appCapabilityIdSchema } from "@fungi.computer/puffball/app";
8
9
  import { releaseSchema } from "@fungi.computer/puffball/effect";
9
10
  import { installOnOyster, installationObservationSignal, completedInstallationResponse, } from "./installation-client.js";
10
11
  import { parseArtifactRef, parseReleaseId, parseSha256Digest, parseSourceRevision, } from "@fungi.computer/puffball";
@@ -115,6 +116,58 @@ export async function installFromSource(input) {
115
116
  await rm(outDirectory, { recursive: true, force: true });
116
117
  }
117
118
  }
119
+ /** Read a built Release directory and upload its artifacts; uploads are idempotent. */
120
+ async function uploadRelease(input) {
121
+ const directory = resolve(input.directory);
122
+ const release = Schema.decodeUnknownSync(Schema.fromJsonString(releaseSchema))(await readFile(join(directory, "release.json"), "utf8"));
123
+ const authorization = { Authorization: `Bearer ${input.key}` };
124
+ for (const file of await filesUnder(join(directory, "artifacts"))) {
125
+ const bytes = new Uint8Array(await readFile(file));
126
+ const artifactRef = `artifact:${relative(join(directory, "artifacts"), file)}`;
127
+ const digest = parseSha256Digest(await sha256(bytes));
128
+ const response = await fetch(new URL(`/api/artifacts/${encodeURIComponent(artifactRef)}?digest=${digest}`, input.url), {
129
+ method: "PUT",
130
+ headers: authorization,
131
+ body: bytes,
132
+ signal: input.signal,
133
+ });
134
+ if (!response.ok)
135
+ throw new Error(`Artifact upload failed (${String(response.status)}): ${artifactRef}`);
136
+ }
137
+ return release;
138
+ }
139
+ const releasePreviewSchema = Schema.Struct({
140
+ name: Schema.String,
141
+ capabilities: Schema.Array(appCapabilityIdSchema),
142
+ /** Set when this Release would update an existing installation. */
143
+ update: Schema.NullOr(Schema.Struct({
144
+ installationId: Schema.String,
145
+ needsApproval: Schema.Array(appCapabilityIdSchema),
146
+ })),
147
+ });
148
+ /**
149
+ * Upload one built Release and ask the Oyster what installing it would
150
+ * request, so an owner can confirm several Releases once before any install.
151
+ */
152
+ export async function previewRelease(input) {
153
+ const signal = installationObservationSignal({});
154
+ const release = await uploadRelease({ ...input, signal });
155
+ const response = await fetch(new URL("/api/installations/preview", input.url), {
156
+ method: "POST",
157
+ headers: {
158
+ Authorization: `Bearer ${input.key}`,
159
+ "Content-Type": "application/json",
160
+ },
161
+ body: JSON.stringify({ release }),
162
+ signal,
163
+ });
164
+ if (!response.ok)
165
+ throw new Error(`Install preview failed (${String(response.status)}): ${await response.text()}`);
166
+ return {
167
+ ...Schema.decodeUnknownSync(releasePreviewSchema)(await response.json()),
168
+ release,
169
+ };
170
+ }
118
171
  /**
119
172
  * Upload a packed Release to an Oyster and install it. The host installs a
120
173
  * new installation (201) or switches an existing one to this Release (200),
@@ -128,17 +181,7 @@ export async function installRelease(input) {
128
181
  // One installer budget for uploads + observation, not an App authority grant.
129
182
  const signal = installationObservationSignal(input);
130
183
  signal.throwIfAborted();
131
- const directory = resolve(input.directory);
132
- const release = Schema.decodeUnknownSync(Schema.fromJsonString(releaseSchema))(await readFile(join(directory, "release.json"), "utf8"));
133
- const authorization = { Authorization: `Bearer ${input.key}` };
134
- for (const file of await filesUnder(join(directory, "artifacts"))) {
135
- const bytes = new Uint8Array(await readFile(file));
136
- const artifactRef = `artifact:${relative(join(directory, "artifacts"), file)}`;
137
- const digest = parseSha256Digest(await sha256(bytes));
138
- const response = await fetch(new URL(`/api/artifacts/${encodeURIComponent(artifactRef)}?digest=${digest}`, input.url), { method: "PUT", headers: authorization, body: bytes, signal });
139
- if (!response.ok)
140
- throw new Error(`Artifact upload failed (${String(response.status)}): ${artifactRef}`);
141
- }
184
+ const release = input.uploaded ?? (await uploadRelease({ ...input, signal }));
142
185
  let installation = {
143
186
  url: input.url,
144
187
  key: input.key,
@@ -152,7 +152,6 @@ function PermissionEditor({ port, appKey, onAccepted, onStateChange, }) {
152
152
  const [retired, setRetired] = useState(false);
153
153
  const [refreshNeeded, setRefreshNeeded] = useState(false);
154
154
  const [message, setMessage] = useState(null);
155
- const [saved, setSaved] = useState(false);
156
155
  const [loadError, setLoadError] = useState(false);
157
156
  const [reload, setReload] = useState(0);
158
157
  const [otherOpen, setOtherOpen] = useState(false);
@@ -205,8 +204,7 @@ function PermissionEditor({ port, appKey, onAccepted, onStateChange, }) {
205
204
  if (!mounted.current)
206
205
  return;
207
206
  setRefreshNeeded(false);
208
- setSaved(true);
209
- setMessage("Permissions saved");
207
+ toast.success("Permissions saved", { toasterId: describeId });
210
208
  }
211
209
  catch (cause) {
212
210
  console.error("App permissions surrounding-screen refresh failed", cause);
@@ -232,7 +230,6 @@ function PermissionEditor({ port, appKey, onAccepted, onStateChange, }) {
232
230
  return;
233
231
  setSaving(true);
234
232
  setRefreshNeeded(false);
235
- setSaved(false);
236
233
  setMessage(null);
237
234
  try {
238
235
  if (!uncertain) {
@@ -386,7 +383,7 @@ function PermissionEditor({ port, appKey, onAccepted, onStateChange, }) {
386
383
  ? `${view.appName} asks for`
387
384
  : `${view.appName} permissions`, headings: gridHeadings, rows: first })), later.length > 0 && (_jsx(Disclosure, { open: otherOpen, onOpenChange: setOtherOpen, summary: `Other permissions · ${String(later.length)}`, children: _jsx(PermissionGrid, { caption: "Already decided", headings: gridHeadings, rows: later }) })), _jsx("div", { className: "sr-only", children: groups
388
385
  .flatMap((group) => [...group.columns, ...group.switches])
389
- .map((column) => (_jsxs("p", { id: `${describeId}-${column.capability}`, children: [column.description, column.warning === null ? "" : ` ${column.warning}`] }, column.capability))) }), screen.groups.length === 0 && _jsx("p", { children: "This App requests no permissions." }), message !== null && !showFooter && (_jsx("p", { role: "status", "aria-live": "polite", children: message })), showFooter && (_jsxs(FormFooter, { divider: false, children: [message !== null && saved && !uncertain && !refreshNeeded && (_jsx(Status, { role: "status", size: "compact", glyph: "dot", tone: "success", label: message })), refreshNeeded && (_jsx(Button, { type: "button", size: "xs", variant: "outline", disabled: saving, onClick: () => void retryRefresh(), children: "Retry screen refresh" })), (changes.length > 0 || saving || uncertain) && (_jsx(Button, { type: "submit", variant: "primary", disabled: saving || retired || !screen.canEdit, children: saving
386
+ .map((column) => (_jsxs("p", { id: `${describeId}-${column.capability}`, children: [column.description, column.warning === null ? "" : ` ${column.warning}`] }, column.capability))) }), screen.groups.length === 0 && _jsx("p", { children: "This App requests no permissions." }), message !== null && !showFooter && (_jsx("p", { role: "status", "aria-live": "polite", children: message })), showFooter && (_jsxs(FormFooter, { divider: false, children: [refreshNeeded && (_jsx(Button, { type: "button", size: "xs", variant: "outline", disabled: saving, onClick: () => void retryRefresh(), children: "Retry screen refresh" })), (changes.length > 0 || saving || uncertain) && (_jsx(Button, { type: "submit", variant: "primary", disabled: saving || retired || !screen.canEdit, children: saving
390
387
  ? "Saving…"
391
388
  : uncertain
392
389
  ? "Review current permissions"
@@ -14,7 +14,7 @@ import { OysterAgentBrowserHost } from "./agent-browser.js";
14
14
  import { createPageLifetime } from "./lifetime.js";
15
15
  import { computerTargetUrl } from "../computer-target.js";
16
16
  import * as Schema from "effect/Schema";
17
- import { AppError, createCapabilityRegistry, } from "@fungi.computer/agar";
17
+ import { AppError, readAppFailure, createCapabilityRegistry, } from "@fungi.computer/agar";
18
18
  import { appStorage } from "@fungi.computer/agar/storage";
19
19
  import { approvals } from "@fungi.computer/agar/approvals";
20
20
  import { oysterStorageHandle } from "./storage.js";
@@ -51,10 +51,7 @@ async function answer(response) {
51
51
  retryable: false,
52
52
  });
53
53
  if (!response.ok)
54
- throw new AppError("App backend request failed", {
55
- code: "HOST_FAILURE",
56
- retryable: response.status >= 500,
57
- });
54
+ throw await readAppFailure(response);
58
55
  return parseJsonValue(await response.json());
59
56
  }
60
57
  /** The App's typed methods, reached through this host's method route. */