pi-creel 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-creel",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "request_secret for the pi coding agent: capture an API key into a local .env via a tmux popup (the creel tool) so it never enters the chat/context.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/index.ts CHANGED
@@ -13,8 +13,8 @@
13
13
  // pi-wakeup and guardrails use.
14
14
 
15
15
  import { execFileSync } from "node:child_process";
16
- import { existsSync, readFileSync, rmSync } from "node:fs";
17
- import { tmpdir } from "node:os";
16
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, watch } from "node:fs";
17
+ import { homedir, tmpdir } from "node:os";
18
18
  import { join } from "node:path";
19
19
  import { randomUUID } from "node:crypto";
20
20
  import { setTimeout as sleep } from "node:timers/promises";
@@ -26,18 +26,27 @@ import {
26
26
  tokenToText,
27
27
  validName,
28
28
  } from "./capture.ts";
29
+ import { parseEvent, savedMessage } from "./notify.ts";
29
30
 
30
31
  const POPUP_WIDTH = "64";
31
32
  const POPUP_HEIGHT = "14";
32
33
  const TOKEN_TIMEOUT_MS = 120_000;
33
34
  const POLL_INTERVAL_MS = 150;
34
35
 
36
+ export type WatchHandle = { close: () => void };
37
+
35
38
  export type Deps = {
36
39
  resolveTmux?: (env: NodeJS.ProcessEnv) => TmuxContext | undefined;
37
40
  creelOnPath?: () => boolean;
38
41
  spawnPopup?: (tmux: TmuxContext, command: string) => void;
39
42
  waitForToken?: (statusPath: string, timeoutMs: number) => Promise<string | undefined>;
40
43
  tmpStatusPath?: () => string;
44
+ resolveSessionId?: (tmux: TmuxContext) => string | undefined;
45
+ homedir?: () => string;
46
+ watch?: (dir: string, cb: (event: string, filename: string | null) => void) => WatchHandle;
47
+ readEventFile?: (path: string) => string;
48
+ eventMtimeMs?: (path: string) => number;
49
+ mkdir?: (dir: string) => void;
41
50
  };
42
51
 
43
52
  function defaultCreelOnPath(): boolean {
@@ -52,12 +61,18 @@ function defaultCreelOnPath(): boolean {
52
61
  function defaultSpawnPopup(tmux: TmuxContext, command: string): void {
53
62
  // display-popup returns immediately (the popup runs detached on the server),
54
63
  // so completion is observed out-of-band via the status file.
64
+ //
65
+ // -d anchors the popup's working directory to this process's cwd — the folder
66
+ // pi was launched in, i.e. the project being worked on. creel resolves a
67
+ // relative --dest (".env") against that cwd, so the key lands in the project's
68
+ // .env. Without -d, tmux opens the popup in $HOME and the .env goes there.
55
69
  execFileSync(
56
70
  "tmux",
57
71
  [
58
72
  "-L", tmux.socket,
59
73
  "display-popup",
60
74
  "-t", tmux.pane,
75
+ "-d", process.cwd(),
61
76
  "-E",
62
77
  "-w", POPUP_WIDTH,
63
78
  "-h", POPUP_HEIGHT,
@@ -104,9 +119,9 @@ export function createCreel(pi: any, deps: Deps = {}): void {
104
119
  name: "request_secret",
105
120
  label: "Request Secret",
106
121
  description:
107
- "Capture an API key or secret from the user without it entering the chat. Opens a masked tmux popup (the creel tool); the user pastes once and the value is written straight into a local .env. Call this whenever you would otherwise ask the user to paste a key — you receive only a confirmation (added/updated), never the value. Requires a tmux session and the 'creel' binary on PATH.",
122
+ "Capture an API key, token, password, or any secret from the user WITHOUT it entering the chat or your context. Opens a masked tmux popup (the creel tool); the user pastes once and the value is written straight into a local .env (chmod 600). ALWAYS use this instead of asking the user to paste a secret into chat: any time you need a credential, or are about to say 'paste your ... key/token', call request_secret first. You receive only a confirmation (added/updated/cancelled), never the value. Requires a tmux session and the 'creel' binary on PATH.",
108
123
  promptSnippet:
109
- "request_secret(name, dest?) — need an API key/secret? Capture it into a .env via a popup instead of asking the user to paste it into chat.",
124
+ "request_secret(name, dest?) - need ANY secret, API key, token, or password? ALWAYS capture it via this popup instead of asking the user to paste it into chat.",
110
125
  parameters: REQUEST_SECRET_PARAMS,
111
126
  async execute(_id: string, params: { name?: string; dest?: string }) {
112
127
  const name = typeof params?.name === "string" ? params.name : "";
@@ -146,6 +161,112 @@ export function createCreel(pi: any, deps: Deps = {}): void {
146
161
  });
147
162
  }
148
163
 
164
+ const EVENTS_SUBDIR = ".pi/agent/creel-events";
165
+
166
+ // defaultResolveSessionId asks tmux for the id of the session this pi runs in,
167
+ // so the watcher reacts only to saves made in THIS session (routing by tmux
168
+ // session). Returns undefined outside tmux or on any tmux error.
169
+ function defaultResolveSessionId(tmux: TmuxContext): string | undefined {
170
+ try {
171
+ const out = execFileSync(
172
+ "tmux",
173
+ ["-L", tmux.socket, "display-message", "-p", "-t", tmux.pane, "#{session_id}"],
174
+ { stdio: ["ignore", "pipe", "ignore"] },
175
+ ).toString("utf-8");
176
+ const id = out.trim();
177
+ return id || undefined;
178
+ } catch {
179
+ return undefined;
180
+ }
181
+ }
182
+
183
+ // startCreelWatch notifies THIS pi session when the user saves a secret via
184
+ // creel outside a request_secret call (the tmux keybind runs creel with
185
+ // --event-file <dir>/<session>.json). It resolves the session id so a save in
186
+ // one session never notifies another (routing by tmux session), watches the
187
+ // events dir, and on a NEW event delivers a value-free note - steering a fresh
188
+ // turn when idle, queuing after the current turn when busy (mirroring
189
+ // pi-wakeup). It is a no-op outside tmux, where there is no keybind to hear.
190
+ export function startCreelWatch(pi: any, deps: Deps = {}): void {
191
+ const resolveT = deps.resolveTmux ?? resolveTmux;
192
+ const resolveSid = deps.resolveSessionId ?? defaultResolveSessionId;
193
+ const home = (deps.homedir ?? homedir)();
194
+ const startWatch = deps.watch ?? watch;
195
+ const readEvent = deps.readEventFile ?? ((p: string) => readFileSync(p, "utf-8"));
196
+ const mtimeMs = deps.eventMtimeMs ?? ((p: string) => statSync(p).mtimeMs);
197
+ const ensureDir = deps.mkdir ?? ((d: string) => mkdirSync(d, { recursive: true }));
198
+
199
+ const tmux = resolveT(process.env);
200
+ if (!tmux) return;
201
+ const sid = resolveSid(tmux);
202
+ if (!sid) return;
203
+
204
+ const dir = join(home, EVENTS_SUBDIR);
205
+ try {
206
+ ensureDir(dir);
207
+ } catch {
208
+ return; // nothing to watch if the dir cannot be made
209
+ }
210
+ const fileName = `${sid}.json`;
211
+ const target = join(dir, fileName);
212
+
213
+ let ctx: any;
214
+ pi.on?.("session_start", (_e: unknown, sessionCtx: any) => {
215
+ ctx = sessionCtx;
216
+ });
217
+
218
+ // Dedupe by mtime: one write can fire the watcher twice (rename+change), and
219
+ // two saves with identical name/dest/action have identical CONTENT, so mtime
220
+ // - which advances on every write - is the reliable "is this a new save" key.
221
+ let lastMtimeMs = -1;
222
+ const handle = startWatch(dir, (_event: string, changed: string | null) => {
223
+ if (changed !== null && changed !== fileName) return;
224
+ let m: number;
225
+ try {
226
+ m = mtimeMs(target);
227
+ } catch {
228
+ return; // file gone or unreadable
229
+ }
230
+ if (m === lastMtimeMs) return;
231
+ lastMtimeMs = m;
232
+ let raw: string;
233
+ try {
234
+ raw = readEvent(target);
235
+ } catch {
236
+ return;
237
+ }
238
+ const evt = parseEvent(raw);
239
+ if (!evt) return;
240
+ let idle = false;
241
+ try {
242
+ idle = ctx && typeof ctx.isIdle === "function" ? Boolean(ctx.isIdle()) : false;
243
+ } catch {
244
+ idle = false;
245
+ }
246
+ try {
247
+ pi.sendMessage(
248
+ { content: savedMessage(evt), customType: "creel_saved", display: true },
249
+ { triggerTurn: true, deliverAs: idle ? "steer" : "followUp" },
250
+ );
251
+ } catch (error) {
252
+ try {
253
+ pi.appendEntry?.("creel_notify_failed", { error: String(error) });
254
+ } catch {
255
+ // best-effort
256
+ }
257
+ }
258
+ });
259
+
260
+ pi.on?.("session_shutdown", () => {
261
+ try {
262
+ handle?.close?.();
263
+ } catch {
264
+ // best-effort
265
+ }
266
+ });
267
+ }
268
+
149
269
  export default function (pi: any) {
150
270
  createCreel(pi);
271
+ startCreelWatch(pi);
151
272
  }
@@ -0,0 +1,41 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+
4
+ import { parseEvent, savedMessage } from "./notify.ts";
5
+
6
+ test("parseEvent accepts a well-formed added/updated event", () => {
7
+ assert.deepEqual(parseEvent('{"name":"STRIPE_KEY","dest":".env","action":"added"}'), {
8
+ name: "STRIPE_KEY",
9
+ dest: ".env",
10
+ action: "added",
11
+ });
12
+ assert.deepEqual(parseEvent('{"name":"K","dest":"config/.env","action":"updated"}'), {
13
+ name: "K",
14
+ dest: "config/.env",
15
+ action: "updated",
16
+ });
17
+ });
18
+
19
+ test("parseEvent rejects bad json, missing fields, bad name, bad action", () => {
20
+ assert.equal(parseEvent("not json"), undefined);
21
+ assert.equal(parseEvent("{}"), undefined);
22
+ assert.equal(parseEvent('{"name":"K","dest":".env"}'), undefined); // no action
23
+ assert.equal(parseEvent('{"name":"BAD-NAME","dest":".env","action":"added"}'), undefined);
24
+ assert.equal(parseEvent('{"name":"K","dest":".env","action":"deleted"}'), undefined);
25
+ assert.equal(parseEvent('{"name":"K","dest":"","action":"added"}'), undefined);
26
+ });
27
+
28
+ test("parseEvent refuses any payload carrying a value field", () => {
29
+ assert.equal(
30
+ parseEvent('{"name":"K","dest":".env","action":"added","value":"sk-secret"}'),
31
+ undefined,
32
+ );
33
+ });
34
+
35
+ test("savedMessage names the key and dest, points at process.env, and omits the value", () => {
36
+ const m = savedMessage({ name: "STRIPE_KEY", dest: ".env", action: "added" });
37
+ assert.match(m, /STRIPE_KEY/);
38
+ assert.match(m, /\.env/);
39
+ assert.match(m, /process\.env\.STRIPE_KEY/);
40
+ assert.ok(!/sk-/.test(m));
41
+ });
package/src/notify.ts ADDED
@@ -0,0 +1,44 @@
1
+ // Pure pieces of the creel-save notifier: the value-free event shape, its
2
+ // parser, and the note the agent receives. None of these ever see the secret
3
+ // value; creel writes only {name, dest, action} to its --event-file, and this
4
+ // code refuses anything carrying a value field.
5
+
6
+ export type CreelEvent = { name: string; dest: string; action: "added" | "updated" };
7
+
8
+ // A legal environment-variable name, mirroring creel's own ValidName.
9
+ const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
10
+
11
+ // parseEvent reads a creel --event-file payload and returns a CreelEvent only
12
+ // when it is well-formed: a valid env-var name, a non-empty dest, an
13
+ // added/updated action, and crucially NO value field. Anything else (bad JSON,
14
+ // missing fields, or a stray value) returns undefined and is ignored, so a
15
+ // malformed or tampered file can never push a secret into the agent.
16
+ export function parseEvent(raw: string): CreelEvent | undefined {
17
+ let obj: unknown;
18
+ try {
19
+ obj = JSON.parse(raw);
20
+ } catch {
21
+ return undefined;
22
+ }
23
+ if (typeof obj !== "object" || obj === null) return undefined;
24
+ const rec = obj as Record<string, unknown>;
25
+ if ("value" in rec) return undefined; // creel never writes one; refuse if present
26
+ const name = typeof rec.name === "string" ? rec.name : "";
27
+ const dest = typeof rec.dest === "string" ? rec.dest : "";
28
+ const action = rec.action === "added" || rec.action === "updated" ? rec.action : "";
29
+ if (!NAME_RE.test(name) || dest === "" || action === "") return undefined;
30
+ return { name, dest, action };
31
+ }
32
+
33
+ // savedMessage is the note the agent receives when the user saves a secret via
34
+ // creel OUTSIDE a request_secret call (the tmux keybind). It names what was
35
+ // captured and where, tells the agent how to reference it, and never carries
36
+ // the value.
37
+ export function savedMessage(e: CreelEvent): string {
38
+ return (
39
+ `The user just ${e.action} the secret \`${e.name}\` in \`${e.dest}\` using creel. ` +
40
+ `The value went straight into that file and is not shown here: reference it as ` +
41
+ `\`process.env.${e.name}\` (or have your program read \`${e.dest}\` at runtime), and do not ` +
42
+ `try to read the .env yourself. No action is needed unless you were waiting on this key.`
43
+ );
44
+ }
@@ -0,0 +1,115 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+
4
+ import { startCreelWatch, type Deps, type WatchHandle } from "./index.ts";
5
+
6
+ type Sent = { content: any; opts: any };
7
+
8
+ function fakePi() {
9
+ const sent: Sent[] = [];
10
+ const handlers: Record<string, (...a: any[]) => void> = {};
11
+ const pi = {
12
+ on(evt: string, cb: (...a: any[]) => void) {
13
+ handlers[evt] = cb;
14
+ },
15
+ sendMessage(content: any, opts: any) {
16
+ sent.push({ content, opts });
17
+ },
18
+ appendEntry() {},
19
+ };
20
+ return { pi, sent, handlers };
21
+ }
22
+
23
+ // watchDeps wires a fully-injected Deps: no real fs, no real tmux. `fire`
24
+ // invokes the captured watch callback for this session's file; `closeFake`
25
+ // reports whether the handle was closed.
26
+ function watchDeps(overrides: Partial<Deps> = {}) {
27
+ let cb: ((e: string, f: string | null) => void) | undefined;
28
+ let closed = false;
29
+ const deps: Deps = {
30
+ resolveTmux: () => ({ socket: "s", pane: "%1" }),
31
+ resolveSessionId: () => "$3",
32
+ homedir: () => "/home/u",
33
+ mkdir: () => {},
34
+ watch: (_dir, c) => {
35
+ cb = c;
36
+ return { close() { closed = true; } } as WatchHandle;
37
+ },
38
+ readEventFile: () => '{"name":"STRIPE_KEY","dest":".env","action":"added"}',
39
+ eventMtimeMs: () => 1000,
40
+ ...overrides,
41
+ };
42
+ return {
43
+ deps,
44
+ fire: (file: string | null = "$3.json") => cb?.("change", file),
45
+ isClosed: () => closed,
46
+ };
47
+ }
48
+
49
+ test("delivers a value-free note on a new event, queued after the turn", () => {
50
+ const { pi, sent } = fakePi();
51
+ const { deps, fire } = watchDeps();
52
+ startCreelWatch(pi, deps);
53
+ fire();
54
+ assert.equal(sent.length, 1);
55
+ assert.match(sent[0].content.content, /STRIPE_KEY/);
56
+ assert.equal(sent[0].content.customType, "creel_saved");
57
+ assert.equal(sent[0].opts.triggerTurn, true);
58
+ assert.equal(sent[0].opts.deliverAs, "followUp"); // no ctx captured -> not idle
59
+ });
60
+
61
+ test("an idle session steers a fresh turn", () => {
62
+ const { pi, sent, handlers } = fakePi();
63
+ const { deps, fire } = watchDeps();
64
+ startCreelWatch(pi, deps);
65
+ handlers.session_start?.(null, { isIdle: () => true });
66
+ fire();
67
+ assert.equal(sent[0].opts.deliverAs, "steer");
68
+ });
69
+
70
+ test("the same mtime does not re-notify; a new mtime does", () => {
71
+ const { pi, sent } = fakePi();
72
+ let mt = 1000;
73
+ const { deps, fire } = watchDeps({ eventMtimeMs: () => mt });
74
+ startCreelWatch(pi, deps);
75
+ fire();
76
+ fire(); // double-fire of one write -> same mtime -> skipped
77
+ assert.equal(sent.length, 1);
78
+ mt = 2000; // a genuinely new save
79
+ fire();
80
+ assert.equal(sent.length, 2);
81
+ });
82
+
83
+ test("ignores a change to another session's file", () => {
84
+ const { pi, sent } = fakePi();
85
+ const { deps, fire } = watchDeps();
86
+ startCreelWatch(pi, deps);
87
+ fire("$9.json");
88
+ assert.equal(sent.length, 0);
89
+ });
90
+
91
+ test("is a no-op outside tmux and when the session id cannot resolve", () => {
92
+ const a = fakePi();
93
+ startCreelWatch(a.pi, watchDeps({ resolveTmux: () => undefined }).deps);
94
+ assert.equal(a.sent.length, 0);
95
+ const b = fakePi();
96
+ startCreelWatch(b.pi, watchDeps({ resolveSessionId: () => undefined }).deps);
97
+ assert.equal(b.sent.length, 0);
98
+ });
99
+
100
+ test("ignores a malformed event file", () => {
101
+ const { pi, sent } = fakePi();
102
+ const { deps, fire } = watchDeps({ readEventFile: () => "garbage" });
103
+ startCreelWatch(pi, deps);
104
+ fire();
105
+ assert.equal(sent.length, 0);
106
+ });
107
+
108
+ test("closes the watcher on session shutdown", () => {
109
+ const { pi, handlers } = fakePi();
110
+ const { deps, isClosed } = watchDeps();
111
+ startCreelWatch(pi, deps);
112
+ assert.equal(isClosed(), false);
113
+ handlers.session_shutdown?.();
114
+ assert.equal(isClosed(), true);
115
+ });