@agentprojectcontext/apx 1.14.0 → 1.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentprojectcontext/apx",
3
- "version": "1.14.0",
3
+ "version": "1.14.1",
4
4
  "description": "APX — unified CLI + daemon for the Agent Project Context (APC) standard.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -113,6 +113,40 @@ export async function sendVoice(token, chatId, audio, { caption, duration } = {}
113
113
  * @param {string} [opts.title]
114
114
  * @param {string} [opts.performer]
115
115
  */
116
+ /**
117
+ * Send any file as a Telegram document (PDF, zip, txt, etc).
118
+ * @param {string} token
119
+ * @param {string|number} chatId
120
+ * @param {string|Buffer} document Path or Buffer of document data
121
+ * @param {object} [opts]
122
+ * @param {string} [opts.caption]
123
+ * @param {string} [opts.filename] override filename for Buffer input
124
+ * @param {string} [opts.mime_type]
125
+ */
126
+ export async function sendDocument(token, chatId, document, { caption, filename, mime_type } = {}) {
127
+ const url = `${API_BASE}/bot${token}/sendDocument`;
128
+ const form = new FormData();
129
+ form.append("chat_id", String(chatId));
130
+ if (caption) form.append("caption", caption);
131
+
132
+ // URL string → let Telegram fetch it
133
+ if (typeof document === "string" && /^https?:\/\//.test(document)) {
134
+ form.append("document", document);
135
+ } else {
136
+ const buf = Buffer.isBuffer(document) ? document : fs.readFileSync(document);
137
+ const name =
138
+ filename ||
139
+ (typeof document === "string" ? path.basename(document) : "document.bin");
140
+ const blob = new Blob([buf], { type: mime_type || "application/octet-stream" });
141
+ form.append("document", blob, name);
142
+ }
143
+
144
+ const res = await fetch(url, { method: "POST", body: form });
145
+ const json = await res.json();
146
+ if (!json.ok) throw new Error(`sendDocument failed: ${json.description || res.status}`);
147
+ return json.result;
148
+ }
149
+
116
150
  export async function sendAudio(token, chatId, audio, { caption, title, performer } = {}) {
117
151
  const url = `${API_BASE}/bot${token}/sendAudio`;
118
152
  const form = new FormData();
@@ -724,6 +758,14 @@ class ChannelPoller {
724
758
  return sendVoice(token, target, audio, { caption, duration });
725
759
  }
726
760
 
761
+ /** Send a document (PDF, zip, etc) via this channel */
762
+ async _sendDocument({ chat_id, document, caption, filename, mime_type }) {
763
+ const token = resolveBotToken(this.channel);
764
+ if (!token) throw new Error(`channel ${this.channel.name}: no bot_token`);
765
+ const target = chat_id || resolveChatId(this.channel);
766
+ return sendDocument(token, target, document, { caption, filename, mime_type });
767
+ }
768
+
727
769
  /** Send an audio file via this channel */
728
770
  async _sendAudio({ chat_id, audio, caption, title, performer }) {
729
771
  const token = resolveBotToken(this.channel);
@@ -848,6 +890,29 @@ export default {
848
890
  return result;
849
891
  },
850
892
 
893
+ /**
894
+ * Send a document (PDF, zip, txt, generated reports, etc).
895
+ * document: local file path, Buffer, or public https URL.
896
+ */
897
+ async sendDocument({ channel: channelName, chat_id, document, caption, filename, mime_type, author = "apx" }) {
898
+ const p =
899
+ (channelName && pollers.find((pp) => pp.channel.name === channelName)) ||
900
+ pollers.find((pp) => resolveBotToken(pp.channel)) ||
901
+ null;
902
+ if (!p) throw new Error("no telegram channel available");
903
+ const result = await p._sendDocument({ chat_id, document, caption, filename, mime_type });
904
+ appendGlobalMessage({
905
+ channel: "telegram",
906
+ direction: "out",
907
+ type: "document",
908
+ actor_id: author,
909
+ author,
910
+ body: caption || `[document${filename ? " " + filename : ""}]`,
911
+ meta: { chat_id: chat_id || resolveChatId(p.channel), tg_channel: p.channel.name, filename, mime_type },
912
+ });
913
+ return result;
914
+ },
915
+
851
916
  /**
852
917
  * Send an audio file (MP3/M4A — shown in music player).
853
918
  * audio: local file path or Buffer
@@ -1,12 +1,41 @@
1
1
  import { confirmedProperty } from "../helpers.js";
2
2
 
3
+ function decodeBase64(b64) {
4
+ const clean = String(b64).replace(/^data:[a-z/-]+;base64,/, "");
5
+ return Buffer.from(clean, "base64");
6
+ }
7
+
3
8
  function decodePhoto({ photo_base64, photo_path, photo_url }) {
4
- if (photo_url) return String(photo_url);
5
- if (photo_path) return String(photo_path);
6
- if (photo_base64) {
7
- // Strip "data:image/...;base64," prefix if present
8
- const clean = String(photo_base64).replace(/^data:image\/[a-z]+;base64,/, "");
9
- return Buffer.from(clean, "base64");
9
+ if (photo_url) return String(photo_url);
10
+ if (photo_path) return String(photo_path);
11
+ if (photo_base64) return decodeBase64(photo_base64);
12
+ return null;
13
+ }
14
+
15
+ function decodeDocument({ document_base64, document_path, document_url }) {
16
+ if (document_url) return String(document_url);
17
+ if (document_path) return String(document_path);
18
+ if (document_base64) return decodeBase64(document_base64);
19
+ return null;
20
+ }
21
+
22
+ /**
23
+ * Detect the common LLM mistake of embedding raw base64 in the text field
24
+ * (often wrapped in markdown image syntax). Telegram does NOT render those —
25
+ * it just shows the literal characters. Fail fast with a clear hint.
26
+ */
27
+ function detectBase64InText(text) {
28
+ if (!text || typeof text !== "string") return null;
29
+ if (/!\[[^\]]*\]\(data:image\/[a-z]+;base64,/i.test(text)) {
30
+ return "markdown image with data URI";
31
+ }
32
+ if (/data:image\/[a-z]+;base64,/i.test(text)) {
33
+ return "data URI";
34
+ }
35
+ // Long runs of base64-looking chars (>500 contiguous) — almost certainly a
36
+ // dumped image
37
+ if (/[A-Za-z0-9+/=]{500,}/.test(text)) {
38
+ return "raw base64 blob (>500 chars)";
10
39
  }
11
40
  return null;
12
41
  }
@@ -18,28 +47,61 @@ export default {
18
47
  function: {
19
48
  name: "send_telegram",
20
49
  description:
21
- "Send a Telegram message via the daemon's Telegram plugin. Text only by default; pass photo_base64 (from browser_screenshot) / photo_path / photo_url to attach an image the text becomes the caption. Use this AFTER a browser_screenshot when the user asks for a screenshot or visual reply.",
50
+ "Send a Telegram message via the daemon's Telegram plugin. STRICT rule: to attach an image use the photo_* params; to attach a file use the document_* params — NEVER paste base64 or a data URI inside `text` (Telegram does not render markdown images / data URIs, the recipient sees the literal base64). After browser_screenshot, pass its `base64` field directly to photo_base64 here (not in text). The text field becomes the caption when media is attached.",
22
51
  parameters: {
23
52
  type: "object",
24
53
  properties: {
25
- channel: { type: "string", description: "telegram channel name; omit for default" },
26
- chat_id: { type: "string", description: "destination chat id; omit to use channel default" },
27
- text: { type: "string", description: "message body (becomes the photo caption when a photo_* arg is passed)" },
28
- photo_base64: { type: "string", description: "raw base64 PNG/JPG (or 'data:image/...;base64,...' data URI). Pass the `base64` field returned by browser_screenshot here." },
29
- photo_path: { type: "string", description: "absolute filesystem path to an image file" },
30
- photo_url: { type: "string", description: "public https URL of an image" },
31
- confirmed: confirmedProperty("true only after explicit user confirmation for this exact outbound message"),
54
+ channel: { type: "string", description: "telegram channel name; omit for default" },
55
+ chat_id: { type: "string", description: "destination chat id; omit to use channel default" },
56
+ text: {
57
+ type: "string",
58
+ description:
59
+ "Plain-text body (becomes the caption when a photo_* or document_* is attached). MUST NOT contain base64, data URIs, or markdown image syntax like ![](data:...) — use photo_base64 for that.",
60
+ },
61
+ // --- image attachments ---
62
+ photo_base64: {
63
+ type: "string",
64
+ description:
65
+ "raw base64 PNG/JPG (or 'data:image/...;base64,...'). Pass the `base64` field from browser_screenshot directly here.",
66
+ },
67
+ photo_path: { type: "string", description: "absolute filesystem path to an image file" },
68
+ photo_url: { type: "string", description: "public https URL of an image" },
69
+ // --- document attachments (PDF, txt, zip, etc) ---
70
+ document_base64: { type: "string", description: "raw base64 of a file" },
71
+ document_path: { type: "string", description: "absolute filesystem path to any file (PDF, txt, zip, .csv...)" },
72
+ document_url: { type: "string", description: "public https URL of a file" },
73
+ filename: { type: "string", description: "filename to show in Telegram when sending a document (Buffer-style input)" },
74
+ mime_type: { type: "string", description: "optional MIME type for the document" },
75
+ confirmed: confirmedProperty("true only after explicit user confirmation for this exact outbound message"),
32
76
  },
33
77
  required: ["text"],
34
78
  },
35
79
  },
36
80
  },
37
- makeHandler: ({ plugins, requirePermission }) => async ({ channel, chat_id, text, photo_base64, photo_path, photo_url, confirmed = false }) => {
81
+ makeHandler: ({ plugins, requirePermission }) => async (args = {}) => {
82
+ const {
83
+ channel, chat_id, text,
84
+ photo_base64, photo_path, photo_url,
85
+ document_base64, document_path, document_url,
86
+ filename, mime_type,
87
+ confirmed = false,
88
+ } = args;
89
+
38
90
  requirePermission("send_telegram", { dangerous: true, confirmed });
39
91
  if (!plugins) throw new Error("plugins unavailable");
40
92
  const telegram = plugins.get("telegram");
41
93
  if (!telegram) throw new Error("telegram plugin not loaded");
42
94
 
95
+ // Defensive: catch the classic mistake of dumping base64 into text.
96
+ const bad = detectBase64InText(text);
97
+ if (bad) {
98
+ throw new Error(
99
+ `send_telegram: refusing to send — text appears to contain ${bad}. ` +
100
+ `Telegram does not render data URIs or markdown images. ` +
101
+ `Pass the base64 in photo_base64 (NOT text). Set text to a short caption like "Captura de localhost:8801".`
102
+ );
103
+ }
104
+
43
105
  const photo = decodePhoto({ photo_base64, photo_path, photo_url });
44
106
  if (photo) {
45
107
  const result = await telegram.sendPhoto({
@@ -48,6 +110,14 @@ export default {
48
110
  return { ok: true, kind: "photo", message_id: result.message_id };
49
111
  }
50
112
 
113
+ const document = decodeDocument({ document_base64, document_path, document_url });
114
+ if (document) {
115
+ const result = await telegram.sendDocument({
116
+ channel, chat_id, document, caption: text, filename, mime_type, author: "apx",
117
+ });
118
+ return { ok: true, kind: "document", message_id: result.message_id, filename };
119
+ }
120
+
51
121
  const result = await telegram.send({ channel, chat_id, text, author: "apx" });
52
122
  return { ok: true, kind: "text", message_id: result.message_id };
53
123
  },
@@ -65,7 +65,8 @@ HARD RULES (do not deviate):
65
65
  18. **NO EMPTY RESPONSES**: Never respond with only text when you have tools available and the user is asking you to DO something. Call the tool FIRST, then explain. Never say "I'll do X" without immediately calling the tool. Empty acknowledgments ("ok", "entendido", "dame un minuto", "voy", "checking", "stand by") without a tool call are invalid responses — they will be re-prompted and waste a turn.
66
66
  19. **CWD RULE**: When the channel context includes a "CWD: <path>" line, that is the user's current working directory. References to "este directorio", "este proyecto", "esta carpeta", "acá", "aquí", "this directory", "this project", "current dir/folder" all mean that exact CWD path. Use it as the path argument directly — DO NOT ask the user "what's the path?" when CWD is already given. Example: if user says "agregá este proyecto a la lista", call add_project({path: <CWD>}) immediately.
67
67
  20. **NO MANUAL SCAFFOLDING**: To register or scaffold a project, ALWAYS use add_project — it auto-creates AGENTS.md and .apc/project.json when missing (one call, atomic). NEVER write AGENTS.md, .apc/project.json, or any APC scaffold file by hand via run_shell / write_file / shell pipes. The schema must come from the official initApf scaffold, not improvised. If add_project errors, report the error to the user — don't try to work around it with shell hacks. Same for any other APC-managed file (.apc/agents/*, .apc/skills/*, etc.) — use the dedicated tool, never raw filesystem writes.
68
- 21. **SKILLS — ON DEMAND**: The "# Available skills" section below lists every skill available to you (slug + description, NO body). When the user asks about specific APX/APC commands, project structure, agent runtimes, or anything where exact syntax or detailed behavior matches a skill description (in ANY language — match semantically, not by keyword), call load_skill({slug}) to fetch the full markdown body. If a CWD is in the contextNote, pass it as project_path so project-scoped skills resolve. If the user explicitly asks "what skills do you have?", you can either read the catalog below directly OR call list_skills to get a fresh enumeration. Do NOT load skills for trivial / unrelated questions — that wastes tokens. Don't guess CLI syntax when a skill can tell you; load it.`;
68
+ 21. **SKILLS — ON DEMAND**: The "# Available skills" section below lists every skill available to you (slug + description, NO body). When the user asks about specific APX/APC commands, project structure, agent runtimes, or anything where exact syntax or detailed behavior matches a skill description (in ANY language — match semantically, not by keyword), call load_skill({slug}) to fetch the full markdown body. If a CWD is in the contextNote, pass it as project_path so project-scoped skills resolve. If the user explicitly asks "what skills do you have?", you can either read the catalog below directly OR call list_skills to get a fresh enumeration. Do NOT load skills for trivial / unrelated questions — that wastes tokens. Don't guess CLI syntax when a skill can tell you; load it.
69
+ 22. **NEVER PASTE BASE64 OR DATA URIs IN MESSAGE TEXT**: When you need to send an image, audio, or file via Telegram (or any channel), you MUST pass it via the dedicated parameter — NEVER embed it in the text field. Concretely: after browser_screenshot returns its base64 field, call send_telegram({text: "<short caption>", photo_base64: "<that base64>"}). Do NOT write text like 'Aquí está: ![screenshot](data:image/png;base64,...)' — Telegram (and most chat clients) do NOT render data URIs or markdown images; the user sees thousands of garbage characters. Same for files: use document_path / document_base64 / document_url, NOT the text field. The text field is exclusively for human-readable prose (and becomes the caption when media is attached). If unsure, save the image to /tmp/screenshot-<ts>.png first (browser_screenshot supports save_to_tmp=true and returns a path field) and pass that path to send_telegram via photo_path — never inline the bytes in text.`;
69
70
 
70
71
  function isShortConfirmation(text) {
71
72
  return /^(yes|y|si|si dale|dale|ok|okay|confirm|confirmed|go|proceed|do it)\b/i
@@ -197,7 +197,7 @@ export async function browser_navigate({ url, launch_options, allow_dangerous }
197
197
  };
198
198
  }
199
199
 
200
- export async function browser_screenshot({ selector, full_page = false, width, height, encoded = false } = {}) {
200
+ export async function browser_screenshot({ selector, full_page = false, width, height, encoded = false, save_path, save_to_tmp = false } = {}) {
201
201
  const page = await ensureBrowser();
202
202
  if (width || height) {
203
203
  await page.setViewport({
@@ -218,12 +218,30 @@ export async function browser_screenshot({ selector, full_page = false, width, h
218
218
  throw new Error(`Screenshot too large: ${Math.round(size / 1024)}KB (max ${Math.round(MAX_SCREENSHOT_BYTES / 1024)}KB)`);
219
219
  }
220
220
 
221
+ // Optional disk write so the caller can pass `path` to e.g. send_telegram
222
+ // instead of shuttling base64 around.
223
+ let writtenPath = null;
224
+ if (save_path || save_to_tmp) {
225
+ const fs = await import("node:fs");
226
+ const path = await import("node:path");
227
+ const os = await import("node:os");
228
+ let target = save_path;
229
+ if (!target) {
230
+ const dir = path.join(os.tmpdir(), "apx-screenshots");
231
+ fs.mkdirSync(dir, { recursive: true });
232
+ target = path.join(dir, `screenshot-${Date.now()}.png`);
233
+ }
234
+ fs.writeFileSync(target, Buffer.from(String(buf), "base64"));
235
+ writtenPath = target;
236
+ }
237
+
221
238
  return {
222
239
  ok: true,
223
240
  url: page.url(),
224
241
  format: "png",
225
242
  bytes: size,
226
243
  base64: buf,
244
+ path: writtenPath,
227
245
  data_uri: encoded ? `data:image/png;base64,${buf}` : undefined,
228
246
  };
229
247
  }
@@ -366,19 +366,21 @@ const TOOL_DEFINITIONS = [
366
366
  {
367
367
  name: "browser_screenshot",
368
368
  category: "browser",
369
- description: "Take a screenshot of the current browser page (or a single element via selector). Returns base64 PNG.",
369
+ description: "Take a screenshot of the current browser page (or an element via selector). Returns { base64, path?, bytes, url }. To send via Telegram, prefer `save_to_tmp: true` and pass the returned `path` to send_telegram({photo_path}); otherwise pass `base64` straight to send_telegram({photo_base64}). NEVER include the base64 in any text field — Telegram does not render it.",
370
370
  endpoint: { method: "POST", path: "/tools/browser/screenshot" },
371
371
  parameters: {
372
372
  type: "object",
373
373
  properties: {
374
- selector: { type: "string", description: "CSS selector of element to capture. Omit to capture full viewport/page." },
375
- full_page: { type: "boolean", default: false },
376
- width: { type: "number", description: "Viewport width (capped at 1920)." },
377
- height: { type: "number", description: "Viewport height (capped at 1080)." },
378
- encoded: { type: "boolean", description: "Also return a data: URI." },
374
+ selector: { type: "string", description: "CSS selector of element to capture. Omit for full viewport/page." },
375
+ full_page: { type: "boolean", default: false },
376
+ width: { type: "number", description: "Viewport width (capped at 1920)." },
377
+ height: { type: "number", description: "Viewport height (capped at 1080)." },
378
+ encoded: { type: "boolean", description: "Also return a data:image/png;base64 URI in response." },
379
+ save_path: { type: "string", description: "Absolute path to write the PNG. Returns it in `path`." },
380
+ save_to_tmp: { type: "boolean", description: "Auto-write to <os.tmpdir>/apx-screenshots/screenshot-<ts>.png. Returns the path." },
379
381
  },
380
382
  },
381
- examples: [{}, { selector: "#hero" }],
383
+ examples: [{}, { selector: "#hero" }, { save_to_tmp: true }],
382
384
  },
383
385
  {
384
386
  name: "browser_click",