@mnemom/mnemom 0.17.6-next.2 → 0.17.6

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/README.md CHANGED
@@ -86,13 +86,18 @@ or `launch` in `launcher.toml`) also skips the Remote Control capability probe
86
86
 
87
87
  #### Context profile: how the gateway folds a session's context
88
88
 
89
- `--context-profile <off|balanced|aggressive>` picks how the Mnemom gateway folds a
89
+ `--context-profile <off|balanced|aggressive|adaptive>` picks how the Mnemom gateway folds a
90
90
  session's context. Each profile serves a different set of use cases:
91
91
 
92
92
  - **`balanced`** (the default) keeps more of the earlier work verbatim and folds later —
93
93
  for long sessions that revisit earlier files and decisions.
94
94
  - **`aggressive`** folds earlier and keeps a tighter working set — for cost-sensitive
95
95
  sessions and short, focused tasks.
96
+ - **`adaptive`** (opt-in) lets the gateway size the fold to the conversation's original
97
+ context: no fold below 200k tokens (folding a small conversation costs more than it
98
+ saves), the `aggressive` budgets from 200k to 1M, and `balanced` above 1M. It sends
99
+ `CONTEXT_RUNTIME_SIZE_POLICY=banded` in the per-session config; the band thresholds are the
100
+ gateway's defaults.
96
101
  - **`off`** leaves compaction to the coding agent.
97
102
 
98
103
  Set it per launch, as a standing default, or in the environment (flag > env > `launcher.toml`):
@@ -101,10 +106,11 @@ Set it per launch, as a standing default, or in the environment (flag > env > `l
101
106
  mnemom agent my-task --context-profile aggressive # this launch only
102
107
  mnemom agent config set context_profile aggressive # persists in ~/.mnemom/launcher.toml
103
108
  export MNEMOM_AGENT_CONTEXT_PROFILE=aggressive # for every launch in this shell
109
+ mnemom agent my-task --context-profile adaptive # size-banded folding, this launch only
104
110
  ```
105
111
 
106
112
  `--no-context` (or `context = false` in `launcher.toml`) is the same as `off`. Pass one or the
107
- other: `--no-context` together with `--context-profile balanced` or `aggressive` is refused. A
113
+ other: `--no-context` together with `--context-profile balanced`, `aggressive` or `adaptive` is refused. A
108
114
  `--context-profile` flag overrides a standing `context = false` in `launcher.toml`. `--dry-run`
109
115
  prints the resolved profile and, when the launch sends the per-session config header, the
110
116
  decoded key/value list; `mnemom agent show` and the session ledger record the profile.
@@ -2,11 +2,13 @@
2
2
  * `mnemom agent doctor` — a read-only preflight for `mnemom agent`. It checks the
3
3
  * things a governed launch needs and prints a checklist with clear, actionable
4
4
  * remediation, so a customer can see at a glance why a launch would fail before
5
- * it does. Writes nothing and reads no secret VALUE (only whether a key is
6
- * resolvable). Exits non-zero when the machine is not launch-ready (no coding
7
- * agent CLI, or no Anthropic key), so it can gate a script.
5
+ * it does. Writes nothing and prints no secret VALUE (the Mnemom key is sent to the
6
+ * Mnemom API to check it, exactly as a launch does). Exits non-zero when the machine is
7
+ * not launch-ready (no coding agent CLI, or no Anthropic key), so it can gate a script.
8
8
  *
9
- * Checks: settings file, coding-agent CLI, Anthropic key source, gateway health
9
+ * Checks: settings file, coding-agent CLI, Anthropic key source, Mnemom API key source and
10
+ * whether it is still active (every launch sends one; none yet is informational — the launch
11
+ * mints it; a saved key proven dead is a warning — the launch re-mints it), gateway health
10
12
  * (200 + the x-mnemom-verdict header that proves the governance pipeline is
11
13
  * live), Remote-Control capability (node + openssl + the --remote-control flag),
12
14
  * claude.ai login (informational — Remote Control needs it), and CLI auto-update status.
@@ -17,6 +19,21 @@ export interface DoctorOptions {
17
19
  }
18
20
  /** Run the preflight and print the checklist. Sets process.exitCode on failure. */
19
21
  export declare function agentDoctorCommand(options?: DoctorOptions): Promise<void>;
22
+ /**
23
+ * The Mnemom API key row: where the key a launch would send comes from, and whether it passes
24
+ * the launch's own one-time check (commands/agent.ts verifyLocalMnemomKey). A key counts as dead
25
+ * only when proven (lib/subscription-login.ts checkMnemomKey), so only a saved key this CLI
26
+ * minted can be:
27
+ * valid → ok
28
+ * saved key, invalid → warn (the next launch mints a new one and revokes the old)
29
+ * anything else → info (not verified: a launch sends it as is)
30
+ * none → info (the next launch mints one for the launch's org)
31
+ */
32
+ export declare function mnemomKeyRow(): Promise<{
33
+ mark: Mark;
34
+ text: string;
35
+ hint?: string;
36
+ }>;
20
37
  export interface CodeAccessProbe {
21
38
  mark: Mark;
22
39
  text: string;
@@ -2,18 +2,20 @@
2
2
  * `mnemom agent doctor` — a read-only preflight for `mnemom agent`. It checks the
3
3
  * things a governed launch needs and prints a checklist with clear, actionable
4
4
  * remediation, so a customer can see at a glance why a launch would fail before
5
- * it does. Writes nothing and reads no secret VALUE (only whether a key is
6
- * resolvable). Exits non-zero when the machine is not launch-ready (no coding
7
- * agent CLI, or no Anthropic key), so it can gate a script.
5
+ * it does. Writes nothing and prints no secret VALUE (the Mnemom key is sent to the
6
+ * Mnemom API to check it, exactly as a launch does). Exits non-zero when the machine is
7
+ * not launch-ready (no coding agent CLI, or no Anthropic key), so it can gate a script.
8
8
  *
9
- * Checks: settings file, coding-agent CLI, Anthropic key source, gateway health
9
+ * Checks: settings file, coding-agent CLI, Anthropic key source, Mnemom API key source and
10
+ * whether it is still active (every launch sends one; none yet is informational — the launch
11
+ * mints it; a saved key proven dead is a warning — the launch re-mints it), gateway health
10
12
  * (200 + the x-mnemom-verdict header that proves the governance pipeline is
11
13
  * live), Remote-Control capability (node + openssl + the --remote-control flag),
12
14
  * claude.ai login (informational — Remote Control needs it), and CLI auto-update status.
13
15
  */
14
16
  import { spawnSync } from "node:child_process";
15
17
  import { existsSync } from "node:fs";
16
- import { anthropicKeySource, checkRcCapability, defaultConsoleKeyDeps, resolveCliBin, } from "./agent.js";
18
+ import { anthropicKeySource, checkRcCapability, defaultConsoleKeyDeps, localLaunchMnemomKey, verifyLocalMnemomKey, resolveCliBin, } from "./agent.js";
17
19
  import { readConsoleKey } from "../lib/console-key.js";
18
20
  import { resolveAgentAuth } from "../lib/subscription-login.js";
19
21
  import { isProdGateway, resolveAnthropicDoor, resolveGatewayHost, singleCellError, } from "../lib/agent.js";
@@ -73,6 +75,9 @@ export async function agentDoctorCommand(options = {}) {
73
75
  else
74
76
  add("miss", "Anthropic key: none found", "export MNEMOM_AGENT_ANTHROPIC_KEY=sk-ant-… (or ANTHROPIC_API_KEY), or run `mnemom agent` once and accept the save prompt");
75
77
  }
78
+ // ── Mnemom API key: every launch sends one, whatever the auth mode ──
79
+ const keyRow = await mnemomKeyRow();
80
+ add(keyRow.mark, keyRow.text, keyRow.hint);
76
81
  // ── one cell: the launch door must be the CLI's own cell ──
77
82
  const cellError = singleCellError({
78
83
  door: resolveAnthropicDoor(env),
@@ -176,6 +181,47 @@ function claudeLoggedIn(bin) {
176
181
  return null;
177
182
  }
178
183
  }
184
+ const MNEMOM_KEY_MINT_HINT = "minting needs a signed-in session (`mnemom login`) and an org role that may mint a gateway key (owner, admin or member); or ask an org owner/admin for an org API key with the `gateway` scope and set MNEMOM_AGENT_MNEMOM_KEY";
185
+ /**
186
+ * The Mnemom API key row: where the key a launch would send comes from, and whether it passes
187
+ * the launch's own one-time check (commands/agent.ts verifyLocalMnemomKey). A key counts as dead
188
+ * only when proven (lib/subscription-login.ts checkMnemomKey), so only a saved key this CLI
189
+ * minted can be:
190
+ * valid → ok
191
+ * saved key, invalid → warn (the next launch mints a new one and revokes the old)
192
+ * anything else → info (not verified: a launch sends it as is)
193
+ * none → info (the next launch mints one for the launch's org)
194
+ */
195
+ export async function mnemomKeyRow() {
196
+ const local = localLaunchMnemomKey();
197
+ const org = getActiveOrg();
198
+ const orgLabel = org ? `org ${org.slug}` : "no active org";
199
+ if (!local) {
200
+ return {
201
+ mark: "info",
202
+ text: `Mnemom API key: none yet for ${orgLabel} — the next launch mints a gateway-only org key and saves it`,
203
+ hint: MNEMOM_KEY_MINT_HINT,
204
+ };
205
+ }
206
+ const where = local.source === "env"
207
+ ? "MNEMOM_AGENT_MNEMOM_KEY (environment)"
208
+ : `~/.mnemom/launcher.json (saved for ${orgLabel})`;
209
+ const verdict = await verifyLocalMnemomKey(local);
210
+ if (verdict === "valid")
211
+ return { mark: "ok", text: `Mnemom API key: ${where} — verified` };
212
+ if (verdict === "invalid" && local.source === "store") {
213
+ return {
214
+ mark: "warn",
215
+ text: `Mnemom API key: the key saved for ${orgLabel} is no longer active (revoked or rotated) — the next launch mints a new one`,
216
+ hint: MNEMOM_KEY_MINT_HINT,
217
+ };
218
+ }
219
+ return {
220
+ mark: "info",
221
+ text: `Mnemom API key: ${where} — not verified (API unreachable, not signed in, or a gateway-only key the API cannot look up); a launch sends it as is`,
222
+ hint: "sign in (`mnemom login`) so the doctor and each launch can check a saved key; the gateway refuses a dead key with a clear message",
223
+ };
224
+ }
179
225
  /**
180
226
  * The invited-cohort gate, as the doctor reports it. Signed out → info (we can't
181
227
  * check without a session); enabled → ok with the reason; a determined
@@ -31,7 +31,7 @@ export interface GoalCommandDeps {
31
31
  }
32
32
  /**
33
33
  * The Anthropic key the launch would resolve (env, then ~/.mnemom/launcher.json), never prompted
34
- * for. Lazy import: commands/agent.ts is the launcher and carries a heavy import graph.
34
+ * for, plus the Mnemom key the launch sent (null when this machine has none). Lazy import: commands/agent.ts is the launcher and carries a heavy import graph.
35
35
  */
36
36
  export declare function resolveLaunchCreds(): Promise<GoalControlCreds>;
37
37
  export declare const liveGoalDeps: GoalCommandDeps;
@@ -24,17 +24,20 @@ import { askYesNo, isInteractive } from "../lib/prompt.js";
24
24
  import { localGoalFlag, resolveSessionRef } from "./agent-sessions.js";
25
25
  /**
26
26
  * The Anthropic key the launch would resolve (env, then ~/.mnemom/launcher.json), never prompted
27
- * for. Lazy import: commands/agent.ts is the launcher and carries a heavy import graph.
27
+ * for, plus the Mnemom key the launch sent (null when this machine has none). Lazy import: commands/agent.ts is the launcher and carries a heavy import graph.
28
28
  */
29
29
  export async function resolveLaunchCreds() {
30
- const { resolveAnthropicKey } = await import("./agent.js");
30
+ const agentMod = await import("./agent.js");
31
+ let anthropicKey;
31
32
  try {
32
- return { anthropicKey: await resolveAnthropicKey(process.env, { allowPrompt: false }) };
33
+ anthropicKey = await agentMod.resolveAnthropicKey(process.env, { allowPrompt: false });
33
34
  }
34
35
  catch {
35
36
  throw new Error("no Anthropic key in env (MNEMOM_AGENT_ANTHROPIC_KEY / ANTHROPIC_API_KEY) or ~/.mnemom/launcher.json — " +
36
37
  "the goal commands authenticate with the same key the session launched with");
37
38
  }
39
+ // The Mnemom key the launch sent too (env, then the store — never minted here).
40
+ return { anthropicKey, mnemomKey: agentMod.localLaunchMnemomKey()?.key ?? null };
38
41
  }
39
42
  export const liveGoalDeps = {
40
43
  readRecords: () => readSessionRecords({ dir: MNEMOM_DIR }).reverse(),
@@ -68,6 +68,15 @@ export interface EnsureAgentOptions {
68
68
  slug: string;
69
69
  /** The customer's Anthropic key (for the birth call + hash-proof). Never logged. */
70
70
  anthropicKey: string;
71
+ /**
72
+ * The launch's Mnemom API key, sent on the gateway probe/birth call (x-mnemom-api-key, with a
73
+ * no-op x-mnemom-session-config — see birthThroughGateway). That makes the call Mnemom agent
74
+ * traffic: the gateway verifies the key and births a new agent in the key's org — the active
75
+ * org, else the personal org, i.e. the launch org the key was minted for. The claim below
76
+ * records the claim in that same org, which the gateway's agent-traffic org check requires of
77
+ * every governed turn. Never logged.
78
+ */
79
+ mnemomKey?: string;
71
80
  /** undefined = auto, true = force (--setup), false handled by the caller (skip). */
72
81
  setup?: boolean;
73
82
  /** Gateway host the launch targets (birth goes to the same cell). */
@@ -157,11 +166,13 @@ export declare function ensureSessionAndBalance(opts: {
157
166
  }>;
158
167
  /**
159
168
  * The account for a launch an orchestrator already preflighted
160
- * (`MNEMOM_AGENT_PREFLIGHTED=1`, see launchPreflighted): no session prompt, no
161
- * personal-org lookup, no µ-balance read. The entitlement is still fetched — it
162
- * is the access gate and decides Remote Control fail-closed, which a caller's
163
- * preflight can't vouch for. With no active org the api resolves the caller's
164
- * primary org, and the ledger records the org id the entitlement names.
169
+ * (`MNEMOM_AGENT_PREFLIGHTED=1`, see launchPreflighted): no session prompt and no
170
+ * µ-balance read. The launch org resolves exactly as on a normal launch — the
171
+ * active org, else the caller's personal org — because the launch's Mnemom key is
172
+ * minted for it and the agent is claimed into it (the gateway requires the agent's
173
+ * org to be the key's org). The entitlement is still fetched for that org — it is
174
+ * the access gate and decides Remote Control fail-closed, which a caller's
175
+ * preflight can't vouch for.
165
176
  */
166
177
  export declare function resolvePreflightedAccount(): Promise<{
167
178
  orgId: string;
@@ -34,7 +34,8 @@ import { configKeySpec, loadLauncherConfig, writeLauncherConfig } from "../lib/l
34
34
  import { readServedAgent, servedFingerprint, writeServedAgent } from "../lib/served-agent-cache.js";
35
35
  import { deriveHashProof } from "./agents.js";
36
36
  import { birthThroughGateway } from "./wrap.js";
37
- import { resolveAnthropicKey } from "./agent.js";
37
+ import { defaultMnemomKeyDeps, resolveAnthropicKey } from "./agent.js";
38
+ import { resolveLaunchMnemomKey } from "../lib/subscription-login.js";
38
39
  import { assertCodeEnabled, CodeNotEnabledError } from "./agent-invite.js";
39
40
  const say = (line = "") => console.error(line);
40
41
  /**
@@ -145,6 +146,7 @@ export async function ensureGovernedAgent(opts) {
145
146
  cached ??
146
147
  (await birthThroughGateway(gatewayUrl, "anthropic", slug, opts.anthropicKey, {
147
148
  timeoutMs: opts.setup === true ? undefined : SERVED_PROBE_TIMEOUT_MS,
149
+ mnemomKey: opts.mnemomKey,
148
150
  }));
149
151
  }
150
152
  catch (err) {
@@ -206,7 +208,9 @@ export async function ensureGovernedAgent(opts) {
206
208
  }
207
209
  // 5. Birth → claim → publish observe-only cards. (Key never logged.)
208
210
  const gatewayUrl = opts.gatewayHost.replace(/\/+$/, "");
209
- const agentId = await birthThroughGateway(gatewayUrl, "anthropic", slug, opts.anthropicKey);
211
+ const agentId = await birthThroughGateway(gatewayUrl, "anthropic", slug, opts.anthropicKey, {
212
+ mnemomKey: opts.mnemomKey,
213
+ });
210
214
  const hashProof = deriveHashProof(opts.anthropicKey, slug);
211
215
  await claimAgent(agentId, { hashProof, orgId: org?.org_id });
212
216
  say(fmt.success(`mnemom agent: claimed '${slug}' (${agentId}) in ${orgLabel}.`));
@@ -322,8 +326,9 @@ export async function agentSetupCommand(opts = {}) {
322
326
  if (cellError)
323
327
  throw new Error(cellError.replace("mnemom agent:", "mnemom agent setup:"));
324
328
  // Sign in (offer sign-up) and enforce the MU balance before any account write.
329
+ let launchOrgId;
325
330
  try {
326
- await ensureSessionAndBalance({});
331
+ launchOrgId = (await ensureSessionAndBalance({})).orgId;
327
332
  }
328
333
  catch (err) {
329
334
  if (isQuietPreambleExit(err))
@@ -338,7 +343,16 @@ export async function agentSetupCommand(opts = {}) {
338
343
  : await resolveDefaultSlug({ strict: true });
339
344
  if (!slug)
340
345
  throw new Error("mnemom agent setup: agent slug sanitised to empty — pass --agent <slug>.");
341
- const result = await ensureGovernedAgent({ slug, anthropicKey, setup: true, gatewayHost });
346
+ // The birth call carries the same Mnemom key every launch sends, minted for the org the agent
347
+ // is claimed into (see EnsureAgentOptions.mnemomKey).
348
+ const mnemomKey = await resolveLaunchMnemomKey(defaultMnemomKeyDeps(undefined, launchOrgId));
349
+ const result = await ensureGovernedAgent({
350
+ slug,
351
+ anthropicKey,
352
+ mnemomKey,
353
+ setup: true,
354
+ gatewayHost,
355
+ });
342
356
  if (!result.provisioned) {
343
357
  say(fmt.dim(` '${slug}' is ready (already claimed) or setup was skipped.`));
344
358
  }
@@ -508,17 +522,20 @@ export async function ensureSessionAndBalance(opts) {
508
522
  }
509
523
  /**
510
524
  * The account for a launch an orchestrator already preflighted
511
- * (`MNEMOM_AGENT_PREFLIGHTED=1`, see launchPreflighted): no session prompt, no
512
- * personal-org lookup, no µ-balance read. The entitlement is still fetched — it
513
- * is the access gate and decides Remote Control fail-closed, which a caller's
514
- * preflight can't vouch for. With no active org the api resolves the caller's
515
- * primary org, and the ledger records the org id the entitlement names.
525
+ * (`MNEMOM_AGENT_PREFLIGHTED=1`, see launchPreflighted): no session prompt and no
526
+ * µ-balance read. The launch org resolves exactly as on a normal launch — the
527
+ * active org, else the caller's personal org — because the launch's Mnemom key is
528
+ * minted for it and the agent is claimed into it (the gateway requires the agent's
529
+ * org to be the key's org). The entitlement is still fetched for that org — it is
530
+ * the access gate and decides Remote Control fail-closed, which a caller's
531
+ * preflight can't vouch for.
516
532
  */
517
533
  export async function resolvePreflightedAccount() {
518
534
  const active = getActiveOrg();
519
- const orgLabel = active ? `${active.name} (${active.slug})` : "your primary org";
520
- const entitlement = await assertCodeEnabled(active?.org_id ?? "", orgLabel);
521
- return { orgId: active?.org_id ?? entitlement?.org_id ?? "", orgLabel, entitlement };
535
+ const orgId = active?.org_id ?? (await getMyPersonalOrg()).org_id;
536
+ const orgLabel = active ? `${active.name} (${active.slug})` : "your personal org";
537
+ const entitlement = await assertCodeEnabled(orgId, orgLabel);
538
+ return { orgId, orgLabel, entitlement };
522
539
  }
523
540
  // ── The default coding posture (cards observe-only; goal contracts nudge) ────
524
541
  function buildCodeAlignmentCard(agentId) {
@@ -25,7 +25,7 @@
25
25
  * line, or the proxy's stdin under RC). It is never logged, printed, or passed as
26
26
  * an argv value.
27
27
  */
28
- import { type MnemomKeyDeps } from "../lib/subscription-login.js";
28
+ import { type LocalMnemomKey, type MnemomKeyCheck, type MnemomKeyDeps, type StoredMnemomKey } from "../lib/subscription-login.js";
29
29
  import { type SessionRecord } from "../lib/agent-ledger.js";
30
30
  import { type ExperimentalId } from "../lib/experimental.js";
31
31
  import { type ConsoleKeyDeps } from "../lib/console-key.js";
@@ -65,9 +65,9 @@ export interface AgentOptions {
65
65
  */
66
66
  context?: boolean;
67
67
  /**
68
- * How the gateway folds this session's context (`--context-profile`): `off`, `balanced` or
69
- * `aggressive`. Undefined ⇒ MNEMOM_AGENT_CONTEXT_PROFILE (the `context_profile` setting), else
70
- * `balanced`. `--no-context` is `off`; combined with balanced|aggressive the launch refuses.
68
+ * How the gateway folds this session's context (`--context-profile`): `off`, `balanced`,
69
+ * `aggressive` or `adaptive`. Undefined ⇒ MNEMOM_AGENT_CONTEXT_PROFILE (the `context_profile` setting), else
70
+ * `balanced`. `--no-context` is `off`; combined with balanced|aggressive|adaptive the launch refuses.
71
71
  */
72
72
  contextProfile?: ContextProfile;
73
73
  /**
@@ -200,8 +200,30 @@ export declare function recordSessionLaunch(ctx: {
200
200
  /** The resolved compaction target this launch runs under (`resolveCompactAt`). */
201
201
  compactAt: number | null;
202
202
  }): Promise<void>;
203
- /** The real I/O behind a subscription launch's Mnemom key (lib/subscription-login.ts). */
204
- export declare function defaultMnemomKeyDeps(storePath?: string): MnemomKeyDeps;
203
+ /** Per-call timeout of the launch's Mnemom-key check: a slow API must not hold up a launch. */
204
+ export declare const MNEMOM_KEY_CHECK_TIMEOUT_MS = 2500;
205
+ /**
206
+ * Mint the launch's key: an ORG-owned key for `orgId` (the launch's org) with scopes exactly
207
+ * ["gateway"], which any owner/admin/member may mint — so the gateway's agent-traffic org check
208
+ * (agent org = key org) passes for the agent the launcher claims into that org. Never a personal
209
+ * key: it has no org, and the gateway would refuse every governed turn with it. A refusal (403:
210
+ * an API that predates member org keys, or a viewer/auditor role) is thrown as is; the launch
211
+ * stops with guidance (lib/subscription-login.ts mintAndStore).
212
+ */
213
+ export declare function mintLaunchMnemomKey(orgId: string): Promise<StoredMnemomKey>;
214
+ /**
215
+ * The real I/O behind every launch's Mnemom key (lib/subscription-login.ts). `launchOrgId` is
216
+ * the org the launch runs in (ensureSessionAndBalance's `orgId`: the active org, else the
217
+ * caller's personal org); omitted or empty, it is the active org.
218
+ */
219
+ export declare function defaultMnemomKeyDeps(storePath?: string, launchOrgId?: string | null): MnemomKeyDeps;
220
+ /**
221
+ * The Mnemom key already on this machine (MNEMOM_AGENT_MNEMOM_KEY, then ~/.mnemom/launcher.json),
222
+ * never minted: `mnemom agent doctor` reports its source, the goal commands send it.
223
+ */
224
+ export declare function localLaunchMnemomKey(storePath?: string): LocalMnemomKey | null;
225
+ /** The launch's one-time check of that key (`mnemom agent doctor` reports it). Never throws. */
226
+ export declare function verifyLocalMnemomKey(local: LocalMnemomKey): Promise<MnemomKeyCheck>;
205
227
  /** The real machine behind lib/console-key.ts: the macOS keychain via `security`, no shell. */
206
228
  export declare function defaultConsoleKeyDeps(env: NodeJS.ProcessEnv): ConsoleKeyDeps;
207
229
  /**
@@ -33,10 +33,10 @@ import { basename, join, dirname } from "node:path";
33
33
  import { fileURLToPath } from "node:url";
34
34
  import { statuslineLaunch } from "../lib/statusline.js";
35
35
  import { getApiUrl, getGatewayUrl, MNEMOM_DIR } from "../lib/config.js";
36
- import { createApiKey, getAgentByName } from "../lib/api.js";
37
- import { MNEMOM_KEY_STORE_FIELD, resolveAgentAuth, resolveSubscriptionMnemomKey, subscriptionChildEnv, subscriptionShape, } from "../lib/subscription-login.js";
36
+ import { apiAcceptsMnemomKey, createOrgApiKey, getAgentByName, listOwnApiKeysForCheck, revokeApiKey, } from "../lib/api.js";
37
+ import { checkMnemomKey, MNEMOM_KEY_ENV, readLocalMnemomKey, readStoredMnemomKey, resolveAgentAuth, resolveLaunchMnemomKey, storePatchForMnemomKey, subscriptionChildEnv, subscriptionShape, } from "../lib/subscription-login.js";
38
38
  import { LEDGER_FILE, appendSessionRecord, findResumeCandidate, readSessionRecords, resolveRetentionDays, toLedgerContract, } from "../lib/agent-ledger.js";
39
- import { loadCliConfig } from "../lib/cli-config.js";
39
+ import { getActiveOrg, loadCliConfig } from "../lib/cli-config.js";
40
40
  import { configKeySpec, loadLauncherConfig, writeLauncherConfig } from "../lib/launcher-config.js";
41
41
  import { experimentalNotice } from "../lib/experimental.js";
42
42
  import { fmt } from "../lib/format.js";
@@ -45,8 +45,8 @@ import { authConfigured, chooseAuth, detectClaudeLogin, readClaudeLoginState, }
45
45
  import { requireConsoleKey, readConsoleKey } from "../lib/console-key.js";
46
46
  import { goalAlignmentLine, resolveSessionSetup } from "./agent-session.js";
47
47
  import { AgentIdentityMismatchError, defaultAgentSlug, ensureGovernedAgent, ensureSessionAndBalance, isQuietPreambleExit, resolveDefaultSlug, resolvePreflightedAccount, } from "./agent-setup.js";
48
- import { assembleContract, buildGoalModeHeader, buildCustomHeaders, buildHandoffMcpConfigJson, buildSessionConfig, buildSessionConfigB64, assertCompactAtCompatible, compactAtWindowWarning, describeCompactAt, launchWindow, resolveCompactAt, applyGatewayHintHeaders, resolveCompactionIntercept, resolveContextHandoff, resolveContextProfile, resolveHandoffGatewayHost, HANDOFF_RC_KEY_ENV_NAME, isProdGateway, launchPreferenceExplicit, launchPreflighted, remoteControlAllowed, applyToolSearchDefault, DISABLE_1M_ENV, readCcSettings, resolveWindowModel, resolveAnthropicDoor, resolveLaunchModel, resolveConversationId, resolveGatewayHost, singleCellError, resolveLaunchShape, resolveRemoteControlShape, passthroughName, sanitizeAgentName, sessionDisplayName, SESSION_NAME_ENV, SESSION_CONFIG_HEADER, } from "../lib/agent.js";
49
- import { LAUNCHER_STORE_PATH, mergeStore } from "../lib/launcher-store.js";
48
+ import { assembleContract, buildGoalModeHeader, buildCustomHeaders, buildHandoffMcpConfigJson, buildSessionConfig, buildSessionConfigB64, assertCompactAtCompatible, compactAtWindowWarning, describeCompactAt, launchWindow, resolveCompactAt, applyGatewayHintHeaders, resolveCompactionIntercept, resolveContextHandoff, resolveContextProfile, resolveHandoffGatewayHost, HANDOFF_RC_KEY_ENV_NAME, HANDOFF_RC_MNEMOM_KEY_ENV_NAME, isProdGateway, launchPreferenceExplicit, launchPreflighted, remoteControlAllowed, applyToolSearchDefault, DISABLE_1M_ENV, readCcSettings, resolveWindowModel, resolveAnthropicDoor, resolveLaunchModel, resolveConversationId, resolveGatewayHost, singleCellError, resolveLaunchShape, resolveRemoteControlShape, passthroughName, sanitizeAgentName, sessionDisplayName, SESSION_NAME_ENV, SESSION_CONFIG_HEADER, } from "../lib/agent.js";
49
+ import { LAUNCHER_STORE_PATH, mergeStore, readStore } from "../lib/launcher-store.js";
50
50
  import { slackChannelArgs } from "../lib/slack-launch.js";
51
51
  /** The CLI's own provider-key store (zero 1Password): ~/.mnemom/launcher.json, 0600. */
52
52
  const CODE_STORE = LAUNCHER_STORE_PATH;
@@ -64,6 +64,9 @@ function sayContextProfile(profile) {
64
64
  else if (profile === "aggressive") {
65
65
  say("mnemom agent: context profile aggressive — the gateway folds earlier and keeps a tighter working set.");
66
66
  }
67
+ else if (profile === "adaptive") {
68
+ say("mnemom agent: context profile adaptive — the gateway sizes the fold to the conversation: none below 200k tokens, aggressive up to 1M, balanced above.");
69
+ }
67
70
  }
68
71
  /**
69
72
  * The one-line launch-banner note for the resolved compaction target (`resolveCompactAt`):
@@ -299,8 +302,9 @@ export async function agentCommand(scenarioArg, options = {}) {
299
302
  // lives in (default: the user's personal org). No µ ⇒ blocked with a
300
303
  // portal-style top-up message. Skipped only on --dry-run (handled above).
301
304
  // MNEMOM_AGENT_PREFLIGHTED=1 (orchestrators such as the ADW fleet that already
302
- // ran their own session + balance preflight) skips those round trips; the
303
- // entitlement is still fetched — see resolvePreflightedAccount.
305
+ // ran their own session + balance preflight) skips those round trips; the launch
306
+ // org resolves the same way and its entitlement is still fetched — see
307
+ // resolvePreflightedAccount.
304
308
  let account;
305
309
  try {
306
310
  account = launchPreflighted(env)
@@ -340,14 +344,19 @@ export async function agentCommand(scenarioArg, options = {}) {
340
344
  rcCapable: rc.ok,
341
345
  say,
342
346
  });
343
- // Subscription login: Remote Control only for RC-entitled (internal) accounts, and the governed identity anchors on a
344
- // Mnemom API key (minted once and stored if there is none). Resolved after sign-in so
345
- // minting can use the session.
346
- let mnemomKey;
347
+ // Subscription login: Remote Control only for RC-entitled (internal) accounts.
347
348
  if (auth === "subscription") {
348
349
  shape = subscriptionShape(shape, shapeExplicit, rcAllowed, say);
349
- mnemomKey = await resolveSubscriptionMnemomKey(defaultMnemomKeyDeps());
350
350
  }
351
+ // Every launch — api-key, console and subscription, every shape — sends a Mnemom API key
352
+ // (x-mnemom-api-key): the gateway refuses `mnemom agent` traffic without a verified one.
353
+ // Resolved after sign-in so minting and the one-time liveness check can use the session: the
354
+ // key stored for the active org, checked once (a revoked/rotated one is re-minted), else a
355
+ // fresh key minted for the launch's org (account.orgId: the active org, else the personal
356
+ // org — the org the agent is claimed into, which the gateway's org check requires of the key)
357
+ // and stored. No key ⇒ this throws and the launch does not start (a session the gateway
358
+ // would refuse is worse than an actionable error).
359
+ const mnemomKey = await resolveLaunchMnemomKey(defaultMnemomKeyDeps(CODE_STORE, account.orgId));
351
360
  // Now that a session exists, a defaulted slug uses the real login handle from
352
361
  // /v1/auth/me (the stored token has no email, so the pre-sign-in value was the
353
362
  // "agent-user" fallback). Only when the caller didn't name an agent. Under an
@@ -378,6 +387,7 @@ export async function agentCommand(scenarioArg, options = {}) {
378
387
  const ensured = await ensureGovernedAgent({
379
388
  slug: agent,
380
389
  anthropicKey,
390
+ mnemomKey,
381
391
  setup: options.setup,
382
392
  gatewayHost,
383
393
  });
@@ -477,15 +487,22 @@ export async function agentCommand(scenarioArg, options = {}) {
477
487
  // back out at request time. Remote Control (both shapes) strips every ANTHROPIC_* auth
478
488
  // var from the child's env, so `spawnRcCli` below instead sets a dedicated, non-ANTHROPIC
479
489
  // var (HANDOFF_RC_KEY_ENV_NAME) on that same child env — still nothing in this file.
480
- const anthropicKeySource = shape === "terminal"
490
+ // The Mnemom key the gateway requires rides the same way: its `x-mnemom-api-key:` line
491
+ // in ANTHROPIC_CUSTOM_HEADERS (terminal), or HANDOFF_RC_MNEMOM_KEY_ENV_NAME (RC).
492
+ const terminal = shape === "terminal";
493
+ const anthropicKeySource = terminal
481
494
  ? { envName: "ANTHROPIC_CUSTOM_HEADERS" }
482
495
  : { envName: HANDOFF_RC_KEY_ENV_NAME };
496
+ const mnemomKeySource = terminal
497
+ ? { envName: "ANTHROPIC_CUSTOM_HEADERS" }
498
+ : { envName: HANDOFF_RC_MNEMOM_KEY_ENV_NAME };
483
499
  handoffMcpConfigPath = writeHandoffMcpConfigFile(buildHandoffMcpConfigJson({
484
500
  // The SAME origin the session's own model traffic goes to — not resolveGatewayHost,
485
501
  // which would ignore a MNEMOM_AGENT_ANTHROPIC_GATEWAY override (a test-cell launch
486
502
  // must never send its handoff calls to prod, or vice versa).
487
503
  gatewayHost: resolveHandoffGatewayHost(door),
488
504
  anthropicKeySource,
505
+ mnemomKeySource,
489
506
  agent,
490
507
  conversationId,
491
508
  sessionConfigB64,
@@ -703,25 +720,55 @@ export async function recordSessionLaunch(ctx) {
703
720
  // ───────────────────────────────────────────────────────────────────────────
704
721
  // Credential resolution (zero 1Password)
705
722
  // ───────────────────────────────────────────────────────────────────────────
706
- /** The real I/O behind a subscription launch's Mnemom key (lib/subscription-login.ts). */
707
- export function defaultMnemomKeyDeps(storePath = CODE_STORE) {
723
+ /** Per-call timeout of the launch's Mnemom-key check: a slow API must not hold up a launch. */
724
+ export const MNEMOM_KEY_CHECK_TIMEOUT_MS = 2500;
725
+ /**
726
+ * Mint the launch's key: an ORG-owned key for `orgId` (the launch's org) with scopes exactly
727
+ * ["gateway"], which any owner/admin/member may mint — so the gateway's agent-traffic org check
728
+ * (agent org = key org) passes for the agent the launcher claims into that org. Never a personal
729
+ * key: it has no org, and the gateway would refuse every governed turn with it. A refusal (403:
730
+ * an API that predates member org keys, or a viewer/auditor role) is thrown as is; the launch
731
+ * stops with guidance (lib/subscription-login.ts mintAndStore).
732
+ */
733
+ export async function mintLaunchMnemomKey(orgId) {
734
+ const k = await createOrgApiKey(orgId, `mnemom-agent ${hostname()}`, ["gateway"]);
735
+ return { key: k.key, keyId: k.key_id };
736
+ }
737
+ /**
738
+ * The real I/O behind every launch's Mnemom key (lib/subscription-login.ts). `launchOrgId` is
739
+ * the org the launch runs in (ensureSessionAndBalance's `orgId`: the active org, else the
740
+ * caller's personal org); omitted or empty, it is the active org.
741
+ */
742
+ export function defaultMnemomKeyDeps(storePath = CODE_STORE, launchOrgId) {
743
+ const activeOrgId = getActiveOrg()?.org_id || null;
708
744
  return {
709
745
  env: process.env,
710
- readStored: () => {
711
- try {
712
- const data = JSON.parse(readFileSync(storePath, "utf8"));
713
- const v = data[MNEMOM_KEY_STORE_FIELD];
714
- return typeof v === "string" ? stripCrlf(v) : undefined;
715
- }
716
- catch {
717
- return undefined;
718
- }
719
- },
720
- mint: async () => (await createApiKey(`mnemom-agent ${hostname()}`, ["gateway"])).key,
721
- store: (key) => mergeStore({ [MNEMOM_KEY_STORE_FIELD]: key }, storePath),
746
+ activeOrgId,
747
+ launchOrgId: launchOrgId || activeOrgId,
748
+ readStored: (orgId) => readStoredMnemomKey(readStore(storePath), orgId),
749
+ mint: mintLaunchMnemomKey,
750
+ store: (orgId, key) => mergeStore(storePatchForMnemomKey(readStore(storePath), orgId, key), storePath),
751
+ check: (key, keyId) => checkMnemomKey(key, keyId, {
752
+ apiAccepts: (k) => apiAcceptsMnemomKey(k, MNEMOM_KEY_CHECK_TIMEOUT_MS),
753
+ listOwnKeys: () => listOwnApiKeysForCheck(MNEMOM_KEY_CHECK_TIMEOUT_MS),
754
+ }),
755
+ // DELETE /v1/api-keys/:key_id revokes only keys the signed-in user created (org keys
756
+ // included), so a replaced key minted by someone else is never touched.
757
+ revoke: (keyId) => revokeApiKey(keyId, { timeoutMs: MNEMOM_KEY_CHECK_TIMEOUT_MS }),
722
758
  say,
723
759
  };
724
760
  }
761
+ /**
762
+ * The Mnemom key already on this machine (MNEMOM_AGENT_MNEMOM_KEY, then ~/.mnemom/launcher.json),
763
+ * never minted: `mnemom agent doctor` reports its source, the goal commands send it.
764
+ */
765
+ export function localLaunchMnemomKey(storePath = CODE_STORE) {
766
+ return readLocalMnemomKey(defaultMnemomKeyDeps(storePath));
767
+ }
768
+ /** The launch's one-time check of that key (`mnemom agent doctor` reports it). Never throws. */
769
+ export function verifyLocalMnemomKey(local) {
770
+ return defaultMnemomKeyDeps().check(local.key, local.keyId);
771
+ }
725
772
  /** The real machine behind lib/console-key.ts: the macOS keychain via `security`, no shell. */
726
773
  export function defaultConsoleKeyDeps(env) {
727
774
  return {
@@ -997,6 +1044,8 @@ function launchTerminal(ctx) {
997
1044
  if (ctx.anthropicKey) {
998
1045
  childEnv = { ...process.env };
999
1046
  delete childEnv.ANTHROPIC_API_KEY;
1047
+ // The Mnemom key already rides in the headers; the child has no other use for it.
1048
+ Reflect.deleteProperty(childEnv, MNEMOM_KEY_ENV);
1000
1049
  childEnv.ANTHROPIC_BASE_URL = ctx.door;
1001
1050
  childEnv.ANTHROPIC_AUTH_TOKEN = "mnemom-gateway";
1002
1051
  childEnv.ANTHROPIC_CUSTOM_HEADERS = headers;
@@ -1181,9 +1230,10 @@ function launchRemoteControl(ctx) {
1181
1230
  }
1182
1231
  };
1183
1232
  process.on("exit", onExit);
1184
- // Secrets on stdin — three lines (anthropic, mnemom, openai). An api-key launch sends the
1185
- // Anthropic key only; a subscription launch sends the Mnemom key only (the identity anchor —
1186
- // the user's OAuth bearer is what pays). openai is always empty on this Anthropic-only door.
1233
+ // Secrets on stdin — three lines (anthropic, mnemom, openai). Every launch sends the Mnemom
1234
+ // key (the proxy adds it as x-mnemom-api-key on every gateway request); an api-key launch
1235
+ // also sends the Anthropic key, a subscription launch leaves that line empty (the user's
1236
+ // OAuth bearer is what pays). openai is always empty on this Anthropic-only door.
1187
1237
  // A proxy that exits before reading them turns this write into an EPIPE; that is
1188
1238
  // not a failure of its own — the exited-before-READY check below refuses the
1189
1239
  // launch. Any other stdin error fails closed like a spawn error.
@@ -1194,7 +1244,7 @@ function launchRemoteControl(ctx) {
1194
1244
  onExit();
1195
1245
  process.exit(1);
1196
1246
  });
1197
- proxy.stdin?.end(`${ctx.anthropicKey ?? ""}\n${ctx.anthropicKey ? "" : (ctx.mnemomKey ?? "")}\n\n`);
1247
+ proxy.stdin?.end(`${ctx.anthropicKey ?? ""}\n${ctx.mnemomKey}\n\n`);
1198
1248
  let stdoutBuf = "";
1199
1249
  const start = Date.now();
1200
1250
  const tryStart = () => {
@@ -1262,6 +1312,9 @@ function spawnRcCli(ctx) {
1262
1312
  "no_proxy",
1263
1313
  "HTTP_PROXY",
1264
1314
  "http_proxy",
1315
+ // The Mnemom key rides to the gateway via the proxy (stdin) and, with handoff on, in
1316
+ // HANDOFF_RC_MNEMOM_KEY_ENV_NAME below; the CLI itself has no use for the launch's env var.
1317
+ MNEMOM_KEY_ENV,
1265
1318
  ]);
1266
1319
  const childEnv = {};
1267
1320
  for (const [k, v] of Object.entries(process.env)) {
@@ -1289,8 +1342,10 @@ function spawnRcCli(ctx) {
1289
1342
  // ride through here ungated), so this rides through untouched. Only set when the tool is
1290
1343
  // actually registered — never on a plain RC launch.
1291
1344
  // (Never on a subscription launch — handoff is turned off there, so there is no key to set.)
1345
+ // The Mnemom key the gateway requires rides beside it in its own non-ANTHROPIC var.
1292
1346
  if (ctx.handoffMcpConfigPath && ctx.anthropicKey) {
1293
1347
  childEnv[HANDOFF_RC_KEY_ENV_NAME] = ctx.anthropicKey;
1348
+ childEnv[HANDOFF_RC_MNEMOM_KEY_ENV_NAME] = ctx.mnemomKey;
1294
1349
  }
1295
1350
  let args;
1296
1351
  if (ctx.shape === "server") {
@@ -26,5 +26,13 @@ export interface WrapOptions {
26
26
  export declare function wrapCommand(options?: WrapOptions): Promise<void>;
27
27
  export declare function birthThroughGateway(gatewayUrl: string, provider: Provider, agentName: string, providerKey: string, opts?: {
28
28
  timeoutMs?: number;
29
+ /**
30
+ * The caller's Mnemom API key, sent as `x-mnemom-api-key` together with a no-op
31
+ * `x-mnemom-session-config` (NOOP_SESSION_CONFIG_B64). The session config makes the call
32
+ * Mnemom agent traffic, so the gateway verifies the key and births a NEW agent in the key's
33
+ * org; the caller's claim step then records the claim in that same org. `mnemom agent`
34
+ * always sends its launch key; `mnemom wrap` sends neither header (plain traffic, as before).
35
+ */
36
+ mnemomKey?: string;
29
37
  }): Promise<string>;
30
38
  export {};