@fungi.computer/oyster 0.9.0 → 0.10.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 (49) hide show
  1. package/README.md +13 -0
  2. package/dist/agents.d.ts +16 -1
  3. package/dist/agents.js +60 -3
  4. package/dist/computer-control-port.d.ts +20 -1
  5. package/dist/mcp.d.ts +128 -0
  6. package/dist/mcp.js +63 -1
  7. package/dist/standalone/agent-computers.d.ts +12 -1
  8. package/dist/standalone/agent-computers.js +35 -0
  9. package/dist/standalone/agent-connections.d.ts +47 -0
  10. package/dist/standalone/agent-connections.js +170 -0
  11. package/dist/standalone/agent-model-choice.d.ts +7 -3
  12. package/dist/standalone/agent-model-choice.js +33 -4
  13. package/dist/standalone/agents.d.ts +70 -9
  14. package/dist/standalone/agents.js +187 -110
  15. package/dist/standalone/browser.d.ts +4 -3
  16. package/dist/standalone/browser.js +4 -3
  17. package/dist/standalone/computer-control.js +55 -1
  18. package/dist/standalone/computer-fleet.d.ts +21 -0
  19. package/dist/standalone/computer-fleet.js +30 -6
  20. package/dist/standalone/computer.d.ts +20 -1
  21. package/dist/standalone/computer.js +63 -1
  22. package/dist/standalone/model-key-vault.d.ts +50 -0
  23. package/dist/standalone/model-key-vault.js +147 -0
  24. package/dist/standalone/registry.d.ts +23 -0
  25. package/dist/standalone/registry.js +30 -0
  26. package/dist/standalone/web.d.ts +10 -0
  27. package/dist/standalone/web.js +34 -0
  28. package/dist/standalone/worker-routes.d.ts +3 -1
  29. package/dist/standalone/worker-routes.js +1 -0
  30. package/dist/standalone/worker.js +9 -1
  31. package/dist/web/index.d.ts +3 -0
  32. package/dist/web/index.js +3 -0
  33. package/dist/web/search-contract.d.ts +19 -0
  34. package/dist/web/search-contract.js +14 -0
  35. package/dist/web/search.d.ts +25 -0
  36. package/dist/web/search.js +123 -0
  37. package/dist/web/source.d.ts +46 -0
  38. package/dist/web/source.js +335 -0
  39. package/dist/workers-git.js +2 -1
  40. package/docs/api/agents.md +81 -3
  41. package/docs/api/apps.md +129 -111
  42. package/docs/api/build-contract.md +27 -21
  43. package/docs/api/build.md +55 -54
  44. package/docs/api/git.md +3 -3
  45. package/docs/api/host.md +69 -60
  46. package/docs/api/mcp.md +81 -44
  47. package/docs/api/workers-git.md +6 -6
  48. package/docs/api/workers.md +53 -47
  49. package/package.json +27 -22
@@ -14,7 +14,7 @@ import { ComputerDO as NativeComputerDO, ComputerOperationConflictError, } from
14
14
  import { patchInputSchema, patchOutputSchema, } from "@fungi.computer/knapsack/files-patch";
15
15
  import { ComputerFileConflict, computerExecutionRequestSchema, computerValueSchema, computerPortInputSchema, listInputSchema, listOutputSchema, readBytesInputSchema, writeInputSchema, replaceInputSchema, writeOutputSchema, mkdirOutputSchema, computerPortsOutputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, processListOutputSchema, processKillOutputSchema, computerOperationResultSchema, mintComputerRequestId, processIdInputSchema, } from "@fungi.computer/computer-contract";
16
16
  import { workflowGitExecutionEnvironment, workflowGitPassGrantSchema, } from "@fungi.computer/braid/runtime";
17
- import { checkComputerGrant, computerActionSchema, computerGrantSchema, createFleetBacking, FleetGrantRefused, FleetLifecycle, } from "@fungi.computer/computer/fleet";
17
+ import { checkComputerGrant, computerActionSchema, computerGrantSchema, ComputerBackingError, createFleetBacking, FleetGrantRefused, FleetLifecycle, } from "@fungi.computer/computer/fleet";
18
18
  import { AppInstanceError, selectionOf } from "../index.js";
19
19
  import {} from "../cloudflare.js";
20
20
  import { computerSlots } from "../computer.js";
@@ -160,6 +160,68 @@ export class ComputerDO extends NativeComputerDO {
160
160
  owner.ensure();
161
161
  this.#backends = owner.computerCreated(this.#id(), z.array(hostedBackingSchema).parse(backings)).backends;
162
162
  }
163
+ /**
164
+ * The attached set changed in storage: rebuild the Workspace now, so a
165
+ * detached machine's live connection closes before the control returns.
166
+ */
167
+ #attachedSetChanged() {
168
+ this.#backends = undefined;
169
+ this.workspace();
170
+ }
171
+ /** The owner's attached backends with live status. Reads wake nothing. */
172
+ readBackends(authority, actor) {
173
+ this.#accept(authority, "backing");
174
+ // Describing first gives a never-used Computer its creation record.
175
+ const described = this.describeBackends();
176
+ const owners = createFleetBacking(this.state.storage).localOwners(this.#id());
177
+ return described.map((backend) => ({
178
+ id: backend.id,
179
+ kind: backend.kind,
180
+ status: backend.status,
181
+ queuePosition: null,
182
+ hostId: backend.hostId ?? null,
183
+ hostLabel: backend.hostLabel ?? null,
184
+ folderLabel: backend.folderLabel ?? null,
185
+ detachable: owners.get(backend.id) === actor,
186
+ }));
187
+ }
188
+ /** Attach the owner's machine; a replay of the same request returns it. */
189
+ attachLocalBackend(authority, actor, input) {
190
+ this.#accept(authority, "backing");
191
+ // The default Computer gains its creation record on first read.
192
+ this.attachedBackends();
193
+ try {
194
+ const result = createFleetBacking(this.state.storage).attachLocal(actor, {
195
+ ...input,
196
+ computerId: this.#id(),
197
+ });
198
+ this.#attachedSetChanged();
199
+ return { backendId: result.backendId };
200
+ }
201
+ catch (cause) {
202
+ if (cause instanceof ComputerBackingError)
203
+ return { error: cause.code };
204
+ throw cause;
205
+ }
206
+ }
207
+ /** Detach the owner's machine and close its live connection. */
208
+ detachLocalBackend(authority, actor, input) {
209
+ this.#accept(authority, "backing");
210
+ this.attachedBackends();
211
+ try {
212
+ const result = createFleetBacking(this.state.storage).detachLocal(actor, {
213
+ ...input,
214
+ computerId: this.#id(),
215
+ });
216
+ this.#attachedSetChanged();
217
+ return { detached: result.detached };
218
+ }
219
+ catch (cause) {
220
+ if (cause instanceof ComputerBackingError)
221
+ return { error: cause.code };
222
+ throw cause;
223
+ }
224
+ }
163
225
  /** An admitted fleet control starts exactly this Computer's hosted backend. */
164
226
  async startHostedComputer(authority) {
165
227
  this.#accept(authority, "start");
@@ -0,0 +1,50 @@
1
+ import { type CredentialRecord, type CredentialStorage } from "@fungi.computer/veil/credential-store";
2
+ import { type ModelKeyRecord, type ModelKeyVault } from "@fungi.computer/veil/model-keys";
3
+ /**
4
+ * This instance's own model-key owner. Provider API keys are sealed (AES-GCM)
5
+ * under a key derived from the instance master secret, a host secret that never
6
+ * enters the repository, storage or a log. A key leaves the vault only inside
7
+ * the request it is sent with; listings carry no secret.
8
+ */
9
+ /** Why a key could not be stored or used; stable, secret-free. */
10
+ export type ModelKeyRefusal = "invalid_key" | "key_rejected" | "provider_unavailable" | "custody_unavailable" | "key_removed" | "target_denied" | "limit";
11
+ export declare class ModelKeyRefused extends Error {
12
+ readonly reason: ModelKeyRefusal;
13
+ constructor(reason: ModelKeyRefusal);
14
+ }
15
+ export type { ModelKeyRecord };
16
+ /** What the owner submits to seal one provider key. */
17
+ export type ModelKeySealInput = Readonly<{
18
+ provider: string;
19
+ label: string;
20
+ apiKey: string;
21
+ }>;
22
+ export type ModelKeyStorage = CredentialStorage;
23
+ /**
24
+ * The instance's one encrypted credential store. Listing and removal need no
25
+ * key; sealing and opening refuse without one.
26
+ */
27
+ export declare function createInstanceCredentialStore(options: {
28
+ storage: CredentialStorage;
29
+ credentialKey: string | undefined;
30
+ now?: () => number;
31
+ }): {
32
+ put(input: {
33
+ kind: string;
34
+ label: string;
35
+ secret: string;
36
+ }): Promise<CredentialRecord>;
37
+ list(kind?: string): Promise<readonly CredentialRecord[]>;
38
+ get(credentialId: string): Promise<CredentialRecord | null>;
39
+ remove(credentialId: string): Promise<"deleted" | "absent">;
40
+ withSecret<T>(credentialId: string, action: (secret: string, record: CredentialRecord) => Promise<T> | T): Promise<T>;
41
+ };
42
+ export declare function createModelKeyVault(options: {
43
+ storage: ModelKeyStorage;
44
+ /** The instance credential key (32 bytes, base64url); absent means no custody. */
45
+ credentialKey: string | undefined;
46
+ fetch?: typeof globalThis.fetch;
47
+ now?: () => number;
48
+ }): ModelKeyVault & Readonly<{
49
+ get: (keyId: string) => Promise<ModelKeyRecord | null>;
50
+ }>;
@@ -0,0 +1,147 @@
1
+ import { createCredentialSealer, createCredentialStore, CredentialError, } from "@fungi.computer/veil/credential-store";
2
+ import { isModelKeyProvider, modelKeyForwardedHeaders, modelKeyBaseUrl, modelKeyTarget, modelKeyValidationRequest, modelKeyValidationResult, } from "@fungi.computer/veil/model-keys";
3
+ export class ModelKeyRefused extends Error {
4
+ reason;
5
+ constructor(reason) {
6
+ super(reason);
7
+ this.reason = reason;
8
+ this.name = "ModelKeyRefused";
9
+ }
10
+ }
11
+ const kindOf = (provider) => `model-key/${provider}`;
12
+ const providerOf = (kind) => {
13
+ const provider = kind.slice("model-key/".length);
14
+ if (!isModelKeyProvider(provider))
15
+ throw new ModelKeyRefused("invalid_key");
16
+ return provider;
17
+ };
18
+ const maxKeyLength = 16_384;
19
+ const publicRecord = (record) => ({
20
+ keyId: record.credentialId,
21
+ provider: providerOf(record.kind),
22
+ label: record.label,
23
+ createdAt: record.createdAt,
24
+ validatedAt: record.validatedAt,
25
+ });
26
+ /** Anthropic authenticates with `x-api-key`; the others take a bearer token. */
27
+ function authenticated(provider, headers, apiKey) {
28
+ const next = new Headers(headers);
29
+ if (provider === "anthropic")
30
+ next.set("x-api-key", apiKey);
31
+ else
32
+ next.set("authorization", `Bearer ${apiKey}`);
33
+ return next;
34
+ }
35
+ /**
36
+ * The instance's one encrypted credential store. Listing and removal need no
37
+ * key; sealing and opening refuse without one.
38
+ */
39
+ export function createInstanceCredentialStore(options) {
40
+ const unavailable = () => Promise.reject(new CredentialError("unavailable"));
41
+ const sealer = options.credentialKey === undefined
42
+ ? { seal: unavailable, open: unavailable }
43
+ : createCredentialSealer({
44
+ activeKeyId: "instance",
45
+ keys: { instance: options.credentialKey },
46
+ }, "fungi.oyster.credentials.v1");
47
+ const storeOptions = {
48
+ storage: options.storage,
49
+ sealer,
50
+ };
51
+ if (options.now !== undefined)
52
+ storeOptions.now = options.now;
53
+ return createCredentialStore(storeOptions);
54
+ }
55
+ export function createModelKeyVault(options) {
56
+ const send = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
57
+ const credentialKey = options.credentialKey;
58
+ const credentials = createInstanceCredentialStore(options);
59
+ const store = () => credentials;
60
+ const custody = async (work) => {
61
+ try {
62
+ return await work();
63
+ }
64
+ catch (cause) {
65
+ if (cause instanceof CredentialError)
66
+ throw new ModelKeyRefused(cause.code === "absent"
67
+ ? "key_removed"
68
+ : cause.code === "limit"
69
+ ? "limit"
70
+ : "custody_unavailable");
71
+ throw cause;
72
+ }
73
+ };
74
+ return {
75
+ /** Validate with one cheap authenticated read, then store only the sealed key. */
76
+ async seal(input) {
77
+ const { provider, label, apiKey } = input;
78
+ if (!isModelKeyProvider(provider) ||
79
+ provider === "openai-compatible" ||
80
+ label.length === 0 ||
81
+ label.length > 64 ||
82
+ apiKey.length === 0 ||
83
+ apiKey.length > maxKeyLength)
84
+ throw new ModelKeyRefused("invalid_key");
85
+ if (credentialKey === undefined)
86
+ throw new ModelKeyRefused("custody_unavailable");
87
+ const baseUrl = modelKeyBaseUrl(provider);
88
+ const probe = modelKeyValidationRequest({ provider, baseUrl }, AbortSignal.timeout(15_000));
89
+ let status;
90
+ try {
91
+ const response = await send(new Request(probe, {
92
+ headers: authenticated(provider, probe.headers, apiKey),
93
+ }));
94
+ status = response.status;
95
+ await response.body?.cancel();
96
+ }
97
+ catch {
98
+ // Transport text can echo request headers; surface only the typed cause.
99
+ throw new ModelKeyRefused("provider_unavailable");
100
+ }
101
+ const verdict = modelKeyValidationResult(status);
102
+ if (verdict === "rejected")
103
+ throw new ModelKeyRefused("key_rejected");
104
+ if (verdict === "unavailable")
105
+ throw new ModelKeyRefused("provider_unavailable");
106
+ return publicRecord(await custody(() => credentials.put({ kind: kindOf(provider), label, secret: apiKey })));
107
+ },
108
+ async list() {
109
+ return (await custody(() => store().list()))
110
+ .filter((record) => record.kind.startsWith("model-key/"))
111
+ .map(publicRecord);
112
+ },
113
+ async get(keyId) {
114
+ const record = await custody(() => store().get(keyId));
115
+ return record === null ? null : publicRecord(record);
116
+ },
117
+ remove(keyId) {
118
+ return custody(() => store().remove(keyId));
119
+ },
120
+ /** Send one provider request with the key attached; the caller's auth is dropped. */
121
+ send(keyId, request) {
122
+ return custody(() => store().withSecret(keyId, (apiKey, record) => {
123
+ const provider = providerOf(record.kind);
124
+ let target;
125
+ try {
126
+ target = modelKeyTarget({
127
+ locator: record.credentialId,
128
+ provider,
129
+ baseUrl: modelKeyBaseUrl(provider),
130
+ }, request);
131
+ }
132
+ catch {
133
+ throw new ModelKeyRefused("target_denied");
134
+ }
135
+ // `duplex` is a Node/Workers extension lib.dom's RequestInit omits.
136
+ const init = {
137
+ method: request.method,
138
+ headers: authenticated(provider, modelKeyForwardedHeaders(request), apiKey),
139
+ body: request.method === "GET" ? null : request.body,
140
+ signal: request.signal,
141
+ duplex: "half",
142
+ };
143
+ return send(new Request(target, init));
144
+ }));
145
+ },
146
+ };
147
+ }
@@ -60,6 +60,29 @@ export declare abstract class StandaloneRegistry extends OysterRegistry implemen
60
60
  updatedAt: number;
61
61
  }>[];
62
62
  readonly nextOffset: number | null;
63
+ } | ({
64
+ backendId: string;
65
+ error?: undefined;
66
+ } & Disposable) | ({
67
+ error: "request_conflict" | "invalid" | "not_owner" | "unknown_computer" | "not_enabled" | "local_limit";
68
+ backendId?: undefined;
69
+ } & Disposable) | ({
70
+ detached: boolean;
71
+ error?: undefined;
72
+ } & Disposable) | ({
73
+ error: "request_conflict" | "invalid" | "not_owner" | "unknown_computer" | "not_enabled" | "local_limit";
74
+ detached?: undefined;
75
+ } & Disposable) | {
76
+ backends: {
77
+ id: string;
78
+ kind: "platform-container" | "on-box-vm" | "local";
79
+ status: "queued" | "ready" | "online" | "offline";
80
+ queuePosition: number | null;
81
+ hostId: string | null;
82
+ hostLabel: string | null;
83
+ folderLabel: string | null;
84
+ detachable: boolean;
85
+ }[];
63
86
  } | ({
64
87
  state: "queued";
65
88
  position: number;
@@ -131,6 +131,10 @@ export class StandaloneRegistry extends OysterRegistry {
131
131
  enabled: await computer.keepAwake(input.operation === "set-keep-awake" ? input.enabled : undefined),
132
132
  };
133
133
  }
134
+ case "backends":
135
+ case "attach-local":
136
+ case "detach-local":
137
+ return this.#machines(memberId, input);
134
138
  case "select": {
135
139
  const computer = this.#computers.read(input.computerId);
136
140
  if (computer === null)
@@ -158,6 +162,32 @@ export class StandaloneRegistry extends OysterRegistry {
158
162
  });
159
163
  }
160
164
  }
165
+ /** Attached machines of one owned Computer; the Computer holds the rows. */
166
+ async #machines(memberId, input) {
167
+ const computerId = input.operation === "backends"
168
+ ? input.computerId
169
+ : input.request.computerId;
170
+ if (!this.ownsComputer(computerId))
171
+ return null;
172
+ const computer = this.#env.COMPUTER.getByName(computerId);
173
+ const authority = {
174
+ computerId,
175
+ actions: new Set(["backing"]),
176
+ expiresAt: Date.now() + 60_000,
177
+ provenance: { actor: memberId },
178
+ };
179
+ switch (input.operation) {
180
+ case "backends":
181
+ // The RPC result is disposable; the registry returns plain data.
182
+ return {
183
+ backends: [...(await computer.readBackends(authority, memberId))],
184
+ };
185
+ case "attach-local":
186
+ return await computer.attachLocalBackend(authority, memberId, input.request);
187
+ case "detach-local":
188
+ return await computer.detachLocalBackend(authority, memberId, input.request);
189
+ }
190
+ }
161
191
  /** A durable selection snapshot; the configured default remains the App build Computer. */
162
192
  async selectedComputer() {
163
193
  const selected = await this.#fleetStorage.get("selected-computer");
@@ -0,0 +1,10 @@
1
+ import type { CapabilitySource } from "@fungi.computer/mycelium";
2
+ import type { VeilBindings } from "@fungi.computer/veil/gatekeeper";
3
+ /**
4
+ * A standalone Oyster's `web` module. Page reads go through Veil's
5
+ * public-fetch door exactly as the Hub's do (one resolve, non-public addresses
6
+ * refused, redirects rechecked). Search is Parallel through Veil's route when
7
+ * the owner configured `PARALLEL_API_KEY`, else an explicit refusal. There is
8
+ * no credit ledger here: the owner's Parallel account pays directly.
9
+ */
10
+ export declare function standaloneWebSource(env: VeilBindings): CapabilitySource;
@@ -0,0 +1,34 @@
1
+ import { configuredPublicFetch } from "@fungi.computer/veil/public-fetch";
2
+ import { causeClass } from "../cause-class.js";
3
+ import { createWebSource, parallelWebSearch } from "../web/index.js";
4
+ /**
5
+ * A standalone Oyster's `web` module. Page reads go through Veil's
6
+ * public-fetch door exactly as the Hub's do (one resolve, non-public addresses
7
+ * refused, redirects rechecked). Search is Parallel through Veil's route when
8
+ * the owner configured `PARALLEL_API_KEY`, else an explicit refusal. There is
9
+ * no credit ledger here: the owner's Parallel account pays directly.
10
+ */
11
+ export function standaloneWebSource(env) {
12
+ return createWebSource({
13
+ // The sockets door loads when a page is first read, so hosts that never
14
+ // fetch (and Node test hosts) never resolve the Workers-only module.
15
+ get: async (request) => {
16
+ const { connect } = await import("cloudflare:sockets");
17
+ return configuredPublicFetch({
18
+ connect,
19
+ fetch: (input, init) => fetch(input, init),
20
+ }).get(request);
21
+ },
22
+ search: parallelWebSearch(env, {
23
+ fetch: (input, init) => fetch(input, init),
24
+ report: (event) => {
25
+ // Code-only: never a URL, provider body or key.
26
+ console.warn("Oyster web search", {
27
+ kind: event.kind,
28
+ status: event.status,
29
+ cause: causeClass(event.cause),
30
+ });
31
+ },
32
+ }),
33
+ });
34
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The standalone Worker's top-level table, before any tenant is selected:
3
- * device enrollment and links, signed Workflow webhook delivery, then the
3
+ * device enrollment and links, attached-machine dials, signed Workflow webhook delivery, then the
4
4
  * selected tenant's own declared host table for every other path. The Worker
5
5
  * and the authorization law both compose it here.
6
6
  */
@@ -10,6 +10,8 @@ import { type Routes } from "../authorization.js";
10
10
  export type StandaloneWorkerRoutePorts = Readonly<{
11
11
  /** The machine-link doors' own table, served for this request. */
12
12
  machineLink: (request: Request) => Promise<Response>;
13
+ /** A machine's signed dial to its attached Computer, verified by that Computer. */
14
+ localBackendDial: (request: Request) => Promise<Response>;
13
15
  /** Signed Workflow webhook delivery, verified by the library's run owner. */
14
16
  workflowWebhooks: Routes<BlankEnv>;
15
17
  /** The selected tenant's declared host table. */
@@ -4,6 +4,7 @@ export function standaloneWorkerRoutes(ports) {
4
4
  return routes()
5
5
  .all("/local/mesh/join", door("machine enrollment; the join route verifies its key"), (context) => ports.machineLink(context.req.raw))
6
6
  .all("/api/teams/:teamId/local/mesh/:deviceId/connect", door("a machine link; the device's link verifies Seam"), (context) => ports.machineLink(context.req.raw))
7
+ .all("/api/computers/:computerId/backends/:backendId/connect", door("an attached machine's dial; the Computer verifies its Seam signature"), (context) => ports.localBackendDial(context.req.raw))
7
8
  .include(ports.workflowWebhooks)
8
9
  .all("*", door("the selected tenant's own declared host table"), (context) => ports.tenant(context.req.raw));
9
10
  }
@@ -8,7 +8,7 @@ import { defaultTenant, tenantScope } from "../tenant.js";
8
8
  import { oysterPrincipalIsOwner } from "../authorization.js";
9
9
  import { standaloneComputerControl } from "./computer-control.js";
10
10
  import { standalonePermissionResources } from "./permission-resources.js";
11
- import { onBoxVmIngress } from "@fungi.computer/computer";
11
+ import { onBoxVmIngress, ownerLocalBackendDialPath, } from "@fungi.computer/computer";
12
12
  import { WorkerEntrypoint } from "cloudflare:workers";
13
13
  import { installationWorkerEntrypoint } from "../installation-execution.js";
14
14
  import { putContentObject } from "../build-contract.js";
@@ -189,6 +189,14 @@ export default {
189
189
  // tenant host's own declared table.
190
190
  return serveDoors(standaloneWorkerRoutes({
191
191
  machineLink: (incoming) => serveDoors(standaloneMachineLinkRoutes(env).onError(standaloneWorkerErrorHandler)).fetch(incoming, env, context),
192
+ localBackendDial: async (incoming) => {
193
+ const dial = ownerLocalBackendDialPath.exec(new URL(incoming.url).pathname);
194
+ // Only a Computer this Oyster owns is addressed; no stray object is made.
195
+ if (dial === null ||
196
+ !(await computerRegistry(env).ownsComputer(dial[1] ?? "")))
197
+ return new Response(null, { status: 404 });
198
+ return env.COMPUTER.getByName(dial[1] ?? "").fetch(incoming);
199
+ },
192
200
  workflowWebhooks: standaloneWorkflowWebhookRoutes(env, async (incoming) => {
193
201
  const admitted = await oysterRoot.admit(env, incoming);
194
202
  return admitted === null
@@ -0,0 +1,3 @@
1
+ export { createWebSource, fetchWebPage, WEB_FETCH_MAX_BYTES, type WebFetchResult, } from "./source.js";
2
+ export { parallelWebSearch, unconfiguredWebSearch, WebSearchError, type WebSearchReport, } from "./search.js";
3
+ export { webSearchInputSchema, webSearchOutputSchema, type WebSearch, type WebSearchInput, type WebSearchOutput, } from "./search-contract.js";
@@ -0,0 +1,3 @@
1
+ export { createWebSource, fetchWebPage, WEB_FETCH_MAX_BYTES, } from "./source.js";
2
+ export { parallelWebSearch, unconfiguredWebSearch, WebSearchError, } from "./search.js";
3
+ export { webSearchInputSchema, webSearchOutputSchema, } from "./search-contract.js";
@@ -0,0 +1,19 @@
1
+ import { z } from "zod";
2
+ export declare const webSearchInputSchema: z.ZodObject<{
3
+ objective: z.ZodString;
4
+ queries: z.ZodDefault<z.ZodArray<z.ZodString>>;
5
+ maxResults: z.ZodDefault<z.ZodNumber>;
6
+ }, z.core.$strict>;
7
+ export declare const webSearchOutputSchema: z.ZodObject<{
8
+ results: z.ZodArray<z.ZodObject<{
9
+ url: z.ZodString;
10
+ title: z.ZodNullable<z.ZodString>;
11
+ publishDate: z.ZodNullable<z.ZodString>;
12
+ excerpts: z.ZodArray<z.ZodString>;
13
+ }, z.core.$strict>>;
14
+ }, z.core.$strict>;
15
+ export type WebSearchInput = z.output<typeof webSearchInputSchema>;
16
+ export type WebSearchOutput = z.output<typeof webSearchOutputSchema>;
17
+ export type WebSearch = Readonly<{
18
+ search: (input: WebSearchInput, signal: AbortSignal) => Promise<WebSearchOutput>;
19
+ }>;
@@ -0,0 +1,14 @@
1
+ import { z } from "zod";
2
+ export const webSearchInputSchema = z.strictObject({
3
+ objective: z.string().trim().min(1).max(2_000),
4
+ queries: z.array(z.string().trim().min(1).max(200)).max(5).default([]),
5
+ maxResults: z.number().int().min(1).max(10).default(5),
6
+ });
7
+ export const webSearchOutputSchema = z.strictObject({
8
+ results: z.array(z.strictObject({
9
+ url: z.string(),
10
+ title: z.string().nullable(),
11
+ publishDate: z.string().nullable(),
12
+ excerpts: z.array(z.string()),
13
+ })),
14
+ });
@@ -0,0 +1,25 @@
1
+ import { type VeilBindings } from "@fungi.computer/veil/gatekeeper";
2
+ import type { WebSearch } from "./search-contract.js";
3
+ export type WebSearchErrorCode = "unavailable" | "insufficient_credits" | "denied" | "provider";
4
+ /** A typed search failure whose message is safe to show the model. */
5
+ export declare class WebSearchError extends Error {
6
+ readonly code: WebSearchErrorCode;
7
+ constructor(code: WebSearchErrorCode, message: string);
8
+ }
9
+ /** A diagnostic a host decides how to record; it never carries a body or key. */
10
+ export type WebSearchReport = Readonly<{
11
+ kind: "response_body_unavailable";
12
+ status: number;
13
+ cause: unknown;
14
+ }>;
15
+ /** The operation's behavior when no search provider is configured. */
16
+ export declare const unconfiguredWebSearch: WebSearch;
17
+ /**
18
+ * Parallel Search for a host's Worker environment: unconfigured without
19
+ * Veil's Parallel credential, otherwise Parallel through the AI Gateway when
20
+ * the host names one, else directly.
21
+ */
22
+ export declare function parallelWebSearch(env: VeilBindings, options: Readonly<{
23
+ fetch: typeof globalThis.fetch;
24
+ report: (event: WebSearchReport) => void;
25
+ }>): WebSearch;
@@ -0,0 +1,123 @@
1
+ import { z } from "zod";
2
+ import { configuredProviderEgress, providerFetch, } from "@fungi.computer/veil/gatekeeper";
3
+ /**
4
+ * `web.search` through Parallel's Search API (routed through the AI Gateway
5
+ * when the host names one). Veil owns the key and the route: this module never
6
+ * sees the credential. Without a Parallel key the operation says so and
7
+ * fetches nothing; it never invents results. Funding is the host's decision:
8
+ * the Hub wraps this search in Team credits, a standalone Oyster's owner pays
9
+ * Parallel directly.
10
+ */
11
+ /** Excerpt characters returned to the model across all results. */
12
+ const maxChars = 12_000;
13
+ /** A typed search failure whose message is safe to show the model. */
14
+ export class WebSearchError extends Error {
15
+ code;
16
+ constructor(code, message) {
17
+ super(`web.search ${code}: ${message}`);
18
+ this.code = code;
19
+ this.name = "WebSearchError";
20
+ }
21
+ }
22
+ /** Parallel's `/v1/search` answer; unknown fields are ignored. */
23
+ const parallelResponseSchema = z.looseObject({
24
+ results: z.array(z.looseObject({
25
+ url: z.url(),
26
+ title: z.string().nullish(),
27
+ publish_date: z.string().nullish(),
28
+ excerpts: z.array(z.string()).default([]),
29
+ })),
30
+ });
31
+ /**
32
+ * Parallel Search over `baseUrl`, which is Parallel or the gateway route.
33
+ * `fetch` is Veil's `parallel` route: it carries the key, never this module.
34
+ */
35
+ function createParallelSearch(options) {
36
+ return {
37
+ search: async (input, signal) => {
38
+ let response;
39
+ try {
40
+ response = await options.fetch(`${options.baseUrl}/v1/search`, {
41
+ method: "POST",
42
+ headers: {
43
+ "Content-Type": "application/json",
44
+ },
45
+ body: JSON.stringify({
46
+ objective: input.objective,
47
+ search_queries: input.queries.length > 0
48
+ ? input.queries
49
+ : [input.objective.slice(0, 200)],
50
+ mode: "basic",
51
+ max_chars_total: maxChars,
52
+ advanced_settings: { max_results: input.maxResults },
53
+ }),
54
+ signal,
55
+ });
56
+ }
57
+ catch {
58
+ signal.throwIfAborted();
59
+ throw new WebSearchError("provider", "the search service is unreachable");
60
+ }
61
+ if (!response.ok) {
62
+ await response.body?.cancel();
63
+ throw new WebSearchError("provider", `the search service answered HTTP ${String(response.status)}`);
64
+ }
65
+ let body;
66
+ try {
67
+ body = await response.json();
68
+ }
69
+ catch (cause) {
70
+ signal.throwIfAborted();
71
+ options.report({
72
+ kind: "response_body_unavailable",
73
+ status: response.status,
74
+ cause,
75
+ });
76
+ throw new WebSearchError("provider", "the search answer could not be read");
77
+ }
78
+ const parsed = parallelResponseSchema.safeParse(body);
79
+ if (!parsed.success)
80
+ throw new WebSearchError("provider", "the search answer was malformed");
81
+ let budget = maxChars;
82
+ return {
83
+ results: parsed.data.results
84
+ .slice(0, input.maxResults)
85
+ .map((result) => {
86
+ const excerpts = [];
87
+ for (const excerpt of result.excerpts) {
88
+ if (budget <= 0)
89
+ break;
90
+ excerpts.push(excerpt.slice(0, budget));
91
+ budget -= excerpt.length;
92
+ }
93
+ return {
94
+ url: result.url,
95
+ title: result.title ?? null,
96
+ publishDate: result.publish_date ?? null,
97
+ excerpts,
98
+ };
99
+ }),
100
+ };
101
+ },
102
+ };
103
+ }
104
+ /** The operation's behavior when no search provider is configured. */
105
+ export const unconfiguredWebSearch = {
106
+ search: () => Promise.reject(new WebSearchError("unavailable", "web search is not configured on this platform; no search was run")),
107
+ };
108
+ /**
109
+ * Parallel Search for a host's Worker environment: unconfigured without
110
+ * Veil's Parallel credential, otherwise Parallel through the AI Gateway when
111
+ * the host names one, else directly.
112
+ */
113
+ export function parallelWebSearch(env, options) {
114
+ const egress = configuredProviderEgress(env, { fetch: options.fetch });
115
+ const baseUrl = egress.baseUrl("parallel");
116
+ if (baseUrl === null)
117
+ return unconfiguredWebSearch;
118
+ return createParallelSearch({
119
+ baseUrl,
120
+ fetch: providerFetch(egress, "parallel"),
121
+ report: options.report,
122
+ });
123
+ }