@openape/apes 0.9.3 → 0.9.4

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.
@@ -44,7 +44,23 @@ function notifyGrantPending(info) {
44
44
  }
45
45
  }
46
46
 
47
+ // src/shell/apes-self-dispatch.ts
48
+ import { basename } from "path";
49
+ var APES_GATED_SUBCOMMANDS = /* @__PURE__ */ new Set(["run", "fetch", "mcp"]);
50
+ function isApesSelfDispatch(parsed) {
51
+ if (!parsed || parsed.isCompound)
52
+ return false;
53
+ const invokedName = basename(parsed.executable);
54
+ if (invokedName !== "apes" && invokedName !== "apes.js")
55
+ return false;
56
+ const subCommand = parsed.argv[0];
57
+ if (!subCommand)
58
+ return false;
59
+ return !APES_GATED_SUBCOMMANDS.has(subCommand);
60
+ }
61
+
47
62
  export {
48
- notifyGrantPending
63
+ notifyGrantPending,
64
+ isApesSelfDispatch
49
65
  };
50
- //# sourceMappingURL=chunk-5FV5KXEX.js.map
66
+ //# sourceMappingURL=chunk-ZHTLP2DD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/notifications.ts","../src/shell/apes-self-dispatch.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\nimport consola from 'consola'\nimport { quote } from 'shell-quote'\nimport { loadConfig } from './config'\n\nexport interface PendingGrantInfo {\n grantId: string\n approveUrl: string\n command: string\n audience: string\n host: string\n}\n\n/**\n * Resolve the notification command for pending grants. Checks (in order):\n * 1. `APES_NOTIFY_PENDING_COMMAND` env var (highest priority — lets\n * parent programs like openclaw override per invocation)\n * 2. `[notifications] pending_command` in ~/.config/apes/config.toml\n *\n * Returns undefined if no notification command is configured.\n */\nfunction resolvePendingCommand(): string | undefined {\n if (process.env.APES_NOTIFY_PENDING_COMMAND)\n return process.env.APES_NOTIFY_PENDING_COMMAND\n\n const config = loadConfig()\n return config.notifications?.pending_command\n}\n\n/**\n * Escape a value for safe embedding inside a single-quoted shell string.\n * We use `shell-quote` to produce a safe literal, then strip the outer\n * quoting because the template substitution embeds the value inside the\n * user's command template which is itself passed to `sh -c`.\n */\nfunction shellEscape(value: string): string {\n // quote() wraps in single quotes and escapes internal single quotes\n // e.g. \"it's\" → \"'it'\\\\''s'\"\n // We return the raw escaped form so it's safe inside sh -c.\n return quote([value])\n}\n\n/**\n * Substitute template variables in the notification command.\n * All values are shell-escaped to prevent injection.\n */\nfunction renderTemplate(template: string, info: PendingGrantInfo): string {\n return template\n .replace(/\\{grant_id\\}/g, shellEscape(info.grantId))\n .replace(/\\{approve_url\\}/g, shellEscape(info.approveUrl))\n .replace(/\\{command\\}/g, shellEscape(info.command))\n .replace(/\\{audience\\}/g, shellEscape(info.audience))\n .replace(/\\{host\\}/g, shellEscape(info.host))\n}\n\n/**\n * Send a notification that a grant is awaiting human approval.\n *\n * This is **fire-and-forget**: the notification subprocess runs detached\n * and unref'd so it cannot block the grant flow. A 10-second timeout\n * kills it if it hangs (e.g. network issue reaching Telegram API).\n *\n * Only fires when a notification command is configured. Silently returns\n * if not — the grant flow must never depend on notifications.\n *\n * Only call this when the grant **actually requires waiting** (new grant\n * with pending status). Do NOT call when:\n * - An existing timed/always grant was reused (no human action needed)\n * - The grant was instantly approved (no waiting phase)\n */\nexport function notifyGrantPending(info: PendingGrantInfo): void {\n const template = resolvePendingCommand()\n if (!template)\n return\n\n const rendered = renderTemplate(template, info)\n\n try {\n const child = spawn('sh', ['-c', rendered], {\n detached: true,\n stdio: 'ignore',\n env: { ...process.env },\n })\n\n // Don't let the notification process keep the parent alive\n child.unref()\n\n // Kill after 10 seconds if it hasn't exited\n const timeout = setTimeout(() => {\n try {\n child.kill('SIGKILL')\n }\n catch {}\n }, 10_000)\n timeout.unref()\n\n child.on('exit', () => clearTimeout(timeout))\n }\n catch (err) {\n // Never let notification failure break the grant flow\n consola.debug('Notification command failed:', err)\n }\n}\n","import { basename } from 'node:path'\nimport type { ParsedShellCommand } from '../shapes/shell-parser.js'\n\n/**\n * Subset of `apes` subcommands that remain grant-gated even when invoked\n * as self-dispatches from inside an ape-shell context. These are the\n * three categories where the shell-grant layer adds real security value\n * that isn't duplicated by server-side auth gates or local-file-only\n * semantics:\n *\n * - `run` — spawns arbitrary executables, the core of the grant system\n * - `fetch` — forwards the bearer token to a user-specified URL\n * - `mcp` — binds a network port and serves a persistent API\n *\n * Every other `apes <subcmd>` either reads state, mutates the user's own\n * local config, or talks to the IdP through endpoints that are already\n * scoped by the auth token — gating them in the shell is redundant\n * friction, and under 0.9.0's async-default grant flow it actively\n * breaks `apes grants run <id>` via recursion (the polling call itself\n * creates a new grant, cascading indefinitely).\n *\n * This is the single source of truth shared by both dispatch paths:\n * - Interactive REPL: `shell/grant-dispatch.ts` → `requestGrantForShellLine`\n * - One-shot `ape-shell -c`: `commands/run.ts` → `runShellMode` (which\n * receives the bash-c-wrapped command after `rewriteApeShellArgs`\n * rewrites `ape-shell -c \"<cmd>\"` into `apes run --shell -- bash -c <cmd>`)\n *\n * Keep this list in sync with the blocklist snapshot test in\n * `shell-grant-dispatch.test.ts` — the tripwire that forces a review\n * decision whenever a new top-level apes subcommand is added.\n */\nexport const APES_GATED_SUBCOMMANDS = new Set(['run', 'fetch', 'mcp'])\n\n/**\n * Returns true if the parsed shell command is an `apes <subcmd>`\n * invocation that should bypass the grant flow entirely. Non-apes\n * binaries, compound lines (pipes, &&, etc.), and subcommands in\n * `APES_GATED_SUBCOMMANDS` all return false so they stay on the normal\n * grant path.\n *\n * The caller (either `requestGrantForShellLine` for the REPL path or\n * `runShellMode` for the one-shot path) is responsible for parsing the\n * input string and passing the resulting ParsedShellCommand here.\n */\nexport function isApesSelfDispatch(parsed: ParsedShellCommand | null | undefined): boolean {\n if (!parsed || parsed.isCompound)\n return false\n const invokedName = basename(parsed.executable)\n if (invokedName !== 'apes' && invokedName !== 'apes.js')\n return false\n const subCommand = parsed.argv[0]\n if (!subCommand)\n return false\n return !APES_GATED_SUBCOMMANDS.has(subCommand)\n}\n"],"mappings":";;;;;;AAAA,SAAS,a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AAO;AACT,QAAM,cAAc,SAAS,OAAO,UAAU;AAC9C,MAAI,gBAAgB,UAAU,gBAAgB;AAC5C,WAAO;AACT,QAAM,aAAa,OAAO,KAAK,CAAC;AAChC,MAAI,CAAC;AACH,WAAO;AACT,SAAO,CAAC,uBAAuB,IAAI,UAAU;AAC/C;","names":[]}
package/dist/cli.js CHANGED
@@ -9,8 +9,9 @@ import {
9
9
  readPublicKeyComment
10
10
  } from "./chunk-ION3CWD5.js";
11
11
  import {
12
+ isApesSelfDispatch,
12
13
  notifyGrantPending
13
- } from "./chunk-5FV5KXEX.js";
14
+ } from "./chunk-ZHTLP2DD.js";
14
15
  import {
15
16
  ApiError,
16
17
  apiFetch,
@@ -2076,6 +2077,14 @@ async function runShellMode(command, args) {
2076
2077
  const idp = getIdpUrl(args.idp);
2077
2078
  if (!idp)
2078
2079
  throw new CliError("No IdP URL configured. Run `apes login` first or pass --idp.");
2080
+ const innerLine = extractShellCommandString(command);
2081
+ if (innerLine) {
2082
+ const parsedInner = parseShellCommand(innerLine);
2083
+ if (isApesSelfDispatch(parsedInner)) {
2084
+ execShellCommand(command);
2085
+ return;
2086
+ }
2087
+ }
2079
2088
  const adapterHandled = await tryAdapterModeFromShell(command, idp, args);
2080
2089
  if (adapterHandled) return;
2081
2090
  const grantsUrl = await getGrantsEndpoint(idp);
@@ -2193,7 +2202,11 @@ function execShellCommand(command) {
2193
2202
  if (command.length === 0)
2194
2203
  throw new CliError("No command to execute");
2195
2204
  try {
2196
- execFileSync2(command[0], command.slice(1), { stdio: "inherit" });
2205
+ const { APES_SHELL_WRAPPER: _wrapperMarker, ...inheritedEnv } = process.env;
2206
+ execFileSync2(command[0], command.slice(1), {
2207
+ stdio: "inherit",
2208
+ env: inheritedEnv
2209
+ });
2197
2210
  } catch (err) {
2198
2211
  const exitCode = err.status || 1;
2199
2212
  throw new CliExit(exitCode);
@@ -2313,8 +2326,10 @@ async function runAudienceMode(audience, action, args) {
2313
2326
  if (audience === "escapes") {
2314
2327
  consola19.info(`Executing: ${command.join(" ")}`);
2315
2328
  try {
2329
+ const { APES_SHELL_WRAPPER: _wrapperMarker, ...inheritedEnv } = process.env;
2316
2330
  execFileSync2(args["escapes-path"] || "escapes", ["--grant", authz_jwt, "--", ...command], {
2317
- stdio: "inherit"
2331
+ stdio: "inherit",
2332
+ env: inheritedEnv
2318
2333
  });
2319
2334
  } catch (err) {
2320
2335
  const exitCode = err.status || 1;
@@ -2593,7 +2608,7 @@ var mcpCommand = defineCommand26({
2593
2608
  if (transport !== "stdio" && transport !== "sse") {
2594
2609
  throw new Error('Transport must be "stdio" or "sse"');
2595
2610
  }
2596
- const { startMcpServer } = await import("./server-2IMH7YQX.js");
2611
+ const { startMcpServer } = await import("./server-ED5MMYT3.js");
2597
2612
  await startMcpServer(transport, port);
2598
2613
  }
2599
2614
  });
@@ -3085,7 +3100,7 @@ async function bestEffortGrantCount(idp) {
3085
3100
  }
3086
3101
  }
3087
3102
  async function runHealth(args) {
3088
- const version = true ? "0.9.3" : "0.0.0";
3103
+ const version = true ? "0.9.4" : "0.0.0";
3089
3104
  const auth = loadAuth();
3090
3105
  if (!auth) {
3091
3106
  throw new CliError("Not logged in. Run `apes login` first.", 1);
@@ -3287,10 +3302,10 @@ if (shellRewrite) {
3287
3302
  if (shellRewrite.action === "rewrite") {
3288
3303
  process.argv = shellRewrite.argv;
3289
3304
  } else if (shellRewrite.action === "version") {
3290
- console.log(`ape-shell ${"0.9.3"} (OpenApe DDISA shell wrapper)`);
3305
+ console.log(`ape-shell ${"0.9.4"} (OpenApe DDISA shell wrapper)`);
3291
3306
  process.exit(0);
3292
3307
  } else if (shellRewrite.action === "help") {
3293
- console.log(`ape-shell ${"0.9.3"} \u2014 OpenApe DDISA shell wrapper`);
3308
+ console.log(`ape-shell ${"0.9.4"} \u2014 OpenApe DDISA shell wrapper`);
3294
3309
  console.log("");
3295
3310
  console.log("Usage:");
3296
3311
  console.log(" ape-shell Start interactive grant-mediated REPL");
@@ -3305,7 +3320,7 @@ if (shellRewrite) {
3305
3320
  console.log(" --help, -h Show this help message");
3306
3321
  process.exit(0);
3307
3322
  } else if (shellRewrite.action === "interactive") {
3308
- const { runInteractiveShell } = await import("./orchestrator-MVOSHEI2.js");
3323
+ const { runInteractiveShell } = await import("./orchestrator-5EZD7ZQE.js");
3309
3324
  await runInteractiveShell();
3310
3325
  process.exit(0);
3311
3326
  } else {
@@ -3348,7 +3363,7 @@ var configCommand = defineCommand33({
3348
3363
  var main = defineCommand33({
3349
3364
  meta: {
3350
3365
  name: "apes",
3351
- version: "0.9.3",
3366
+ version: "0.9.4",
3352
3367
  description: "Unified CLI for OpenApe"
3353
3368
  },
3354
3369
  subCommands: {