@pugi/cli 0.1.0-alpha.6 → 0.1.0-alpha.7

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,172 @@
1
+ /**
2
+ * Persistent REPL history (per-workspace) - Sprint α6.14.
3
+ *
4
+ * Stores submitted briefs in `~/.pugi/history/<workspace-slug>.jsonl`,
5
+ * one JSON object per line. The format is line-delimited JSON so the
6
+ * file can be appended to atomically (single `write(2)` per entry on
7
+ * Linux/macOS for entries < PIPE_BUF) and tailed by humans without a
8
+ * parser. Per-workspace separation lets the operator switch repos and
9
+ * keep brief history contextual: `brief: fix the cabinet sidebar 401`
10
+ * does not bleed into the agents repo.
11
+ *
12
+ * Contract:
13
+ *
14
+ * - `append({ home, workspaceSlug, brief })` writes one line. Dedups
15
+ * a brief that is identical to the immediately preceding entry
16
+ * (most common operator pattern: Up + Enter to re-run).
17
+ * - `read({ home, workspaceSlug })` returns entries oldest-first so
18
+ * the caller can navigate with `index = entries.length - 1` for
19
+ * "most recent" semantics.
20
+ * - The file is capped at MAX_ENTRIES; on overflow we keep the most
21
+ * recent slice and rewrite. Cheap because briefs are short text
22
+ * and the cap is 1000.
23
+ * - `slugForCwd(cwd)` normalises a working directory into a safe
24
+ * filename component (alphanumerics + `-`, lowercase, slashes
25
+ * collapsed). Empty cwd resolves to `default`.
26
+ * - Failures (missing $HOME, disk full, EACCES) NEVER throw. History
27
+ * is operator comfort, not a contract surface; degrading to "no
28
+ * history this session" is correct.
29
+ *
30
+ * Brand voice: file is operator-facing if they `cat` it, so the JSON
31
+ * keys stay readable English (`brief`, `ts`). No forbidden words.
32
+ */
33
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, renameSync, unlinkSync, } from 'node:fs';
34
+ import { homedir } from 'node:os';
35
+ import { dirname, join } from 'node:path';
36
+ /** Cap on stored entries per workspace. Drops oldest on overflow. */
37
+ export const MAX_HISTORY_ENTRIES = 1000;
38
+ /**
39
+ * Compute the on-disk path for a given workspace slug. Tests rely on
40
+ * this to assert per-workspace isolation without re-implementing the
41
+ * directory math.
42
+ */
43
+ export function historyPath(io) {
44
+ const home = io.home ?? homedir();
45
+ const safe = sanitiseSlug(io.workspaceSlug);
46
+ return join(home, '.pugi', 'history', `${safe}.jsonl`);
47
+ }
48
+ /**
49
+ * Append a brief to history. Dedups consecutive identical entries.
50
+ * Returns the entry that was written, or `null` when the entry was
51
+ * deduped or the brief was empty.
52
+ */
53
+ export function append(input) {
54
+ const brief = input.brief.trim();
55
+ if (brief.length === 0)
56
+ return null;
57
+ const path = historyPath(input);
58
+ try {
59
+ ensureDir(dirname(path));
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ const existing = read({ home: input.home, workspaceSlug: input.workspaceSlug });
65
+ const last = existing[existing.length - 1];
66
+ if (last && last.brief === brief) {
67
+ return null;
68
+ }
69
+ const ts = (input.now ?? (() => new Date()))().toISOString();
70
+ const entry = { ts, brief };
71
+ // Overflow path: combined length > cap means we trim before rewrite.
72
+ // Write to a sibling tmp file and renameSync over the target so
73
+ // concurrent CLI instances in the same workspace cannot observe a
74
+ // half-written file or race a parallel appendFileSync into oblivion.
75
+ // POSIX renameSync is atomic within a directory; on Windows fs.rename
76
+ // is atomic too as long as both paths are on the same volume (the tmp
77
+ // sibling guarantees that). P2 fix from PR #335 triple-review.
78
+ if (existing.length + 1 > MAX_HISTORY_ENTRIES) {
79
+ const trimmed = [...existing.slice(existing.length + 1 - MAX_HISTORY_ENTRIES), entry];
80
+ const tmpPath = `${path}.tmp`;
81
+ try {
82
+ writeFileSync(tmpPath, trimmed.map(serialize).join('\n') + '\n', { mode: 0o600 });
83
+ renameSync(tmpPath, path);
84
+ }
85
+ catch {
86
+ // Best-effort cleanup of the orphan tmp file; never throw out.
87
+ try {
88
+ unlinkSync(tmpPath);
89
+ }
90
+ catch {
91
+ /* ignore — tmp file may not exist yet */
92
+ }
93
+ return null;
94
+ }
95
+ return entry;
96
+ }
97
+ try {
98
+ appendFileSync(path, serialize(entry) + '\n', { mode: 0o600 });
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ return entry;
104
+ }
105
+ /**
106
+ * Read history for a workspace, oldest-first. Returns `[]` when the
107
+ * file is missing, unreadable, or empty. Malformed lines are dropped
108
+ * silently - one bad line should not nuke the whole history.
109
+ */
110
+ export function read(io) {
111
+ const path = historyPath(io);
112
+ if (!existsSync(path))
113
+ return [];
114
+ let raw;
115
+ try {
116
+ raw = readFileSync(path, 'utf8');
117
+ }
118
+ catch {
119
+ return [];
120
+ }
121
+ const out = [];
122
+ for (const line of raw.split('\n')) {
123
+ const trimmed = line.trim();
124
+ if (trimmed.length === 0)
125
+ continue;
126
+ try {
127
+ const parsed = JSON.parse(trimmed);
128
+ if (typeof parsed === 'object' &&
129
+ parsed !== null &&
130
+ typeof parsed.brief === 'string' &&
131
+ typeof parsed.ts === 'string') {
132
+ out.push({
133
+ ts: parsed.ts,
134
+ brief: parsed.brief,
135
+ });
136
+ }
137
+ }
138
+ catch {
139
+ // Drop malformed line.
140
+ }
141
+ }
142
+ return out;
143
+ }
144
+ /**
145
+ * Normalise a cwd or workspace name into a safe filename component.
146
+ * Lowercase, alphanumerics + `-` only. Slashes become `-`. Empty input
147
+ * resolves to `default` so we never produce an empty filename.
148
+ */
149
+ export function slugForCwd(cwd) {
150
+ if (!cwd || cwd.trim().length === 0)
151
+ return 'default';
152
+ // Strip leading slash so `/Users/foo` becomes `users-foo`.
153
+ const normalised = cwd
154
+ .replace(/^[/\\]+/, '')
155
+ .replace(/[/\\]+/g, '-')
156
+ .toLowerCase();
157
+ return sanitiseSlug(normalised);
158
+ }
159
+ function sanitiseSlug(raw) {
160
+ const cleaned = raw.replace(/[^a-z0-9-]/gi, '-').toLowerCase().replace(/-+/g, '-');
161
+ const trimmed = cleaned.replace(/^-+|-+$/g, '');
162
+ return trimmed.length === 0 ? 'default' : trimmed;
163
+ }
164
+ function serialize(entry) {
165
+ return JSON.stringify(entry);
166
+ }
167
+ function ensureDir(dir) {
168
+ if (existsSync(dir))
169
+ return;
170
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
171
+ }
172
+ //# sourceMappingURL=history.js.map
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Kill ring for the REPL input - Sprint α6.14.
3
+ *
4
+ * Tiny LIFO buffer that backs the readline-style kill commands:
5
+ *
6
+ * Ctrl+U - kill from cursor to line start
7
+ * Ctrl+K - kill from cursor to line end
8
+ * Ctrl+W - kill word backwards (whitespace + punctuation delimiter)
9
+ * Ctrl+Y - yank the most recent kill at the cursor
10
+ *
11
+ * The ring is bounded (MAX_RING_ENTRIES = 10) so the operator's
12
+ * recent kills are reachable without leaking memory across long
13
+ * sessions. We do NOT implement Meta+Y (cycle yanks) at this layer -
14
+ * sticking to the most-recent-yank keeps the input box logic small
15
+ * and matches the bash default for new operators.
16
+ *
17
+ * The module is pure functional: every operation returns a NEW ring,
18
+ * so the input box can stash one in `useState` without mutation
19
+ * worries. Empty slices are no-ops (we do not push empty strings) so
20
+ * Ctrl+U at column 0 does not pollute the ring with `""`.
21
+ */
22
+ export const MAX_RING_ENTRIES = 10;
23
+ export const EMPTY_KILL_RING = { entries: [] };
24
+ /**
25
+ * Push a slice into the ring. Returns a new ring with the slice at
26
+ * the front; older entries shift right and the tail is dropped if
27
+ * the cap is exceeded. Empty / whitespace-only slices are a no-op so
28
+ * the ring stays meaningful.
29
+ */
30
+ export function push(ring, slice) {
31
+ if (slice.length === 0)
32
+ return ring;
33
+ const next = [slice, ...ring.entries];
34
+ return { entries: next.slice(0, MAX_RING_ENTRIES) };
35
+ }
36
+ /**
37
+ * Read the most-recent entry without mutating the ring. Returns
38
+ * `null` when the ring is empty so the caller can decide whether to
39
+ * beep, no-op, or fall through to plain insert.
40
+ */
41
+ export function yank(ring) {
42
+ return ring.entries.length > 0 ? ring.entries[0] : null;
43
+ }
44
+ /**
45
+ * Word delimiter used by Ctrl+W. Whitespace + ASCII punctuation,
46
+ * matching the readline default. We treat `_` and `-` as part of the
47
+ * word so kebab-case and snake_case identifiers behave as one token
48
+ * (the brief frequently mentions filenames + symbols).
49
+ */
50
+ const WORD_DELIMITERS = new Set([
51
+ ' ', '\t', '\n',
52
+ '.', ',', ';', ':',
53
+ '/', '\\',
54
+ '!', '?', '@', '#', '$', '%', '^', '&', '*',
55
+ '(', ')', '[', ']', '{', '}', '<', '>',
56
+ '"', "'", '`',
57
+ '=', '+', '|', '~',
58
+ ]);
59
+ /**
60
+ * Compute the start of the previous word given a cursor position.
61
+ * Walks LEFT from `cursor - 1`, skipping any delimiters that
62
+ * immediately precede the cursor (so Ctrl+W at the end of `foo `
63
+ * still kills `foo`), then continues left until it hits the next
64
+ * delimiter or the start of the line.
65
+ *
66
+ * Returns the offset BEFORE which the kill should start (i.e. the
67
+ * slice to remove is `line.slice(start, cursor)`).
68
+ */
69
+ export function previousWordStart(line, cursor) {
70
+ let i = Math.min(cursor, line.length) - 1;
71
+ // Skip trailing delimiters.
72
+ while (i >= 0 && WORD_DELIMITERS.has(line[i]))
73
+ i -= 1;
74
+ // Walk through the word.
75
+ while (i >= 0 && !WORD_DELIMITERS.has(line[i]))
76
+ i -= 1;
77
+ return i + 1;
78
+ }
79
+ /**
80
+ * Apply a Ctrl+U kill: from cursor to line start. Returns the new
81
+ * line + cursor + ring. No-op when cursor is already at column 0.
82
+ */
83
+ export function killToLineStart(line, cursor, ring) {
84
+ if (cursor === 0)
85
+ return { line, cursor, ring };
86
+ const slice = line.slice(0, cursor);
87
+ return {
88
+ line: line.slice(cursor),
89
+ cursor: 0,
90
+ ring: push(ring, slice),
91
+ };
92
+ }
93
+ /**
94
+ * Apply a Ctrl+K kill: from cursor to line end. Returns the new
95
+ * line + cursor + ring. No-op when cursor is already past the last
96
+ * character.
97
+ */
98
+ export function killToLineEnd(line, cursor, ring) {
99
+ if (cursor >= line.length)
100
+ return { line, cursor, ring };
101
+ const slice = line.slice(cursor);
102
+ return {
103
+ line: line.slice(0, cursor),
104
+ cursor,
105
+ ring: push(ring, slice),
106
+ };
107
+ }
108
+ /**
109
+ * Apply a Ctrl+W kill: from cursor back to the start of the previous
110
+ * word. Returns the new line + cursor + ring. No-op when cursor is
111
+ * at column 0.
112
+ */
113
+ export function killWordBackward(line, cursor, ring) {
114
+ if (cursor === 0)
115
+ return { line, cursor, ring };
116
+ const start = previousWordStart(line, cursor);
117
+ const slice = line.slice(start, cursor);
118
+ return {
119
+ line: line.slice(0, start) + line.slice(cursor),
120
+ cursor: start,
121
+ ring: push(ring, slice),
122
+ };
123
+ }
124
+ /**
125
+ * Apply a Ctrl+Y yank: insert the most-recent entry at the cursor.
126
+ * Returns the new line + cursor unchanged when the ring is empty
127
+ * (the caller decides whether to surface a visual cue).
128
+ */
129
+ export function yankAtCursor(line, cursor, ring) {
130
+ const entry = yank(ring);
131
+ if (entry === null)
132
+ return { line, cursor };
133
+ return {
134
+ line: line.slice(0, cursor) + entry + line.slice(cursor),
135
+ cursor: cursor + entry.length,
136
+ };
137
+ }
138
+ //# sourceMappingURL=kill-ring.js.map
@@ -30,6 +30,8 @@ import { randomUUID } from 'node:crypto';
30
30
  import { listRoles, getPersonaForRole } from '../agents/registry.js';
31
31
  import { evaluateCap, describeVerdict } from './cap-warning.js';
32
32
  import { parseSlashCommand } from './slash-commands.js';
33
+ import { webFetchTool } from '../../tools/web-fetch.js';
34
+ import { loadSettings } from '../settings.js';
33
35
  const MAX_TRANSCRIPT_ROWS = 500;
34
36
  const MAX_RECONNECT_ATTEMPTS = 10;
35
37
  const RECONNECT_BASE_MS = 250;
@@ -133,7 +135,49 @@ export class ReplSession {
133
135
  await this.dispatchBrief(verdict.brief);
134
136
  return verdict;
135
137
  }
138
+ case 'web': {
139
+ await this.dispatchWebFetch(verdict.url);
140
+ return verdict;
141
+ }
142
+ }
143
+ }
144
+ /**
145
+ * Fetch one URL via the web_fetch tool and inject the resulting
146
+ * Markdown into the transcript as an operator-attributed brief. The
147
+ * `<untrusted-content>` sentinel travels with the body so the Mira
148
+ * system prompt can refuse to follow instructions inside it.
149
+ *
150
+ * Gating: the dispatcher reads PugiSettings from disk on every
151
+ * call so the operator can flip `web.fetch.enabled` mid-session
152
+ * without restarting the REPL. The CLI's bare `--allow-fetch` flag
153
+ * is honored by the runtime entry point and propagates through
154
+ * env to keep the session module transport-free.
155
+ */
156
+ async dispatchWebFetch(url) {
157
+ // Malformed `.pugi/settings.json` must not crash the REPL —
158
+ // surface the error to the operator and treat fetch as disabled
159
+ // (fail-safe). The session keeps running.
160
+ let settings;
161
+ try {
162
+ settings = loadSettings(process.cwd());
163
+ }
164
+ catch (error) {
165
+ const msg = error instanceof Error ? error.message : String(error);
166
+ this.appendSystemLine(`web_fetch refused: failed to load .pugi/settings.json (${msg}).`);
167
+ return;
168
+ }
169
+ const allowFetch = (this.options.env ?? process.env).PUGI_ALLOW_FETCH === '1';
170
+ const result = await webFetchTool({ url }, { settings, allowFetch });
171
+ if (!result.ok) {
172
+ this.appendSystemLine(`web_fetch refused: ${result.error}`);
173
+ return;
136
174
  }
175
+ this.appendOperatorLine(`/web ${result.url}`);
176
+ this.appendSystemLine(`Fetched ${result.title} (${result.fetched_at}).`);
177
+ // Surface the Markdown body so the operator sees what landed in
178
+ // the brief; downstream the body is the actual dispatch payload.
179
+ this.appendSystemLine(result.content_md);
180
+ await this.dispatchBrief(`Brief from fetched page:\n\n${result.content_md}`);
137
181
  }
138
182
  /* ------------- dispatch -------------- */
139
183
  async dispatchBrief(brief) {
@@ -26,6 +26,7 @@ export const SLASH_COMMAND_HELP = Object.freeze([
26
26
  { name: 'stop', args: '<persona>', gloss: 'Stop one agent by persona slug' },
27
27
  { name: 'help', args: '', gloss: 'Show this help overlay' },
28
28
  { name: 'quit', args: '', gloss: 'Exit the REPL (session resumes via pugi resume)' },
29
+ { name: 'web', args: '<url>', gloss: 'Fetch a URL and brief Pugi on the page' },
29
30
  ]);
30
31
  /**
31
32
  * Parse one line of input from the REPL. The contract:
@@ -90,6 +91,13 @@ export function parseSlashCommand(input) {
90
91
  case 'q': {
91
92
  return { kind: 'quit' };
92
93
  }
94
+ case 'web':
95
+ case 'fetch': {
96
+ if (tail.length === 0) {
97
+ return { kind: 'error', message: 'Usage: /web <url>' };
98
+ }
99
+ return { kind: 'web', url: tail };
100
+ }
93
101
  default: {
94
102
  return {
95
103
  kind: 'error',
@@ -34,6 +34,19 @@ const pugiSettingsSchema = z.object({
34
34
  promoteExplicitly: z.boolean().default(true),
35
35
  })
36
36
  .default({}),
37
+ // `web.fetch.enabled` gates the `pugi web` / `/web` SSRF-guarded
38
+ // fetcher. Default-off matches the spec posture; the schema must
39
+ // declare it explicitly because Zod's strict-pass strips unknown
40
+ // keys and would silently swallow the operator's intent.
41
+ web: z
42
+ .object({
43
+ fetch: z
44
+ .object({
45
+ enabled: z.boolean().optional(),
46
+ })
47
+ .optional(),
48
+ })
49
+ .optional(),
37
50
  });
38
51
  export function loadSettings(root) {
39
52
  const settingsPath = resolve(root, '.pugi/settings.json');