@ashx-j/lunr-dev 0.2.40-dev.60.1 → 0.2.40-dev.62.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/core/agent-session.d.ts +10 -0
  2. package/dist/core/agent-session.js +49 -1
  3. package/dist/core/auth-storage.d.ts +2 -0
  4. package/dist/core/auth-storage.js +5 -0
  5. package/dist/core/model-runtime.d.ts +3 -0
  6. package/dist/core/model-runtime.js +20 -5
  7. package/dist/core/resolve-config-value.d.ts +5 -0
  8. package/dist/core/resolve-config-value.js +16 -0
  9. package/dist/core/saved-login-redaction.d.ts +74 -0
  10. package/dist/core/saved-login-redaction.js +322 -0
  11. package/dist/core/session-manager.d.ts +13 -0
  12. package/dist/core/session-manager.js +19 -8
  13. package/dist/core/subscriptions.d.ts +2 -0
  14. package/dist/core/subscriptions.js +5 -0
  15. package/dist/core/tools/edit.d.ts +11 -4
  16. package/dist/core/tools/edit.js +36 -20
  17. package/dist/modes/interactive/tool-renderers/edit.js +4 -0
  18. package/dist/node-runtime/{agent-session-services-UOVUJAX2.js → agent-session-services-2MOVXNT5.js} +6 -6
  19. package/dist/node-runtime/{builtin-extensions-JNJRND4E.js → builtin-extensions-S23KMP4W.js} +1 -1
  20. package/dist/node-runtime/{chunk-HQ5A4VVO.js → chunk-2EQL4TLM.js} +19 -8
  21. package/dist/node-runtime/{chunk-EJMB4PAV.js → chunk-4JOKLU3I.js} +35 -20
  22. package/dist/node-runtime/{chunk-4OALPI3C.js → chunk-6NUWUTVC.js} +1 -1
  23. package/dist/node-runtime/{chunk-QNFPZIP3.js → chunk-C5PAMN7Y.js} +244 -17
  24. package/dist/node-runtime/{chunk-GX7UZDSI.js → chunk-EWYLZSES.js} +1 -1
  25. package/dist/node-runtime/{chunk-GAWWLIGY.js → chunk-FIDZY4JX.js} +4 -4
  26. package/dist/node-runtime/{chunk-U7MTVVT3.js → chunk-JCL5IRM5.js} +1 -1
  27. package/dist/node-runtime/{chunk-Y7DFMHY5.js → chunk-KV4RBM3L.js} +10 -10
  28. package/dist/node-runtime/{chunk-HYOPEHDE.js → chunk-QQSC6CTJ.js} +1 -1
  29. package/dist/node-runtime/{chunk-RXG6DWO2.js → chunk-S2BEWKPR.js} +3 -3
  30. package/dist/node-runtime/{chunk-S46QLY2F.js → chunk-SJSWJWAT.js} +30 -11
  31. package/dist/node-runtime/{chunk-BQROL43X.js → chunk-TKN7VEZR.js} +11 -11
  32. package/dist/node-runtime/{chunk-QDQAKIVU.js → chunk-TYPA7FJQ.js} +1 -1
  33. package/dist/node-runtime/{chunk-FCINT2KC.js → chunk-VBNMCUV2.js} +2 -2
  34. package/dist/node-runtime/{chunk-2B5RTZA4.js → chunk-XLGSGHTG.js} +1 -1
  35. package/dist/node-runtime/{chunk-XXGJ7Z3C.js → chunk-YVOU5W7H.js} +7 -7
  36. package/dist/node-runtime/{command-6GJNLXGD.js → command-ARYMXJF7.js} +3 -3
  37. package/dist/node-runtime/{commands-2UG5F4VT.js → commands-E3EQFYAC.js} +5 -5
  38. package/dist/node-runtime/{doctor-cli-TU4HVXWP.js → doctor-cli-DWI46VPW.js} +1 -1
  39. package/dist/node-runtime/{export-html-SW3CIZRJ.js → export-html-YM4QKDTD.js} +1 -1
  40. package/dist/node-runtime/{gateway-UDWVYEGX.js → gateway-I7YA6MJ4.js} +9 -9
  41. package/dist/node-runtime/index.js +12 -12
  42. package/dist/node-runtime/{install-cli-YIIFVCFM.js → install-cli-A5HIEOOK.js} +1 -1
  43. package/dist/node-runtime/{interactive-mode-VCPSTUAW.js → interactive-mode-6UDD62TS.js} +9 -9
  44. package/dist/node-runtime/{lunr-cron-3VI5CLK3.js → lunr-cron-FYLIKLSZ.js} +4 -4
  45. package/dist/node-runtime/main.js +8 -8
  46. package/dist/node-runtime/{mobile-commands-HQXEYAF6.js → mobile-commands-CKQHQBEW.js} +2 -2
  47. package/dist/node-runtime/{model-runtime-T552YPXL.js → model-runtime-RFMIP23V.js} +1 -1
  48. package/dist/node-runtime/{pi-subagents-YVVMY4B4.js → pi-subagents-C5FBVY72.js} +3 -3
  49. package/dist/node-runtime/{print-mode-M52NLHKG.js → print-mode-I6R6RWLJ.js} +7 -7
  50. package/dist/node-runtime/rpc-entry.js +8 -8
  51. package/dist/node-runtime/{session-handoff-TEOBWIFW.js → session-handoff-XCKL6SRJ.js} +2 -2
  52. package/dist/node-runtime/{session-manager-I6535F4R.js → session-manager-AGK72CRA.js} +1 -1
  53. package/dist/node-runtime/{setup-7IC2PQIB.js → setup-HF7HDJKG.js} +1 -1
  54. package/dist/node-runtime/{subagent-executor-RTGKJ35C.js → subagent-executor-N6FKWYCK.js} +3 -3
  55. package/dist/node-runtime/{tool-renderers-KL5EPAMN.js → tool-renderers-XZX7BEOM.js} +1 -1
  56. package/docs/extensions.md +3 -1
  57. package/docs/security.md +28 -0
  58. package/examples/extensions/built-in-tool-renderer.ts +2 -0
  59. package/examples/extensions/minimal-mode.ts +2 -0
  60. package/install-lock/package-lock.json +24 -24
  61. package/install-lock/package.json +2 -2
  62. package/npm-shrinkwrap.json +12 -12
  63. package/package.json +4 -4
@@ -277,6 +277,16 @@ export declare class AgentSession {
277
277
  private _getUserMessageText;
278
278
  /** Find the last assistant message in agent state (including aborted ones) */
279
279
  private _findLastAssistantMessage;
280
+ /**
281
+ * Replaces saved-login values (`core/saved-login-redaction.ts`) in the text of a message entering
282
+ * history, in place, so agent state, the loop's context and every later request share it. Every
283
+ * message the agent loop produces passes here at message_end, including its own error and refusal
284
+ * results; `sendCustomMessage` and `recordBashResult` call it for the messages they add outside the
285
+ * loop. Only tool results, custom messages and `!` output are filtered, and only their text: details
286
+ * never reach a request, and the session file gets every line filtered by `SessionManager`. If
287
+ * redaction throws, the text is replaced with SAVED_LOGIN_WITHHELD instead of going on raw.
288
+ */
289
+ private _scrubSavedLogins;
280
290
  private _replaceMessageInPlace;
281
291
  private _emitExtensionEvent;
282
292
  /**
@@ -34,6 +34,7 @@ import { AUTONOMOUS_ADDENDUM, deletePermissionContext, getPermissionMode, initia
34
34
  import { READ_ONLY_MODE_ADDENDUM } from "./plan-mode.js";
35
35
  import { expandPromptTemplate } from "./prompt-templates.js";
36
36
  import { withoutDeletedHeaders } from "./provider-headers.js";
37
+ import { SAVED_LOGIN_WITHHELD } from "./saved-login-redaction.js";
37
38
  import { SessionCompaction } from "./session-compaction.js";
38
39
  import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
39
40
  import { isRetryableError, isRotationError, prepareRetry, tryRotateSubscriptionKey, } from "./session-retry.js";
@@ -167,6 +168,7 @@ export class AgentSession {
167
168
  constructor(config) {
168
169
  this.agent = config.agent;
169
170
  this.sessionManager = config.sessionManager;
171
+ this.sessionManager.setSavedLoginFilter(config.modelRuntime.savedLogins);
170
172
  this.settingsManager = config.settingsManager;
171
173
  const childProcess = isSubagentChildProcess();
172
174
  const parentAutoReview = childProcess ? process.env[SUBAGENT_CHILD_AUTO_REVIEW_ENV] : undefined;
@@ -587,6 +589,10 @@ export class AgentSession {
587
589
  this._activePromptRun?.completion?.messages.push(event.message);
588
590
  // Emit to extensions first
589
591
  await this._emitExtensionEvent(event);
592
+ // After any extension replacement and before listeners, persistence and the next request: the loop
593
+ // adds this same object to its context only after message_end listeners return.
594
+ if (event.type === "message_end")
595
+ this._scrubSavedLogins(event.message);
590
596
  // Notify all listeners
591
597
  this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
592
598
  // Handle session persistence
@@ -657,6 +663,44 @@ export class AgentSession {
657
663
  }
658
664
  return undefined;
659
665
  }
666
+ /**
667
+ * Replaces saved-login values (`core/saved-login-redaction.ts`) in the text of a message entering
668
+ * history, in place, so agent state, the loop's context and every later request share it. Every
669
+ * message the agent loop produces passes here at message_end, including its own error and refusal
670
+ * results; `sendCustomMessage` and `recordBashResult` call it for the messages they add outside the
671
+ * loop. Only tool results, custom messages and `!` output are filtered, and only their text: details
672
+ * never reach a request, and the session file gets every line filtered by `SessionManager`. If
673
+ * redaction throws, the text is replaced with SAVED_LOGIN_WITHHELD instead of going on raw.
674
+ */
675
+ _scrubSavedLogins(message) {
676
+ const savedLogins = this._modelRuntime.savedLogins;
677
+ // Undefined only for test doubles of the model runtime.
678
+ if (!savedLogins)
679
+ return;
680
+ try {
681
+ if (message.role === "toolResult") {
682
+ message.content = savedLogins.redactContent(message.content) ?? message.content;
683
+ }
684
+ else if (message.role === "custom") {
685
+ message.content = savedLogins.redactMessageContent(message.content);
686
+ }
687
+ else if (message.role === "bashExecution") {
688
+ message.output = savedLogins.redactText(message.output);
689
+ }
690
+ }
691
+ catch {
692
+ if (message.role === "toolResult") {
693
+ message.content = [{ type: "text", text: SAVED_LOGIN_WITHHELD }];
694
+ message.isError = true;
695
+ }
696
+ else if (message.role === "custom") {
697
+ message.content = SAVED_LOGIN_WITHHELD;
698
+ }
699
+ else if (message.role === "bashExecution") {
700
+ message.output = SAVED_LOGIN_WITHHELD;
701
+ }
702
+ }
703
+ }
660
704
  _replaceMessageInPlace(target, replacement) {
661
705
  // Agent-core stores the finalized message object in its state before emitting message_end.
662
706
  // SessionManager persistence happens later in _handleAgentEvent() with event.message.
@@ -1858,8 +1902,11 @@ export class AgentSession {
1858
1902
  await this._runAgentPrompt(appMessage);
1859
1903
  }
1860
1904
  else {
1905
+ // Queued messages above keep the sender's details object for hasQueuedCustomMessage; the
1906
+ // loop scrubs them at message_end. This one enters history here.
1907
+ this._scrubSavedLogins(appMessage);
1861
1908
  this.agent.state.messages.push(appMessage);
1862
- this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
1909
+ this.sessionManager.appendCustomMessageEntry(appMessage.customType, appMessage.content, appMessage.display, appMessage.details);
1863
1910
  this._emit({ type: "message_start", message: appMessage });
1864
1911
  this._emit({ type: "message_end", message: appMessage });
1865
1912
  }
@@ -2526,6 +2573,7 @@ export class AgentSession {
2526
2573
  timestamp: Date.now(),
2527
2574
  excludeFromContext: options?.excludeFromContext,
2528
2575
  };
2576
+ this._scrubSavedLogins(bashMessage);
2529
2577
  // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
2530
2578
  if (this.isStreaming) {
2531
2579
  // Queue for later - will be flushed on agent_end
@@ -50,6 +50,8 @@ export declare class AuthStorage implements CredentialStore {
50
50
  read(provider: string): Promise<Credential | undefined>;
51
51
  modify(provider: string, fn: (current: Credential | undefined) => Promise<Credential | undefined>): Promise<Credential | undefined>;
52
52
  delete(provider: string): Promise<void>;
53
+ /** The credential strings this store holds, for `SavedLoginRedactor`; the same array until they change. */
54
+ savedLoginValues(): readonly string[];
53
55
  /** List credential metadata without resolving configured key values. */
54
56
  list(): Promise<readonly CredentialInfo[]>;
55
57
  }
@@ -8,6 +8,7 @@ import lockfile from "proper-lockfile";
8
8
  import { getAgentDir } from "../config.js";
9
9
  import { normalizePath } from "../utils/paths.js";
10
10
  import { resolveConfigValue } from "./resolve-config-value.js";
11
+ import { authValuesOf } from "./saved-login-redaction.js";
11
12
  const AUTH_FILE_WRITE_OPTIONS = { encoding: "utf-8", mode: 0o600 };
12
13
  /** OAuth refresh holds this lock for the IdP round-trip. 30s made a sleepy refresh look stale and let a second process spend the same token. */
13
14
  const AUTH_LOCK_STALE_MS = 120_000;
@@ -248,6 +249,10 @@ export class AuthStorage {
248
249
  return { result: undefined, next: JSON.stringify(currentData, null, 2) };
249
250
  });
250
251
  }
252
+ /** The credential strings this store holds, for `SavedLoginRedactor`; the same array until they change. */
253
+ savedLoginValues() {
254
+ return authValuesOf(this.data);
255
+ }
251
256
  /** List credential metadata without resolving configured key values. */
252
257
  async list() {
253
258
  return Object.entries(this.data).map(([providerId, credential]) => ({ providerId, type: credential.type }));
@@ -2,6 +2,7 @@ import { type Api, type AssistantMessage, type AssistantMessageEventStream, type
2
2
  import { type IncompleteLiveModel, type LiveCatalogResult } from "./live-catalog.ts";
3
3
  import { type OfficialCatalogLoadResult } from "./official-catalog.ts";
4
4
  import { type AuthStatus, type CompatibilityRequestConfig, type ProviderConfigInput } from "./provider-composer.ts";
5
+ import { SavedLoginRedactor } from "./saved-login-redaction.ts";
5
6
  import { type RequestSubscriptionKey, SubscriptionManager } from "./subscriptions.ts";
6
7
  import { type UserModelEntry } from "./user-models.ts";
7
8
  export interface CreateModelRuntimeOptions {
@@ -42,6 +43,8 @@ export declare class ModelRuntime implements Models {
42
43
  private readonly credentials;
43
44
  /** lunr: per-provider subscription-key pools; rotation mirrors the active key into the credential store. */
44
45
  readonly subscriptionManager: SubscriptionManager;
46
+ /** lunr: removes saved-login values from tool output before the session stores or sends it. */
47
+ readonly savedLogins: SavedLoginRedactor;
45
48
  private readonly requestSubscriptionKeys;
46
49
  private readonly defaultBuiltins;
47
50
  private readonly builtins;
@@ -13,6 +13,7 @@ import { FileModelsStore, InMemoryCodingAgentModelsStore } from "./models-store.
13
13
  import { loadOfficialCatalog, officialCatalogCachePath, officialEntryToModel, officialModelKeys, preferOfficialCatalog, } from "./official-catalog.js";
14
14
  import { composeModelProvider, configuredRequestAuthStatus, resolveCompatibilityRequestConfig, resolveConfiguredModelHeaders, validateExtensionProvider, } from "./provider-composer.js";
15
15
  import { RuntimeCredentials } from "./runtime-credentials.js";
16
+ import { SavedLoginRedactor } from "./saved-login-redaction.js";
16
17
  import { SubscriptionManager, subscriptionKeyFingerprint } from "./subscriptions.js";
17
18
  import { clearPlanUsageCache } from "./usage-service.js";
18
19
  import { UserModelsStore, userEntryToModel, userModelsPath } from "./user-models.js";
@@ -36,6 +37,8 @@ export class ModelRuntime {
36
37
  credentials;
37
38
  /** lunr: per-provider subscription-key pools; rotation mirrors the active key into the credential store. */
38
39
  subscriptionManager;
40
+ /** lunr: removes saved-login values from tool output before the session stores or sends it. */
41
+ savedLogins;
39
42
  requestSubscriptionKeys = new WeakMap();
40
43
  defaultBuiltins;
41
44
  builtins = new Map();
@@ -64,8 +67,9 @@ export class ModelRuntime {
64
67
  nextAutomaticRefresh = 0;
65
68
  automaticRefreshIdentity = "";
66
69
  grokHome;
67
- constructor(credentials, config, modelsPath, modelsStore, providers, allowModelNetwork, subscriptionManager, catalogDir, grokHome) {
70
+ constructor(credentials, config, modelsPath, modelsStore, providers, allowModelNetwork, subscriptionManager, catalogDir, grokHome, savedLogins) {
68
71
  this.credentials = credentials;
72
+ this.savedLogins = savedLogins;
69
73
  this.config = config;
70
74
  this.modelsPath = modelsPath;
71
75
  this.modelsStore = modelsStore;
@@ -92,10 +96,21 @@ export class ModelRuntime {
92
96
  // Pool persistence: subscriptions.json next to auth.json. A custom credential
93
97
  // store without an authPath (tests, SDK embeddings) gets a process-local pool
94
98
  // so nothing leaks into the real agent dir.
99
+ const subscriptionsPath = join(options.authPath ? dirname(options.authPath) : getAgentDir(), "subscriptions.json");
100
+ const subscriptionsOnDisk = !options.subscriptions && !(options.credentials && !options.authPath);
95
101
  const subscriptionManager = options.subscriptions ??
96
- (options.credentials && !options.authPath
97
- ? SubscriptionManager.inMemory(baseStore)
98
- : SubscriptionManager.create(baseStore, options.authPath ? join(dirname(options.authPath), "subscriptions.json") : undefined));
102
+ (subscriptionsOnDisk
103
+ ? SubscriptionManager.create(baseStore, subscriptionsPath)
104
+ : SubscriptionManager.inMemory(baseStore));
105
+ // A file-backed store is read from its file, so another lunR process's changes apply too and a
106
+ // value removed there leaves the set; a store without a file is read from memory.
107
+ const savedLogins = new SavedLoginRedactor([
108
+ ...(options.credentials && rawStore instanceof DefaultAuthStorage ? [rawStore] : []),
109
+ ...(subscriptionsOnDisk ? [] : [subscriptionManager]),
110
+ ], [
111
+ ...(options.credentials ? [] : [options.authPath ?? join(getAgentDir(), "auth.json")]),
112
+ ...(subscriptionsOnDisk ? [subscriptionsPath] : []),
113
+ ]);
99
114
  const modelsPath = options.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), "models.json"));
100
115
  const config = await ModelConfig.load(modelsPath);
101
116
  const modelsStore = options.modelsStore ??
@@ -104,7 +119,7 @@ export class ModelRuntime {
104
119
  : new InMemoryCodingAgentModelsStore());
105
120
  const providers = builtinProviderCatalog.builtinProviders();
106
121
  const catalogDir = modelsPath ? dirname(modelsPath) : options.authPath ? dirname(options.authPath) : undefined;
107
- const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, options.allowModelNetwork ?? !isOfflineModeEnabled(), subscriptionManager, catalogDir, grokHome);
122
+ const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, options.allowModelNetwork ?? !isOfflineModeEnabled(), subscriptionManager, catalogDir, grokHome, savedLogins);
108
123
  runtime.configureRadiusProviders();
109
124
  runtime.rebuildProviders();
110
125
  // lunr: create() must not wait on GitHub / provider /v1/models / a dead NIC.
@@ -6,6 +6,11 @@ export declare function getConfigValueEnvVarName(config: string): string | undef
6
6
  export declare function getConfigValueEnvVarNames(config: string): string[];
7
7
  export declare function getMissingConfigValueEnvVarNames(config: string, env?: Record<string, string>): string[];
8
8
  export declare function isCommandConfigValue(config: string): boolean;
9
+ /**
10
+ * The value a config string stands for when it is a plain literal (`$$` and `$!` unescaped), or
11
+ * undefined when it runs a command or reads an environment variable.
12
+ */
13
+ export declare function literalConfigValue(config: string): string | undefined;
9
14
  export declare function isConfigValueConfigured(config: string, env?: Record<string, string>): boolean;
10
15
  /**
11
16
  * Resolve a config value (API key, header value, etc.) to an actual value.
@@ -110,6 +110,22 @@ export function getMissingConfigValueEnvVarNames(config, env) {
110
110
  export function isCommandConfigValue(config) {
111
111
  return parseConfigValueReference(config).type === "command";
112
112
  }
113
+ /**
114
+ * The value a config string stands for when it is a plain literal (`$$` and `$!` unescaped), or
115
+ * undefined when it runs a command or reads an environment variable.
116
+ */
117
+ export function literalConfigValue(config) {
118
+ const reference = parseConfigValueReference(config);
119
+ if (reference.type === "command")
120
+ return undefined;
121
+ let value = "";
122
+ for (const part of reference.parts) {
123
+ if (part.type === "env")
124
+ return undefined;
125
+ value += part.value;
126
+ }
127
+ return value;
128
+ }
113
129
  export function isConfigValueConfigured(config, env) {
114
130
  return getMissingConfigValueEnvVarNames(config, env).length === 0;
115
131
  }
@@ -0,0 +1,74 @@
1
+ import type { Credential, ImageContent, TextContent } from "@ashx-j/lunr-ai";
2
+ /**
3
+ * Removes the values of lunR's saved logins (`auth.json` and the `subscriptions.json` key pool) from
4
+ * text that tools and commands produce. `credential-files.ts` refuses the plain spellings of those
5
+ * paths; this catches every other way a command prints the file (globs, `grep -r`, `tar`, `bash -c`,
6
+ * a script). Two filters, one set of values:
7
+ * - `redactContent`/`redactText`: the text of messages a provider request is built from. `AgentSession`
8
+ * applies it to tool results, custom messages and `!` output as they enter history, and
9
+ * `SessionManager` to compaction and branch summaries as they are stored.
10
+ * - `redactSessionLine`: every JSONL line `SessionManager` writes, whatever its entry type or shape.
11
+ * It matches exact values only. docs/agents/permissions-and-memory.md lists what is covered.
12
+ */
13
+ export declare const SAVED_LOGIN_MARKER = "[saved login removed by lunR]";
14
+ /** What replaces a message whose redaction threw, so it never enters history unchecked. */
15
+ export declare const SAVED_LOGIN_WITHHELD = "[lunR withheld this output: removing saved logins from it failed]";
16
+ /** Shorter strings could blank out ordinary output; real keys and tokens are far longer. */
17
+ export declare const MIN_SAVED_LOGIN_LENGTH = 16;
18
+ /** A store of saved logins. `savedLoginValues` returns the same array until its data changes. */
19
+ export interface SavedLoginSource {
20
+ savedLoginValues(): readonly string[];
21
+ }
22
+ /** A subscription pool as `subscriptions.json` stores it: per provider, the keys of the pool. */
23
+ type PoolData = Readonly<Record<string, {
24
+ readonly keys: readonly {
25
+ readonly key: string;
26
+ }[];
27
+ }>>;
28
+ /** API keys and OAuth access and refresh tokens in `auth.json` data. Claude subscription records hold none. */
29
+ export declare function authValuesOf(data: Readonly<Record<string, Credential>>): readonly string[];
30
+ /** The pool keys in `subscriptions.json` data. lunR mirrors the active one into `auth.json` as an API key. */
31
+ export declare function poolValuesOf(data: PoolData): readonly string[];
32
+ type ToolContent = TextContent | ImageContent;
33
+ /**
34
+ * Exact-value redaction for one process. The set is the values of the in-memory stores that have no
35
+ * file, plus `auth.json` and `subscriptions.json` as last read. Every filter call compares each file's
36
+ * inode, mtime, ctime and size with the last good read (2 `stat` calls, about 4 µs) and rereads a changed
37
+ * file; a failed read keeps the last good values and is retried at the next call. The 2 patterns are
38
+ * rebuilt only when the set of values changed.
39
+ */
40
+ export declare class SavedLoginRedactor {
41
+ private readonly sources;
42
+ private readonly files;
43
+ private readonly fileStamps;
44
+ private readonly fileValues;
45
+ private sourceValues;
46
+ private valueKey;
47
+ private textPattern;
48
+ private linePattern;
49
+ constructor(sources: readonly SavedLoginSource[], files?: readonly string[]);
50
+ /** `text` with every saved-login value replaced by SAVED_LOGIN_MARKER; the same string when none occurs. */
51
+ redactText(text: string): string;
52
+ /**
53
+ * Text parts redacted, or undefined when nothing changed. Providers and summaries join a message's
54
+ * text parts with "" or "\n", so a value split across adjacent parts is found in either join and
55
+ * those parts are merged into 1 before the replacement. Image parts are not inspected.
56
+ */
57
+ redactContent(content: readonly ToolContent[]): ToolContent[] | undefined;
58
+ /** Message content (a string or parts) with saved-login values replaced; `content` itself when none occurs. */
59
+ redactMessageContent(content: string | ToolContent[]): string | ToolContent[];
60
+ /**
61
+ * A serialized JSONL line with every saved value replaced, in its JSON-escaped form (the raw text
62
+ * for values without quotes, backslashes or control characters). The marker needs no escaping, so
63
+ * the line stays valid JSON.
64
+ */
65
+ redactSessionLine(line: string): string;
66
+ private refresh;
67
+ /**
68
+ * Rereads each file whose inode, mtime, ctime or size changed (a rename onto it changes the inode).
69
+ * True when a file's values were replaced.
70
+ */
71
+ private checkFiles;
72
+ }
73
+ export {};
74
+ //# sourceMappingURL=saved-login-redaction.d.ts.map
@@ -0,0 +1,322 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { literalConfigValue } from "./resolve-config-value.js";
3
+ /**
4
+ * Removes the values of lunR's saved logins (`auth.json` and the `subscriptions.json` key pool) from
5
+ * text that tools and commands produce. `credential-files.ts` refuses the plain spellings of those
6
+ * paths; this catches every other way a command prints the file (globs, `grep -r`, `tar`, `bash -c`,
7
+ * a script). Two filters, one set of values:
8
+ * - `redactContent`/`redactText`: the text of messages a provider request is built from. `AgentSession`
9
+ * applies it to tool results, custom messages and `!` output as they enter history, and
10
+ * `SessionManager` to compaction and branch summaries as they are stored.
11
+ * - `redactSessionLine`: every JSONL line `SessionManager` writes, whatever its entry type or shape.
12
+ * It matches exact values only. docs/agents/permissions-and-memory.md lists what is covered.
13
+ */
14
+ export const SAVED_LOGIN_MARKER = "[saved login removed by lunR]";
15
+ /** What replaces a message whose redaction threw, so it never enters history unchecked. */
16
+ export const SAVED_LOGIN_WITHHELD = "[lunR withheld this output: removing saved logins from it failed]";
17
+ /** Shorter strings could blank out ordinary output; real keys and tokens are far longer. */
18
+ export const MIN_SAVED_LOGIN_LENGTH = 16;
19
+ const valuesByData = new WeakMap();
20
+ function memoized(data, collect) {
21
+ let values = valuesByData.get(data);
22
+ if (!values) {
23
+ const found = new Set();
24
+ collect((value) => {
25
+ if (typeof value === "string")
26
+ found.add(value);
27
+ });
28
+ values = [...found];
29
+ valuesByData.set(data, values);
30
+ }
31
+ return values;
32
+ }
33
+ /**
34
+ * An API key as stored and as lunR sends it, when it is a literal. A `!command` or `$VAR` reference
35
+ * is resolved only at request time, so the stored text is not the secret.
36
+ */
37
+ function addApiKey(add, key) {
38
+ if (typeof key !== "string")
39
+ return;
40
+ const literal = literalConfigValue(key);
41
+ if (literal === undefined)
42
+ return;
43
+ add(key);
44
+ add(literal);
45
+ }
46
+ /** API keys and OAuth access and refresh tokens in `auth.json` data. Claude subscription records hold none. */
47
+ export function authValuesOf(data) {
48
+ return memoized(data, (add) => {
49
+ for (const credential of Object.values(data)) {
50
+ if (credential.type === "api_key")
51
+ addApiKey(add, credential.key);
52
+ else if (credential.type === "oauth") {
53
+ add(credential.access);
54
+ add(credential.refresh);
55
+ }
56
+ }
57
+ });
58
+ }
59
+ /** The pool keys in `subscriptions.json` data. lunR mirrors the active one into `auth.json` as an API key. */
60
+ export function poolValuesOf(data) {
61
+ return memoized(data, (add) => {
62
+ for (const pool of Object.values(data))
63
+ for (const entry of pool.keys)
64
+ addApiKey(add, entry.key);
65
+ });
66
+ }
67
+ /** Either file's parsed JSON: each provider entry is a credential record or a pool. */
68
+ function fileValuesOf(json) {
69
+ if (json === null || typeof json !== "object")
70
+ return [];
71
+ return memoized(json, (add) => {
72
+ for (const entry of Object.values(json)) {
73
+ if (entry === null || typeof entry !== "object")
74
+ continue;
75
+ if ("type" in entry && entry.type === "api_key" && "key" in entry)
76
+ addApiKey(add, entry.key);
77
+ if ("type" in entry && entry.type === "oauth") {
78
+ if ("access" in entry)
79
+ add(entry.access);
80
+ if ("refresh" in entry)
81
+ add(entry.refresh);
82
+ }
83
+ if ("keys" in entry && Array.isArray(entry.keys)) {
84
+ for (const item of entry.keys) {
85
+ if (item !== null && typeof item === "object" && "key" in item)
86
+ addApiKey(add, item.key);
87
+ }
88
+ }
89
+ }
90
+ });
91
+ }
92
+ /** A file's values, [] when it is missing, undefined when it could not be read whole. */
93
+ function readFileValues(path) {
94
+ let text;
95
+ try {
96
+ text = readFileSync(path, "utf8");
97
+ }
98
+ catch (error) {
99
+ return error instanceof Error && "code" in error && error.code === "ENOENT" ? [] : undefined;
100
+ }
101
+ try {
102
+ return fileValuesOf(JSON.parse(text));
103
+ }
104
+ catch {
105
+ // A writer on Windows replaces the file in place, so a read can catch it half written.
106
+ return undefined;
107
+ }
108
+ }
109
+ /** JSON escapes quotes, backslashes and control characters, so a JSONL line holds a value in this form. */
110
+ const jsonEscaped = (value) => JSON.stringify(value).slice(1, -1);
111
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
112
+ /** One alternation, longest first so a value that contains another is replaced whole. */
113
+ function alternation(values) {
114
+ const list = [...new Set(values)].sort((a, b) => b.length - a.length);
115
+ return list.length > 0 ? new RegExp(list.map(escapeRegExp).join("|"), "g") : undefined;
116
+ }
117
+ /**
118
+ * Exact-value redaction for one process. The set is the values of the in-memory stores that have no
119
+ * file, plus `auth.json` and `subscriptions.json` as last read. Every filter call compares each file's
120
+ * inode, mtime, ctime and size with the last good read (2 `stat` calls, about 4 µs) and rereads a changed
121
+ * file; a failed read keeps the last good values and is retried at the next call. The 2 patterns are
122
+ * rebuilt only when the set of values changed.
123
+ */
124
+ export class SavedLoginRedactor {
125
+ sources;
126
+ files;
127
+ fileStamps = new Map();
128
+ fileValues = new Map();
129
+ sourceValues;
130
+ valueKey = "";
131
+ textPattern;
132
+ linePattern;
133
+ constructor(sources, files = []) {
134
+ this.sources = sources;
135
+ this.sourceValues = sources.map(() => undefined);
136
+ this.files = files;
137
+ }
138
+ /** `text` with every saved-login value replaced by SAVED_LOGIN_MARKER; the same string when none occurs. */
139
+ redactText(text) {
140
+ this.refresh();
141
+ return this.textPattern ? replaceAll(text, this.textPattern) : text;
142
+ }
143
+ /**
144
+ * Text parts redacted, or undefined when nothing changed. Providers and summaries join a message's
145
+ * text parts with "" or "\n", so a value split across adjacent parts is found in either join and
146
+ * those parts are merged into 1 before the replacement. Image parts are not inspected.
147
+ */
148
+ redactContent(content) {
149
+ this.refresh();
150
+ const pattern = this.textPattern;
151
+ if (!pattern)
152
+ return undefined;
153
+ let parts = [...content];
154
+ let changed = false;
155
+ for (const separator of ["", "\n"]) {
156
+ const merged = mergeSplitValues(parts, pattern, separator);
157
+ if (!merged)
158
+ continue;
159
+ parts = merged;
160
+ changed = true;
161
+ }
162
+ for (const [index, part] of parts.entries()) {
163
+ if (part.type !== "text")
164
+ continue;
165
+ const text = replaceAll(part.text, pattern);
166
+ if (text === part.text)
167
+ continue;
168
+ parts[index] = { ...part, text };
169
+ changed = true;
170
+ }
171
+ return changed ? parts : undefined;
172
+ }
173
+ /** Message content (a string or parts) with saved-login values replaced; `content` itself when none occurs. */
174
+ redactMessageContent(content) {
175
+ return typeof content === "string" ? this.redactText(content) : (this.redactContent(content) ?? content);
176
+ }
177
+ /**
178
+ * A serialized JSONL line with every saved value replaced, in its JSON-escaped form (the raw text
179
+ * for values without quotes, backslashes or control characters). The marker needs no escaping, so
180
+ * the line stays valid JSON.
181
+ */
182
+ redactSessionLine(line) {
183
+ this.refresh();
184
+ return this.linePattern ? replaceOutsideEscapes(line, this.linePattern) : line;
185
+ }
186
+ refresh() {
187
+ let changed = this.checkFiles();
188
+ for (const [index, source] of this.sources.entries()) {
189
+ const values = source.savedLoginValues();
190
+ if (values === this.sourceValues[index])
191
+ continue;
192
+ this.sourceValues[index] = values;
193
+ changed = true;
194
+ }
195
+ if (!changed)
196
+ return;
197
+ const values = new Set();
198
+ for (const list of [...this.sourceValues, ...this.fileValues.values()]) {
199
+ for (const value of list ?? []) {
200
+ // A value inside the marker would come back with every replacement.
201
+ if (value.length >= MIN_SAVED_LOGIN_LENGTH && !SAVED_LOGIN_MARKER.includes(value))
202
+ values.add(value);
203
+ }
204
+ }
205
+ const key = [...values].sort().join("\0");
206
+ if (key === this.valueKey)
207
+ return;
208
+ this.valueKey = key;
209
+ this.textPattern = alternation(values);
210
+ this.linePattern = alternation([...values].map(jsonEscaped));
211
+ }
212
+ /**
213
+ * Rereads each file whose inode, mtime, ctime or size changed (a rename onto it changes the inode).
214
+ * True when a file's values were replaced.
215
+ */
216
+ checkFiles() {
217
+ let changed = false;
218
+ for (const file of this.files) {
219
+ let stamp;
220
+ try {
221
+ const stat = statSync(file, { throwIfNoEntry: false });
222
+ stamp = stat ? `${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}` : "missing";
223
+ }
224
+ catch {
225
+ continue;
226
+ }
227
+ if (stamp === this.fileStamps.get(file))
228
+ continue;
229
+ const values = stamp === "missing" ? [] : readFileValues(file);
230
+ // Keep the stamp unset after a failed read, so the next call reads the file again.
231
+ if (!values)
232
+ continue;
233
+ this.fileStamps.set(file, stamp);
234
+ this.fileValues.set(file, values);
235
+ changed = true;
236
+ }
237
+ return changed;
238
+ }
239
+ }
240
+ function replaceAll(text, pattern) {
241
+ pattern.lastIndex = 0;
242
+ return pattern.test(text) ? text.replace(pattern, SAVED_LOGIN_MARKER) : text;
243
+ }
244
+ /**
245
+ * `replaceAll` for a serialized JSON line. A match after an odd number of backslashes starts inside an
246
+ * escape (`\n` followed by the rest of a value that starts with `n`), so it is not the value, and
247
+ * replacing it would leave a lone backslash and a line that no longer parses.
248
+ */
249
+ function replaceOutsideEscapes(line, pattern) {
250
+ pattern.lastIndex = 0;
251
+ if (!pattern.test(line))
252
+ return line;
253
+ return line.replace(pattern, (match, offset) => {
254
+ let backslashes = 0;
255
+ while (line[offset - backslashes - 1] === "\\")
256
+ backslashes++;
257
+ return backslashes % 2 === 0 ? SAVED_LOGIN_MARKER : match;
258
+ });
259
+ }
260
+ /**
261
+ * `parts` with each run of adjacent text parts that a match crosses when joined by `separator` merged
262
+ * into 1 text part (joined the same way), or undefined when no match crosses a part boundary.
263
+ */
264
+ function mergeSplitValues(parts, pattern, separator) {
265
+ const textIndexes = parts.flatMap((part, index) => (part.type === "text" ? [index] : []));
266
+ if (textIndexes.length < 2)
267
+ return undefined;
268
+ const starts = [];
269
+ let joined = "";
270
+ for (const [position, index] of textIndexes.entries()) {
271
+ const part = parts[index];
272
+ if (position > 0)
273
+ joined += separator;
274
+ starts.push(joined.length);
275
+ joined += part?.type === "text" ? part.text : "";
276
+ }
277
+ const partAt = (offset) => {
278
+ let position = 0;
279
+ while (position + 1 < starts.length && (starts[position + 1] ?? Infinity) <= offset)
280
+ position++;
281
+ return position;
282
+ };
283
+ // Runs of positions in textIndexes, [first, last], that a match spans.
284
+ const runs = [];
285
+ for (const match of joined.matchAll(pattern)) {
286
+ const first = partAt(match.index);
287
+ const last = partAt(match.index + match[0].length - 1);
288
+ if (first === last)
289
+ continue;
290
+ const previous = runs[runs.length - 1];
291
+ if (previous && first <= previous[1])
292
+ previous[1] = Math.max(previous[1], last);
293
+ else
294
+ runs.push([first, last]);
295
+ }
296
+ if (runs.length === 0)
297
+ return undefined;
298
+ const merged = [];
299
+ const dropped = new Set();
300
+ const replacements = new Map();
301
+ for (const [first, last] of runs) {
302
+ const indexes = textIndexes.slice(first, last + 1);
303
+ const text = indexes
304
+ .map((index) => {
305
+ const part = parts[index];
306
+ return part?.type === "text" ? part.text : "";
307
+ })
308
+ .join(separator);
309
+ const head = parts[indexes[0] ?? 0];
310
+ if (head?.type === "text")
311
+ replacements.set(indexes[0] ?? 0, { ...head, text });
312
+ for (const index of indexes.slice(1))
313
+ dropped.add(index);
314
+ }
315
+ for (const [index, part] of parts.entries()) {
316
+ if (dropped.has(index))
317
+ continue;
318
+ merged.push(replacements.get(index) ?? part);
319
+ }
320
+ return merged;
321
+ }
322
+ //# sourceMappingURL=saved-login-redaction.js.map