@yagni-app/code-staging 1.2.14-staging.2276.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.
@@ -0,0 +1,255 @@
1
+ /**
2
+ * A person's message reaches a running session-lane turn (YAG-1210). While a
3
+ * yak's ticket runs, the host writes each message a person sends it into
4
+ * this execution's inbox folder on the machine
5
+ * (`<input folder>/inbox/<execution>/<message>.json`, `yaks/inbox.ts` in the
6
+ * backend). After every tool call this turn reads the folder and hands each
7
+ * new message to pi as a steer (`deliverAs: "steer"`, pi 0.84.1): pi puts it
8
+ * in the conversation once the current tool calls finish, before the model's
9
+ * next step, so it never cuts a command off.
10
+ *
11
+ * The receipt is the proof it arrived: `<message>.received`, written beside
12
+ * the message when pi puts that steer into the conversation (its
13
+ * `message_end`), never when it is only queued. pi exits when its prompt is
14
+ * done, so a steer queued after the model's last tool call may never be
15
+ * taken; such a message has no receipt, and the host sends it the way it
16
+ * always has, to the next turn. The host reads the receipts (its watch's
17
+ * poll, `sessionPoll.ts`) and records them, so each message arrives once.
18
+ *
19
+ * Fail-soft and bounded: a folder that is missing or cannot be read, a file
20
+ * that is too big or does not parse, a send that throws, or a receipt that
21
+ * cannot be written leave the turn running exactly as it was, and the
22
+ * message to the host's fallback. The message is data: the host writes it
23
+ * wrapped as a person's words, and nothing here runs or follows it. Only the
24
+ * session's own turn takes messages (never a subagent it spawns), and only
25
+ * while its prompt is running, so a send never starts a new prompt.
26
+ */
27
+ import { existsSync as nodeExistsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync, } from "node:fs";
28
+ import { join } from "node:path";
29
+ import { logEvent } from "../errorSink.js";
30
+ import { isSessionLaneTurn, SESSION_INBOX_DIR_ENV } from "./sessionLane.js";
31
+ export { SESSION_INBOX_DIR_ENV, sessionInboxDir } from "./sessionLane.js";
32
+ /** A message the host wrote: `<id>.json`. */
33
+ export const INBOX_MESSAGE_SUFFIX = ".json";
34
+ /** The receipt this turn writes once pi put the message in the conversation: `<id>.received`. */
35
+ export const INBOX_RECEIPT_SUFFIX = ".received";
36
+ /** The most one message file may weigh; a larger one is never read, and goes the host's other way. */
37
+ export const MAX_INBOX_FILE_BYTES = 32 * 1024;
38
+ /** The most of a message's text one steer carries. */
39
+ export const MAX_STEER_CHARS = 16_000;
40
+ /** The most messages one check hands to pi: the oldest first. */
41
+ export const MAX_INBOX_FILES_PER_CHECK = 20;
42
+ /**
43
+ * The most message files one check reads to find the oldest: more than the
44
+ * host ever gives one execution's inbox (50, `MAX_INBOX_MESSAGES_PER_EXECUTION`
45
+ * in the backend's `yaks/inbox.ts`), so messages reach pi in the order they
46
+ * were written whatever their file names.
47
+ */
48
+ export const MAX_INBOX_FILES_READ = 64;
49
+ const MESSAGE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
50
+ /** Whether a string is a message id the inbox names files by. */
51
+ export function isInboxMessageId(value) {
52
+ return MESSAGE_ID.test(value);
53
+ }
54
+ /**
55
+ * The first line of a message's steer, naming it: what the receipt matches
56
+ * the message pi puts in the conversation by, so a person's words that quote
57
+ * another message cannot answer for it.
58
+ */
59
+ export function steerHeader(id) {
60
+ return `A person on the Team wrote to you while you worked (YAGNI message ${id}).`;
61
+ }
62
+ /** A message file's text read as a message named `id`, or null when it is not one. Pure. */
63
+ export function parseInboxMessage(id, raw) {
64
+ let data;
65
+ try {
66
+ data = JSON.parse(raw);
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ if (!data || typeof data !== "object" || Array.isArray(data))
72
+ return null;
73
+ const record = data;
74
+ if (record.id !== id || typeof record.text !== "string")
75
+ return null;
76
+ const text = record.text.trim();
77
+ if (!text)
78
+ return null;
79
+ const at = typeof record.at === "number" && Number.isFinite(record.at) ? record.at : 0;
80
+ return { id, text, at };
81
+ }
82
+ /** The steer a message is handed over as: its header, then its words, capped. Pure. */
83
+ export function steerText(message) {
84
+ const text = message.text.length > MAX_STEER_CHARS
85
+ ? `${message.text.slice(0, MAX_STEER_CHARS)}\n\n(cut: the rest is on the ticket's conversation)`
86
+ : message.text;
87
+ return `${steerHeader(message.id)}\n\n${text}`;
88
+ }
89
+ /** The text of a message's content, as pi holds a user message. */
90
+ function textOf(content) {
91
+ if (typeof content === "string")
92
+ return content;
93
+ if (!Array.isArray(content))
94
+ return "";
95
+ return content
96
+ .map((part) => part && typeof part === "object" && part.type === "text"
97
+ ? String(part.text ?? "")
98
+ : "")
99
+ .join("\n");
100
+ }
101
+ export const nodeInboxFs = {
102
+ list: (dir) => readdirSync(dir),
103
+ size: (path) => statSync(path).size,
104
+ read: (path) => readFileSync(path, "utf8"),
105
+ exists: (path) => nodeExistsSync(path),
106
+ writeWhole: (path, text) => {
107
+ const temp = `${path}.${process.pid}.tmp`;
108
+ writeFileSync(temp, text, { mode: 0o644 });
109
+ renameSync(temp, path);
110
+ },
111
+ };
112
+ /** The inbox's logic over its folder, its file system and pi's send. */
113
+ export function createSessionInbox(dir, send, fs = nodeInboxFs, now = Date.now) {
114
+ /** Handed to pi and not in the conversation yet: id to header. */
115
+ const pending = new Map();
116
+ /** Put in the conversation by this turn, or receipted before it. */
117
+ const taken = new Set();
118
+ const receiptOf = (id) => join(dir, `${id}${INBOX_RECEIPT_SUFFIX}`);
119
+ const unread = () => {
120
+ let names;
121
+ try {
122
+ names = fs.list(dir);
123
+ }
124
+ catch {
125
+ return [];
126
+ }
127
+ const found = [];
128
+ let read = 0;
129
+ for (const name of names.sort()) {
130
+ if (read >= MAX_INBOX_FILES_READ)
131
+ break;
132
+ if (!name.endsWith(INBOX_MESSAGE_SUFFIX))
133
+ continue;
134
+ const id = name.slice(0, -INBOX_MESSAGE_SUFFIX.length);
135
+ if (!isInboxMessageId(id) || pending.has(id) || taken.has(id))
136
+ continue;
137
+ const path = join(dir, name);
138
+ try {
139
+ // A receipt from an earlier pi child of the same execution (the plan's re-ask).
140
+ if (fs.exists(receiptOf(id))) {
141
+ taken.add(id);
142
+ continue;
143
+ }
144
+ if (fs.size(path) > MAX_INBOX_FILE_BYTES)
145
+ continue;
146
+ read += 1;
147
+ const message = parseInboxMessage(id, fs.read(path));
148
+ if (message)
149
+ found.push(message);
150
+ }
151
+ catch {
152
+ // Unreadable now: the next tool call reads it again.
153
+ }
154
+ }
155
+ // Ids are random: the oldest by when they were written, then the bound.
156
+ return found
157
+ .sort((a, b) => a.at - b.at || a.id.localeCompare(b.id))
158
+ .slice(0, MAX_INBOX_FILES_PER_CHECK);
159
+ };
160
+ return {
161
+ check(idle) {
162
+ // pi starts a new prompt for a message sent while it is idle; this
163
+ // turn's prompt is over then, and the host's fallback takes the rest.
164
+ if (idle)
165
+ return [];
166
+ const handed = [];
167
+ for (const message of unread()) {
168
+ pending.set(message.id, steerHeader(message.id));
169
+ try {
170
+ send(steerText(message));
171
+ handed.push(message.id);
172
+ }
173
+ catch {
174
+ pending.delete(message.id);
175
+ }
176
+ }
177
+ if (handed.length > 0) {
178
+ logEvent({
179
+ source: "session-inbox",
180
+ level: "info",
181
+ event: "steered",
182
+ fields: { messages: handed.length },
183
+ });
184
+ }
185
+ return handed;
186
+ },
187
+ delivered(message) {
188
+ if (!message || message.role !== "user" || pending.size === 0)
189
+ return null;
190
+ const text = textOf(message.content);
191
+ for (const [id, header] of pending) {
192
+ if (!text.startsWith(header))
193
+ continue;
194
+ pending.delete(id);
195
+ taken.add(id);
196
+ try {
197
+ fs.writeWhole(receiptOf(id), `${JSON.stringify({ id, at: now() })}\n`);
198
+ }
199
+ catch {
200
+ // No receipt: the host reads the message as not taken and sends it
201
+ // to the next turn too. Said, since it is the one way a message
202
+ // can arrive twice.
203
+ logEvent({
204
+ source: "session-inbox",
205
+ level: "warn",
206
+ event: "receipt_unwritten",
207
+ flush: "sync",
208
+ });
209
+ }
210
+ return id;
211
+ }
212
+ return null;
213
+ },
214
+ };
215
+ }
216
+ /**
217
+ * On a session-lane turn whose inbox the session lane named, messages in it
218
+ * reach the session after each tool call. Registered nowhere else.
219
+ */
220
+ export function registerSessionInbox(pi, env = process.env, fs = nodeInboxFs) {
221
+ if (!isSessionLaneTurn(env))
222
+ return false;
223
+ const dir = env[SESSION_INBOX_DIR_ENV]?.trim();
224
+ if (!dir)
225
+ return false;
226
+ const inbox = createSessionInbox(dir, (text) => {
227
+ // Typed `void`: pi 0.84.1's binding catches a failed send itself (an
228
+ // extension error, `send_user_message`). A promise from a later pi is
229
+ // caught here, never an unhandled rejection. A send that failed writes
230
+ // no receipt, so the message reaches the next turn.
231
+ const sent = pi.sendUserMessage(text, { deliverAs: "steer" });
232
+ if (sent instanceof Promise)
233
+ sent.catch(() => undefined);
234
+ }, fs);
235
+ pi.on("tool_execution_end", (_event, ctx) => {
236
+ try {
237
+ const idle = typeof ctx?.isIdle === "function" ? ctx.isIdle() : false;
238
+ inbox.check(idle);
239
+ }
240
+ catch {
241
+ // Never the turn's failure.
242
+ }
243
+ });
244
+ pi.on("message_end", (event) => {
245
+ try {
246
+ inbox.delivered(event.message);
247
+ }
248
+ catch {
249
+ // Never the turn's failure.
250
+ }
251
+ return undefined;
252
+ });
253
+ return true;
254
+ }
255
+ //# sourceMappingURL=sessionInbox.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. */
@@ -193,6 +196,18 @@ export interface SessionTurnOutcome {
193
196
  export declare const HEARTBEAT_EVERY_MS = 30000;
194
197
  /** The child's env: the folder its turn's inputs are in, which the compaction pins read (`compactionPins.ts`). */
195
198
  export declare const SESSION_INPUT_DIR_ENV = "YAGNI_SESSION_INPUT_DIR";
199
+ /**
200
+ * The child's env: this execution's inbox, where the host writes what a
201
+ * person sends the yak while the turn runs (YAG-1210, `sessionInbox.ts`).
202
+ */
203
+ export declare const SESSION_INBOX_DIR_ENV = "YAGNI_SESSION_INBOX_DIR";
204
+ /**
205
+ * The execution's inbox under the turn's input folder, as the host writes
206
+ * it (`yaks/inbox.ts` in the backend); null for an execution id that is not
207
+ * one, which names no folder. Keyed by the execution, so a message written
208
+ * after its session ended is never read by the next one.
209
+ */
210
+ export declare function sessionInboxDir(inputDir: string, executionId: string): string | null;
196
211
  /** What a turn's heartbeat carries, kept up to date from the child's events. */
197
212
  export interface TurnPulse {
198
213
  /** Tokens the turn's model calls used so far: input, output and cache together. */
@@ -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";
@@ -375,6 +377,21 @@ export function turnStop(run, writes, aborted) {
375
377
  export const HEARTBEAT_EVERY_MS = 30_000;
376
378
  /** The child's env: the folder its turn's inputs are in, which the compaction pins read (`compactionPins.ts`). */
377
379
  export const SESSION_INPUT_DIR_ENV = "YAGNI_SESSION_INPUT_DIR";
380
+ /**
381
+ * The child's env: this execution's inbox, where the host writes what a
382
+ * person sends the yak while the turn runs (YAG-1210, `sessionInbox.ts`).
383
+ */
384
+ export const SESSION_INBOX_DIR_ENV = "YAGNI_SESSION_INBOX_DIR";
385
+ const EXECUTION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
386
+ /**
387
+ * The execution's inbox under the turn's input folder, as the host writes
388
+ * it (`yaks/inbox.ts` in the backend); null for an execution id that is not
389
+ * one, which names no folder. Keyed by the execution, so a message written
390
+ * after its session ended is never read by the next one.
391
+ */
392
+ export function sessionInboxDir(inputDir, executionId) {
393
+ return EXECUTION_ID.test(executionId) ? join(inputDir, "inbox", executionId) : null;
394
+ }
378
395
  /** One child event folded into the pulse: its spend, its tool, its time. */
379
396
  export function notePulse(pulse, event, at) {
380
397
  pulse.lastEventAt = at;
@@ -479,10 +496,17 @@ async function runTurn(input, deps, pulse) {
479
496
  ...(timeBudgetMs !== undefined ? { timeBudgetMs } : {}),
480
497
  };
481
498
  let decisionsRecorded = 0;
499
+ const inboxDir = sessionInboxDir(input.inputDir, input.identity.executionId);
482
500
  const runDeps = {
483
501
  cwd: input.cwd,
484
- // The input folder, for the turn's own compaction to pin its facts from (YAG-1163).
485
- env: { ...input.childEnv, [SESSION_INPUT_DIR_ENV]: input.inputDir },
502
+ // The input folder, for the turn's own compaction to pin its facts from
503
+ // (YAG-1163), and the execution's inbox, for what a person sends the
504
+ // running turn (YAG-1210).
505
+ env: {
506
+ ...input.childEnv,
507
+ [SESSION_INPUT_DIR_ENV]: input.inputDir,
508
+ ...(inboxDir ? { [SESSION_INBOX_DIR_ENV]: inboxDir } : {}),
509
+ },
486
510
  sessionFile: paths.sessionFile,
487
511
  callerLabel: SESSION_CALLER_LABEL,
488
512
  ...(input.runId ? { attribution: { runId: input.runId } } : {}),
@@ -531,6 +555,22 @@ async function runTurn(input, deps, pulse) {
531
555
  try {
532
556
  let run = await turn(message);
533
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
+ }
534
574
  if (input.stage === "plan") {
535
575
  const planned = await planWithBlock(run, turn, input.signal);
536
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