agentful 0.4.45 → 0.4.46

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 (3) hide show
  1. package/README.md +34 -6
  2. package/dist/index.cjs +376 -65
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -36,6 +36,7 @@ agentful open # open the preview
36
36
  | `licenses` | Licences of the software shipped with this CLI |
37
37
  | `-s, --session <id>` | Resume a previous coding session without changing its model |
38
38
  | `-m, --model <provider/model> [--variant <name>]` | Pin an exact engine model and optional provider-specific variant (`agentful` and `agentful tui`) |
39
+ | `--folder-settings` | Ask again whether to load engine settings this folder brings along (`agentful` and `agentful tui`) |
39
40
 
40
41
  Inside the interface, `/` lists the Agentful commands (`/setup`, `/push`,
41
42
  `/preview`, `/publish`, `/share`, `/status`) alongside the built-in ones.
@@ -198,11 +199,36 @@ suspends the silence timer.
198
199
  - recovery requires an explicit `y` and only reopens the same session. It does
199
200
  not continue automatically, so completed tool calls are not replayed by the CLI.
200
201
 
201
- Local providers are governed by the organization's BYOK policy (`/api/org/me`):
202
- `disabled` blocks them, `provider_allowlist` permits only the listed provider ids,
203
- `allow` (and private accounts without an org) permits any. The check is done by
204
- the CLI, so it is a cooperative control, not a cryptographic one — the config
205
- lives on the user's machine.
202
+ ## Provider rules in organizations
203
+
204
+ For an organization's work the same rule covers local providers, direct TUI
205
+ connections and the engine's built-in providers (`/api/org/me`, `src/lib/orgPolicy.ts`):
206
+
207
+ | Organization setting | Available besides Agentful models |
208
+ | --- | --- |
209
+ | BYOK `disabled` | nothing |
210
+ | BYOK `provider_allowlist` | the listed provider ids |
211
+ | BYOK `allow`, data region Germany or EU | local providers on this machine (`localhost`, `127.0.0.1`, `::1`) |
212
+ | BYOK `allow`, data region EU + USA | everything |
213
+ | rules not readable | nothing |
214
+
215
+ A linked project in the member's private area and accounts without an
216
+ organization are not limited; without a linked project a member works for the
217
+ organization. Connections are hidden, not deleted. `agentful models` and the TUI
218
+ start name what is switched off, why, and where to ask. The check is done by the
219
+ CLI, so it is a cooperative control, not a cryptographic one — the config lives
220
+ on the user's machine.
221
+
222
+ ## Engine settings in a folder
223
+
224
+ `opencode.json`, `tui.json` and `.opencode/` in a folder (or above it) can
225
+ redirect model requests and run code when the engine starts. The CLI therefore
226
+ starts the engine with folder settings off, pins the gateway address, and asks
227
+ once per folder and state of those files whether to load them (default: no). For
228
+ an organization's work they are never loaded. `agentful tui --folder-settings`
229
+ asks again. `AGENTS.md`, `CLAUDE.md` and `CONTEXT.md` are read either way. The
230
+ answers are kept in `~/.config/agentful/trusted-folders.json`
231
+ (`src/lib/engineGuard.ts`).
206
232
 
207
233
  ## Personal data check
208
234
 
@@ -223,7 +249,9 @@ fail-open); if it cannot be installed at all, the TUI says so in a toast. Not
223
249
  covered: attachments, shell mode, IDE editor context, free-text answers to the
224
250
  agent's questions. Like the BYOK lock it is a cooperative control on the
225
251
  user's machine. On every engine bump run `npm run check-pii` (real TUI against
226
- a stub model, no login, no credits) next to `npm run check-engine`.
252
+ a stub model, no login, no credits) next to `npm run check-engine` and
253
+ `npm run check-guard` (folder settings and provider rules, real engine and real
254
+ CLI against stubs).
227
255
 
228
256
  ## Known limitation: the engine's exit banner
229
257
 
package/dist/index.cjs CHANGED
@@ -3044,7 +3044,7 @@ var VERSION, brand, useColor, wrap, paint, tuiDesign, sym, ui;
3044
3044
  var init_branding = __esm({
3045
3045
  "src/branding.ts"() {
3046
3046
  "use strict";
3047
- VERSION = "0.4.45" ? "0.4.45" : null.version;
3047
+ VERSION = "0.4.46" ? "0.4.46" : null.version;
3048
3048
  brand = {
3049
3049
  name: "agentful",
3050
3050
  // the command users type
@@ -4303,7 +4303,7 @@ var DEFAULT_RETRY = {
4303
4303
  function isRetryableStatus(status) {
4304
4304
  return RETRYABLE_STATUSES.has(status);
4305
4305
  }
4306
- var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
4306
+ var sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
4307
4307
  async function request(url, opts = {}) {
4308
4308
  const attempts = Math.max(1, opts.retry?.attempts ?? (opts.retry ? DEFAULT_RETRY.attempts : 1));
4309
4309
  const delayMs = opts.retry?.delayMs ?? DEFAULT_RETRY.delayMs;
@@ -9409,7 +9409,7 @@ async function openCommand() {
9409
9409
  // src/commands/tui.ts
9410
9410
  var import_node_child_process6 = require("child_process");
9411
9411
  var import_promises4 = require("readline/promises");
9412
- var import_node_path22 = require("path");
9412
+ var import_node_path23 = require("path");
9413
9413
 
9414
9414
  // src/lib/binWrapper.ts
9415
9415
  var import_node_fs13 = require("fs");
@@ -9836,7 +9836,18 @@ var LEVELS = ["org", "department", "person"];
9836
9836
  function asLevel(value) {
9837
9837
  return LEVELS.includes(value) ? value : void 0;
9838
9838
  }
9839
- async function fetchLocalProviderPolicy(auth) {
9839
+ async function isPrivateProject(auth, projectId) {
9840
+ try {
9841
+ const res = await request(
9842
+ `${PB_URL}/api/llm/available-models?project=${encodeURIComponent(projectId)}`,
9843
+ { token: auth.pb_token, timeoutMs: 1e4 }
9844
+ );
9845
+ return res?.org_policy?.has_org === false;
9846
+ } catch {
9847
+ return false;
9848
+ }
9849
+ }
9850
+ async function fetchLocalProviderPolicy(auth, projectId) {
9840
9851
  try {
9841
9852
  const me = await request(`${PB_URL}/api/org/me`, { token: auth.pb_token, timeoutMs: 1e4 });
9842
9853
  if (!me?.has_org) return { hasOrg: false, allowedProviders: [] };
@@ -9845,6 +9856,9 @@ async function fetchLocalProviderPolicy(auth) {
9845
9856
  const modelLevels = Array.isArray(sources.allowed_models) ? LEVELS.filter((l) => sources.allowed_models.includes(l)) : [];
9846
9857
  return {
9847
9858
  hasOrg: true,
9859
+ privateProject: projectId ? await isPrivateProject(auth, projectId) : false,
9860
+ regionCap: typeof policy.region_cap === "string" ? policy.region_cap : void 0,
9861
+ regionLevel: asLevel(sources.region_cap),
9848
9862
  byokMode: policy.byok_mode || "allow",
9849
9863
  allowedProviders: Array.isArray(policy.allowed_byok_providers) ? policy.allowed_byok_providers : [],
9850
9864
  // /api/org/me reports the org as `org.id`; effective_policy carries no
@@ -9856,7 +9870,7 @@ async function fetchLocalProviderPolicy(auth) {
9856
9870
  byokLevel: asLevel(sources.byok_mode)
9857
9871
  };
9858
9872
  } catch {
9859
- return { hasOrg: true, byokMode: "disabled", allowedProviders: [] };
9873
+ return { hasOrg: true, unreadable: true, byokMode: "disabled", allowedProviders: [] };
9860
9874
  }
9861
9875
  }
9862
9876
  function levelName(policy, level) {
@@ -9869,24 +9883,54 @@ function levelName(policy, level) {
9869
9883
  function capitalize(text) {
9870
9884
  return text.charAt(0).toUpperCase() + text.slice(1);
9871
9885
  }
9872
- function decideLocalProviders(policy) {
9873
- if (!policy.hasOrg) return { allowed: true, allowlist: [] };
9886
+ function isOrganizationWork(policy) {
9887
+ return policy.hasOrg && !policy.privateProject;
9888
+ }
9889
+ var REGION_NAME = { de: "Germany", eu: "EU" };
9890
+ function decideProviders(policy) {
9891
+ const any = { limited: false, allowlist: [], allowLoopback: true };
9892
+ if (!isOrganizationWork(policy)) return any;
9893
+ if (policy.unreadable) {
9894
+ return {
9895
+ limited: true,
9896
+ allowlist: [],
9897
+ allowLoopback: false,
9898
+ reason: "Your organization's rules could not be read, so only Agentful models are available."
9899
+ };
9900
+ }
9874
9901
  const who = capitalize(levelName(policy, policy.byokLevel));
9875
9902
  if (policy.byokMode === "disabled") {
9876
9903
  return {
9877
- allowed: false,
9904
+ limited: true,
9878
9905
  allowlist: [],
9879
- reason: `${who} has disabled bring-your-own-key, which includes local providers.`
9906
+ allowLoopback: false,
9907
+ reason: `${who} has disabled bring-your-own-key, which includes local providers and direct connections.`
9880
9908
  };
9881
9909
  }
9882
9910
  if (policy.byokMode === "provider_allowlist") {
9883
9911
  return {
9884
- allowed: true,
9912
+ limited: true,
9885
9913
  allowlist: policy.allowedProviders,
9914
+ allowLoopback: false,
9886
9915
  reason: `${who} allows only these providers: ${policy.allowedProviders.join(", ") || "(none)"}`
9887
9916
  };
9888
9917
  }
9889
- return { allowed: true, allowlist: [] };
9918
+ if (policy.regionCap === "us_eu") return any;
9919
+ const region = REGION_NAME[policy.regionCap ?? ""];
9920
+ return {
9921
+ limited: true,
9922
+ allowlist: [],
9923
+ allowLoopback: true,
9924
+ reason: `${capitalize(levelName(policy, policy.regionLevel))} has set the data region${region ? ` ${region}` : ""}: only Agentful models and models on this machine are available.`
9925
+ };
9926
+ }
9927
+ function enabledProviders(decision, localProviderIds) {
9928
+ if (!decision.limited) return void 0;
9929
+ return Array.from(/* @__PURE__ */ new Set(["agentful", ...decision.allowlist, ...localProviderIds]));
9930
+ }
9931
+ function blockedConnections(decision, connected, localProviderIds) {
9932
+ const enabled2 = enabledProviders(decision, localProviderIds);
9933
+ return enabled2 ? connected.filter((id) => !enabled2.includes(id)) : [];
9890
9934
  }
9891
9935
  function policyRequestHint(policy) {
9892
9936
  if (!policy.hasOrg) return void 0;
@@ -9924,21 +9968,31 @@ function readLocalProviders() {
9924
9968
  }
9925
9969
  return {};
9926
9970
  }
9971
+ function isLoopbackProvider(config) {
9972
+ const baseURL = config.options?.baseURL;
9973
+ if (typeof baseURL !== "string") return false;
9974
+ let host;
9975
+ try {
9976
+ host = new URL(baseURL).hostname.toLowerCase();
9977
+ } catch {
9978
+ return false;
9979
+ }
9980
+ const loopback = host === "localhost" || host === "[::1]" || /^127(\.\d{1,3}){3}$/.test(host);
9981
+ if (!loopback) return false;
9982
+ const models = Object.values(config.models ?? {});
9983
+ return models.every((m) => !(m && typeof m === "object" && "provider" in m));
9984
+ }
9927
9985
  function resolveLocalProviders(policy) {
9928
9986
  const configured = readLocalProviders();
9929
9987
  const ids = Object.keys(configured);
9930
9988
  if (!ids.length) return { providers: {}, blocked: [] };
9931
- const decision = decideLocalProviders(policy);
9932
- if (!decision.allowed) {
9933
- return { providers: {}, blocked: ids, policyReason: decision.reason };
9934
- }
9935
- if (!decision.allowlist.length) {
9936
- return { providers: configured, blocked: [] };
9937
- }
9989
+ const decision = decideProviders(policy);
9990
+ if (!decision.limited) return { providers: configured, blocked: [] };
9938
9991
  const providers = {};
9939
9992
  const blocked = [];
9940
9993
  for (const id of ids) {
9941
- if (decision.allowlist.includes(id)) providers[id] = configured[id];
9994
+ const permitted = decision.allowlist.includes(id) || decision.allowLoopback && isLoopbackProvider(configured[id]);
9995
+ if (permitted) providers[id] = configured[id];
9942
9996
  else blocked.push(id);
9943
9997
  }
9944
9998
  return { providers, blocked, policyReason: blocked.length ? decision.reason : void 0 };
@@ -10166,10 +10220,11 @@ function parseEngineModelsOutput(output) {
10166
10220
  function modelProvider(model) {
10167
10221
  return model.slice(0, model.indexOf("/"));
10168
10222
  }
10169
- async function listEngineModels(binPath, xdg, provider) {
10223
+ async function listEngineModels(binPath, xdg, provider, guardEnv) {
10170
10224
  const { stdout } = await execFileAsync(binPath, ["models", provider], {
10171
10225
  env: {
10172
10226
  ...process.env,
10227
+ ...guardEnv,
10173
10228
  XDG_CONFIG_HOME: xdg.configHome,
10174
10229
  XDG_DATA_HOME: xdg.dataHome,
10175
10230
  XDG_STATE_HOME: xdg.stateHome,
@@ -10181,10 +10236,11 @@ async function listEngineModels(binPath, xdg, provider) {
10181
10236
  });
10182
10237
  return parseEngineModelsOutput(stdout);
10183
10238
  }
10184
- async function refreshEngineModelCache(binPath, xdg) {
10239
+ async function refreshEngineModelCache(binPath, xdg, guardEnv) {
10185
10240
  await execFileAsync(binPath, ["models", "--refresh"], {
10186
10241
  env: {
10187
10242
  ...process.env,
10243
+ ...guardEnv,
10188
10244
  XDG_CONFIG_HOME: xdg.configHome,
10189
10245
  XDG_DATA_HOME: xdg.dataHome,
10190
10246
  XDG_STATE_HOME: xdg.stateHome,
@@ -10195,9 +10251,9 @@ async function refreshEngineModelCache(binPath, xdg) {
10195
10251
  timeout: 6e4
10196
10252
  });
10197
10253
  }
10198
- async function assertEngineModelAvailable(binPath, xdg, model, listModels = listEngineModels) {
10254
+ async function assertEngineModelAvailable(binPath, xdg, model, guardEnv, listModels = listEngineModels) {
10199
10255
  const provider = modelProvider(model);
10200
- const models = await listModels(binPath, xdg, provider);
10256
+ const models = await listModels(binPath, xdg, provider, guardEnv);
10201
10257
  if (!models.includes(model)) {
10202
10258
  const examples = models.slice(0, 5);
10203
10259
  const hint = examples.length ? ` Available for ${provider}: ${examples.join(", ")}.` : "";
@@ -10237,8 +10293,183 @@ function describeModelRoute(model, catalog, localProviders, connectedProviders)
10237
10293
  return "external engine route \u2014 provider setup and terms apply; no Agentful credits or region guarantee";
10238
10294
  }
10239
10295
 
10240
- // src/lib/engineEvents.ts
10296
+ // src/lib/engineGuard.ts
10241
10297
  var import_node_crypto4 = require("crypto");
10298
+ var import_node_fs20 = require("fs");
10299
+ var import_node_os6 = require("os");
10300
+ var import_node_path22 = require("path");
10301
+ var TRUSTED_FOLDERS_FILE = "trusted-folders.json";
10302
+ var CONFIG_NAMES = ["opencode.json", "opencode.jsonc"];
10303
+ var TUI_NAMES = ["tui.json", "tui.jsonc"];
10304
+ var ENGINE_DIRS = [
10305
+ "agent",
10306
+ "agents",
10307
+ "command",
10308
+ "commands",
10309
+ "mode",
10310
+ "modes",
10311
+ "plugin",
10312
+ "plugins",
10313
+ "skill",
10314
+ "skills",
10315
+ "theme",
10316
+ "themes",
10317
+ "tool",
10318
+ "tools"
10319
+ ];
10320
+ var MAX_FILES = 400;
10321
+ var MAX_DEPTH = 6;
10322
+ var INSTRUCTION_NAMES = ["AGENTS.md", "CLAUDE.md", "CONTEXT.md"];
10323
+ function ancestors(start, stop) {
10324
+ const out = [];
10325
+ let dir = start;
10326
+ for (; ; ) {
10327
+ out.push(dir);
10328
+ if (dir === stop) break;
10329
+ const parent = (0, import_node_path22.dirname)(dir);
10330
+ if (parent === dir) break;
10331
+ dir = parent;
10332
+ }
10333
+ return out;
10334
+ }
10335
+ function realFolder(cwd) {
10336
+ try {
10337
+ return (0, import_node_fs20.realpathSync)(cwd);
10338
+ } catch {
10339
+ return (0, import_node_path22.resolve)(cwd);
10340
+ }
10341
+ }
10342
+ function worktreeOf(dir) {
10343
+ return ancestors(dir).find((d) => (0, import_node_fs20.existsSync)((0, import_node_path22.join)(d, ".git")));
10344
+ }
10345
+ function isFile(path) {
10346
+ try {
10347
+ return (0, import_node_fs20.statSync)(path).isFile();
10348
+ } catch {
10349
+ return false;
10350
+ }
10351
+ }
10352
+ function isDirectory(path) {
10353
+ try {
10354
+ return (0, import_node_fs20.statSync)(path).isDirectory();
10355
+ } catch {
10356
+ return false;
10357
+ }
10358
+ }
10359
+ function filesBelow(dir, depth, out) {
10360
+ if (depth > MAX_DEPTH || out.length >= MAX_FILES) return;
10361
+ let names;
10362
+ try {
10363
+ names = (0, import_node_fs20.readdirSync)(dir).sort();
10364
+ } catch {
10365
+ return;
10366
+ }
10367
+ for (const name2 of names) {
10368
+ if (name2 === "node_modules" || name2 === ".git") continue;
10369
+ const path = (0, import_node_path22.join)(dir, name2);
10370
+ if (isDirectory(path)) filesBelow(path, depth + 1, out);
10371
+ else if (out.length < MAX_FILES) out.push(path);
10372
+ }
10373
+ }
10374
+ function findFolderSettings(cwd = process.cwd(), home = (0, import_node_os6.homedir)()) {
10375
+ const start = realFolder(cwd);
10376
+ const homeDir = realFolder(home);
10377
+ const stop = worktreeOf(start);
10378
+ const configDirs = new Set(ancestors(start, stop));
10379
+ const files = [];
10380
+ for (const dir of ancestors(start)) {
10381
+ if (configDirs.has(dir)) files.push(...CONFIG_NAMES.map((n) => (0, import_node_path22.join)(dir, n)).filter(isFile));
10382
+ files.push(...TUI_NAMES.map((n) => (0, import_node_path22.join)(dir, n)).filter(isFile));
10383
+ const dot = (0, import_node_path22.join)(dir, ".opencode");
10384
+ if (dir === homeDir || !isDirectory(dot)) continue;
10385
+ files.push(...[...CONFIG_NAMES, ...TUI_NAMES].map((n) => (0, import_node_path22.join)(dot, n)).filter(isFile));
10386
+ for (const name2 of ENGINE_DIRS) {
10387
+ const sub = (0, import_node_path22.join)(dot, name2);
10388
+ if (isDirectory(sub)) filesBelow(sub, 1, files);
10389
+ }
10390
+ }
10391
+ if (!files.length) return { files, fingerprint: "" };
10392
+ const hash = (0, import_node_crypto4.createHash)("sha256");
10393
+ for (const path of files) {
10394
+ hash.update(path).update("\0");
10395
+ try {
10396
+ hash.update((0, import_node_crypto4.createHash)("sha256").update((0, import_node_fs20.readFileSync)(path)).digest());
10397
+ } catch {
10398
+ hash.update("unreadable");
10399
+ }
10400
+ }
10401
+ if (files.length >= MAX_FILES) hash.update((0, import_node_crypto4.randomUUID)());
10402
+ return { files, fingerprint: hash.digest("hex") };
10403
+ }
10404
+ function findProjectInstructions(cwd = process.cwd()) {
10405
+ const start = realFolder(cwd);
10406
+ const dirs = ancestors(start, worktreeOf(start));
10407
+ for (const name2 of INSTRUCTION_NAMES) {
10408
+ const found = dirs.map((dir) => (0, import_node_path22.join)(dir, name2)).filter(isFile);
10409
+ if (found.length) return found;
10410
+ }
10411
+ return [];
10412
+ }
10413
+ function describeFolderFiles(files, cwd = process.cwd(), max = 6) {
10414
+ const start = realFolder(cwd);
10415
+ const shown = files.slice(0, max).map((path) => {
10416
+ const rel = (0, import_node_path22.relative)(start, path);
10417
+ return (rel.startsWith("..") ? path : rel).replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
10418
+ });
10419
+ if (files.length > max) shown.push(`\u2026 and ${files.length - max} more`);
10420
+ return shown;
10421
+ }
10422
+ function trustPath() {
10423
+ return (0, import_node_path22.join)(configDir(), TRUSTED_FOLDERS_FILE);
10424
+ }
10425
+ function readTrust() {
10426
+ try {
10427
+ const parsed = JSON.parse((0, import_node_fs20.readFileSync)(trustPath(), "utf8"));
10428
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
10429
+ } catch {
10430
+ return {};
10431
+ }
10432
+ }
10433
+ function rememberedFolderAnswer(settings, cwd = process.cwd()) {
10434
+ const store = readTrust();
10435
+ const key = realFolder(cwd);
10436
+ const entry = Object.hasOwn(store, key) ? store[key] : void 0;
10437
+ return entry && entry.fingerprint === settings.fingerprint && typeof entry.load === "boolean" ? entry.load : void 0;
10438
+ }
10439
+ function rememberFolderAnswer(settings, load, cwd = process.cwd()) {
10440
+ const store = readTrust();
10441
+ store[realFolder(cwd)] = { fingerprint: settings.fingerprint, load, answered_at: (/* @__PURE__ */ new Date()).toISOString() };
10442
+ (0, import_node_fs20.mkdirSync)(configDir(), { recursive: true });
10443
+ (0, import_node_fs20.writeFileSync)(trustPath(), JSON.stringify(store, null, 2) + "\n", { mode: 384 });
10444
+ try {
10445
+ (0, import_node_fs20.chmodSync)(trustPath(), 384);
10446
+ } catch {
10447
+ }
10448
+ }
10449
+ function decideFolderSettings(input) {
10450
+ if (!input.settings.files.length) return { kind: "nothing" };
10451
+ if (input.organizationWork) return { kind: "skip", reason: "organization" };
10452
+ if (input.remembered !== void 0 && !(input.askAgain && input.interactive)) {
10453
+ return input.remembered ? { kind: "load" } : { kind: "skip", reason: "declined" };
10454
+ }
10455
+ return input.interactive ? { kind: "ask" } : { kind: "skip", reason: "non_interactive" };
10456
+ }
10457
+ function engineGuardEnv(opts) {
10458
+ const instructions = opts.loadFolderSettings ? [] : findProjectInstructions(opts.cwd);
10459
+ const inline = {
10460
+ provider: { agentful: { options: { baseURL: opts.gatewayUrl } } },
10461
+ ...opts.enabledProviders ? { enabled_providers: opts.enabledProviders } : {},
10462
+ ...instructions.length ? { instructions } : {}
10463
+ };
10464
+ return {
10465
+ OPENCODE_CONFIG_CONTENT: JSON.stringify(inline),
10466
+ // Always explicit: a CLI started from inside a TUI inherits the outer value.
10467
+ OPENCODE_DISABLE_PROJECT_CONFIG: opts.loadFolderSettings ? "false" : "true"
10468
+ };
10469
+ }
10470
+
10471
+ // src/lib/engineEvents.ts
10472
+ var import_node_crypto5 = require("crypto");
10242
10473
  var import_node_net = require("net");
10243
10474
  function payloadOf(event) {
10244
10475
  return event.payload && typeof event.payload === "object" ? event.payload : event;
@@ -10364,17 +10595,17 @@ var EngineLivenessPolicy = class {
10364
10595
  function engineServerCredentials(env = process.env) {
10365
10596
  return {
10366
10597
  username: env.OPENCODE_SERVER_USERNAME || void 0,
10367
- password: env.OPENCODE_SERVER_PASSWORD || (0, import_node_crypto4.randomUUID)()
10598
+ password: env.OPENCODE_SERVER_PASSWORD || (0, import_node_crypto5.randomUUID)()
10368
10599
  };
10369
10600
  }
10370
10601
  async function reserveLoopbackPort() {
10371
- return new Promise((resolve2, reject) => {
10602
+ return new Promise((resolve3, reject) => {
10372
10603
  const server = (0, import_node_net.createServer)();
10373
10604
  server.once("error", reject);
10374
10605
  server.listen(0, "127.0.0.1", () => {
10375
10606
  const address = server.address();
10376
10607
  const port = address && typeof address === "object" ? address.port : 0;
10377
- server.close((error) => error ? reject(error) : resolve2(port));
10608
+ server.close((error) => error ? reject(error) : resolve3(port));
10378
10609
  });
10379
10610
  });
10380
10611
  }
@@ -10410,11 +10641,11 @@ async function consumeSseStream(body, onEvent) {
10410
10641
  }
10411
10642
  async function delay(ms, signal) {
10412
10643
  if (signal.aborted) return;
10413
- await new Promise((resolve2) => {
10414
- const timer = setTimeout(resolve2, ms);
10644
+ await new Promise((resolve3) => {
10645
+ const timer = setTimeout(resolve3, ms);
10415
10646
  signal.addEventListener("abort", () => {
10416
10647
  clearTimeout(timer);
10417
- resolve2();
10648
+ resolve3();
10418
10649
  }, { once: true });
10419
10650
  });
10420
10651
  }
@@ -10495,6 +10726,43 @@ function startEngineEventMonitor(opts) {
10495
10726
  }
10496
10727
 
10497
10728
  // src/commands/tui.ts
10729
+ async function resolveFolderSettings(organizationWork, askAgain) {
10730
+ const settings = findFolderSettings();
10731
+ const decision = decideFolderSettings({
10732
+ settings,
10733
+ organizationWork,
10734
+ remembered: rememberedFolderAnswer(settings),
10735
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
10736
+ askAgain
10737
+ });
10738
+ if (decision.kind === "nothing") return false;
10739
+ const list = describeFolderFiles(settings.files);
10740
+ if (decision.kind === "load") {
10741
+ ui.info(paint.dim(`Engine settings from this folder are loaded (${list.join(", ")}). Change: agentful tui --folder-settings`));
10742
+ return true;
10743
+ }
10744
+ if (decision.kind === "skip") {
10745
+ const why = {
10746
+ organization: "not used for your organization's work",
10747
+ declined: "your choice; to change it: agentful tui --folder-settings",
10748
+ non_interactive: "there is no terminal to ask in"
10749
+ }[decision.reason];
10750
+ ui.info(`Engine settings in this folder are not loaded (${list.join(", ")}): ${why}.`);
10751
+ return false;
10752
+ }
10753
+ ui.warn("This folder brings its own engine settings:");
10754
+ for (const line of list) console.log(` ${line}`);
10755
+ ui.info("They can send your prompts and your session to another address and run code on this machine.");
10756
+ const rl = (0, import_promises4.createInterface)({ input: process.stdin, output: process.stdout });
10757
+ try {
10758
+ const answer = await rl.question("Load them? Only if you trust where this folder comes from. [y/N] ");
10759
+ const load = /^y(es)?$/i.test(answer.trim());
10760
+ rememberFolderAnswer(settings, load);
10761
+ return load;
10762
+ } finally {
10763
+ rl.close();
10764
+ }
10765
+ }
10498
10766
  async function confirmSameSessionRecovery(sessionID) {
10499
10767
  if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
10500
10768
  const rl = (0, import_promises4.createInterface)({ input: process.stdin, output: process.stdout });
@@ -10518,10 +10786,18 @@ async function tuiCommand(opts = {}) {
10518
10786
  ]);
10519
10787
  const [catalog, policy, backendState] = await Promise.all([
10520
10788
  fetchModelCatalog(auth, session),
10521
- fetchLocalProviderPolicy(auth),
10789
+ fetchLocalProviderPolicy(auth, project?.projectId),
10522
10790
  project ? fetchBackendSessionState(auth, project.userId, project.projectId) : Promise.resolve(void 0)
10523
10791
  ]);
10524
10792
  const local = resolveLocalProviders(policy);
10793
+ const providerDecision = decideProviders(policy);
10794
+ const allowedProviders = enabledProviders(providerDecision, Object.keys(local.providers));
10795
+ const loadFolderSettings = await resolveFolderSettings(isOrganizationWork(policy), Boolean(opts.folderSettings));
10796
+ const guardEnv = engineGuardEnv({
10797
+ gatewayUrl: session.gateway_url,
10798
+ loadFolderSettings,
10799
+ enabledProviders: allowedProviders
10800
+ });
10525
10801
  const framework = detectFramework(process.cwd());
10526
10802
  const skills = skillsInstructionFor(framework, process.cwd());
10527
10803
  const initialXdg = engineXdg();
@@ -10544,17 +10820,24 @@ async function tuiCommand(opts = {}) {
10544
10820
  initialPin?.model
10545
10821
  );
10546
10822
  const binDir = ensureCliOnPath();
10547
- const connectedProviders = readConnectedEngineProviders(xdg);
10823
+ const allConnections = readConnectedEngineProviders(xdg);
10824
+ const hiddenConnections = blockedConnections(providerDecision, allConnections, Object.keys(local.providers));
10825
+ const connectedProviders = allConnections.filter((id) => !hiddenConnections.includes(id));
10548
10826
  const validateAndApplyPin = async (pin) => {
10549
10827
  if (!pin) return;
10550
10828
  const provider = modelProvider(pin.model);
10829
+ if (allowedProviders && !allowedProviders.includes(provider)) {
10830
+ throw new Error(
10831
+ `${pin.model} is not available here. ${providerDecision.reason ?? ""} Choose another one with --model, for example agentful/` + catalog.defaultModel + "."
10832
+ );
10833
+ }
10551
10834
  const hasProvider = provider === "agentful" || provider === "opencode" || Object.hasOwn(local.providers, provider) || connectedProviders.includes(provider);
10552
10835
  if (!hasProvider) {
10553
10836
  throw new Error(
10554
10837
  `Provider ${provider} is not connected. Start without this pin, connect it in /models, then retry.`
10555
10838
  );
10556
10839
  }
10557
- await assertEngineModelAvailable(binPath, xdg, pin.model);
10840
+ await assertEngineModelAvailable(binPath, xdg, pin.model, guardEnv);
10558
10841
  if (pin.variant) writeEngineVariant(xdg, pin.model, pin.variant);
10559
10842
  };
10560
10843
  await validateAndApplyPin(initialPin);
@@ -10582,8 +10865,11 @@ async function tuiCommand(opts = {}) {
10582
10865
  if (local.blocked.length) {
10583
10866
  ui.warn(`Local provider(s) not loaded: ${local.blocked.join(", ")} \u2014 ${local.policyReason || "blocked by policy"}`);
10584
10867
  }
10868
+ if (hiddenConnections.length) {
10869
+ ui.warn(`Direct connection(s) switched off: ${hiddenConnections.join(", ")} \u2014 ${providerDecision.reason}`);
10870
+ }
10585
10871
  const modelNotice = modelLimitNotice(policy);
10586
- if (modelNotice || local.blocked.length) {
10872
+ if (modelNotice || local.blocked.length || hiddenConnections.length) {
10587
10873
  const hint = policyRequestHint(policy);
10588
10874
  if (modelNotice) ui.info(paint.dim(modelNotice));
10589
10875
  if (hint) ui.info(paint.dim(hint));
@@ -10634,7 +10920,7 @@ async function tuiCommand(opts = {}) {
10634
10920
  username: serverAuth.username,
10635
10921
  password: serverAuth.password
10636
10922
  });
10637
- code = await new Promise((resolve2) => {
10923
+ code = await new Promise((resolve3) => {
10638
10924
  const engineArgs = [
10639
10925
  "--hostname",
10640
10926
  "127.0.0.1",
@@ -10648,9 +10934,11 @@ async function tuiCommand(opts = {}) {
10648
10934
  cwd: process.cwd(),
10649
10935
  env: {
10650
10936
  ...process.env,
10937
+ // Provider list, pinned gateway address, folder settings (engineGuard).
10938
+ ...guardEnv,
10651
10939
  // Slash commands run `agentful …` through the agent's bash tool, which
10652
10940
  // has no access to the user's shell aliases.
10653
- PATH: `${binDir}${import_node_path22.delimiter}${process.env.PATH || ""}`,
10941
+ PATH: `${binDir}${import_node_path23.delimiter}${process.env.PATH || ""}`,
10654
10942
  XDG_CONFIG_HOME: xdg.configHome,
10655
10943
  XDG_DATA_HOME: xdg.dataHome,
10656
10944
  XDG_STATE_HOME: xdg.stateHome,
@@ -10668,10 +10956,10 @@ async function tuiCommand(opts = {}) {
10668
10956
  ...session.image_model ? { IMAGE_MODEL: session.image_model } : {}
10669
10957
  }
10670
10958
  });
10671
- child.on("exit", (childCode) => resolve2(childCode ?? 0));
10959
+ child.on("exit", (childCode) => resolve3(childCode ?? 0));
10672
10960
  child.on("error", (err2) => {
10673
10961
  ui.fail(`Could not start the engine: ${err2.message}`);
10674
- resolve2(1);
10962
+ resolve3(1);
10675
10963
  });
10676
10964
  });
10677
10965
  monitor.stop();
@@ -10875,38 +11163,38 @@ async function shareCommand(opts) {
10875
11163
  }
10876
11164
 
10877
11165
  // src/commands/pull.ts
10878
- var import_node_fs21 = require("fs");
10879
- var import_node_path24 = require("path");
11166
+ var import_node_fs22 = require("fs");
11167
+ var import_node_path25 = require("path");
10880
11168
  init_branding();
10881
11169
  init_branding();
10882
11170
 
10883
11171
  // src/lib/pullFiles.ts
10884
- var import_node_fs20 = require("fs");
10885
- var import_node_path23 = require("path");
11172
+ var import_node_fs21 = require("fs");
11173
+ var import_node_path24 = require("path");
10886
11174
  var INLINE_BASE64_EXTENSIONS = /\.(?:png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?|woff2?|ttf|otf|eot|pdf|docx?|xlsx?|pptx?|zip|tar|gz|7z|rar|bz2|mp[34]|m4a|wav|ogg|avi|mov|mkv|flac|webm|exe|dll|so|dylib|bin|wasm)$/i;
10887
11175
  function inlineContent(value) {
10888
11176
  return typeof value === "object" && value !== null && "content" in value ? String(value.content) : String(value ?? "");
10889
11177
  }
10890
11178
  function writePulledWorkspaceEntry(root, rel, value) {
10891
- const target = (0, import_node_path23.join)(root, rel);
10892
- (0, import_node_fs20.mkdirSync)((0, import_node_path23.dirname)(target), { recursive: true });
11179
+ const target = (0, import_node_path24.join)(root, rel);
11180
+ (0, import_node_fs21.mkdirSync)((0, import_node_path24.dirname)(target), { recursive: true });
10893
11181
  const content = inlineContent(value);
10894
11182
  if (INLINE_BASE64_EXTENSIONS.test(rel)) {
10895
- (0, import_node_fs20.writeFileSync)(target, Buffer.from(content, "base64"));
11183
+ (0, import_node_fs21.writeFileSync)(target, Buffer.from(content, "base64"));
10896
11184
  return;
10897
11185
  }
10898
- (0, import_node_fs20.writeFileSync)(target, content, "utf8");
11186
+ (0, import_node_fs21.writeFileSync)(target, content, "utf8");
10899
11187
  }
10900
11188
  function writePulledBackendDeclaration(root, declaration) {
10901
- const target = (0, import_node_path23.join)(root, ".agentful", "backend.json");
10902
- (0, import_node_fs20.mkdirSync)((0, import_node_path23.dirname)(target), { recursive: true });
11189
+ const target = (0, import_node_path24.join)(root, ".agentful", "backend.json");
11190
+ (0, import_node_fs21.mkdirSync)((0, import_node_path24.dirname)(target), { recursive: true });
10903
11191
  const {
10904
11192
  source: _source,
10905
11193
  received_at: _receivedAt,
10906
11194
  last_sync: _lastSync,
10907
11195
  ...portableDeclaration
10908
11196
  } = declaration;
10909
- (0, import_node_fs20.writeFileSync)(target, `${JSON.stringify(portableDeclaration, null, 2)}
11197
+ (0, import_node_fs21.writeFileSync)(target, `${JSON.stringify(portableDeclaration, null, 2)}
10910
11198
  `, "utf8");
10911
11199
  }
10912
11200
  function explainPullRefusal(err2) {
@@ -10923,7 +11211,7 @@ async function pullCommand(opts) {
10923
11211
  console.log(banner());
10924
11212
  const auth = await ensureAuth();
10925
11213
  const project = requireProject();
10926
- const nonHidden = (0, import_node_fs21.readdirSync)(process.cwd()).filter((n) => n !== ".agentful" && !n.startsWith("."));
11214
+ const nonHidden = (0, import_node_fs22.readdirSync)(process.cwd()).filter((n) => n !== ".agentful" && !n.startsWith("."));
10927
11215
  if (nonHidden.length > 0 && !opts.force) {
10928
11216
  throw new ApiError(
10929
11217
  0,
@@ -10952,9 +11240,9 @@ async function pullCommand(opts) {
10952
11240
  ui.warn(`Skipped ${rel} (HTTP ${resp.status})`);
10953
11241
  continue;
10954
11242
  }
10955
- const target = (0, import_node_path24.join)(process.cwd(), rel);
10956
- (0, import_node_fs21.mkdirSync)((0, import_node_path24.dirname)(target), { recursive: true });
10957
- (0, import_node_fs21.writeFileSync)(target, Buffer.from(await resp.arrayBuffer()));
11243
+ const target = (0, import_node_path25.join)(process.cwd(), rel);
11244
+ (0, import_node_fs22.mkdirSync)((0, import_node_path25.dirname)(target), { recursive: true });
11245
+ (0, import_node_fs22.writeFileSync)(target, Buffer.from(await resp.arrayBuffer()));
10958
11246
  written++;
10959
11247
  }
10960
11248
  } else if (data.files) {
@@ -11106,7 +11394,7 @@ async function modelsCommand(opts) {
11106
11394
  const session = await ensureGatewaySession(auth, project?.projectId);
11107
11395
  const [catalog, policy] = await Promise.all([
11108
11396
  fetchModelCatalog(auth, session),
11109
- fetchLocalProviderPolicy(auth)
11397
+ fetchLocalProviderPolicy(auth, project?.projectId)
11110
11398
  ]);
11111
11399
  console.log("");
11112
11400
  console.log(paint.bold("Your Agentful models") + paint.dim(" (credits, region and org rules apply)"));
@@ -11118,8 +11406,20 @@ async function modelsCommand(opts) {
11118
11406
  ui.info(modelNotice);
11119
11407
  ui.info(policyRequestHint(policy));
11120
11408
  }
11121
- const decision = decideLocalProviders(policy);
11409
+ const decision = decideProviders(policy);
11122
11410
  const resolved = resolveLocalProviders(policy);
11411
+ const localIds = Object.keys(resolved.providers);
11412
+ const folder = findFolderSettings();
11413
+ const guardEnv = engineGuardEnv({
11414
+ gatewayUrl: session.gateway_url,
11415
+ loadFolderSettings: decideFolderSettings({
11416
+ settings: folder,
11417
+ organizationWork: isOrganizationWork(policy),
11418
+ remembered: rememberedFolderAnswer(folder),
11419
+ interactive: false
11420
+ }).kind === "load",
11421
+ enabledProviders: enabledProviders(decision, localIds)
11422
+ });
11123
11423
  const configured = Object.keys(readLocalProviders());
11124
11424
  if (catalog.byokNotice) {
11125
11425
  console.log("");
@@ -11139,7 +11439,7 @@ async function modelsCommand(opts) {
11139
11439
  const binPath = await ensureEngine();
11140
11440
  if (opts.refresh) {
11141
11441
  try {
11142
- await refreshEngineModelCache(binPath, xdg);
11442
+ await refreshEngineModelCache(binPath, xdg, guardEnv);
11143
11443
  ui.step("Refreshed the engine model cache from models.dev.");
11144
11444
  } catch {
11145
11445
  ui.warn("Engine model cache could not be refreshed \u2014 listing the cached catalog.");
@@ -11147,9 +11447,14 @@ async function modelsCommand(opts) {
11147
11447
  }
11148
11448
  console.log("");
11149
11449
  console.log(paint.bold("Direct TUI connections") + paint.dim(" (provider billing/terms; outside Agentful credits and region controls)"));
11450
+ const switchedOff = blockedConnections(decision, connectedProviders, localIds);
11150
11451
  for (const provider of connectedProviders) {
11452
+ if (switchedOff.includes(provider)) {
11453
+ console.log(` ${paint.warn("\u2716")} ${provider} ${paint.dim("\u2014 switched off by your organization")}`);
11454
+ continue;
11455
+ }
11151
11456
  try {
11152
- const models = await listEngineModels(binPath, xdg, provider);
11457
+ const models = await listEngineModels(binPath, xdg, provider, guardEnv);
11153
11458
  if (!models.length) {
11154
11459
  console.log(` ${paint.warn("!")} ${provider} ${paint.dim("\u2014 connected, but no engine models found")}`);
11155
11460
  continue;
@@ -11159,6 +11464,11 @@ async function modelsCommand(opts) {
11159
11464
  console.log(` ${paint.warn("!")} ${provider} ${paint.dim("\u2014 catalog could not be read")}`);
11160
11465
  }
11161
11466
  }
11467
+ if (switchedOff.length) {
11468
+ if (decision.reason) ui.info(decision.reason);
11469
+ const hint = policyRequestHint(policy);
11470
+ if (hint) ui.info(hint);
11471
+ }
11162
11472
  } else if (opts.refresh) {
11163
11473
  console.log("");
11164
11474
  ui.info("No provider is connected directly in the TUI, so nothing is cached \u2014");
@@ -11166,7 +11476,8 @@ async function modelsCommand(opts) {
11166
11476
  }
11167
11477
  console.log("");
11168
11478
  console.log(paint.bold("Local providers") + paint.dim(" (your key, direct to the provider)"));
11169
- if (!decision.allowed) {
11479
+ const noneAllowed = decision.limited && !decision.allowlist.length && !decision.allowLoopback;
11480
+ if (noneAllowed) {
11170
11481
  ui.warn(decision.reason || "Local providers are not permitted for your account.");
11171
11482
  const hint = policyRequestHint(policy);
11172
11483
  if (hint) ui.info(hint);
@@ -11185,15 +11496,15 @@ async function modelsCommand(opts) {
11185
11496
  if (hint) ui.info(hint);
11186
11497
  }
11187
11498
  }
11188
- if (decision.allowed) {
11499
+ if (!noneAllowed) {
11189
11500
  if (opts.addLocal || !configured.length) {
11190
11501
  const path = writeLocalProvidersExample();
11191
11502
  console.log("");
11192
11503
  ui.step(`Edit ${paint.accent(path)} to add a provider with your own key.`);
11193
11504
  ui.info("Those requests go straight to the provider: no Agentful credits,");
11194
11505
  ui.info("no platform region guarantee, and no usage recorded on your account.");
11195
- if (decision.allowlist.length) {
11196
- ui.info(`Your organization permits: ${decision.allowlist.join(", ")}`);
11506
+ if (decision.limited) {
11507
+ ui.info(decision.reason ?? `Your organization permits: ${decision.allowlist.join(", ")}`);
11197
11508
  }
11198
11509
  } else {
11199
11510
  console.log("");
@@ -11245,8 +11556,8 @@ async function upgradeCommand() {
11245
11556
 
11246
11557
  // src/lib/commandOptions.ts
11247
11558
  function tuiOptionsFrom(command) {
11248
- const { session, model, variant } = command.optsWithGlobals();
11249
- return { session, model, variant };
11559
+ const { session, model, variant, folderSettings } = command.optsWithGlobals();
11560
+ return { session, model, variant, ...folderSettings ? { folderSettings } : {} };
11250
11561
  }
11251
11562
 
11252
11563
  // src/index.ts
@@ -11263,7 +11574,7 @@ var run = (fn) => async (...args) => {
11263
11574
  process.exitCode = 1;
11264
11575
  }
11265
11576
  };
11266
- program2.name("agentful").description("Agentful in your terminal \u2014 local development with push-to-cloud previews").version(VERSION).option("-s, --session <id>", "resume a previous session (same as `tui -s`)").option("-m, --model <provider/model>", "pin an exact model from the final engine catalog").option("--variant <name>", "pin the provider-specific model variant (for example high)").action(run((opts, cmd) => {
11577
+ program2.name("agentful").description("Agentful in your terminal \u2014 local development with push-to-cloud previews").version(VERSION).option("-s, --session <id>", "resume a previous session (same as `tui -s`)").option("-m, --model <provider/model>", "pin an exact model from the final engine catalog").option("--variant <name>", "pin the provider-specific model variant (for example high)").option("--folder-settings", "ask again whether to load engine settings this folder brings along").action(run((opts, cmd) => {
11267
11578
  const [unknown] = cmd.args;
11268
11579
  if (unknown) {
11269
11580
  throw new ApiError(
@@ -11282,7 +11593,7 @@ program2.command("push").description("Upload this project and get a live preview
11282
11593
  program2.command("build-status").description("Show the cloud's record of the last build (the real error on failures)").action(run(buildStatusCommand));
11283
11594
  program2.command("backend").description("Open this project's Backend tab (managed DB + server actions) in the browser").action(run(backendCommand));
11284
11595
  program2.command("open").description("Open the live preview in the browser").action(run(openCommand));
11285
- program2.command("tui").description("Start the Agentful coding TUI with your Agentful account").option("-s, --session <id>", "resume a previous session").option("-m, --model <provider/model>", "pin an exact model from the final engine catalog").option("--variant <name>", "pin the provider-specific model variant (for example high)").action(run((_opts, cmd) => tuiCommand(tuiOptionsFrom(cmd))));
11596
+ program2.command("tui").description("Start the Agentful coding TUI with your Agentful account").option("-s, --session <id>", "resume a previous session").option("-m, --model <provider/model>", "pin an exact model from the final engine catalog").option("--variant <name>", "pin the provider-specific model variant (for example high)").option("--folder-settings", "ask again whether to load engine settings this folder brings along").action(run((_opts, cmd) => tuiCommand(tuiOptionsFrom(cmd))));
11286
11597
  program2.command("publish <subdomain>").description("Publish the built project at https://<subdomain>.agentful.page").option("--json", "print the address and the security check as JSON (for scripts and agents)").action(run(publishCommand));
11287
11598
  program2.command("share").description("Make the live preview public (anyone with the link)").option("--private", "make the preview owner-only again").action(run((opts) => shareCommand(opts)));
11288
11599
  program2.command("pull").description("Download the cloud workspace into this directory").option("--force", "overwrite files in a non-empty directory").action(run((opts) => pullCommand(opts)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentful",
3
- "version": "0.4.45",
3
+ "version": "0.4.46",
4
4
  "description": "Agentful in your terminal — local development with push-to-cloud previews",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://agentful.dev",
@@ -26,6 +26,7 @@
26
26
  "typecheck": "tsc --noEmit",
27
27
  "check-engine": "node scripts/check-engine-contract.mjs",
28
28
  "check-pii": "node scripts/check-pii-guard.mjs",
29
+ "check-guard": "node scripts/check-engine-guard.mjs",
29
30
  "dev": "tsx src/index.ts",
30
31
  "sync-theme": "cp src/branding/agentful-theme.json ../frontend/public/cli/theme.json",
31
32
  "test": "node --import tsx --test src/lib/*.test.ts"