recess-cli 3.50.2 → 3.51.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.
package/dist/api.js CHANGED
@@ -24,6 +24,8 @@ export class RecessAdminApi {
24
24
  clientTag;
25
25
  client;
26
26
  villageSessionPromise;
27
+ /** Every request to the API origin: the injected transport when hosted. */
28
+ apiFetch;
27
29
  constructor(config, reason, clientTag = RECESS_CLIENT_CLI, clientOverride, fetchOverride) {
28
30
  this.config = config;
29
31
  this.reason = reason;
@@ -41,6 +43,8 @@ export class RecessAdminApi {
41
43
  const requestClientTag = this.clientTag;
42
44
  const liveConfig = this.config;
43
45
  const doFetch = fetchOverride ?? globalThis.fetch;
46
+ this.apiFetch =
47
+ fetchOverride ?? ((input, init) => globalThis.fetch(input, init));
44
48
  // Replayable copies for the one 401 retry below (the sent body is spent).
45
49
  const replays = new WeakMap();
46
50
  this.client.use({
@@ -80,7 +84,7 @@ export class RecessAdminApi {
80
84
  if (!path.startsWith("/") || path.startsWith("//")) {
81
85
  throw new CliError("invalid_arguments", "Raw request paths must start with one '/'.");
82
86
  }
83
- const response = await fetch(new URL(path, this.config.apiOrigin), {
87
+ const response = await this.apiFetch(new URL(path, this.config.apiOrigin), {
84
88
  headers: cliRequestHeaders({ cookie: this.config.sessionCookie }, this.reason, this.clientTag),
85
89
  });
86
90
  noteServerCliVersions(response.headers);
@@ -105,7 +109,7 @@ export class RecessAdminApi {
105
109
  : { "content-type": "application/json" }),
106
110
  }, this.reason, this.clientTag);
107
111
  applyIdempotencyHeaders(headers);
108
- const response = await fetch(new URL(path, this.config.apiOrigin), {
112
+ const response = await this.apiFetch(new URL(path, this.config.apiOrigin), {
109
113
  method: options.method ?? "GET",
110
114
  headers,
111
115
  ...(options.body === undefined
@@ -157,7 +161,7 @@ export class RecessAdminApi {
157
161
  form.set("file", new Blob([arrayBuffer], { type: "model/gltf-binary" }), fileName);
158
162
  const headers = cliRequestHeaders({ cookie: this.config.sessionCookie }, this.reason, this.clientTag);
159
163
  applyIdempotencyHeaders(headers);
160
- const response = await fetch(new URL(`/admin/village/models/upload?worldId=${encodeURIComponent(worldId)}`, this.config.apiOrigin), {
164
+ const response = await this.apiFetch(new URL(`/admin/village/models/upload?worldId=${encodeURIComponent(worldId)}`, this.config.apiOrigin), {
161
165
  method: "POST",
162
166
  headers,
163
167
  body: form,
@@ -181,7 +185,7 @@ export class RecessAdminApi {
181
185
  formData.append("file", new Blob([arrayBuffer], { type: mimeType }), fileName);
182
186
  const headers = cliRequestHeaders({ cookie: this.config.sessionCookie }, this.reason, this.clientTag);
183
187
  applyIdempotencyHeaders(headers);
184
- const response = await fetch(new URL("/admin/partner/logo-upload", this.config.apiOrigin), {
188
+ const response = await this.apiFetch(new URL("/admin/partner/logo-upload", this.config.apiOrigin), {
185
189
  method: "POST",
186
190
  headers,
187
191
  body: formData,
@@ -198,7 +202,7 @@ export class RecessAdminApi {
198
202
  formData.append("file", new Blob([arrayBuffer], { type: mimeType }), fileName);
199
203
  const headers = cliRequestHeaders({ cookie: this.config.sessionCookie }, this.reason, this.clientTag);
200
204
  applyIdempotencyHeaders(headers);
201
- const response = await fetch(new URL(`/admin/channels/${encodeURIComponent(channelId)}/image`, this.config.apiOrigin), {
205
+ const response = await this.apiFetch(new URL(`/admin/channels/${encodeURIComponent(channelId)}/image`, this.config.apiOrigin), {
202
206
  method: "POST",
203
207
  headers,
204
208
  body: formData,
@@ -216,7 +220,7 @@ export class RecessAdminApi {
216
220
  formData.append("file", new Blob([pdfBody.buffer], { type: "application/pdf" }), fileName);
217
221
  const headers = cliRequestHeaders({ cookie: this.config.sessionCookie }, this.reason, this.clientTag);
218
222
  applyIdempotencyHeaders(headers);
219
- const response = await fetch(new URL(`/tutor/students/${encodeURIComponent(studentId)}/map-test-scores/upload`, this.config.apiOrigin), {
223
+ const response = await this.apiFetch(new URL(`/tutor/students/${encodeURIComponent(studentId)}/map-test-scores/upload`, this.config.apiOrigin), {
220
224
  method: "POST",
221
225
  headers,
222
226
  body: formData,
@@ -247,7 +251,7 @@ export class RecessAdminApi {
247
251
  if (value !== undefined)
248
252
  url.searchParams.set(key, String(value));
249
253
  }
250
- const response = await fetch(url, {
254
+ const response = await this.apiFetch(url, {
251
255
  method: "POST",
252
256
  headers,
253
257
  body: formData,
@@ -270,7 +274,7 @@ export class RecessAdminApi {
270
274
  const url = new URL(`/admin/admissions/${encodeURIComponent(packetId)}/contract`, this.config.apiOrigin);
271
275
  if (optionId)
272
276
  url.searchParams.set("option", optionId);
273
- const response = await fetch(url, {
277
+ const response = await this.apiFetch(url, {
274
278
  headers: cliRequestHeaders({ cookie: this.config.sessionCookie }, this.reason, this.clientTag),
275
279
  });
276
280
  noteServerCliVersions(response.headers);
@@ -299,7 +303,7 @@ export class RecessAdminApi {
299
303
  formData.append("file", new Blob([pdfBody.buffer], { type: "application/pdf" }), fileName);
300
304
  const headers = cliRequestHeaders({ cookie: this.config.sessionCookie }, this.reason, this.clientTag);
301
305
  applyIdempotencyHeaders(headers);
302
- const response = await fetch(new URL(`/admin/admissions/${encodeURIComponent(packetId)}/signed-agreement`, this.config.apiOrigin), { method: "POST", headers, body: formData });
306
+ const response = await this.apiFetch(new URL(`/admin/admissions/${encodeURIComponent(packetId)}/signed-agreement`, this.config.apiOrigin), { method: "POST", headers, body: formData });
303
307
  const body = await readResponseBody(response);
304
308
  if (!response.ok)
305
309
  throw apiError(response.status, body);
package/dist/auth.js CHANGED
@@ -3,6 +3,7 @@ import { createServer } from "node:http";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { clearPendingDeviceAuth, updateStoredConfig } from "./config.js";
5
5
  import { apiError, CliError } from "./errors.js";
6
+ import { assertLocalMachine } from "./in-app.js";
6
7
  import { cliRequestHeaders } from "./http.js";
7
8
  /** Stored secrets stay in the 0600 config; never return them to stdout. */
8
9
  function publicSession(session) {
@@ -23,6 +24,7 @@ export function openBrowser(url) {
23
24
  ? "rundll32"
24
25
  : "xdg-open";
25
26
  const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
27
+ assertLocalMachine();
26
28
  const child = spawn(command, args, { detached: true, stdio: "ignore" });
27
29
  child.unref();
28
30
  }
@@ -32,6 +34,7 @@ export function waitForSsoCallback(port, expectedState) {
32
34
  server.close();
33
35
  reject(new CliError("auth_timeout", "Timed out waiting for Recess SSO."));
34
36
  }, 5 * 60 * 1000);
37
+ assertLocalMachine();
35
38
  const server = createServer((request, response) => {
36
39
  const url = new URL(request.url ?? "/", `http://127.0.0.1:${port}`);
37
40
  if (url.pathname !== "/callback") {
package/dist/cli.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { execFile } from "node:child_process";
3
- import fs from "node:fs/promises";
3
+ import { fs, inAppGit, inAppState, isInApp, runInApp, } from "./in-app.js";
4
4
  import path from "node:path";
5
5
  import { RecessAdminApi, unwrap, withIdempotencyContext } from "./api.js";
6
6
  import { flagList, flagNumber, flagString, hasFlag, parseArgs, } from "./args.js";
7
7
  import { login, pollDeviceAuth, requestDeviceAuth } from "./auth.js";
8
8
  import { clearStoredSession, withConfigLock, deleteProfile, listProfiles, resolveConfig, saveProfile, useProfile, } from "./config.js";
9
- import { agentContext, buildCommandSchema, findCommandSchema, remoteCommands, scopedHelp, validateInvocation, } from "./command-schema.js";
9
+ import { agentContext, buildCommandSchema, findCommandSchema, inAppCommands, remoteCommands, scopedHelp, validateInvocation, } from "./command-schema.js";
10
10
  import { runAdmissionsCommand } from "./commands/admissions.js";
11
11
  import { runApplicationsCommand } from "./commands/applications.js";
12
12
  import { runAppsCommand } from "./commands/apps.js";
@@ -464,6 +464,8 @@ const GOAL_QUEUE_MAX_ENTRIES = 500;
464
464
  const URL_QUEUE_DESCRIPTION_POINTER = "Skill queue managed by the system.";
465
465
  const RECESS_GIT_METADATA = "recess-workspace.json";
466
466
  async function runGit(cwd, args, options = {}) {
467
+ if (isInApp())
468
+ return inAppGit(cwd, args);
467
469
  return new Promise((resolve, reject) => {
468
470
  execFile("git", ["-C", cwd, ...args], {
469
471
  encoding: "utf8",
@@ -898,6 +900,10 @@ async function readTutorTemplateLessons(directory) {
898
900
  return lessons;
899
901
  }
900
902
  async function previewBoundWrite(parsed, preview, execute, persistOrOptions = false) {
903
+ // In the app chat the operation store is the approval ledger, not ~/.recess-cli.
904
+ const hostedWrite = inAppState()?.write;
905
+ if (hostedWrite)
906
+ return hostedWrite(parsed, preview, execute);
901
907
  const context = await requirePreviewBoundConfirmation(parsed, preview, persistOrOptions);
902
908
  try {
903
909
  const result = await withIdempotencyContext(context, execute);
@@ -2181,7 +2187,9 @@ function remoteWriteCommand(argv, structuredInput, store) {
2181
2187
  details: {
2182
2188
  ...preview.details,
2183
2189
  operationKey,
2184
- retry: "Confirm with the same command path plus --confirm --operation-key <operationKey>. The hosted service will execute the stored exact payload; do not retransmit structured input.",
2190
+ retry: isInApp()
2191
+ ? "After the person approves in a later message, rerun the identical command plus --confirm --operation-key <operationKey>."
2192
+ : "Confirm with the same command path plus --confirm --operation-key <operationKey>. The hosted service will execute the stored exact payload; do not retransmit structured input.",
2185
2193
  },
2186
2194
  });
2187
2195
  }
@@ -2238,6 +2246,12 @@ async function readAssignmentSelection(filePath) {
2238
2246
  },
2239
2247
  };
2240
2248
  }
2249
+ /** The only commands that take a JSON document in place of a local file. */
2250
+ const STRUCTURED_INPUT_COMMANDS = [
2251
+ "apps validate",
2252
+ "goal-templates validate-spec",
2253
+ "goal-templates create",
2254
+ ];
2241
2255
  /** Hosted goal-template authoring and skills are guide/admin only (see below). */
2242
2256
  const HOSTED_STAFF_NOUNS = new Set(["goal-templates", "skills"]);
2243
2257
  /**
@@ -2259,26 +2273,41 @@ export async function executeRecessCommand(argv, options = {}) {
2259
2273
  const [noun, verb] = parsed.positionals;
2260
2274
  const commands = buildCommandSchema(HELP);
2261
2275
  const isRemote = options.transport === "remote";
2262
- if (!isRemote && !options.operationStore) {
2276
+ const inApp = options.transport === "in-app";
2277
+ if (inApp && !isInApp()) {
2278
+ return runInApp(() => executeRecessCommand(argv, options), {
2279
+ files: options.files,
2280
+ store: options.fileStore,
2281
+ });
2282
+ }
2283
+ // No local machine: hosted MCP's small catalog, or the app chat's full one.
2284
+ const isHosted = isRemote || inApp;
2285
+ if (!isHosted && !options.operationStore) {
2263
2286
  localInvocations.set(parsed, { argv: [...argv] });
2264
2287
  }
2265
- if (isRemote &&
2266
- (!options.api || !options.config || !options.operationStore)) {
2288
+ if (isHosted &&
2289
+ (!options.api ||
2290
+ !options.config ||
2291
+ !options.operationStore ||
2292
+ (inApp && !options.discovery))) {
2267
2293
  throw new CliError("remote_context_required", "Hosted execution requires injected API, configuration, and operation-store adapters.");
2268
2294
  }
2269
- if (isRemote) {
2295
+ if (isHosted) {
2270
2296
  const forbiddenTransportFlag = ["deliver", "profile", "json"].find((name) => hasFlag(parsed, name));
2271
2297
  if (forbiddenTransportFlag) {
2272
- throw new CliError("remote_flag_unavailable", `--${forbiddenTransportFlag} is not available over hosted MCP.`);
2298
+ throw new CliError("remote_flag_unavailable", `--${forbiddenTransportFlag} is not available ${inApp ? "in the Recess app chat" : "over hosted MCP"}.`);
2273
2299
  }
2274
2300
  }
2275
2301
  const writeCommand = options.operationStore
2276
2302
  ? remoteWriteCommand(argv, options.structuredInput, options.operationStore)
2277
2303
  : localWriteCommand;
2304
+ const inAppRun = inAppState();
2305
+ if (inAppRun)
2306
+ inAppRun.write = writeCommand;
2278
2307
  // Before the help branch: `--version` parses as a FLAG, so `noun` is
2279
2308
  // undefined and `!noun` would return help instead. (Found by running it.)
2280
2309
  if (noun === "version" || (!noun && hasFlag(parsed, "version"))) {
2281
- if (isRemote) {
2310
+ if (isHosted) {
2282
2311
  throw new CliError("remote_command_unavailable", "The version command is not exposed by the hosted Recess CLI.");
2283
2312
  }
2284
2313
  const unknown = Array.from(parsed.flags.keys()).filter((name) => !["deliver", "json", "no-json", "pretty", "version"].includes(name));
@@ -2311,10 +2340,13 @@ export async function executeRecessCommand(argv, options = {}) {
2311
2340
  const discovery = options.discovery ?? resolveCommandDiscovery(config);
2312
2341
  const visibleCommands = isRemote
2313
2342
  ? hostedCommands(commands, discovery)
2314
- : commands;
2343
+ : inApp
2344
+ ? inAppCommands(commands, discovery)
2345
+ : commands;
2315
2346
  return {
2316
2347
  help: scopedHelp(HELP, visibleCommands, [], discovery, {
2317
2348
  remoteOnly: isRemote,
2349
+ inApp,
2318
2350
  all: hasFlag(parsed, "all"),
2319
2351
  }),
2320
2352
  };
@@ -2325,26 +2357,34 @@ export async function executeRecessCommand(argv, options = {}) {
2325
2357
  const discovery = options.discovery ?? resolveCommandDiscovery(config);
2326
2358
  const visibleCommands = isRemote
2327
2359
  ? hostedCommands(commands, discovery)
2328
- : commands;
2360
+ : inApp
2361
+ ? inAppCommands(commands, discovery)
2362
+ : commands;
2329
2363
  return {
2330
2364
  help: scopedHelp(HELP, visibleCommands, scope, discovery, {
2331
2365
  remoteOnly: isRemote,
2366
+ inApp,
2332
2367
  all: hasFlag(parsed, "all"),
2333
2368
  }),
2334
2369
  };
2335
2370
  }
2336
2371
  validateInvocation(parsed, commands, { remote: isRemote });
2372
+ if (inApp) {
2373
+ if (noun === "confirm") {
2374
+ throw new CliError("command_unavailable", "Confirm with the same command plus --confirm --operation-key <operationKey>.");
2375
+ }
2376
+ const command = findCommandSchema(commands, parsed.positionals);
2377
+ if (!command || inAppCommands([command], options.discovery).length === 0) {
2378
+ throw new CliError("command_unavailable", `\`${parsed.positionals.join(" ")}\` is not available in the Recess app chat for this account. Run \`help\` for the catalog.`);
2379
+ }
2380
+ }
2337
2381
  if (isRemote) {
2338
2382
  const command = findCommandSchema(commands, parsed.positionals);
2339
2383
  if (!command?.remoteCapable) {
2340
2384
  throw new CliError("remote_command_unavailable", `\`${parsed.positionals.join(" ")}\` is not exposed by the hosted Recess CLI. Use help or agent-context to discover the remote catalog.`);
2341
2385
  }
2342
2386
  if (options.structuredInput !== undefined &&
2343
- ![
2344
- "apps validate",
2345
- "goal-templates validate-spec",
2346
- "goal-templates create",
2347
- ].includes(command.path.join(" "))) {
2387
+ !STRUCTURED_INPUT_COMMANDS.includes(command.path.join(" "))) {
2348
2388
  throw new CliError("invalid_arguments", "Structured input is accepted only by hosted apps validate and goal-templates validate-spec/create.");
2349
2389
  }
2350
2390
  if (!hostedNounAllowed(noun, options.session?.user.role, options.discovery?.scope)) {
@@ -2361,16 +2401,20 @@ export async function executeRecessCommand(argv, options = {}) {
2361
2401
  }
2362
2402
  }
2363
2403
  if (noun === "agent-context") {
2364
- const [profiles, config] = isRemote
2404
+ const [profiles, config] = isHosted
2365
2405
  ? [{ profiles: [] }, options.config ?? (await resolveConfig(undefined))]
2366
2406
  : await Promise.all([
2367
2407
  listProfiles(),
2368
2408
  options.config ?? resolveConfig(flagString(parsed, "profile")),
2369
2409
  ]);
2370
2410
  const discovery = options.discovery ?? resolveCommandDiscovery(config);
2371
- return agentContext(isRemote ? hostedCommands(commands, discovery) : commands, {
2411
+ return agentContext(isRemote
2412
+ ? hostedCommands(commands, discovery)
2413
+ : inApp
2414
+ ? inAppCommands(commands, discovery)
2415
+ : commands, {
2372
2416
  cliVersion: options.versions?.cliVersion ??
2373
- (isRemote ? "hosted" : await readCliVersion()),
2417
+ (isHosted ? "hosted" : await readCliVersion()),
2374
2418
  availableProfiles: profiles.profiles.map((profile) => profile.name),
2375
2419
  feedbackUpstreamConfigured: Boolean(process.env.RECESS_CLI_FEEDBACK_ENDPOINT),
2376
2420
  discovery,
@@ -2502,11 +2546,19 @@ export async function executeRecessCommand(argv, options = {}) {
2502
2546
  // that uses it. Sign-in/out commands manage the session themselves. Not
2503
2547
  // fatal here: an offline local command must still run, and an API call
2504
2548
  // that needs auth refreshes on its 401 and reports the real error.
2505
- if (!isRemote &&
2549
+ if (!isHosted &&
2506
2550
  !(noun === "auth" && verb !== "status") &&
2507
2551
  noun !== "setup") {
2508
2552
  await ensureFreshSession(config).catch(() => undefined);
2509
2553
  }
2554
+ if (noun === "doctor" && inApp) {
2555
+ return {
2556
+ transport: "in-app",
2557
+ authenticated: true,
2558
+ session: options.session ?? null,
2559
+ scope: options.discovery?.scope ?? null,
2560
+ };
2561
+ }
2510
2562
  if (noun === "doctor" && isRemote) {
2511
2563
  return {
2512
2564
  transport: "streamable-http-mcp",
@@ -3034,6 +3086,23 @@ export async function executeRecessCommand(argv, options = {}) {
3034
3086
  params: { query: { search: query, limit } },
3035
3087
  }));
3036
3088
  }
3089
+ if (noun === "users" && verb === "roster") {
3090
+ const role = assertChoice(flagString(parsed, "role") ?? "kid", ["kid", "guardian", "guide", "admin", "program", "moderator"], "--role");
3091
+ const limit = flagNumber(parsed, "limit") ?? 100;
3092
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500) {
3093
+ throw new CliError("invalid_arguments", "--limit must be an integer from 1 through 500.");
3094
+ }
3095
+ const cursor = flagString(parsed, "cursor");
3096
+ return unwrap(await api.client.GET("/admin/users/roster", {
3097
+ params: {
3098
+ query: {
3099
+ role: role.toUpperCase(),
3100
+ limit,
3101
+ ...(cursor ? { cursor } : {}),
3102
+ },
3103
+ },
3104
+ }));
3105
+ }
3037
3106
  if (noun === "users" && verb === "tier") {
3038
3107
  const action = positional(parsed, 2, "users tier action");
3039
3108
  if (action === "list-tiers") {
@@ -3675,7 +3744,7 @@ export async function executeRecessCommand(argv, options = {}) {
3675
3744
  parsed,
3676
3745
  api,
3677
3746
  writeCommand,
3678
- transport: options.transport,
3747
+ transport: isRemote ? "remote" : "local",
3679
3748
  structuredInput: options.structuredInput,
3680
3749
  });
3681
3750
  }
@@ -4513,7 +4582,7 @@ export async function executeRecessCommand(argv, options = {}) {
4513
4582
  // infers whether `get` means guardian guidance or staff-only operations.
4514
4583
  const audience = assertChoice(verb, ["admin", "guardian"], "skill audience");
4515
4584
  const action = positional(parsed, 2, "skills action");
4516
- const refresh = isRemote || hasFlag(parsed, "refresh");
4585
+ const refresh = isHosted || hasFlag(parsed, "refresh");
4517
4586
  if (action === "list") {
4518
4587
  const query = flagString(parsed, "query");
4519
4588
  const category = flagString(parsed, "category");
@@ -4532,7 +4601,7 @@ export async function executeRecessCommand(argv, options = {}) {
4532
4601
  },
4533
4602
  },
4534
4603
  }));
4535
- if (!isRemote)
4604
+ if (!isHosted)
4536
4605
  await writeSkillCache(config.apiOrigin, cacheKey, data);
4537
4606
  return { ...data, cached: false };
4538
4607
  }
@@ -4558,7 +4627,7 @@ export async function executeRecessCommand(argv, options = {}) {
4558
4627
  },
4559
4628
  },
4560
4629
  }));
4561
- if (!isRemote)
4630
+ if (!isHosted)
4562
4631
  await writeSkillCache(config.apiOrigin, cacheKey, data);
4563
4632
  return { ...data, cached: false };
4564
4633
  }
@@ -665,6 +665,18 @@ export function commandIsAvailable(command, scope) {
665
665
  }
666
666
  return scope === "full_admin";
667
667
  }
668
+ /** `local` nouns that still answer inside the Recess app chat. */
669
+ const IN_APP_LOCAL_NOUNS = new Set(["help", "agent-context", "doctor"]);
670
+ /**
671
+ * The in-app catalog: every command this session's scope reaches, minus the
672
+ * ones that manage a local install (sign-in, profiles, the job ledger).
673
+ */
674
+ export function inAppCommands(commands, context) {
675
+ return commands.filter((command) => command.access === "local"
676
+ ? IN_APP_LOCAL_NOUNS.has(command.path[0])
677
+ : command.path[0] !== "confirm" &&
678
+ commandIsAvailable(command, context.scope));
679
+ }
668
680
  function usageBlocks(help) {
669
681
  const lines = help.split("\n");
670
682
  const blocks = [];
@@ -1049,6 +1061,7 @@ function nounIndex(commands) {
1049
1061
  const width = Math.max(...Array.from(counts.keys(), (noun) => noun.length));
1050
1062
  return Array.from(counts, ([noun, count]) => ` ${`${noun} (${count})`.padEnd(width + 6)}${NOUN_SUMMARIES[noun] ?? ""}`.trimEnd());
1051
1063
  }
1064
+ const IN_APP_CONVENTIONS = "--reason TEXT says why (audit-logged). ✎ writes return a preview with an operationKey and change nothing; after the person approves in a later message, rerun the same command with --confirm --operation-key KEY. File and folder flags take paths in this chat's files folder, where written files stay.";
1052
1065
  const LOCAL_CONVENTIONS = "--reason TEXT says why (audit-logged): ✎ writes require it, reads default it. Writes preview and exit 2; after human approval run `recess confirm <operation-key>` (replays the stored preview) or rerun with --confirm --operation-key KEY.";
1053
1066
  export function scopedHelp(help, commands, scope, context, options = {}) {
1054
1067
  const matches = commands.filter((command) => pathStartsWith(command.path, scope) &&
@@ -1083,7 +1096,9 @@ export function scopedHelp(help, commands, scope, context, options = {}) {
1083
1096
  "",
1084
1097
  `Access: ${accessLabel}`,
1085
1098
  "Key: ◇ shared command ◆ admin-only command ✎ write (previews; needs confirmation)",
1086
- ...(options.remoteOnly ? [] : [LOCAL_CONVENTIONS]),
1099
+ ...(options.remoteOnly
1100
+ ? []
1101
+ : [options.inApp ? IN_APP_CONVENTIONS : LOCAL_CONVENTIONS]),
1087
1102
  "",
1088
1103
  "Usage:",
1089
1104
  ...(compactRoot
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
2
+ import { fs } from "../in-app.js";
3
3
  import path from "node:path";
4
4
  import { unwrap } from "../api.js";
5
5
  import { flagList, flagString, hasFlag } from "../args.js";
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
2
+ import { assertLocalMachine, fs } from "../in-app.js";
3
3
  import http from "node:http";
4
4
  import path from "node:path";
5
5
  import { unwrap } from "../api.js";
@@ -650,6 +650,7 @@ export async function runAppsCommand(ctx) {
650
650
  ".webp": "image/webp",
651
651
  };
652
652
  const mapTag = `<script type="importmap">${JSON.stringify({ imports: importMap })}</script>`;
653
+ assertLocalMachine();
653
654
  const server = http.createServer((req, res) => {
654
655
  void (async () => {
655
656
  const urlPath = decodeURIComponent((req.url ?? "/").split("?")[0]);
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "../in-app.js";
2
2
  import path from "node:path";
3
3
  import { unwrap } from "../api.js";
4
4
  import { flagString } from "../args.js";
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
2
+ import { fs } from "../in-app.js";
3
3
  import path from "node:path";
4
4
  import { unwrap } from "../api.js";
5
5
  import { flagNumber, flagString, hasFlag } from "../args.js";
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "../in-app.js";
2
2
  import path from "node:path";
3
3
  import { unwrap } from "../api.js";
4
4
  import { flagNumber, flagString } from "../args.js";
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
2
+ import { fs } from "../in-app.js";
3
3
  import path from "node:path";
4
4
  import { unwrap } from "../api.js";
5
5
  import { flagNumber, flagString, hasFlag } from "../args.js";
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "../in-app.js";
2
2
  import path from "node:path";
3
3
  import { unwrap } from "../api.js";
4
4
  import { flagString, hasFlag } from "../args.js";
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "../in-app.js";
2
2
  import path from "node:path";
3
3
  import { unwrap } from "../api.js";
4
4
  import { flagString, hasFlag } from "../args.js";
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
2
+ import { fs } from "../in-app.js";
3
3
  import path from "node:path";
4
4
  import { unwrap } from "../api.js";
5
5
  import { flagString, hasFlag } from "../args.js";
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
2
+ import { fs } from "../in-app.js";
3
3
  import path from "node:path";
4
4
  import { unwrap } from "../api.js";
5
5
  import { flagList, flagString, hasFlag } from "../args.js";
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "../in-app.js";
2
2
  import path from "node:path";
3
3
  import { flagNumber, flagString } from "../args.js";
4
4
  import { CliError } from "../errors.js";
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
- import fs from "node:fs/promises";
2
+ import { assertLocalMachine, fs } from "../in-app.js";
3
3
  import path from "node:path";
4
4
  import { unwrap } from "../api.js";
5
5
  import { flagList, flagString, hasFlag } from "../args.js";
@@ -217,6 +217,7 @@ export function parseTuitionPlanSpecFlags(parsed, options) {
217
217
  if (customRaw) {
218
218
  const text = customRaw.startsWith("@")
219
219
  ? (() => {
220
+ assertLocalMachine();
220
221
  try {
221
222
  return readFileSync(path.resolve(customRaw.slice(1)), "utf-8");
222
223
  }
package/dist/config.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import fs from "node:fs/promises";
2
+ import { fs } from "./in-app.js";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { CliError } from "./errors.js";
package/dist/delivery.js CHANGED
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "./in-app.js";
2
2
  import path from "node:path";
3
3
  import { CliError } from "./errors.js";
4
4
  export async function deliverJson(destination, envelope) {
package/dist/feedback.js CHANGED
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "./in-app.js";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { CliError } from "./errors.js";
package/dist/help.js CHANGED
@@ -36,6 +36,8 @@ Usage:
36
36
  recess [--json] auth poll [--timeout 300]
37
37
  recess [--json] auth status|logout
38
38
  recess [--json] users search <name-or-id> [--limit 10]
39
+ recess [--json] users roster [--role kid|guardian|guide|admin|program|moderator]
40
+ [--limit 100] [--cursor <user-id>]
39
41
  recess [--json] users get <user-id>
40
42
  recess [--json] users school complete-action <user-id> <action-id> --note <text> [--confirm]
41
43
  recess [--json] users school status <user-id>
@@ -1267,6 +1269,7 @@ export const COMMAND_SUMMARIES = {
1267
1269
  "auth status": "Show the current session's user, role, and CLI scope.",
1268
1270
  "auth logout": "Sign out and delete the stored session.",
1269
1271
  "users search": "Find users by name, email, or id.",
1272
+ "users roster": "Whole-school head counts by role, plus one page of a role's people by name.",
1270
1273
  "users get": "Read a user's account, family, roles, and flags.",
1271
1274
  "users school complete-action": "Mark a school-enrollment action done.",
1272
1275
  "users school status": "Show a kid's school-enrollment status and actions.",
package/dist/in-app.js ADDED
@@ -0,0 +1,511 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import nodeFs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { CliError } from "./errors.js";
6
+ const context = new AsyncLocalStorage();
7
+ /** Inline input files of one command, all together. */
8
+ export const IN_APP_FILES_MAX_BYTES = 2 * 1024 * 1024;
9
+ /** What one command may write to the store. */
10
+ const IN_APP_COMMIT_MAX_BYTES = 64 * 1024 * 1024;
11
+ /** `.git` cannot be a path inside the store's own repository. */
12
+ const GIT_DIR = ".git";
13
+ const STORED_GIT_DIR = ".recess-checkout";
14
+ export async function runInApp(run, input = {}) {
15
+ const state = {
16
+ root: process.cwd(),
17
+ store: input.store,
18
+ files: new Map(),
19
+ dirs: new Set(),
20
+ dirty: new Set(),
21
+ };
22
+ let total = 0;
23
+ for (const [name, text] of Object.entries(input.files ?? {})) {
24
+ if (!name ||
25
+ path.isAbsolute(name) ||
26
+ name.split(/[\\/]/).includes("..") ||
27
+ typeof text !== "string") {
28
+ throw new CliError("invalid_arguments", `Input file names are plain relative names such as patch.json; got ${JSON.stringify(name)}.`);
29
+ }
30
+ const bytes = Buffer.from(text, "utf8");
31
+ total += bytes.byteLength;
32
+ const stored = storedPath(state, name);
33
+ state.files.set(stored, bytes);
34
+ // With a store the file stays for the confirm; without one it lives only
35
+ // for this command.
36
+ if (state.store)
37
+ state.dirty.add(stored);
38
+ }
39
+ if (total > IN_APP_FILES_MAX_BYTES) {
40
+ throw new CliError("invalid_arguments", "The input files are too large for the Recess app chat (2 MB in total).");
41
+ }
42
+ return context.run(state, async () => {
43
+ let result;
44
+ try {
45
+ result = await run();
46
+ }
47
+ catch (error) {
48
+ // The command's own failure is the one to report.
49
+ await flush(state).catch(() => undefined);
50
+ throw error;
51
+ }
52
+ try {
53
+ await flush(state);
54
+ }
55
+ catch (error) {
56
+ throw new CliError("files_not_saved", `The command finished, but its files could not be saved to this chat's files folder: ${error instanceof Error ? error.message : String(error)}`);
57
+ }
58
+ return result;
59
+ });
60
+ }
61
+ export function isInApp() {
62
+ return context.getStore() !== undefined;
63
+ }
64
+ /** This in-app command's own state, or undefined everywhere else. */
65
+ export function inAppState() {
66
+ return context.getStore();
67
+ }
68
+ /** Refuse anything that needs the caller's own computer. */
69
+ export function assertLocalMachine() {
70
+ if (!isInApp())
71
+ return;
72
+ throw unavailable();
73
+ }
74
+ function unavailable() {
75
+ return new CliError("files_unavailable", "This needs a program or a place on a computer that the Recess app chat does not have. Run it with the Recess CLI on a computer.");
76
+ }
77
+ function fsError(code, target) {
78
+ const error = new Error(`${code}: ${typeof target === "string" ? path.basename(target) : "path"}`);
79
+ error.code = code;
80
+ return error;
81
+ }
82
+ /** The store path for a file-system path, or null when outside the root. */
83
+ function storedPath(state, target) {
84
+ if (typeof target !== "string")
85
+ return null;
86
+ const relative = path.relative(state.root, path.resolve(state.root, target));
87
+ if (relative.startsWith("..") || path.isAbsolute(relative))
88
+ return null;
89
+ return relative
90
+ .split(path.sep)
91
+ .filter(Boolean)
92
+ .map((segment) => (segment === GIT_DIR ? STORED_GIT_DIR : segment))
93
+ .join("/");
94
+ }
95
+ function index(state) {
96
+ state.index ??= (async () => new Set(state.store ? await state.store.list() : []))();
97
+ return state.index;
98
+ }
99
+ /** Every live file path: the store's, plus this command's, minus deletions. */
100
+ async function livePaths(state) {
101
+ const paths = new Set(await index(state));
102
+ for (const [file, bytes] of state.files) {
103
+ if (bytes)
104
+ paths.add(file);
105
+ else
106
+ paths.delete(file);
107
+ }
108
+ return Array.from(paths);
109
+ }
110
+ async function fileBytes(state, stored) {
111
+ if (stored === null)
112
+ return null;
113
+ const seen = state.files.get(stored);
114
+ if (seen !== undefined)
115
+ return seen;
116
+ if (!state.store || !(await index(state)).has(stored))
117
+ return null;
118
+ const bytes = await state.store.read(stored);
119
+ const buffer = bytes ? Buffer.from(bytes) : null;
120
+ state.files.set(stored, buffer);
121
+ return buffer;
122
+ }
123
+ async function isDirectory(state, stored) {
124
+ if (stored === null)
125
+ return false;
126
+ if (stored === "" || state.dirs.has(stored))
127
+ return true;
128
+ const prefix = `${stored}/`;
129
+ return (await livePaths(state)).some((file) => file.startsWith(prefix));
130
+ }
131
+ function requireStore(state, stored) {
132
+ if (!state.store || stored === null)
133
+ throw unavailable();
134
+ return stored;
135
+ }
136
+ function put(state, stored, bytes) {
137
+ state.files.set(stored, bytes);
138
+ state.dirty.add(stored);
139
+ }
140
+ function addDirectory(state, stored) {
141
+ const segments = stored.split("/").filter(Boolean);
142
+ for (let depth = 1; depth <= segments.length; depth += 1) {
143
+ state.dirs.add(segments.slice(0, depth).join("/"));
144
+ }
145
+ }
146
+ function stats(bytes) {
147
+ return {
148
+ size: bytes?.byteLength ?? 0,
149
+ mode: bytes ? 0o600 : 0o700,
150
+ mtimeMs: 0,
151
+ isFile: () => bytes !== null,
152
+ isDirectory: () => bytes === null,
153
+ isSymbolicLink: () => false,
154
+ };
155
+ }
156
+ async function statOf(state, target) {
157
+ const stored = storedPath(state, target);
158
+ const bytes = await fileBytes(state, stored);
159
+ if (bytes)
160
+ return stats(bytes);
161
+ if (await isDirectory(state, stored))
162
+ return stats(null);
163
+ throw fsError("ENOENT", target);
164
+ }
165
+ /** Files and folders directly under `stored`, by name. */
166
+ async function children(state, stored) {
167
+ const prefix = stored ? `${stored}/` : "";
168
+ const found = new Map();
169
+ for (const file of await livePaths(state)) {
170
+ if (!file.startsWith(prefix))
171
+ continue;
172
+ const [name, ...rest] = file.slice(prefix.length).split("/");
173
+ if (name)
174
+ found.set(name, rest.length > 0 ? "dir" : "file");
175
+ }
176
+ for (const dir of state.dirs) {
177
+ if (!dir.startsWith(prefix) || dir === stored)
178
+ continue;
179
+ const name = dir.slice(prefix.length).split("/")[0];
180
+ if (name && !found.has(name))
181
+ found.set(name, "dir");
182
+ }
183
+ return found;
184
+ }
185
+ async function moveTree(state, from, to, keepSource) {
186
+ const bytes = await fileBytes(state, from);
187
+ if (bytes) {
188
+ put(state, to, bytes);
189
+ if (!keepSource)
190
+ put(state, from, null);
191
+ return;
192
+ }
193
+ const prefix = `${from}/`;
194
+ for (const file of await livePaths(state)) {
195
+ if (!file.startsWith(prefix))
196
+ continue;
197
+ const content = await fileBytes(state, file);
198
+ if (!content)
199
+ continue;
200
+ put(state, `${to}/${file.slice(prefix.length)}`, content);
201
+ if (!keepSource)
202
+ put(state, file, null);
203
+ }
204
+ for (const dir of Array.from(state.dirs)) {
205
+ if (dir !== from && !dir.startsWith(prefix))
206
+ continue;
207
+ addDirectory(state, `${to}${dir.slice(from.length)}`);
208
+ if (!keepSource)
209
+ state.dirs.delete(dir);
210
+ }
211
+ }
212
+ function encodingOf(options) {
213
+ const encoding = typeof options === "string"
214
+ ? options
215
+ : options?.encoding;
216
+ return (encoding ?? undefined);
217
+ }
218
+ function toBuffer(data, options) {
219
+ if (typeof data === "string") {
220
+ return Buffer.from(data, encodingOf(options) ?? "utf8");
221
+ }
222
+ if (data instanceof Uint8Array)
223
+ return Buffer.from(data);
224
+ throw unavailable();
225
+ }
226
+ const OPS = {
227
+ async readFile(state, [target, options]) {
228
+ const stored = storedPath(state, target);
229
+ const bytes = await fileBytes(state, stored);
230
+ if (!bytes) {
231
+ throw fsError((await isDirectory(state, stored)) ? "EISDIR" : "ENOENT", target);
232
+ }
233
+ const encoding = encodingOf(options);
234
+ return encoding ? bytes.toString(encoding) : bytes;
235
+ },
236
+ async writeFile(state, [target, data, options]) {
237
+ const stored = requireStore(state, storedPath(state, target));
238
+ if (options?.flag === "wx" &&
239
+ (await fileBytes(state, stored))) {
240
+ throw fsError("EEXIST", target);
241
+ }
242
+ put(state, stored, toBuffer(data, options));
243
+ },
244
+ async appendFile(state, [target, data, options]) {
245
+ const stored = requireStore(state, storedPath(state, target));
246
+ const before = (await fileBytes(state, stored)) ?? Buffer.alloc(0);
247
+ put(state, stored, Buffer.concat([before, toBuffer(data, options)]));
248
+ },
249
+ async mkdir(state, [target]) {
250
+ addDirectory(state, requireStore(state, storedPath(state, target)));
251
+ return undefined;
252
+ },
253
+ async mkdtemp(state, [prefix]) {
254
+ const directory = `${String(prefix)}${randomBytes(4).toString("hex")}`;
255
+ addDirectory(state, requireStore(state, storedPath(state, directory)));
256
+ return directory;
257
+ },
258
+ async readdir(state, [target, options]) {
259
+ const stored = storedPath(state, target);
260
+ if (stored === null || !(await isDirectory(state, stored))) {
261
+ throw fsError("ENOENT", target);
262
+ }
263
+ const entries = Array.from(await children(state, stored)).sort(([left], [right]) => left.localeCompare(right));
264
+ if (!options?.withFileTypes) {
265
+ return entries.map(([name]) => name);
266
+ }
267
+ return entries.map(([name, kind]) => ({
268
+ name,
269
+ isFile: () => kind === "file",
270
+ isDirectory: () => kind === "dir",
271
+ isSymbolicLink: () => false,
272
+ }));
273
+ },
274
+ stat: (state, [target]) => statOf(state, target),
275
+ lstat: (state, [target]) => statOf(state, target),
276
+ async realpath(state, [target]) {
277
+ await statOf(state, target);
278
+ return path.resolve(state.root, target);
279
+ },
280
+ async access(state, [target]) {
281
+ await statOf(state, target);
282
+ },
283
+ async chmod(state, [target]) {
284
+ await statOf(state, target);
285
+ },
286
+ async rm(state, [target, options]) {
287
+ const stored = storedPath(state, target);
288
+ const settings = (options ?? {});
289
+ if (stored !== null && (await fileBytes(state, stored))) {
290
+ put(state, requireStore(state, stored), null);
291
+ return;
292
+ }
293
+ if (stored !== null && (await isDirectory(state, stored))) {
294
+ requireStore(state, stored);
295
+ const prefix = `${stored}/`;
296
+ for (const file of await livePaths(state)) {
297
+ if (file.startsWith(prefix))
298
+ put(state, file, null);
299
+ }
300
+ for (const dir of Array.from(state.dirs)) {
301
+ if (dir === stored || dir.startsWith(prefix))
302
+ state.dirs.delete(dir);
303
+ }
304
+ return;
305
+ }
306
+ if (!settings.force)
307
+ throw fsError("ENOENT", target);
308
+ },
309
+ async rename(state, [from, to]) {
310
+ await statOf(state, from);
311
+ await moveTree(state, requireStore(state, storedPath(state, from)), requireStore(state, storedPath(state, to)), false);
312
+ },
313
+ async cp(state, [from, to]) {
314
+ await statOf(state, from);
315
+ await moveTree(state, requireStore(state, storedPath(state, from)), requireStore(state, storedPath(state, to)), true);
316
+ },
317
+ async open(state, [target, flags]) {
318
+ if (flags !== undefined && flags !== "r")
319
+ throw unavailable();
320
+ const bytes = await fileBytes(state, storedPath(state, target));
321
+ if (!bytes)
322
+ throw fsError("ENOENT", target);
323
+ return {
324
+ async read(buffer, offset, length, position) {
325
+ const bytesRead = bytes.copy(buffer, offset, position, Math.min(bytes.byteLength, position + length));
326
+ return { bytesRead, buffer };
327
+ },
328
+ stat: async () => stats(bytes),
329
+ readFile: async (options) => {
330
+ const encoding = encodingOf(options);
331
+ return encoding ? bytes.toString(encoding) : bytes;
332
+ },
333
+ close: async () => undefined,
334
+ };
335
+ },
336
+ };
337
+ OPS.unlink = (state, [target]) => OPS.rm(state, [target]);
338
+ async function flush(state) {
339
+ if (!state.store || state.dirty.size === 0)
340
+ return;
341
+ const stored = await index(state);
342
+ const changes = [];
343
+ let total = 0;
344
+ for (const file of state.dirty) {
345
+ const content = state.files.get(file) ?? null;
346
+ // Deleting what the store never held is nothing to write.
347
+ if (!content && !stored.has(file))
348
+ continue;
349
+ total += content?.byteLength ?? 0;
350
+ changes.push({ path: file, content });
351
+ }
352
+ if (changes.length === 0)
353
+ return;
354
+ if (total > IN_APP_COMMIT_MAX_BYTES) {
355
+ throw new CliError("files_too_large", "This command's files are too large for the Recess app chat (64 MB). Run it with the Recess CLI on a computer.");
356
+ }
357
+ await state.store.commit(changes);
358
+ }
359
+ /**
360
+ * `node:fs/promises` everywhere but in-app, where every call answers from the
361
+ * command's virtual files and anything else is refused.
362
+ */
363
+ export const fs = new Proxy(nodeFs, {
364
+ get(target, property, receiver) {
365
+ const value = Reflect.get(target, property, receiver);
366
+ if (typeof value !== "function")
367
+ return value;
368
+ return (...args) => {
369
+ const state = context.getStore();
370
+ if (!state) {
371
+ return value.apply(target, args);
372
+ }
373
+ const operation = typeof property === "string" ? OPS[property] : undefined;
374
+ // Async like the real one, so `.catch()` chains still see the failure.
375
+ return (async () => {
376
+ if (!operation)
377
+ throw unavailable();
378
+ return operation(state, args);
379
+ })();
380
+ };
381
+ },
382
+ });
383
+ const LEDGER = `${GIT_DIR}/recess-in-app.json`;
384
+ async function readLedger(cwd) {
385
+ const raw = await fs
386
+ .readFile(path.join(cwd, LEDGER), "utf8")
387
+ .catch(() => null);
388
+ return raw ? JSON.parse(raw) : null;
389
+ }
390
+ async function workingTree(state, cwd) {
391
+ const root = storedPath(state, cwd);
392
+ if (root === null)
393
+ throw unavailable();
394
+ const prefix = root ? `${root}/` : "";
395
+ const tree = {};
396
+ for (const file of (await livePaths(state)).sort()) {
397
+ if (!file.startsWith(prefix))
398
+ continue;
399
+ const relative = file.slice(prefix.length);
400
+ if (relative.startsWith(`${STORED_GIT_DIR}/`))
401
+ continue;
402
+ const bytes = await fileBytes(state, file);
403
+ if (bytes) {
404
+ tree[relative] = createHash("sha256").update(bytes).digest("hex");
405
+ }
406
+ }
407
+ return tree;
408
+ }
409
+ function sameTree(left, right) {
410
+ const names = Object.keys(left);
411
+ return (names.length === Object.keys(right).length &&
412
+ names.every((name) => left[name] === right[name]));
413
+ }
414
+ async function commitTree(state, cwd, ledger, subject) {
415
+ const commit = {
416
+ parent: ledger.head,
417
+ subject,
418
+ tree: await workingTree(state, cwd),
419
+ };
420
+ const id = createHash("sha1").update(JSON.stringify(commit)).digest("hex");
421
+ ledger.commits[id] = commit;
422
+ ledger.head = id;
423
+ await fs.writeFile(path.join(cwd, LEDGER), JSON.stringify(ledger), "utf8");
424
+ return id;
425
+ }
426
+ /** `base..head`, oldest first; throws when `base` is not an ancestor. */
427
+ function commitsAfter(ledger, base, head) {
428
+ const chain = [];
429
+ for (let id = head; id && id !== base; id = ledger.commits[id]?.parent ?? null) {
430
+ if (!ledger.commits[id])
431
+ break;
432
+ chain.unshift(id);
433
+ }
434
+ const oldest = chain[0] ? ledger.commits[chain[0]] : undefined;
435
+ if (head !== base && oldest?.parent !== base) {
436
+ throw new CliError("git_failed", "This checkout does not continue from the workspace it was checked out of. Check it out again.");
437
+ }
438
+ return chain;
439
+ }
440
+ /** The git commands the workspace flows run, answered from the ledger. */
441
+ export async function inAppGit(cwd, args) {
442
+ const state = context.getStore();
443
+ if (!state)
444
+ throw unavailable();
445
+ const [command, ...rest] = args;
446
+ if (command === "config")
447
+ return rest[0] === "--get" ? "Recess CLI\n" : "";
448
+ if (command === "add")
449
+ return "";
450
+ if (command === "init") {
451
+ await fs.mkdir(path.join(cwd, GIT_DIR), { recursive: true });
452
+ await fs.writeFile(path.join(cwd, LEDGER), JSON.stringify({ head: null, commits: {} }), "utf8");
453
+ return "";
454
+ }
455
+ const ledger = await readLedger(cwd);
456
+ if (!ledger) {
457
+ throw new CliError("invalid_checkout", "That folder is not a Recess checkout. Check the workspace out first.");
458
+ }
459
+ if (command === "rev-parse" && rest[0] === "--show-toplevel") {
460
+ return `${path.resolve(cwd)}\n`;
461
+ }
462
+ // Nothing is ever "uncommitted": edits fold into HEAD when it is asked for.
463
+ if (command === "status")
464
+ return "";
465
+ if (command === "ls-files") {
466
+ return Object.keys(await workingTree(state, cwd))
467
+ .map((file) => `${file}\0`)
468
+ .join("");
469
+ }
470
+ if (command === "commit") {
471
+ const subject = rest[rest.indexOf("-m") + 1] ?? "Update workspace";
472
+ await commitTree(state, cwd, ledger, subject);
473
+ return "";
474
+ }
475
+ if (command === "rev-parse" && rest[0] === "HEAD") {
476
+ const head = ledger.head ? ledger.commits[ledger.head] : undefined;
477
+ if (!head || !sameTree(head.tree, await workingTree(state, cwd))) {
478
+ return `${await commitTree(state, cwd, ledger, "Edit workspace files")}\n`;
479
+ }
480
+ return `${ledger.head}\n`;
481
+ }
482
+ const range = rest.at(-1)?.split("..") ?? [];
483
+ if (command === "merge-base" && rest[0] === "--is-ancestor") {
484
+ commitsAfter(ledger, rest[1], rest[2]);
485
+ return "";
486
+ }
487
+ if (command === "log" && range.length === 2) {
488
+ return commitsAfter(ledger, range[0], range[1])
489
+ .map((id) => `${id}\t${ledger.commits[id].subject}\n`)
490
+ .join("");
491
+ }
492
+ if (command === "diff" && range.length === 2) {
493
+ const before = ledger.commits[range[0]]?.tree;
494
+ const after = ledger.commits[range[1]]?.tree;
495
+ if (!before || !after) {
496
+ throw new CliError("git_failed", "This checkout has lost its history.");
497
+ }
498
+ const fields = [];
499
+ for (const file of new Set([
500
+ ...Object.keys(before),
501
+ ...Object.keys(after),
502
+ ])) {
503
+ if (before[file] === after[file])
504
+ continue;
505
+ fields.push(!before[file] ? "A" : !after[file] ? "D" : "M", file);
506
+ }
507
+ return fields.map((field) => `${field}\0`).join("");
508
+ }
509
+ throw unavailable();
510
+ }
511
+ //# sourceMappingURL=in-app.js.map
package/dist/jobs.js CHANGED
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "./in-app.js";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  function jobsPath() {
package/dist/setup.js CHANGED
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "./in-app.js";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
@@ -1,4 +1,4 @@
1
- import fs from "node:fs/promises";
1
+ import { fs } from "./in-app.js";
2
2
  import path from "node:path";
3
3
  import { cliRequestHeaders } from "./http.js";
4
4
  import { skillDestinations } from "./setup.js";
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import fs from "node:fs/promises";
2
+ import { fs } from "./in-app.js";
3
3
  import path from "node:path";
4
4
  import { defaultConfigPath } from "./config.js";
5
5
  /**
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import fs from "node:fs/promises";
2
+ import { assertLocalMachine, fs } from "./in-app.js";
3
3
  import path from "node:path";
4
4
  import { defaultConfigPath } from "./config.js";
5
5
  import { CliError } from "./errors.js";
@@ -66,6 +66,7 @@ export async function printUpdateNotice(cliVersion, write = (text) => process.st
66
66
  write(`\n${text}\n`);
67
67
  }
68
68
  export async function runSelfUpdate() {
69
+ assertLocalMachine();
69
70
  const [bin, ...args] = UPGRADE_COMMAND.split(" ");
70
71
  const exitCode = await new Promise((resolve, reject) => {
71
72
  const child = spawn(bin, args, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "recess-cli",
3
- "version": "3.50.2",
3
+ "version": "3.51.0",
4
4
  "description": "Safe Recess administration and family AI tools from the command line.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {