@fungi.computer/oyster 0.16.0 → 0.18.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.
@@ -1,6 +1,7 @@
1
1
  import type { Release } from "@fungi.computer/puffball";
2
2
  import { createAppStorage } from "./app-storage.js";
3
3
  import type { InstallationStore, verifyRelease } from "./host.js";
4
+ import type { InstallingApp } from "@fungi.computer/nacre/workbench-directory";
4
5
  import { type AppDirectoryEntry } from "@fungi.computer/nacre/app-directory";
5
6
  /**
6
7
  * A destination the host offers the dashboard. This is a structural twin of
@@ -26,6 +27,8 @@ export type OysterRootDirectory = Readonly<{
26
27
  computerId: string;
27
28
  name: string;
28
29
  }>;
30
+ /** Trial starter Apps still being set up; the registry adds them. */
31
+ installing?: readonly InstallingApp[];
29
32
  }>;
30
33
  /** Existing installation, Release and SQLite owners supplied by the root. */
31
34
  export type OysterRootDataOptions = Parameters<typeof createAppStorage>[0] & Readonly<{
@@ -27,6 +27,7 @@ import { type AgentModelChoice, type AgentModelRefusal } from "./agent-model-cho
27
27
  import * as Schema from "effect/Schema";
28
28
  import { type FrameBindingProps } from "../cloudflare.js";
29
29
  import { type AppAgentScheduleListInput, type AgentSchedulePage, type AgentScheduleTarget, type AgentScheduleControlReceipt } from "../agent-schedules.js";
30
+ import { type StarterLedgerRow } from "../starter-agent.js";
30
31
  import type { Avatar } from "@fungi.computer/sprite/avatar";
31
32
  import type { InvocationFrame } from "../invocation.js";
32
33
  import type { OysterJson } from "../host.js";
@@ -445,6 +446,13 @@ export declare class AgentDirectory extends DurableObject<StandaloneAgentEnv> {
445
446
  archived?: boolean;
446
447
  }>): readonly AgentEntry[];
447
448
  has(agentId: string): boolean;
449
+ private starterLedgerOwner;
450
+ private get starterLedger();
451
+ /** The starter Agent's one-row ledger and the Agent total it reads, for the owner's ensure. */
452
+ readStarter(): StarterLedgerRow | undefined;
453
+ recordStarter(row: StarterLedgerRow): void;
454
+ /** Every Agent in the directory, archived ones included. */
455
+ agentTotal(): number;
448
456
  /** Resolve the existing recorded creator for host-side owner admission. */
449
457
  readCreator(agentId: string): string | null;
450
458
  /** Immutable creating Agent, distinct from the human credential owner. */
@@ -524,7 +532,7 @@ export declare const agentFrameMethods: {
524
532
  readonly state: "pending" | "delivered" | "answered" | "timed_out" | "closed";
525
533
  readonly workflowTitle: string;
526
534
  readonly reviewTitle: string;
527
- readonly reviewers: "runner" | "owners";
535
+ readonly reviewers: "owners" | "runner";
528
536
  readonly show: readonly Schema.Json[];
529
537
  readonly openedAt: number;
530
538
  readonly choices?: readonly string[] | undefined;
@@ -57,6 +57,7 @@ import { agentScheduleBindingArgs, appAgentScheduleListInputSchema, agentSchedul
57
57
  import { readAgentSchedulePage, controlAgentSchedule, } from "@fungi.computer/shiitake-extensions/schedules/client";
58
58
  import { agentScheduleTargetSchema } from "@fungi.computer/shiitake-extensions/schedules";
59
59
  import { createAgentAvatarStore, } from "../agent-avatars.js";
60
+ import { createStarterLedger, ensureStarterAgent, } from "../starter-agent.js";
60
61
  import { agentIds, createAgentDirectory, createFleetSessions, commandSettlementSchema, DirectoryError, } from "@fungi.computer/shiitake/fleet";
61
62
  import { appToolPolicySchema, } from "../apps/index.js";
62
63
  import { oysterPrincipalId } from "../host.js";
@@ -1689,6 +1690,21 @@ export class AgentDirectory extends DurableObject {
1689
1690
  const id = agentIds.agent.parse(agentId);
1690
1691
  return id.ok && this.directory.read(this.grant(), id.value) !== null;
1691
1692
  }
1693
+ starterLedgerOwner;
1694
+ get starterLedger() {
1695
+ return (this.starterLedgerOwner ??= createStarterLedger(this.ctx.storage.sql));
1696
+ }
1697
+ /** The starter Agent's one-row ledger and the Agent total it reads, for the owner's ensure. */
1698
+ readStarter() {
1699
+ return this.starterLedger.read();
1700
+ }
1701
+ recordStarter(row) {
1702
+ this.starterLedger.record(row);
1703
+ }
1704
+ /** Every Agent in the directory, archived ones included. */
1705
+ agentTotal() {
1706
+ return this.directory.list(this.grant()).length;
1707
+ }
1692
1708
  /** Resolve the existing recorded creator for host-side owner admission. */
1693
1709
  readCreator(agentId) {
1694
1710
  return this.directory.readCreator(this.grant(), agentId);
@@ -1970,6 +1986,20 @@ export function standaloneAgents(env, scope) {
1970
1986
  avatar: entry.avatar,
1971
1987
  sessionOperations: everyOperation,
1972
1988
  });
1989
+ const created = async (name, requestId, principal, actor, avatar) => {
1990
+ const entry = await directory().create(name, requestId, principal, actor, avatar);
1991
+ await env.AGENTS.getByName(entry.agentId).usePolicyDirectory({
1992
+ directoryName,
1993
+ tenantId: scope?.tenantId ?? defaultTenant,
1994
+ });
1995
+ if (actor === "owner-direct" && entry.policyRevision !== null) {
1996
+ // Best-effort: a stale membership lookup leaves the Agent pending
1997
+ // rather than failing its creation. Grove's "Allow App tools"
1998
+ // control recovers it through the same approval path.
1999
+ await directory().approveAppToolPolicy(entry.agentId, principal, "write", entry.policyRevision, actor, scope?.tenantId ?? defaultTenant);
2000
+ }
2001
+ return toAgent(entry);
2002
+ };
1973
2003
  return {
1974
2004
  list: async (options) => (await directory().list(options)).map(toAgent),
1975
2005
  setArchived: async (agentId, archived, principal) => {
@@ -1984,19 +2014,28 @@ export function standaloneAgents(env, scope) {
1984
2014
  return { error: "not_found" };
1985
2015
  return agent.setArchived(archived);
1986
2016
  },
1987
- create: async (name, requestId, principal, actor, avatar) => {
1988
- const entry = await directory().create(name, requestId, principal, actor, avatar);
1989
- await env.AGENTS.getByName(entry.agentId).usePolicyDirectory({
1990
- directoryName,
1991
- tenantId: scope?.tenantId ?? defaultTenant,
2017
+ create: created,
2018
+ ensureStarter: (principal) => {
2019
+ const owner = directory();
2020
+ return ensureStarterAgent({
2021
+ ledger: {
2022
+ read: () => owner.readStarter(),
2023
+ record: (row) => owner.recordStarter(row),
2024
+ },
2025
+ isOwner: () => oysterPrincipalIsOwner(principal),
2026
+ agentCount: () => owner.agentTotal(),
2027
+ // The ordinary create: the same Computer-less Agent, policy and approval any owner create gets.
2028
+ create: async (request) => {
2029
+ const agent = await created(request.name, request.requestId, principal, "owner-direct");
2030
+ return { status: "created", agentId: agent.agentId };
2031
+ },
2032
+ report: (cause) => {
2033
+ console.warn(JSON.stringify({
2034
+ event: "starter_agent_failed",
2035
+ cause: String(cause),
2036
+ }));
2037
+ },
1992
2038
  });
1993
- if (actor === "owner-direct" && entry.policyRevision !== null) {
1994
- // Best-effort: a stale membership lookup leaves the Agent pending
1995
- // rather than failing its creation. Grove's "Allow App tools"
1996
- // control recovers it through the same approval path.
1997
- await directory().approveAppToolPolicy(entry.agentId, principal, "write", entry.policyRevision, actor, scope?.tenantId ?? defaultTenant);
1998
- }
1999
- return toAgent(entry);
2000
2039
  },
2001
2040
  rename: async (agentId, name, principal) => {
2002
2041
  const result = await directory().rename(agentId, name, principal);
@@ -3,6 +3,7 @@ import { agentDirectoryForScope } from "./agent-directory.js";
3
3
  import { standaloneAgentComputerRoutes } from "./agent-computers.js";
4
4
  import { appSourceOwnerRoutes, } from "./app-source.js";
5
5
  import { standaloneBuildRoutes } from "./builds.js";
6
+ import { trialStarterRoutes } from "./trial-starters.js";
6
7
  import { standaloneComputerFleetRoutes } from "./computer-fleet.js";
7
8
  import { standaloneWorkflowWebhookControls } from "./workflow-webhooks.js";
8
9
  import { standaloneWebsiteControl, standaloneWebsiteRoutes, } from "./website-channels.js";
@@ -13,6 +14,7 @@ export function standaloneOwnerRoutes(env, scope, hostFor) {
13
14
  const directory = () => agentDirectoryForScope(env, scope);
14
15
  const owned = appSourceOwnerRoutes(env, scope)
15
16
  .include(standaloneBuildRoutes(registry))
17
+ .include(trialStarterRoutes(registry))
16
18
  .include(standaloneComputerFleetRoutes(registry))
17
19
  .include(standaloneAgentComputerRoutes({
18
20
  attach: (principal, command) => directory().attachComputer(command, principal, scope.tenantId),
@@ -1,6 +1,8 @@
1
1
  import type { Release } from "@fungi.computer/puffball";
2
2
  import { OysterRegistry, type OysterWorkerEnv } from "../workers.js";
3
3
  import { type OysterHost } from "../host.js";
4
+ import type { OysterRootDirectory } from "../root-data.js";
5
+ import type { InstallingApp } from "@fungi.computer/nacre/workbench-directory";
4
6
  import { type TenantScope, type TenantId } from "../tenant.js";
5
7
  import { type OysterGitEnv } from "../workers-git.js";
6
8
  import { type AppSourceForkResult, type TemplateSeedClaim } from "../source/index.js";
@@ -45,6 +47,20 @@ export declare abstract class StandaloneRegistry extends OysterRegistry implemen
45
47
  #private;
46
48
  protected abstract hostFor(scope: TenantScope): Promise<OysterHost>;
47
49
  constructor(state: DurableObjectState, env: StandaloneRegistryEnv, git?: StandaloneRegistryGit);
50
+ /** Starter Apps a trial is still setting up, cleared once each is installed. */
51
+ directory(): Promise<OysterRootDirectory>;
52
+ reportTrialStarters(installing: readonly InstallingApp[]): Promise<void>;
53
+ trialStartersList(): Promise<readonly {
54
+ installationId: string;
55
+ displayName: string;
56
+ state: "failed" | "installing" | "needs-runtime";
57
+ reason?: {
58
+ code: "unknown" | "build_failed" | "network" | "unsupported";
59
+ message: string;
60
+ } | undefined;
61
+ }[]>;
62
+ requestTrialRetry(installationId: string): Promise<boolean>;
63
+ takeTrialRetries(): Promise<readonly string[]>;
48
64
  /** Whether installations or build jobs were written by Oyster 0.2 or earlier. */
49
65
  storeFromOlderOyster(): boolean;
50
66
  /** Re-admit the live owner before inventory access or a hosted start. */
@@ -1,6 +1,7 @@
1
1
  import { canonicalJson } from "@fungi.computer/braid";
2
2
  import { OysterRegistry, r2ArtifactStore, } from "../workers.js";
3
3
  import { installOrSelect } from "../host.js";
4
+ import { createTrialStarters, pendingStarters } from "./trial-starters.js";
4
5
  import { installationOperationsPort } from "../installation-operations.js";
5
6
  import { tenantScope } from "../tenant.js";
6
7
  import { artifactsOf } from "../workers-git.js";
@@ -33,11 +34,22 @@ export class StandaloneRegistry extends OysterRegistry {
33
34
  #builds;
34
35
  #computers;
35
36
  #fleetStorage;
37
+ #trial;
36
38
  constructor(state, env, git = {}) {
37
39
  super(state, env);
38
40
  this.#env = env;
39
41
  this.#git = git;
40
42
  this.#fleetStorage = state.storage;
43
+ this.#trial = createTrialStarters({
44
+ starters: {
45
+ read: () => state.storage.get("trial.starters"),
46
+ write: (value) => state.storage.put("trial.starters", value),
47
+ },
48
+ retries: {
49
+ read: () => state.storage.get("trial.retries"),
50
+ write: (value) => state.storage.put("trial.retries", value),
51
+ },
52
+ });
41
53
  // Native hosts own infrastructure capacity. Standalone has no Team quota.
42
54
  this.#computers = createFleetComputers(state.storage, {
43
55
  limit: Number.MAX_SAFE_INTEGER,
@@ -45,6 +57,24 @@ export class StandaloneRegistry extends OysterRegistry {
45
57
  });
46
58
  this.#computers.ensure();
47
59
  }
60
+ /** Starter Apps a trial is still setting up, cleared once each is installed. */
61
+ async directory() {
62
+ const base = await super.directory();
63
+ const installing = pendingStarters(await this.#trial.list(), base.apps.flatMap((app) => app.installationId === null ? [] : [app.installationId]));
64
+ return installing.length === 0 ? base : { ...base, installing };
65
+ }
66
+ async reportTrialStarters(installing) {
67
+ await this.#trial.report(installing);
68
+ }
69
+ trialStartersList() {
70
+ return this.#trial.list();
71
+ }
72
+ requestTrialRetry(installationId) {
73
+ return this.#trial.requestRetry(installationId);
74
+ }
75
+ takeTrialRetries() {
76
+ return this.#trial.takeRetries();
77
+ }
48
78
  /** Whether installations or build jobs were written by Oyster 0.2 or earlier. */
49
79
  storeFromOlderOyster() {
50
80
  return (super.storeFromOlderOyster() ||
@@ -1,6 +1,7 @@
1
1
  import { TenancyRegistryDO, admittedRegistry, durableObjectRegistry, } from "../tenancy/cloudflare.js";
2
2
  import { createTenancy, } from "../tenancy/index.js";
3
3
  import { ownerKey } from "../tenancy/owner-key.js";
4
+ import { loopbackAliasLocation } from "../tenancy/registry-record.js";
4
5
  import { hosts } from "../tenancy/resolve.js";
5
6
  import { ownerOrKeyAuth } from "../auth.js";
6
7
  import { HTTPException } from "hono/http-exception";
@@ -89,7 +90,16 @@ export class StandaloneTenants extends TenancyRegistryDO {
89
90
  export async function standaloneTenancyForRequest(env, request) {
90
91
  const configuredOrigin = tenantScope(defaultTenant, env.OYSTER_ORIGIN).origin;
91
92
  const requestOrigin = new URL(request.url).origin;
92
- if (requestOrigin !== configuredOrigin)
93
+ if (requestOrigin !== configuredOrigin) {
94
+ // Another loopback name for this machine is the same Oyster.
95
+ const canonical = loopbackAliasLocation(new URL(request.url), configuredOrigin);
96
+ if (canonical !== null)
97
+ throw new HTTPException(307, {
98
+ res: new Response(null, {
99
+ status: 307,
100
+ headers: { Location: canonical, "Cache-Control": "no-store" },
101
+ }),
102
+ });
93
103
  throw new HTTPException(404, {
94
104
  res: Response.json({
95
105
  kind: "refused",
@@ -99,6 +109,7 @@ export async function standaloneTenancyForRequest(env, request) {
99
109
  message: `Request origin ${requestOrigin} does not match configured OYSTER_ORIGIN ${configuredOrigin}. Set OYSTER_ORIGIN to this Worker's URL.`,
100
110
  }, { status: 404 }),
101
111
  });
112
+ }
102
113
  return standaloneTenancy(env);
103
114
  }
104
115
  const environments = new WeakMap();
@@ -0,0 +1,52 @@
1
+ import * as z from "zod";
2
+ import { type InstallingApp } from "@fungi.computer/nacre/workbench-directory";
3
+ import { type Routes } from "../authorization.js";
4
+ import type { OysterEnv } from "../host.js";
5
+ import type { StandaloneRegistry } from "./registry.js";
6
+ /** What `oyster try` tells its Oyster about the starter Apps still being set up. */
7
+ export declare const trialStartersBodySchema: z.ZodObject<{
8
+ installing: z.ZodArray<z.ZodObject<{
9
+ installationId: z.ZodString;
10
+ displayName: z.ZodString;
11
+ state: z.ZodEnum<{
12
+ readonly installing: "installing";
13
+ readonly failed: "failed";
14
+ readonly "needs-runtime": "needs-runtime";
15
+ }>;
16
+ reason: z.ZodOptional<z.ZodObject<{
17
+ code: z.ZodEnum<{
18
+ readonly build_failed: "build_failed";
19
+ readonly network: "network";
20
+ readonly unsupported: "unsupported";
21
+ readonly unknown: "unknown";
22
+ }>;
23
+ message: z.ZodString;
24
+ }, z.core.$strict>>;
25
+ }, z.core.$strict>>;
26
+ }, z.core.$strict>;
27
+ /** One typed record the registry keeps durably. */
28
+ export type TrialPort<T> = Readonly<{
29
+ read(): Promise<T | undefined>;
30
+ write(value: T): Promise<void>;
31
+ }>;
32
+ /** Where the trial's list and retry asks live. */
33
+ export type TrialStarterStorage = Readonly<{
34
+ starters: TrialPort<readonly InstallingApp[]>;
35
+ retries: TrialPort<readonly string[]>;
36
+ }>;
37
+ /**
38
+ * The trial's starter-App state. `oyster try` replaces the list as each App
39
+ * settles; the desktop asks for a retry of one App and `try` takes the asks.
40
+ */
41
+ export declare function createTrialStarters(storage: TrialStarterStorage): {
42
+ list(): Promise<readonly InstallingApp[]>;
43
+ report(installing: readonly InstallingApp[]): Promise<readonly InstallingApp[]>;
44
+ /** Only a failed App can be retried; the ask is remembered until taken. */
45
+ requestRetry(installationId: string): Promise<boolean>;
46
+ takeRetries(): Promise<readonly string[]>;
47
+ };
48
+ /** Starters still listed once their App is installed no longer show as pending. */
49
+ export declare function pendingStarters(listed: readonly InstallingApp[], installedIds: readonly string[]): readonly InstallingApp[];
50
+ export type RegistryBinding = () => Pick<StandaloneRegistry, "reportTrialStarters" | "requestTrialRetry" | "takeTrialRetries" | "trialStartersList">;
51
+ /** Owner-key routes `oyster try` and the desktop use; the owner guard is declared per route. */
52
+ export declare function trialStarterRoutes(registry: RegistryBinding): Routes<OysterEnv>;
@@ -0,0 +1,67 @@
1
+ import * as z from "zod";
2
+ import { installingAppSchema, } from "@fungi.computer/nacre/workbench-directory";
3
+ import { owner, routes as routeTable } from "../authorization.js";
4
+ /** What `oyster try` tells its Oyster about the starter Apps still being set up. */
5
+ export const trialStartersBodySchema = z.strictObject({
6
+ installing: z.array(installingAppSchema).max(16),
7
+ });
8
+ /**
9
+ * The trial's starter-App state. `oyster try` replaces the list as each App
10
+ * settles; the desktop asks for a retry of one App and `try` takes the asks.
11
+ */
12
+ export function createTrialStarters(storage) {
13
+ return {
14
+ async list() {
15
+ return (await storage.starters.read()) ?? [];
16
+ },
17
+ async report(installing) {
18
+ const parsed = trialStartersBodySchema.parse({ installing }).installing;
19
+ await storage.starters.write(parsed);
20
+ return parsed;
21
+ },
22
+ /** Only a failed App can be retried; the ask is remembered until taken. */
23
+ async requestRetry(installationId) {
24
+ const current = await this.list();
25
+ if (!current.some((entry) => entry.installationId === installationId && entry.state === "failed"))
26
+ return false;
27
+ const asks = (await storage.retries.read()) ?? [];
28
+ if (!asks.includes(installationId))
29
+ await storage.retries.write([...asks, installationId]);
30
+ return true;
31
+ },
32
+ async takeRetries() {
33
+ const asks = (await storage.retries.read()) ?? [];
34
+ if (asks.length > 0)
35
+ await storage.retries.write([]);
36
+ return asks;
37
+ },
38
+ };
39
+ }
40
+ /** Starters still listed once their App is installed no longer show as pending. */
41
+ export function pendingStarters(listed, installedIds) {
42
+ return listed.filter((entry) => !installedIds.includes(entry.installationId));
43
+ }
44
+ /** Owner-key routes `oyster try` and the desktop use; the owner guard is declared per route. */
45
+ export function trialStarterRoutes(registry) {
46
+ const routes = routeTable();
47
+ routes.put("/api/trial/starters", owner("direct"), async (context) => {
48
+ let body;
49
+ try {
50
+ body = await context.req.json();
51
+ }
52
+ catch {
53
+ return context.json({ kind: "invalid" }, 400);
54
+ }
55
+ const parsed = trialStartersBodySchema.safeParse(body);
56
+ if (!parsed.success)
57
+ return context.json({ kind: "invalid" }, 400);
58
+ await registry().reportTrialStarters(parsed.data.installing);
59
+ return new Response(null, { status: 204 });
60
+ });
61
+ routes.get("/api/trial/starters", owner("direct"), async () => Response.json({ installing: await registry().trialStartersList() }, { headers: { "Cache-Control": "no-store" } }));
62
+ routes.post("/api/trial/starters/:installationId/retry", owner("direct"), async (context) => (await registry().requestTrialRetry(context.req.param("installationId")))
63
+ ? new Response(null, { status: 202 })
64
+ : context.json({ kind: "not_retryable" }, 409));
65
+ routes.post("/api/trial/starters/retries", owner("direct"), async () => Response.json({ retries: await registry().takeTrialRetries() }, { headers: { "Cache-Control": "no-store" } }));
66
+ return routes;
67
+ }
@@ -330,6 +330,27 @@ async function runInstall(directory, manager, verbose, signal) {
330
330
  await awaitCleanup(logClosed);
331
331
  }
332
332
  }
333
+ const originFile = join(".oyster", "origin");
334
+ /**
335
+ * Local data belongs to the origin it was seeded for. A project made for
336
+ * another origin (an older `try` used https://oyster.test; another --port is
337
+ * another origin) cannot be served, so its trial data is reset. The owner key,
338
+ * Hello source and Git history are not data of the Oyster. Returns the origin
339
+ * the data was reset from, or null.
340
+ */
341
+ async function reconcileOrigin(directory, origin) {
342
+ const marker = join(directory, originFile);
343
+ const saved = (await exists(marker))
344
+ ? (await readFile(marker, "utf8")).trim()
345
+ : "https://oyster.test";
346
+ const state = join(directory, ".wrangler", "state");
347
+ const reset = saved !== origin && (await exists(state));
348
+ if (reset)
349
+ await rm(state, { recursive: true, force: true });
350
+ await mkdir(join(directory, ".oyster"), { recursive: true });
351
+ await writeFile(marker, `${origin}\n`);
352
+ return reset ? saved : null;
353
+ }
333
354
  function portFree(port) {
334
355
  return new Promise((done) => {
335
356
  const server = createServer();
@@ -381,14 +402,10 @@ function startWrangler(input) {
381
402
  "127.0.0.1",
382
403
  "--port",
383
404
  String(input.port),
384
- "--local-upstream",
385
- "oyster.test",
386
- "--upstream-protocol",
387
- "https",
388
405
  "--var",
389
406
  `OYSTER_OWNER_KEY:${input.key}`,
390
407
  "--var",
391
- "OYSTER_ORIGIN:https://oyster.test",
408
+ `OYSTER_ORIGIN:${url}`,
392
409
  ], {
393
410
  cwd: input.directory,
394
411
  detached: process.platform !== "win32",
@@ -612,6 +629,9 @@ export async function tryOyster(args, effects = realEffects, ui = createTryCli(a
612
629
  await rm(join(directory, pendingInstall));
613
630
  }
614
631
  const url = `http://127.0.0.1:${String(port)}`;
632
+ const resetFrom = await reconcileOrigin(directory, url);
633
+ if (resetFrom !== null)
634
+ ui.info(`This project's local data was made for ${resetFrom}, so it was reset for ${url}. Your owner key and Hello source are unchanged; the Apps reinstall below.`);
615
635
  const server = await task("Starting Oyster", () => (async () => {
616
636
  const resource = await effects.startServer({
617
637
  directory,
@@ -605,7 +605,7 @@ export declare function createStandaloneWorkflowHost(owner: WatchdogSqliteOwner,
605
605
  readonly kind: "review";
606
606
  readonly title: string;
607
607
  readonly timeout: number;
608
- readonly reviewers: "runner" | "owners";
608
+ readonly reviewers: "owners" | "runner";
609
609
  readonly show: readonly {
610
610
  readonly node: string;
611
611
  readonly port: string;
@@ -702,7 +702,7 @@ export declare function createStandaloneWorkflowHost(owner: WatchdogSqliteOwner,
702
702
  readonly kind: "review";
703
703
  readonly title: string;
704
704
  readonly timeout: number;
705
- readonly reviewers: "runner" | "owners";
705
+ readonly reviewers: "owners" | "runner";
706
706
  readonly show: readonly {
707
707
  readonly node: string;
708
708
  readonly port: string;
@@ -343,7 +343,7 @@ export declare abstract class StandaloneWorkflowRunsBase<Env extends StandaloneW
343
343
  readonly kind: "review";
344
344
  readonly title: string;
345
345
  readonly timeout: number;
346
- readonly reviewers: "runner" | "owners";
346
+ readonly reviewers: "owners" | "runner";
347
347
  readonly show: readonly {
348
348
  readonly node: string;
349
349
  readonly port: string;
@@ -440,7 +440,7 @@ export declare abstract class StandaloneWorkflowRunsBase<Env extends StandaloneW
440
440
  readonly kind: "review";
441
441
  readonly title: string;
442
442
  readonly timeout: number;
443
- readonly reviewers: "runner" | "owners";
443
+ readonly reviewers: "owners" | "runner";
444
444
  readonly show: readonly {
445
445
  readonly node: string;
446
446
  readonly port: string;
@@ -20,12 +20,17 @@ export type StarterLedgerRow = Readonly<{
20
20
  agentId: string | null;
21
21
  at: number;
22
22
  }>;
23
- /** One row per Team, in the host's own SQLite. */
24
- export type StarterLedger = Readonly<{
23
+ /** One row per Team in the host's own SQLite. */
24
+ export type StarterLedgerStore = Readonly<{
25
25
  read(): StarterLedgerRow | undefined;
26
26
  /** First write wins; a later one is ignored. */
27
27
  record(row: StarterLedgerRow): void;
28
28
  }>;
29
+ /** The ledger as the policy reads it; a host across an RPC awaits its store. */
30
+ export type StarterLedger = Readonly<{
31
+ read(): StarterLedgerRow | undefined | Promise<StarterLedgerRow | undefined>;
32
+ record(row: StarterLedgerRow): void | Promise<void>;
33
+ }>;
29
34
  /** The host's ordinary create, as the starter sees it. */
30
35
  export type StarterCreateResult = Readonly<{
31
36
  status: "created";
@@ -38,7 +43,7 @@ export type StarterAgentHost = Readonly<{
38
43
  /** Only the Team owner's read may trigger the starter. */
39
44
  isOwner(): boolean;
40
45
  /** Agents in the Team, archived ones included. */
41
- agentCount(): number;
46
+ agentCount(): number | Promise<number>;
42
47
  /** The host's normal create, replayed by `requestId`; funding refusal is `unfunded`. */
43
48
  create(request: {
44
49
  name: string;
@@ -48,9 +53,10 @@ export type StarterAgentHost = Readonly<{
48
53
  report?(cause: unknown): void;
49
54
  now?(): number;
50
55
  }>;
56
+ /** How one offer of the starter Agent settled; only `created` made an Agent. */
51
57
  export type StarterOutcome = "created" | "already-offered" | "team-not-empty" | "unfunded" | "not-owner" | "failed";
52
58
  /** Open the one-row ledger in the host's own SQLite. */
53
- export declare function createStarterLedger(sql: WatchdogSqliteOwner["sql"]): StarterLedger;
59
+ export declare function createStarterLedger(sql: WatchdogSqliteOwner["sql"]): StarterLedgerStore;
54
60
  /**
55
61
  * Offer the starter Agent if this Team never had its chance. Safe to call on
56
62
  * every owner directory read: concurrent calls share one attempt, and the
@@ -52,11 +52,11 @@ async function settle(host) {
52
52
  try {
53
53
  if (!host.isOwner())
54
54
  return "not-owner";
55
- if (host.ledger.read() !== undefined)
55
+ if ((await host.ledger.read()) !== undefined)
56
56
  return "already-offered";
57
57
  const at = (host.now ?? Date.now)();
58
- if (host.agentCount() > 0) {
59
- host.ledger.record({
58
+ if ((await host.agentCount()) > 0) {
59
+ await host.ledger.record({
60
60
  version: starterAgent.version,
61
61
  outcome: "team-not-empty",
62
62
  agentId: null,
@@ -70,7 +70,7 @@ async function settle(host) {
70
70
  });
71
71
  if (result.status === "unfunded")
72
72
  return "unfunded";
73
- host.ledger.record({
73
+ await host.ledger.record({
74
74
  version: starterAgent.version,
75
75
  outcome: "created",
76
76
  agentId: result.agentId,
@@ -1,3 +1,4 @@
1
+ import { isTenantOriginScheme } from "./registry-record.js";
1
2
  import { createOysterTenancy } from "./oyster.js";
2
3
  import { tenantScope } from "../tenant.js";
3
4
  function managed(registry) {
@@ -21,7 +22,7 @@ export function createTenancy(config) {
21
22
  if (tenant === null || tenant.status === "deleting")
22
23
  return null;
23
24
  if (config.resolve.kind === "origin" &&
24
- (url.protocol !== "https:" || !tenant.domains.includes(url.host)))
25
+ (!isTenantOriginScheme(url) || !tenant.domains.includes(url.host)))
25
26
  return null;
26
27
  return tenant;
27
28
  };
@@ -1,5 +1,18 @@
1
1
  import * as Schema from "effect/Schema";
2
2
  import type { Tenant } from "./contracts.js";
3
+ /** Plain HTTP on a loopback host: traffic that never leaves this machine. */
4
+ export declare function isLoopbackHttp(url: URL): boolean;
5
+ /**
6
+ * Where a loopback request at another loopback host (localhost, 127.0.0.1,
7
+ * [::1]) on the same port belongs: the same path at the canonical origin, or
8
+ * null when either origin is not loopback HTTP or the host is already canonical.
9
+ */
10
+ export declare function loopbackAliasLocation(request: URL, canonicalOrigin: string): string | null;
11
+ /**
12
+ * A tenant origin is HTTPS. Plain HTTP is admitted only for a loopback host,
13
+ * which browsers treat as a secure context; no other HTTP origin is.
14
+ */
15
+ export declare function isTenantOriginScheme(url: URL): boolean;
3
16
  export declare function checkedOrigin(origin: string, domains: readonly string[]): string;
4
17
  export declare function immutable(tenant: Tenant): Tenant;
5
18
  export declare function createMemberId(): string;
@@ -5,18 +5,48 @@ const identityIds = defineIdFamily({
5
5
  version: 1,
6
6
  kinds: { member: { prefix: "tenant_member" } },
7
7
  });
8
+ const loopbackHosts = new Set([
9
+ "localhost",
10
+ "127.0.0.1",
11
+ "[::1]",
12
+ ]);
13
+ /** Plain HTTP on a loopback host: traffic that never leaves this machine. */
14
+ export function isLoopbackHttp(url) {
15
+ return url.protocol === "http:" && loopbackHosts.has(url.hostname);
16
+ }
17
+ /**
18
+ * Where a loopback request at another loopback host (localhost, 127.0.0.1,
19
+ * [::1]) on the same port belongs: the same path at the canonical origin, or
20
+ * null when either origin is not loopback HTTP or the host is already canonical.
21
+ */
22
+ export function loopbackAliasLocation(request, canonicalOrigin) {
23
+ const canonical = new URL(canonicalOrigin);
24
+ if (!isLoopbackHttp(request) ||
25
+ !isLoopbackHttp(canonical) ||
26
+ request.port !== canonical.port ||
27
+ request.host === canonical.host)
28
+ return null;
29
+ return `${canonical.origin}${request.pathname}${request.search}`;
30
+ }
31
+ /**
32
+ * A tenant origin is HTTPS. Plain HTTP is admitted only for a loopback host,
33
+ * which browsers treat as a secure context; no other HTTP origin is.
34
+ */
35
+ export function isTenantOriginScheme(url) {
36
+ return url.protocol === "https:" || isLoopbackHttp(url);
37
+ }
8
38
  export function checkedOrigin(origin, domains) {
9
39
  const url = new URL(origin);
10
- if (url.protocol !== "https:" ||
40
+ if (!isTenantOriginScheme(url) ||
11
41
  url.username ||
12
42
  url.password ||
13
43
  url.pathname !== "/" ||
14
44
  url.search ||
15
45
  url.hash ||
16
46
  !domains.includes(url.host))
17
- throw new TypeError("Tenant origin must be HTTPS and match a declared domain, without credentials or a path");
47
+ throw new TypeError("Tenant origin must be HTTPS (or HTTP on a loopback host) and match a declared domain, without credentials or a path");
18
48
  for (const domain of domains) {
19
- const parsed = new URL(`https://${domain}`);
49
+ const parsed = new URL(`${url.protocol}//${domain}`);
20
50
  if (parsed.host !== domain ||
21
51
  parsed.pathname !== "/" ||
22
52
  parsed.search ||