@fungi.computer/oyster 0.13.0 → 0.14.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 (52) hide show
  1. package/README.md +30 -15
  2. package/dist/agents.js +2 -1
  3. package/dist/approval-home.js +4 -2
  4. package/dist/boot-host-script.js +1 -1
  5. package/dist/browser/cdp-client.d.ts +1 -1
  6. package/dist/browser/cdp-client.js +73 -37
  7. package/dist/browser/errors.d.ts +2 -0
  8. package/dist/browser/lease-registry.d.ts +5 -1
  9. package/dist/browser/lease-registry.js +2 -6
  10. package/dist/build/candidate-cli.mjs +267 -246
  11. package/dist/build/definition-emission.js +17 -3
  12. package/dist/build/local-build.d.ts +6 -0
  13. package/dist/build/local-build.js +104 -91
  14. package/dist/build/process-group.d.ts +6 -0
  15. package/dist/build/process-group.js +92 -0
  16. package/dist/build.d.ts +1 -1
  17. package/dist/build.js +1 -1
  18. package/dist/embed-metafiles.js +2 -2
  19. package/dist/embed-scripts.js +1 -1
  20. package/dist/git-journal.js +12 -9
  21. package/dist/hello-app-script.js +1 -1
  22. package/dist/host-page-assets.js +1 -1
  23. package/dist/host-page.d.ts +6 -1
  24. package/dist/host-page.js +40 -0
  25. package/dist/host.js +24 -9
  26. package/dist/installation-operations.js +1 -1
  27. package/dist/machine-link/host.js +18 -13
  28. package/dist/pack.d.ts +3 -1
  29. package/dist/pack.js +28 -7
  30. package/dist/page/app-permissions.js +3 -13
  31. package/dist/page-script.js +2 -2
  32. package/dist/standalone/agent-mail.d.ts +38 -11
  33. package/dist/standalone/agent-mail.js +8 -22
  34. package/dist/standalone/agents.d.ts +1 -0
  35. package/dist/standalone/agents.js +30 -5
  36. package/dist/standalone/hello-app.d.ts +4 -1
  37. package/dist/standalone/hello-app.js +67 -22
  38. package/dist/standalone/hello-lesson.d.ts +2 -0
  39. package/dist/standalone/hello-lesson.js +36 -0
  40. package/dist/standalone/local-desktop.d.ts +6 -4
  41. package/dist/standalone/local-desktop.js +39 -20
  42. package/dist/standalone/sign-in-link.d.ts +2 -1
  43. package/dist/standalone/sign-in-link.js +58 -17
  44. package/dist/standalone/try-cli.d.ts +12 -9
  45. package/dist/standalone/try-cli.js +490 -138
  46. package/docs/api/browser.md +24 -7
  47. package/docs/api/pack.md +3 -2
  48. package/docs/api/workers-git.md +2 -2
  49. package/docs/api/workers.md +2 -2
  50. package/docs/site/agent-quickstart.mdx +109 -354
  51. package/examples/standalone/wrangler.jsonc +1 -1
  52. package/package.json +24 -24
@@ -1,5 +1,6 @@
1
+ import { type AppPermissionsViewData } from "./apps/permissions.js";
1
2
  /** Human-facing states only. API refusals keep their original wire format. */
2
- export type HostPageState = "root" | "empty" | "login" | "login-invalid" | "key-help" | "signing-in" | "link-expired" | "not-found" | "server-error" | "access-denied" | "desktop-missing";
3
+ export type HostPageState = "permissions" | "root" | "empty" | "login" | "login-invalid" | "key-help" | "signing-in" | "link-expired" | "not-found" | "server-error" | "access-denied" | "desktop-missing";
3
4
  export type HostPageOptions = Readonly<{
4
5
  state: HostPageState;
5
6
  title?: string;
@@ -19,6 +20,10 @@ export type HostPageOptions = Readonly<{
19
20
  action: string;
20
21
  key: string;
21
22
  }>;
23
+ permissions?: Readonly<{
24
+ config: AppPermissionsViewData;
25
+ script: string;
26
+ }>;
22
27
  }>;
23
28
  /** Serve only qualified build outputs; no filesystem or runtime image tools. */
24
29
  export declare function hostPageAsset(path: string): Promise<Response>;
package/dist/host-page.js CHANGED
@@ -5,8 +5,15 @@ import { Button } from "@fungi.computer/caps/components/button";
5
5
  import { Input } from "@fungi.computer/caps/components/input";
6
6
  import { Card, CardHeader, CardTitle, CardContent, } from "@fungi.computer/caps/components/card";
7
7
  import { fungiFaviconHref } from "@fungi.computer/sigils/favicon";
8
+ import { permissionScreen, } from "./apps/permissions.js";
9
+ import { permissionCatalog } from "./apps/catalog.js";
8
10
  const docs = "https://docs.fungi.computer";
9
11
  const copy = {
12
+ permissions: [
13
+ "Choose what this App can do.",
14
+ "Oyster · App permissions",
15
+ "Review the requested access. To decline, return to Apps without saving or confirming a change.",
16
+ ],
10
17
  root: [
11
18
  "Your Apps, all together.",
12
19
  "Oyster · App directory",
@@ -64,6 +71,12 @@ const copy = {
64
71
  ],
65
72
  };
66
73
  const abilities = {
74
+ permissions: [
75
+ "You choose the access",
76
+ "Check the App and Release below.",
77
+ "Review each permission before saving.",
78
+ "Leave unchanged if you are unsure.",
79
+ ],
67
80
  root: [
68
81
  "Choose your next App",
69
82
  "Open an App from the directory.",
@@ -159,6 +172,22 @@ function pageContent(options, url) {
159
172
  const { state, signIn } = options;
160
173
  const content = [];
161
174
  const actions = [];
175
+ if (state === "permissions" && options.permissions) {
176
+ const { config } = options.permissions;
177
+ const screen = permissionScreen({
178
+ ...config.permissions,
179
+ resources: config.resources,
180
+ canEdit: config.canEdit,
181
+ });
182
+ content.push(h("h2", null, `${config.appName} permissions`), h("p", { className: "detail" }, "App: ", config.appId, h("br"), "Installation: ", config.installationId, h("br"), "Release: ", h("code", null, config.artifactDigest)), h("div", { id: "oyster-consent" }, h("p", { role: "status" }, "Changes apply only after you save or confirm."), h("ul", { className: "form-stack" }, ...config.permissions.declaredOperations.capabilities.map(({ capability }) => h("li", { key: capability }, h("strong", null, permissionCatalog[capability].label, permissionCatalog[capability].consent === "affordance"
183
+ ? " · No approval required"
184
+ : screen.pending.includes(capability)
185
+ ? " · Needs review"
186
+ : " · Approved"), h("p", null, permissionCatalog[capability].description), permissionCatalog[capability].warning
187
+ ? h("p", null, permissionCatalog[capability].warning)
188
+ : null))), h("noscript", null, h("p", null, "JavaScript is needed to review and change permissions. No permissions have changed.")), h("div", { className: "actions" }, link("Back to Apps", url("/"), true))));
189
+ return { content, actions };
190
+ }
162
191
  if (state === "login" || state === "login-invalid") {
163
192
  content.push(h("form", { method: "post", action: url("/login"), className: "form-stack" }, state === "login-invalid"
164
193
  ? h("p", { className: "error-copy", role: "alert" }, "The key wasn’t accepted. Please check it and try again.")
@@ -208,6 +237,7 @@ function illustration(state, assetUrl) {
208
237
  const eyebrow = copy[state][1];
209
238
  const [ability, ...steps] = abilities[state];
210
239
  const keyArt = [
240
+ "permissions",
211
241
  "login",
212
242
  "login-invalid",
213
243
  "key-help",
@@ -287,6 +317,16 @@ export async function hostPage(options) {
287
317
  ? "Your key is sent only to this Oyster."
288
318
  : h("a", { href: `${docs}/agents/index.md` }, "Hand your LLM the setup guide →")))), h("footer", { className: "page-footer" }, h("span", null, "Oyster · A home for your Apps")), assetUrl("host-page.js")
289
319
  ? h("script", { type: "module", src: assetUrl("host-page.js") })
320
+ : null, options.permissions
321
+ ? h("script", {
322
+ type: "application/json",
323
+ id: "oyster-consent-config",
324
+ dangerouslySetInnerHTML: {
325
+ __html: JSON.stringify(options.permissions.config).replaceAll("<", "\\u003c"),
326
+ },
327
+ })
328
+ : null, options.permissions
329
+ ? h("script", { type: "module", src: options.permissions.script })
290
330
  : null)));
291
331
  return new Response(`<!doctype html>${body}`, {
292
332
  status: options.status ?? 200,
package/dist/host.js CHANGED
@@ -447,6 +447,10 @@ export function oysterRouteTable(host) {
447
447
  // resource (an Agent, the Computer) under the same principal.
448
448
  const dispatchCapability = async (context, principal) => {
449
449
  const url = new URL(context.req.url);
450
+ // A send/manage transport also matches GET requests. The Agent's model
451
+ // catalog is an agent.read projection, not a write-capability side door.
452
+ const agentModelRead = context.req.method === "GET" &&
453
+ /^\/agents\/[^/]+\/models$/u.test(url.pathname);
450
454
  const candidates = capabilityRoutes.filter((route) => (route.method === "ANY" || route.method === context.req.method) &&
451
455
  route.matches(url.pathname));
452
456
  if (candidates.length === 0)
@@ -472,6 +476,8 @@ export function oysterRouteTable(host) {
472
476
  return refusal(403, "Capability permission denied");
473
477
  const facts = await gateFacts(installation, await releaseOf(installation.release), principal);
474
478
  for (const { capability, operation } of candidates) {
479
+ if (agentModelRead && capability.id !== "agent.read")
480
+ continue;
475
481
  if (admits(facts, {
476
482
  kind: "capability-route",
477
483
  capability: capability.permission,
@@ -708,15 +714,15 @@ export function oysterRouteTable(host) {
708
714
  return Response.json(config, {
709
715
  headers: { "Cache-Control": "no-store" },
710
716
  });
711
- const encoded = JSON.stringify(config).replaceAll("<", "\\u003c");
712
- return new Response(`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${escapeHtml(config.appName)} permissions</title><link rel="stylesheet" href="${(await assets()).fonts.path}"><style>html,body{margin:0;min-height:100%;font-family:var(--font-sans);background:var(--color-base-100);color:var(--color-base-content)}</style><div id="oyster-consent"></div><script type="application/json" id="oyster-consent-config">${encoded}</script><script type="module" src="${(await assets()).grantConsent.path}"></script>`, {
713
- headers: {
714
- "Content-Type": "text/html; charset=utf-8",
715
- "Cache-Control": "no-store",
716
- "X-Content-Type-Options": "nosniff",
717
- "Content-Security-Policy": "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src data:; base-uri 'none'; form-action 'self'; frame-ancestors 'self'",
718
- },
717
+ const pageAssets = await assets();
718
+ const response = await hostPage({
719
+ state: "permissions",
720
+ title,
721
+ stylesheets: [pageAssets.loginFonts.path, pageAssets.styles.path],
722
+ permissions: { config, script: pageAssets.grantConsent.path },
719
723
  });
724
+ response.headers.set("Content-Security-Policy", "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src data:; base-uri 'none'; form-action 'self'; frame-ancestors 'self'");
725
+ return response;
720
726
  });
721
727
  table.put("/api/installations/:installationId/grants",
722
728
  // Capability-origin requests cannot become direct owner consent.
@@ -879,7 +885,16 @@ export function oysterRouteTable(host) {
879
885
  return Response.json(config, {
880
886
  headers: { "Cache-Control": "no-store", Vary: "Accept" },
881
887
  });
882
- const head = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${escapeHtml(installation.installationId)} · ${escapeHtml(title)}</title>${tabIcon}<link rel="stylesheet" href="${(await assets()).fonts.path}">`;
888
+ // The shell module imports its chunks a few levels deep; naming every
889
+ // digest-pinned chunk up front fetches them side by side instead.
890
+ const shellPreloads = config.shellModuleUrl !== null && release.ui?.kind === "assets"
891
+ ? release.ui.build.assets
892
+ .filter((asset) => asset.contentType.startsWith("text/javascript") &&
893
+ asset.path !== shellModuleAssetPath)
894
+ .map((asset) => `<link rel="modulepreload" href="${escapeHtml(`${uiUrl.slice(0, -1)}${asset.path}`)}">`)
895
+ .join("")
896
+ : "";
897
+ const head = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${escapeHtml(installation.installationId)} · ${escapeHtml(title)}</title>${tabIcon}<link rel="stylesheet" href="${(await assets()).fonts.path}">${shellPreloads}`;
883
898
  const tail = `<script type="application/json" id="oyster-config">${JSON.stringify(config).replaceAll("<", "\\u003c")}</script><script type="module" src="${(await assets()).page.path}"></script>`;
884
899
  // The home shell is trusted: the host's page script renders it in this
885
900
  // top-level document, and it mounts each App's sandboxed frame inside
@@ -746,7 +746,7 @@ export async function createInstallationOperations(ports) {
746
746
  for (const requestId of settledInTick)
747
747
  wake(requestId);
748
748
  settledInTick.clear();
749
- if (await watchdog.hasPendingWork())
749
+ if ((await watchdog.wakeState(Date.now())).pending)
750
750
  await ports.scheduleWake(Date.now());
751
751
  else {
752
752
  const due = nextRetentionWake();
@@ -270,7 +270,7 @@ export class MachineLinkHost {
270
270
  ? recipientOffline
271
271
  : previousCustodyReceipt(raced);
272
272
  }
273
- await this.options.scheduleWake(post.nextWake() ?? Date.now());
273
+ await this.options.scheduleWake(Date.now());
274
274
  if (socket === undefined)
275
275
  return recipientOffline;
276
276
  await this.publishDirectory(socket, deviceId);
@@ -386,16 +386,24 @@ export class MachineLinkHost {
386
386
  const watchdog = await Watchdog.make({
387
387
  owner: this.owner,
388
388
  isAlive: () => Promise.resolve(false),
389
- execute: (job) => {
389
+ retryPolicy: (job) => {
390
390
  const post = postRef.current;
391
391
  if (post === undefined)
392
392
  throw new Error("Carrier Post runtime is not initialized");
393
- return post.execute(job);
393
+ return post.retryPolicy(job);
394
+ },
395
+ execute: (job, signal, attempt) => {
396
+ const post = postRef.current;
397
+ if (post === undefined)
398
+ throw new Error("Carrier Post runtime is not initialized");
399
+ return post.execute(job, attempt, signal);
394
400
  },
395
401
  wake: {
396
402
  recompute: async () => {
397
- const at = postRef.current?.nextWake();
398
- if (at !== null && at !== undefined)
403
+ const now = Date.now();
404
+ const state = await watchdog.wakeState(now);
405
+ const at = state.pending ? now : state.nextWakeAt;
406
+ if (at !== null)
399
407
  await this.options.scheduleWake(at);
400
408
  },
401
409
  },
@@ -404,7 +412,6 @@ export class MachineLinkHost {
404
412
  routes: this.custodyRoutes,
405
413
  owner: this.owner,
406
414
  transactional: watchdog.transactional,
407
- readJob: watchdog.read,
408
415
  now: Date.now,
409
416
  scheduleWake: this.options.scheduleWake,
410
417
  });
@@ -419,17 +426,15 @@ export class MachineLinkHost {
419
426
  } while (cursor !== undefined);
420
427
  }
421
428
  async drainCustody() {
422
- const { post, watchdog } = await this.custody();
423
- let cursor;
424
- do {
425
- cursor = await post.enqueueDue(64, cursor);
426
- } while (cursor !== undefined);
429
+ const { watchdog } = await this.custody();
427
430
  for (let count = 0; count < 64; count += 1) {
428
431
  const tick = await watchdog.tick();
429
- if (tick.status !== "settled")
432
+ if (tick.status !== "settled" && tick.status !== "requeued")
430
433
  break;
431
434
  }
432
- const at = post.nextWake();
435
+ const now = Date.now();
436
+ const state = await watchdog.wakeState(now);
437
+ const at = state.pending ? now : state.nextWakeAt;
433
438
  if (at !== null)
434
439
  await this.options.scheduleWake(at);
435
440
  }
package/dist/pack.d.ts CHANGED
@@ -20,6 +20,8 @@ export type PackOptions = Readonly<{
20
20
  packageStoreDirectory?: string;
21
21
  /** Where to write `release.json` and the immutable `artifacts/` directory. */
22
22
  outDirectory: string;
23
+ /** Interrupt local preparation and await its owned scratch/process cleanup. */
24
+ signal?: AbortSignal;
23
25
  }>;
24
26
  /** A packed Release on disk. */
25
27
  export type PackedRelease = Readonly<{
@@ -37,7 +39,7 @@ export declare function packRelease(options: PackOptions): Promise<PackedRelease
37
39
  * and install it, or switch an existing installation to it
38
40
  * ({@link installRelease}).
39
41
  * `waitMs` starts with the upload/observation phase after packing; a supplied
40
- * caller signal retains its original lifetime through that phase.
42
+ * caller signal also interrupts packing and retains its original lifetime.
41
43
  */
42
44
  export declare function installFromSource(input: Readonly<{
43
45
  appId: string;
package/dist/pack.js CHANGED
@@ -2,6 +2,8 @@ import { mkdir, mkdtemp, readdir, readFile, rm, writeFile, } from "node:fs/promi
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, relative, resolve } from "node:path";
4
4
  import * as Effect from "effect/Effect";
5
+ import * as Cause from "effect/Cause";
6
+ import * as Exit from "effect/Exit";
5
7
  import * as Schema from "effect/Schema";
6
8
  import { releaseSchema } from "@fungi.computer/puffball/effect";
7
9
  import { installOnOyster, installationObservationSignal, completedInstallationResponse, } from "./installation-client.js";
@@ -23,6 +25,7 @@ async function filesUnder(directory) {
23
25
  .sort();
24
26
  }
25
27
  async function packCapturedSource(options, sourceCapture) {
28
+ options.signal?.throwIfAborted();
26
29
  const revision = parseSourceRevision(options.sourceRevision);
27
30
  const out = resolve(options.outDirectory);
28
31
  const artifactsDirectory = join(out, "artifacts");
@@ -33,14 +36,30 @@ async function packCapturedSource(options, sourceCapture) {
33
36
  ? {}
34
37
  : { packageStoreDirectory: options.packageStoreDirectory }),
35
38
  });
36
- const prepared = await Effect.runPromise(Effect.scoped(preparer.prepareCandidate(parseReleaseId(options.releaseId ??
37
- `rel_${revision.slice("git:".length, "git:".length + 12)}`))));
38
- const release = await Effect.runPromise(commitPreparedCandidate(prepared, {
39
- artifactWriter: createLocalArtifactWriter(artifactsDirectory, options.recipe.assets),
40
- releaseCatalog: { createRelease: (value) => Promise.resolve(value) },
41
- }));
39
+ const packed = await Effect.runPromiseExit(Effect.gen(function* () {
40
+ const prepared = yield* Effect.scoped(preparer.prepareCandidate(parseReleaseId(options.releaseId ??
41
+ `rel_${revision.slice("git:".length, "git:".length + 12)}`)));
42
+ // These are local artifact writes, not host installation admission.
43
+ // Settle them before the caller may remove its output directory.
44
+ return yield* Effect.uninterruptible(commitPreparedCandidate(prepared, {
45
+ artifactWriter: createLocalArtifactWriter(artifactsDirectory, options.recipe.assets),
46
+ releaseCatalog: { createRelease: (value) => Promise.resolve(value) },
47
+ }));
48
+ }), { signal: options.signal });
49
+ if (Exit.isFailure(packed)) {
50
+ // Scope cleanup defects must not disappear behind a simultaneous build failure.
51
+ const defect = packed.cause.reasons.find(Cause.isDieReason);
52
+ if (defect !== undefined)
53
+ throw defect.defect;
54
+ if (Cause.hasInterruptsOnly(packed.cause))
55
+ options.signal?.throwIfAborted();
56
+ throw Cause.squash(packed.cause);
57
+ }
58
+ const release = packed.value;
59
+ options.signal?.throwIfAborted();
42
60
  await mkdir(out, { recursive: true });
43
61
  await writeFile(join(out, "release.json"), `${Schema.encodeUnknownSync(Schema.fromJsonString(releaseSchema))(release)}\n`);
62
+ options.signal?.throwIfAborted();
44
63
  const artifacts = (await filesUnder(artifactsDirectory)).map((path) => ({
45
64
  artifactRef: parseArtifactRef(`artifact:${relative(artifactsDirectory, path)}`),
46
65
  path,
@@ -56,7 +75,7 @@ export async function packRelease(options) {
56
75
  * and install it, or switch an existing installation to it
57
76
  * ({@link installRelease}).
58
77
  * `waitMs` starts with the upload/observation phase after packing; a supplied
59
- * caller signal retains its original lifetime through that phase.
78
+ * caller signal also interrupts packing and retains its original lifetime.
60
79
  */
61
80
  export async function installFromSource(input) {
62
81
  const outDirectory = await mkdtemp(join(tmpdir(), "oyster-source-release-"));
@@ -67,6 +86,8 @@ export async function installFromSource(input) {
67
86
  sourceRevision: input.source.sourceRevision,
68
87
  outDirectory,
69
88
  };
89
+ if (input.signal !== undefined)
90
+ options = { ...options, signal: input.signal };
70
91
  if (input.releaseId !== undefined)
71
92
  options = { ...options, releaseId: input.releaseId };
72
93
  if (input.packageStoreDirectory !== undefined)
@@ -262,17 +262,7 @@ function ShellPermissionRow({ column, changed, otherChanges, disabled, onToggle,
262
262
  gap: "var(--spacing-sm)",
263
263
  padding: 0,
264
264
  minHeight: 36,
265
- }, children: [_jsx(Sigil, { name: column.sigil, size: 20 }), _jsxs("div", { style: {
266
- display: "flex",
267
- alignItems: "baseline",
268
- gap: "var(--spacing-sm)",
269
- minWidth: 0,
270
- }, children: [_jsx("strong", { style: { whiteSpace: "nowrap", flexShrink: 0 }, children: column.label }), _jsx("span", { title: column.description, style: {
271
- color: "var(--stipe-fg-muted)",
272
- whiteSpace: "nowrap",
273
- overflow: "hidden",
274
- textOverflow: "ellipsis",
275
- }, children: column.description })] }), _jsxs("div", { style: {
265
+ }, children: [_jsx(Sigil, { name: column.sigil, size: 20 }), _jsx("strong", { children: column.label }), _jsxs("div", { style: {
276
266
  display: "flex",
277
267
  alignItems: "center",
278
268
  gap: "var(--spacing-sm)",
@@ -280,11 +270,11 @@ function ShellPermissionRow({ column, changed, otherChanges, disabled, onToggle,
280
270
  ? "Shell change not saved"
281
271
  : on
282
272
  ? "Shell allowed"
283
- : "Shell not allowed" }), _jsx(Button, { type: "button", size: "xs", variant: changed || !on ? "outline" : "ghost-destructive", disabled: disabled, onClick: changed ? onCancel : onToggle, children: changed ? "Cancel" : on ? "Revoke" : "Allow" })] })] }) }), _jsx("p", { style: {
273
+ : "Shell not allowed" }), _jsx(Button, { type: "button", size: "xs", variant: changed || !on ? "outline" : "ghost-destructive", disabled: disabled, onClick: changed ? onCancel : onToggle, children: changed ? "Cancel" : on ? "Revoke" : "Allow" })] })] }) }), _jsxs("p", { style: {
284
274
  margin: 0,
285
275
  color: "var(--stipe-fg-muted)",
286
276
  fontSize: "var(--text-sm)",
287
- }, children: column.warning }), changed && (_jsx(FormFooter, { divider: false, status: otherChanges
277
+ }, children: [_jsx("span", { style: { display: "block" }, children: column.description }), column.warning] }), changed && (_jsx(FormFooter, { divider: false, status: otherChanges
288
278
  ? "Save all permission edits, including Shell access?"
289
279
  : on
290
280
  ? "Allow Shell full access?"