@agntn/tools 0.3.1 โ†’ 0.3.3

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/README.md CHANGED
@@ -24,6 +24,7 @@ MCP wants an `inputSchema`. Pi wants `parameters` and a prompt snippet. OMP swap
24
24
  - ๐Ÿงช **Schema rules at definition time.** An open object or a union of literals fails in `defineTool`. Not three weeks later in a model's hands.
25
25
  - โณ **Progress that gets somewhere.** `progress?.("still at it")` turns into `onUpdate` in Pi and OMP, `notifications/progress` in MCP and one live line in your terminal. A slow call stops looking like a dead one.
26
26
  - ๐Ÿ™‹ **Ask the person, not the model.** `ask?.({ message, schema })` becomes MCP elicitation, or one dialog per field in Pi and OMP. Three puzzles match? Let them pick instead of letting the model guess.
27
+ - ๐Ÿ”Ž **Tools when you need them.** `AGNTN_PI_EXPOSURE=deferred` keeps Pi tools out of the prompt. The ones nobody called today stop riding along. Turn on `tool_search` and the model still finds them.
27
28
  - โŒจ๏ธ **A CLI on the side.** `runCli` turns the same tools into commands, no CLI library needed. Flags come from the schema. Hints add positionals, short flags and stdin.
28
29
  - ๐ŸŒ **Runs anywhere.** No `node:*` import in the core or the host adapters. The docs site runs them in a browser tab. The CLI is the one Node part, as a CLI should be.
29
30
 
@@ -1,4 +1,9 @@
1
+ import { __exportAll } from "./rolldown-runtime.mjs";
1
2
  import { ToolInputError, sanitizeLine } from "./src.mjs";
3
+ var causes_exports = /* @__PURE__ */ __exportAll({
4
+ causeLines: () => causeLines,
5
+ throwWithCauses: () => throwWithCauses
6
+ });
2
7
  const CAUSE_DEPTH = 5;
3
8
  const CAUSE_LENGTH = 300;
4
9
  function causeLines(error) {
@@ -9,12 +14,15 @@ function causeLines(error) {
9
14
  for (let depth = 0; depth < CAUSE_DEPTH && level !== void 0 && !seen.has(level); depth += 1) {
10
15
  seen.add(level);
11
16
  const text = causeText(level);
12
- if (text !== "" && !above.includes(text)) lines.push(`caused by: ${text}`);
13
- if (text !== "") above = text;
17
+ if (text !== "" && !alreadySaid(above, text)) lines.push(`caused by: ${text}`);
18
+ if (text !== "") above += `\n${text}`;
14
19
  level = nextCause(level);
15
20
  }
16
21
  return lines;
17
22
  }
23
+ function alreadySaid(above, text) {
24
+ return above.includes(text.length > CAUSE_LENGTH ? text.slice(0, CAUSE_LENGTH) : text);
25
+ }
18
26
  function nextCause(error) {
19
27
  if (!(error instanceof Error)) return void 0;
20
28
  if (error.cause !== void 0) return error.cause;
@@ -68,4 +76,4 @@ function throwWithCauses(error) {
68
76
  shown.name = error.name;
69
77
  throw shown;
70
78
  }
71
- export { causeLines, throwWithCauses };
79
+ export { causeLines, causes_exports, throwWithCauses };
package/dist/cli.d.mts CHANGED
@@ -28,8 +28,8 @@ export interface CliOptions {
28
28
  /** Adds `mcp` over stdio, named by the CLI on `true` or by the server info it's handed. */
29
29
  readonly mcp?: boolean | McpServerInfo;
30
30
  /**
31
- * Errors the package throws on purpose. They print as one line with exit
32
- * code 1; any other error keeps its stack trace.
31
+ * Errors the package throws on purpose. They print as one line with a `caused by:`
32
+ * line per cause and exit code 1; any other error keeps its stack trace.
33
33
  */
34
34
  readonly expected?: (error: unknown) => boolean;
35
35
  }
package/dist/cli.mjs CHANGED
@@ -164,7 +164,14 @@ function fieldDescription(field, values = "") {
164
164
  }
165
165
  function valueHint(field) {
166
166
  if (field.kind === "enum") return field.schema.enum.join("|");
167
- return field.kind === "string" ? field.flag : field.kind;
167
+ if (field.kind !== "json") return field.kind === "string" ? field.flag : field.kind;
168
+ const word = wordBranch(field.schema);
169
+ if (word === void 0) return "json";
170
+ return `${valueHint({
171
+ ...field,
172
+ schema: word,
173
+ kind: fieldKind(word)
174
+ })}|json`;
168
175
  }
169
176
  function optionSpelling(field, hint = valueHint(field)) {
170
177
  return field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${hint}>`;
@@ -387,6 +394,23 @@ function wordValue(schema, word) {
387
394
  if (index !== -1) return readings[index];
388
395
  return spelled.find((value) => typeof value === "number") ?? word;
389
396
  }
397
+ function wordBranch(schema) {
398
+ return unionBranches(schema).find((branch) => fieldKind(branch) !== "json" && branch.type !== "null");
399
+ }
400
+ function jsonValue(schema, word) {
401
+ let parsed;
402
+ try {
403
+ parsed = { value: JSON.parse(word) };
404
+ } catch {
405
+ parsed = void 0;
406
+ }
407
+ if (wordBranch(schema) === void 0) return parsed ?? { error: "must be JSON" };
408
+ if (parsed !== void 0 && (quotedJson(parsed.value) || Check(schema, parsed.value))) return parsed;
409
+ return { value: wordValue(schema, word) };
410
+ }
411
+ function quotedJson(value) {
412
+ return typeof value === "string" || typeof value === "object" && value !== null;
413
+ }
390
414
  function fieldValue(field, raw) {
391
415
  if (field.stdin && raw === "-") {
392
416
  const text = readStdin();
@@ -396,11 +420,7 @@ function fieldValue(field, raw) {
396
420
  if (field.kind === "number") return numberValue(field.schema.type === "integer", raw);
397
421
  if (field.kind === "string") return { value: wordValue(field.schema, raw) };
398
422
  if (field.kind !== "json") return { value: raw };
399
- try {
400
- return { value: JSON.parse(raw) };
401
- } catch {
402
- return { error: "must be JSON" };
403
- }
423
+ return jsonValue(field.schema, raw);
404
424
  }
405
425
  function toolInput(fields, values) {
406
426
  const input = emptyRecord();
@@ -462,10 +482,12 @@ function fail(lines) {
462
482
  writeLine("stderr", lines.map(sanitizeLine).join("\n"));
463
483
  process.exitCode = 1;
464
484
  }
465
- function handleError(options, error) {
485
+ async function handleError(options, error) {
466
486
  if (error instanceof ToolInputError) fail(error.lines);
467
- else if (options.expected?.(error) === true) fail([error instanceof Error ? error.message : String(error)]);
468
- else throw error;
487
+ else if (options.expected?.(error) === true) {
488
+ const { causeLines } = await import("./_chunks/causes.mjs").then((n) => n.causes_exports);
489
+ fail([error instanceof Error ? error.message : String(error), ...causeLines(error)]);
490
+ } else throw error;
469
491
  }
470
492
  function detailsJson(details) {
471
493
  return (JSON.stringify(details, (_key, value) => typeof value === "bigint" ? value.toString() : value, 2) ?? "null").replaceAll(JSON_FORGING, (character) => `\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, "0")}`);
@@ -695,7 +717,7 @@ async function runCommand(options, command, rawArgs) {
695
717
  if (words.errors.length > 0) throw new ToolInputError(words.errors);
696
718
  await command.run(words);
697
719
  } catch (error) {
698
- handleError(options, error);
720
+ await handleError(options, error);
699
721
  }
700
722
  }
701
723
  function table(rows) {
package/dist/omp.d.mts CHANGED
@@ -14,10 +14,7 @@ export interface OmpRenderers {
14
14
  renderCall?: ToolDefinition["renderCall"];
15
15
  /** Short metadata after the badge, one entry per fact. Each entry is sanitized. */
16
16
  describeResult?(result: OmpResultView): readonly unknown[];
17
- /**
18
- * Replaces the result status line with the package's own component, such as
19
- * a bounded preview of long output. It owns sanitizing what it draws.
20
- */
17
+ /** Replaces the status line and the answer under it. It owns sanitizing what it draws. */
21
18
  renderResult?: ToolDefinition["renderResult"];
22
19
  }
23
20
  export interface OmpToolOptions {
package/dist/omp.mjs CHANGED
@@ -1,6 +1,7 @@
1
- import { indexTools, invokeTool, sanitizeLine, wireSchema } from "./_chunks/src.mjs";
1
+ import { indexTools, invokeTool, sanitizeLine, sanitizeText, wireSchema } from "./_chunks/src.mjs";
2
2
  import { throwWithCauses } from "./_chunks/causes.mjs";
3
3
  import { hostContext } from "./_chunks/updates.mjs";
4
+ const COLLAPSED_LINES = 4;
4
5
  const APPROVAL = {
5
6
  read: "read",
6
7
  write: "write",
@@ -34,11 +35,10 @@ function registerOmpTools(pi, tools, options) {
34
35
  renderResult(result, renderOptions, theme, args) {
35
36
  if (renderers?.renderResult) return renderers.renderResult(result, renderOptions, theme, args);
36
37
  if (renderOptions.isPartial) return new Text(progressLine(tool, result, renderOptions, theme), 0, 0);
37
- const icon = result.isError ? theme.styledSymbol("status.error", "error") : theme.styledSymbol("status.done", "success");
38
- const { bracketLeft, bracketRight } = theme.format;
39
- const badge = theme.fg("accent", `${bracketLeft}${APPROVAL[tool.effect]}${bracketRight}`);
40
38
  const facts = result.isError ? [] : renderers?.describeResult?.(result) ?? [];
41
- return new Text(`${icon} ${theme.fg("accent", sanitizeLine(tool.title))} ${badge}${dimFacts(facts, theme)}`, 0, 0);
39
+ const status = `${statusLine(tool, result, theme)}${dimFacts(facts, theme)}`;
40
+ const answer = answerLines(result, renderOptions.expanded, theme);
41
+ return new Text(answer ? `${status}\n${answer}` : status, 0, 0);
42
42
  }
43
43
  });
44
44
  }
@@ -48,6 +48,22 @@ function progressLine(tool, result, options, theme) {
48
48
  const title = theme.fg("accent", sanitizeLine(tool.title));
49
49
  return `${callIcon(options, theme)} ${title}${message ? ` ${theme.fg("dim", message)}` : ""}`;
50
50
  }
51
+ function statusLine(tool, result, theme) {
52
+ const icon = result.isError ? theme.styledSymbol("status.error", "error") : theme.styledSymbol("status.done", "success");
53
+ const { bracketLeft, bracketRight } = theme.format;
54
+ const badge = theme.fg("accent", `${bracketLeft}${APPROVAL[tool.effect]}${bracketRight}`);
55
+ return `${icon} ${theme.fg("accent", sanitizeLine(tool.title))} ${badge}`;
56
+ }
57
+ function answerLines(result, expanded, theme) {
58
+ const text = result.content.flatMap((block) => block.type === "text" && block.text ? [block.text] : []).join("\n");
59
+ const lines = sanitizeText(text).trimEnd().split("\n");
60
+ if (lines.join("") === "") return "";
61
+ const shown = expanded ? lines : lines.slice(0, COLLAPSED_LINES);
62
+ const body = shown.map((line) => theme.fg("toolOutput", line));
63
+ const hidden = lines.length - shown.length;
64
+ if (hidden > 0) body.push(theme.fg("dim", `โ€ฆ ${hidden} more lines`));
65
+ return body.join("\n");
66
+ }
51
67
  function dimFacts(facts, theme) {
52
68
  const shown = facts.map(sanitizeLine).filter(Boolean);
53
69
  return shown.length > 0 ? ` ${theme.fg("dim", shown.join(theme.sep.dot))}` : "";
package/dist/pi.d.mts CHANGED
@@ -21,6 +21,23 @@ export interface PiToolOptions {
21
21
  readonly confirm?: Readonly<Record<string, PiConfirm>>;
22
22
  /** Pi's argument repair by tool name, run before validation. A name off the list throws. */
23
23
  readonly prepareArguments?: Readonly<Record<string, PiPrepareArguments>>;
24
+ /** How the model reaches the tools, for all or by name. Left out, Pi's `direct`. */
25
+ readonly exposure?: PiToolExposure | PiExposures;
26
+ /** Group the tools share, as Pi groups the tools of one MCP server. */
27
+ readonly namespace?: PiToolNamespace;
28
+ }
29
+ /** Pi's `ToolExposure`, spelled out so older Pi types still compile. */
30
+ export type PiToolExposure = "direct" | "model-only" | "codemode" | "deferred" | "hidden";
31
+ /** Exposure by tool name, with a fallback for the rest. A name off the list throws. */
32
+ export interface PiExposures {
33
+ readonly default?: PiToolExposure;
34
+ readonly tools?: Readonly<Record<string, PiToolExposure>>;
35
+ }
36
+ /** Pi's `ToolNamespace`: what `describeNamespace()` and `tool_search` read. */
37
+ export interface PiToolNamespace {
38
+ readonly name: string;
39
+ readonly description?: string;
40
+ readonly instructions?: string;
24
41
  }
25
42
  /** Repairs raw model input before validation. Hand back what it doesn't recognise untouched. */
26
43
  export type PiPrepareArguments = (args: unknown) => unknown;
@@ -41,8 +58,9 @@ export interface PiRenderers extends Readonly<Pick<ToolDefinition, "renderCall"
41
58
  *
42
59
  * @param pi - Pi extension API.
43
60
  * @param tools - Tools to register.
44
- * @param options - Failure policy, host `Text`, renderers, questions and argument repairs.
61
+ * @param options - Failure policy, host `Text`, renderers, questions, repairs and exposure.
45
62
  * @throws {ToolDefinitionError} When two tools share a name, a tool has `describeCall` but no
46
- * `Text` came with it, or `confirm` or `prepareArguments` names a tool that isn't in the list.
63
+ * `Text` came with it, `confirm`, `prepareArguments` or `exposure` names a tool that isn't in
64
+ * the list, or an exposure isn't one Pi knows.
47
65
  */
48
66
  export declare function registerPiTools(pi: ExtensionAPI, tools: readonly ToolDefinition$1[], options?: PiToolOptions): void;
package/dist/pi.mjs CHANGED
@@ -1,24 +1,37 @@
1
+ import { Check } from "./_chunks/libs/typebox.mjs";
1
2
  import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput } from "./_chunks/src.mjs";
2
3
  import { throwWithCauses } from "./_chunks/causes.mjs";
3
4
  import { hostContext } from "./_chunks/updates.mjs";
5
+ const EXPOSURES = [
6
+ "direct",
7
+ "model-only",
8
+ "codemode",
9
+ "deferred",
10
+ "hidden"
11
+ ];
12
+ const EXPOSURE_VARIABLE = "AGNTN_PI_EXPOSURE";
4
13
  function registerPiTools(pi, tools, options = {}) {
5
14
  const names = [...indexTools(tools).keys()];
6
15
  const failures = options.failures ?? "throw";
7
16
  refuseStray(names, "confirm", options.confirm);
8
17
  refuseStray(names, "prepareArguments", options.prepareArguments);
18
+ checkOption(names, options.exposure);
19
+ fromEnvironment(EXPOSURE_VARIABLE);
20
+ const exposures = new Map(names.map((name) => [name, exposureOf(name, options.exposure)]));
9
21
  for (const tool of tools) {
10
22
  const renderers = byName(options.renderers, tool.name);
11
23
  const ask = byName(options.confirm, tool.name);
12
- const prepare = byName(options.prepareArguments, tool.name);
24
+ const prepare = parseJsonText(tool, byName(options.prepareArguments, tool.name));
13
25
  pi.registerTool({
14
26
  ...hostRenderers(tool, renderers, options.Text),
15
- ...prepare === void 0 ? {} : { prepareArguments: prepare },
27
+ prepareArguments: prepare,
16
28
  name: tool.name,
17
29
  label: tool.title,
18
30
  description: tool.description,
19
31
  ...tool.snippet === void 0 ? {} : { promptSnippet: tool.snippet },
20
32
  ...tool.guidelines === void 0 ? {} : { promptGuidelines: [...tool.guidelines] },
21
33
  parameters: tool.input,
34
+ ...reach(exposures.get(tool.name), options.namespace),
22
35
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
23
36
  if (ask) await approve(tool, ask, params, signal, ctx);
24
37
  const context = hostContext(signal, onUpdate, ctx);
@@ -29,6 +42,61 @@ function registerPiTools(pi, tools, options = {}) {
29
42
  });
30
43
  }
31
44
  }
45
+ function parseJsonText(tool, own) {
46
+ if (own === void 0) return (args) => repairJsonText(tool, args);
47
+ return (args) => own(repairJsonText(tool, args));
48
+ }
49
+ function repairJsonText(tool, args) {
50
+ if (typeof args !== "object" || args === null || Array.isArray(args)) return args;
51
+ const raw = args;
52
+ let repaired;
53
+ const properties = Object.entries(tool.input.properties);
54
+ for (const [key, schema] of properties) {
55
+ const parsed = Object.hasOwn(raw, key) ? jsonValue(raw[key], schema) : void 0;
56
+ if (parsed === void 0) continue;
57
+ repaired ??= { ...raw };
58
+ repaired[key] = parsed;
59
+ }
60
+ return repaired ?? args;
61
+ }
62
+ function jsonValue(value, schema) {
63
+ if (typeof value !== "string" || !/^\s*[[{]/.test(value)) return void 0;
64
+ try {
65
+ const parsed = JSON.parse(value);
66
+ return typeof parsed === "object" && parsed !== null && Check(schema, parsed) ? parsed : void 0;
67
+ } catch {
68
+ return;
69
+ }
70
+ }
71
+ function reach(exposure, namespace) {
72
+ return {
73
+ ...exposure === void 0 ? {} : { exposure },
74
+ ...namespace === void 0 ? {} : { namespace: { ...namespace } }
75
+ };
76
+ }
77
+ function exposureOf(name, option) {
78
+ const own = `${EXPOSURE_VARIABLE}_${name.split("_", 1)[0]?.toUpperCase() ?? ""}`;
79
+ const global = fromEnvironment(EXPOSURE_VARIABLE);
80
+ return fromEnvironment(own) ?? global ?? (typeof option === "object" ? byName(option.tools, name) ?? option.default : option);
81
+ }
82
+ function checkOption(names, option) {
83
+ if (typeof option !== "object") {
84
+ if (option !== void 0) checkExposure(option, "exposure");
85
+ return;
86
+ }
87
+ refuseStray(names, "exposure.tools", option.tools);
88
+ if (option.default !== void 0) checkExposure(option.default, "exposure.default");
89
+ for (const [name, value] of Object.entries(option.tools ?? {})) checkExposure(value, `exposure of ${name}`);
90
+ }
91
+ function fromEnvironment(variable) {
92
+ const value = typeof process === "undefined" ? void 0 : process.env[variable];
93
+ return value ? checkExposure(value, variable) : void 0;
94
+ }
95
+ function checkExposure(value, where) {
96
+ if (typeof value === "string" && EXPOSURES.includes(value)) return value;
97
+ const shown = typeof value === "string" ? `is ${JSON.stringify(value)}` : "isn't a string";
98
+ throw new ToolDefinitionError(`${where} ${shown}; takes ${EXPOSURES.join(", ")}`);
99
+ }
32
100
  function refuseStray(names, option, entries) {
33
101
  const stray = Object.keys(entries ?? {}).find((name) => !names.includes(name));
34
102
  if (stray === void 0) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agntn/tools",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "One tool definition for MCP, Pi, OMP and the AI SDK",
5
5
  "homepage": "https://github.com/agntn/tools#readme",
6
6
  "bugs": "https://github.com/agntn/tools/issues",