mercury-agent 0.4.5

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 (218) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +438 -0
  3. package/container/Dockerfile +127 -0
  4. package/container/Dockerfile.base +109 -0
  5. package/container/Dockerfile.power +17 -0
  6. package/container/agent-package.json +8 -0
  7. package/container/build.sh +54 -0
  8. package/docs/TODOS.md +147 -0
  9. package/docs/auth/dashboard.md +28 -0
  10. package/docs/auth/overview.md +109 -0
  11. package/docs/auth/whatsapp.md +173 -0
  12. package/docs/configuration.md +54 -0
  13. package/docs/container-lifecycle.md +349 -0
  14. package/docs/context-architecture.md +87 -0
  15. package/docs/deployment.md +199 -0
  16. package/docs/extensions.md +375 -0
  17. package/docs/graceful-shutdown.md +62 -0
  18. package/docs/kb-distillation.md +77 -0
  19. package/docs/media/overview.md +140 -0
  20. package/docs/media/whatsapp.md +171 -0
  21. package/docs/memory.md +137 -0
  22. package/docs/permissions.md +217 -0
  23. package/docs/pipeline.md +228 -0
  24. package/docs/prd-chat-memory.md +76 -0
  25. package/docs/prd-config-load.md +82 -0
  26. package/docs/rate-limiting.md +166 -0
  27. package/docs/scheduler.md +288 -0
  28. package/docs/setup-discord.md +100 -0
  29. package/docs/setup-slack.md +119 -0
  30. package/docs/setup-whatsapp.md +94 -0
  31. package/docs/subagents.md +166 -0
  32. package/docs/web-search.md +62 -0
  33. package/examples/extensions/README.md +12 -0
  34. package/examples/extensions/charts/index.ts +13 -0
  35. package/examples/extensions/charts/skill/SKILL.md +98 -0
  36. package/examples/extensions/gws/README.md +52 -0
  37. package/examples/extensions/gws/index.ts +106 -0
  38. package/examples/extensions/gws/skill/SKILL.md +57 -0
  39. package/examples/extensions/gws/skill/references/calendar.md +101 -0
  40. package/examples/extensions/gws/skill/references/docs.md +65 -0
  41. package/examples/extensions/gws/skill/references/drive.md +79 -0
  42. package/examples/extensions/gws/skill/references/gmail.md +85 -0
  43. package/examples/extensions/gws/skill/references/sheets.md +60 -0
  44. package/examples/extensions/napkin/index.ts +821 -0
  45. package/examples/extensions/napkin/prompts/consolidation-monthly.md +73 -0
  46. package/examples/extensions/napkin/prompts/consolidation-weekly.md +67 -0
  47. package/examples/extensions/napkin/prompts/kb-distillation.md +176 -0
  48. package/examples/extensions/napkin/skill/SKILL.md +728 -0
  49. package/examples/extensions/pdf/index.ts +23 -0
  50. package/examples/extensions/pdf/skill/LICENSE.txt +30 -0
  51. package/examples/extensions/pdf/skill/SKILL.md +314 -0
  52. package/examples/extensions/pdf/skill/forms.md +294 -0
  53. package/examples/extensions/pdf/skill/reference.md +612 -0
  54. package/examples/extensions/pdf/skill/scripts/check_bounding_boxes.py +65 -0
  55. package/examples/extensions/pdf/skill/scripts/check_fillable_fields.py +11 -0
  56. package/examples/extensions/pdf/skill/scripts/convert_pdf_to_images.py +33 -0
  57. package/examples/extensions/pdf/skill/scripts/create_validation_image.py +37 -0
  58. package/examples/extensions/pdf/skill/scripts/extract_form_field_info.py +122 -0
  59. package/examples/extensions/pdf/skill/scripts/extract_form_structure.py +115 -0
  60. package/examples/extensions/pdf/skill/scripts/fill_fillable_fields.py +98 -0
  61. package/examples/extensions/pdf/skill/scripts/fill_pdf_form_with_annotations.py +107 -0
  62. package/examples/extensions/permission-guard/index.ts +65 -0
  63. package/examples/extensions/pinchtab/index.ts +199 -0
  64. package/examples/extensions/pinchtab/lib/session-injector.ts +144 -0
  65. package/examples/extensions/pinchtab/skill/SKILL.md +224 -0
  66. package/examples/extensions/pinchtab/skill/TRUST.md +69 -0
  67. package/examples/extensions/pinchtab/skill/references/api.md +297 -0
  68. package/examples/extensions/pinchtab/skill/references/env.md +45 -0
  69. package/examples/extensions/pinchtab/skill/references/profiles.md +107 -0
  70. package/examples/extensions/tradestation/host/refresh.ts +102 -0
  71. package/examples/extensions/tradestation/index.ts +153 -0
  72. package/examples/extensions/tradestation/skill/SKILL.md +67 -0
  73. package/examples/extensions/tradestation/skill/scripts/ts-cli.ts +111 -0
  74. package/examples/extensions/voice-synth/index.ts +94 -0
  75. package/examples/extensions/voice-synth/skill/SKILL.md +38 -0
  76. package/examples/extensions/voice-transcribe/index.ts +381 -0
  77. package/examples/extensions/voice-transcribe/requirements.txt +8 -0
  78. package/examples/extensions/voice-transcribe/scripts/transcribe.py +179 -0
  79. package/examples/extensions/voice-transcribe/skill/SKILL.md +53 -0
  80. package/examples/extensions/web-search/index.ts +22 -0
  81. package/examples/extensions/web-search/skill/SKILL.md +114 -0
  82. package/examples/extensions/web-search/skill/references/apartments.md +178 -0
  83. package/examples/extensions/web-search/skill/references/car-purchase.md +132 -0
  84. package/examples/extensions/web-search/skill/references/car-rental.md +113 -0
  85. package/examples/extensions/web-search/skill/references/flights.md +133 -0
  86. package/examples/extensions/web-search/skill/references/hotels.md +148 -0
  87. package/examples/extensions/yahoo-mail/cli/bun.lock +66 -0
  88. package/examples/extensions/yahoo-mail/cli/package.json +13 -0
  89. package/examples/extensions/yahoo-mail/cli/ymail.mjs +353 -0
  90. package/examples/extensions/yahoo-mail/index.ts +57 -0
  91. package/examples/extensions/yahoo-mail/skill/SKILL.md +78 -0
  92. package/package.json +106 -0
  93. package/resources/agents/explore.md +50 -0
  94. package/resources/agents/worker.md +24 -0
  95. package/resources/builtin-extensions.txt +3 -0
  96. package/resources/connection-env-vars.json +25 -0
  97. package/resources/extensions/.gitkeep +0 -0
  98. package/resources/pi-extensions/subagent/agents.ts +126 -0
  99. package/resources/pi-extensions/subagent/index.ts +964 -0
  100. package/resources/profiles/coding/AGENTS.md +43 -0
  101. package/resources/profiles/coding/mercury-profile.yaml +15 -0
  102. package/resources/profiles/general/AGENTS.md +31 -0
  103. package/resources/profiles/general/mercury-profile.yaml +15 -0
  104. package/resources/profiles/research/AGENTS.md +40 -0
  105. package/resources/profiles/research/mercury-profile.yaml +15 -0
  106. package/resources/skills/config/SKILL.md +25 -0
  107. package/resources/skills/context/SKILL.md +33 -0
  108. package/resources/skills/conversation-recap/SKILL.md +19 -0
  109. package/resources/skills/media/SKILL.md +27 -0
  110. package/resources/skills/mutes/SKILL.md +31 -0
  111. package/resources/skills/permissions/SKILL.md +19 -0
  112. package/resources/skills/preferences/SKILL.md +31 -0
  113. package/resources/skills/recall/SKILL.md +24 -0
  114. package/resources/skills/roles/SKILL.md +18 -0
  115. package/resources/skills/spaces/SKILL.md +18 -0
  116. package/resources/skills/tasks/SKILL.md +45 -0
  117. package/resources/templates/AGENTS.md +157 -0
  118. package/resources/templates/env.template +34 -0
  119. package/resources/templates/mercury.example.yaml +75 -0
  120. package/src/adapters/discord-native.ts +534 -0
  121. package/src/adapters/discord.ts +38 -0
  122. package/src/adapters/setup.ts +89 -0
  123. package/src/adapters/slack.ts +9 -0
  124. package/src/adapters/whatsapp-media.ts +337 -0
  125. package/src/adapters/whatsapp.ts +629 -0
  126. package/src/agent/api-socket.ts +127 -0
  127. package/src/agent/container-entry.ts +967 -0
  128. package/src/agent/container-error.ts +49 -0
  129. package/src/agent/container-runner.ts +1272 -0
  130. package/src/agent/model-capabilities-core.ts +23 -0
  131. package/src/agent/model-capabilities.ts +231 -0
  132. package/src/agent/pi-failure-class.ts +83 -0
  133. package/src/agent/pi-jsonl-parser.ts +306 -0
  134. package/src/agent/preferences-prompt.ts +20 -0
  135. package/src/agent/user-error-messages.ts +78 -0
  136. package/src/bridges/discord.ts +171 -0
  137. package/src/bridges/slack.ts +177 -0
  138. package/src/bridges/teams.ts +160 -0
  139. package/src/bridges/telegram.ts +571 -0
  140. package/src/bridges/whatsapp.ts +290 -0
  141. package/src/chat-shim.ts +259 -0
  142. package/src/cli/mercury.ts +2508 -0
  143. package/src/cli/mrctl-http.ts +27 -0
  144. package/src/cli/mrctl.ts +611 -0
  145. package/src/cli/whatsapp-auth.ts +260 -0
  146. package/src/config-file.ts +397 -0
  147. package/src/config-model-chain.ts +30 -0
  148. package/src/config.ts +316 -0
  149. package/src/core/api-types.ts +58 -0
  150. package/src/core/api.ts +105 -0
  151. package/src/core/commands.ts +76 -0
  152. package/src/core/conversation.ts +47 -0
  153. package/src/core/handler.ts +206 -0
  154. package/src/core/media.ts +200 -0
  155. package/src/core/mute-duration.ts +22 -0
  156. package/src/core/outbox.ts +76 -0
  157. package/src/core/permissions.ts +192 -0
  158. package/src/core/profiles.ts +245 -0
  159. package/src/core/rate-limiter.ts +127 -0
  160. package/src/core/router.ts +191 -0
  161. package/src/core/routes/chat.ts +172 -0
  162. package/src/core/routes/config-builtin.ts +107 -0
  163. package/src/core/routes/config.ts +81 -0
  164. package/src/core/routes/connections.ts +190 -0
  165. package/src/core/routes/console.ts +668 -0
  166. package/src/core/routes/control.ts +46 -0
  167. package/src/core/routes/conversations.ts +66 -0
  168. package/src/core/routes/dashboard.ts +2491 -0
  169. package/src/core/routes/extensions.ts +37 -0
  170. package/src/core/routes/index.ts +14 -0
  171. package/src/core/routes/media.ts +72 -0
  172. package/src/core/routes/messages.ts +37 -0
  173. package/src/core/routes/mutes.ts +89 -0
  174. package/src/core/routes/prefs.ts +95 -0
  175. package/src/core/routes/roles.ts +125 -0
  176. package/src/core/routes/spaces.ts +60 -0
  177. package/src/core/routes/storage.ts +126 -0
  178. package/src/core/routes/tasks.ts +189 -0
  179. package/src/core/routes/tradestation.ts +268 -0
  180. package/src/core/routes/tts.ts +51 -0
  181. package/src/core/runtime.ts +1140 -0
  182. package/src/core/space-queue.ts +103 -0
  183. package/src/core/storage-cleanup.ts +140 -0
  184. package/src/core/storage-guard.ts +24 -0
  185. package/src/core/task-scheduler.ts +132 -0
  186. package/src/core/telegram-format.ts +178 -0
  187. package/src/core/trigger.ts +142 -0
  188. package/src/dashboard/index.html +729 -0
  189. package/src/dashboard/tokens.css +53 -0
  190. package/src/extensions/api.ts +252 -0
  191. package/src/extensions/catalog.ts +117 -0
  192. package/src/extensions/config-registry.ts +83 -0
  193. package/src/extensions/context.ts +36 -0
  194. package/src/extensions/hooks.ts +156 -0
  195. package/src/extensions/image-builder.ts +617 -0
  196. package/src/extensions/installer.ts +306 -0
  197. package/src/extensions/jobs.ts +122 -0
  198. package/src/extensions/loader.ts +271 -0
  199. package/src/extensions/permission-guard.ts +52 -0
  200. package/src/extensions/reserved.ts +28 -0
  201. package/src/extensions/skills.ts +123 -0
  202. package/src/extensions/types.ts +462 -0
  203. package/src/logger.ts +174 -0
  204. package/src/main.ts +586 -0
  205. package/src/server.ts +391 -0
  206. package/src/storage/db.ts +1624 -0
  207. package/src/storage/memory.ts +45 -0
  208. package/src/storage/pi-auth.ts +95 -0
  209. package/src/text/markdown.ts +117 -0
  210. package/src/text/rtl.ts +38 -0
  211. package/src/tradestation/host-api.ts +77 -0
  212. package/src/tradestation/pending-orders.ts +69 -0
  213. package/src/tts/azure.ts +52 -0
  214. package/src/tts/google.ts +128 -0
  215. package/src/tts/index.ts +8 -0
  216. package/src/tts/language.ts +20 -0
  217. package/src/tts/synthesize.ts +133 -0
  218. package/src/types.ts +295 -0
@@ -0,0 +1,33 @@
1
+ import os
2
+ import sys
3
+
4
+ from pdf2image import convert_from_path
5
+
6
+
7
+
8
+
9
+ def convert(pdf_path, output_dir, max_dim=1000):
10
+ images = convert_from_path(pdf_path, dpi=200)
11
+
12
+ for i, image in enumerate(images):
13
+ width, height = image.size
14
+ if width > max_dim or height > max_dim:
15
+ scale_factor = min(max_dim / width, max_dim / height)
16
+ new_width = int(width * scale_factor)
17
+ new_height = int(height * scale_factor)
18
+ image = image.resize((new_width, new_height))
19
+
20
+ image_path = os.path.join(output_dir, f"page_{i+1}.png")
21
+ image.save(image_path)
22
+ print(f"Saved page {i+1} as {image_path} (size: {image.size})")
23
+
24
+ print(f"Converted {len(images)} pages to PNG images")
25
+
26
+
27
+ if __name__ == "__main__":
28
+ if len(sys.argv) != 3:
29
+ print("Usage: convert_pdf_to_images.py [input pdf] [output directory]")
30
+ sys.exit(1)
31
+ pdf_path = sys.argv[1]
32
+ output_directory = sys.argv[2]
33
+ convert(pdf_path, output_directory)
@@ -0,0 +1,37 @@
1
+ import json
2
+ import sys
3
+
4
+ from PIL import Image, ImageDraw
5
+
6
+
7
+
8
+
9
+ def create_validation_image(page_number, fields_json_path, input_path, output_path):
10
+ with open(fields_json_path, 'r') as f:
11
+ data = json.load(f)
12
+
13
+ img = Image.open(input_path)
14
+ draw = ImageDraw.Draw(img)
15
+ num_boxes = 0
16
+
17
+ for field in data["form_fields"]:
18
+ if field["page_number"] == page_number:
19
+ entry_box = field['entry_bounding_box']
20
+ label_box = field['label_bounding_box']
21
+ draw.rectangle(entry_box, outline='red', width=2)
22
+ draw.rectangle(label_box, outline='blue', width=2)
23
+ num_boxes += 2
24
+
25
+ img.save(output_path)
26
+ print(f"Created validation image at {output_path} with {num_boxes} bounding boxes")
27
+
28
+
29
+ if __name__ == "__main__":
30
+ if len(sys.argv) != 5:
31
+ print("Usage: create_validation_image.py [page number] [fields.json file] [input image path] [output image path]")
32
+ sys.exit(1)
33
+ page_number = int(sys.argv[1])
34
+ fields_json_path = sys.argv[2]
35
+ input_image_path = sys.argv[3]
36
+ output_image_path = sys.argv[4]
37
+ create_validation_image(page_number, fields_json_path, input_image_path, output_image_path)
@@ -0,0 +1,122 @@
1
+ import json
2
+ import sys
3
+
4
+ from pypdf import PdfReader
5
+
6
+
7
+
8
+
9
+ def get_full_annotation_field_id(annotation):
10
+ components = []
11
+ while annotation:
12
+ field_name = annotation.get('/T')
13
+ if field_name:
14
+ components.append(field_name)
15
+ annotation = annotation.get('/Parent')
16
+ return ".".join(reversed(components)) if components else None
17
+
18
+
19
+ def make_field_dict(field, field_id):
20
+ field_dict = {"field_id": field_id}
21
+ ft = field.get('/FT')
22
+ if ft == "/Tx":
23
+ field_dict["type"] = "text"
24
+ elif ft == "/Btn":
25
+ field_dict["type"] = "checkbox"
26
+ states = field.get("/_States_", [])
27
+ if len(states) == 2:
28
+ if "/Off" in states:
29
+ field_dict["checked_value"] = states[0] if states[0] != "/Off" else states[1]
30
+ field_dict["unchecked_value"] = "/Off"
31
+ else:
32
+ print(f"Unexpected state values for checkbox `${field_id}`. Its checked and unchecked values may not be correct; if you're trying to check it, visually verify the results.")
33
+ field_dict["checked_value"] = states[0]
34
+ field_dict["unchecked_value"] = states[1]
35
+ elif ft == "/Ch":
36
+ field_dict["type"] = "choice"
37
+ states = field.get("/_States_", [])
38
+ field_dict["choice_options"] = [{
39
+ "value": state[0],
40
+ "text": state[1],
41
+ } for state in states]
42
+ else:
43
+ field_dict["type"] = f"unknown ({ft})"
44
+ return field_dict
45
+
46
+
47
+ def get_field_info(reader: PdfReader):
48
+ fields = reader.get_fields()
49
+
50
+ field_info_by_id = {}
51
+ possible_radio_names = set()
52
+
53
+ for field_id, field in fields.items():
54
+ if field.get("/Kids"):
55
+ if field.get("/FT") == "/Btn":
56
+ possible_radio_names.add(field_id)
57
+ continue
58
+ field_info_by_id[field_id] = make_field_dict(field, field_id)
59
+
60
+
61
+ radio_fields_by_id = {}
62
+
63
+ for page_index, page in enumerate(reader.pages):
64
+ annotations = page.get('/Annots', [])
65
+ for ann in annotations:
66
+ field_id = get_full_annotation_field_id(ann)
67
+ if field_id in field_info_by_id:
68
+ field_info_by_id[field_id]["page"] = page_index + 1
69
+ field_info_by_id[field_id]["rect"] = ann.get('/Rect')
70
+ elif field_id in possible_radio_names:
71
+ try:
72
+ on_values = [v for v in ann["/AP"]["/N"] if v != "/Off"]
73
+ except KeyError:
74
+ continue
75
+ if len(on_values) == 1:
76
+ rect = ann.get("/Rect")
77
+ if field_id not in radio_fields_by_id:
78
+ radio_fields_by_id[field_id] = {
79
+ "field_id": field_id,
80
+ "type": "radio_group",
81
+ "page": page_index + 1,
82
+ "radio_options": [],
83
+ }
84
+ radio_fields_by_id[field_id]["radio_options"].append({
85
+ "value": on_values[0],
86
+ "rect": rect,
87
+ })
88
+
89
+ fields_with_location = []
90
+ for field_info in field_info_by_id.values():
91
+ if "page" in field_info:
92
+ fields_with_location.append(field_info)
93
+ else:
94
+ print(f"Unable to determine location for field id: {field_info.get('field_id')}, ignoring")
95
+
96
+ def sort_key(f):
97
+ if "radio_options" in f:
98
+ rect = f["radio_options"][0]["rect"] or [0, 0, 0, 0]
99
+ else:
100
+ rect = f.get("rect") or [0, 0, 0, 0]
101
+ adjusted_position = [-rect[1], rect[0]]
102
+ return [f.get("page"), adjusted_position]
103
+
104
+ sorted_fields = fields_with_location + list(radio_fields_by_id.values())
105
+ sorted_fields.sort(key=sort_key)
106
+
107
+ return sorted_fields
108
+
109
+
110
+ def write_field_info(pdf_path: str, json_output_path: str):
111
+ reader = PdfReader(pdf_path)
112
+ field_info = get_field_info(reader)
113
+ with open(json_output_path, "w") as f:
114
+ json.dump(field_info, f, indent=2)
115
+ print(f"Wrote {len(field_info)} fields to {json_output_path}")
116
+
117
+
118
+ if __name__ == "__main__":
119
+ if len(sys.argv) != 3:
120
+ print("Usage: extract_form_field_info.py [input pdf] [output json]")
121
+ sys.exit(1)
122
+ write_field_info(sys.argv[1], sys.argv[2])
@@ -0,0 +1,115 @@
1
+ """
2
+ Extract form structure from a non-fillable PDF.
3
+
4
+ This script analyzes the PDF to find:
5
+ - Text labels with their exact coordinates
6
+ - Horizontal lines (row boundaries)
7
+ - Checkboxes (small rectangles)
8
+
9
+ Output: A JSON file with the form structure that can be used to generate
10
+ accurate field coordinates for filling.
11
+
12
+ Usage: python extract_form_structure.py <input.pdf> <output.json>
13
+ """
14
+
15
+ import json
16
+ import sys
17
+ import pdfplumber
18
+
19
+
20
+ def extract_form_structure(pdf_path):
21
+ structure = {
22
+ "pages": [],
23
+ "labels": [],
24
+ "lines": [],
25
+ "checkboxes": [],
26
+ "row_boundaries": []
27
+ }
28
+
29
+ with pdfplumber.open(pdf_path) as pdf:
30
+ for page_num, page in enumerate(pdf.pages, 1):
31
+ structure["pages"].append({
32
+ "page_number": page_num,
33
+ "width": float(page.width),
34
+ "height": float(page.height)
35
+ })
36
+
37
+ words = page.extract_words()
38
+ for word in words:
39
+ structure["labels"].append({
40
+ "page": page_num,
41
+ "text": word["text"],
42
+ "x0": round(float(word["x0"]), 1),
43
+ "top": round(float(word["top"]), 1),
44
+ "x1": round(float(word["x1"]), 1),
45
+ "bottom": round(float(word["bottom"]), 1)
46
+ })
47
+
48
+ for line in page.lines:
49
+ if abs(float(line["x1"]) - float(line["x0"])) > page.width * 0.5:
50
+ structure["lines"].append({
51
+ "page": page_num,
52
+ "y": round(float(line["top"]), 1),
53
+ "x0": round(float(line["x0"]), 1),
54
+ "x1": round(float(line["x1"]), 1)
55
+ })
56
+
57
+ for rect in page.rects:
58
+ width = float(rect["x1"]) - float(rect["x0"])
59
+ height = float(rect["bottom"]) - float(rect["top"])
60
+ if 5 <= width <= 15 and 5 <= height <= 15 and abs(width - height) < 2:
61
+ structure["checkboxes"].append({
62
+ "page": page_num,
63
+ "x0": round(float(rect["x0"]), 1),
64
+ "top": round(float(rect["top"]), 1),
65
+ "x1": round(float(rect["x1"]), 1),
66
+ "bottom": round(float(rect["bottom"]), 1),
67
+ "center_x": round((float(rect["x0"]) + float(rect["x1"])) / 2, 1),
68
+ "center_y": round((float(rect["top"]) + float(rect["bottom"])) / 2, 1)
69
+ })
70
+
71
+ lines_by_page = {}
72
+ for line in structure["lines"]:
73
+ page = line["page"]
74
+ if page not in lines_by_page:
75
+ lines_by_page[page] = []
76
+ lines_by_page[page].append(line["y"])
77
+
78
+ for page, y_coords in lines_by_page.items():
79
+ y_coords = sorted(set(y_coords))
80
+ for i in range(len(y_coords) - 1):
81
+ structure["row_boundaries"].append({
82
+ "page": page,
83
+ "row_top": y_coords[i],
84
+ "row_bottom": y_coords[i + 1],
85
+ "row_height": round(y_coords[i + 1] - y_coords[i], 1)
86
+ })
87
+
88
+ return structure
89
+
90
+
91
+ def main():
92
+ if len(sys.argv) != 3:
93
+ print("Usage: extract_form_structure.py <input.pdf> <output.json>")
94
+ sys.exit(1)
95
+
96
+ pdf_path = sys.argv[1]
97
+ output_path = sys.argv[2]
98
+
99
+ print(f"Extracting structure from {pdf_path}...")
100
+ structure = extract_form_structure(pdf_path)
101
+
102
+ with open(output_path, "w") as f:
103
+ json.dump(structure, f, indent=2)
104
+
105
+ print(f"Found:")
106
+ print(f" - {len(structure['pages'])} pages")
107
+ print(f" - {len(structure['labels'])} text labels")
108
+ print(f" - {len(structure['lines'])} horizontal lines")
109
+ print(f" - {len(structure['checkboxes'])} checkboxes")
110
+ print(f" - {len(structure['row_boundaries'])} row boundaries")
111
+ print(f"Saved to {output_path}")
112
+
113
+
114
+ if __name__ == "__main__":
115
+ main()
@@ -0,0 +1,98 @@
1
+ import json
2
+ import sys
3
+
4
+ from pypdf import PdfReader, PdfWriter
5
+
6
+ from extract_form_field_info import get_field_info
7
+
8
+
9
+
10
+
11
+ def fill_pdf_fields(input_pdf_path: str, fields_json_path: str, output_pdf_path: str):
12
+ with open(fields_json_path) as f:
13
+ fields = json.load(f)
14
+ fields_by_page = {}
15
+ for field in fields:
16
+ if "value" in field:
17
+ field_id = field["field_id"]
18
+ page = field["page"]
19
+ if page not in fields_by_page:
20
+ fields_by_page[page] = {}
21
+ fields_by_page[page][field_id] = field["value"]
22
+
23
+ reader = PdfReader(input_pdf_path)
24
+
25
+ has_error = False
26
+ field_info = get_field_info(reader)
27
+ fields_by_ids = {f["field_id"]: f for f in field_info}
28
+ for field in fields:
29
+ existing_field = fields_by_ids.get(field["field_id"])
30
+ if not existing_field:
31
+ has_error = True
32
+ print(f"ERROR: `{field['field_id']}` is not a valid field ID")
33
+ elif field["page"] != existing_field["page"]:
34
+ has_error = True
35
+ print(f"ERROR: Incorrect page number for `{field['field_id']}` (got {field['page']}, expected {existing_field['page']})")
36
+ else:
37
+ if "value" in field:
38
+ err = validation_error_for_field_value(existing_field, field["value"])
39
+ if err:
40
+ print(err)
41
+ has_error = True
42
+ if has_error:
43
+ sys.exit(1)
44
+
45
+ writer = PdfWriter(clone_from=reader)
46
+ for page, field_values in fields_by_page.items():
47
+ writer.update_page_form_field_values(writer.pages[page - 1], field_values, auto_regenerate=False)
48
+
49
+ writer.set_need_appearances_writer(True)
50
+
51
+ with open(output_pdf_path, "wb") as f:
52
+ writer.write(f)
53
+
54
+
55
+ def validation_error_for_field_value(field_info, field_value):
56
+ field_type = field_info["type"]
57
+ field_id = field_info["field_id"]
58
+ if field_type == "checkbox":
59
+ checked_val = field_info["checked_value"]
60
+ unchecked_val = field_info["unchecked_value"]
61
+ if field_value != checked_val and field_value != unchecked_val:
62
+ return f'ERROR: Invalid value "{field_value}" for checkbox field "{field_id}". The checked value is "{checked_val}" and the unchecked value is "{unchecked_val}"'
63
+ elif field_type == "radio_group":
64
+ option_values = [opt["value"] for opt in field_info["radio_options"]]
65
+ if field_value not in option_values:
66
+ return f'ERROR: Invalid value "{field_value}" for radio group field "{field_id}". Valid values are: {option_values}'
67
+ elif field_type == "choice":
68
+ choice_values = [opt["value"] for opt in field_info["choice_options"]]
69
+ if field_value not in choice_values:
70
+ return f'ERROR: Invalid value "{field_value}" for choice field "{field_id}". Valid values are: {choice_values}'
71
+ return None
72
+
73
+
74
+ def monkeypatch_pydpf_method():
75
+ from pypdf.generic import DictionaryObject
76
+ from pypdf.constants import FieldDictionaryAttributes
77
+
78
+ original_get_inherited = DictionaryObject.get_inherited
79
+
80
+ def patched_get_inherited(self, key: str, default = None):
81
+ result = original_get_inherited(self, key, default)
82
+ if key == FieldDictionaryAttributes.Opt:
83
+ if isinstance(result, list) and all(isinstance(v, list) and len(v) == 2 for v in result):
84
+ result = [r[0] for r in result]
85
+ return result
86
+
87
+ DictionaryObject.get_inherited = patched_get_inherited
88
+
89
+
90
+ if __name__ == "__main__":
91
+ if len(sys.argv) != 4:
92
+ print("Usage: fill_fillable_fields.py [input pdf] [field_values.json] [output pdf]")
93
+ sys.exit(1)
94
+ monkeypatch_pydpf_method()
95
+ input_pdf = sys.argv[1]
96
+ fields_json = sys.argv[2]
97
+ output_pdf = sys.argv[3]
98
+ fill_pdf_fields(input_pdf, fields_json, output_pdf)
@@ -0,0 +1,107 @@
1
+ import json
2
+ import sys
3
+
4
+ from pypdf import PdfReader, PdfWriter
5
+ from pypdf.annotations import FreeText
6
+
7
+
8
+
9
+
10
+ def transform_from_image_coords(bbox, image_width, image_height, pdf_width, pdf_height):
11
+ x_scale = pdf_width / image_width
12
+ y_scale = pdf_height / image_height
13
+
14
+ left = bbox[0] * x_scale
15
+ right = bbox[2] * x_scale
16
+
17
+ top = pdf_height - (bbox[1] * y_scale)
18
+ bottom = pdf_height - (bbox[3] * y_scale)
19
+
20
+ return left, bottom, right, top
21
+
22
+
23
+ def transform_from_pdf_coords(bbox, pdf_height):
24
+ left = bbox[0]
25
+ right = bbox[2]
26
+
27
+ pypdf_top = pdf_height - bbox[1]
28
+ pypdf_bottom = pdf_height - bbox[3]
29
+
30
+ return left, pypdf_bottom, right, pypdf_top
31
+
32
+
33
+ def fill_pdf_form(input_pdf_path, fields_json_path, output_pdf_path):
34
+
35
+ with open(fields_json_path, "r") as f:
36
+ fields_data = json.load(f)
37
+
38
+ reader = PdfReader(input_pdf_path)
39
+ writer = PdfWriter()
40
+
41
+ writer.append(reader)
42
+
43
+ pdf_dimensions = {}
44
+ for i, page in enumerate(reader.pages):
45
+ mediabox = page.mediabox
46
+ pdf_dimensions[i + 1] = [mediabox.width, mediabox.height]
47
+
48
+ annotations = []
49
+ for field in fields_data["form_fields"]:
50
+ page_num = field["page_number"]
51
+
52
+ page_info = next(p for p in fields_data["pages"] if p["page_number"] == page_num)
53
+ pdf_width, pdf_height = pdf_dimensions[page_num]
54
+
55
+ if "pdf_width" in page_info:
56
+ transformed_entry_box = transform_from_pdf_coords(
57
+ field["entry_bounding_box"],
58
+ float(pdf_height)
59
+ )
60
+ else:
61
+ image_width = page_info["image_width"]
62
+ image_height = page_info["image_height"]
63
+ transformed_entry_box = transform_from_image_coords(
64
+ field["entry_bounding_box"],
65
+ image_width, image_height,
66
+ float(pdf_width), float(pdf_height)
67
+ )
68
+
69
+ if "entry_text" not in field or "text" not in field["entry_text"]:
70
+ continue
71
+ entry_text = field["entry_text"]
72
+ text = entry_text["text"]
73
+ if not text:
74
+ continue
75
+
76
+ font_name = entry_text.get("font", "Arial")
77
+ font_size = str(entry_text.get("font_size", 14)) + "pt"
78
+ font_color = entry_text.get("font_color", "000000")
79
+
80
+ annotation = FreeText(
81
+ text=text,
82
+ rect=transformed_entry_box,
83
+ font=font_name,
84
+ font_size=font_size,
85
+ font_color=font_color,
86
+ border_color=None,
87
+ background_color=None,
88
+ )
89
+ annotations.append(annotation)
90
+ writer.add_annotation(page_number=page_num - 1, annotation=annotation)
91
+
92
+ with open(output_pdf_path, "wb") as output:
93
+ writer.write(output)
94
+
95
+ print(f"Successfully filled PDF form and saved to {output_pdf_path}")
96
+ print(f"Added {len(annotations)} text annotations")
97
+
98
+
99
+ if __name__ == "__main__":
100
+ if len(sys.argv) != 4:
101
+ print("Usage: fill_pdf_form_with_annotations.py [input pdf] [fields.json] [output pdf]")
102
+ sys.exit(1)
103
+ input_pdf = sys.argv[1]
104
+ fields_json = sys.argv[2]
105
+ output_pdf = sys.argv[3]
106
+
107
+ fill_pdf_form(input_pdf, fields_json, output_pdf)
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Mercury Permission Guard — pi extension
3
+ *
4
+ * Prevents the agent from bypassing RBAC by calling extension CLIs
5
+ * directly in bash. Forces all extension CLI calls through `mrctl`,
6
+ * which checks permissions via the Mercury API.
7
+ *
8
+ * Environment variables:
9
+ * MERCURY_EXT_CLIS — comma-separated list of extension CLI names
10
+ * e.g. "pinchtab,napkin,charts,pdf"
11
+ *
12
+ * Without this extension, the agent can call `pinchtab search foo`
13
+ * directly in bash, bypassing the permission check that `mrctl pinchtab
14
+ * search foo` would enforce.
15
+ *
16
+ * Behavior: intercepts bash tool calls that invoke an extension CLI
17
+ * directly and blocks them with a message to use `mrctl` instead.
18
+ */
19
+
20
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
21
+
22
+ export default function (pi: ExtensionAPI) {
23
+ const extClisEnv = process.env.MERCURY_EXT_CLIS;
24
+ if (!extClisEnv) return;
25
+
26
+ const extClis = extClisEnv
27
+ .split(",")
28
+ .map((s) => s.trim())
29
+ .filter(Boolean);
30
+
31
+ if (extClis.length === 0) return;
32
+
33
+ // Match CLI name as the first command word, or after shell operators
34
+ // Covers: `pinchtab args`, `cd /tmp && pinchtab args`, `pinchtab &`
35
+ const cliPatterns = extClis.map((name) => ({
36
+ name,
37
+ pattern: new RegExp(
38
+ `(?:^|&&|\\|\\||;|\\|)\\s*${escapeRegex(name)}(?:\\s|$|&)`,
39
+ ),
40
+ }));
41
+
42
+ pi.on("tool_call", async (event) => {
43
+ if (event.toolName !== "bash") return undefined;
44
+
45
+ const command = (event.input.command as string).trim();
46
+
47
+ // Don't block if already going through mrctl
48
+ if (/(?:^|&&|\|\||;|\|)\s*mrctl\s/.test(command)) return undefined;
49
+
50
+ for (const { name, pattern } of cliPatterns) {
51
+ if (pattern.test(command)) {
52
+ return {
53
+ block: true,
54
+ reason: `Direct "${name}" calls are not allowed. Use "mrctl ${name} ..." instead, which enforces permissions.`,
55
+ };
56
+ }
57
+ }
58
+
59
+ return undefined;
60
+ });
61
+ }
62
+
63
+ function escapeRegex(s: string): string {
64
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
65
+ }