@runappsai/agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -2
  3. package/dist/agent-core.umd.js +266 -0
  4. package/dist/agent.d.ts +222 -0
  5. package/dist/agent.js +1331 -0
  6. package/dist/agent.umd.js +732 -0
  7. package/dist/browser.d.ts +2 -0
  8. package/dist/browser.js +4 -0
  9. package/dist/chat-theme.d.ts +24 -0
  10. package/dist/chat-theme.js +101 -0
  11. package/dist/chat.d.ts +271 -0
  12. package/dist/chat.js +4097 -0
  13. package/dist/compaction.d.ts +48 -0
  14. package/dist/compaction.js +208 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.js +88 -0
  17. package/dist/context.d.ts +44 -0
  18. package/dist/context.js +177 -0
  19. package/dist/debug-panel.d.ts +40 -0
  20. package/dist/debug-panel.js +262 -0
  21. package/dist/dialogs.d.ts +7 -0
  22. package/dist/dialogs.js +231 -0
  23. package/dist/directory-fs.d.ts +5 -0
  24. package/dist/directory-fs.js +118 -0
  25. package/dist/dom.d.ts +83 -0
  26. package/dist/dom.js +163 -0
  27. package/dist/edit.d.ts +22 -0
  28. package/dist/edit.js +133 -0
  29. package/dist/file-guard.d.ts +46 -0
  30. package/dist/file-guard.js +153 -0
  31. package/dist/file-tools.d.ts +16 -0
  32. package/dist/file-tools.js +339 -0
  33. package/dist/files-panel.d.ts +60 -0
  34. package/dist/files-panel.js +613 -0
  35. package/dist/index.cjs +4848 -0
  36. package/dist/index.d.ts +37 -0
  37. package/dist/index.js +44 -0
  38. package/dist/json-schema.d.ts +3 -0
  39. package/dist/json-schema.js +141 -0
  40. package/dist/llm.d.ts +95 -0
  41. package/dist/llm.js +5 -0
  42. package/dist/markdown.d.ts +4 -0
  43. package/dist/markdown.js +265 -0
  44. package/dist/mcp.d.ts +82 -0
  45. package/dist/mcp.js +325 -0
  46. package/dist/node.cjs +402 -0
  47. package/dist/node.d.ts +78 -0
  48. package/dist/node.js +432 -0
  49. package/dist/pdf.d.ts +52 -0
  50. package/dist/pdf.js +77 -0
  51. package/dist/provider.d.ts +135 -0
  52. package/dist/provider.js +181 -0
  53. package/dist/sandbox.d.ts +33 -0
  54. package/dist/sandbox.js +219 -0
  55. package/dist/select.d.ts +30 -0
  56. package/dist/select.js +185 -0
  57. package/dist/skill-zips.d.ts +28 -0
  58. package/dist/skill-zips.js +123 -0
  59. package/dist/skills.d.ts +20 -0
  60. package/dist/skills.js +111 -0
  61. package/dist/templates.d.ts +24 -0
  62. package/dist/templates.js +136 -0
  63. package/dist/tool.d.ts +28 -0
  64. package/dist/tool.js +102 -0
  65. package/dist/types.d.ts +571 -0
  66. package/dist/types.js +7 -0
  67. package/dist/ui.cjs +6246 -0
  68. package/dist/ui.d.ts +6 -0
  69. package/dist/ui.js +11 -0
  70. package/dist/vlist.d.ts +80 -0
  71. package/dist/vlist.js +277 -0
  72. package/dist/workspace.d.ts +343 -0
  73. package/dist/workspace.js +1203 -0
  74. package/dist/zip.d.ts +26 -0
  75. package/dist/zip.js +204 -0
  76. package/docs/agent.md +228 -0
  77. package/docs/chat-ui.md +307 -0
  78. package/docs/node.md +135 -0
  79. package/docs/providers.md +176 -0
  80. package/docs/reference.md +143 -0
  81. package/docs/skills.md +131 -0
  82. package/docs/tools.md +254 -0
  83. package/docs/workspace.md +198 -0
  84. package/package.json +59 -4
package/dist/select.js ADDED
@@ -0,0 +1,185 @@
1
+ // A dropdown that looks like the rest of the chat (a native <select>
2
+ // cannot be styled where it opens): a button showing the choice, and a
3
+ // list that opens under it (above when there is no room) with the choice
4
+ // ticked, a dimmer second line or side note per option, a filter box when
5
+ // the list is long, and the keyboard: arrows, Enter, Escape, type to filter.
6
+ // It fires "change" on its element like a <select>.
7
+ import { h, I } from "./dom.js";
8
+ /**
9
+ * `host` is the element the list is positioned in (the chat's root: the
10
+ * list may leave the menu the box sits in, never the chat). It needs a
11
+ * position (relative is fine) and the chat's tokens: the chat's root, or
12
+ * any element with the class `ra-ui`.
13
+ */
14
+ export function selectBox(host, opts = {}) {
15
+ let options = opts.options ?? [];
16
+ let value = opts.value ?? options[0]?.value ?? "";
17
+ let disabled = false;
18
+ const btn = h("button", "ra-sel");
19
+ btn.type = "button";
20
+ btn.setAttribute("aria-haspopup", "listbox");
21
+ const label = h("span", "ra-sell");
22
+ const chev = h("span", "ra-selc");
23
+ chev.innerHTML = I.chevDown(14);
24
+ btn.append(label, chev);
25
+ let pop = null;
26
+ let active = 0;
27
+ let filter = "";
28
+ const draw = () => {
29
+ const o = options.find((x) => x.value === value);
30
+ label.textContent = o?.label ?? opts.placeholder ?? "";
31
+ label.classList.toggle("ph", !o);
32
+ btn.disabled = disabled;
33
+ };
34
+ const shown = () => (filter ? options.filter((o) => `${o.label} ${o.note ?? ""}`.toLowerCase().includes(filter.toLowerCase())) : options);
35
+ const close = (focus = true) => {
36
+ if (!pop)
37
+ return;
38
+ pop.remove();
39
+ pop = null;
40
+ filter = "";
41
+ btn.setAttribute("aria-expanded", "false");
42
+ document.removeEventListener("pointerdown", outside, true);
43
+ if (focus)
44
+ btn.focus();
45
+ };
46
+ const outside = (e) => { if (pop && (!btn.isConnected || (!pop.contains(e.target) && !btn.contains(e.target))))
47
+ close(false); };
48
+ const pick = (v) => {
49
+ const changed = v !== value;
50
+ value = v;
51
+ draw();
52
+ close();
53
+ if (changed)
54
+ btn.dispatchEvent(new Event("change", { bubbles: true }));
55
+ };
56
+ const renderList = (list) => {
57
+ list.replaceChildren();
58
+ const items = shown();
59
+ if (active >= items.length)
60
+ active = Math.max(0, items.length - 1);
61
+ items.forEach((o, i) => {
62
+ const row = h("div", "ra-selo" + (i === active ? " act" : "") + (o.value === value ? " cur" : ""));
63
+ row.setAttribute("role", "option");
64
+ row.setAttribute("aria-selected", String(o.value === value));
65
+ const tick = h("span", "ra-selt");
66
+ tick.innerHTML = o.value === value ? I.tick(13) : "";
67
+ row.append(tick, h("span", "ra-selol", o.label));
68
+ if (o.note)
69
+ row.append(h("span", "ra-selon", o.note));
70
+ row.addEventListener("pointermove", () => { if (active !== i) {
71
+ active = i;
72
+ list.querySelectorAll(".ra-selo").forEach((r, j) => r.classList.toggle("act", j === i));
73
+ } });
74
+ row.addEventListener("click", () => pick(o.value));
75
+ list.append(row);
76
+ });
77
+ if (!items.length)
78
+ list.append(h("div", "ra-selnone", "—"));
79
+ list.querySelector(".act")?.scrollIntoView?.({ block: "nearest" });
80
+ };
81
+ const open = () => {
82
+ if (pop || disabled)
83
+ return;
84
+ pop = h("div", "ra-selp");
85
+ pop.setAttribute("role", "listbox");
86
+ const list = h("div", "ra-sellist");
87
+ let input = null;
88
+ if (options.length >= (opts.filterAt ?? 10)) {
89
+ input = h("input", "ra-self");
90
+ input.type = "text";
91
+ input.placeholder = opts.filterLabel ?? "Filter…";
92
+ input.addEventListener("input", () => { filter = input.value; active = 0; renderList(list); });
93
+ input.addEventListener("keydown", keys);
94
+ pop.append(input);
95
+ }
96
+ pop.append(list);
97
+ active = Math.max(0, options.findIndex((o) => o.value === value));
98
+ renderList(list);
99
+ host.append(pop);
100
+ // Under the button, as wide; above it when the room below is short.
101
+ const hr = host.getBoundingClientRect(), br = btn.getBoundingClientRect();
102
+ const below = hr.bottom - br.bottom - 8, above = br.top - hr.top - 8;
103
+ const want = Math.min(pop.scrollHeight, 320);
104
+ const up = below < want && above > below;
105
+ // Positions are in the host's content box: a host that scrolls (a sidebar) adds its scroll offset.
106
+ pop.style.left = `${br.left - hr.left + host.scrollLeft}px`;
107
+ pop.style.width = `${br.width}px`;
108
+ pop.style.maxHeight = `${Math.max(120, Math.min(320, up ? above : below))}px`;
109
+ pop.style.top = up ? `${br.top - hr.top + host.scrollTop - pop.offsetHeight - 4}px` : `${br.bottom - hr.top + host.scrollTop + 4}px`;
110
+ btn.setAttribute("aria-expanded", "true");
111
+ document.addEventListener("pointerdown", outside, true);
112
+ (input ?? btn).focus();
113
+ };
114
+ const keys = (e) => {
115
+ if (!pop) {
116
+ if (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === "Enter" || e.key === " ") {
117
+ e.preventDefault();
118
+ open();
119
+ }
120
+ return;
121
+ }
122
+ const items = shown();
123
+ const list = pop.querySelector(".ra-sellist");
124
+ if (e.key === "ArrowDown") {
125
+ e.preventDefault();
126
+ active = Math.min(items.length - 1, active + 1);
127
+ renderList(list);
128
+ }
129
+ else if (e.key === "ArrowUp") {
130
+ e.preventDefault();
131
+ active = Math.max(0, active - 1);
132
+ renderList(list);
133
+ }
134
+ else if (e.key === "Enter") {
135
+ e.preventDefault();
136
+ const o = items[active];
137
+ if (o)
138
+ pick(o.value);
139
+ }
140
+ else if (e.key === "Escape") {
141
+ e.preventDefault();
142
+ e.stopPropagation();
143
+ close();
144
+ }
145
+ else if (e.key === "Tab")
146
+ close(false);
147
+ };
148
+ btn.addEventListener("click", () => (pop ? close() : open()));
149
+ btn.addEventListener("keydown", keys);
150
+ draw();
151
+ return {
152
+ el: btn,
153
+ get value() { return value; },
154
+ set value(v) { value = v; draw(); },
155
+ get disabled() { return disabled; },
156
+ set disabled(d) { disabled = d; if (d)
157
+ close(false); draw(); },
158
+ get options() { return options; },
159
+ setOptions(next) { options = next; if (!options.some((o) => o.value === value))
160
+ value = options[0]?.value ?? ""; draw(); },
161
+ close() { close(false); },
162
+ };
163
+ }
164
+ /** The dropdown's look, in the chat's tokens. */
165
+ export const SELECT_CSS = `
166
+ :is(.ra-chat,.ra-ui) .ra-sel{display:flex;align-items:center;gap:8px;width:100%;min-width:0;min-height:34px;padding:6px 10px 6px 12px;box-sizing:border-box;font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;text-align:left;cursor:pointer}
167
+ :is(.ra-chat,.ra-ui) .ra-sel:hover:not(:disabled){border-color:color-mix(in srgb,var(--ra-fg) 25%,var(--ra-border))}
168
+ :is(.ra-chat,.ra-ui) .ra-sel:focus-visible,:is(.ra-chat,.ra-ui) .ra-sel[aria-expanded=true]{border-color:var(--ra-accent);outline:0;box-shadow:0 0 0 3px var(--ra-accent-subtle)}
169
+ :is(.ra-chat,.ra-ui) .ra-sel:disabled{opacity:.55;cursor:not-allowed}
170
+ :is(.ra-chat,.ra-ui) .ra-sel .ra-sell{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
171
+ :is(.ra-chat,.ra-ui) .ra-sel .ra-sell.ph{color:var(--ra-fg-muted)}
172
+ :is(.ra-chat,.ra-ui) .ra-sel .ra-selc{flex:none;display:inline-flex;color:var(--ra-fg-muted);transition:transform .15s}
173
+ :is(.ra-chat,.ra-ui) .ra-sel[aria-expanded=true] .ra-selc{transform:rotate(180deg)}
174
+ :is(.ra-chat,.ra-ui) .ra-selp{position:absolute;z-index:30;display:flex;flex-direction:column;background:var(--ra-panel);border:1px solid var(--ra-border);border-radius:10px;box-shadow:var(--ra-shadow-md);padding:4px;box-sizing:border-box;overflow:hidden;font-size:13px}
175
+ :is(.ra-chat,.ra-ui) .ra-selp .ra-self{flex:none;margin:2px 2px 4px;padding:6px 9px;font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:6px;outline:0}
176
+ :is(.ra-chat,.ra-ui) .ra-selp .ra-self:focus{border-color:var(--ra-accent)}
177
+ :is(.ra-chat,.ra-ui) .ra-selp .ra-sellist{overflow-y:auto;min-height:0}
178
+ :is(.ra-chat,.ra-ui) .ra-selo{display:flex;align-items:center;gap:6px;padding:6px 8px;border-radius:6px;cursor:pointer;color:var(--ra-fg)}
179
+ :is(.ra-chat,.ra-ui) .ra-selo.act{background:var(--ra-muted)}
180
+ :is(.ra-chat,.ra-ui) .ra-selo .ra-selt{flex:none;width:14px;display:inline-flex;color:var(--ra-accent-fg)}
181
+ :is(.ra-chat,.ra-ui) .ra-selo .ra-selol{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
182
+ :is(.ra-chat,.ra-ui) .ra-selo.cur .ra-selol{font-weight:500}
183
+ :is(.ra-chat,.ra-ui) .ra-selo .ra-selon{flex:none;font-size:11.5px;color:var(--ra-fg-muted);font-variant-numeric:tabular-nums}
184
+ :is(.ra-chat,.ra-ui) .ra-selnone{padding:8px;color:var(--ra-fg-muted)}
185
+ `;
@@ -0,0 +1,28 @@
1
+ import type { AgentFS } from "./types.js";
2
+ import { type Inflate, type ZipEntry } from "./zip.js";
3
+ interface Parsed {
4
+ /** Every file, by path inside the zip. */
5
+ entries: Map<string, ZipEntry>;
6
+ /** Skill folders: name → prefix inside the zip ("" for a zip with SKILL.md at its root). */
7
+ folders: Map<string, string>;
8
+ bytes: Uint8Array;
9
+ /** Decoded entries, by path inside the zip. */
10
+ cache: Map<string, string | Uint8Array>;
11
+ }
12
+ /**
13
+ * Where the skills are in a zip: SKILL.md at the root is one skill named
14
+ * `base`; otherwise every folder with a SKILL.md (a leading `skills/` is
15
+ * looked through) is a skill of that folder's name.
16
+ */
17
+ export declare function skillFoldersOf(paths: Iterable<string>, base: string): Map<string, string>;
18
+ /** The files of a zip (cleaned paths → entries), without caching. */
19
+ export declare function zipFiles(bytes: Uint8Array): Map<string, ZipEntry>;
20
+ /** A zip already parsed under `key` (this zip, this version), without its bytes. */
21
+ export declare function cachedSkillZip(key: string): Parsed | undefined;
22
+ /** The zip, parsed; `key` names this zip and version (the same key reuses the parse and its decoded entries). */
23
+ export declare function parseSkillZip(name: string, bytes: Uint8Array, key: string): Parsed;
24
+ /** One skill folder of a zip as a read-only file tree (paths relative to the folder). */
25
+ export declare function skillZipFS(parsed: Parsed, prefix: string, mtime: number, inflate?: Inflate): AgentFS;
26
+ /** The part of `fs` under `base`, as its own read-only tree. */
27
+ export declare function subFS(fs: AgentFS, base: string): AgentFS;
28
+ export {};
@@ -0,0 +1,123 @@
1
+ // Skills straight from their zips: a zip is read in place — its central
2
+ // directory parsed once, an entry inflated the first time it is read and
3
+ // kept in memory — and each skill folder in it is served as a read-only
4
+ // file tree. The workspace puts these trees, with the user's skill
5
+ // folders, under the generated `<skillsDir>/<name>/`.
6
+ import { listZip, readZipEntry } from "./zip.js";
7
+ const parsedCache = new Map();
8
+ const MAX_PARSED = 64;
9
+ /** A cleaned path inside a zip, or null for what is skipped (folders, macOS litter, `..`). */
10
+ function cleanEntry(name) {
11
+ if (name.endsWith("/") || name.includes("__MACOSX/") || /(^|\/)\.DS_Store$/.test(name))
12
+ return null;
13
+ const rel = name.replace(/^\.?\/+/, "").replace(/\/{2,}/g, "/");
14
+ if (!rel || rel.split("/").some((s) => s === ".."))
15
+ return null;
16
+ return rel;
17
+ }
18
+ /**
19
+ * Where the skills are in a zip: SKILL.md at the root is one skill named
20
+ * `base`; otherwise every folder with a SKILL.md (a leading `skills/` is
21
+ * looked through) is a skill of that folder's name.
22
+ */
23
+ export function skillFoldersOf(paths, base) {
24
+ const all = [...paths];
25
+ const out = new Map();
26
+ if (all.includes("SKILL.md")) {
27
+ out.set(base, "");
28
+ return out;
29
+ }
30
+ for (const p of all) {
31
+ const m = /^(?:skills\/)?([^/]+)\/SKILL\.md$/.exec(p);
32
+ if (!m)
33
+ continue;
34
+ const name = m[1];
35
+ const prefix = p.slice(0, -"SKILL.md".length);
36
+ if (!out.has(name) || prefix.length < out.get(name).length)
37
+ out.set(name, prefix);
38
+ }
39
+ return out;
40
+ }
41
+ /** The files of a zip (cleaned paths → entries), without caching. */
42
+ export function zipFiles(bytes) {
43
+ const entries = new Map();
44
+ for (const e of listZip(bytes)) {
45
+ const rel = cleanEntry(e.name);
46
+ if (rel)
47
+ entries.set(rel, e);
48
+ }
49
+ return entries;
50
+ }
51
+ /** A zip already parsed under `key` (this zip, this version), without its bytes. */
52
+ export function cachedSkillZip(key) {
53
+ return parsedCache.get(key);
54
+ }
55
+ /** The zip, parsed; `key` names this zip and version (the same key reuses the parse and its decoded entries). */
56
+ export function parseSkillZip(name, bytes, key) {
57
+ const hit = parsedCache.get(key);
58
+ if (hit && hit.bytes.byteLength === bytes.byteLength)
59
+ return hit;
60
+ const entries = zipFiles(bytes);
61
+ const parsed = { entries, folders: skillFoldersOf(entries.keys(), name), bytes, cache: new Map() };
62
+ if (parsedCache.size >= MAX_PARSED)
63
+ parsedCache.delete(parsedCache.keys().next().value);
64
+ parsedCache.set(key, parsed);
65
+ return parsed;
66
+ }
67
+ const decoder = new TextDecoder("utf-8", { fatal: true });
68
+ const asText = (bytes) => { try {
69
+ return decoder.decode(bytes);
70
+ }
71
+ catch {
72
+ return null;
73
+ } };
74
+ /** One skill folder of a zip as a read-only file tree (paths relative to the folder). */
75
+ export function skillZipFS(parsed, prefix, mtime, inflate) {
76
+ const files = new Map(); // "/rel" → path inside the zip
77
+ for (const p of parsed.entries.keys())
78
+ if (p.startsWith(prefix))
79
+ files.set("/" + p.slice(prefix.length), p);
80
+ const stat = (rel) => {
81
+ const p = files.get(rel);
82
+ return p ? { path: rel, size: parsed.entries.get(p).size, mtime } : null;
83
+ };
84
+ return {
85
+ async list(at) {
86
+ const base = at === "/" ? "/" : at.replace(/\/+$/, "") + "/";
87
+ const out = [];
88
+ for (const rel of files.keys())
89
+ if (base === "/" || rel.startsWith(base) || rel === at)
90
+ out.push(stat(rel));
91
+ return out;
92
+ },
93
+ async stat(rel) { return stat(rel); },
94
+ async read(rel) {
95
+ const p = files.get(rel);
96
+ if (!p)
97
+ throw new Error(`No such file: ${rel}`);
98
+ const hit = parsed.cache.get(p);
99
+ if (hit !== undefined)
100
+ return hit;
101
+ const bytes = await readZipEntry(parsed.bytes, parsed.entries.get(p), inflate);
102
+ const value = asText(bytes) ?? bytes;
103
+ parsed.cache.set(p, value);
104
+ return value;
105
+ },
106
+ };
107
+ }
108
+ /** The part of `fs` under `base`, as its own read-only tree. */
109
+ export function subFS(fs, base) {
110
+ return {
111
+ async list(at) {
112
+ const out = [];
113
+ for (const f of await fs.list(at === "/" ? base : base + at)) {
114
+ const p = f.path.startsWith(base + "/") ? f.path.slice(base.length) : null;
115
+ if (p)
116
+ out.push({ ...f, path: p });
117
+ }
118
+ return out;
119
+ },
120
+ async stat(at) { const s = fs.stat ? await fs.stat(base + at) : null; return s ? { ...s, path: at } : null; },
121
+ read: (at) => fs.read(base + at),
122
+ };
123
+ }
@@ -0,0 +1,20 @@
1
+ import type { Skill } from "./types.js";
2
+ export declare const MAX_SKILL_DESCRIPTION = 1024;
3
+ export interface ParsedSkill {
4
+ skill: Skill;
5
+ /** The instructions after the frontmatter. */
6
+ body: string;
7
+ warnings: string[];
8
+ }
9
+ /**
10
+ * Parses a SKILL.md. `path` is where it sits in the workspace; the folder
11
+ * name is the fallback for a missing `name`. Returns null when the file
12
+ * has no usable description (such a skill is not loaded).
13
+ */
14
+ export declare function parseSkill(text: string, path: string): ParsedSkill | null;
15
+ /**
16
+ * The YAML subset frontmatter uses: `key: value` lines, quoted or plain
17
+ * scalars, one level of nesting under `metadata:` (flattened to
18
+ * `metadata.key`), `>`/`|` block scalars for long descriptions.
19
+ */
20
+ export declare function parseFrontmatter(text: string): Record<string, string>;
package/dist/skills.js ADDED
@@ -0,0 +1,111 @@
1
+ // Skills: folders with a SKILL.md whose frontmatter names and describes
2
+ // them (the Agent Skills format pi uses). The model sees name +
3
+ // description in the system prompt and reads the body on demand.
4
+ export const MAX_SKILL_DESCRIPTION = 1024;
5
+ const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
6
+ /**
7
+ * Parses a SKILL.md. `path` is where it sits in the workspace; the folder
8
+ * name is the fallback for a missing `name`. Returns null when the file
9
+ * has no usable description (such a skill is not loaded).
10
+ */
11
+ export function parseSkill(text, path) {
12
+ const src = text.replace(/^/, "").replace(/\r\n?/g, "\n");
13
+ const dir = path.replace(/\/[^/]*$/, "") || "/";
14
+ const folder = dir.split("/").filter(Boolean).pop() ?? "skill";
15
+ const warnings = [];
16
+ let fm = {};
17
+ let body = src;
18
+ const m = /^---\n([\s\S]*?)\n---\n?/.exec(src);
19
+ if (m) {
20
+ fm = parseFrontmatter(m[1] ?? "");
21
+ body = src.slice(m[0].length);
22
+ }
23
+ const description = (fm.description ?? "").trim();
24
+ if (!description)
25
+ return null;
26
+ let name = (fm.name ?? "").trim() || folder;
27
+ if (!NAME_RE.test(name) || name.length > 64) {
28
+ warnings.push(`skill name "${name}" is not lowercase-hyphenated (≤64); using the folder name`);
29
+ name = NAME_RE.test(folder) ? folder : folder.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "skill";
30
+ }
31
+ const skill = {
32
+ name,
33
+ description: description.length > MAX_SKILL_DESCRIPTION ? description.slice(0, MAX_SKILL_DESCRIPTION) : description,
34
+ path,
35
+ dir,
36
+ };
37
+ if (description.length > MAX_SKILL_DESCRIPTION)
38
+ warnings.push(`description of "${name}" cut to ${MAX_SKILL_DESCRIPTION} characters`);
39
+ if (/^(true|yes)$/i.test(fm["disable-model-invocation"] ?? ""))
40
+ skill.disableModelInvocation = true;
41
+ if (fm.license)
42
+ skill.license = fm.license;
43
+ if (fm.compatibility)
44
+ skill.compatibility = fm.compatibility;
45
+ if (fm["allowed-tools"])
46
+ skill.allowedTools = fm["allowed-tools"].split(/[\s,]+/).filter(Boolean);
47
+ const meta = {};
48
+ for (const [k, v] of Object.entries(fm))
49
+ if (k.startsWith("metadata."))
50
+ meta[k.slice(9)] = v;
51
+ if (Object.keys(meta).length)
52
+ skill.metadata = meta;
53
+ return { skill, body: body.trim(), warnings };
54
+ }
55
+ /**
56
+ * The YAML subset frontmatter uses: `key: value` lines, quoted or plain
57
+ * scalars, one level of nesting under `metadata:` (flattened to
58
+ * `metadata.key`), `>`/`|` block scalars for long descriptions.
59
+ */
60
+ export function parseFrontmatter(text) {
61
+ const out = {};
62
+ const lines = text.split("\n");
63
+ let i = 0;
64
+ let parent = "";
65
+ while (i < lines.length) {
66
+ const line = lines[i] ?? "";
67
+ i++;
68
+ if (!line.trim() || line.trimStart().startsWith("#"))
69
+ continue;
70
+ const indent = line.length - line.trimStart().length;
71
+ const m = /^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(line.trim());
72
+ if (!m)
73
+ continue;
74
+ const key = indent > 0 && parent ? `${parent}.${m[1]}` : m[1];
75
+ if (indent === 0)
76
+ parent = "";
77
+ let value = m[2] ?? "";
78
+ if (value === "") {
79
+ // Either a nested map or an empty value.
80
+ const next = lines[i] ?? "";
81
+ if (next.length - next.trimStart().length > indent && next.trim()) {
82
+ parent = m[1];
83
+ continue;
84
+ }
85
+ }
86
+ else if (value === ">" || value === "|" || value === ">-" || value === "|-") {
87
+ const fold = value.startsWith(">");
88
+ const block = [];
89
+ while (i < lines.length) {
90
+ const l = lines[i] ?? "";
91
+ if (l.trim() && l.length - l.trimStart().length <= indent)
92
+ break;
93
+ block.push(l.trim());
94
+ i++;
95
+ }
96
+ value = fold ? block.join(" ").trim() : block.join("\n").trim();
97
+ }
98
+ else {
99
+ value = unquote(value);
100
+ }
101
+ out[key] = value;
102
+ }
103
+ return out;
104
+ }
105
+ function unquote(v) {
106
+ const t = v.trim();
107
+ if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
108
+ return t.slice(1, -1).replace(/\\"/g, '"').replace(/''/g, "'");
109
+ }
110
+ return t.replace(/\s+#.*$/, "");
111
+ }
@@ -0,0 +1,24 @@
1
+ import type { Workspace } from "./workspace.js";
2
+ export declare const PROMPTS_ROOT = "/prompts";
3
+ export interface PromptTemplate {
4
+ name: string;
5
+ description: string;
6
+ argumentHint?: string;
7
+ path: string;
8
+ }
9
+ /** Bash-style argument splitting: quotes group words, "" is an empty argument. */
10
+ export declare function parseCommandArgs(argsString: string): string[];
11
+ /**
12
+ * `$1`…`$N`, `$@` / `$ARGUMENTS` (all), `${N:-default}`, `${@:-default}`,
13
+ * `${@:N}` and `${@:N:L}` (slices). Values are not substituted again.
14
+ */
15
+ export declare function substituteArgs(content: string, args: string[]): string;
16
+ /** The templates under /prompts (name = file name without .md). */
17
+ export declare function listTemplates(ws: Workspace): Promise<PromptTemplate[]>;
18
+ /**
19
+ * Expands a prompt that starts with `/`: `/skill:name args` → the skill's
20
+ * instructions (as pi words them) plus the arguments; `/name args` → the
21
+ * template's body with its placeholders filled. Anything else is
22
+ * returned unchanged.
23
+ */
24
+ export declare function expandSlash(ws: Workspace | null, text: string): Promise<string>;
@@ -0,0 +1,136 @@
1
+ // Prompt templates and skill invocation typed as slash commands, as in
2
+ // pi: `/name args` expands the workspace file /prompts/<name>.md with
3
+ // bash-style arguments ($1, $@, ${2:-default}, ${@:2}…); `/skill:name
4
+ // args` loads a skill's instructions for this prompt. The argument
5
+ // parsing and substitution are pi's (github.com/earendil-works/pi, MIT).
6
+ export const PROMPTS_ROOT = "/prompts";
7
+ /** Bash-style argument splitting: quotes group words, "" is an empty argument. */
8
+ export function parseCommandArgs(argsString) {
9
+ const args = [];
10
+ let current = "";
11
+ let hasToken = false;
12
+ let inQuote = null;
13
+ for (let i = 0; i < argsString.length; i++) {
14
+ const char = argsString[i];
15
+ if (inQuote) {
16
+ if (char === inQuote)
17
+ inQuote = null;
18
+ else
19
+ current += char;
20
+ }
21
+ else if (char === '"' || char === "'") {
22
+ inQuote = char;
23
+ hasToken = true;
24
+ }
25
+ else if (/\s/.test(char)) {
26
+ if (hasToken) {
27
+ args.push(current);
28
+ current = "";
29
+ hasToken = false;
30
+ }
31
+ }
32
+ else {
33
+ current += char;
34
+ hasToken = true;
35
+ }
36
+ }
37
+ if (hasToken)
38
+ args.push(current);
39
+ return args;
40
+ }
41
+ /**
42
+ * `$1`…`$N`, `$@` / `$ARGUMENTS` (all), `${N:-default}`, `${@:-default}`,
43
+ * `${@:N}` and `${@:N:L}` (slices). Values are not substituted again.
44
+ */
45
+ export function substituteArgs(content, args) {
46
+ const allArgs = args.join(" ");
47
+ return content.replace(/\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g, (_match, defaultTarget, defaultValue, sliceStart, sliceLength, simple) => {
48
+ if (defaultTarget) {
49
+ const value = defaultTarget === "@" || defaultTarget === "ARGUMENTS" ? allArgs : args[parseInt(defaultTarget, 10) - 1];
50
+ return value ? value : defaultValue;
51
+ }
52
+ if (sliceStart) {
53
+ let start = parseInt(sliceStart, 10) - 1;
54
+ if (start < 0)
55
+ start = 0;
56
+ if (sliceLength)
57
+ return args.slice(start, start + parseInt(sliceLength, 10)).join(" ");
58
+ return args.slice(start).join(" ");
59
+ }
60
+ if (simple === "ARGUMENTS" || simple === "@")
61
+ return allArgs;
62
+ return args[parseInt(simple, 10) - 1] ?? "";
63
+ });
64
+ }
65
+ /** The templates under /prompts (name = file name without .md). */
66
+ export async function listTemplates(ws) {
67
+ const out = [];
68
+ for (const f of await ws.list(PROMPTS_ROOT)) {
69
+ if (!f.path.endsWith(".md"))
70
+ continue;
71
+ const name = f.path.slice(PROMPTS_ROOT.length + 1, -3);
72
+ if (name.includes("/"))
73
+ continue;
74
+ let text;
75
+ try {
76
+ text = await ws.readText(f.path);
77
+ }
78
+ catch {
79
+ continue;
80
+ }
81
+ const { fm, body } = splitFrontmatter(text);
82
+ const description = fm.description || firstLine(body);
83
+ out.push({ name, description, argumentHint: fm["argument-hint"], path: f.path });
84
+ }
85
+ return out.sort((a, b) => a.name.localeCompare(b.name));
86
+ }
87
+ /**
88
+ * Expands a prompt that starts with `/`: `/skill:name args` → the skill's
89
+ * instructions (as pi words them) plus the arguments; `/name args` → the
90
+ * template's body with its placeholders filled. Anything else is
91
+ * returned unchanged.
92
+ */
93
+ export async function expandSlash(ws, text) {
94
+ const m = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(text);
95
+ if (!m || !ws)
96
+ return text;
97
+ const name = m[1];
98
+ const argText = (m[2] ?? "").trim();
99
+ if (name.startsWith("skill:")) {
100
+ const skillName = name.slice(6);
101
+ const skills = await ws.skills();
102
+ const skill = skills.find((s) => s.name === skillName);
103
+ if (!skill)
104
+ return text;
105
+ const { body } = await ws.skillBody(skillName);
106
+ const expanded = `<skill name="${skill.name}" location="${skill.path}">\nReferences are relative to ${skill.dir}.\n\n${body}\n</skill>`;
107
+ return argText ? `${expanded}\n\n${argText}` : expanded;
108
+ }
109
+ const path = `${PROMPTS_ROOT}/${name}.md`;
110
+ let source;
111
+ try {
112
+ source = await ws.readText(path);
113
+ }
114
+ catch {
115
+ return text;
116
+ }
117
+ const { body } = splitFrontmatter(source);
118
+ return substituteArgs(body, parseCommandArgs(argText));
119
+ }
120
+ function splitFrontmatter(text) {
121
+ const src = text.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
122
+ const m = /^---\n([\s\S]*?)\n---\n?/.exec(src);
123
+ if (!m)
124
+ return { fm: {}, body: src.trim() };
125
+ const fm = {};
126
+ for (const line of (m[1] ?? "").split("\n")) {
127
+ const kv = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(line.trim());
128
+ if (kv)
129
+ fm[kv[1]] = kv[2].replace(/^["']|["']$/g, "");
130
+ }
131
+ return { fm, body: src.slice(m[0].length).trim() };
132
+ }
133
+ function firstLine(body) {
134
+ const line = body.split("\n").find((l) => l.trim()) ?? "";
135
+ return line.length > 60 ? line.slice(0, 60) + "..." : line;
136
+ }
package/dist/tool.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { ChatTool, ContentPart } from "./llm.js";
2
+ import type { Tool, ToolDefinition, ToolResultValue } from "./types.js";
3
+ export declare const DEFAULT_MAX_RESULT_CHARS = 32000;
4
+ /**
5
+ * Declares a tool. Checks the name and fills in an empty-object schema
6
+ * when the tool takes no arguments. The JSON Schema in `parameters`
7
+ * should close objects with `additionalProperties: false` and list
8
+ * `required` fields: the model's arguments are checked against it before
9
+ * `execute` runs, and a mismatch is reported back to the model.
10
+ */
11
+ export declare function defineTool<A = Record<string, unknown>>(def: ToolDefinition<A>): Tool<A>;
12
+ export declare function toChatTool(tool: Tool<unknown>): ChatTool;
13
+ export interface NormalizedResult {
14
+ /** What the model gets as the tool message content. */
15
+ content: string | ContentPart[];
16
+ /** The text form (for events and the loop guard). */
17
+ text: string;
18
+ details?: unknown;
19
+ truncated: boolean;
20
+ }
21
+ /** Turns whatever `execute` returned into the tool message. */
22
+ export declare function normalizeResult(value: ToolResultValue, maxChars?: number): NormalizedResult;
23
+ export declare function truncate(text: string, maxChars: number): {
24
+ text: string;
25
+ truncated: boolean;
26
+ };
27
+ /** The text of a content-parts array (images noted, not included). */
28
+ export declare function textOf(content: string | ContentPart[] | null | undefined): string;