@yagni-app/code-staging 1.2.14-staging.2281.1 → 1.2.14-staging.2282.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.
@@ -112,6 +112,19 @@ export declare const SANDBOX_SECTION: string;
112
112
  * contain the standalone word "pi", no `- ` bullet lines, no emojis.
113
113
  */
114
114
  export declare const SANDBOX_CLOUD_SECTION: string;
115
+ export declare const PLACED_VALUES_SECTION_HEADER = "## The System's values";
116
+ /**
117
+ * What a session on a machine that holds a yak's System values is told
118
+ * (YAG-1209): never read them. Appended only where the extension found the
119
+ * file at activation (`placedValues.ts`), so no other session's prompt
120
+ * changes. The paths are the backend's (`repos/system/needs/placement.ts`),
121
+ * created at run time, never on the image, so the image smoke does not read
122
+ * this section.
123
+ *
124
+ * Content constraints (parity with {@link SANDBOX_SECTION}): must not contain
125
+ * the standalone word "pi", no `- ` bullet lines, no emojis.
126
+ */
127
+ export declare const PLACED_VALUES_SECTION: string;
115
128
  /**
116
129
  * File-tool steering: prefer the first-class write/edit tools over bash file
117
130
  * writes, one write call per file instead of a heredoc batch, and never create
@@ -221,6 +234,11 @@ export interface BrandSystemPromptOptions {
221
234
  * {@link SANDBOX_CLOUD_SECTION} instead of {@link SANDBOX_SECTION}.
222
235
  */
223
236
  cloud?: boolean;
237
+ /**
238
+ * The machine holds a yak's System values (`placedValues.ts` found the
239
+ * file): {@link PLACED_VALUES_SECTION} is appended. Absent, nothing changes.
240
+ */
241
+ placedValues?: boolean;
224
242
  }
225
243
  /**
226
244
  * Rebrand pi's assembled system prompt as YAGNI Code's, and optionally inject a
@@ -253,6 +253,31 @@ export const SANDBOX_CLOUD_SECTION = `${SANDBOX_SECTION_HEADER}\n` +
253
253
  "and read one with " +
254
254
  "`gh api -H 'Accept: application/vnd.github.raw' 'repos/<owner>/<repo>/contents/<path>'`. " +
255
255
  "Nothing there is part of your change.";
256
+ export const PLACED_VALUES_SECTION_HEADER = "## The System's values";
257
+ /**
258
+ * What a session on a machine that holds a yak's System values is told
259
+ * (YAG-1209): never read them. Appended only where the extension found the
260
+ * file at activation (`placedValues.ts`), so no other session's prompt
261
+ * changes. The paths are the backend's (`repos/system/needs/placement.ts`),
262
+ * created at run time, never on the image, so the image smoke does not read
263
+ * this section.
264
+ *
265
+ * Content constraints (parity with {@link SANDBOX_SECTION}): must not contain
266
+ * the standalone word "pi", no `- ` bullet lines, no emojis.
267
+ */
268
+ export const PLACED_VALUES_SECTION = `${PLACED_VALUES_SECTION_HEADER}\n` +
269
+ "\n" +
270
+ "This machine holds the System's provided values, the credentials and test data its " +
271
+ "services run with, in `/run/yagni/secret/env` (linked at `/run/yagni/env`). Never read, " +
272
+ "print, copy or search that file, and never read a running service's environment " +
273
+ "(`/proc/<pid>/environ`, `docker inspect`, `env` or `printenv` run inside a container). " +
274
+ "A command that needs the values sources the file itself " +
275
+ "(`set -a; . /run/yagni/env; set +a; <command>`) and never prints one. Code you write " +
276
+ "reads a credential by its variable name, never as a literal, and no credential goes " +
277
+ "into a file, a commit message or your report. A credential that reaches you in any " +
278
+ "output shows as [REDACTED], and YAGNI does not push a change, commit message or pull " +
279
+ "request that holds one. Test data (a test user, seed records, the app's URL) and a " +
280
+ "public value show as they are, and a test may hold them.";
256
281
  /**
257
282
  * File-tool steering: prefer the first-class write/edit tools over bash file
258
283
  * writes, one write call per file instead of a heredoc batch, and never create
@@ -475,6 +500,11 @@ export function brandSystemPrompt(original, opts = {}) {
475
500
  else if (!s.includes(TICKET_IMAGE_RULE_HEADER)) {
476
501
  s = `${s}\n\n${TICKET_IMAGE_RULE_HEADER}\n${TICKET_IMAGE_RULE}`;
477
502
  }
503
+ // 5b1. YAG-1209: a machine that holds a yak's System values says never to
504
+ // read them, beside what the sandbox has. Same idempotency shape.
505
+ if (opts.placedValues && !s.includes(PLACED_VALUES_SECTION_HEADER)) {
506
+ s = `${s}\n\n${PLACED_VALUES_SECTION}`;
507
+ }
478
508
  // 5b2. GitHub operations — a standing directive added alongside
479
509
  // the ticket-image rule (same placement, same idempotency shape). It is
480
510
  // universal knowledge, not user policy, so it rides the branded prompt
@@ -27,6 +27,8 @@ import { maybeOfferMiningBeat as defaultMaybeOfferMiningBeat, type MineBeatMarke
27
27
  export interface RegisterYagniDeps {
28
28
  baseUrl?: string;
29
29
  getToken?: () => string | undefined;
30
+ /** Where a yak's System places its values (`placedValues.ts`); the backend's paths by default. */
31
+ placedValuePaths?: readonly string[];
30
32
  /** The token's ISO expiry, forwarded by the launcher (for the expiry notice). */
31
33
  getTokenExpiresAt?: () => string | undefined;
32
34
  /** Clock seam for the expiry notice (defaults to Date.now). */
@@ -63,6 +63,7 @@ import { registerDecisionCommands } from "./decisions.js";
63
63
  import { makeDecisionCapture } from "./decisionCapture.js";
64
64
  import { loadGroundingEnabled } from "./grounding.js";
65
65
  import { attributionPromptSection, loadAttributionSettings, } from "./attribution.js";
66
+ import { openPlacedValues, registerPlacedValueRedaction } from "./placedValues.js";
66
67
  import { registerAmbientRecall } from "./recall.js";
67
68
  import { resilientFetch } from "./resilientFetch.js";
68
69
  import { installNonZeroExitReporter, installUncaughtExceptionMonitor, makeCrashReporter, runningUnderTest, } from "./crashReport.js";
@@ -175,6 +176,10 @@ export async function registerYagni(pi, deps = {}) {
175
176
  // mode under the harness, where team_read is registered). A local eval
176
177
  // compare sets eval mode without the harness, so it keeps the laptop's.
177
178
  const sandboxSession = cloudSession || (evalMode && runsInSandboxHarness(env));
179
+ // YAG-1209: a yak's machine holds its System's values in a file this
180
+ // session could read. Opened only where the file is (null everywhere else,
181
+ // where nothing below changes); its handlers register last, at the end.
182
+ const placedValues = openPlacedValues(deps.placedValuePaths);
178
183
  // A timed /go stage child refuses every tool once its time is up. Order does
179
184
  // not matter: pi runs every tool_call handler until one blocks, and an allow
180
185
  // (a result without `block`) never ends the loop, so this block always lands.
@@ -1757,6 +1762,7 @@ export async function registerYagni(pi, deps = {}) {
1757
1762
  fileToolSteering: condensedToolsRegistered,
1758
1763
  ...(sandboxSession ? { sandbox: true } : {}),
1759
1764
  ...(cloudSession ? { cloud: true } : {}),
1765
+ ...(placedValues ? { placedValues: true } : {}),
1760
1766
  }),
1761
1767
  });
1762
1768
  // Turn-lifecycle WAL: a `turn_start` with no matching `turn_end` is the
@@ -2214,6 +2220,10 @@ export async function registerYagni(pi, deps = {}) {
2214
2220
  fields: { toolName: event.toolName, errorClass },
2215
2221
  });
2216
2222
  });
2223
+ // YAG-1209: last, so the placed values are replaced in whatever every
2224
+ // other tool_result and context handler above added.
2225
+ if (placedValues)
2226
+ registerPlacedValueRedaction(pi, placedValues);
2217
2227
  }
2218
2228
  export default async function (pi) {
2219
2229
  await registerYagni(pi);
@@ -37,10 +37,6 @@ export interface AddedText {
37
37
  export declare function scanAddedText(files: readonly AddedText[], sessionSecrets?: readonly string[]): Finding[];
38
38
  /** A binary file this run added or changed, other than an image: the host never stores one. */
39
39
  export declare function binaryFindings(paths: readonly string[]): Finding[];
40
- /**
41
- * A unified diff (`-U0`) as the text each file gained: its `+` lines with
42
- * their new line numbers. Deleted files and binary sections gain nothing.
43
- */
44
40
  export declare function addedTextOfDiff(diff: string): AddedText[];
45
41
  /** The git seam: argv run in `cwd`, resolving its exit code and output. */
46
42
  export type ScanExec = (argv: string[], cwd: string, signal?: AbortSignal) => Promise<{
@@ -218,17 +218,63 @@ export function binaryFindings(paths) {
218
218
  * A unified diff (`-U0`) as the text each file gained: its `+` lines with
219
219
  * their new line numbers. Deleted files and binary sections gain nothing.
220
220
  */
221
+ const C_ESCAPES = {
222
+ a: 7,
223
+ b: 8,
224
+ t: 9,
225
+ n: 10,
226
+ v: 11,
227
+ f: 12,
228
+ r: 13,
229
+ '"': 34,
230
+ "\\": 92,
231
+ };
232
+ /**
233
+ * A patch header's path as the file is named: git C-quotes a name holding a
234
+ * quote, a backslash, a tab or a newline (`"b/a\"b.txt"`) even with
235
+ * `core.quotepath=off`, and may append a tab after an unquoted one.
236
+ */
237
+ function gitHeaderPath(raw) {
238
+ if (!raw.startsWith('"'))
239
+ return raw.replace(/\t.*$/, "");
240
+ const end = raw.lastIndexOf('"');
241
+ // By code point, so a character outside the BMP (an emoji) stays whole.
242
+ const inner = Array.from(raw.slice(1, end > 0 ? end : undefined));
243
+ const bytes = [];
244
+ for (let at = 0; at < inner.length; at++) {
245
+ const char = inner[at];
246
+ if (char !== "\\") {
247
+ bytes.push(...Buffer.from(char, "utf8"));
248
+ continue;
249
+ }
250
+ const octal = /^[0-7]{3}$/.exec(inner.slice(at + 1, at + 4).join(""));
251
+ if (octal) {
252
+ bytes.push(Number.parseInt(octal[0], 8));
253
+ at += 3;
254
+ }
255
+ else {
256
+ const next = inner[at + 1] ?? "";
257
+ bytes.push(C_ESCAPES[next] ?? next.charCodeAt(0));
258
+ at += 1;
259
+ }
260
+ }
261
+ return Buffer.from(bytes).toString("utf8");
262
+ }
221
263
  export function addedTextOfDiff(diff) {
222
264
  const files = [];
223
265
  let current;
224
266
  let next = 0;
267
+ // A file's header comes before its first hunk: inside one, a line that
268
+ // reads `+++ ` is an added line that starts `++ `, never a header.
269
+ let inHunk = false;
225
270
  for (const raw of diff.split("\n")) {
226
271
  if (raw.startsWith("diff --git ")) {
227
272
  current = undefined;
273
+ inHunk = false;
228
274
  continue;
229
275
  }
230
- if (raw.startsWith("+++ ")) {
231
- const path = raw.slice(4).replace(/\t.*$/, "");
276
+ if (!inHunk && raw.startsWith("+++ ")) {
277
+ const path = gitHeaderPath(raw.slice(4));
232
278
  current = path === "/dev/null" ? undefined : { path: path.replace(/^b\//, ""), lines: [] };
233
279
  if (current)
234
280
  files.push(current);
@@ -237,9 +283,10 @@ export function addedTextOfDiff(diff) {
237
283
  const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw);
238
284
  if (hunk) {
239
285
  next = Number(hunk[1]);
286
+ inHunk = true;
240
287
  continue;
241
288
  }
242
- if (current && raw.startsWith("+")) {
289
+ if (current && inHunk && raw.startsWith("+")) {
243
290
  current.lines.push({ line: next, text: raw.slice(1) });
244
291
  next += 1;
245
292
  }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * A System secret in the session's own change, taken out by the session
3
+ * before it ends (YAG-1209). A yak's machine holds its System's values
4
+ * (`../placedValues.ts`), and the host never pushes a change that holds one
5
+ * of the secrets among them: that refusal hands the push to a person. So
6
+ * before a writing turn ends, its change is read for each secret's value. One
7
+ * there is named to the model by variable and place, never by value, and the
8
+ * model is asked once, in the same session, to read it from the environment
9
+ * instead and finish. A secret still there after that is left for the host's
10
+ * refusal, the backstop, and the turn's result says so by name.
11
+ *
12
+ * What is read: the change's added lines and new files (the tree's dirt from
13
+ * before the turn left out, as `changeScan.ts` leaves it), every path it
14
+ * touched, each commit's own patch past the turn's start (a value one commit
15
+ * added and a later one took out is still pushed), and their messages.
16
+ *
17
+ * Only exact text is found, as on the host: a value the session encoded
18
+ * first gets past both.
19
+ */
20
+ import { type PlacedSecret, type PlacedValues } from "../placedValues.js";
21
+ import type { StageResult } from "./types.js";
22
+ import type { WorktreeExec } from "./worktree.js";
23
+ /** One secret the change holds, and where; never its value. */
24
+ export interface PlacedSecretHit {
25
+ name: string;
26
+ /** The change's files that hold it in their text or their path, each path with any value marked. */
27
+ files: string[];
28
+ /** A commit past the start holds it, whether or not the change still does: the branch needs rewriting. */
29
+ committed: boolean;
30
+ /** A commit message holds it. */
31
+ message: boolean;
32
+ }
33
+ export interface PlacedSecretScanOpts {
34
+ exec: WorktreeExec;
35
+ /** The tree's dirt from before the turn (`git status` paths, a folder ending in `/`): not the turn's. */
36
+ skip?: readonly string[];
37
+ signal?: AbortSignal;
38
+ readFile?: (path: string) => Buffer;
39
+ }
40
+ /**
41
+ * Each secret the change past `base` holds, or null when git could not say
42
+ * what changed (the read that failed is logged). The value never leaves this
43
+ * function.
44
+ */
45
+ export declare function placedSecretsInChange(cwd: string, base: string, secrets: readonly PlacedSecret[], opts: PlacedSecretScanOpts): Promise<PlacedSecretHit[] | null>;
46
+ /** The ask: each secret by name and place, what to do instead, and to finish as before. */
47
+ export declare function placedSecretAsk(hits: readonly PlacedSecretHit[], base: string): string;
48
+ export interface PlacedSecretHeal {
49
+ /** The turn's last run: the ask's, when it ran to its end. */
50
+ run: StageResult;
51
+ /** The ask's run, when there was one. */
52
+ asked: StageResult[];
53
+ /** For the turn's result: a secret the change still holds, by name, or a scan that could not read it. */
54
+ note: string | null;
55
+ }
56
+ /**
57
+ * Reads a writing turn's change for the System's secrets and, when it holds
58
+ * one, asks the model once to take it out and finish. Not asked of a turn
59
+ * that was stopped, ran out of time or ended in an error, nor on a machine
60
+ * with no secret placed.
61
+ */
62
+ export declare function healPlacedSecrets(run: StageResult, turn: (message: string) => Promise<StageResult>, opts: PlacedSecretScanOpts & {
63
+ cwd: string;
64
+ base: string | null;
65
+ store: PlacedValues | null;
66
+ }): Promise<PlacedSecretHeal>;
67
+ //# sourceMappingURL=placedValueHeal.d.ts.map
@@ -0,0 +1,195 @@
1
+ /**
2
+ * A System secret in the session's own change, taken out by the session
3
+ * before it ends (YAG-1209). A yak's machine holds its System's values
4
+ * (`../placedValues.ts`), and the host never pushes a change that holds one
5
+ * of the secrets among them: that refusal hands the push to a person. So
6
+ * before a writing turn ends, its change is read for each secret's value. One
7
+ * there is named to the model by variable and place, never by value, and the
8
+ * model is asked once, in the same session, to read it from the environment
9
+ * instead and finish. A secret still there after that is left for the host's
10
+ * refusal, the backstop, and the turn's result says so by name.
11
+ *
12
+ * What is read: the change's added lines and new files (the tree's dirt from
13
+ * before the turn left out, as `changeScan.ts` leaves it), every path it
14
+ * touched, each commit's own patch past the turn's start (a value one commit
15
+ * added and a later one took out is still pushed), and their messages.
16
+ *
17
+ * Only exact text is found, as on the host: a value the session encoded
18
+ * first gets past both.
19
+ */
20
+ import { readFileSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import { logEvent } from "../errorSink.js";
23
+ import { PLACED_VALUE_MARK } from "../placedValues.js";
24
+ import { addedTextOfDiff } from "./changeScan.js";
25
+ /** How much of one new file is read: a value sits in source, not past the first megabyte. */
26
+ const MAX_READ_BYTES = 1024 * 1024;
27
+ /** Each named git read's output, or the first that failed, by name and exit code. */
28
+ async function readAll(reads) {
29
+ const names = Object.keys(reads);
30
+ const results = await Promise.all(names.map((name) => reads[name]));
31
+ const out = {};
32
+ for (const [at, name] of names.entries()) {
33
+ const result = results[at];
34
+ if (result.code !== 0)
35
+ return { failed: name, code: result.code };
36
+ out[name] = result.output;
37
+ }
38
+ return out;
39
+ }
40
+ /**
41
+ * Each secret the change past `base` holds, or null when git could not say
42
+ * what changed (the read that failed is logged). The value never leaves this
43
+ * function.
44
+ */
45
+ export async function placedSecretsInChange(cwd, base, secrets, opts) {
46
+ if (secrets.length === 0)
47
+ return [];
48
+ const skipFiles = new Set((opts.skip ?? []).filter((path) => !path.endsWith("/")));
49
+ const skipDirs = (opts.skip ?? []).filter((path) => path.endsWith("/"));
50
+ const skipped = (path) => skipFiles.has(path) || skipDirs.some((dir) => path.startsWith(dir));
51
+ const git = (args) => opts.exec(["git", "-c", "core.quotepath=off", ...args], cwd, opts.signal);
52
+ const range = `${base}..HEAD`;
53
+ // Each commit's own patch, as the host's push reads it: a merge's by what
54
+ // it changed beyond merging (`remerge`), and one of three parents or more,
55
+ // which `remerge` shows nothing for, against its first parent.
56
+ const patch = ["--format=", "-p", "-U0", "--text", "--no-color", "--no-ext-diff"];
57
+ const remerge = "--diff-merges=remerge";
58
+ const octopus = ["--min-parents=3", "--diff-merges=first-parent"];
59
+ const read = await readAll({
60
+ diff: git(["diff", base, "-U0", "--no-color", "--no-renames", "--no-ext-diff", "--text"]),
61
+ changedPaths: git(["diff", base, "--name-only", "-z", "--no-renames"]),
62
+ others: git(["ls-files", "--others", "--exclude-standard", "-z"]),
63
+ merged: git(["log", remerge, ...patch, range]),
64
+ octopusMerged: git(["log", ...octopus, ...patch, range]),
65
+ mergedPaths: git(["log", remerge, "--format=", "--name-only", "-z", range]),
66
+ octopusPaths: git(["log", ...octopus, "--format=", "--name-only", "-z", range]),
67
+ messages: git(["log", "--format=%B%x00", range]),
68
+ });
69
+ if ("failed" in read) {
70
+ logEvent({
71
+ source: "placed-values",
72
+ level: "warn",
73
+ event: "heal_scan_unread",
74
+ fields: { read: read.failed, exitCode: read.code },
75
+ });
76
+ return null;
77
+ }
78
+ const { diff, changedPaths, others, messages } = read;
79
+ const history = `${read.merged}\n${read.octopusMerged}`;
80
+ const historyPaths = `${read.mergedPaths}\0${read.octopusPaths}`;
81
+ const split = (text) => text.split("\0").filter(Boolean);
82
+ const texts = addedTextOfDiff(diff)
83
+ .filter((file) => !skipped(file.path))
84
+ .map((file) => ({ path: file.path, text: file.lines.map((line) => line.text).join("\n") }));
85
+ const readFile = opts.readFile ?? ((path) => readFileSync(path));
86
+ for (const path of split(others)) {
87
+ if (skipped(path))
88
+ continue;
89
+ try {
90
+ texts.push({
91
+ path,
92
+ text: readFile(join(cwd, path)).subarray(0, MAX_READ_BYTES).toString("utf8"),
93
+ });
94
+ }
95
+ catch {
96
+ // A file gone since git listed it holds nothing to push.
97
+ }
98
+ }
99
+ const paths = [...split(changedPaths), ...split(others)].filter((path) => !skipped(path));
100
+ const historyText = addedTextOfDiff(history)
101
+ .map((file) => file.lines.map((line) => line.text).join("\n"))
102
+ .join("\n");
103
+ // A path is shown with every secret out of it, the longest first, never
104
+ // only the one it is named for.
105
+ const longestFirst = [...secrets].sort((a, b) => b.value.length - a.value.length);
106
+ const shown = (path) => longestFirst.reduce((out, { value }) => out.split(value).join(PLACED_VALUE_MARK), path);
107
+ const hits = [];
108
+ const named = new Set();
109
+ for (const { name, value } of secrets) {
110
+ if (named.has(name))
111
+ continue;
112
+ const files = [
113
+ ...new Set([
114
+ ...texts.filter((file) => file.text.includes(value)).map((file) => file.path),
115
+ ...paths.filter((path) => path.includes(value)),
116
+ ]),
117
+ ].map(shown);
118
+ // A commit that holds it is pushed even once the tree no longer does.
119
+ const committed = historyText.includes(value) || split(historyPaths).some((path) => path.includes(value));
120
+ const message = messages.includes(value);
121
+ if (files.length === 0 && !committed && !message)
122
+ continue;
123
+ named.add(name);
124
+ hits.push({ name, files, committed, message });
125
+ }
126
+ return hits;
127
+ }
128
+ /** `a`, `a and b`, `a, b and c`. */
129
+ function listed(items) {
130
+ return items.length < 2
131
+ ? (items[0] ?? "")
132
+ : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
133
+ }
134
+ /** The ask: each secret by name and place, what to do instead, and to finish as before. */
135
+ export function placedSecretAsk(hits, base) {
136
+ const rewrite = hits.some((hit) => hit.committed || hit.message);
137
+ return [
138
+ "Your change holds the value of a System credential, and YAGNI never pushes a change that holds one:",
139
+ ...hits.map((hit) => {
140
+ const places = [
141
+ ...hit.files.map((file) => `\`${file}\``),
142
+ ...(hit.committed
143
+ ? [`${hit.files.length ? "a" : "an earlier"} commit on this branch`]
144
+ : []),
145
+ ...(hit.message ? ["a commit message"] : []),
146
+ ];
147
+ return `- ${hit.name}, in ${listed(places)}`;
148
+ }),
149
+ "",
150
+ "Take each one out. Where the code needs it, read it from the environment instead " +
151
+ `(\`process.env.${hits[0].name}\`, \`os.environ["${hits[0].name}"]\`), and in a test use an obvious fake. ` +
152
+ `You cannot see the value: what you read shows it as ${PLACED_VALUE_MARK}, so find the line by what is ` +
153
+ "around it, or write the file again whole. Never read /run/yagni/env, or print a value, to find it.",
154
+ rewrite
155
+ ? `A commit on this branch holds it too, and every commit is pushed: rewrite this branch's commits so that none of them, and no message, holds it (for example \`git reset --soft ${base}\` once the files are fixed, then commit again).`
156
+ : "Then commit.",
157
+ "Then end your turn as before, with your report.",
158
+ ].join("\n");
159
+ }
160
+ /**
161
+ * Reads a writing turn's change for the System's secrets and, when it holds
162
+ * one, asks the model once to take it out and finish. Not asked of a turn
163
+ * that was stopped, ran out of time or ended in an error, nor on a machine
164
+ * with no secret placed.
165
+ */
166
+ export async function healPlacedSecrets(run, turn, opts) {
167
+ const unchanged = { run, asked: [], note: null };
168
+ const { store, base } = opts;
169
+ if (!store || !base || opts.signal?.aborted || run.timedOut || run.exitCode !== 0) {
170
+ return unchanged;
171
+ }
172
+ const scan = () => placedSecretsInChange(opts.cwd, base, store.secrets(), opts).catch(() => null);
173
+ const unread = "The change could not be read for the System's credentials before the turn ended; the host still checks its push.";
174
+ const hits = await scan();
175
+ if (hits === null)
176
+ return { ...unchanged, note: unread };
177
+ if (hits.length === 0)
178
+ return unchanged;
179
+ const again = await turn(placedSecretAsk(hits, base));
180
+ const left = await scan();
181
+ return {
182
+ run: again.exitCode === 0 ? again : run,
183
+ asked: [again],
184
+ note: left === null ? unread : stillThereNote(left),
185
+ };
186
+ }
187
+ /** The result's note for secrets still in the change after the ask, by name; null when none is. */
188
+ function stillThereNote(left) {
189
+ if (left.length === 0)
190
+ return null;
191
+ const names = left.map((hit) => hit.name);
192
+ const them = names.length > 1 ? "them" : "it";
193
+ return `The change still holds the System's ${listed(names)} after one ask to take ${them} out: YAGNI will not push it, and a person is asked.`;
194
+ }
195
+ //# sourceMappingURL=placedValueHeal.js.map
@@ -38,6 +38,7 @@
38
38
  * kept: the review loop and its round cap, the fixer, and the plan stage's
39
39
  * own clock.
40
40
  */
41
+ import { type PlacedValues } from "../placedValues.js";
41
42
  import { type AttemptResult, type CloudIdentity, type CloudStage } from "./cloud.js";
42
43
  import type { ContinuationInputs } from "./continuation.js";
43
44
  import { type PlanChange } from "./planChanges.js";
@@ -176,6 +177,8 @@ export interface SessionTurnDeps {
176
177
  rss: number;
177
178
  heapUsed: number;
178
179
  };
180
+ /** A yak's placed values (YAG-1209); absent, read from the machine, null on any other. */
181
+ placedValues?: PlacedValues | null;
179
182
  }
180
183
  export interface SessionTurnOutcome {
181
184
  /** A written plan, or a clean turn whose branch carries the attempt's committed work. */
@@ -41,12 +41,14 @@
41
41
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
42
42
  import { homedir } from "node:os";
43
43
  import { join, relative } from "node:path";
44
+ import { openPlacedValues } from "../placedValues.js";
44
45
  import { scanChange } from "./changeScan.js";
45
46
  import { completeCloudSession, RESULT_FILE_NAME, } from "./cloud.js";
46
47
  import { finishExec } from "./finish.js";
47
48
  import { MISSION_CHECKS_FILE_NAME, readMissionChecksFile } from "./missionChecks.js";
48
49
  import { creditExhaustionReason } from "./orchestrator.js";
49
50
  import { WORK_A_TICKET_SKILL } from "./personas.js";
51
+ import { healPlacedSecrets } from "./placedValueHeal.js";
50
52
  import { extractPlanJson } from "./planOutput.js";
51
53
  import { PLAN_CHANGES_RULE, parsePlanChanges, planChangeNote, } from "./planChanges.js";
52
54
  import { runStage as defaultRunStage } from "./runner.js";
@@ -553,6 +555,22 @@ async function runTurn(input, deps, pulse) {
553
555
  try {
554
556
  let run = await turn(message);
555
557
  stages.push(run);
558
+ if (writes) {
559
+ // A System secret in the change is taken out in this session, before
560
+ // the host's push would stop on it for a person (YAG-1209).
561
+ const healed = await healPlacedSecrets(run, turn, {
562
+ cwd: input.cwd,
563
+ base: baseSha,
564
+ store: deps.placedValues === undefined ? openPlacedValues() : deps.placedValues,
565
+ exec,
566
+ skip: preRunDirt,
567
+ ...(input.signal ? { signal: input.signal } : {}),
568
+ });
569
+ stages.push(...healed.asked);
570
+ run = healed.run;
571
+ if (healed.note)
572
+ notes.push(healed.note);
573
+ }
556
574
  if (input.stage === "plan") {
557
575
  const planned = await planWithBlock(run, turn, input.signal);
558
576
  stages.push(...planned.asked);
@@ -0,0 +1,102 @@
1
+ /**
2
+ * A yak's System places its provided values on the machine the session works
3
+ * on (YAG-1209): a tmpfs file, `/run/yagni/secret/env`, linked at
4
+ * `/run/yagni/env`, owned by the run user the session runs as, so the session
5
+ * can read it, and a running service's environment too. This module is the
6
+ * first of three precautions: it replaces each placed secret in what the
7
+ * model reads. Only the secrets count ({@link PLACED_SECRET_NAMES_FILE}: a
8
+ * credential the host's one change classifier calls a secret); test data
9
+ * and a public value the model reads as they are. The session is told never
10
+ * to read the file (`branding.ts`, `PLACED_VALUES_SECTION`), its finish asks
11
+ * the model to take a secret out of its change (`pipeline/placedValueHeal.ts`),
12
+ * and the host refuses a push that still holds one (the backend's
13
+ * `attempts/placedValues.ts`).
14
+ *
15
+ * It acts only where the file is: on any other machine {@link openPlacedValues}
16
+ * opens nothing and no handler registers, so every other session is unchanged.
17
+ * Where it is, three handlers run after every other one the extension adds:
18
+ * `tool_result` rewrites what a tool returns before the model reads it (and
19
+ * before the session file keeps it), `message_end` rewrites any other message
20
+ * before the session file keeps it (a background job's notification quotes
21
+ * the job's output tail, and pi's compaction and branch summaries read the
22
+ * saved session, never a model call's context), and `context` rewrites every
23
+ * message a model call carries, as the backstop. An assistant's own message
24
+ * is never rewritten: its thinking is signed.
25
+ *
26
+ * Honest scope: an exact match of each value in the forms it is printed in
27
+ * (raw, inside the file, as bash and JSON quote it). A value the session
28
+ * encodes first (base64, split, reversed), part of a value cut by a tool's
29
+ * truncation, and a value inside an image all get past.
30
+ */
31
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
32
+ /** Where the backend places the values (`repos/system/needs/placement.ts`, `SYSTEM_SECRET_FILE`). */
33
+ export declare const PLACED_VALUES_FILE = "/run/yagni/secret/env";
34
+ /** The link scripts source (`SYSTEM_ENV_PATH`). */
35
+ export declare const PLACED_VALUES_LINK = "/run/yagni/env";
36
+ /**
37
+ * The names of the placed values that are secrets, one per line, names only
38
+ * (`SYSTEM_SECRET_NAMES_FILE`): the host's one classifier picked them
39
+ * (`placedSecretsOf`, a credential its change scan calls a secret). Every
40
+ * other value (test data, a public URL) the model reads as it is. A machine
41
+ * whose values were placed without this file keeps every value from the model.
42
+ */
43
+ export declare const PLACED_SECRET_NAMES_FILE = "/run/yagni/secret/secret-names";
44
+ /**
45
+ * The shortest value replaced: the shortest a person can enter for a need
46
+ * (`SYSTEM_NEED_VALUE_MIN_LENGTH`), and the floor the host's redactors keep.
47
+ * Anything shorter (`postgres`, a port) would mangle ordinary output.
48
+ */
49
+ export declare const PLACED_VALUE_MIN_LENGTH = 8;
50
+ /** The host's own mark (`redactValues`), so the transcript reads the same on both sides. */
51
+ export declare const PLACED_VALUE_MARK = "[REDACTED]";
52
+ /**
53
+ * The values in the host's file: one `NAME='value'` line per value, a `'`
54
+ * inside written `'"'"'`, a value free to span lines. A line it cannot read
55
+ * is skipped.
56
+ */
57
+ export declare function parsePlacedEnvFile(text: string): Map<string, string>;
58
+ /**
59
+ * Every form a value is printed in, longest first: as it is, inside the
60
+ * host's file, as bash quotes it (`declare -p`, `set`, in single, double or
61
+ * ANSI-C quotes), and as JSON escapes it (`docker inspect`, `jq`, a
62
+ * multi-line key). Values under the floor are left out.
63
+ */
64
+ export declare function placedValueForms(values: Iterable<string>): string[];
65
+ /** `text` with every form replaced by the mark. */
66
+ export declare function redactPlacedText(text: string, forms: readonly string[]): string;
67
+ /** A secret the System placed, by the variable a person knows it as; never logged. */
68
+ export interface PlacedSecret {
69
+ name: string;
70
+ value: string;
71
+ }
72
+ /** The secrets this process has seen, read again at every check; never forgotten. */
73
+ export interface PlacedValues {
74
+ /** Reads the file again and returns every form of every secret seen so far. */
75
+ forms(): string[];
76
+ /**
77
+ * Reads the file again and returns every secret the host's list named so
78
+ * far, each by its first name: what the session is asked to take out of
79
+ * its change. A value kept from the model only because there is no list is
80
+ * never one, so a fixture's test data is never asked about.
81
+ */
82
+ secrets(): PlacedSecret[];
83
+ }
84
+ /**
85
+ * Opens the placed values when one of `paths` is there, else null (no file:
86
+ * not a yak's machine, and nothing should change). Only the secrets among
87
+ * them are kept from the model: those `namesPath` lists. A secret is kept
88
+ * for the life of the process, so a session that deletes the file and prints
89
+ * a copy is still covered, and one placed later is added. While there is no
90
+ * list (a placement from before it, or the list gone), every value read is
91
+ * kept from the model too, but only until a list is read: it is read again
92
+ * at every check, and test data and a public value then show as they are.
93
+ */
94
+ export declare function openPlacedValues(paths?: readonly string[], namesPath?: string | null): PlacedValues | null;
95
+ /**
96
+ * Registers the handlers. Call it after every other `tool_result`,
97
+ * `message_end`, `context` and `before_agent_start` handler the extension
98
+ * adds, so it sees what they append. Each message handler withholds what it
99
+ * could not check rather than pass it.
100
+ */
101
+ export declare function registerPlacedValueRedaction(pi: ExtensionAPI, store: PlacedValues): void;
102
+ //# sourceMappingURL=placedValues.d.ts.map
@@ -0,0 +1,462 @@
1
+ /**
2
+ * A yak's System places its provided values on the machine the session works
3
+ * on (YAG-1209): a tmpfs file, `/run/yagni/secret/env`, linked at
4
+ * `/run/yagni/env`, owned by the run user the session runs as, so the session
5
+ * can read it, and a running service's environment too. This module is the
6
+ * first of three precautions: it replaces each placed secret in what the
7
+ * model reads. Only the secrets count ({@link PLACED_SECRET_NAMES_FILE}: a
8
+ * credential the host's one change classifier calls a secret); test data
9
+ * and a public value the model reads as they are. The session is told never
10
+ * to read the file (`branding.ts`, `PLACED_VALUES_SECTION`), its finish asks
11
+ * the model to take a secret out of its change (`pipeline/placedValueHeal.ts`),
12
+ * and the host refuses a push that still holds one (the backend's
13
+ * `attempts/placedValues.ts`).
14
+ *
15
+ * It acts only where the file is: on any other machine {@link openPlacedValues}
16
+ * opens nothing and no handler registers, so every other session is unchanged.
17
+ * Where it is, three handlers run after every other one the extension adds:
18
+ * `tool_result` rewrites what a tool returns before the model reads it (and
19
+ * before the session file keeps it), `message_end` rewrites any other message
20
+ * before the session file keeps it (a background job's notification quotes
21
+ * the job's output tail, and pi's compaction and branch summaries read the
22
+ * saved session, never a model call's context), and `context` rewrites every
23
+ * message a model call carries, as the backstop. An assistant's own message
24
+ * is never rewritten: its thinking is signed.
25
+ *
26
+ * Honest scope: an exact match of each value in the forms it is printed in
27
+ * (raw, inside the file, as bash and JSON quote it). A value the session
28
+ * encodes first (base64, split, reversed), part of a value cut by a tool's
29
+ * truncation, and a value inside an image all get past.
30
+ */
31
+ import { readFileSync, statSync } from "node:fs";
32
+ import { logEvent } from "./errorSink.js";
33
+ /** Where the backend places the values (`repos/system/needs/placement.ts`, `SYSTEM_SECRET_FILE`). */
34
+ export const PLACED_VALUES_FILE = "/run/yagni/secret/env";
35
+ /** The link scripts source (`SYSTEM_ENV_PATH`). */
36
+ export const PLACED_VALUES_LINK = "/run/yagni/env";
37
+ /**
38
+ * The names of the placed values that are secrets, one per line, names only
39
+ * (`SYSTEM_SECRET_NAMES_FILE`): the host's one classifier picked them
40
+ * (`placedSecretsOf`, a credential its change scan calls a secret). Every
41
+ * other value (test data, a public URL) the model reads as it is. A machine
42
+ * whose values were placed without this file keeps every value from the model.
43
+ */
44
+ export const PLACED_SECRET_NAMES_FILE = "/run/yagni/secret/secret-names";
45
+ /**
46
+ * The shortest value replaced: the shortest a person can enter for a need
47
+ * (`SYSTEM_NEED_VALUE_MIN_LENGTH`), and the floor the host's redactors keep.
48
+ * Anything shorter (`postgres`, a port) would mangle ordinary output.
49
+ */
50
+ export const PLACED_VALUE_MIN_LENGTH = 8;
51
+ /** The host's own mark (`redactValues`), so the transcript reads the same on both sides. */
52
+ export const PLACED_VALUE_MARK = "[REDACTED]";
53
+ /** The tmpfs is mounted at 1 MiB; a larger file is not the host's. */
54
+ const MAX_FILE_BYTES = 1024 * 1024;
55
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
56
+ const WITHHELD = "[The tool's output was withheld: it could not be checked for the System's placed values.]";
57
+ const WITHHELD_MESSAGE = "[This message was withheld: it could not be checked for the System's placed values.]";
58
+ /**
59
+ * The values in the host's file: one `NAME='value'` line per value, a `'`
60
+ * inside written `'"'"'`, a value free to span lines. A line it cannot read
61
+ * is skipped.
62
+ */
63
+ export function parsePlacedEnvFile(text) {
64
+ const values = new Map();
65
+ let at = 0;
66
+ while (at < text.length) {
67
+ const eq = text.indexOf("=", at);
68
+ const lineEnd = text.indexOf("\n", at);
69
+ const name = eq === -1 ? "" : text.slice(at, eq);
70
+ const read = NAME.test(name) && (lineEnd === -1 || eq < lineEnd) ? quotedValueAt(text, eq + 1) : null;
71
+ if (read)
72
+ values.set(name, read.value);
73
+ at = read ? read.next : lineEnd === -1 ? text.length : lineEnd + 1;
74
+ }
75
+ return values;
76
+ }
77
+ /**
78
+ * The quoted value that starts at `start` (`'a'"'"'b'`, free to span lines),
79
+ * and where the next line starts; null when the line is not one the host writes.
80
+ */
81
+ function quotedValueAt(text, start) {
82
+ if (start >= text.length || text[start] === "\n")
83
+ return null;
84
+ let cursor = start;
85
+ let value = "";
86
+ while (cursor < text.length && text[cursor] !== "\n") {
87
+ if (text.startsWith(`"'"`, cursor)) {
88
+ value += "'";
89
+ cursor += 3;
90
+ continue;
91
+ }
92
+ const close = text[cursor] === "'" ? text.indexOf("'", cursor + 1) : -1;
93
+ if (close === -1)
94
+ return null;
95
+ value += text.slice(cursor + 1, close);
96
+ cursor = close + 1;
97
+ }
98
+ return { value, next: cursor + 1 };
99
+ }
100
+ /** Bash's own names for the characters its ANSI-C quoting escapes (`ansic_quote`). */
101
+ const ANSI_C_NAMED = {
102
+ "\u001b": "\\E",
103
+ "\u0007": "\\a",
104
+ "\v": "\\v",
105
+ "\b": "\\b",
106
+ "\f": "\\f",
107
+ "\n": "\\n",
108
+ "\r": "\\r",
109
+ "\t": "\\t",
110
+ "\\": "\\\\",
111
+ "'": "\\'",
112
+ };
113
+ /** A value inside bash's `$'...'` (`declare -p` of a value with a newline or a control character). */
114
+ function ansiCQuoted(value) {
115
+ let out = "";
116
+ for (const char of value) {
117
+ const code = char.codePointAt(0);
118
+ const named = ANSI_C_NAMED[char];
119
+ if (named)
120
+ out += named;
121
+ else if (code < 0x20 || code === 0x7f)
122
+ out += `\\${code.toString(8).padStart(3, "0")}`;
123
+ else
124
+ out += char;
125
+ }
126
+ return out;
127
+ }
128
+ /**
129
+ * Every form a value is printed in, longest first: as it is, inside the
130
+ * host's file, as bash quotes it (`declare -p`, `set`, in single, double or
131
+ * ANSI-C quotes), and as JSON escapes it (`docker inspect`, `jq`, a
132
+ * multi-line key). Values under the floor are left out.
133
+ */
134
+ export function placedValueForms(values) {
135
+ const forms = new Set();
136
+ for (const value of values) {
137
+ if (value.length < PLACED_VALUE_MIN_LENGTH)
138
+ continue;
139
+ forms.add(value);
140
+ forms.add(value.replaceAll("'", `'"'"'`));
141
+ forms.add(value.replaceAll("'", `'\\''`));
142
+ forms.add(value.replace(/[\\"$`]/g, (char) => `\\${char}`));
143
+ forms.add(ansiCQuoted(value));
144
+ forms.add(JSON.stringify(value).slice(1, -1));
145
+ }
146
+ return [...forms].sort((a, b) => b.length - a.length);
147
+ }
148
+ /** `text` with every form replaced by the mark. */
149
+ export function redactPlacedText(text, forms) {
150
+ let out = text;
151
+ for (const form of forms) {
152
+ if (out.includes(form))
153
+ out = out.split(form).join(PLACED_VALUE_MARK);
154
+ }
155
+ return out;
156
+ }
157
+ /** The file's text, or null when it is not a regular file of the host's size. */
158
+ function readPlacedFile(path) {
159
+ try {
160
+ const stat = statSync(path);
161
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES)
162
+ return null;
163
+ return readFileSync(path, "utf8");
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ }
169
+ /** The names the host listed as secrets, or null when it listed none (a placement before the list). */
170
+ function readSecretNames(path) {
171
+ const text = path ? readPlacedFile(path) : null;
172
+ if (text === null)
173
+ return null;
174
+ return new Set(text
175
+ .split("\n")
176
+ .map((line) => line.trim())
177
+ .filter((line) => NAME.test(line)));
178
+ }
179
+ /**
180
+ * Opens the placed values when one of `paths` is there, else null (no file:
181
+ * not a yak's machine, and nothing should change). Only the secrets among
182
+ * them are kept from the model: those `namesPath` lists. A secret is kept
183
+ * for the life of the process, so a session that deletes the file and prints
184
+ * a copy is still covered, and one placed later is added. While there is no
185
+ * list (a placement from before it, or the list gone), every value read is
186
+ * kept from the model too, but only until a list is read: it is read again
187
+ * at every check, and test data and a public value then show as they are.
188
+ */
189
+ export function openPlacedValues(paths = [PLACED_VALUES_FILE, PLACED_VALUES_LINK], namesPath = PLACED_SECRET_NAMES_FILE) {
190
+ /** Each secret the list named, by value: never forgotten. */
191
+ const kept = new Map();
192
+ /** Every value read while there is no list: kept until a list is read. */
193
+ const unlisted = new Map();
194
+ let forms = [];
195
+ const all = () => new Map([...unlisted, ...kept]);
196
+ const read = () => {
197
+ let found = false;
198
+ const names = readSecretNames(namesPath);
199
+ // The list says what is a secret: whatever it does not name shows again.
200
+ if (names !== null)
201
+ unlisted.clear();
202
+ for (const path of paths) {
203
+ const text = readPlacedFile(path);
204
+ if (text === null)
205
+ continue;
206
+ found = true;
207
+ for (const [name, value] of parsePlacedEnvFile(text)) {
208
+ if (names === null)
209
+ unlisted.set(value, name);
210
+ else if (names.has(name) && !kept.has(value))
211
+ kept.set(value, name);
212
+ }
213
+ }
214
+ // A handful of values: their forms are made again at each check.
215
+ forms = placedValueForms(all().keys());
216
+ return found;
217
+ };
218
+ if (!read())
219
+ return null;
220
+ return {
221
+ forms: () => {
222
+ read();
223
+ return forms;
224
+ },
225
+ secrets: () => {
226
+ read();
227
+ return [...kept].map(([value, name]) => ({ name, value }));
228
+ },
229
+ };
230
+ }
231
+ /** The parts with each text part's values replaced; the same array when nothing changed. */
232
+ function redactParts(parts, forms) {
233
+ let changed = false;
234
+ const next = parts.map((part) => {
235
+ if (part?.type !== "text" || typeof part.text !== "string")
236
+ return part;
237
+ const text = redactPlacedText(part.text, forms);
238
+ if (text === part.text)
239
+ return part;
240
+ changed = true;
241
+ return { ...part, text };
242
+ });
243
+ return changed ? next : parts;
244
+ }
245
+ /** String or parts, as a user or custom message carries its content. */
246
+ function redactContent(content, forms) {
247
+ if (typeof content === "string")
248
+ return redactPlacedText(content, forms);
249
+ return (Array.isArray(content) ? redactParts(content, forms) : content);
250
+ }
251
+ /** How deep {@link redactDetails} walks: a tool's details are a few levels of plain data. */
252
+ const MAX_DETAILS_DEPTH = 8;
253
+ /**
254
+ * A tool result's `details` with each string's secrets replaced: plain
255
+ * objects and arrays walked, anything else left as it is. The model never
256
+ * reads them, but the session saves them (the edit tool's `diff` and
257
+ * `patch` quote the lines around an edit). The same value when nothing changed.
258
+ */
259
+ function redactDetails(value, forms, depth = 0) {
260
+ if (typeof value === "string")
261
+ return redactPlacedText(value, forms);
262
+ if (depth >= MAX_DETAILS_DEPTH || value === null || typeof value !== "object")
263
+ return value;
264
+ if (Array.isArray(value)) {
265
+ const next = value.map((item) => redactDetails(item, forms, depth + 1));
266
+ return next.some((item, at) => item !== value[at]) ? next : value;
267
+ }
268
+ const proto = Object.getPrototypeOf(value);
269
+ if (proto !== Object.prototype && proto !== null)
270
+ return value;
271
+ let changed = false;
272
+ const next = {};
273
+ for (const [key, item] of Object.entries(value)) {
274
+ next[key] = redactDetails(item, forms, depth + 1);
275
+ if (next[key] !== item)
276
+ changed = true;
277
+ }
278
+ return changed ? next : value;
279
+ }
280
+ /** One message with its values replaced; the same object when nothing changed. Never an assistant's. */
281
+ function redactMessage(message, forms) {
282
+ const m = message;
283
+ switch (m.role) {
284
+ case "user":
285
+ case "custom":
286
+ case "toolResult": {
287
+ const content = m.content === undefined ? undefined : redactContent(m.content, forms);
288
+ const details = redactDetails(m.details, forms);
289
+ return content === m.content && details === m.details
290
+ ? message
291
+ : {
292
+ ...m,
293
+ ...(content !== undefined ? { content } : {}),
294
+ ...(details !== undefined ? { details } : {}),
295
+ };
296
+ }
297
+ case "bashExecution": {
298
+ if (typeof m.output !== "string")
299
+ return message;
300
+ const output = redactPlacedText(m.output, forms);
301
+ return output === m.output ? message : { ...m, output };
302
+ }
303
+ case "compactionSummary":
304
+ case "branchSummary": {
305
+ if (typeof m.summary !== "string")
306
+ return message;
307
+ const summary = redactPlacedText(m.summary, forms);
308
+ return summary === m.summary ? message : { ...m, summary };
309
+ }
310
+ default:
311
+ return message;
312
+ }
313
+ }
314
+ /**
315
+ * One message with its text withheld, for one that could not be checked: the
316
+ * same text-bearing fields {@link redactMessage} rewrites, `details` dropped.
317
+ * Never an assistant's.
318
+ */
319
+ function withheldMessage(message) {
320
+ switch (message.role) {
321
+ case "user":
322
+ case "custom":
323
+ case "toolResult": {
324
+ const { details: _unchecked, ...rest } = message;
325
+ return { ...rest, content: [{ type: "text", text: WITHHELD_MESSAGE }] };
326
+ }
327
+ case "bashExecution":
328
+ return { ...message, output: WITHHELD_MESSAGE };
329
+ case "compactionSummary":
330
+ case "branchSummary":
331
+ return { ...message, summary: WITHHELD_MESSAGE };
332
+ default:
333
+ return message;
334
+ }
335
+ }
336
+ /** The message redacted, or withheld when it could not be checked; never passed through unchecked. */
337
+ function checkedMessage(message, forms, event) {
338
+ try {
339
+ if (forms === null)
340
+ throw new Error("the placed values could not be read");
341
+ return redactMessage(message, forms);
342
+ }
343
+ catch (err) {
344
+ logEvent({
345
+ source: "placed-values",
346
+ level: "warn",
347
+ event,
348
+ fields: { role: message.role, errorClass: err instanceof Error ? err.name : typeof err },
349
+ });
350
+ return withheldMessage(message);
351
+ }
352
+ }
353
+ /**
354
+ * Every form, or null when they could not be read (a message is then
355
+ * withheld, not passed), the failure logged by its error's class.
356
+ */
357
+ function formsOf(store, handler) {
358
+ try {
359
+ return store.forms();
360
+ }
361
+ catch (err) {
362
+ logEvent({
363
+ source: "placed-values",
364
+ level: "warn",
365
+ event: "values_unread",
366
+ fields: { handler, errorClass: err instanceof Error ? err.name : typeof err },
367
+ });
368
+ return null;
369
+ }
370
+ }
371
+ /**
372
+ * Registers the handlers. Call it after every other `tool_result`,
373
+ * `message_end`, `context` and `before_agent_start` handler the extension
374
+ * adds, so it sees what they append. Each message handler withholds what it
375
+ * could not check rather than pass it.
376
+ */
377
+ export function registerPlacedValueRedaction(pi, store) {
378
+ pi.on("tool_result", (event) => {
379
+ try {
380
+ const forms = store.forms();
381
+ if (forms.length === 0)
382
+ return undefined;
383
+ const raw = event.content;
384
+ // The model never reads `details`, but the session saves them.
385
+ const details = redactDetails(event.details, forms);
386
+ const withDetails = details === event.details ? {} : { details };
387
+ if (typeof raw === "string") {
388
+ // Off pi's contract, but a tool that answers one string is still checked.
389
+ const text = redactPlacedText(raw, forms);
390
+ return text === raw && details === event.details
391
+ ? undefined
392
+ : { content: [{ type: "text", text }], ...withDetails };
393
+ }
394
+ if (!Array.isArray(event.content)) {
395
+ return details === event.details ? undefined : withDetails;
396
+ }
397
+ const content = redactParts(event.content, forms);
398
+ return content === event.content && details === event.details
399
+ ? undefined
400
+ : { content, ...withDetails };
401
+ }
402
+ catch (err) {
403
+ // Never pass through what could not be checked.
404
+ logEvent({
405
+ source: "placed-values",
406
+ level: "warn",
407
+ event: "tool_result_withheld",
408
+ fields: { errorClass: err instanceof Error ? err.name : typeof err },
409
+ });
410
+ // pi keeps a result's `details` unless a handler names new ones.
411
+ return { content: [{ type: "text", text: WITHHELD }], details: {} };
412
+ }
413
+ });
414
+ // A message is saved as `message_end` leaves it, and pi's compaction and
415
+ // branch summaries read the saved session, never the `context` pass below:
416
+ // a user or extension message that quotes a value (a background job's
417
+ // notice quotes its output) is saved replaced.
418
+ pi.on("message_end", (event) => {
419
+ const forms = formsOf(store, "message_end");
420
+ if (forms?.length === 0)
421
+ return undefined;
422
+ const message = checkedMessage(event.message, forms, "message_withheld");
423
+ return message === event.message ? undefined : { message };
424
+ });
425
+ pi.on("context", (event) => {
426
+ const forms = formsOf(store, "context");
427
+ if (forms?.length === 0 || !Array.isArray(event.messages))
428
+ return undefined;
429
+ let changed = false;
430
+ const messages = event.messages.map((message) => {
431
+ const next = checkedMessage(message, forms, "context_message_withheld");
432
+ if (next !== message)
433
+ changed = true;
434
+ return next;
435
+ });
436
+ return changed ? { messages } : undefined;
437
+ });
438
+ // The system prompt is not a message: pi builds it from the repository's
439
+ // own instruction files (AGENTS.md and the like), which could quote a
440
+ // secret, and this extension's branding. Registered after the branding, so
441
+ // it reads the prompt as sent.
442
+ pi.on("before_agent_start", (event) => {
443
+ if (typeof event.systemPrompt !== "string")
444
+ return undefined;
445
+ const forms = formsOf(store, "before_agent_start");
446
+ if (forms === null) {
447
+ // The one handler that does not fail closed: the prompt is the
448
+ // session's whole instructions, and withholding it would end the
449
+ // session. It goes as it is; `values_unread` above logs why.
450
+ logEvent({
451
+ source: "placed-values",
452
+ level: "warn",
453
+ event: "system_prompt_unchecked",
454
+ fields: {},
455
+ });
456
+ return undefined;
457
+ }
458
+ const systemPrompt = redactPlacedText(event.systemPrompt, forms);
459
+ return systemPrompt === event.systemPrompt ? undefined : { systemPrompt };
460
+ });
461
+ }
462
+ //# sourceMappingURL=placedValues.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yagni-app/code-staging",
3
- "version": "1.2.14-staging.2281.1",
3
+ "version": "1.2.14-staging.2282.1",
4
4
  "description": "YAGNI Code: a terminal coding agent that already knows your company. One YAGNI login routes the model and grounds the agent in your team's context.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "YAGNI, Inc. <jack@yagni.app> (https://yagni.app)",
@@ -58,5 +58,5 @@
58
58
  "turndown": "^7.2.4",
59
59
  "typebox": "^1.3.15"
60
60
  },
61
- "yagniSourceSha": "63e73bd85004c339d647aa5ce5f79c71527a9e89"
61
+ "yagniSourceSha": "ab5e7376b562f4a0af054b2bd7377214afdc1394"
62
62
  }