@bluecopa/harness 0.1.0-snapshot.99 → 2.0.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.
- package/dist/arc/index.d.ts +796 -0
- package/dist/arc/index.js +2863 -0
- package/dist/arc/index.js.map +1 -0
- package/dist/observability/otel.d.ts +36 -0
- package/dist/observability/otel.js +73 -0
- package/dist/observability/otel.js.map +1 -0
- package/dist/shared-types-DRxnerLT.d.ts +138 -0
- package/dist/skills/index.d.ts +67 -0
- package/dist/skills/index.js +282 -0
- package/dist/skills/index.js.map +1 -0
- package/package.json +11 -15
- package/dist/arc/app-adapter.d.ts +0 -101
- package/dist/arc/app-adapter.js +0 -312
- package/dist/arc/app-adapter.js.map +0 -1
- package/dist/arc/create-arc-agent.d.ts +0 -50
- package/dist/arc/create-arc-agent.js +0 -2926
- package/dist/arc/create-arc-agent.js.map +0 -1
- package/dist/arc/profile-builder.d.ts +0 -49
- package/dist/arc/profile-builder.js +0 -163
- package/dist/arc/profile-builder.js.map +0 -1
- package/dist/loop/vercel-agent-loop.d.ts +0 -99
- package/dist/loop/vercel-agent-loop.js +0 -308
- package/dist/loop/vercel-agent-loop.js.map +0 -1
- package/dist/types-g-3DvSSE.d.ts +0 -745
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import { P as ProfileConfig, d as ProfileDeclaration, e as AnyTool, f as ProcessProfile } from '../types-g-3DvSSE.js';
|
|
2
|
-
import 'zod';
|
|
3
|
-
import 'ai';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Profile builder — generates prompts and resolves tools from ProfileDeclarations.
|
|
7
|
-
*
|
|
8
|
-
* The core idea: profiles declare WHAT (signature, tools, background).
|
|
9
|
-
* This module generates the HOW (system prompts, tool objects).
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Generate a thread system prompt from a ProfileDeclaration.
|
|
14
|
-
*
|
|
15
|
-
* The prompt tells the thread:
|
|
16
|
-
* - What it is (name)
|
|
17
|
-
* - What it produces (signature)
|
|
18
|
-
* - What tools it has (enforced, not suggested)
|
|
19
|
-
* - Domain knowledge (background)
|
|
20
|
-
*/
|
|
21
|
-
declare function buildProfilePrompt(decl: ProfileDeclaration): string;
|
|
22
|
-
/**
|
|
23
|
-
* Generate an orchestrator system prompt from a set of profile declarations.
|
|
24
|
-
*
|
|
25
|
-
* The orchestrator sees profile names, signatures, and tool counts —
|
|
26
|
-
* enough to route correctly. No tool names, no delivery methods.
|
|
27
|
-
*
|
|
28
|
-
* @param profiles - The registered profiles
|
|
29
|
-
* @param preamble - Optional strategy preamble (phasing, rules, context).
|
|
30
|
-
* Composed with the auto-generated profile catalog.
|
|
31
|
-
*/
|
|
32
|
-
declare function buildOrchestratorPrompt(profiles: Record<string, ProfileConfig>, preamble?: string): string;
|
|
33
|
-
/**
|
|
34
|
-
* Resolve tool names to tool objects from the global tool registry.
|
|
35
|
-
* Returns only the tools listed in the declaration.
|
|
36
|
-
*/
|
|
37
|
-
declare function resolveProfileTools(toolNames: string[], globalTools: Record<string, AnyTool>): Record<string, AnyTool>;
|
|
38
|
-
/**
|
|
39
|
-
* Build a runtime ProcessProfile from a ProfileDeclaration.
|
|
40
|
-
* Generates the system prompt and resolves tool objects.
|
|
41
|
-
*/
|
|
42
|
-
declare function buildProcessProfile(decl: ProfileDeclaration, globalTools: Record<string, AnyTool>): ProcessProfile;
|
|
43
|
-
/**
|
|
44
|
-
* Resolve a ProfileConfig (declaration or legacy) into a ProcessProfile.
|
|
45
|
-
* Declarations are built; legacy profiles are passed through.
|
|
46
|
-
*/
|
|
47
|
-
declare function resolveProfile(config: ProfileConfig, globalTools: Record<string, AnyTool>): ProcessProfile;
|
|
48
|
-
|
|
49
|
-
export { buildOrchestratorPrompt, buildProcessProfile, buildProfilePrompt, resolveProfile, resolveProfileTools };
|
|
@@ -1,163 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
|
|
3
|
-
// src/arc/types.ts
|
|
4
|
-
function isProfileDeclaration(p) {
|
|
5
|
-
return "signature" in p && typeof p.signature === "string";
|
|
6
|
-
}
|
|
7
|
-
var FIELD_RE = /^(\w+)(?::(\w+)(\[\])?)(\?)?(?:\s*\(([^)]+)\))?$/;
|
|
8
|
-
function parseField(raw) {
|
|
9
|
-
const trimmed = raw.trim();
|
|
10
|
-
const match = trimmed.match(FIELD_RE);
|
|
11
|
-
if (!match) {
|
|
12
|
-
const name2 = trimmed.replace(/\?$/, "");
|
|
13
|
-
return {
|
|
14
|
-
name: name2,
|
|
15
|
-
type: "string",
|
|
16
|
-
isArray: false,
|
|
17
|
-
isOptional: trimmed.endsWith("?")
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
const [, name, typeStr, arrayMark, optionalMark, desc] = match;
|
|
21
|
-
const type = ["string", "number", "boolean"].includes(typeStr) ? typeStr : "string";
|
|
22
|
-
const field = {
|
|
23
|
-
name,
|
|
24
|
-
type,
|
|
25
|
-
isArray: arrayMark === "[]",
|
|
26
|
-
isOptional: optionalMark === "?"
|
|
27
|
-
};
|
|
28
|
-
if (desc) field.description = desc.trim();
|
|
29
|
-
return field;
|
|
30
|
-
}
|
|
31
|
-
function parseSignature(sig) {
|
|
32
|
-
const arrowIdx = sig.indexOf("->");
|
|
33
|
-
if (arrowIdx < 0) {
|
|
34
|
-
throw new Error(`Invalid signature: missing "->". Got: "${sig}"`);
|
|
35
|
-
}
|
|
36
|
-
const inputStr = sig.slice(0, arrowIdx).trim();
|
|
37
|
-
const outputStr = sig.slice(arrowIdx + 2).trim();
|
|
38
|
-
const inputs = inputStr.split(",").map((s) => s.trim()).filter(Boolean).map(parseField);
|
|
39
|
-
const outputs = outputStr.split(",").map((s) => s.trim()).filter(Boolean).map(parseField);
|
|
40
|
-
return { inputs, outputs };
|
|
41
|
-
}
|
|
42
|
-
function signatureToSchema(sig) {
|
|
43
|
-
const shape = {};
|
|
44
|
-
for (const field of sig.outputs) {
|
|
45
|
-
let base;
|
|
46
|
-
switch (field.type) {
|
|
47
|
-
case "number":
|
|
48
|
-
base = z.number();
|
|
49
|
-
break;
|
|
50
|
-
case "boolean":
|
|
51
|
-
base = z.boolean();
|
|
52
|
-
break;
|
|
53
|
-
default:
|
|
54
|
-
base = z.string();
|
|
55
|
-
break;
|
|
56
|
-
}
|
|
57
|
-
if (field.isArray) base = z.array(base);
|
|
58
|
-
if (field.description) base = base.describe(field.description);
|
|
59
|
-
if (field.isOptional) base = base.optional();
|
|
60
|
-
shape[field.name] = base;
|
|
61
|
-
}
|
|
62
|
-
return z.object(shape);
|
|
63
|
-
}
|
|
64
|
-
function isTypedSignature(sig) {
|
|
65
|
-
return /\b\w+:\w+/.test(sig);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// src/arc/profile-builder.ts
|
|
69
|
-
function buildProfilePrompt(decl) {
|
|
70
|
-
const [input, output] = decl.signature.split("->").map((s) => s.trim());
|
|
71
|
-
const lines = [
|
|
72
|
-
`You are a ${decl.name} thread.`,
|
|
73
|
-
`Your task: take ${input} and produce ${output}.`,
|
|
74
|
-
"",
|
|
75
|
-
`## Available tools`,
|
|
76
|
-
`You have access to: ${decl.tools.join(", ")}`,
|
|
77
|
-
"Use ONLY these tools. You cannot use any other tools.",
|
|
78
|
-
"If you have Skill Instructions below, follow them for delivery method and style."
|
|
79
|
-
];
|
|
80
|
-
if (decl.background) {
|
|
81
|
-
lines.push("", "## Background", decl.background);
|
|
82
|
-
}
|
|
83
|
-
return lines.join("\n");
|
|
84
|
-
}
|
|
85
|
-
function buildOrchestratorPrompt(profiles, preamble) {
|
|
86
|
-
const profileList = Object.entries(profiles).map(([name, p]) => {
|
|
87
|
-
if (isProfileDeclaration(p)) {
|
|
88
|
-
return `- **${name}** \u2014 ${p.signature} (tools: ${p.tools.length}, ${p.model || "medium"})`;
|
|
89
|
-
}
|
|
90
|
-
return `- **${name}**`;
|
|
91
|
-
}).join("\n");
|
|
92
|
-
const sections = [
|
|
93
|
-
"You are an orchestrator. Accomplish tasks by decomposing them into focused threads, delegating each to the right profile, and synthesizing results.",
|
|
94
|
-
"",
|
|
95
|
-
"## Workflow: Decompose \u2192 Delegate \u2192 Synthesize",
|
|
96
|
-
"",
|
|
97
|
-
"1. **Decompose**: Break the request into independent, focused sub-tasks.",
|
|
98
|
-
"2. **Delegate**: Dispatch each sub-task as a Thread call with the appropriate profile. Independent sub-tasks go in the SAME turn (parallel).",
|
|
99
|
-
"3. **Synthesize**: Combine thread results into a coherent response.",
|
|
100
|
-
"",
|
|
101
|
-
"## Profiles",
|
|
102
|
-
profileList,
|
|
103
|
-
"",
|
|
104
|
-
"## Thread actions",
|
|
105
|
-
"Describe WHAT to produce, not HOW. 2-5 sentences. Threads have tools and skill instructions \u2014 they know delivery methods.",
|
|
106
|
-
"ALWAYS set the profile parameter on every Thread call.",
|
|
107
|
-
"",
|
|
108
|
-
"## Concurrency",
|
|
109
|
-
"Dispatch at most 3 threads per turn. If more are needed, batch them.",
|
|
110
|
-
"",
|
|
111
|
-
"## Context passing",
|
|
112
|
-
"Threads automatically receive the user's current message and attachments as seed context. Focus action text on WHAT to produce \u2014 threads already know what the user asked and what files are available.",
|
|
113
|
-
"Use contextEpisodeIds to chain dependent threads: research threads first (parallel), then implementation threads with their episodeIds."
|
|
114
|
-
];
|
|
115
|
-
if (preamble) {
|
|
116
|
-
sections.splice(1, 0, "", preamble);
|
|
117
|
-
}
|
|
118
|
-
return sections.join("\n");
|
|
119
|
-
}
|
|
120
|
-
function resolveProfileTools(toolNames, globalTools) {
|
|
121
|
-
const resolved = {};
|
|
122
|
-
for (const name of toolNames) {
|
|
123
|
-
if (globalTools[name]) {
|
|
124
|
-
resolved[name] = globalTools[name];
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
return resolved;
|
|
128
|
-
}
|
|
129
|
-
function buildProcessProfile(decl, globalTools) {
|
|
130
|
-
const profile = {
|
|
131
|
-
systemPrompt: buildProfilePrompt(decl),
|
|
132
|
-
tools: resolveProfileTools(decl.tools, globalTools),
|
|
133
|
-
allowedToolNames: decl.tools
|
|
134
|
-
};
|
|
135
|
-
if (decl.model) profile.model = decl.model;
|
|
136
|
-
if (decl.maxSteps) profile.maxSteps = decl.maxSteps;
|
|
137
|
-
if (isTypedSignature(decl.signature)) {
|
|
138
|
-
const parsed = parseSignature(decl.signature);
|
|
139
|
-
if (parsed.outputs.length > 0) {
|
|
140
|
-
profile.outputSchema = signatureToSchema(parsed);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
if (decl.demos && decl.demos.length > 0) {
|
|
144
|
-
profile.demoMessages = decl.demos.flatMap((demo) => [
|
|
145
|
-
{ role: "user", content: Object.entries(demo.input).map(([k, v]) => `${k}: ${v}`).join("\n") },
|
|
146
|
-
{ role: "assistant", content: JSON.stringify(demo.output, null, 2) }
|
|
147
|
-
]);
|
|
148
|
-
}
|
|
149
|
-
return profile;
|
|
150
|
-
}
|
|
151
|
-
function resolveProfile(config, globalTools) {
|
|
152
|
-
if (isProfileDeclaration(config)) {
|
|
153
|
-
return buildProcessProfile(config, globalTools);
|
|
154
|
-
}
|
|
155
|
-
if (config.tools && !config.allowedToolNames) {
|
|
156
|
-
return { ...config, allowedToolNames: Object.keys(config.tools) };
|
|
157
|
-
}
|
|
158
|
-
return config;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
export { buildOrchestratorPrompt, buildProcessProfile, buildProfilePrompt, resolveProfile, resolveProfileTools };
|
|
162
|
-
//# sourceMappingURL=profile-builder.js.map
|
|
163
|
-
//# sourceMappingURL=profile-builder.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/arc/types.ts","../../src/arc/sig.ts","../../src/arc/profile-builder.ts"],"names":["name"],"mappings":";;;AA4RO,SAAS,qBAAqB,CAAA,EAA2C;AAC9E,EAAA,OAAO,WAAA,IAAe,CAAA,IAAK,OAAQ,CAAA,CAAyB,SAAA,KAAc,QAAA;AAC5E;ACpQA,IAAM,Q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A,EAAG;AAChC,IAAA,OAAO,mBAAA,CAAoB,QAAQ,WAAW,CAAA;AAAA,EAChD;AAEA,EAAA,IAAI,MAAA,CAAO,KAAA,IAAS,CAAC,MAAA,CAAO,gBAAA,EAAkB;AAC5C,IAAA,OAAO,EAAE,GAAG,MAAA,EAAQ,gBAAA,EAAkB,OAAO,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA,EAAE;AAAA,EAClE;AACA,EAAA,OAAO,MAAA;AACT","file":"profile-builder.js","sourcesContent":["// ── Re-exports from shared types ──\n\nexport type {\n Episode,\n EpisodeTrace,\n SessionMemo,\n LongTermMemory,\n EpisodeStore,\n SessionMemoStore,\n LongTermStore,\n AnyTool,\n} from './arc-types';\n\nexport { DEFAULT_MODEL_MAP, resolveModel } from './arc-types';\nexport type { ModelTier } from './arc-types';\n\nexport type {\n AgentMessage,\n ToolCallAction,\n ToolCallInfo,\n ToolResultInfo,\n ContentPart,\n AgentRunResult,\n StepUsage,\n} from '../agent/types';\nexport { getTextContent } from '../agent/types';\n\nexport type { ToolProvider, ToolResult } from '../interfaces/tool-provider';\nexport type { SandboxProvider } from '../interfaces/sandbox-provider';\nexport type { HarnessTelemetry } from '../observability/otel';\nexport type { HookRunner } from '../hooks/hook-runner';\nexport type { PermissionManager } from '../permissions/permission-manager';\nexport type { SkillManager } from '../skills/skill-manager';\n\n// ── Episode artifacts ──\n\nexport interface EpisodeArtifact {\n key: string; // e.g. 'error_output', 'modified_code', 'test_result'\n content: string; // verbatim extracted content\n}\n\n// ── Model factory ──\n\n/** Creates an ai-sdk LanguageModel from a model ID string. Defaults to anthropic(). */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ModelFactory = (modelId: string) => any;\n\n// ── Tool choice ──\n\n/** Static tool choice value for LLM calls. */\nexport type ToolChoiceValue = 'auto' | 'required' | 'none' | { type: 'tool'; toolName: string };\n\n/**\n * Tool choice configuration — static value or per-turn callback.\n *\n * As a callback, receives the turn/step number (0-indexed) and returns the choice for that turn.\n * This enables patterns like forcing tool use on the first turn only:\n * `(turn) => turn === 0 ? 'required' : 'auto'`\n */\nexport type ToolChoiceConfig = ToolChoiceValue | ((turn: number) => ToolChoiceValue);\n\n/** Resolve a ToolChoiceConfig to a concrete value for a given turn. */\nexport function resolveToolChoice(config: ToolChoiceConfig | undefined, turn: number): ToolChoiceValue {\n if (!config) return 'auto';\n return typeof config === 'function' ? config(turn) : config;\n}\n\n// ── ArcLoop v2 Config ──\n\nexport interface ArcLoopConfig {\n // Orchestrator\n /** Orchestrator model (default: 'claude-opus-4-6'). Accepts a model ID or tier name. */\n model?: string;\n /** Model tier mapping. Override to use different models for fast/medium/strong. */\n modelMap?: Record<import('./arc-types').ModelTier, string>;\n /** Model factory — creates an ai-sdk LanguageModel from a model ID. Defaults to anthropic(). */\n createModel?: ModelFactory;\n /** @deprecated Use createModel instead. Anthropic API key (set via ANTHROPIC_API_KEY env var). */\n apiKey?: string;\n /** Custom orchestrator system prompt */\n systemPrompt?: string;\n /** Max orchestrator turns before stopping (default: 30) */\n maxTurns?: number;\n /** Extra orchestrator tools beyond Thread/Check/Cancel/Remember */\n extraOrchestratorTools?: Record<string, import('./arc-types').AnyTool>;\n /** Handler for extra orchestrator tools. Return an AgentAction (typically FinalAction with directive). */\n onOrchestratorTool?: (name: string, args: Record<string, unknown>) => Promise<import('../agent/types').AgentAction>;\n /** Optional resilience policy applied to LLM calls (retry, circuit breaker, timeout, etc.). */\n resilience?: import('./resilience/types').ResiliencePolicy;\n\n /** Tool choice for orchestrator LLM calls. Supports per-turn callbacks. Default: 'auto'. */\n orchestratorToolChoice?: ToolChoiceConfig;\n /** Default tool choice for all processes. Individual profiles can override. Default: 'auto'. */\n processToolChoice?: ToolChoiceConfig;\n\n /** ResultPager for storing large tool results externally in processes. */\n resultPager?: import('./result-pager').ResultPager;\n /** Character threshold above which tool results are paged. Default: 4000. */\n resultPageThreshold?: number;\n /** Tool names to never page (e.g., ['Read', 'Edit']). */\n pagingExclude?: string[];\n /** Hard cap on tool result length (chars) when no resultPager is configured. Truncates with a note. */\n maxToolResultLength?: number;\n /** Structured facts injected into process system prompts (e.g., from long-term memory). */\n contextFacts?: string[];\n /** Max context tokens for worker threads. When set, stubs old tool results to keep within budget. */\n maxContextTokens?: number;\n /**\n * Seed context injected into every process as a system message.\n * Use this to pass the user's original request, attachment metadata,\n * or other context that threads need but the orchestrator may not include\n * in the Thread action text.\n */\n processSeedContext?: string | import('../agent/types').AgentMessage[];\n\n // Processes\n /** Per-process timeout in ms (default: 120_000) */\n processTimeout?: number;\n /** Per-process max steps (default: 20) */\n processMaxSteps?: number;\n /** Default system prompt for all processes (overrides the built-in default) */\n processSystemPrompt?: string;\n /** Named process profiles. Accepts ProfileDeclaration (new, declarative) or ProcessProfile (legacy). */\n processProfiles?: Record<string, ProfileConfig>;\n /** Tools available inside processes (default: builtinTools) */\n processTools?: Record<string, import('./arc-types').AnyTool>;\n\n // Context\n /** Context window size in tokens (default: 200_000) */\n contextWindowSize?: number;\n /** Tokens reserved for output (default: 20_000) */\n outputReserve?: number;\n /**\n * Enable dynamic context window detection via OpenRouter API.\n * When true, fetches model-specific context_length from OpenRouter.\n * Falls back to 128K tokens for unknown models.\n * Overrides contextWindowSize if both are set.\n * @default false\n */\n dynamicContextWindow?: boolean;\n\n // Stores (required)\n episodeStore: import('./arc-types').EpisodeStore;\n sessionMemoStore: import('./arc-types').SessionMemoStore;\n longTermStore: import('./arc-types').LongTermStore;\n\n // Identity (required)\n taskId: string;\n sessionId: string;\n\n // Memory\n /** Enable auto-memory detection and promotion (default: true) */\n autoMemory?: boolean;\n\n // Dependency injection\n /** Pre-built SkillResolver instance. If omitted, one is created from skillIndexPath (if provided). */\n skillResolver?: import('./skill-resolver').SkillResolver;\n\n // Tools & providers\n toolProvider: import('../interfaces/tool-provider').ToolProvider;\n /** Tool provider for skill-matched processes (sandbox) */\n skillToolProvider?: import('../interfaces/tool-provider').ToolProvider;\n /** Local directory to sync sandbox output artifacts to (default: './outputs') */\n localOutputDir?: string;\n\n // Runtime (passed through to processes)\n sandboxProvider?: import('../interfaces/sandbox-provider').SandboxProvider;\n skillManager?: import('../skills/skill-manager').SkillManager;\n skillIndexPath?: string;\n telemetry?: import('../observability/otel').HarnessTelemetry;\n hookRunner?: import('../hooks/hook-runner').HookRunner;\n permissionManager?: import('../permissions/permission-manager').PermissionManager;\n executeToolAction?: (action: import('../agent/types').ToolCallAction) => Promise<import('../interfaces/tool-provider').ToolResult | null>;\n}\n\n// ── Process types ──\n\nexport interface Process {\n id: string;\n action: string;\n model: string;\n status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';\n\n /** Outbox: observable stream of events from this process. */\n outbox: AsyncIterable<ProcessEvent>;\n\n /** Inbox: send messages or signals to a running process. */\n inbox: {\n send(message: import('../agent/types').AgentMessage): void;\n cancel(): void;\n };\n\n /** Result (available after completion). */\n result?: ProcessResult;\n}\n\nexport type ProcessEvent =\n | { type: 'activity'; activity: Activity }\n | { type: 'text_delta'; text: string }\n | { type: 'step_start'; step: number }\n | { type: 'step_end'; step: number; usage?: import('../agent/types').StepUsage }\n | { type: 'episode'; episode: import('./arc-types').Episode }\n | { type: 'done'; result: ProcessResult }\n | { type: 'failed'; error: string };\n\nexport interface ProcessResult {\n episode: import('./arc-types').Episode;\n trace: import('./arc-types').EpisodeTrace;\n artifacts: EpisodeArtifact[];\n success: boolean;\n durationMs: number;\n resolvedModel: string;\n error?: string;\n}\n\nexport interface ProcessRequest {\n action: string;\n contextEpisodeIds?: string[];\n model?: import('./arc-types').ModelTier;\n maxSteps?: number;\n label?: string;\n /** Named profile to use for this process (looked up from ArcLoopConfig.processProfiles). */\n profile?: string;\n}\n\n/**\n * ProfileDeclaration — typed, declarative profile definition.\n *\n * Replaces hand-written system prompts with structured declarations.\n * The system generates prompts from the declaration and enforces tool constraints.\n *\n * @example\n * const visual: ProfileDeclaration = {\n * name: 'visual',\n * signature: 'description -> compiledArtifact',\n * tools: ['CompileJsx', 'Read', 'ListFiles'],\n * skills: ['visual-explainer'],\n * };\n */\nexport interface ProfileDeclaration {\n /** Profile name (matches the Thread tool's profile parameter). */\n name: string;\n /** Typed signature: \"input -> output\". Describes what this profile produces. */\n signature: string;\n /** Tool names this profile can use. Only these tools are available — enforced at schema + executor level. */\n tools: string[];\n /** Domain knowledge injected into system prompt (skill content, color systems, etc.). */\n background?: string;\n /** Default model tier. */\n model?: import('./arc-types').ModelTier;\n /** Max LLM steps. */\n maxSteps?: number;\n /** Skill names this profile can use. SkillRouter is constrained to this set. Omit for all skills. */\n skills?: string[];\n /** Few-shot demonstration examples. Rendered as user/assistant message pairs in the prompt. */\n demos?: Array<{\n input: Record<string, string>;\n output: Record<string, unknown>;\n }>;\n}\n\n/** A named process profile — runtime form with resolved prompt and tools. */\nexport interface ProcessProfile {\n /** System prompt for processes using this profile. */\n systemPrompt: string;\n /** Tools available to processes using this profile (overrides processTools). */\n tools?: Record<string, import('./arc-types').AnyTool>;\n /** Default model tier for this profile (Thread tool's explicit model overrides this). */\n model?: import('./arc-types').ModelTier;\n /** Max steps for this profile (Thread tool's explicit maxSteps overrides this). */\n maxSteps?: number;\n /** Allowed tool names for executor-level validation (populated from ProfileDeclaration.tools). */\n allowedToolNames?: string[];\n /** Zod schema for structured output on the terminal step (generated from typed signatures). */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outputSchema?: import('zod').ZodObject<any>;\n /** Few-shot demo messages rendered before the task prompt. */\n demoMessages?: import('../agent/types').AgentMessage[];\n}\n\n/** A profile config can be either a declaration (new) or a raw ProcessProfile (backward compat). */\nexport type ProfileConfig = ProfileDeclaration | ProcessProfile;\n\n/** Type guard: check if a profile config is a declaration. */\nexport function isProfileDeclaration(p: ProfileConfig): p is ProfileDeclaration {\n return 'signature' in p && typeof (p as ProfileDeclaration).signature === 'string';\n}\n\nexport type Activity =\n | { type: 'tool_start'; name: string; args: Record<string, unknown>; ts: number }\n | { type: 'tool_end'; name: string; ok: boolean; ms: number; preview?: string; ts: number };\n\n// ── Context window types ──\n\nexport interface Turn {\n role: 'orchestrator' | 'process_result' | 'user';\n messages: import('../agent/types').AgentMessage[];\n tokenEstimate: number;\n timestamp: number;\n}\n\nexport interface TokenBudget {\n limit: number;\n used: number;\n layers: {\n system: number;\n memories: number;\n episodes: number;\n conversation: number;\n };\n}\n\nexport interface PreparedContext {\n messages: import('../agent/types').AgentMessage[];\n budget: TokenBudget;\n}\n\n// ── Compression types ──\n\nexport interface CompressInput {\n taskId: string;\n sessionId: string;\n index: number;\n threadAction: string;\n messages: import('../agent/types').AgentMessage[];\n model: string;\n parentEpisodeIds: string[];\n success: boolean;\n}\n\nexport interface CompressOutput {\n episode: import('./arc-types').Episode;\n trace: import('./arc-types').EpisodeTrace;\n artifacts: EpisodeArtifact[];\n}\n\n// ── Event protocol ──\n\nexport type ArcEvent =\n | { type: 'text_delta'; text: string }\n | { type: 'turn_start'; turn: number }\n | { type: 'turn_end'; turn: number }\n | { type: 'process_dispatched'; id: string; action: string; model: string; label?: string; profile?: string }\n | { type: 'thread_rejected'; action: string; reason: string }\n | { type: 'skill_resolved'; processId: string; skillName: string; skillPath: string }\n | { type: 'process_activity'; id: string; activity: Activity }\n | { type: 'process_text_delta'; id: string; text: string }\n | { type: 'process_step_start'; id: string; step: number }\n | { type: 'process_step_end'; id: string; step: number; usage?: import('../agent/types').StepUsage }\n | { type: 'process_completed'; id: string; episodeId: string; summary: string; durationMs: number }\n | { type: 'process_failed'; id: string; error: string }\n | { type: 'process_cancelled'; id: string }\n | { type: 'memory_stored'; id: string; content: string }\n | { type: 'context_compressed'; tier: 'template' | 'episode_group' | 'llm'; tokensSaved: number }\n | { type: 'done'; output: string; stats: RunStats };\n\nexport interface RunStats {\n turns: number;\n processes: number;\n durationMs: number;\n}\n\nexport interface ArcRunResult {\n output: string;\n events: ArcEvent[];\n}\n\n// ── Trace types (for Stateright verification bridge) ──\n\nexport interface TraceEvent {\n ts: number;\n kind: TraceEventKind;\n}\n\nexport type TraceEventKind =\n | { type: 'turn_start'; turn: number }\n | { type: 'turn_end'; turn: number }\n | { type: 'llm_call_start' }\n | { type: 'llm_call_end'; response_type: string }\n | { type: 'process_created'; id: string; status: string }\n | { type: 'process_transition'; id: string; from: string; to: string }\n | { type: 'tool_call'; tool: string; process_id?: string }\n | { type: 'context_prepare'; used: number; limit: number; compression_tier: string }\n | { type: 'abort_signal'; target?: string }\n | { type: 'done' };\n","/**\n * DSPy-style signature parsing and schema generation.\n *\n * Parses signature strings like \"question:string -> evidence:string[], confidence:number\"\n * into typed field definitions, and generates Zod schemas for structured output.\n */\n\nimport { z } from 'zod';\n\n// ── Types ──\n\nexport interface SignatureField {\n name: string;\n type: 'string' | 'number' | 'boolean';\n isArray: boolean;\n isOptional: boolean;\n description?: string;\n}\n\nexport interface ParsedSignature {\n inputs: SignatureField[];\n outputs: SignatureField[];\n}\n\n// ── Parser ──\n\nconst FIELD_RE = /^(\\w+)(?::(\\w+)(\\[\\])?)(\\?)?(?:\\s*\\(([^)]+)\\))?$/;\n\nfunction parseField(raw: string): SignatureField {\n const trimmed = raw.trim();\n const match = trimmed.match(FIELD_RE);\n\n if (!match) {\n // Bare field name — default to string\n const name = trimmed.replace(/\\?$/, '');\n return {\n name,\n type: 'string',\n isArray: false,\n isOptional: trimmed.endsWith('?'),\n };\n }\n\n const [, name, typeStr, arrayMark, optionalMark, desc] = match;\n const type = (['string', 'number', 'boolean'].includes(typeStr!) ? typeStr : 'string') as SignatureField['type'];\n\n const field: SignatureField = {\n name: name!,\n type,\n isArray: arrayMark === '[]',\n isOptional: optionalMark === '?',\n };\n if (desc) field.description = desc.trim();\n return field;\n}\n\n/**\n * Parse a signature string into typed input/output fields.\n *\n * @example\n * parseSignature('question:string -> evidence:string[], confidence:number')\n * // { inputs: [{ name: 'question', type: 'string', ... }],\n * // outputs: [{ name: 'evidence', type: 'string', isArray: true, ... },\n * // { name: 'confidence', type: 'number', ... }] }\n *\n * parseSignature('query -> findings')\n * // All fields default to type 'string', isArray false\n */\nexport function parseSignature(sig: string): ParsedSignature {\n const arrowIdx = sig.indexOf('->');\n if (arrowIdx < 0) {\n throw new Error(`Invalid signature: missing \"->\". Got: \"${sig}\"`);\n }\n\n const inputStr = sig.slice(0, arrowIdx).trim();\n const outputStr = sig.slice(arrowIdx + 2).trim();\n\n const inputs = inputStr.split(',').map(s => s.trim()).filter(Boolean).map(parseField);\n const outputs = outputStr.split(',').map(s => s.trim()).filter(Boolean).map(parseField);\n\n return { inputs, outputs };\n}\n\n// ── Schema generation ──\n\n/**\n * Convert a parsed signature's output fields into a Zod schema.\n * Used with ai-sdk's generateObject() for structured output extraction.\n */\nexport function signatureToSchema(sig: ParsedSignature): z.ZodObject<Record<string, z.ZodTypeAny>> {\n const shape: Record<string, z.ZodTypeAny> = {};\n\n for (const field of sig.outputs) {\n let base: z.ZodTypeAny;\n switch (field.type) {\n case 'number': base = z.number(); break;\n case 'boolean': base = z.boolean(); break;\n default: base = z.string(); break;\n }\n if (field.isArray) base = z.array(base);\n if (field.description) base = base.describe(field.description);\n if (field.isOptional) base = base.optional();\n shape[field.name] = base;\n }\n\n return z.object(shape);\n}\n\n/**\n * Check if a signature string has typed fields (contains ':').\n * Untyped signatures like 'query -> findings' are treated as cosmetic labels.\n */\nexport function isTypedSignature(sig: string): boolean {\n return /\\b\\w+:\\w+/.test(sig);\n}\n","/**\n * Profile builder — generates prompts and resolves tools from ProfileDeclarations.\n *\n * The core idea: profiles declare WHAT (signature, tools, background).\n * This module generates the HOW (system prompts, tool objects).\n */\n\nimport type { AnyTool } from './arc-types';\nimport type { ProfileDeclaration, ProcessProfile, ProfileConfig } from './types';\nimport { isProfileDeclaration } from './types';\nimport { parseSignature, signatureToSchema, isTypedSignature } from './sig';\n\n// ── Thread prompt generation ────────────────────────────────────\n\n/**\n * Generate a thread system prompt from a ProfileDeclaration.\n *\n * The prompt tells the thread:\n * - What it is (name)\n * - What it produces (signature)\n * - What tools it has (enforced, not suggested)\n * - Domain knowledge (background)\n */\nexport function buildProfilePrompt(decl: ProfileDeclaration): string {\n const [input, output] = decl.signature.split('->').map(s => s.trim());\n const lines = [\n `You are a ${decl.name} thread.`,\n `Your task: take ${input} and produce ${output}.`,\n '',\n `## Available tools`,\n `You have access to: ${decl.tools.join(', ')}`,\n 'Use ONLY these tools. You cannot use any other tools.',\n 'If you have Skill Instructions below, follow them for delivery method and style.',\n ];\n\n if (decl.background) {\n lines.push('', '## Background', decl.background);\n }\n\n return lines.join('\\n');\n}\n\n// ── Orchestrator prompt generation ──────────────────────────────\n\n/**\n * Generate an orchestrator system prompt from a set of profile declarations.\n *\n * The orchestrator sees profile names, signatures, and tool counts —\n * enough to route correctly. No tool names, no delivery methods.\n *\n * @param profiles - The registered profiles\n * @param preamble - Optional strategy preamble (phasing, rules, context).\n * Composed with the auto-generated profile catalog.\n */\nexport function buildOrchestratorPrompt(\n profiles: Record<string, ProfileConfig>,\n preamble?: string,\n): string {\n const profileList = Object.entries(profiles)\n .map(([name, p]) => {\n if (isProfileDeclaration(p)) {\n return `- **${name}** — ${p.signature} (tools: ${p.tools.length}, ${p.model || 'medium'})`;\n }\n // Legacy ProcessProfile — show name only\n return `- **${name}**`;\n })\n .join('\\n');\n\n const sections = [\n 'You are an orchestrator. Accomplish tasks by decomposing them into focused threads, delegating each to the right profile, and synthesizing results.',\n '',\n '## Workflow: Decompose → Delegate → Synthesize',\n '',\n '1. **Decompose**: Break the request into independent, focused sub-tasks.',\n '2. **Delegate**: Dispatch each sub-task as a Thread call with the appropriate profile. Independent sub-tasks go in the SAME turn (parallel).',\n '3. **Synthesize**: Combine thread results into a coherent response.',\n '',\n '## Profiles',\n profileList,\n '',\n '## Thread actions',\n 'Describe WHAT to produce, not HOW. 2-5 sentences. Threads have tools and skill instructions — they know delivery methods.',\n 'ALWAYS set the profile parameter on every Thread call.',\n '',\n '## Concurrency',\n 'Dispatch at most 3 threads per turn. If more are needed, batch them.',\n '',\n '## Context passing',\n 'Threads automatically receive the user\\'s current message and attachments as seed context. Focus action text on WHAT to produce — threads already know what the user asked and what files are available.',\n 'Use contextEpisodeIds to chain dependent threads: research threads first (parallel), then implementation threads with their episodeIds.',\n ];\n\n if (preamble) {\n // Insert preamble after the identity line\n sections.splice(1, 0, '', preamble);\n }\n\n return sections.join('\\n');\n}\n\n// ── Tool resolution ─────────────────────────────────────────────\n\n/**\n * Resolve tool names to tool objects from the global tool registry.\n * Returns only the tools listed in the declaration.\n */\nexport function resolveProfileTools(\n toolNames: string[],\n globalTools: Record<string, AnyTool>,\n): Record<string, AnyTool> {\n const resolved: Record<string, AnyTool> = {};\n for (const name of toolNames) {\n if (globalTools[name]) {\n resolved[name] = globalTools[name];\n }\n }\n return resolved;\n}\n\n// ── ProfileDeclaration → ProcessProfile conversion ──────────────\n\n/**\n * Build a runtime ProcessProfile from a ProfileDeclaration.\n * Generates the system prompt and resolves tool objects.\n */\nexport function buildProcessProfile(\n decl: ProfileDeclaration,\n globalTools: Record<string, AnyTool>,\n): ProcessProfile {\n const profile: ProcessProfile = {\n systemPrompt: buildProfilePrompt(decl),\n tools: resolveProfileTools(decl.tools, globalTools),\n allowedToolNames: decl.tools,\n };\n if (decl.model) profile.model = decl.model;\n if (decl.maxSteps) profile.maxSteps = decl.maxSteps;\n // Generate output schema from typed signatures (e.g., 'question:string -> evidence:string[]')\n if (isTypedSignature(decl.signature)) {\n const parsed = parseSignature(decl.signature);\n if (parsed.outputs.length > 0) {\n profile.outputSchema = signatureToSchema(parsed);\n }\n }\n // Render demos as user/assistant message pairs\n if (decl.demos && decl.demos.length > 0) {\n profile.demoMessages = decl.demos.flatMap(demo => [\n { role: 'user' as const, content: Object.entries(demo.input).map(([k, v]) => `${k}: ${v}`).join('\\n') },\n { role: 'assistant' as const, content: JSON.stringify(demo.output, null, 2) },\n ]);\n }\n return profile;\n}\n\n/**\n * Resolve a ProfileConfig (declaration or legacy) into a ProcessProfile.\n * Declarations are built; legacy profiles are passed through.\n */\nexport function resolveProfile(\n config: ProfileConfig,\n globalTools: Record<string, AnyTool>,\n): ProcessProfile {\n if (isProfileDeclaration(config)) {\n return buildProcessProfile(config, globalTools);\n }\n // Backfill allowedToolNames for legacy profiles when tools are defined\n if (config.tools && !config.allowedToolNames) {\n return { ...config, allowedToolNames: Object.keys(config.tools) };\n }\n return config;\n}\n"]}
|
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import { Tool } from 'ai';
|
|
2
|
-
import { g as AgentLoop, S as StepUsage, M as ModelFactory, h as ToolChoiceConfig, i as PrepareStepContext, j as PrepareStepResult, b as AgentMessage, k as AgentAction, l as AgentStreamEvent } from '../types-g-3DvSSE.js';
|
|
3
|
-
import 'zod';
|
|
4
|
-
|
|
5
|
-
type AnyTool = Tool<any, any>;
|
|
6
|
-
/** Built-in tool schemas. Merge with custom tools: `{ ...builtinTools, ...myTools }` */
|
|
7
|
-
declare const builtinTools: {
|
|
8
|
-
Bash: Tool<{
|
|
9
|
-
command: string;
|
|
10
|
-
cwd?: string | undefined;
|
|
11
|
-
timeout?: number | undefined;
|
|
12
|
-
}, never>;
|
|
13
|
-
Read: Tool<{
|
|
14
|
-
path: string;
|
|
15
|
-
}, never>;
|
|
16
|
-
Write: Tool<{
|
|
17
|
-
path: string;
|
|
18
|
-
content: string;
|
|
19
|
-
}, never>;
|
|
20
|
-
Edit: Tool<{
|
|
21
|
-
path: string;
|
|
22
|
-
old_text: string;
|
|
23
|
-
new_text: string;
|
|
24
|
-
}, never>;
|
|
25
|
-
Glob: Tool<{
|
|
26
|
-
pattern: string;
|
|
27
|
-
}, never>;
|
|
28
|
-
Grep: Tool<{
|
|
29
|
-
pattern: string;
|
|
30
|
-
path?: string | undefined;
|
|
31
|
-
}, never>;
|
|
32
|
-
WebFetch: Tool<{
|
|
33
|
-
url: string;
|
|
34
|
-
selector?: string | undefined;
|
|
35
|
-
maxContentLength?: number | undefined;
|
|
36
|
-
}, never>;
|
|
37
|
-
WebSearch: Tool<{
|
|
38
|
-
query: string;
|
|
39
|
-
}, never>;
|
|
40
|
-
AskUser: Tool<{
|
|
41
|
-
question: string;
|
|
42
|
-
options?: string[] | undefined;
|
|
43
|
-
}, never>;
|
|
44
|
-
TellUser: Tool<{
|
|
45
|
-
message: string;
|
|
46
|
-
}, never>;
|
|
47
|
-
DownloadRawFile: Tool<{
|
|
48
|
-
path: string;
|
|
49
|
-
}, never>;
|
|
50
|
-
};
|
|
51
|
-
/** A system prompt block with optional Anthropic cache control. */
|
|
52
|
-
interface SystemPromptBlock {
|
|
53
|
-
text: string;
|
|
54
|
-
cacheControl?: {
|
|
55
|
-
type: 'ephemeral';
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
interface VercelAgentLoopConfig {
|
|
59
|
-
model?: string;
|
|
60
|
-
/** System prompt — string or structured blocks with cache control markers. */
|
|
61
|
-
systemPrompt?: string | SystemPromptBlock[];
|
|
62
|
-
createModel?: ModelFactory;
|
|
63
|
-
/** @deprecated Prefer createModel. */
|
|
64
|
-
apiKey?: string;
|
|
65
|
-
/** Custom tool definitions. If provided, replaces built-in agentTools for LLM calls. */
|
|
66
|
-
tools?: Record<string, AnyTool>;
|
|
67
|
-
/** Tool choice for LLM calls. Supports per-turn callbacks. Default: 'auto'. */
|
|
68
|
-
toolChoice?: ToolChoiceConfig;
|
|
69
|
-
/** Provider options passed to generateText/streamText (e.g. anthropic thinking config). */
|
|
70
|
-
providerOptions?: Record<string, unknown>;
|
|
71
|
-
/** Per-step callback to override model and active tools before each LLM call. */
|
|
72
|
-
prepareStep?: (context: PrepareStepContext) => PrepareStepResult | void;
|
|
73
|
-
}
|
|
74
|
-
declare class VercelAgentLoop implements AgentLoop {
|
|
75
|
-
private readonly model;
|
|
76
|
-
private readonly createModel;
|
|
77
|
-
private readonly systemPrompt;
|
|
78
|
-
private readonly tools;
|
|
79
|
-
private readonly validToolNames;
|
|
80
|
-
private readonly toolChoiceConfig;
|
|
81
|
-
private readonly providerOptions;
|
|
82
|
-
private readonly prepareStep;
|
|
83
|
-
/** Track tool names called across steps for prepareStep context. */
|
|
84
|
-
private toolCallHistory;
|
|
85
|
-
private step;
|
|
86
|
-
/** Last step's token usage — read after nextAction/streamAction completes. */
|
|
87
|
-
lastUsage: StepUsage | undefined;
|
|
88
|
-
constructor(config?: VercelAgentLoopConfig);
|
|
89
|
-
/** Build the `system` parameter for generateText/streamText. */
|
|
90
|
-
private buildSystemParam;
|
|
91
|
-
/** Resolve model + tools for this step via prepareStep callback. */
|
|
92
|
-
private resolveStep;
|
|
93
|
-
/** Extract StepUsage from AI SDK usage object. */
|
|
94
|
-
private static extractUsage;
|
|
95
|
-
nextAction(messages: AgentMessage[]): Promise<AgentAction>;
|
|
96
|
-
streamAction(messages: AgentMessage[]): AsyncGenerator<AgentStreamEvent>;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export { type SystemPromptBlock, VercelAgentLoop, type VercelAgentLoopConfig, builtinTools };
|