@agentsmarket/pipeline-runtime 0.1.6 → 0.1.7

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.
@@ -9,6 +9,14 @@
9
9
  * Prompts keep their existing behavior (LLM interprets literal refs
10
10
  * as context markers — works because LLMs are smart).
11
11
  *
12
+ * Native types are PRESERVED. When `$input.urls` resolves and `urls`
13
+ * is an array, the substituted value is the array, NOT a JSON string.
14
+ * Tool skills (web_fetch, etc.) need native arrays/objects to work.
15
+ * If a prompt needs the array stringified, the prompt author can do
16
+ * it inside the template (e.g. wrap in explicit JSON.stringify call
17
+ * is not available in YAML — but a downstream LLM can handle arrays
18
+ * shown as `[object Array]` if needed).
19
+ *
12
20
  * Why "leave literal if missing" instead of throwing:
13
21
  * The skill may receive partial input and choose to return an
14
22
  * error JSON (which downstream stages can handle). Throwing
@@ -9,6 +9,14 @@
9
9
  * Prompts keep their existing behavior (LLM interprets literal refs
10
10
  * as context markers — works because LLMs are smart).
11
11
  *
12
+ * Native types are PRESERVED. When `$input.urls` resolves and `urls`
13
+ * is an array, the substituted value is the array, NOT a JSON string.
14
+ * Tool skills (web_fetch, etc.) need native arrays/objects to work.
15
+ * If a prompt needs the array stringified, the prompt author can do
16
+ * it inside the template (e.g. wrap in explicit JSON.stringify call
17
+ * is not available in YAML — but a downstream LLM can handle arrays
18
+ * shown as `[object Array]` if needed).
19
+ *
12
20
  * Why "leave literal if missing" instead of throwing:
13
21
  * The skill may receive partial input and choose to return an
14
22
  * error JSON (which downstream stages can handle). Throwing
@@ -20,8 +28,8 @@
20
28
  * Strings get the regex substitution. Numbers, booleans, null return
21
29
  * unchanged.
22
30
  */
23
- const INPUT_REF_PATTERN = /\$\{?\s*input\.([A-Za-z_][A-Za-z0-9_]*)\s*\}?/g;
24
- const STAGE_OUTPUT_REF_PATTERN = /\$\{?\s*stages\.([A-Za-z_][A-Za-z0-9_.-]*)\.output\s*\}?/g;
31
+ const INPUT_REF_PATTERN = /\$\{\s*input\.([A-Za-z_][A-Za-z0-9_]*)\s*\}|\$input\.([A-Za-z_][A-Za-z0-9_]*)/g;
32
+ const STAGE_OUTPUT_REF_PATTERN = /\$\{\s*stages\.([A-Za-z_][A-Za-z0-9_.-]*)\.output\s*\}|\$stages\.([A-Za-z_][A-Za-z0-9_.-]*)\.output/g;
25
33
  export function resolveInputRefs(value, ctx) {
26
34
  if (typeof value === 'string') {
27
35
  return resolveStringRefs(value, ctx);
@@ -39,16 +47,43 @@ export function resolveInputRefs(value, ctx) {
39
47
  return value;
40
48
  }
41
49
  function resolveStringRefs(text, ctx) {
50
+ const trimmed = text.trim();
51
+ const inputMatches = [...trimmed.matchAll(/\$input\.([A-Za-z_][A-Za-z0-9_]*)|\$\{\s*input\.([A-Za-z_][A-Za-z0-9_]*)\s*\}/g)];
52
+ const stageMatches = [...trimmed.matchAll(/\$stages\.([A-Za-z_][A-Za-z0-9_.-]*)\.output|\$\{\s*stages\.([A-Za-z_][A-Za-z0-9_.-]*)\.output\s*\}/g)];
53
+ const isSingleInputRef = inputMatches.length === 1
54
+ && stageMatches.length === 0
55
+ && inputMatches[0][0] === trimmed;
56
+ const isSingleStageRef = stageMatches.length === 1
57
+ && inputMatches.length === 0
58
+ && stageMatches[0][0] === trimmed;
59
+ if (isSingleInputRef) {
60
+ const m = inputMatches[0];
61
+ const key = m[1] ?? m[2];
62
+ if (key !== undefined && Object.prototype.hasOwnProperty.call(ctx.inputs, key)) {
63
+ return ctx.inputs[key];
64
+ }
65
+ return text;
66
+ }
67
+ if (isSingleStageRef) {
68
+ const m = stageMatches[0];
69
+ const stageId = m[1] ?? m[2];
70
+ if (stageId !== undefined && Object.prototype.hasOwnProperty.call(ctx.previousOutputs, stageId)) {
71
+ return ctx.previousOutputs[stageId] ?? '';
72
+ }
73
+ return text;
74
+ }
42
75
  let out = text;
43
- out = out.replace(INPUT_REF_PATTERN, (match, key) => {
44
- if (Object.prototype.hasOwnProperty.call(ctx.inputs, key)) {
76
+ out = out.replace(INPUT_REF_PATTERN, (match, key1, key2) => {
77
+ const key = key1 ?? key2;
78
+ if (key !== undefined && Object.prototype.hasOwnProperty.call(ctx.inputs, key)) {
45
79
  const v = ctx.inputs[key];
46
80
  return stringifyValue(v);
47
81
  }
48
82
  return match;
49
83
  });
50
- out = out.replace(STAGE_OUTPUT_REF_PATTERN, (match, stageId) => {
51
- if (Object.prototype.hasOwnProperty.call(ctx.previousOutputs, stageId)) {
84
+ out = out.replace(STAGE_OUTPUT_REF_PATTERN, (match, sid1, sid2) => {
85
+ const stageId = sid1 ?? sid2;
86
+ if (stageId !== undefined && Object.prototype.hasOwnProperty.call(ctx.previousOutputs, stageId)) {
52
87
  return ctx.previousOutputs[stageId] ?? '';
53
88
  }
54
89
  return match;
package/dist/stages.js CHANGED
@@ -17,6 +17,7 @@ import { createModelResolver, } from './model-resolver.js';
17
17
  import { computeSkillContentHash } from './content-hash.js';
18
18
  import { shouldSkipStage } from './when.js';
19
19
  import { resolveInputRefs } from './pipeline-refs.js';
20
+ import { isToolSkill, invokeToolSkill } from './tools/tool-skills.js';
20
21
  import { isRetryableStatus, computeBackoffMs, RetryExhaustedError, DEFAULT_RETRY, } from './retry.js';
21
22
  import { NoopEventSink, makeStartedEvent as makePipelineStartedEvent, makeCompletedEvent as makePipelineCompletedEvent, makeFailedEvent as makePipelineFailedEvent, makeStageStartedEvent, makeStageCompletedEvent, makeStageSkippedEvent, makeStageFailedEvent, makeStageRetriedEvent, } from './streaming-events.js';
22
23
  import { validateRuntimeConstraints, collectRuntimeWarnings, defaultRuntimeConstraints, } from './runtime-constraints.js';
@@ -363,6 +364,26 @@ export async function executeStage(stage, pipeline, ctx, deps) {
363
364
  const resolvedInput = typeof chainedInput === 'string'
364
365
  ? resolveStageOutputRefs(chainedInput, ctx.previousOutputs)
365
366
  : resolveInputRefs(chainedInput, { inputs: ctx.inputs, previousOutputs: ctx.previousOutputs });
367
+ if (isToolSkill(use.id)) {
368
+ const toolT0 = Date.now();
369
+ const toolResult = await invokeToolSkill(use.id, resolvedInput, {
370
+ agentId: deps.getCurrentAgentId(),
371
+ });
372
+ const toolDurationMs = Date.now() - toolT0;
373
+ deps.onLlmResponse?.(`${stage.id}:${use.id}`, toolResult.text, 'tool');
374
+ lastResult = {
375
+ text: toolResult.text,
376
+ usage: toolResult.usage,
377
+ };
378
+ chainedInput = { input_from_previous_skill: toolResult.text };
379
+ nestedCalls.push({
380
+ step_id: `${stage.id}:${i + 1}`,
381
+ skill_id: use.id,
382
+ duration_ms: toolDurationMs,
383
+ ok: true,
384
+ });
385
+ continue;
386
+ }
366
387
  const { result, durationMs } = await invokeSkill(skill, resolvedInput, previousContext, label, stageProvider, stage.retry, retryCtx, stage.output_format);
367
388
  deps.onLlmResponse?.(`${stage.id}:${use.id}`, result.text, skillModel);
368
389
  lastResult = result;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Built-in tool skills — execute natively in the runtime instead of going
3
+ * through LLM-as-skill composition.
4
+ *
5
+ * Why: F27. Skill execution in v0.2 was LLM-only (compose skill.full_md +
6
+ * Input JSON, send to LLM, treat response as skill output). That's fine for
7
+ * prompt-engineering tasks (summarize, translate, classify) but fails for
8
+ * side-effect tasks that need real I/O — web_fetch needs actual HTTP,
9
+ * not LLM roleplay.
10
+ *
11
+ * Architecture: tool skills are matched by `skill.id` (NOT by marketplace
12
+ * lookup). The pipeline can still declare `uses: web_fetch@1.0.0` so the
13
+ * skill appears in provenance + spec_hash, but the runtime intercepts
14
+ * the invocation and runs the native handler instead of going to the LLM.
15
+ *
16
+ * Add new tools here as the catalog grows.
17
+ */
18
+ export interface ToolSkillContext {
19
+ /** Agent ID of the caller — for logging/tracing. */
20
+ agentId: string;
21
+ /** Abort signal — for cancellation on pipeline timeout. */
22
+ signal?: AbortSignal;
23
+ }
24
+ export interface ToolSkillResult {
25
+ /** String output that becomes the stage's final output (same shape as LLM skill returns). */
26
+ text: string;
27
+ /** Usage — reported as 0 tokens since no LLM was called. */
28
+ usage: {
29
+ inputTokens: number;
30
+ outputTokens: number;
31
+ };
32
+ /** Optional metadata for downstream stages or provenance. */
33
+ meta?: Record<string, unknown>;
34
+ }
35
+ export type ToolSkillHandler = (input: unknown, ctx: ToolSkillContext) => Promise<ToolSkillResult>;
36
+ export declare function isToolSkill(skillId: string): boolean;
37
+ export declare function invokeToolSkill(skillId: string, input: unknown, ctx: ToolSkillContext): Promise<ToolSkillResult>;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Built-in tool skills — execute natively in the runtime instead of going
3
+ * through LLM-as-skill composition.
4
+ *
5
+ * Why: F27. Skill execution in v0.2 was LLM-only (compose skill.full_md +
6
+ * Input JSON, send to LLM, treat response as skill output). That's fine for
7
+ * prompt-engineering tasks (summarize, translate, classify) but fails for
8
+ * side-effect tasks that need real I/O — web_fetch needs actual HTTP,
9
+ * not LLM roleplay.
10
+ *
11
+ * Architecture: tool skills are matched by `skill.id` (NOT by marketplace
12
+ * lookup). The pipeline can still declare `uses: web_fetch@1.0.0` so the
13
+ * skill appears in provenance + spec_hash, but the runtime intercepts
14
+ * the invocation and runs the native handler instead of going to the LLM.
15
+ *
16
+ * Add new tools here as the catalog grows.
17
+ */
18
+ const TOOL_SKILLS = {
19
+ web_fetch: webFetchHandler,
20
+ };
21
+ export function isToolSkill(skillId) {
22
+ return skillId in TOOL_SKILLS;
23
+ }
24
+ export async function invokeToolSkill(skillId, input, ctx) {
25
+ const handler = TOOL_SKILLS[skillId];
26
+ if (!handler) {
27
+ throw new Error(`Tool skill '${skillId}' is registered but has no handler`);
28
+ }
29
+ return handler(input, ctx);
30
+ }
31
+ async function webFetchHandler(input, ctx) {
32
+ const { urls, max_chars, max_per_article_chars } = parseFetchInput(input);
33
+ const cap = typeof max_chars === 'number' && max_chars > 0
34
+ ? max_chars
35
+ : (typeof max_per_article_chars === 'number' && max_per_article_chars > 0
36
+ ? max_per_article_chars
37
+ : 4000);
38
+ const articles = [];
39
+ for (const url of urls) {
40
+ try {
41
+ const res = await fetch(url, { signal: ctx.signal });
42
+ const raw = await res.text();
43
+ const content = stripHtmlToText(raw).slice(0, cap);
44
+ articles.push({ url, content, status: res.status });
45
+ }
46
+ catch (e) {
47
+ articles.push({
48
+ url,
49
+ content: '',
50
+ status: 0,
51
+ error: e instanceof Error ? e.message : String(e),
52
+ });
53
+ }
54
+ }
55
+ const text = articles.map((a) => {
56
+ if (a.error) {
57
+ return `URL: ${a.url}\nSTATUS: error\nERROR: ${a.error}\nCONTENT:\n`;
58
+ }
59
+ return `URL: ${a.url}\nSTATUS: ${a.status}\nCONTENT:\n${a.content}\n`;
60
+ }).join('\n---\n\n');
61
+ return {
62
+ text,
63
+ usage: { inputTokens: 0, outputTokens: 0 },
64
+ meta: { articles, urls_requested: urls.length, cap_chars: cap },
65
+ };
66
+ }
67
+ function parseFetchInput(input) {
68
+ if (!input || typeof input !== 'object') {
69
+ throw new Error('web_fetch requires input object');
70
+ }
71
+ const obj = input;
72
+ const urlsRaw = obj.urls;
73
+ if (!Array.isArray(urlsRaw)) {
74
+ throw new Error('web_fetch requires `urls: string[]`');
75
+ }
76
+ const urls = urlsRaw.filter((u) => typeof u === 'string');
77
+ if (urls.length === 0) {
78
+ throw new Error('web_fetch requires non-empty `urls: string[]`');
79
+ }
80
+ const maxChars = typeof obj.max_chars === 'number' ? obj.max_chars : undefined;
81
+ const maxPerArticleChars = typeof obj.max_per_article_chars === 'number' ? obj.max_per_article_chars : undefined;
82
+ return { urls, max_chars: maxChars, max_per_article_chars: maxPerArticleChars };
83
+ }
84
+ function stripHtmlToText(html) {
85
+ return html
86
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
87
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
88
+ .replace(/<noscript[\s\S]*?<\/noscript>/gi, '')
89
+ .replace(/<[^>]+>/g, ' ')
90
+ .replace(/&nbsp;/g, ' ')
91
+ .replace(/&amp;/g, '&')
92
+ .replace(/&lt;/g, '<')
93
+ .replace(/&gt;/g, '>')
94
+ .replace(/&quot;/g, '"')
95
+ .replace(/&#39;/g, "'")
96
+ .replace(/\s+/g, ' ')
97
+ .trim();
98
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsmarket/pipeline-runtime",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Runtime for executing PIPELINE.md workflows (multi-skill orchestration). Provider-agnostic (MiniMax, Claude, OpenAI).",
5
5
  "license": "MIT",
6
6
  "type": "module",