@deepstrike/sdk 0.1.10 → 0.1.12

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 (40) hide show
  1. package/README.md +25 -0
  2. package/dist/agent.d.ts +10 -9
  3. package/dist/agent.js +64 -12
  4. package/dist/collaboration/contract.d.ts +55 -0
  5. package/dist/collaboration/contract.js +65 -0
  6. package/dist/collaboration/handoff.d.ts +79 -0
  7. package/dist/collaboration/handoff.js +98 -0
  8. package/dist/collaboration/harness.d.ts +55 -0
  9. package/dist/collaboration/harness.js +150 -0
  10. package/dist/collaboration/index.d.ts +10 -0
  11. package/dist/collaboration/index.js +9 -0
  12. package/dist/collaboration/modes/creator-verifier.d.ts +69 -0
  13. package/dist/collaboration/modes/creator-verifier.js +124 -0
  14. package/dist/collaboration/pool.d.ts +46 -0
  15. package/dist/collaboration/pool.js +80 -0
  16. package/dist/harness/harness.js +7 -1
  17. package/dist/index.d.ts +12 -2
  18. package/dist/index.js +5 -0
  19. package/dist/kernel.d.ts +5 -2
  20. package/dist/memory/protocols.d.ts +8 -1
  21. package/dist/providers/anthropic.d.ts +3 -3
  22. package/dist/providers/anthropic.js +9 -9
  23. package/dist/providers/base.d.ts +7 -4
  24. package/dist/providers/base.js +41 -38
  25. package/dist/providers/deepseek.d.ts +2 -2
  26. package/dist/providers/deepseek.js +2 -2
  27. package/dist/providers/gemini.d.ts +3 -3
  28. package/dist/providers/gemini.js +8 -13
  29. package/dist/providers/ollama.d.ts +3 -3
  30. package/dist/providers/ollama.js +12 -8
  31. package/dist/providers/openai-chat.d.ts +2 -2
  32. package/dist/providers/openai-chat.js +6 -4
  33. package/dist/providers/openai-responses.d.ts +5 -5
  34. package/dist/providers/openai-responses.js +13 -19
  35. package/dist/providers/openai.d.ts +3 -3
  36. package/dist/providers/openai.js +4 -4
  37. package/dist/providers/qwen.d.ts +3 -3
  38. package/dist/providers/qwen.js +4 -4
  39. package/dist/types.d.ts +12 -2
  40. package/package.json +2 -2
@@ -0,0 +1,150 @@
1
+ import { formatContractForSystemPrompt, contractToCriteriaStrings } from "./contract.js";
2
+ import { HandoffBus } from "./handoff.js";
3
+ /**
4
+ * ContractDrivenHarness — the core multi-agent execution primitive.
5
+ *
6
+ * Differs from HarnessLoop in three ways:
7
+ * 1. Executor and verifier are **separate Agent instances** — no shared history.
8
+ * 2. Verifier receives only the artifact + contract, not the implementation transcript.
9
+ * 3. Feedback returned to the executor is a structured list of Violations,
10
+ * not a free-text LLM summary.
11
+ *
12
+ * Protocol per attempt:
13
+ * executor.run(goal, contract) → artifact
14
+ * verifier.runIsolated(artifact, contract) → audit text
15
+ * parse audit text → ContractCheckResult[]
16
+ * all required criteria pass → Done
17
+ * violations remain → inject only violation list into next executor goal
18
+ * maxAttempts exceeded → produce HandoffArtifact with blocked_on
19
+ */
20
+ export class ContractDrivenHarness {
21
+ pool;
22
+ contract;
23
+ maxAttempts;
24
+ onViolation;
25
+ constructor(pool, contract, options = {}) {
26
+ this.pool = pool;
27
+ this.contract = contract;
28
+ this.maxAttempts = options.maxAttempts ?? 3;
29
+ this.onViolation = options.onViolation;
30
+ }
31
+ async run() {
32
+ let artifact = "";
33
+ let checkResults = [];
34
+ let attemptsUsed = 0;
35
+ let currentGoal = this.contract.goal;
36
+ for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
37
+ attemptsUsed = attempt;
38
+ // ── Phase 1: Executor ──────────────────────────────────────────────────
39
+ // Executor sees: contract block + goal. No verifier history.
40
+ const contractBlock = formatContractForSystemPrompt(this.contract);
41
+ const violationNote = attempt > 1
42
+ ? `\n\n[Previous attempt failed. Violations to fix:\n${this._formatViolationsForFeedback(checkResults)}]`
43
+ : "";
44
+ const executorGoal = `${contractBlock}\n\n---\n\n${currentGoal}${violationNote}`;
45
+ artifact = await this.pool.get("executor").run(executorGoal, contractToCriteriaStrings(this.contract));
46
+ // ── Phase 2: Verifier ──────────────────────────────────────────────────
47
+ // Verifier sees: artifact + contract only. No executor history.
48
+ const auditText = await this.pool.runVerifier({ contract: this.contract, artifact });
49
+ // ── Phase 3: Parse audit → ContractCheckResult[] ──────────────────────
50
+ checkResults = this._parseAuditText(auditText);
51
+ const violations = this._findViolations(checkResults);
52
+ if (violations.length === 0) {
53
+ // All required criteria passed
54
+ return {
55
+ success: true,
56
+ artifact,
57
+ checkResults,
58
+ attemptsUsed,
59
+ totalTokensConsumed: 0,
60
+ handoff: HandoffBus.fromContractOutcome({
61
+ contract: this.contract,
62
+ checkResults,
63
+ artifact,
64
+ success: true,
65
+ }),
66
+ };
67
+ }
68
+ this.onViolation?.(violations);
69
+ }
70
+ // Max attempts exhausted
71
+ const blockedOn = this._findViolations(checkResults).map(v => `[${v.criterionId}] ${v.text}: ${v.detail}`);
72
+ return {
73
+ success: false,
74
+ artifact,
75
+ checkResults,
76
+ attemptsUsed,
77
+ totalTokensConsumed: 0,
78
+ handoff: HandoffBus.fromContractOutcome({
79
+ contract: this.contract,
80
+ checkResults,
81
+ artifact,
82
+ success: false,
83
+ blockedOn,
84
+ }),
85
+ };
86
+ }
87
+ _findViolations(results) {
88
+ const violations = [];
89
+ for (const result of results) {
90
+ if (!result.passed) {
91
+ const criterion = this.contract.acceptance.find(c => c.id === result.criterionId);
92
+ if (criterion?.required) {
93
+ violations.push({
94
+ criterionId: result.criterionId,
95
+ text: criterion.text,
96
+ detail: result.evidence ?? "no evidence provided",
97
+ });
98
+ }
99
+ }
100
+ }
101
+ return violations;
102
+ }
103
+ _formatViolationsForFeedback(results) {
104
+ return this._findViolations(results)
105
+ .map(v => `- [${v.criterionId}] ${v.text}: ${v.detail}`)
106
+ .join("\n");
107
+ }
108
+ /**
109
+ * Parse the verifier's free-text audit into structured ContractCheckResult[].
110
+ *
111
+ * The verifier is prompted to produce a structured PASS/FAIL per criterion.
112
+ * This parser handles the common patterns; callers can subclass and override
113
+ * for stricter parsing.
114
+ */
115
+ _parseAuditText(auditText) {
116
+ const results = [];
117
+ const lower = auditText.toLowerCase();
118
+ for (const criterion of this.contract.acceptance) {
119
+ // Look for explicit "id: PASS" or "id: FAIL" patterns from the verifier prompt
120
+ const idPattern = new RegExp(`\\b${criterion.id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b[^\\n]*?(pass|fail)`, "i");
121
+ const match = auditText.match(idPattern);
122
+ if (match) {
123
+ const passed = match[1].toLowerCase() === "pass";
124
+ // Extract the line as evidence
125
+ const lineStart = auditText.lastIndexOf("\n", match.index ?? 0) + 1;
126
+ const lineEnd = auditText.indexOf("\n", match.index ?? 0);
127
+ const evidence = auditText.slice(lineStart, lineEnd > 0 ? lineEnd : undefined).trim();
128
+ results.push({ criterionId: criterion.id, passed, evidence });
129
+ }
130
+ else {
131
+ // Fallback: search for criterion text near PASS/FAIL keywords
132
+ const textIdx = lower.indexOf(criterion.text.toLowerCase().slice(0, 30));
133
+ if (textIdx !== -1) {
134
+ const window = lower.slice(textIdx, textIdx + 200);
135
+ const passed = window.includes("pass") && !window.includes("fail");
136
+ results.push({ criterionId: criterion.id, passed, evidence: "inferred from context" });
137
+ }
138
+ else {
139
+ // No mention found — conservative: treat as failed
140
+ results.push({
141
+ criterionId: criterion.id,
142
+ passed: false,
143
+ evidence: "criterion not mentioned in audit",
144
+ });
145
+ }
146
+ }
147
+ }
148
+ return results;
149
+ }
150
+ }
@@ -0,0 +1,10 @@
1
+ export type { AcceptanceCriterion, VerificationContract, ContractCheckResult, } from "./contract.js";
2
+ export { ContractBuilder, formatContractForSystemPrompt, contractToCriteriaStrings, } from "./contract.js";
3
+ export { AgentPool } from "./pool.js";
4
+ export type { AgentRole, IsolatedVerifierContext } from "./pool.js";
5
+ export { ContractDrivenHarness } from "./harness.js";
6
+ export type { ContractOutcome, ContractHarnessOptions, Violation, } from "./harness.js";
7
+ export { HandoffBus } from "./handoff.js";
8
+ export type { HandoffArtifact, ContractOutcomeInput } from "./handoff.js";
9
+ export { CreatorVerifierMode, OrchestrationMode } from "./modes/creator-verifier.js";
10
+ export type { CreatorVerifierMetrics } from "./modes/creator-verifier.js";
@@ -0,0 +1,9 @@
1
+ export { ContractBuilder, formatContractForSystemPrompt, contractToCriteriaStrings, } from "./contract.js";
2
+ // AgentPool
3
+ export { AgentPool } from "./pool.js";
4
+ // ContractDrivenHarness
5
+ export { ContractDrivenHarness } from "./harness.js";
6
+ // HandoffBus
7
+ export { HandoffBus } from "./handoff.js";
8
+ // Collaboration modes
9
+ export { CreatorVerifierMode, OrchestrationMode } from "./modes/creator-verifier.js";
@@ -0,0 +1,69 @@
1
+ import type { AgentPool } from "../pool.js";
2
+ import type { VerificationContract } from "../contract.js";
3
+ import type { ContractOutcome } from "../harness.js";
4
+ export interface CreatorVerifierMetrics {
5
+ total: number;
6
+ failed: number;
7
+ driftRate: number;
8
+ }
9
+ /**
10
+ * CreatorVerifierMode — the simplest multi-agent collaboration pattern.
11
+ *
12
+ * Wires an executor + verifier from an AgentPool into a ContractDrivenHarness.
13
+ * The executor creates, the verifier audits. Contexts are fully isolated.
14
+ *
15
+ * Usage:
16
+ * ```ts
17
+ * const pool = new AgentPool()
18
+ * .add("executor", new Agent(provider, { maxTokens: 32_000, skillDir }))
19
+ * .add("verifier", new Agent(provider, { maxTokens: 8_000 }))
20
+ *
21
+ * const mode = new CreatorVerifierMode(pool)
22
+ * const result = await mode.run(contract)
23
+ *
24
+ * if (HandoffBus.requiresEscalation(result.handoff)) {
25
+ * // drift > 5% or blocked_on is non-empty → pause autonomous delegation
26
+ * }
27
+ * ```
28
+ */
29
+ export declare class CreatorVerifierMode {
30
+ private pool;
31
+ private options;
32
+ private _total;
33
+ private _failed;
34
+ constructor(pool: AgentPool, options?: {
35
+ maxAttempts?: number;
36
+ });
37
+ run(contract: VerificationContract): Promise<ContractOutcome>;
38
+ /** Aggregate drift metrics across all runs through this mode instance. */
39
+ getMetrics(): CreatorVerifierMetrics;
40
+ /**
41
+ * True when accumulated drift rate exceeds threshold.
42
+ * When true, pause autonomous delegation and surface to human or orchestrator.
43
+ */
44
+ isDrifting(threshold?: number): boolean;
45
+ /** Reset accumulated metrics (e.g. at the start of a new sprint). */
46
+ resetMetrics(): void;
47
+ }
48
+ /**
49
+ * OrchestrationMode — three-role collaboration: orchestrator → executor → verifier.
50
+ *
51
+ * The orchestrator produces a VerificationContract from a raw goal, then
52
+ * CreatorVerifierMode executes it.
53
+ *
54
+ * Requires all three roles in the pool: orchestrator, executor, verifier.
55
+ */
56
+ export declare class OrchestrationMode {
57
+ private pool;
58
+ private options;
59
+ private inner;
60
+ constructor(pool: AgentPool, options?: {
61
+ maxAttempts?: number;
62
+ });
63
+ run(goal: string): Promise<ContractOutcome & {
64
+ contract: VerificationContract;
65
+ }>;
66
+ getMetrics(): CreatorVerifierMetrics;
67
+ isDrifting(threshold?: number): boolean;
68
+ private _parseContract;
69
+ }
@@ -0,0 +1,124 @@
1
+ import { ContractDrivenHarness } from "../harness.js";
2
+ /**
3
+ * CreatorVerifierMode — the simplest multi-agent collaboration pattern.
4
+ *
5
+ * Wires an executor + verifier from an AgentPool into a ContractDrivenHarness.
6
+ * The executor creates, the verifier audits. Contexts are fully isolated.
7
+ *
8
+ * Usage:
9
+ * ```ts
10
+ * const pool = new AgentPool()
11
+ * .add("executor", new Agent(provider, { maxTokens: 32_000, skillDir }))
12
+ * .add("verifier", new Agent(provider, { maxTokens: 8_000 }))
13
+ *
14
+ * const mode = new CreatorVerifierMode(pool)
15
+ * const result = await mode.run(contract)
16
+ *
17
+ * if (HandoffBus.requiresEscalation(result.handoff)) {
18
+ * // drift > 5% or blocked_on is non-empty → pause autonomous delegation
19
+ * }
20
+ * ```
21
+ */
22
+ export class CreatorVerifierMode {
23
+ pool;
24
+ options;
25
+ _total = 0;
26
+ _failed = 0;
27
+ constructor(pool, options = {}) {
28
+ this.pool = pool;
29
+ this.options = options;
30
+ }
31
+ async run(contract) {
32
+ this._total++;
33
+ const harness = new ContractDrivenHarness(this.pool, contract, {
34
+ maxAttempts: this.options.maxAttempts ?? 3,
35
+ });
36
+ const outcome = await harness.run();
37
+ if (!outcome.success) {
38
+ this._failed++;
39
+ }
40
+ return outcome;
41
+ }
42
+ /** Aggregate drift metrics across all runs through this mode instance. */
43
+ getMetrics() {
44
+ return {
45
+ total: this._total,
46
+ failed: this._failed,
47
+ driftRate: this._total > 0 ? this._failed / this._total : 0,
48
+ };
49
+ }
50
+ /**
51
+ * True when accumulated drift rate exceeds threshold.
52
+ * When true, pause autonomous delegation and surface to human or orchestrator.
53
+ */
54
+ isDrifting(threshold = 0.05) {
55
+ return this.getMetrics().driftRate > threshold;
56
+ }
57
+ /** Reset accumulated metrics (e.g. at the start of a new sprint). */
58
+ resetMetrics() {
59
+ this._total = 0;
60
+ this._failed = 0;
61
+ }
62
+ }
63
+ /**
64
+ * OrchestrationMode — three-role collaboration: orchestrator → executor → verifier.
65
+ *
66
+ * The orchestrator produces a VerificationContract from a raw goal, then
67
+ * CreatorVerifierMode executes it.
68
+ *
69
+ * Requires all three roles in the pool: orchestrator, executor, verifier.
70
+ */
71
+ export class OrchestrationMode {
72
+ pool;
73
+ options;
74
+ inner;
75
+ constructor(pool, options = {}) {
76
+ this.pool = pool;
77
+ this.options = options;
78
+ this.inner = new CreatorVerifierMode(pool, options);
79
+ }
80
+ async run(goal) {
81
+ // Step 1: orchestrator produces a VerificationContract
82
+ const contractJson = await this.pool.runOrchestrator(goal);
83
+ const contract = this._parseContract(contractJson, goal);
84
+ // Step 2: CreatorVerifierMode executes against the contract
85
+ const outcome = await this.inner.run(contract);
86
+ return { ...outcome, contract };
87
+ }
88
+ getMetrics() {
89
+ return this.inner.getMetrics();
90
+ }
91
+ isDrifting(threshold = 0.05) {
92
+ return this.inner.isDrifting(threshold);
93
+ }
94
+ _parseContract(json, fallbackGoal) {
95
+ try {
96
+ // Extract JSON block from markdown fences if present
97
+ const match = json.match(/```(?:json)?\s*([\s\S]*?)```/) ?? [null, json];
98
+ const raw = JSON.parse(match[1] ?? json);
99
+ return {
100
+ id: raw.id ?? "orchestrated",
101
+ goal: raw.goal ?? fallbackGoal,
102
+ acceptance: (raw.acceptance ?? []).map((c) => ({
103
+ id: String(c.id ?? "criterion"),
104
+ text: String(c.text ?? ""),
105
+ required: c.required !== false,
106
+ weight: Number(c.weight ?? 1.0),
107
+ machineCheckable: Boolean(c.machineCheckable ?? false),
108
+ })),
109
+ antiPatterns: (raw.antiPatterns ?? []).map(String),
110
+ evidenceRequired: (raw.evidenceRequired ?? []).map(String),
111
+ };
112
+ }
113
+ catch {
114
+ // Orchestrator produced unparseable output — return a minimal contract
115
+ return {
116
+ id: "fallback",
117
+ goal: fallbackGoal,
118
+ acceptance: [{ id: "complete", text: "Goal is satisfactorily completed", required: true, weight: 1.0, machineCheckable: false }],
119
+ antiPatterns: [],
120
+ evidenceRequired: [],
121
+ };
122
+ }
123
+ }
124
+ }
@@ -0,0 +1,46 @@
1
+ import type { Agent } from "../agent.js";
2
+ import type { VerificationContract } from "./contract.js";
3
+ /**
4
+ * Roles in a multi-agent collaboration.
5
+ *
6
+ * - orchestrator: strong-reasoning, produces VerificationContracts; no tools beyond planning
7
+ * - executor: code/task execution, full tool access, sees goal + contract only
8
+ * - verifier: adversarial auditor, no tools, low temperature, sees artifact + contract only
9
+ */
10
+ export type AgentRole = "orchestrator" | "executor" | "verifier";
11
+ /** Context passed to a verifier run — intentionally minimal. */
12
+ export interface IsolatedVerifierContext {
13
+ contract: VerificationContract;
14
+ /** The artifact produced by the executor. */
15
+ artifact: string;
16
+ }
17
+ /**
18
+ * AgentPool manages a set of role-specific Agent instances.
19
+ *
20
+ * Each role runs in its own Agent instance with an independent history partition,
21
+ * ensuring that the verifier never sees the executor's implementation transcript.
22
+ *
23
+ * Usage:
24
+ * ```ts
25
+ * const pool = new AgentPool()
26
+ * .add("executor", executorAgent)
27
+ * .add("verifier", verifierAgent)
28
+ * ```
29
+ */
30
+ export declare class AgentPool {
31
+ private agents;
32
+ add(role: AgentRole, agent: Agent): this;
33
+ has(role: AgentRole): boolean;
34
+ get(role: AgentRole): Agent;
35
+ /**
36
+ * Run the verifier with an isolated context — only the artifact and contract.
37
+ * The verifier does NOT receive the executor's conversation history.
38
+ * Returns a structured audit response as a plain string.
39
+ */
40
+ runVerifier(ctx: IsolatedVerifierContext): Promise<string>;
41
+ /**
42
+ * Run the orchestrator to decompose a high-level goal into a VerificationContract.
43
+ * The orchestrator receives the goal and must produce a structured contract in JSON.
44
+ */
45
+ runOrchestrator(goal: string): Promise<string>;
46
+ }
@@ -0,0 +1,80 @@
1
+ import { formatContractForSystemPrompt } from "./contract.js";
2
+ /**
3
+ * AgentPool manages a set of role-specific Agent instances.
4
+ *
5
+ * Each role runs in its own Agent instance with an independent history partition,
6
+ * ensuring that the verifier never sees the executor's implementation transcript.
7
+ *
8
+ * Usage:
9
+ * ```ts
10
+ * const pool = new AgentPool()
11
+ * .add("executor", executorAgent)
12
+ * .add("verifier", verifierAgent)
13
+ * ```
14
+ */
15
+ export class AgentPool {
16
+ agents = new Map();
17
+ add(role, agent) {
18
+ this.agents.set(role, agent);
19
+ return this;
20
+ }
21
+ has(role) {
22
+ return this.agents.has(role);
23
+ }
24
+ get(role) {
25
+ const agent = this.agents.get(role);
26
+ if (!agent)
27
+ throw new Error(`AgentPool: no agent registered for role "${role}"`);
28
+ return agent;
29
+ }
30
+ /**
31
+ * Run the verifier with an isolated context — only the artifact and contract.
32
+ * The verifier does NOT receive the executor's conversation history.
33
+ * Returns a structured audit response as a plain string.
34
+ */
35
+ async runVerifier(ctx) {
36
+ const agent = this.get("verifier");
37
+ const contractBlock = formatContractForSystemPrompt(ctx.contract);
38
+ const auditGoal = [
39
+ contractBlock,
40
+ "",
41
+ "---",
42
+ "",
43
+ "## Artifact to Audit",
44
+ "",
45
+ ctx.artifact,
46
+ "",
47
+ "---",
48
+ "",
49
+ "Audit the artifact against every criterion in the contract above.",
50
+ "For each criterion, state whether it PASSED or FAILED and cite specific evidence.",
51
+ "List any anti-patterns you detected.",
52
+ "Conclude with an overall PASS or FAIL verdict.",
53
+ ].join("\n");
54
+ return agent.run(auditGoal);
55
+ }
56
+ /**
57
+ * Run the orchestrator to decompose a high-level goal into a VerificationContract.
58
+ * The orchestrator receives the goal and must produce a structured contract in JSON.
59
+ */
60
+ async runOrchestrator(goal) {
61
+ const agent = this.get("orchestrator");
62
+ const orchestratorGoal = [
63
+ `You are a planning orchestrator. Decompose the following goal into a VerificationContract.`,
64
+ ``,
65
+ `Goal: ${goal}`,
66
+ ``,
67
+ `Produce a JSON object with this schema:`,
68
+ `{`,
69
+ ` "id": "<kebab-case-id>",`,
70
+ ` "goal": "<restated goal>",`,
71
+ ` "acceptance": [{ "id": "<id>", "text": "<criterion>", "required": true, "weight": 0.x, "machineCheckable": false }],`,
72
+ ` "antiPatterns": ["<pattern>"],`,
73
+ ` "evidenceRequired": ["<evidence item>"]`,
74
+ `}`,
75
+ ``,
76
+ `Output ONLY the JSON object, no prose.`,
77
+ ].join("\n");
78
+ return agent.run(orchestratorGoal);
79
+ }
80
+ }
@@ -92,7 +92,13 @@ export class HarnessLoop {
92
92
  if (evalAction.kind !== "evaluate")
93
93
  break;
94
94
  let evalText = "";
95
- for await (const evt of this.evalProvider.stream(evalAction.messages ?? [], [], undefined)) {
95
+ // Wrap harness eval messages in a RenderedContext (system messages → systemText, rest → turns).
96
+ const evalMsgs = evalAction.messages ?? [];
97
+ const evalContext = {
98
+ systemText: evalMsgs.filter((m) => m.role === "system").map((m) => m.content).join("\n\n"),
99
+ turns: evalMsgs.filter((m) => m.role !== "system"),
100
+ };
101
+ for await (const evt of this.evalProvider.stream(evalContext, [], undefined)) {
96
102
  if (evt.type === "text_delta")
97
103
  evalText += evt.delta;
98
104
  }
package/dist/index.d.ts CHANGED
@@ -20,7 +20,7 @@ export type { RegisteredTool } from "./tools/index.js";
20
20
  export { scanSkillDir, readSkillFile } from "./skills/loader.js";
21
21
  export type { SkillMetadata } from "./skills/loader.js";
22
22
  export { WorkingMemory } from "./memory/working.js";
23
- export type { DreamStore, DreamResult, SessionData, SessionMessage, MemoryEntry, CurationResult, CurationStats, } from "./memory/protocols.js";
23
+ export type { DreamStore, DreamResult, SessionStore, SessionData, SessionMessage, MemoryEntry, CurationResult, CurationStats, } from "./memory/protocols.js";
24
24
  export type { KnowledgeSource } from "./knowledge/source.js";
25
25
  export { SinglePassHarness, EvalLoopHarness, HarnessLoop } from "./harness/harness.js";
26
26
  export type { HarnessRequest, HarnessOutcome, HarnessLoopOptions, QualityGate } from "./harness/harness.js";
@@ -31,4 +31,14 @@ export { PermissionManager, PermissionMode } from "./safety/permissions.js";
31
31
  export type { PermissionDecision, Permission } from "./safety/permissions.js";
32
32
  export { Governance } from "./governance.js";
33
33
  export type { GovernanceVerdict } from "./governance.js";
34
- export type { Message, ToolCall, ToolResult, ToolSchema, ContentPart, TextPart, ImagePart, AudioPart, StreamEvent, TextDelta, ThinkingDelta, ToolCallEvent, ToolResultEvent, DoneEvent, ErrorEvent, PermissionRequestEvent, LLMProvider, RetryConfig, TokenUsage, ProviderToolSpec, ProviderRunState, } from "./types.js";
34
+ export type { Message, ToolCall, ToolResult, ToolSchema, ContentPart, TextPart, ImagePart, AudioPart, StreamEvent, TextDelta, ThinkingDelta, ToolCallEvent, ToolResultEvent, DoneEvent, ErrorEvent, PermissionRequestEvent, LLMProvider, RetryConfig, TokenUsage, ProviderToolSpec, ProviderRunState, RenderedContext, } from "./types.js";
35
+ export type { AcceptanceCriterion, VerificationContract, ContractCheckResult, } from "./collaboration/contract.js";
36
+ export { ContractBuilder, formatContractForSystemPrompt, contractToCriteriaStrings, } from "./collaboration/contract.js";
37
+ export { AgentPool } from "./collaboration/pool.js";
38
+ export type { AgentRole, IsolatedVerifierContext } from "./collaboration/pool.js";
39
+ export { ContractDrivenHarness } from "./collaboration/harness.js";
40
+ export type { ContractOutcome, ContractHarnessOptions, Violation } from "./collaboration/harness.js";
41
+ export { HandoffBus } from "./collaboration/handoff.js";
42
+ export type { HandoffArtifact, ContractOutcomeInput } from "./collaboration/handoff.js";
43
+ export { CreatorVerifierMode, OrchestrationMode } from "./collaboration/modes/creator-verifier.js";
44
+ export type { CreatorVerifierMetrics } from "./collaboration/modes/creator-verifier.js";
package/dist/index.js CHANGED
@@ -20,3 +20,8 @@ export { ScheduledPrompt } from "./signals/scheduled.js";
20
20
  export { SignalGateway } from "./signals/gateway.js";
21
21
  export { PermissionManager, PermissionMode } from "./safety/permissions.js";
22
22
  export { Governance } from "./governance.js";
23
+ export { ContractBuilder, formatContractForSystemPrompt, contractToCriteriaStrings, } from "./collaboration/contract.js";
24
+ export { AgentPool } from "./collaboration/pool.js";
25
+ export { ContractDrivenHarness } from "./collaboration/harness.js";
26
+ export { HandoffBus } from "./collaboration/handoff.js";
27
+ export { CreatorVerifierMode, OrchestrationMode } from "./collaboration/modes/creator-verifier.js";
package/dist/kernel.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Message, ToolCall, ToolResult, ToolSchema } from "./types.js";
1
+ import type { Message, RenderedContext, ToolCall, ToolResult, ToolSchema } from "./types.js";
2
2
  import type { SkillMetadata } from "./skills/loader.js";
3
3
  export interface GovernanceVerdict {
4
4
  kind: "allow" | "deny" | "rate_limited" | "ask_user";
@@ -28,7 +28,7 @@ export interface RuntimeSignal {
28
28
  }
29
29
  export interface LoopAction {
30
30
  kind: "call_llm" | "execute_tools" | "done";
31
- messages?: Message[];
31
+ context?: RenderedContext;
32
32
  tools?: ToolSchema[];
33
33
  calls?: ToolCall[];
34
34
  result?: {
@@ -48,6 +48,7 @@ interface LoopStateMachineInstance {
48
48
  setKnowledgeEnabled(enabled: boolean): void;
49
49
  addSystemMessage(content: string, tokens: number): void;
50
50
  addMemoryMessage(content: string, tokens: number): void;
51
+ addHistoryMessage(message: Message, tokens: number): void;
51
52
  setTools(tools: ToolSchema[]): void;
52
53
  start(task: {
53
54
  goal: string;
@@ -57,6 +58,8 @@ interface LoopStateMachineInstance {
57
58
  feedToolResults(results: ToolResult[]): LoopAction;
58
59
  feedTimeout(): LoopAction;
59
60
  isTerminal(): boolean;
61
+ preloadHistory(messages: Message[]): void;
62
+ drainNewMessages(): Message[];
60
63
  readonly turn: number;
61
64
  pressure(): number;
62
65
  takeObservations(): LoopObservation[];
@@ -1,7 +1,9 @@
1
- import type { Message } from "../types.js";
1
+ import type { Message, ContentPart } from "../types.js";
2
2
  export interface SessionMessage {
3
3
  role: Message["role"];
4
4
  content: string;
5
+ /** Structured multimodal parts. Preserved for round-trip fidelity (e.g. tool result messages). */
6
+ contentParts?: ContentPart[];
5
7
  tokenCount?: number;
6
8
  toolCalls?: Array<{
7
9
  id: string;
@@ -43,6 +45,11 @@ export interface DreamStore {
43
45
  /** Persist a completed session for future consolidation via `Agent.dream()`. */
44
46
  saveSession(data: SessionData): Promise<void>;
45
47
  }
48
+ /** Durable transcript storage for same-session conversational continuity. */
49
+ export interface SessionStore {
50
+ loadSession(sessionId: string): Promise<SessionData | undefined>;
51
+ saveSession(data: SessionData): Promise<void>;
52
+ }
46
53
  export interface DreamResult {
47
54
  sessionsProcessed: number;
48
55
  insightsExtracted: number;
@@ -1,4 +1,4 @@
1
- import type { Message, ToolSchema, StreamEvent, LLMProvider } from "../types.js";
1
+ import type { Message, RenderedContext, ToolSchema, StreamEvent, LLMProvider } from "../types.js";
2
2
  interface AnthropicProviderOptions {
3
3
  baseURL?: string;
4
4
  authMode?: "api-key" | "bearer";
@@ -15,8 +15,8 @@ export declare class AnthropicProvider implements LLMProvider {
15
15
  baseDelay: number;
16
16
  }, options?: AnthropicProviderOptions);
17
17
  private buildTools;
18
- complete(messages: Message[], tools: ToolSchema[]): Promise<Message>;
19
- stream(messages: Message[], tools: ToolSchema[], extensions?: Record<string, unknown>): AsyncIterable<StreamEvent>;
18
+ complete(context: RenderedContext, tools: ToolSchema[]): Promise<Message>;
19
+ stream(context: RenderedContext, tools: ToolSchema[], extensions?: Record<string, unknown>): AsyncIterable<StreamEvent>;
20
20
  private buildMessages;
21
21
  private rememberNativeBlocks;
22
22
  private assistantReplayKey;
@@ -1,6 +1,6 @@
1
1
  import Anthropic from "@anthropic-ai/sdk";
2
2
  import { withServerRuntimeGuard } from "../runtime/server.js";
3
- import { CircuitBreaker, normalizeToolCall, splitAnthropicSystem, toAnthropicMessages } from "./base.js";
3
+ import { CircuitBreaker, normalizeToolCall, toAnthropicMessages } from "./base.js";
4
4
  export class AnthropicProvider {
5
5
  model;
6
6
  client;
@@ -25,11 +25,11 @@ export class AnthropicProvider {
25
25
  input_schema: JSON.parse(t.parameters),
26
26
  }));
27
27
  }
28
- async complete(messages, tools) {
28
+ async complete(context, tools) {
29
29
  if (this.circuit.isOpen())
30
30
  throw new Error("Circuit breaker open");
31
- const system = splitAnthropicSystem(messages);
32
- const msgs = this.buildMessages(messages);
31
+ const system = context.systemText || undefined;
32
+ const msgs = this.buildMessages(context);
33
33
  let lastErr;
34
34
  for (let i = 0; i < this.maxRetries; i++) {
35
35
  try {
@@ -65,9 +65,9 @@ export class AnthropicProvider {
65
65
  }
66
66
  throw lastErr;
67
67
  }
68
- async *stream(messages, tools, extensions) {
69
- const system = splitAnthropicSystem(messages);
70
- const msgs = this.buildMessages(messages);
68
+ async *stream(context, tools, extensions) {
69
+ const system = context.systemText || undefined;
70
+ const msgs = this.buildMessages(context);
71
71
  const toolBlocks = {};
72
72
  const nativeBlocks = {};
73
73
  let finalText = "";
@@ -121,8 +121,8 @@ export class AnthropicProvider {
121
121
  }
122
122
  this.rememberNativeBlocks({ content: finalText, toolCalls: finalToolCalls }, Object.keys(nativeBlocks).map(Number).sort((a, b) => a - b).map(index => nativeBlocks[index]));
123
123
  }
124
- buildMessages(messages) {
125
- return toAnthropicMessages(messages, message => this.nativeAssistantBlocks.get(this.assistantReplayKey(message)));
124
+ buildMessages(context) {
125
+ return toAnthropicMessages(context.turns, message => this.nativeAssistantBlocks.get(this.assistantReplayKey(message)));
126
126
  }
127
127
  rememberNativeBlocks(message, blocks) {
128
128
  if (!message.toolCalls?.length)