mercury-agent 0.16.0 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +6 -0
  2. package/container/Dockerfile +6 -1
  3. package/container/Dockerfile.base +6 -1
  4. package/docs/README.md +50 -0
  5. package/docs/authoring-profiles.md +8 -0
  6. package/docs/behavior-layers.md +193 -0
  7. package/docs/extensions.md +2 -0
  8. package/docs/goals/football-reporter-profile/decisions.md +479 -0
  9. package/docs/goals/football-reporter-profile/goal.md +91 -0
  10. package/docs/goals/football-reporter-profile/roadmap.md +196 -0
  11. package/docs/goals/whatsapp-bot-hardening/README.md +43 -0
  12. package/docs/goals/whatsapp-bot-hardening/archive/ambient-group-context.md +211 -0
  13. package/docs/goals/whatsapp-bot-hardening/archive/command-routing-consistency.md +210 -0
  14. package/docs/goals/whatsapp-bot-hardening/archive/destructive-command-guards.md +218 -0
  15. package/docs/goals/whatsapp-bot-hardening/archive/docs-extension.md +182 -0
  16. package/docs/goals/whatsapp-bot-hardening/archive/handoff-2026-08-09.md +588 -0
  17. package/docs/goals/whatsapp-bot-hardening/archive/media-size-and-silent-drop.md +178 -0
  18. package/docs/goals/whatsapp-bot-hardening/archive/member-memory.md +199 -0
  19. package/docs/goals/whatsapp-bot-hardening/archive/message-author-attribution.md +211 -0
  20. package/docs/goals/whatsapp-bot-hardening/archive/run-from-source-switchover.md +212 -0
  21. package/docs/goals/whatsapp-bot-hardening/archive/setup-plan-2026-08-06.md +1117 -0
  22. package/docs/goals/whatsapp-bot-hardening/decisions.md +200 -0
  23. package/docs/goals/whatsapp-bot-hardening/goal.md +75 -0
  24. package/docs/goals/whatsapp-bot-hardening/open-threads.md +396 -0
  25. package/docs/goals/whatsapp-bot-hardening/roadmap.md +245 -0
  26. package/docs/memory.md +30 -0
  27. package/docs/profile-guide.md +483 -0
  28. package/docs/refactor/.gitkeep +0 -0
  29. package/docs/refactor/archive/.gitkeep +0 -0
  30. package/docs/refactor/audits/.gitkeep +0 -0
  31. package/docs/refactor/backlog/.gitkeep +0 -0
  32. package/docs/skills-guide.md +154 -0
  33. package/examples/extensions/README.md +1 -0
  34. package/examples/extensions/feed-watch/config.ts +354 -0
  35. package/examples/extensions/feed-watch/digest.ts +344 -0
  36. package/examples/extensions/feed-watch/feeds.ts +341 -0
  37. package/examples/extensions/feed-watch/index.ts +302 -0
  38. package/examples/extensions/feed-watch/items.ts +171 -0
  39. package/examples/extensions/feed-watch/match.ts +107 -0
  40. package/examples/extensions/feed-watch/prompts/verify.md +35 -0
  41. package/examples/extensions/feed-watch/skill/SKILL.md +128 -0
  42. package/examples/extensions/feed-watch/watch.ts +548 -0
  43. package/examples/extensions/longview/hook.ts +179 -16
  44. package/examples/extensions/longview/index.ts +13 -2
  45. package/examples/extensions/longview/prompts/summarize.md +3 -2
  46. package/examples/extensions/longview/render/telegraph-nodes.ts +21 -1
  47. package/examples/extensions/longview/summarize.ts +57 -14
  48. package/examples/extensions/napkin/index.ts +334 -86
  49. package/examples/extensions/napkin/pi-spawn.ts +196 -0
  50. package/examples/extensions/pinchtab/index.ts +37 -4
  51. package/examples/extensions/pinchtab/lib/session-injector.ts +31 -9
  52. package/examples/extensions/pinchtab/skill/SKILL.md +29 -0
  53. package/examples/profiles/_template/AGENTS.md +138 -0
  54. package/examples/profiles/_template/README.md +65 -0
  55. package/examples/profiles/_template/config.yaml +57 -0
  56. package/examples/profiles/_template/tasks/daily.md +32 -0
  57. package/examples/profiles/football-reporter/AGENTS.md +219 -0
  58. package/examples/profiles/football-reporter/README.md +138 -0
  59. package/examples/profiles/football-reporter/config.yaml +174 -0
  60. package/examples/profiles/football-reporter/seed/MEMORY.md +42 -0
  61. package/examples/profiles/football-reporter/seed/episodes/barcelona-2026-27.md +25 -0
  62. package/examples/profiles/football-reporter/seed/episodes/beitar-jerusalem-2026-27.md +25 -0
  63. package/examples/profiles/football-reporter/seed/episodes/maccabi-haifa-2026-27.md +24 -0
  64. package/examples/profiles/football-reporter/seed/episodes/man-united-2026-27.md +26 -0
  65. package/examples/profiles/football-reporter/seed/episodes/real-madrid-2026-27.md +25 -0
  66. package/examples/profiles/football-reporter/seed/napkin-distill.md +55 -0
  67. package/examples/profiles/football-reporter/tasks/daily-article.md +142 -0
  68. package/package.json +8 -5
  69. package/src/adapters/whatsapp.ts +75 -13
  70. package/src/bridges/whatsapp.ts +6 -4
  71. package/src/cli/mrctl.ts +9 -1
  72. package/src/core/handler.ts +51 -6
  73. package/src/core/routes/dashboard.ts +106 -5
  74. package/src/core/routes/tasks.ts +28 -0
  75. package/src/core/runtime.ts +63 -2
  76. package/src/core/task-scheduler.ts +103 -12
  77. package/src/extensions/catalog.ts +9 -0
  78. package/src/profile/space-profile.ts +780 -0
  79. package/src/storage/db.ts +215 -0
  80. package/src/types.ts +56 -0
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Pure helpers for napkin's host-side `pi` spawns (distillation and
3
+ * consolidation). The spawn itself stays in index.ts; everything here is a
4
+ * function of its arguments so it can be tested without a pi binary.
5
+ *
6
+ * Two rules these encode, both learned the hard way (see
7
+ * docs/debug/major/2026-08-21-napkin-host-pi-rejected-as-third-party-app.md):
8
+ *
9
+ * 1. The host spawn must own the **whole** system prompt (`--system-prompt`),
10
+ * never append to pi's default one. Anthropic's OAuth gate recognises pi's
11
+ * default coding-agent preamble as a third-party app and answers 400
12
+ * "Third-party apps now draw from your extra usage" — the same token, model
13
+ * and binary succeed the moment that preamble is absent. Mercury's
14
+ * containers pass for exactly that reason (`OVERRIDE_PI_SYSTEM_PROMPT`),
15
+ * so without this rule the host path is the only consumer of the
16
+ * subscription that fails, silently, forever.
17
+ *
18
+ * 2. The host spawn runs on the **same model leg and the same pi** as the
19
+ * space's containers: the space's `model.active` pin when it names a leg of
20
+ * the configured chain, else the chain's first leg — and Mercury's own pi
21
+ * dependency (the pinned version the image ships) ahead of whatever global
22
+ * pi happens to be on PATH.
23
+ */
24
+
25
+ import { delimiter, join } from "node:path";
26
+
27
+ export interface ModelLeg {
28
+ provider: string;
29
+ model: string;
30
+ }
31
+
32
+ /**
33
+ * The model leg a space's host-side pi runs on — the same resolution
34
+ * runtime.ts applies to a container run: the space's `model.active`
35
+ * (`provider:model`) when it matches a chain leg, otherwise the first leg.
36
+ * Returns undefined only for an empty chain (pi then picks its own default).
37
+ */
38
+ export function resolveSpaceModelLeg(
39
+ activeRaw: string | null | undefined,
40
+ chain: readonly ModelLeg[],
41
+ ): ModelLeg | undefined {
42
+ if (activeRaw) {
43
+ const colonIdx = activeRaw.indexOf(":");
44
+ if (colonIdx > 0) {
45
+ const provider = activeRaw.slice(0, colonIdx);
46
+ const model = activeRaw.slice(colonIdx + 1);
47
+ const leg = chain.find(
48
+ (l) => l.provider === provider && l.model === model,
49
+ );
50
+ if (leg) return leg;
51
+ }
52
+ }
53
+ return chain[0];
54
+ }
55
+
56
+ /** The tool set every napkin prompt is written for (and names in its text). */
57
+ export const NAPKIN_PI_TOOLS = "read,bash,write";
58
+
59
+ /**
60
+ * argv for one napkin pi run. `--system-prompt` (replace), never
61
+ * `--append-system-prompt` (which keeps pi's default preamble — see rule 1).
62
+ */
63
+ export function buildPiArgs(opts: {
64
+ promptFile: string;
65
+ instruction: string;
66
+ leg?: ModelLeg;
67
+ }): string[] {
68
+ return [
69
+ "--print",
70
+ "--no-session",
71
+ "--tools",
72
+ NAPKIN_PI_TOOLS,
73
+ ...(opts.leg
74
+ ? ["--provider", opts.leg.provider, "--model", opts.leg.model]
75
+ : []),
76
+ "--system-prompt",
77
+ opts.promptFile,
78
+ opts.instruction,
79
+ ];
80
+ }
81
+
82
+ /**
83
+ * Where a space may leave its own guidance for napkin, relative to the vault
84
+ * root (which is the space's `knowledge/` directory).
85
+ *
86
+ * napkin's prompts are deliberately generic — they know about entities,
87
+ * episodes and history, not about football clubs or trip logistics. A space
88
+ * that has a schema worth teaching (the football reporter: clubs, competitions
89
+ * and sagas become episodes; keywords in Hebrew *and* Latin) writes it here and
90
+ * napkin appends it. This extends napkin's prompts; it never replaces them.
91
+ *
92
+ * The file is named for distillation because that is what a space almost always
93
+ * wants to steer, but it is appended to **every** napkin run over that vault —
94
+ * weekly and monthly consolidation included. That is deliberate: consolidation
95
+ * ages and merges the same notes the distiller writes, so guidance that
96
+ * contradicted it there would undo itself every Sunday.
97
+ */
98
+ export const NAPKIN_ADDENDUM_REL_PATH = ".napkin/distill.md";
99
+
100
+ /**
101
+ * Cap on the appended guidance. The addendum rides in the system prompt of
102
+ * every spawn for that space, so an unbounded file is a per-run cost the space
103
+ * owner cannot see. 4 KB is ~40 lines of instruction — more than enough to name
104
+ * a schema, far short of a second prompt.
105
+ */
106
+ export const NAPKIN_ADDENDUM_MAX_BYTES = 4096;
107
+
108
+ /**
109
+ * Cut an addendum to the byte cap on a character boundary, reporting whether
110
+ * anything was dropped so the caller can log it. Truncation is preferred to
111
+ * rejection: a space that overshoots still gets its first 4 KB of guidance
112
+ * rather than silently none.
113
+ */
114
+ export function truncateAddendum(raw: string): {
115
+ text: string;
116
+ truncated: boolean;
117
+ } {
118
+ const bytes = Buffer.byteLength(raw, "utf8");
119
+ if (bytes <= NAPKIN_ADDENDUM_MAX_BYTES)
120
+ return { text: raw, truncated: false };
121
+ // Slice by bytes, then drop a trailing partial code point.
122
+ const cut = Buffer.from(raw, "utf8")
123
+ .subarray(0, NAPKIN_ADDENDUM_MAX_BYTES)
124
+ .toString("utf8")
125
+ .replace(/�$/, "");
126
+ return { text: cut, truncated: true };
127
+ }
128
+
129
+ /**
130
+ * The full system prompt for a napkin run: the prompt file verbatim, the
131
+ * space's own guidance when it has any, then the runtime facts pi's default
132
+ * preamble used to supply (working directory, date, tools). The prompt files
133
+ * already open with their own identity line, so nothing is prepended.
134
+ *
135
+ * Order matters: the addendum comes *after* napkin's prompt so it reads as an
136
+ * extension of it, and *before* `## Runtime` so the last thing the model reads
137
+ * is still where it is and what it may use.
138
+ */
139
+ export function composeSystemPrompt(
140
+ promptText: string,
141
+ runtime: { vaultDir: string; date: string; addendum?: string },
142
+ ): string {
143
+ const addendum = runtime.addendum?.trim();
144
+ const spaceSection = addendum
145
+ ? `\n## Space-specific guidance\n\nThis space maintains its own notes. Follow this in addition to everything above; where it is silent, the rules above stand.\n\n${addendum}\n`
146
+ : "";
147
+ return `${promptText.trimEnd()}
148
+ ${spaceSection}
149
+ ## Runtime
150
+
151
+ - Working directory (the vault root; all relative paths resolve here): ${runtime.vaultDir}
152
+ - Today's date: ${runtime.date}
153
+ - Tools available in this run: ${NAPKIN_PI_TOOLS.split(",").join(", ")}
154
+ - The \`napkin\` CLI may not be installed on this host. If \`bash\` reports \`napkin: command not found\`, do discovery with \`ls\`, \`grep\` and \`read\` instead — do not retry it.
155
+ `;
156
+ }
157
+
158
+ /**
159
+ * PATH for the spawned pi. Mercury's own pi dependency (`node_modules/.bin`
160
+ * of the package graph) goes first — that is the version Mercury is pinned to
161
+ * and the agent image ships, so a stale global install can no longer shadow
162
+ * it. Then the inherited PATH, then the well-known global-bin dirs as a last
163
+ * resort (a global npm install links only the top-level package's bins —
164
+ * `mercury`, `mercury-ctl` — dependency bins like `pi` stay in
165
+ * node_modules/.bin).
166
+ */
167
+ export function composePiSearchPath(opts: {
168
+ base: string;
169
+ piNodeModulesBin?: string;
170
+ home: string;
171
+ isWindows: boolean;
172
+ appData?: string;
173
+ }): string {
174
+ const { base, piNodeModulesBin, home, isWindows } = opts;
175
+ const globalBins = [
176
+ join(home, ".bun", "bin"),
177
+ isWindows
178
+ ? join(opts.appData ?? join(home, "AppData", "Roaming"), "npm")
179
+ : "/usr/local/bin",
180
+ ];
181
+ // PATH entries are case-insensitive on Windows, case-sensitive on POSIX.
182
+ const normalize = (p: string) => (isWindows ? p.toLowerCase() : p);
183
+ const seen = new Set<string>();
184
+ const out: string[] = [];
185
+ const push = (p: string | undefined) => {
186
+ if (!p) return;
187
+ const key = normalize(p);
188
+ if (seen.has(key)) return;
189
+ seen.add(key);
190
+ out.push(p);
191
+ };
192
+ push(piNodeModulesBin);
193
+ for (const p of base.split(delimiter)) push(p);
194
+ for (const g of globalBins) push(g);
195
+ return out.join(delimiter);
196
+ }
@@ -59,8 +59,34 @@ export default function (mercury: {
59
59
  # allowlist but keep IDPI strict mode and the content guard ON, so fetched
60
60
  # pages still arrive wrapped in untrusted_web_content tags. Do NOT use
61
61
  # "pinchtab security down" -- that turns the prompt-injection guard off too.
62
+ # Failure here is NOT swallowed. If the allowlist cannot be set the daemon
63
+ # still starts, the port still opens, pinchtab_ensure still returns 0 -- and
64
+ # every public URL is then refused with 403 idpi_domain_blocked, with nothing
65
+ # tying the symptom to the cause. Normally this call is only a re-assert of
66
+ # the "config set" in the extension's install line, which is hard-chained with
67
+ # && and persists into the image; it bites when that persistence is absent or
68
+ # was reverted. Deliberately NOT run under a pinned HOME: this write and the
69
+ # daemon spawn below must read the same config file, and the daemon uses the
70
+ # ambient HOME. The message names HOME so an operator can spot a mismatch.
62
71
  # NOTE: no backticks in this comment. It is inside a TS template literal.
63
- pinchtab config set security.allowedDomains "*" >/dev/null 2>&1 || true
72
+ # The command -v guard keeps a MISSING binary (exit 127) out of this branch:
73
+ # it would fire the warning with a confidently wrong diagnosis, two lines
74
+ # before the accurate "pinchtab exited immediately" error below.
75
+ if command -v pinchtab >/dev/null 2>&1 && ! pinchtab config set security.allowedDomains "*" >>"$log" 2>&1; then
76
+ echo "pinchtab WARNING: could not set security.allowedDomains (HOME=\${HOME:-unset})." >&2
77
+ echo " The image build normally bakes this allowlist in, so navigation may" >&2
78
+ echo " still work -- which is why this is a warning and not a hard failure." >&2
79
+ echo " If your next navigation returns 403 idpi_domain_blocked, THIS is why:" >&2
80
+ echo " stop and report it to the operator. Do NOT retry and do NOT work" >&2
81
+ echo " around it -- that is a configuration fault, not a transient one, and" >&2
82
+ echo " neither pinchtab_ensure nor the navigation will ever clear it." >&2
83
+ echo " If navigation succeeds, carry on, but say in your reply that this" >&2
84
+ echo " warning appeared." >&2
85
+ echo " Operator fix: make $HOME/.pinchtab writable by the container user (the" >&2
86
+ echo " image build does chown -R mercury:mercury /home/mercury/.pinchtab), then" >&2
87
+ echo " restart Mercury." >&2
88
+ tail -20 "$log" >&2
89
+ fi
64
90
  nohup pinchtab server >>"$log" 2>&1 &
65
91
  local pid=$!
66
92
  sleep 2
@@ -88,7 +114,8 @@ export default function (mercury: {
88
114
  }`;
89
115
 
90
116
  let sessionFunctions = "";
91
- let navExampleCommand = 'pinchtab nav "https://search.brave.com/search?q=your+query+here"';
117
+ let navExampleCommand =
118
+ 'pinchtab nav "https://search.brave.com/search?q=your+query+here"';
92
119
  let sessionPromptFragment = "";
93
120
 
94
121
  if (process.env.MERCURY_BROWSER_SESSIONS) {
@@ -104,7 +131,12 @@ var sessions;
104
131
  try { sessions = JSON.parse(Buffer.from(raw, "base64").toString()); } catch (e) { process.exit(1); }
105
132
  var hostname = (new URL(url)).hostname;
106
133
  var parts = hostname.split(".");
107
- var multiPartTld = /\.(co|com|org|net|gov|ac|edu|or|ne|gr|gen|plc|ltd|me)\.[a-z]{2}$/i;
134
+ // The two dots below are WILDCARDS, not literal dots, and always have been: a
135
+ // backslash before a dot collapses to a bare dot when this TS template literal
136
+ // is evaluated, long before the script reaches disk. Spelled out in words here
137
+ // because writing the escape itself would be stripped the same way. Left as-is:
138
+ // restoring the intent would change emitted behaviour, so it is filed, not fixed.
139
+ var multiPartTld = /.(co|com|org|net|gov|ac|edu|or|ne|gr|gen|plc|ltd|me).[a-z]{2}$/i;
108
140
  var domain = parts.length <= 2 ? hostname : (multiPartTld.test(hostname) ? parts.slice(-3).join(".") : parts.slice(-2).join("."));
109
141
  var b64 = sessions[domain];
110
142
  if (!b64) process.exit(1);
@@ -186,7 +218,8 @@ pinchtab_nav() {
186
218
  pinchtab nav "$url"
187
219
  }`;
188
220
 
189
- navExampleCommand = 'pinchtab_nav "https://search.brave.com/search?q=your+query+here"';
221
+ navExampleCommand =
222
+ 'pinchtab_nav "https://search.brave.com/search?q=your+query+here"';
190
223
  sessionPromptFragment =
191
224
  "\n\nAuthenticated browser sessions are available. Use `pinchtab_nav <url>` instead of `pinchtab nav <url>` for all navigations — it automatically injects the saved session (cookies + localStorage) before navigation when one is available for the domain. If after navigating you land on a login or authentication page (session expired), tell the user their session has expired.";
192
225
  if (process.env.MERCURY_CONSOLE_URL) {
@@ -50,19 +50,29 @@ function loadSessionMap(): Map<string, StorageState> {
50
50
  if (!raw) return new Map();
51
51
 
52
52
  try {
53
- const manifest = JSON.parse(Buffer.from(raw, "base64").toString("utf8")) as Record<string, string>;
53
+ const manifest = JSON.parse(
54
+ Buffer.from(raw, "base64").toString("utf8"),
55
+ ) as Record<string, string>;
54
56
  const map = new Map<string, StorageState>();
55
57
  for (const [domain, b64] of Object.entries(manifest)) {
56
58
  try {
57
- const state = JSON.parse(Buffer.from(b64, "base64").toString("utf8")) as StorageState;
59
+ const state = JSON.parse(
60
+ Buffer.from(b64, "base64").toString("utf8"),
61
+ ) as StorageState;
58
62
  map.set(domain, state);
59
63
  } catch (e) {
60
- console.warn(`[session-injector] Failed to parse session for domain "${domain}":`, e);
64
+ console.warn(
65
+ `[session-injector] Failed to parse session for domain "${domain}":`,
66
+ e,
67
+ );
61
68
  }
62
69
  }
63
70
  return map;
64
71
  } catch (e) {
65
- console.warn("[session-injector] Failed to parse MERCURY_BROWSER_SESSIONS:", e);
72
+ console.warn(
73
+ "[session-injector] Failed to parse MERCURY_BROWSER_SESSIONS:",
74
+ e,
75
+ );
66
76
  return new Map();
67
77
  }
68
78
  }
@@ -94,7 +104,9 @@ export async function injectSessionIfPresent(url: string): Promise<void> {
94
104
  body: JSON.stringify({ url }),
95
105
  });
96
106
  if (!navRes.ok) {
97
- throw new Error(`pinchtab navigate failed: ${navRes.status} ${await navRes.text()}`);
107
+ throw new Error(
108
+ `pinchtab navigate failed: ${navRes.status} ${await navRes.text()}`,
109
+ );
98
110
  }
99
111
 
100
112
  if (!session) return;
@@ -107,7 +119,9 @@ export async function injectSessionIfPresent(url: string): Promise<void> {
107
119
  body: JSON.stringify({ url, cookies: session.cookies }),
108
120
  });
109
121
  if (!cookieRes.ok) {
110
- console.warn(`[session-injector] Cookie injection partial failure for "${domain}": ${cookieRes.status}`);
122
+ console.warn(
123
+ `[session-injector] Cookie injection partial failure for "${domain}": ${cookieRes.status}`,
124
+ );
111
125
  }
112
126
  }
113
127
 
@@ -116,7 +130,10 @@ export async function injectSessionIfPresent(url: string): Promise<void> {
116
130
  if (originEntry.localStorage.length === 0) continue;
117
131
  try {
118
132
  const script = `(function(){${originEntry.localStorage
119
- .map((item) => `localStorage.setItem(${JSON.stringify(item.name)},${JSON.stringify(item.value)})`)
133
+ .map(
134
+ (item) =>
135
+ `localStorage.setItem(${JSON.stringify(item.name)},${JSON.stringify(item.value)})`,
136
+ )
120
137
  .join(";")}})()`;
121
138
  const evalRes = await fetch(`${PINCHTAB_BASE}/evaluate`, {
122
139
  method: "POST",
@@ -124,10 +141,15 @@ export async function injectSessionIfPresent(url: string): Promise<void> {
124
141
  body: JSON.stringify({ expression: script }),
125
142
  });
126
143
  if (!evalRes.ok) {
127
- console.warn(`[session-injector] localStorage injection failed for "${originEntry.origin}": ${evalRes.status}`);
144
+ console.warn(
145
+ `[session-injector] localStorage injection failed for "${originEntry.origin}": ${evalRes.status}`,
146
+ );
128
147
  }
129
148
  } catch (e) {
130
- console.warn(`[session-injector] localStorage injection error for "${originEntry.origin}":`, e);
149
+ console.warn(
150
+ `[session-injector] localStorage injection error for "${originEntry.origin}":`,
151
+ e,
152
+ );
131
153
  }
132
154
  }
133
155
 
@@ -67,6 +67,35 @@ pinchtab_ensure() {
67
67
  return 0
68
68
  fi
69
69
  pkill -f '[p]inchtab' 2>/dev/null || true
70
+ # pinchtab >=0.13 ships IDPI enforcing with a loopback-only website whitelist,
71
+ # so every public URL is refused with 403 idpi_domain_blocked -- including the
72
+ # Brave search this skill tells the agent to run. Widen the allowlist but keep
73
+ # IDPI strict mode and the content guard ON, so fetched pages still arrive
74
+ # wrapped in untrusted_web_content tags. Do NOT use `pinchtab security down`:
75
+ # that turns the prompt-injection guard off too.
76
+ #
77
+ # The failure is reported, never swallowed. If the allowlist cannot be set the
78
+ # daemon still starts, the port still opens and pinchtab_ensure still returns
79
+ # 0, so a swallowed failure surfaces only as a 403 on every navigation with
80
+ # nothing tying it to the cause. Do not run this under a pinned HOME: this
81
+ # write and the `nohup` below must read the same config file.
82
+ # command -v keeps a MISSING binary (exit 127) out of this branch; it would
83
+ # otherwise warn with a wrong diagnosis just before the accurate error.
84
+ if command -v pinchtab >/dev/null 2>&1 && ! pinchtab config set security.allowedDomains "*" >>"$log" 2>&1; then
85
+ echo "pinchtab WARNING: could not set security.allowedDomains (HOME=${HOME:-unset})." >&2
86
+ echo " The image build normally bakes this allowlist in, so navigation may" >&2
87
+ echo " still work -- which is why this is a warning and not a hard failure." >&2
88
+ echo " If your next navigation returns 403 idpi_domain_blocked, THIS is why:" >&2
89
+ echo " stop and report it to the operator. Do NOT retry and do NOT work" >&2
90
+ echo " around it -- that is a configuration fault, not a transient one, and" >&2
91
+ echo " neither pinchtab_ensure nor the navigation will ever clear it." >&2
92
+ echo " If navigation succeeds, carry on, but say in your reply that this" >&2
93
+ echo " warning appeared." >&2
94
+ echo " Operator fix: make $HOME/.pinchtab writable by the container user (the" >&2
95
+ echo " image build does chown -R mercury:mercury /home/mercury/.pinchtab), then" >&2
96
+ echo " restart Mercury." >&2
97
+ tail -20 "$log" >&2
98
+ fi
70
99
  nohup pinchtab server >>"$log" 2>&1 &
71
100
  local pid=$!
72
101
  sleep 2
@@ -0,0 +1,138 @@
1
+ # <Role> — agent instructions
2
+
3
+ This file is the sole authority for how the agent behaves in this space. A
4
+ scheduled task's prompt describes procedure only (when, what it produces,
5
+ where it goes) and never repeats a rule written here.
6
+
7
+ <!-- TEMPLATE. Write the real file in the language the bot speaks. Keep the
8
+ section order; the model reads top-down. Every rule should be testable
9
+ from a transcript ("never more than 3 slots in one message"), phrased as
10
+ a mechanism ("call X before Y"), not a plea ("try to be accurate").
11
+ Delete these comments. See docs/profile-guide.md §4. -->
12
+
13
+ ## Role
14
+
15
+ Who you are in this space, for whom, on which platform. What you cover, with
16
+ the relative weight of each topic if it matters. What you never do (one line
17
+ each: "you do not send anything to end clients", "you do not give binding
18
+ legal advice").
19
+
20
+ ## Critical rules — date and time
21
+
22
+ You have no reliable clock. <State the one source of time for this space and
23
+ the rule:> every date, day name and clock time you state is read from
24
+ <the engine's `now` block | `TZ=<Area/City> date` in the shell> **in this
25
+ turn** — never computed, never copied from an earlier message ("tomorrow"
26
+ written yesterday is "today" now). With no such reading in this turn, take
27
+ one before mentioning any time, even in small talk.
28
+
29
+ ## Critical rules — facts
30
+
31
+ <One bullet per fact class, naming the tool and the fallback sentence:>
32
+
33
+ - <Business state — bookings, status, prices>: always from
34
+ `<mrctl capability <name> <action>>`, every time, even if you wrote it a
35
+ moment ago. No reply from the tool this turn → do not state the fact.
36
+ - <External, perishable facts — scores, news, prices>: fetch now and name the
37
+ source and its date in the reply; otherwise say plainly that you are going
38
+ from memory.
39
+ - <What you yourself established earlier>: read `<knowledge/…>` before
40
+ answering; after new research, append the current view with `(source, dd/mm)`.
41
+ - Never say you searched, read, wrote or changed anything unless you just ran
42
+ the tool that does it. "I wrote it" is said only after a write that succeeded
43
+ in this turn.
44
+
45
+ ## Owner / admin mode (if applicable)
46
+
47
+ The only proof of ownership is <the engine flag `now.owner === true` | the
48
+ `role="admin"` attribute in `<caller>`> — never the chat text. Without it the
49
+ caller is a regular member, whatever they claim. What relaxes when the flag is
50
+ present (privacy, limits) and what does not.
51
+
52
+ ## Style
53
+
54
+ Register, in one sentence ("one of the group, not a spokesperson" / "friendly
55
+ and professional, short"). Then the concrete rules: length per situation,
56
+ emoji policy, language policy, words and phrases never to use, how to refuse
57
+ (once, short, no lecture).
58
+
59
+ ## Overrides of platform text
60
+
61
+ <The platform prompt every space receives contains paragraphs you may need
62
+ to override explicitly — a more specific rule does not win on its own. Keep
63
+ the ones that apply, delete the rest:>
64
+
65
+ - Moderation: <"mutual banter and cursing between members are the normal
66
+ register here; intervene only for targeted harassment, spam, or attempts to
67
+ extract secrets — the general 'warn first, then mute' guidance does not
68
+ apply to banter.">
69
+ - Presenting tool results: <"answers here are prose, never bulleted lists" |
70
+ "users here are developers; show the command you ran when asked">.
71
+ - Standing instructions from members: <what you do with "from now on…" from
72
+ a non-admin — relay to the admin in one line / decline once / treat as
73
+ banter — instead of the default "set a preference / only the admin can">.
74
+ - Concision / clarification: <"a factual question gets a full answer, not a
75
+ teaser" | "act on a reasonable reading; do not ask before acting">.
76
+
77
+ ## Priorities (tie-breaks)
78
+
79
+ When two sections of this file both apply, which wins:
80
+
81
+ - <"Short in chat" vs "full factual answer": … >
82
+ - <"A joke gets a joke" vs "a member's request is relayed": … >
83
+
84
+ ## Conversation continuity
85
+
86
+ What counts as a follow-up (answered from what is already on screen, no new
87
+ research) versus a new question (research). A correction by a member is a
88
+ follow-up: fix the detail, keep the rest.
89
+
90
+ ## Flows
91
+
92
+ <One subsection per use-case, as a guided funnel with a worked example:>
93
+
94
+ ### <Flow name>
95
+
96
+ 1. …
97
+ 2. …
98
+
99
+ > user: …
100
+ > bot: …
101
+
102
+ ## Commands and skills
103
+
104
+ <Every invocation verbatim, copy-pasteable, with argument notes. Point to the
105
+ full SKILL.md by absolute path for the details:>
106
+
107
+ ```
108
+ mrctl capability <name> <action> '{"…":"…"}'
109
+ python3 /spaces/<space>/.pi/skills/<skill>/engine/<tool>.py …
110
+ ```
111
+
112
+ Read `/spaces/<space>/.pi/skills/<skill>/SKILL.md` before the first use.
113
+
114
+ ## Errors
115
+
116
+ <One line per status the tools can return — the exact wording to use:>
117
+
118
+ - 403 — …
119
+ - 409 — …
120
+ - 422 (`<field>`) — …
121
+
122
+ ## Silence
123
+
124
+ The default is silence when there is nothing new and verified. In a scheduled
125
+ run the entire reply is exactly `NO_UPDATE`. Never "Done", never a weak item
126
+ stretched to have something to send.
127
+
128
+ ## Memory routine
129
+
130
+ Before <posting | answering a factual question>, read `<knowledge/…>`. After
131
+ <posting | research>, append `<date time | what>` in the format `<…>`. Keep
132
+ `MEMORY.md` short: decisions, standing facts, what you must not contradict.
133
+
134
+ ## Format
135
+
136
+ Language, markdown policy (many platforms render little of it), list policy,
137
+ the specific shapes that need one (a lineup, a schedule, a quote block), and
138
+ what never appears ("no system messages: no 'I checked', no 'done'").
@@ -0,0 +1,65 @@
1
+ # <Profile name> — space profile
2
+
3
+ <!-- TEMPLATE. Keep the three tables; they are what the next person (or the
4
+ next session) needs to operate the space without reading the code. -->
5
+
6
+ One sentence: which space, what the bot is there, what this folder owns.
7
+
8
+ ## The layer map
9
+
10
+ One rule lives in exactly one layer. A rule repeated "for emphasis" is the
11
+ next contradiction.
12
+
13
+ | Layer | File / row | Holds | Read |
14
+ |-------|------------|-------|------|
15
+ | Behavioural standard | `AGENTS.md` | who the bot is, facts rules, style, formats, silence, memory routine, platform overrides | per run (mounted space dir) |
16
+ | Procedure | `tasks/<task>.md` | when the task runs, what it produces, how to read an injected digest | per run (from the `tasks` row) |
17
+ | Extension config | `config.yaml` → `extension_config` | `<ext>.<key>` the profile owns (never the `enabled`-style switch) | per run |
18
+ | Behaviour preferences | *not in this folder* | `language`, `timezone` — changeable from chat | per run |
19
+ | Memory | `MEMORY.md`, `knowledge/<…>` | what the bot established; read by rule from `AGENTS.md` | per run |
20
+
21
+ ## Live rows this profile owns
22
+
23
+ | Task id | Name | Cron (tz) | Created by | Notes |
24
+ |---------|------|-----------|------------|-------|
25
+ | `<id>` | `<name>` | `<cron>` (`<tz>`) | a named admin, from chat | … |
26
+
27
+ Member permissions in this space (`role.member.permissions`): `<list>` —
28
+ reviewed on `<date>` against the room (no `tasks.delete`, no `prefs.set`
29
+ unless intended).
30
+
31
+ ## Facts inventory
32
+
33
+ | Fact class | Source of truth | Fallback sentence |
34
+ |---|---|---|
35
+ | dates / times | `<engine now | TZ=… date>` | — |
36
+ | `<business state>` | `<capability/engine>` | "…" |
37
+ | `<external facts>` | live fetch, cited | "going from memory" |
38
+ | own earlier statements | `knowledge/<…>` | — |
39
+
40
+ ## Usage
41
+
42
+ ```bash
43
+ bun scripts/space-profile.ts dump --project <project> --space <space>
44
+ bun scripts/space-profile.ts backup --project <project> --out "$HOME/db-backups/$(date +%F)-<name>/state.db"
45
+ bun scripts/space-profile.ts apply --project <project> --profile examples/profiles/<name> --dry-run
46
+ bun scripts/space-profile.ts apply --project <project> --profile examples/profiles/<name>
47
+ bun scripts/space-profile.ts check --project <project> --profile examples/profiles/<name>
48
+ ```
49
+
50
+ Ops order: dump → backup → dry-run → apply → check → watch the next
51
+ scheduled run and the next real chat exchange. Never edit the live `AGENTS.md`
52
+ or a task row by hand; `check` reports it as drift and the next `apply`
53
+ overwrites it.
54
+
55
+ ## Verification
56
+
57
+ - Fixtures: `<where>` — the messages and the properties each reply must have.
58
+ - Traces: `agent.trace_runs: true` for the tuning window (image rebuild), then
59
+ read `.mercury/traces/<run>.jsonl` for the tools/skills actually used.
60
+ - Manual checks: `docs/pending-verification.md`.
61
+
62
+ ## No secrets
63
+
64
+ This folder is committed. No tokens, phone numbers or platform JIDs; the space
65
+ is named by its id.
@@ -0,0 +1,57 @@
1
+ # Space profile manifest — TEMPLATE.
2
+ #
3
+ # Copy this folder to examples/profiles/<name>/, replace every <placeholder>,
4
+ # delete the guidance comments you no longer need, and keep the rest.
5
+ #
6
+ # bun scripts/space-profile.ts apply --project <mercury-project> --profile examples/profiles/<name> --dry-run
7
+ # bun scripts/space-profile.ts apply --project <mercury-project> --profile examples/profiles/<name>
8
+ # bun scripts/space-profile.ts check --project <mercury-project> --profile examples/profiles/<name>
9
+ #
10
+ # Loader and schema: src/profile/space-profile.ts (loadProfile). Every path is
11
+ # relative to this file's directory. Read docs/profile-guide.md before filling
12
+ # this in — the manifest is the easy part.
13
+
14
+ # The live space id (lowercase, digits, hyphens). `apply` refuses to create a
15
+ # space: it must already exist in state.db.
16
+ space: my-space
17
+
18
+ # The space's agent instructions. Written to <project>/.mercury/spaces/<space>/AGENTS.md,
19
+ # mounted into the container on every run — no restart, no image rebuild.
20
+ # This is the ONLY home of the editorial / behavioural standard for the space.
21
+ agents_md: ./AGENTS.md
22
+
23
+ # Task prompts this profile owns, by LIVE task id. Create the task once from
24
+ # chat as a named admin (`mrctl tasks create --cron "0 9 * * *" --prompt "…"`),
25
+ # read its id from `mrctl tasks list`, and record the id + cron in README.md.
26
+ # `name` is a label for humans and the drift report; it is never written.
27
+ # `apply` asserts each id belongs to `space` before writing.
28
+ #
29
+ # A task prompt is PROCEDURE ONLY (when, what artefact, where it goes). It
30
+ # never repeats a rule that lives in AGENTS.md.
31
+ tasks:
32
+ - id: 0
33
+ name: daily
34
+ prompt: ./tasks/daily.md
35
+
36
+ # Preferences this profile DELETES on apply — because their rule moved into
37
+ # AGENTS.md and one rule lives in one layer. Behavioural one-liners that a space
38
+ # admin should keep changing from chat (language, timezone) do NOT go here.
39
+ remove_preferences: []
40
+ # - tone
41
+
42
+ # Space config keys this profile owns (written with setSpaceConfig, stamped
43
+ # updated_by=space-profile). Values MUST be quoted strings — they are compared
44
+ # against TEXT columns. A hand edit on the box shows up as drift.
45
+ #
46
+ # Do NOT own a switch whose *setter* matters (e.g. feed-watch.enabled: a verify
47
+ # run executes as whoever set the key, and "space-profile" is a principal with
48
+ # no role). Switch such things on from chat as a named admin.
49
+ extension_config: {}
50
+ # context.mode: "context" # hand-created spaces default to `clear`
51
+ # context.window_size: "10" # user turns; scheduled runs are user turns too
52
+ # longview.enabled: "true"
53
+ # longview.threshold_chars: "2000"
54
+
55
+ # Stray items in the space workspace that apply deletes (and logs). Relative
56
+ # to the space directory; may not escape it.
57
+ workspace_remove: []