@fungi.computer/tourtois 0.5.3 → 0.7.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.
@@ -0,0 +1,200 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { SectionHeading } from "@fungi.computer/caps/blocks/section-heading";
3
+ import { Button } from "@fungi.computer/caps/components/button";
4
+ import { DataList, DataListHeading, DataRow, FactRow, } from "@fungi.computer/caps/components/data-list";
5
+ import { FormFooter } from "@fungi.computer/caps/components/field";
6
+ import { KeycapButton } from "@fungi.computer/caps/components/keycap";
7
+ import { SchemaForm, field, useSchemaForm } from "@fungi.computer/caps/form";
8
+ import { Sigil } from "@fungi.computer/sigils";
9
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
10
+ import { useMemo, useState } from "react";
11
+ import * as z from "zod";
12
+ import { SettingsItem } from "./settings-item.js";
13
+ const providers = {
14
+ anthropic: "Anthropic",
15
+ openai: "OpenAI",
16
+ openrouter: "OpenRouter",
17
+ };
18
+ const providerSchema = z.enum(["anthropic", "openai", "openrouter"]);
19
+ /** One stored key as the host lists it; the secret never comes back. */
20
+ const modelKeySchema = z.strictObject({
21
+ keyId: z.string().min(1),
22
+ provider: providerSchema,
23
+ label: z.string().min(1),
24
+ createdAt: z.number(),
25
+ validatedAt: z.number(),
26
+ });
27
+ const agentChoiceSchema = z.strictObject({
28
+ keySource: z.enum(["workers-ai", "ai-gateway", "byok"]),
29
+ keyId: z.string().min(1).optional(),
30
+ model: z.strictObject({
31
+ providerId: z.string().min(1),
32
+ modelId: z.string().min(1),
33
+ reasoning: z.string().optional(),
34
+ }),
35
+ });
36
+ /** Every stored key and every Agent with its persisted model choice. */
37
+ export const modelKeysViewSchema = z.strictObject({
38
+ keys: z.array(modelKeySchema),
39
+ agents: z.array(z.strictObject({
40
+ agentId: z.string().min(1),
41
+ name: z.string(),
42
+ choice: agentChoiceSchema.nullable(),
43
+ })),
44
+ });
45
+ const queryKey = ["tourtois", "model-keys"];
46
+ const defaultSource = "default";
47
+ /**
48
+ * Model keys on a standalone host: store a provider API key once, then pick
49
+ * which model and key each Agent runs on. A key is never shown again.
50
+ */
51
+ export function ModelKeys({ port }) {
52
+ const client = useQueryClient();
53
+ const view = useQuery({ queryKey, queryFn: () => port.read() });
54
+ const refresh = () => client.invalidateQueries({ queryKey });
55
+ const remove = useMutation({
56
+ mutationFn: (keyId) => port.removeKey(keyId),
57
+ onSuccess: refresh,
58
+ });
59
+ const keys = view.data?.keys ?? [];
60
+ const agents = view.data?.agents ?? [];
61
+ // A fresh form after each stored key, so the key field empties.
62
+ const [formKey, setFormKey] = useState(0);
63
+ return (_jsxs("section", { className: "tourtois-settings-content tourtois-model-keys", "aria-label": "Model keys", children: [_jsx(SectionHeading, { children: "Model keys" }), _jsx("p", { className: "tourtois-settings-lede", children: "Bring your own provider API key. It is checked with the provider, sealed on this instance and never shown again. Each Agent can run on any key." }), view.isPending ? _jsx("p", { children: "Loading model keys\u2026" }) : null, view.isError ? (_jsxs("div", { role: "status", className: "tourtois-settings-notice", children: [_jsx("p", { children: "Model keys could not be loaded." }), _jsx(Button, { size: "sm", variant: "outline", onClick: () => void view.refetch(), children: "Retry" })] })) : null, view.isSuccess ? (_jsxs(_Fragment, { children: [_jsxs(DataList, { "aria-label": "Model keys", children: [keys.length === 0 ? (_jsx(DataRow, { className: "tourtois-settings-empty", children: "No model keys yet." })) : null, keys.map((key) => (_jsx(DataRow, { children: _jsx(SettingsItem, { icon: _jsx(Sigil, { name: "restricted" }), title: key.label, detail: _jsx("p", { children: providers[key.provider] }), actions: _jsx(KeycapButton, { density: "compact", tone: "destructive", label: "Remove", "aria-label": `Remove ${key.label}`, disabled: remove.isPending, onClick: () => {
64
+ remove.mutate(key.keyId);
65
+ } }) }) }, key.keyId)))] }), remove.isError ? (_jsx("p", { role: "alert", children: "The model key could not be removed." })) : null, _jsx(AddModelKey, { onAdd: async (draft) => {
66
+ await port.addKey(draft);
67
+ await refresh();
68
+ setFormKey((current) => current + 1);
69
+ } }, formKey), _jsx(SectionHeading, { children: "Agent models" }), _jsxs(DataList, { density: "compact", "aria-label": "Agent models", children: [_jsx(DataListHeading, { children: "Current choice" }), agents.length === 0 ? (_jsx(DataRow, { className: "tourtois-settings-empty", children: "Create an Agent first." })) : null, agents.map((agent) => {
70
+ const keyLabel = agent.choice?.keyId === undefined
71
+ ? null
72
+ : (keys.find((key) => key.keyId === agent.choice?.keyId)
73
+ ?.label ?? "Removed key");
74
+ return (_jsxs(FactRow, { icon: _jsx(Sigil, { name: "agent" }), label: agent.name, children: [agent.choice?.model.modelId ?? "Unavailable", keyLabel === null ? "" : ` · ${keyLabel}`] }, agent.agentId));
75
+ })] }), agents.length > 0 ? (_jsx(ChooseAgentModel, { agents: agents, keys: keys, onChoose: async (agentId, draft) => {
76
+ await port.chooseModel(agentId, draft);
77
+ await refresh();
78
+ } })) : null] })) : null] }));
79
+ }
80
+ function AddModelKey({ onAdd, }) {
81
+ const schema = useMemo(() => z.object({
82
+ provider: providerSchema.meta(field({
83
+ label: "Provider",
84
+ icon: _jsx(Sigil, { name: "internet" }),
85
+ kind: "select",
86
+ options: providers,
87
+ })),
88
+ label: z
89
+ .string()
90
+ .min(1, "Name this key")
91
+ .max(64)
92
+ .meta(field({
93
+ label: "Name",
94
+ icon: _jsx(Sigil, { name: "write" }),
95
+ maxLength: 64,
96
+ placeholder: "Work key",
97
+ })),
98
+ apiKey: z
99
+ .string()
100
+ .min(1, "Paste the key")
101
+ .max(16_384)
102
+ .meta(field({
103
+ label: "API key",
104
+ icon: _jsx(Sigil, { name: "restricted" }),
105
+ help: "Sealed on this instance and never shown again.",
106
+ kind: "secret",
107
+ })),
108
+ }), []);
109
+ const add = useMutation({ mutationFn: onAdd });
110
+ const model = useSchemaForm({
111
+ schema,
112
+ defaultValues: { provider: "anthropic", label: "", apiKey: "" },
113
+ onSubmit: async (value) => {
114
+ try {
115
+ await add.mutateAsync(value);
116
+ return { kind: "saved" };
117
+ }
118
+ catch (cause) {
119
+ return {
120
+ kind: "refused",
121
+ error: cause instanceof Error
122
+ ? cause.message
123
+ : "The model key could not be stored.",
124
+ };
125
+ }
126
+ },
127
+ });
128
+ return (_jsx(SchemaForm, { model: model, layout: "columns", "aria-label": "Add model key", disabled: add.isPending, footer: _jsx(FormFooter, { divider: false, error: model.error, children: _jsx(Button, { type: "submit", children: add.isPending ? "Checking…" : "Add model key" }) }) }));
129
+ }
130
+ function ChooseAgentModel({ agents, keys, onChoose, }) {
131
+ const schema = useMemo(() => z.object({
132
+ agentId: z.string().meta(field({
133
+ label: "Agent",
134
+ icon: _jsx(Sigil, { name: "agent" }),
135
+ kind: "select",
136
+ options: Object.fromEntries(agents.map((agent) => [agent.agentId, agent.name])),
137
+ })),
138
+ source: z.string().meta(field({
139
+ label: "Runs on",
140
+ icon: _jsx(Sigil, { name: "restricted" }),
141
+ kind: "select",
142
+ options: {
143
+ [defaultSource]: "Instance default model",
144
+ ...Object.fromEntries(keys.map((key) => [
145
+ key.keyId,
146
+ `${key.label} (${providers[key.provider]})`,
147
+ ])),
148
+ },
149
+ })),
150
+ modelId: z
151
+ .string()
152
+ .max(256)
153
+ .meta(field({
154
+ label: "Model",
155
+ icon: _jsx(Sigil, { name: "write" }),
156
+ help: "For a key: the provider's model id, such as gpt-6-luna.",
157
+ maxLength: 256,
158
+ })),
159
+ }), [agents, keys]);
160
+ const choose = useMutation({
161
+ mutationFn: (input) => onChoose(input.agentId, input.draft),
162
+ });
163
+ const model = useSchemaForm({
164
+ schema,
165
+ defaultValues: {
166
+ agentId: agents[0]?.agentId ?? "",
167
+ source: defaultSource,
168
+ modelId: "",
169
+ },
170
+ onSubmit: async (value) => {
171
+ const key = keys.find((item) => item.keyId === value.source);
172
+ if (value.source !== defaultSource && key === undefined)
173
+ return { kind: "refused", error: "Choose a stored key." };
174
+ if (key !== undefined && value.modelId.length === 0)
175
+ return { kind: "refused", error: "Name the model this key runs." };
176
+ try {
177
+ await choose.mutateAsync({
178
+ agentId: value.agentId,
179
+ draft: key === undefined
180
+ ? { keyId: null }
181
+ : {
182
+ keyId: key.keyId,
183
+ provider: key.provider,
184
+ modelId: value.modelId,
185
+ },
186
+ });
187
+ return { kind: "saved" };
188
+ }
189
+ catch (cause) {
190
+ return {
191
+ kind: "refused",
192
+ error: cause instanceof Error
193
+ ? cause.message
194
+ : "The model could not be saved.",
195
+ };
196
+ }
197
+ },
198
+ });
199
+ return (_jsx(SchemaForm, { model: model, layout: "columns", "aria-label": "Choose Agent model", disabled: choose.isPending, footer: _jsx(FormFooter, { divider: false, error: model.error, children: _jsx(Button, { type: "submit", children: choose.isPending ? "Saving…" : "Save model" }) }) }));
200
+ }
@@ -1,4 +1,5 @@
1
1
  import { teamComputerDirectorySchema, type TeamComputer } from "@fungi.computer/nacre/workbench";
2
+ import { type ReactElement, type ReactNode } from "react";
2
3
  import * as z from "zod";
3
4
  /** One owner-fleet page returned by the public Computer controls port. */
4
5
  export type ComputerPage = z.output<typeof teamComputerDirectorySchema>;
@@ -9,6 +10,10 @@ export type OysterComputersPort = Readonly<{
9
10
  start(computerId: string): Promise<void>;
10
11
  internetAccess(computerId: string): Promise<boolean>;
11
12
  setInternetAccess(computerId: string, enabled: boolean): Promise<boolean>;
13
+ keepAwake(computerId: string): Promise<boolean>;
14
+ setKeepAwake(computerId: string, enabled: boolean): Promise<boolean>;
15
+ /** Hosts that bill a running Computer's idle time say so beside Keep awake. */
16
+ idleMetered?: true;
12
17
  /** Only hosts with a persisted default for new Apps supply selection. */
13
18
  selection?: Readonly<{
14
19
  selected(): Promise<string | null>;
@@ -17,8 +22,23 @@ export type OysterComputersPort = Readonly<{
17
22
  /** Operator policy readback, when the host exposes it. Unknown locks writes. */
18
23
  egressPolicy?(): Promise<"enabled" | "globally-disabled" | "team-disabled">;
19
24
  }>;
25
+ /** The durable per-Computer switches an owner manages. */
26
+ export type ComputerSwitchSetting = "internet-access" | "keep-awake";
20
27
  /** Bind owner-admitted fleet controls to this trusted shell's host origin. */
21
28
  export declare function createOysterComputersPort(origin: URL): OysterComputersPort;
29
+ /**
30
+ * One per-Computer setting row, the same wherever a Computer's switches show:
31
+ * a Sigil and label, help under it, and the control opposite.
32
+ */
33
+ export declare function ComputerSettingRow({ setting, description, error, children, }: {
34
+ setting: ComputerSwitchSetting;
35
+ description?: ReactNode;
36
+ error?: ReactNode;
37
+ /** The setting's Switch, or a retry key while it cannot be read. */
38
+ children: ReactElement;
39
+ }): import("react/jsx-runtime").JSX.Element;
40
+ /** Keep awake's help; hosts that bill idle time say so. */
41
+ export declare const keepAwakeHelp: (idleMetered: boolean) => string;
22
42
  /** Owner Settings over the host's existing inventory and optional default. */
23
43
  export declare function OysterComputers({ teamId, port, onChanged, }: {
24
44
  teamId: string;
@@ -1,12 +1,16 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { AppError } from "@fungi.computer/agar";
3
3
  import { optimisticMutation } from "@fungi.computer/agar/query";
4
4
  import { SectionHeading } from "@fungi.computer/caps/blocks/section-heading";
5
- import { ActionRow } from "@fungi.computer/caps/components/action-row";
6
5
  import { Button } from "@fungi.computer/caps/components/button";
7
6
  import { DataList, DataRow } from "@fungi.computer/caps/components/data-list";
8
- import { Input } from "@fungi.computer/caps/components/input";
7
+ import { Field, FormFooter } from "@fungi.computer/caps/components/field";
8
+ import { KeycapButton } from "@fungi.computer/caps/components/keycap";
9
+ import { Status } from "@fungi.computer/caps/components/status";
9
10
  import { Switch } from "@fungi.computer/caps/components/switch";
11
+ import { SchemaForm, field, useSchemaForm, } from "@fungi.computer/caps/form";
12
+ import { Sigil } from "@fungi.computer/sigils";
13
+ import { SettingsItem } from "./settings-item.js";
10
14
  import { teamComputerDirectorySchema, teamComputerSchema, } from "@fungi.computer/nacre/workbench";
11
15
  import { workbenchDirectorySchema } from "@fungi.computer/nacre/workbench-directory";
12
16
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
@@ -14,7 +18,7 @@ import { useRef, useState } from "react";
14
18
  import * as z from "zod";
15
19
  import { requestIds } from "./team-directory.js";
16
20
  import { tourtoisQueryKeys } from "./queries.js";
17
- const internetAccessSchema = z.strictObject({ enabled: z.boolean() });
21
+ const computerSwitchSchema = z.strictObject({ enabled: z.boolean() });
18
22
  async function request(url, init) {
19
23
  const response = await fetch(url, {
20
24
  ...init,
@@ -35,6 +39,18 @@ async function request(url, init) {
35
39
  /** Bind owner-admitted fleet controls to this trusted shell's host origin. */
36
40
  export function createOysterComputersPort(origin) {
37
41
  const read = (path, init) => request(new URL(path, origin), init);
42
+ const switchPath = (computerId, setting) => `/api/computers/${encodeURIComponent(computerId)}/${setting}`;
43
+ const readSwitch = async (computerId, setting) => {
44
+ const response = await read(switchPath(computerId, setting));
45
+ return computerSwitchSchema.parse(await response.json()).enabled;
46
+ };
47
+ const writeSwitch = async (computerId, setting, enabled) => {
48
+ const response = await read(switchPath(computerId, setting), {
49
+ method: "PUT",
50
+ body: JSON.stringify({ enabled }),
51
+ });
52
+ return computerSwitchSchema.parse(await response.json()).enabled;
53
+ };
38
54
  return {
39
55
  list: async (offset) => {
40
56
  const response = await read(`/api/computers?${new URLSearchParams({ limit: "100", offset: String(offset) })}`);
@@ -68,40 +84,75 @@ export function createOysterComputersPort(origin) {
68
84
  return teamComputerSchema.parse(await response.json());
69
85
  },
70
86
  },
71
- internetAccess: async (computerId) => {
72
- const response = await read(`/api/computers/${encodeURIComponent(computerId)}/internet-access`);
73
- return internetAccessSchema.parse(await response.json()).enabled;
74
- },
75
- setInternetAccess: async (computerId, enabled) => {
76
- const response = await read(`/api/computers/${encodeURIComponent(computerId)}/internet-access`, { method: "PUT", body: JSON.stringify({ enabled }) });
77
- return internetAccessSchema.parse(await response.json()).enabled;
78
- },
87
+ internetAccess: (computerId) => readSwitch(computerId, "internet-access"),
88
+ setInternetAccess: (computerId, enabled) => writeSwitch(computerId, "internet-access", enabled),
89
+ keepAwake: (computerId) => readSwitch(computerId, "keep-awake"),
90
+ setKeepAwake: (computerId, enabled) => writeSwitch(computerId, "keep-awake", enabled),
79
91
  };
80
92
  }
81
- function InternetAccess({ teamId, computer, port, policy, }) {
82
- const queryKey = tourtoisQueryKeys.oysterInternetAccess(teamId, computer.computerId);
83
- const current = useQuery({
84
- queryKey,
85
- queryFn: () => port.internetAccess(computer.computerId),
86
- });
93
+ const computerSettings = {
94
+ "internet-access": { label: "Internet access", sigil: "internet" },
95
+ "keep-awake": { label: "Keep awake", sigil: "schedule" },
96
+ };
97
+ /**
98
+ * One per-Computer setting row, the same wherever a Computer's switches show:
99
+ * a Sigil and label, help under it, and the control opposite.
100
+ */
101
+ export function ComputerSettingRow({ setting, description, error, children, }) {
102
+ const { label, sigil } = computerSettings[setting];
103
+ return (_jsx(DataRow, { children: _jsx(Field, { orientation: "horizontal", icon: _jsx(Sigil, { name: sigil }), label: label, description: description, error: error, children: children }) }));
104
+ }
105
+ /** One durable per-Computer switch: same read, save, retry and error shape. */
106
+ function ComputerSwitch({ setting, description, computer, queryKey, read, write, locked, }) {
107
+ const { label } = computerSettings[setting];
108
+ const current = useQuery({ queryKey, queryFn: read });
87
109
  const update = useMutation(optimisticMutation({
88
110
  queryKey,
89
111
  apply: (_previous, enabled) => enabled,
90
- mutationFn: (enabled) => port.setInternetAccess(computer.computerId, enabled),
112
+ mutationFn: write,
91
113
  }));
92
- return (_jsxs("div", { className: "grid gap-sm", children: [_jsxs("label", { className: "flex gap-sm", children: ["Internet access", _jsx(Switch, { "aria-label": `Internet access for ${computer.name}`, checked: current.data ?? false, disabled: policy !== "enabled" ||
93
- current.data === undefined ||
94
- update.isPending, onCheckedChange: (enabled) => {
95
- update.mutate(enabled);
96
- } })] }), current.isPending ? (_jsx("p", { role: "status", children: "Checking Internet access\u2026" })) : null, current.isError ? (_jsxs("div", { role: "alert", children: [_jsxs("p", { children: ["Could not check Internet access for ", computer.name, "."] }), _jsx(Button, { onClick: () => {
97
- void current.refetch();
98
- }, children: "Retry Internet access" })] })) : null, update.isError ? (_jsxs("p", { role: "alert", children: ["Could not save Internet access for ", computer.name, "."] })) : null, policy === "globally-disabled" ? (_jsx("p", { children: "Internet access is locked by the global off switch." })) : null, policy === "team-disabled" ? (_jsx("p", { children: "Internet access is locked for this Team." })) : null] }));
114
+ return (_jsx(ComputerSettingRow, { setting: setting, description: description, error: current.isError
115
+ ? `Could not check ${label} for ${computer.name}.`
116
+ : update.isError
117
+ ? `Could not save ${label} for ${computer.name}.`
118
+ : undefined, children: current.isError ? (_jsx(Button, { size: "sm", variant: "outline", "aria-label": `Retry ${label}`, onClick: () => {
119
+ void current.refetch();
120
+ }, children: "Retry" })) : (_jsx(Switch, { "aria-label": `${label} for ${computer.name}`, checked: current.data ?? false, disabled: locked || current.data === undefined || update.isPending, onCheckedChange: (enabled) => {
121
+ update.mutate(enabled);
122
+ } })) }));
123
+ }
124
+ const lockedReason = {
125
+ enabled: undefined,
126
+ "globally-disabled": "Internet access is locked by the global off switch.",
127
+ "team-disabled": "Internet access is locked for this Team.",
128
+ unavailable: undefined,
129
+ };
130
+ function InternetAccess({ teamId, computer, port, policy, }) {
131
+ return (_jsx(ComputerSwitch, { setting: "internet-access", description: lockedReason[policy], computer: computer, queryKey: tourtoisQueryKeys.oysterInternetAccess(teamId, computer.computerId), read: () => port.internetAccess(computer.computerId), write: (enabled) => port.setInternetAccess(computer.computerId, enabled), locked: policy !== "enabled" }));
132
+ }
133
+ function KeepAwake({ teamId, computer, port, }) {
134
+ return (_jsx(ComputerSwitch, { setting: "keep-awake", computer: computer, queryKey: tourtoisQueryKeys.oysterKeepAwake(teamId, computer.computerId), read: () => port.keepAwake(computer.computerId), write: (enabled) => port.setKeepAwake(computer.computerId, enabled), locked: false, description: keepAwakeHelp(port.idleMetered === true) }));
99
135
  }
136
+ /** Keep awake's help; hosts that bill idle time say so. */
137
+ export const keepAwakeHelp = (idleMetered) => `${idleMetered
138
+ ? "Stays on when idle, and idle time is charged."
139
+ : "Stays on when idle."} Off, it sleeps after 15 idle minutes.`;
140
+ const createComputerSchema = z.object({
141
+ name: z
142
+ .string()
143
+ .trim()
144
+ .max(256, "Use at most 256 characters.")
145
+ .meta(field({
146
+ label: "Name",
147
+ icon: _jsx(Sigil, { name: "computer" }),
148
+ placeholder: "Leave blank for a generated name",
149
+ maxLength: 256,
150
+ })),
151
+ });
100
152
  /** Owner Settings over the host's existing inventory and optional default. */
101
153
  export function OysterComputers({ teamId, port, onChanged, }) {
102
154
  const client = useQueryClient();
103
155
  const [offset, setOffset] = useState(0);
104
- const [name, setName] = useState("");
105
156
  const intent = useRef(null);
106
157
  const inventoryKey = tourtoisQueryKeys.oysterComputers(teamId);
107
158
  const selectionKey = tourtoisQueryKeys.oysterSelectedComputer(teamId);
@@ -142,7 +193,6 @@ export function OysterComputers({ teamId, port, onChanged, }) {
142
193
  onSuccess: async (_result, input) => {
143
194
  if (input.kind === "create") {
144
195
  intent.current = null;
145
- setName("");
146
196
  setOffset(0);
147
197
  }
148
198
  await Promise.all([
@@ -159,46 +209,61 @@ export function OysterComputers({ teamId, port, onChanged, }) {
159
209
  inventory.isFetching ||
160
210
  (selection !== undefined && selected.isFetching) ||
161
211
  action.isPending;
212
+ const create = useSchemaForm({
213
+ schema: createComputerSchema,
214
+ defaultValues: { name: "" },
215
+ failure: "Could not create the Computer.",
216
+ onSubmit: async ({ name }) => {
217
+ const requestedName = name === "" ? undefined : name;
218
+ // A retried create keeps its request identity until the host confirms it.
219
+ if (intent.current === null || intent.current.name !== requestedName)
220
+ intent.current = {
221
+ kind: "create",
222
+ name: requestedName,
223
+ requestId: requestIds.request.generate(),
224
+ };
225
+ try {
226
+ await action.mutateAsync(intent.current);
227
+ }
228
+ catch (cause) {
229
+ return cause instanceof Error
230
+ ? { kind: "refused", error: cause.message }
231
+ : { kind: "refused" };
232
+ }
233
+ return { kind: "saved", values: { name: "" } };
234
+ },
235
+ });
162
236
  const policyStatus = port.egressPolicy === undefined
163
237
  ? "enabled"
164
238
  : (policy.data ?? "unavailable");
165
- return (_jsxs("section", { className: "grid gap-sm", "aria-label": "Computers", children: [_jsx(SectionHeading, { children: "Computers" }), _jsx("p", { children: selection === undefined
239
+ const computers = inventory.data?.computers ?? [];
240
+ const paged = offset > 0 || inventory.data?.nextOffset != null;
241
+ return (_jsxs("section", { className: "tourtois-settings-stack", "aria-label": "Computers", children: [_jsx(SectionHeading, { children: "Computers" }), _jsx("p", { className: "tourtois-settings-lede", children: selection === undefined
166
242
  ? "Manage your Team's Computers."
167
- : "Choose the default Computer used for new App configurations." }), port.egressPolicy !== undefined && policyStatus === "unavailable" ? (_jsxs("div", { role: "alert", children: [_jsx("p", { children: "Internet access policy is unavailable; switches are locked." }), _jsx(Button, { onClick: () => void policy.refetch(), children: "Retry policy" })] })) : null, inventory.isPending ? _jsx("p", { role: "status", children: "Loading Computers\u2026" }) : null, inventory.isError || (selection !== undefined && selected.isError) ? (_jsxs("div", { role: "alert", children: [_jsx("p", { children: "Computer inventory or selection could not be loaded." }), _jsx(Button, { onClick: () => {
243
+ : "Choose the default Computer used for new App configurations." }), port.egressPolicy !== undefined && policyStatus === "unavailable" ? (_jsxs("div", { role: "alert", className: "tourtois-settings-notice", children: [_jsx("p", { children: "Internet access policy is unavailable; switches are locked." }), _jsx(Button, { size: "sm", variant: "outline", onClick: () => void policy.refetch(), children: "Retry policy" })] })) : null, inventory.isPending ? _jsx("p", { role: "status", children: "Loading Computers\u2026" }) : null, inventory.isError || (selection !== undefined && selected.isError) ? (_jsxs("div", { role: "alert", className: "tourtois-settings-notice", children: [_jsx("p", { children: "Computer inventory or selection could not be loaded." }), _jsx(Button, { size: "sm", variant: "outline", onClick: () => {
168
244
  void inventory.refetch();
169
245
  if (selection !== undefined)
170
246
  void selected.refetch();
171
- }, children: "Retry" })] })) : null, inventory.isSuccess && inventory.data.computers.length === 0 ? (_jsx("p", { children: "No Computers on this page." })) : null, inventory.data !== undefined ? (_jsx(DataList, { "aria-label": "Computer inventory", children: inventory.data.computers.map((computer) => (_jsx(DataRow, { className: "p-0", children: _jsxs("div", { className: "grid min-w-0 gap-sm", children: [_jsx(ActionRow, { label: computer.name, description: selection !== undefined &&
172
- selected.isSuccess &&
173
- selected.data === computer.computerId
174
- ? "Default for new Apps"
175
- : computer.computerId, trailing: _jsxs("div", { className: "flex flex-wrap gap-sm", children: [_jsx(Button, { "aria-label": `Start ${computer.name}`, disabled: unavailable, onClick: () => {
176
- action.mutate({
177
- kind: "start",
178
- computerId: computer.computerId,
179
- });
180
- }, children: "Start" }), selection !== undefined ? (_jsx(Button, { "aria-label": `Use ${computer.name} for new Apps`, disabled: unavailable || selected.data === computer.computerId, onClick: () => {
181
- action.mutate({
182
- kind: "select",
183
- computerId: computer.computerId,
184
- });
185
- }, children: "Use for new Apps" })) : null] }) }), _jsx(InternetAccess, { teamId: teamId, computer: computer, port: port, policy: policyStatus })] }) }, computer.computerId))) })) : null, _jsxs("div", { className: "flex gap-sm", "aria-label": "Computer pages", children: [_jsx(Button, { disabled: unavailable || offset === 0, onClick: () => {
247
+ }, children: "Retry" })] })) : null, inventory.isSuccess && computers.length === 0 ? (_jsx("p", { children: "No Computers on this page." })) : null, computers.map((computer) => {
248
+ const isDefault = selection !== undefined &&
249
+ selected.isSuccess &&
250
+ selected.data === computer.computerId;
251
+ return (_jsxs("section", { className: "tourtois-computer", "aria-label": computer.name, children: [_jsx(SettingsItem, { icon: _jsx(Sigil, { name: "computer" }), title: computer.name, actions: _jsxs(_Fragment, { children: [_jsx(KeycapButton, { density: "compact", label: "Start", icon: _jsx(Sigil, { name: "run" }), "aria-label": `Start ${computer.name}`, disabled: unavailable, onClick: () => {
252
+ action.mutate({
253
+ kind: "start",
254
+ computerId: computer.computerId,
255
+ });
256
+ } }), isDefault ? (_jsx(Status, { size: "compact", tone: "success", label: "Default for new Apps" })) : selection !== undefined ? (_jsx(KeycapButton, { density: "compact", label: "Use for new Apps", icon: _jsx(Sigil, { name: "allApps" }), "aria-label": `Use ${computer.name} for new Apps`, disabled: unavailable, onClick: () => {
257
+ action.mutate({
258
+ kind: "select",
259
+ computerId: computer.computerId,
260
+ });
261
+ } })) : null] }) }), _jsxs(DataList, { density: "compact", "aria-label": `${computer.name} settings`, children: [_jsx(InternetAccess, { teamId: teamId, computer: computer, port: port, policy: policyStatus }), _jsx(KeepAwake, { teamId: teamId, computer: computer, port: port })] })] }, computer.computerId));
262
+ }), paged ? (_jsxs("div", { className: "tourtois-settings-notice", "aria-label": "Computer pages", children: [_jsx(Button, { size: "sm", variant: "outline", disabled: unavailable || offset === 0, onClick: () => {
186
263
  setOffset(Math.max(0, offset - 100));
187
- }, children: "Previous" }), _jsx(Button, { disabled: unavailable || inventory.data?.nextOffset == null, onClick: () => {
264
+ }, children: "Previous" }), _jsx(Button, { size: "sm", variant: "outline", disabled: unavailable || inventory.data?.nextOffset == null, onClick: () => {
188
265
  const next = inventory.data?.nextOffset;
189
266
  if (next != null)
190
267
  setOffset(next);
191
- }, children: "Next" })] }), _jsxs("form", { className: "grid gap-sm", "aria-label": "Create Computer", onSubmit: (event) => {
192
- event.preventDefault();
193
- const requestedName = name === "" ? undefined : name;
194
- if (intent.current === null || intent.current.name !== requestedName)
195
- intent.current = {
196
- kind: "create",
197
- name: requestedName,
198
- requestId: requestIds.request.generate(),
199
- };
200
- action.mutate(intent.current);
201
- }, children: [_jsxs("label", { children: ["Computer name (optional)", _jsx(Input, { name: "computerName", maxLength: 256, value: name, disabled: unavailable, placeholder: "Leave blank for a generated name", onChange: (event) => {
202
- setName(event.currentTarget.value);
203
- } })] }), _jsx(Button, { type: "submit", disabled: unavailable, children: "Create Computer" })] }), action.isError ? _jsx("p", { role: "alert", children: action.error.message }) : null, action.isSuccess ? (_jsx("p", { role: "status", children: "Computer request completed." })) : null] }));
268
+ }, children: "Next" })] })) : null, _jsx(SchemaForm, { model: create, layout: "columns", "aria-label": "Create Computer", disabled: unavailable, footer: _jsx(FormFooter, { divider: false, error: create.error, children: _jsx(Button, { type: "submit", disabled: unavailable, children: "Create Computer" }) }) }), action.isError && action.variables.kind !== "create" ? (_jsx("p", { role: "alert", children: action.error.message })) : null, action.isSuccess ? (_jsx("p", { role: "status", children: "Computer request completed." })) : null] }));
204
269
  }
@@ -6,6 +6,7 @@ import { addressKey, } from "@fungi.computer/nacre/app-directory";
6
6
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
7
  import { AgentMcpServers } from "./AgentMcpServers.js";
8
8
  import { Keys } from "./Keys.js";
9
+ import { ModelKeys } from "./ModelKeys.js";
9
10
  import { AppIcon } from "./app-icon.js";
10
11
  import { AvatarSettings } from "./member-avatar.js";
11
12
  import { SettingsNavigation } from "./SettingsNavigation.js";
@@ -134,7 +135,7 @@ export function SystemSettings({ location: requestedLocation, sections: ceiling,
134
135
  computerCount: ports.summary?.computerCount ?? null,
135
136
  }, onNavigate: onNavigate })) : null, avatar && ports.avatar !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(AvatarSettings, { save: ports.avatar.save }) })) : null, connectors && agentMcpServers !== undefined ? (_jsx(AgentMcpServers, { port: agentMcpServers })) : null, connectors &&
136
137
  agentMcpServers === undefined &&
137
- ports.connectors !== undefined ? (_jsx(ports.connectors, { target: location.target, onNavigate: onNavigate })) : null, location?.category === "selling" && ports.selling !== undefined ? (_jsx(ports.selling, { appId: location.appId, onNavigate: onNavigate })) : null, computersSection && ports.computers !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(ports.computers, {}) })) : null, keysSection && keys !== undefined ? (_jsx(Keys, { port: keys, apps: keyableApps })) : null, location?.category === "channels" &&
138
+ ports.connectors !== undefined ? (_jsx(ports.connectors, { target: location.target, onNavigate: onNavigate })) : null, location?.category === "selling" && ports.selling !== undefined ? (_jsx(ports.selling, { appId: location.appId, onNavigate: onNavigate })) : null, computersSection && ports.computers !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(ports.computers, {}) })) : null, keysSection && keys !== undefined ? (_jsx(Keys, { port: keys, apps: keyableApps })) : null, keysSection && ports.modelKeys !== undefined ? (_jsx(ModelKeys, { port: ports.modelKeys })) : null, location?.category === "channels" &&
138
139
  ports.channels !== undefined ? (_jsx(ports.channels, {})) : null, defaults && ports.defaults !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(ports.defaults, { onAccepted: onAccepted }) })) : null, appSection && appKey === null ? (_jsxs("section", { className: "tourtois-settings-content", "aria-label": "Choose an App", children: [_jsx(SectionHeading, { className: "tourtois-settings-app-heading", children: desktopOnly ? "App desktop" : "App permissions" }), _jsx(DataList, { density: "compact", "aria-label": "Apps to review", children: apps.map((app) => (_jsx(DataRow, { className: "p-0", children: _jsx(ActionRow, { label: app.displayName ?? app.appId, icon: _jsx(AppIcon, { roles: app.roles, icon: app.icon }), onClick: () => {
139
140
  onNavigate({
140
141
  category: "apps",
@@ -14,6 +14,7 @@ import { z } from "zod";
14
14
  import { useEffect, useRef, useState } from "react";
15
15
  import { createRoot } from "react-dom/client";
16
16
  import { agentMcpServersViewSchema, createPlatformControls, PlatformControlsView, } from "./platform-controls.js";
17
+ import { modelKeysViewSchema } from "./ModelKeys.js";
17
18
  import { settingsLocationSchema } from "./settings-routes.js";
18
19
  import { OysterComputers, createOysterComputersPort, } from "./OysterComputers.js";
19
20
  import { useSettingsLeaveGuard, } from "./settings-leave-guard.js";
@@ -64,6 +65,68 @@ const agentMcpServers = {
64
65
  await ownerRequest(`/api/agent-mcp-servers/${encodeURIComponent(agentId)}/${encodeURIComponent(serverId)}`, { method: "DELETE" }, "The MCP server change was refused");
65
66
  },
66
67
  };
68
+ const modelKeyMessages = {
69
+ key_rejected: "The provider rejected this key",
70
+ provider_unavailable: "The provider could not be reached. Try again",
71
+ custody_unavailable: "This instance has no credential key. Set OYSTER_CREDENTIAL_KEY and redeploy",
72
+ limit: "Remove a model key before adding another",
73
+ invalid_key: "Choose a provider, name the key and paste it",
74
+ key_removed: "That key was removed",
75
+ key_source_mismatch: "That model does not belong to the key's provider",
76
+ model_unavailable: "That provider has no such model",
77
+ invalid_model_choice: "That model choice is not valid",
78
+ };
79
+ const modelKeyMessage = (code) => new Map(Object.entries(modelKeyMessages)).get(code) ?? code;
80
+ /** A model-key request whose host refusal code reads as a sentence. */
81
+ async function modelKeyRequest(path, init, refused) {
82
+ try {
83
+ return await ownerRequest(path, init, refused);
84
+ }
85
+ catch (cause) {
86
+ if (cause instanceof AppError)
87
+ throw new Error(modelKeyMessage(cause.message), { cause });
88
+ throw cause;
89
+ }
90
+ }
91
+ const jsonInit = (method, body) => ({
92
+ method,
93
+ headers: { "Content-Type": "application/json" },
94
+ body,
95
+ });
96
+ /** Owner-direct model-key custody: a key goes in once and never comes back. */
97
+ const modelKeys = {
98
+ read: async () => {
99
+ const [keys, agents] = await Promise.all([
100
+ json("/api/model-keys"),
101
+ json("/api/agent-models"),
102
+ ]);
103
+ return modelKeysViewSchema.parse({
104
+ keys: z.object({ keys: z.unknown() }).parse(keys).keys,
105
+ agents: z.object({ agents: z.unknown() }).parse(agents).agents,
106
+ });
107
+ },
108
+ addKey: async (draft) => {
109
+ await modelKeyRequest("/api/model-keys", jsonInit("POST", JSON.stringify(draft)), "The model key was refused");
110
+ },
111
+ removeKey: async (keyId) => {
112
+ await modelKeyRequest(`/api/model-keys/${encodeURIComponent(keyId)}`, { method: "DELETE" }, "The model key could not be removed");
113
+ },
114
+ chooseModel: async (agentId, draft) => {
115
+ await modelKeyRequest(`/api/agent-models/${encodeURIComponent(agentId)}`, jsonInit("PUT", JSON.stringify(draft.keyId === null
116
+ ? {
117
+ keySource: "workers-ai",
118
+ model: {
119
+ providerId: "cloudflare-workers-ai",
120
+ modelId: "@cf/moonshotai/kimi-k2.6",
121
+ },
122
+ }
123
+ : {
124
+ keySource: "byok",
125
+ keyId: draft.keyId,
126
+ model: { providerId: draft.provider, modelId: draft.modelId },
127
+ })), "The model could not be saved");
128
+ },
129
+ };
67
130
  /** Owner-direct Keys custody; a plaintext secret comes back only once, on issue. */
68
131
  function createOysterKeysPort(oysterKeysWire) {
69
132
  const oysterKeysView = z.strictObject({
@@ -83,13 +146,26 @@ function createOysterKeysPort(oysterKeysWire) {
83
146
  name: app.displayName,
84
147
  }));
85
148
  return Promise.resolve([
86
- { capability: "apps.read", label: "Read Apps", targets },
149
+ {
150
+ capability: "apps.read",
151
+ label: "Read Apps",
152
+ icon: "read",
153
+ hint: "See Apps and their data",
154
+ targets,
155
+ },
87
156
  {
88
157
  capability: "apps.use",
89
158
  label: "Use Apps and run Workflows",
159
+ icon: "allApps",
160
+ hint: "Act through Apps",
90
161
  targets,
91
162
  },
92
- { capability: "computer.use", label: "Use the Computer" },
163
+ {
164
+ capability: "computer.use",
165
+ label: "Use the Computer",
166
+ icon: "computer",
167
+ hint: "Files and commands",
168
+ },
93
169
  ]);
94
170
  },
95
171
  list: async () => oysterKeysView.parse(await json("/api/keys")),
@@ -194,6 +270,7 @@ export const mountPlatformControls = (root, input) => {
194
270
  agentMcpServers,
195
271
  computers,
196
272
  keys,
273
+ modelKeys,
197
274
  requestAppAccess,
198
275
  appPermissions: OysterAppPermissions,
199
276
  } }) }));