@fungi.computer/oyster 0.11.0 → 0.12.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 (50) hide show
  1. package/README.md +70 -10
  2. package/dist/app-builds.d.ts +2 -0
  3. package/dist/app-builds.js +17 -6
  4. package/dist/authorization.d.ts +1 -1
  5. package/dist/build/artifact-writer.d.ts +11 -2
  6. package/dist/build/artifact-writer.js +42 -24
  7. package/dist/build/candidate-cli.mjs +26 -18
  8. package/dist/build/content-objects.d.ts +29 -14
  9. package/dist/build/content-objects.js +57 -19
  10. package/dist/build/local-build.js +3 -0
  11. package/dist/build/submission-contract.d.ts +1 -1
  12. package/dist/build/submission-contract.js +5 -5
  13. package/dist/build-egress.d.ts +8 -7
  14. package/dist/build-egress.js +4 -3
  15. package/dist/build.d.ts +1 -1
  16. package/dist/install-release-cli.d.ts +2 -1
  17. package/dist/install-release-cli.js +18 -10
  18. package/dist/installation-client.d.ts +1 -0
  19. package/dist/installation-operations.d.ts +2 -0
  20. package/dist/installation-operations.js +1 -0
  21. package/dist/pack.d.ts +5 -2
  22. package/dist/pack.js +3 -1
  23. package/dist/standalone/agents.d.ts +6 -2
  24. package/dist/standalone/agents.js +21 -4
  25. package/dist/standalone/computer-egress.d.ts +5 -3
  26. package/dist/standalone/computer-egress.js +1 -1
  27. package/dist/standalone/hello-app.d.ts +9 -0
  28. package/dist/standalone/hello-app.js +78 -0
  29. package/dist/standalone/install-apps-cli.d.ts +2 -1
  30. package/dist/standalone/install-apps-cli.js +36 -14
  31. package/dist/standalone/instance.js +2 -2
  32. package/dist/standalone/local-desktop.d.ts +11 -0
  33. package/dist/standalone/local-desktop.js +75 -0
  34. package/dist/standalone/registry.d.ts +2 -0
  35. package/dist/standalone/sign-in-link.d.ts +9 -0
  36. package/dist/standalone/sign-in-link.js +49 -0
  37. package/dist/standalone/try-cli.d.ts +52 -0
  38. package/dist/standalone/try-cli.js +404 -0
  39. package/dist/standalone/worker.js +1 -1
  40. package/dist/webhook-abuse.d.ts +7 -1
  41. package/dist/webhook-abuse.js +8 -2
  42. package/dist/workers.d.ts +7 -2
  43. package/dist/workers.js +1 -1
  44. package/docs/api/authorization.md +56 -11
  45. package/docs/api/build-contract.md +52 -10
  46. package/docs/api/build.md +16 -2
  47. package/docs/api/host.md +1 -0
  48. package/docs/api/pack.md +179 -3
  49. package/docs/site/agent-quickstart.mdx +8 -0
  50. package/package.json +9 -8
@@ -814,7 +814,7 @@ export declare function candidateObjectMediaType(value: string | null): Candidat
814
814
  export type CandidateUpload = CandidateObject & Readonly<{
815
815
  mediaType: CandidateObjectMediaType;
816
816
  }>;
817
- /** Every distinct object a manifest names, each once, in manifest order. */
817
+ /** Every distinct object (digest and stored type) a manifest names, each once, in manifest order. */
818
818
  export declare function candidateManifestObjects(output: CandidateOutputManifest): readonly CandidateUpload[];
819
819
  /** Decode a stored backend descriptor; a manifest's backend must be one. */
820
820
  export declare function decodeCandidateBackend(bytes: Uint8Array): {
@@ -148,19 +148,19 @@ export const candidateObjectMediaTypes = [
148
148
  export function candidateObjectMediaType(value) {
149
149
  return candidateObjectMediaTypes.find((type) => type === value) ?? null;
150
150
  }
151
- /** Every distinct object a manifest names, each once, in manifest order. */
151
+ /** Every distinct object (digest and stored type) a manifest names, each once, in manifest order. */
152
152
  export function candidateManifestObjects(output) {
153
153
  const objects = [];
154
154
  const add = (object, mediaType) => {
155
- const seen = objects.find(({ digest }) => digest === object.digest);
156
- if (seen === undefined)
155
+ const named = objects.filter(({ digest }) => digest === object.digest);
156
+ if (named.some(({ byteLength }) => byteLength !== object.byteLength))
157
+ throw new Error("One object digest names two sizes");
158
+ if (!named.some((seen) => seen.mediaType === mediaType))
157
159
  objects.push({
158
160
  digest: object.digest,
159
161
  byteLength: object.byteLength,
160
162
  mediaType,
161
163
  });
162
- else if (seen.byteLength !== object.byteLength)
163
- throw new Error("One object digest names two sizes");
164
164
  };
165
165
  if (output.kind !== "backend") {
166
166
  const { content } = output.ui;
@@ -39,21 +39,22 @@ export declare function isBuildGitPrincipal<P extends Readonly<{
39
39
  * The build-report handler for `/jobs/:id/(candidate|artifact|status)` and
40
40
  * `PUT /jobs/:id/objects/sha256-<hex>`. `admitBuild` is the host's own
41
41
  * live-job lookup; `admitObject` admits one object upload for a live job's
42
- * grant and answers its size bound; `storeObject` streams an admitted object
43
- * into the host's content-addressed store, which verifies its digest;
42
+ * grant and answers its size bound (and whatever else the host's store needs,
43
+ * such as the owner namespace); `storeObject` streams an admitted object into
44
+ * the host's content-addressed store, which verifies its digest;
44
45
  * `submitCandidate` hands an admitted manifest to the host's Publisher
45
46
  * custody; `record` delivers a reported fact to the host's own projection.
46
47
  * `report` observes a body or JSON decode failure without changing its 400
47
48
  * outcome; a host may wire its own structured logger or omit it.
48
49
  */
49
- export declare function createBuildEgress(options: Readonly<{
50
+ export declare function createBuildEgress<Admission extends Readonly<{
51
+ maxObjectBytes: number;
52
+ }>>(options: Readonly<{
50
53
  admitBuild: (jobId: string) => Promise<Readonly<{
51
54
  credentialId: string;
52
55
  }> | null>;
53
- admitObject: (jobId: string, grant: string) => Promise<Readonly<{
54
- maxObjectBytes: number;
55
- }> | null>;
56
- storeObject: (object: CandidateObject, body: ReadableStream<Uint8Array> | null, mediaType: CandidateObjectMediaType) => Promise<"stored" | "refused">;
56
+ admitObject: (jobId: string, grant: string) => Promise<Admission | null>;
57
+ storeObject: (object: CandidateObject, body: ReadableStream<Uint8Array> | null, mediaType: CandidateObjectMediaType, admitted: Admission) => Promise<"stored" | "refused">;
57
58
  submitCandidate: (jobId: string, manifest: TeamAppCandidateManifest, grant: string, credentialId: string) => Promise<Response>;
58
59
  record: (event: BuildGitEvent) => Promise<void>;
59
60
  report?: (operation: string, cause: unknown) => void;
@@ -34,8 +34,9 @@ export function isBuildGitPrincipal(principal) {
34
34
  * The build-report handler for `/jobs/:id/(candidate|artifact|status)` and
35
35
  * `PUT /jobs/:id/objects/sha256-<hex>`. `admitBuild` is the host's own
36
36
  * live-job lookup; `admitObject` admits one object upload for a live job's
37
- * grant and answers its size bound; `storeObject` streams an admitted object
38
- * into the host's content-addressed store, which verifies its digest;
37
+ * grant and answers its size bound (and whatever else the host's store needs,
38
+ * such as the owner namespace); `storeObject` streams an admitted object into
39
+ * the host's content-addressed store, which verifies its digest;
39
40
  * `submitCandidate` hands an admitted manifest to the host's Publisher
40
41
  * custody; `record` delivers a reported fact to the host's own projection.
41
42
  * `report` observes a body or JSON decode failure without changing its 400
@@ -67,7 +68,7 @@ export function createBuildEgress(options) {
67
68
  const stored = await options.storeObject(Schema.decodeUnknownSync(candidateObjectSchema)({
68
69
  digest: `sha256:${hex}`,
69
70
  byteLength,
70
- }), request.body, mediaType);
71
+ }), request.body, mediaType, admitted);
71
72
  return new Response(null, { status: stored === "stored" ? 204 : 400 });
72
73
  };
73
74
  return Object.freeze({
package/dist/build.d.ts CHANGED
@@ -9,4 +9,4 @@ export { frozenSnapshotInstallArguments } from "./build/snapshot-package-store.j
9
9
  export { repositoryEnvironment, artifactsGitEnvironment, hostedArtifactsGitRemote, } from "./build/git-environment.js";
10
10
  /** Captured-dependency build program with guarded filesystem access. */
11
11
  export declare const dependencyBuildProgram: string;
12
- export { stageBuildOutput, writeArtifactRoot, type ImmutableArtifactObjects, type StagedArtifactObject, type StagedBuildOutput, } from "./build/artifact-writer.js";
12
+ export { stageBuildOutput, writeArtifactRoot, type ImmutableArtifactObjects, type StagedArtifactObject, type StagedCandidateObject, type StagedBuildOutput, } from "./build/artifact-writer.js";
@@ -1,2 +1,3 @@
1
+ import { Cli } from "@fungi.computer/lantern";
1
2
  export declare const installReleaseUsage = "Usage: oyster install <directory|release.json> [--installation-id <name>]";
2
- export declare function installReleaseCommand(args: readonly string[]): Promise<void>;
3
+ export declare function installReleaseCommand(args: readonly string[], ui?: Cli): Promise<void>;
@@ -3,9 +3,12 @@ import { stat } from "node:fs/promises";
3
3
  import { basename, dirname, resolve } from "node:path";
4
4
  import process from "node:process";
5
5
  import { parseArgs } from "node:util";
6
+ import { Cli } from "@fungi.computer/lantern";
6
7
  import { installRelease } from "./pack.js";
7
8
  export const installReleaseUsage = "Usage: oyster install <directory|release.json> [--installation-id <name>]";
8
- export async function installReleaseCommand(args) {
9
+ export async function installReleaseCommand(args,
10
+ // Progress goes to stderr so stdout stays the installation result.
11
+ ui = new Cli({ brand: "fungi", output: process.stderr })) {
9
12
  const { values, positionals } = parseArgs({
10
13
  args: [...args],
11
14
  allowPositionals: true,
@@ -33,14 +36,19 @@ export async function installReleaseCommand(args) {
33
36
  if (!info.isDirectory() &&
34
37
  (!info.isFile() || basename(path) !== "release.json"))
35
38
  throw new Error("Expected a Release directory or release.json");
36
- const response = await installRelease({
37
- directory: info.isDirectory() ? path : dirname(path),
38
- url,
39
- key,
40
- installationId: values["installation-id"],
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;
41
51
  });
42
- const body = await response.text();
43
- if (!response.ok)
44
- throw new Error("Installation failed (" + String(response.status) + "): " + body);
45
- process.stdout.write(body + "\n");
52
+ process.stdout.write(body.trim() + "\n");
53
+ ui.outro(`Open ${url}/ to use it.`);
46
54
  }
@@ -1,5 +1,6 @@
1
1
  import type { Release } from "@fungi.computer/puffball";
2
2
  import { type InstallationOperation } from "./installation-operations.js";
3
+ /** An installation operation that has finished: it is no longer pending. */
3
4
  export type InstallationCompletion = Exclude<InstallationOperation, {
4
5
  state: "pending";
5
6
  }>;
@@ -127,6 +127,7 @@ declare const installationOutcomeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
127
127
  }, z.core.$strict>], "state">;
128
128
  export type InstallationOutcome = z.output<typeof installationOutcomeSchema>;
129
129
  /** One wire contract for admission and subsequent authoritative observation. */
130
+ /** Parses the owner's answer about one installation request: pending, installed, refused or unconfirmed. */
130
131
  export declare const installationOperationSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
131
132
  state: z.ZodLiteral<"pending">;
132
133
  requestId: z.ZodString;
@@ -323,6 +324,7 @@ export declare const installationOperationSchema: z.ZodDiscriminatedUnion<[z.Zod
323
324
  };
324
325
  }, unknown>>;
325
326
  }, z.core.$strict>], "state">;
327
+ /** The owner's answer about one installation request. */
326
328
  export type InstallationOperation = z.output<typeof installationOperationSchema>;
327
329
  declare const installationAdmissionSchema: z.ZodObject<{
328
330
  requestId: z.ZodString;
@@ -76,6 +76,7 @@ const terminalOperationSchema = z.discriminatedUnion("state", [
76
76
  unconfirmedSchema.extend(identity),
77
77
  ]);
78
78
  /** One wire contract for admission and subsequent authoritative observation. */
79
+ /** Parses the owner's answer about one installation request: pending, installed, refused or unconfirmed. */
79
80
  export const installationOperationSchema = z.discriminatedUnion("state", [
80
81
  pendingOperationSchema,
81
82
  successReferenceSchema
package/dist/pack.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { type InstallationObservationBudget } from "./installation-client.js";
1
+ import { type InstallationCompletion, type InstallationObservationBudget } from "./installation-client.js";
2
2
  import { type ArtifactRef, type Release } from "@fungi.computer/puffball";
3
3
  import { type AppPublisherCoreConfigInput } from "./build.js";
4
4
  import type { InstallationOperation } from "./installation-operations.js";
5
- export { InstallationObservationError } from "./installation-client.js";
5
+ export { InstallationObservationError, type InstallationCompletion, } from "./installation-client.js";
6
+ export { installationOperationSchema, type InstallationOperation, } from "./installation-operations.js";
6
7
  /** One committed repository and its canonical App build recipe. */
7
8
  export type PackOptions = Readonly<{
8
9
  /** The App's ID, `app_<name>`. */
@@ -72,6 +73,8 @@ export declare function installRelease(input: Readonly<{
72
73
  installationId?: string;
73
74
  /** Report owner-correlated admission without shortening the completion wait. */
74
75
  onAdmitted?: (operation: InstallationOperation) => void;
76
+ /** Runs once with the completed operation, before the response is made. */
77
+ onCompleted?: (operation: InstallationCompletion) => Promise<void>;
75
78
  }> & InstallationObservationBudget): Promise<Response>;
76
79
  /** Project one exact first-party commit's editable source, `git push` it to
77
80
  * an Oyster's own template for that App, and claim the pushed head, so
package/dist/pack.js CHANGED
@@ -10,7 +10,8 @@ import { commitPreparedCandidate, createAppCandidatePreparer, createArtifactsSou
10
10
  import { templateSeedClaimSchema, } from "./source/template-seed.js";
11
11
  import { pushTemplateSource } from "./source/template-push.js";
12
12
  import { sha256 } from "./release.js";
13
- export { InstallationObservationError } from "./installation-client.js";
13
+ export { InstallationObservationError, } from "./installation-client.js";
14
+ export { installationOperationSchema, } from "./installation-operations.js";
14
15
  async function filesUnder(directory) {
15
16
  const entries = await readdir(directory, {
16
17
  recursive: true,
@@ -127,6 +128,7 @@ export async function installRelease(input) {
127
128
  if (input.onAdmitted !== undefined)
128
129
  installation = { ...installation, onAdmitted: input.onAdmitted };
129
130
  const operation = await installOnOyster(installation);
131
+ await input.onCompleted?.(operation);
130
132
  return completedInstallationResponse(operation);
131
133
  }
132
134
  /** Project one exact first-party commit's editable source, `git push` it to
@@ -31,7 +31,7 @@ import type { Avatar } from "@fungi.computer/sprite/avatar";
31
31
  import type { InvocationFrame } from "../invocation.js";
32
32
  import type { OysterJson } from "../host.js";
33
33
  import { type FleetMessage } from "@fungi.computer/shiitake/fleet";
34
- import { type AppToolPolicy } from "../apps/index.js";
34
+ import { type AppToolPolicy, type Installation } from "../apps/index.js";
35
35
  import { type OysterHost } from "../host.js";
36
36
  import { type TenantScope, type TenantId, type TenantPrincipal } from "../tenant.js";
37
37
  import type { ReadonlyTenancy } from "../tenancy/index.js";
@@ -542,6 +542,10 @@ export declare const agentFrameMethods: {
542
542
  readonly visited: true;
543
543
  };
544
544
  requiredOperations: () => string[];
545
+ requestedResource: (raw: readonly unknown[]) => {
546
+ kind: string;
547
+ id: string;
548
+ };
545
549
  };
546
550
  };
547
551
  AGENTS: {
@@ -716,5 +720,5 @@ export declare const agentFrameMethods: {
716
720
  };
717
721
  };
718
722
  /** Provider effects are admitted by the originating Instance's live frame. */
719
- export declare function dispatchAgentBinding(env: StandaloneAgentsEnv, scope: TenantScope, frame: InvocationFrame, props: FrameBindingProps, method: string, args: readonly unknown[]): Promise<OysterJson>;
723
+ export declare function dispatchAgentBinding(env: StandaloneAgentsEnv, scope: TenantScope, frame: InvocationFrame, props: FrameBindingProps, method: string, args: readonly unknown[], admitted: Installation): Promise<OysterJson>;
720
724
  export {};
@@ -55,9 +55,9 @@ import { readAgentSchedulePage, controlAgentSchedule, } from "@fungi.computer/sh
55
55
  import { agentScheduleTargetSchema } from "@fungi.computer/shiitake-extensions/schedules";
56
56
  import { createAgentAvatarStore, } from "../agent-avatars.js";
57
57
  import { agentIds, createAgentDirectory, createFleetSessions, commandSettlementSchema, DirectoryError, } from "@fungi.computer/shiitake/fleet";
58
- import { appToolPolicySchema } from "../apps/index.js";
58
+ import { appToolPolicySchema, } from "../apps/index.js";
59
59
  import { oysterPrincipalId } from "../host.js";
60
- import { oysterPrincipalIsOwner } from "../authorization.js";
60
+ import { agentCeiling, oysterPrincipalIsOwner } from "../authorization.js";
61
61
  import { defaultTenant, tenantIdSchema, tenantScope, } from "../tenant.js";
62
62
  import { createCodemodeSandbox } from "@fungi.computer/mycelium/workers";
63
63
  import { forageDiscoveryInstructions } from "@fungi.computer/mycelium/effect";
@@ -2128,6 +2128,10 @@ export const agentFrameMethods = {
2128
2128
  decodeArgs: (raw) => agentBindingArgs.INBOX.visit.parse(raw),
2129
2129
  decodeResult: decodeInboxVisit,
2130
2130
  requiredOperations: () => ["visit"],
2131
+ requestedResource: (raw) => ({
2132
+ kind: "agent",
2133
+ id: agentBindingArgs.INBOX.visit.parse(raw)[0].agentId,
2134
+ }),
2131
2135
  },
2132
2136
  },
2133
2137
  AGENTS: {
@@ -2187,7 +2191,7 @@ export const agentFrameMethods = {
2187
2191
  },
2188
2192
  };
2189
2193
  /** Provider effects are admitted by the originating Instance's live frame. */
2190
- export async function dispatchAgentBinding(env, scope, frame, props, method, args) {
2194
+ export async function dispatchAgentBinding(env, scope, frame, props, method, args, admitted) {
2191
2195
  frame.signal.throwIfAborted();
2192
2196
  if (frame.facts.selection.owner.kind !== "installation")
2193
2197
  throw new AppInstanceError("revoked");
@@ -2196,8 +2200,21 @@ export async function dispatchAgentBinding(env, scope, frame, props, method, arg
2196
2200
  let result;
2197
2201
  if (props.binding === "INBOX" && method === "page") {
2198
2202
  agentBindingArgs.INBOX.page.parse(args);
2203
+ const read = admitted.authority.approvedGrants.find((grant) => grant.capability === "agent.read");
2204
+ if (read === undefined)
2205
+ throw new AppInstanceError("binding_not_granted");
2206
+ const ceiling = agentCeiling(read.resources);
2199
2207
  const inbox = await standaloneAgents(env, scope).inbox();
2200
- result = { items: inbox.items, next: null, cursor: inbox.revision };
2208
+ result =
2209
+ ceiling === "all"
2210
+ ? { items: inbox.items, next: null, cursor: inbox.revision }
2211
+ : {
2212
+ items: inbox.items.filter((item) => "agentId" in item && ceiling.has(item.agentId)),
2213
+ next: null,
2214
+ // The global revision also moves for Agents outside the selection;
2215
+ // with no scoped change stream, a narrowed App sees neither it nor their rows.
2216
+ cursor: 0,
2217
+ };
2201
2218
  }
2202
2219
  else if (props.binding === "INBOX" && method === "visit") {
2203
2220
  const [input] = agentBindingArgs.INBOX.visit.parse(args);
@@ -1,4 +1,5 @@
1
1
  import { type BuildGitEvent } from "../build-egress.js";
2
+ import type { ContentObjectOwner } from "../build/content-objects.js";
2
3
  import type { CandidateObject, CandidateObjectMediaType, TeamAppCandidateManifest } from "../build-contract.js";
3
4
  import { type GitDoorTarget } from "../git.js";
4
5
  /** Loopback props the ComputerDO sets; a guest cannot choose them. */
@@ -13,12 +14,13 @@ export type OysterComputerBuildPort = Readonly<{
13
14
  admitBuild(jobId: string): Promise<Readonly<{
14
15
  credentialId: string;
15
16
  }> | null>;
16
- /** One object upload for a live job's grant, and its size bound. */
17
+ /** One object upload for a live job's grant, its size bound and owner. */
17
18
  admitObject(jobId: string, grant: string): Promise<Readonly<{
18
19
  maxObjectBytes: number;
20
+ owner: ContentObjectOwner;
19
21
  }> | null>;
20
- /** Stream one admitted object into the host's Release store. */
21
- storeObject(object: CandidateObject, body: ReadableStream<Uint8Array> | null, mediaType: CandidateObjectMediaType): Promise<"stored" | "refused">;
22
+ /** Stream one admitted object into the host's Release store, in its owner's namespace. */
23
+ storeObject(object: CandidateObject, body: ReadableStream<Uint8Array> | null, mediaType: CandidateObjectMediaType, owner: ContentObjectOwner): Promise<"stored" | "refused">;
22
24
  submitCandidate(jobId: string, manifest: TeamAppCandidateManifest, grant: string, credentialId: string): Promise<Response>;
23
25
  record(event: BuildGitEvent): Promise<void>;
24
26
  }>;
@@ -74,7 +74,7 @@ export async function serveOysterComputerEgress(request, options) {
74
74
  response = await createBuildEgress({
75
75
  admitBuild: (jobId) => options.build.admitBuild(jobId),
76
76
  admitObject: (jobId, grant) => options.build.admitObject(jobId, grant),
77
- storeObject: (object, body, mediaType) => options.build.storeObject(object, body, mediaType),
77
+ storeObject: (object, body, mediaType, admitted) => options.build.storeObject(object, body, mediaType, admitted.owner),
78
78
  submitCandidate: (jobId, manifest, grant, credentialId) => options.build.submitCandidate(jobId, manifest, grant, credentialId),
79
79
  record: (event) => options.build.record(event),
80
80
  }).fetch(request, url);
@@ -0,0 +1,9 @@
1
+ /** Pack the Hello App kept at `<directory>/hello-app` and install it as
2
+ * `hello`; answers the HTTP status (201 new, 200 when already installed).
3
+ * The first call writes and commits the source; later calls pack its current
4
+ * `HEAD`, so a committed edit followed by `oyster try` shows the change. */
5
+ export declare function installHelloApp(input: Readonly<{
6
+ directory: string;
7
+ url: string;
8
+ key: string;
9
+ }>): Promise<number>;
@@ -0,0 +1,78 @@
1
+ // The starter Hello App for a local Oyster: a one-page bundled-html App,
2
+ // committed to git, packed into a Release and installed as `hello`. The
3
+ // quick start and `oyster try` install the same App through this module;
4
+ // `try` keeps its source at `<project>/hello-app` for the person to edit.
5
+ import { execFileSync } from "node:child_process";
6
+ import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { installRelease, packRelease } from "../pack.js";
10
+ const manifest = {
11
+ name: "hello-app",
12
+ private: true,
13
+ fungi: { app: { displayName: "Hello", icon: "fungi", capabilities: [] } },
14
+ };
15
+ const page = "<!doctype html>\n<title>Hello</title>\n<h1>Hello from my first Oyster App</h1>\n";
16
+ const exists = (path) => access(path).then(() => true, () => false);
17
+ const git = (directory, args) => execFileSync("git", [
18
+ "-C",
19
+ directory,
20
+ "-c",
21
+ "user.name=Oyster",
22
+ "-c",
23
+ "user.email=oyster@example.invalid",
24
+ ...args,
25
+ ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
26
+ // Write `hello-app/` under `directory` and commit it; answers the commit.
27
+ async function writeHelloApp(directory) {
28
+ const source = join(directory, "hello-app");
29
+ await mkdir(join(source, "bundle"), { recursive: true });
30
+ await writeFile(join(source, "package.json"), JSON.stringify(manifest, null, 2) + "\n");
31
+ await writeFile(join(source, "bundle", "index.html"), page);
32
+ git(source, ["init", "-q"]);
33
+ git(source, ["add", "."]);
34
+ git(source, ["commit", "-qm", "Hello App"]);
35
+ return git(source, ["rev-parse", "HEAD"]);
36
+ }
37
+ /** Pack the Hello App kept at `<directory>/hello-app` and install it as
38
+ * `hello`; answers the HTTP status (201 new, 200 when already installed).
39
+ * The first call writes and commits the source; later calls pack its current
40
+ * `HEAD`, so a committed edit followed by `oyster try` shows the change. */
41
+ export async function installHelloApp(input) {
42
+ const source = join(input.directory, "hello-app");
43
+ const commit = (await exists(join(source, ".git")))
44
+ ? git(source, ["rev-parse", "HEAD"])
45
+ : await writeHelloApp(input.directory);
46
+ const scratch = await mkdtemp(join(tmpdir(), "oyster-hello-"));
47
+ try {
48
+ await packRelease({
49
+ appId: "app_hello",
50
+ sourceDirectory: source,
51
+ sourceRevision: `git:${commit}`,
52
+ recipe: {
53
+ kind: "bundled-html",
54
+ entry: "bundle/index.html",
55
+ assets: {
56
+ maxManifestBytes: 65_536,
57
+ maxObjects: 16,
58
+ maxObjectBytes: 1_048_576,
59
+ maxTotalBytes: 4_194_304,
60
+ },
61
+ assetBase: "./",
62
+ backend: null,
63
+ maxOutputBytes: 4_194_304,
64
+ },
65
+ outDirectory: join(scratch, "release"),
66
+ });
67
+ const response = await installRelease({
68
+ directory: join(scratch, "release"),
69
+ url: input.url,
70
+ key: input.key,
71
+ installationId: "hello",
72
+ });
73
+ return response.status;
74
+ }
75
+ finally {
76
+ await rm(scratch, { recursive: true, force: true });
77
+ }
78
+ }
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { Cli } from "@fungi.computer/lantern";
2
3
  import { installStandaloneAppSet } from "./app-set.js";
3
- export declare function installApps(args: readonly string[], install?: typeof installStandaloneAppSet): Promise<void>;
4
+ export declare function installApps(args: readonly string[], install?: typeof installStandaloneAppSet, ui?: Cli): Promise<void>;
4
5
  export declare function runInstallAppsCli(args?: readonly string[]): Promise<void>;
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // `oyster install-apps`: seed, build on the Oyster's own Computer, and install
2
+ // `oyster try` starts a local Oyster; `oyster install-apps`: seed, build on the Oyster's own Computer, and install
3
3
  // the seven starter Apps (Tourtois, Bonsai, Shed, Inkcap, Trellis, Prints,
4
4
  // and Grove). Each comes from its own public repository by default,
5
5
  // or from a Botanical checkout with `--from <directory>`.
@@ -13,6 +13,8 @@ import { tmpdir } from "node:os";
13
13
  import { join, resolve } from "node:path";
14
14
  import process from "node:process";
15
15
  import { parseArgs } from "node:util";
16
+ import { Cli } from "@fungi.computer/lantern";
17
+ import { createTryCli, reportTryFailure, tryOyster, tryUsage, } from "./try-cli.js";
16
18
  import { installReleaseCommand, installReleaseUsage, } from "../install-release-cli.js";
17
19
  import { defaultStarterBuildConcurrency, installStandaloneAppSet, } from "./app-set.js";
18
20
  /** The starter Apps' public source repositories. */
@@ -74,9 +76,14 @@ function timingTable(results) {
74
76
  "upload",
75
77
  "install",
76
78
  ];
77
- return [header, ...rows].map((row) => row.join("\t")).join("\n");
79
+ const table = [header, ...rows];
80
+ const widths = header.map((_, column) => Math.max(...table.map((row) => row[column]?.length ?? 0)));
81
+ return table.map((row) => row
82
+ .map((cell, column) => cell.padEnd(widths[column] ?? 0))
83
+ .join(" ")
84
+ .trimEnd());
78
85
  }
79
- export async function installApps(args, install = installStandaloneAppSet) {
86
+ export async function installApps(args, install = installStandaloneAppSet, ui = new Cli({ brand: "fungi" })) {
80
87
  const { values } = parseArgs({
81
88
  args: [...args],
82
89
  options: {
@@ -93,6 +100,7 @@ export async function installApps(args, install = installStandaloneAppSet) {
93
100
  process.stdout.write(helpText);
94
101
  return;
95
102
  }
103
+ ui.welcome("Oyster: install the starter Apps");
96
104
  const url = process.env.OYSTER_URL;
97
105
  const key = process.env.OYSTER_OWNER_KEY;
98
106
  if (!url || !key)
@@ -126,18 +134,23 @@ export async function installApps(args, install = installStandaloneAppSet) {
126
134
  url,
127
135
  key,
128
136
  concurrency,
137
+ // Builds run side by side, so each report is its own line, not a spinner.
129
138
  report: (message) => {
130
- process.stdout.write(`${message}\n`);
139
+ ui.step(message);
131
140
  },
132
141
  });
133
142
  const elapsed = performance.now() - started;
134
- process.stdout.write(`\n${timingTable(installed)}\n`);
135
- process.stdout.write("\nApp\tResult\n");
136
- for (const app of installed)
137
- process.stdout.write(`${app.installationId}\tinstalled\n`);
138
- for (const app of failed)
139
- process.stdout.write(`${app.installationId}\tfailed: ${app.reason}\n`);
140
- process.stdout.write(`\nInstalled ${String(installed.length)} Apps; failed ${String(failed.length)} in ${seconds(elapsed)}.${installed.length > 0 ? ` Open ${url}/ to use the installed Apps.` : ""}\n`);
143
+ if (installed.length > 0)
144
+ ui.note("Build timings", timingTable(installed));
145
+ ui.note("Apps", [
146
+ ...installed.map((app) => `${app.installationId} installed`),
147
+ ...failed.map((app) => `${app.installationId} failed: ${app.reason}`),
148
+ ]);
149
+ const summary = `Installed ${String(installed.length)} Apps; failed ${String(failed.length)} in ${seconds(elapsed)}.`;
150
+ if (failed.length > 0)
151
+ ui.warn(summary, `Fix the failed Apps above and run oyster install-apps again.`);
152
+ else
153
+ ui.outro(`${summary} Open ${url}/ to use the installed Apps.`);
141
154
  if (values.timings !== undefined)
142
155
  await writeFile(values.timings, JSON.stringify({
143
156
  concurrency,
@@ -159,15 +172,24 @@ export async function installApps(args, install = installStandaloneAppSet) {
159
172
  export async function runInstallAppsCli(args = process.argv.slice(2)) {
160
173
  const [command, ...rest] = args;
161
174
  if (command === "--help" || command === "-h") {
162
- process.stdout.write(usage + "\n" + installReleaseUsage + "\n");
175
+ process.stdout.write(tryUsage + "\n" + usage + "\n" + installReleaseUsage + "\n");
163
176
  }
164
- else if (command !== "install-apps" && command !== "install") {
177
+ else if (command !== "try" &&
178
+ command !== "install-apps" &&
179
+ command !== "install") {
165
180
  process.stderr.write(`${usage}\n`);
166
181
  process.exitCode = 2;
167
182
  }
183
+ else if (command === "try") {
184
+ const ui = createTryCli(rest);
185
+ await tryOyster(rest, undefined, ui).catch((cause) => {
186
+ reportTryFailure(cause, ui);
187
+ process.exitCode = 1;
188
+ });
189
+ }
168
190
  else
169
191
  await (command === "install" ? installReleaseCommand(rest) : installApps(rest)).catch((cause) => {
170
- process.stderr.write(`${cause instanceof Error ? cause.message : String(cause)}\n`);
192
+ new Cli({ brand: "fungi", output: process.stderr }).problem(cause instanceof Error ? cause.message : String(cause), `Run \`oyster ${command} --help\` for the options.`);
171
193
  process.exitCode = 1;
172
194
  });
173
195
  }
@@ -38,11 +38,11 @@ export const standaloneBindings = {
38
38
  },
39
39
  INBOX: {
40
40
  methods: agentFrameMethods.INBOX,
41
- dispatch: (context, frame, props, method, args) => dispatchAgentBinding(context.env, context.scope(), frame, props, method, args),
41
+ dispatch: (context, frame, props, method, args, admitted) => dispatchAgentBinding(context.env, context.scope(), frame, props, method, args, admitted),
42
42
  },
43
43
  AGENTS: {
44
44
  methods: agentFrameMethods.AGENTS,
45
- dispatch: (context, frame, props, method, args) => dispatchAgentBinding(context.env, context.scope(), frame, props, method, args),
45
+ dispatch: (context, frame, props, method, args, admitted) => dispatchAgentBinding(context.env, context.scope(), frame, props, method, args, admitted),
46
46
  },
47
47
  /** The emit commits to the delivery owner; Workflows libraries receive it afterwards. */
48
48
  EVENTS: eventsBindingFor(async (context) => {
@@ -0,0 +1,11 @@
1
+ /** Whether the Oyster already has an installation with this id. */
2
+ export declare function isInstalled(input: Readonly<{
3
+ url: string;
4
+ key: string;
5
+ installationId: string;
6
+ }>): Promise<boolean>;
7
+ /** Build Tourtois from source on this machine and install it as `tourtois`. */
8
+ export declare function installLocalDesktop(input: Readonly<{
9
+ url: string;
10
+ key: string;
11
+ }>): Promise<void>;