@tangle-network/agent-runtime 0.87.0 → 0.88.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/agent.js +3 -3
- package/dist/analyst-loop.js +2 -2
- package/dist/{chunk-VKVNDNG4.js → chunk-22HPUH77.js} +272 -142
- package/dist/chunk-22HPUH77.js.map +1 -0
- package/dist/{chunk-QUXZBZCS.js → chunk-FVJ7M3DA.js} +1 -1
- package/dist/chunk-FVJ7M3DA.js.map +1 -0
- package/dist/{chunk-FLVVVBWV.js → chunk-HBE77SWV.js} +4 -4
- package/dist/{chunk-MHYF2LIP.js → chunk-JHULWWQD.js} +2 -2
- package/dist/{chunk-6XCW3M7W.js → chunk-LRNRPJAV.js} +282 -34
- package/dist/chunk-LRNRPJAV.js.map +1 -0
- package/dist/{chunk-LCXXIL3U.js → chunk-ZQZX77MM.js} +2 -2
- package/dist/index.js +6 -6
- package/dist/loop-runner-bin.js +5 -5
- package/dist/loops.d.ts +209 -5
- package/dist/loops.js +15 -3
- package/dist/mcp/bin.js +2 -2
- package/dist/mcp/index.js +4 -4
- package/package.json +2 -2
- package/skills/build-with-agent-runtime/SKILL.md +6 -0
- package/skills/loop-writer/SKILL.md +73 -0
- package/dist/chunk-6XCW3M7W.js.map +0 -1
- package/dist/chunk-QUXZBZCS.js.map +0 -1
- package/dist/chunk-VKVNDNG4.js.map +0 -1
- /package/dist/{chunk-FLVVVBWV.js.map → chunk-HBE77SWV.js.map} +0 -0
- /package/dist/{chunk-MHYF2LIP.js.map → chunk-JHULWWQD.js.map} +0 -0
- /package/dist/{chunk-LCXXIL3U.js.map → chunk-ZQZX77MM.js.map} +0 -0
package/dist/agent.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import "./chunk-
|
|
1
|
+
import "./chunk-22HPUH77.js";
|
|
2
2
|
import {
|
|
3
3
|
createSandboxForSpec
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-LRNRPJAV.js";
|
|
5
5
|
import "./chunk-UD4BHQMI.js";
|
|
6
6
|
import "./chunk-BZF3KQ6G.js";
|
|
7
7
|
import {
|
|
8
8
|
mapSandboxEvent
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-FVJ7M3DA.js";
|
|
10
10
|
import "./chunk-7LO5GMAO.js";
|
|
11
11
|
import "./chunk-YEJR7IXO.js";
|
|
12
12
|
import "./chunk-DPEUKJRO.js";
|
package/dist/analyst-loop.js
CHANGED
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
settledToIteration,
|
|
16
16
|
supervise,
|
|
17
17
|
withDriverExecutor
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-LRNRPJAV.js";
|
|
19
19
|
import {
|
|
20
20
|
addTokenUsage,
|
|
21
21
|
isAbortError,
|
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
createSandboxToolPartState,
|
|
29
29
|
mapSandboxEvent,
|
|
30
30
|
mapSandboxToolEvent
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-FVJ7M3DA.js";
|
|
32
32
|
import {
|
|
33
33
|
AnalystError,
|
|
34
34
|
BackendTransportError,
|
|
@@ -1405,6 +1405,263 @@ function inProcessSandboxClient(options) {
|
|
|
1405
1405
|
};
|
|
1406
1406
|
}
|
|
1407
1407
|
|
|
1408
|
+
// src/runtime/loop-author.ts
|
|
1409
|
+
import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
|
|
1410
|
+
import { join as join4 } from "path";
|
|
1411
|
+
|
|
1412
|
+
// src/runtime/strategy-author.ts
|
|
1413
|
+
import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
1414
|
+
import { join as join3 } from "path";
|
|
1415
|
+
var strategyAuthorContract = `
|
|
1416
|
+
You author an OPTIMIZATION STRATEGY for an agentic loop system. A strategy decides how to
|
|
1417
|
+
spend a compute budget to beat a task's deployable check. You compose exactly two steps:
|
|
1418
|
+
|
|
1419
|
+
shot(spec?: { handle?, messages?, steer?, persona?, tools? }): Promise<ShotResult | null>
|
|
1420
|
+
Runs ONE worker attempt (a bounded tool loop) over an artifact.
|
|
1421
|
+
- omit handle => the shot opens its OWN fresh artifact and closes it after (a sample).
|
|
1422
|
+
- pass handle => the shot CONTINUES that artifact (state accumulates across shots).
|
|
1423
|
+
- messages => the carried conversation (pass the previous ShotResult.messages to continue).
|
|
1424
|
+
- steer => a corrective instruction injected before the shot.
|
|
1425
|
+
- persona => { systemPrompt?, model? } \u2014 give THIS shot its own role and/or model
|
|
1426
|
+
(multi-agent strategies: a researcher shot then an engineer shot, a panel of k
|
|
1427
|
+
personas over one budget). On a fresh shot the systemPrompt replaces the task's; on
|
|
1428
|
+
a carried conversation it arrives as a hand-off message. Same conserved budget.
|
|
1429
|
+
- tools => string[] \u2014 restrict THIS shot to a subset of the task's tools by
|
|
1430
|
+
name (focus an explore shot on read-only tools, an execute shot on write tools).
|
|
1431
|
+
Restriction-only; unknown names make the shot fail. ALWAYS select from
|
|
1432
|
+
await listTools(handle) \u2014 never hardcode. Omitted => the shot sees every tool.
|
|
1433
|
+
ShotResult = { messages, score (0..1 on the task's check), passes, total, completions, toolErrors }
|
|
1434
|
+
Returns null if the attempt failed infra-wise.
|
|
1435
|
+
|
|
1436
|
+
critique(messages): Promise<string | null>
|
|
1437
|
+
A firewalled trace-analyst reads the attempt's trajectory and returns ONE corrective
|
|
1438
|
+
instruction (or null when it judges the work complete). Costs ~1 completion.
|
|
1439
|
+
|
|
1440
|
+
consult(messages, instruction): Promise<string | null>
|
|
1441
|
+
The RAW analyst channel: the same firewalled critic answers YOUR instruction over the
|
|
1442
|
+
trajectory verbatim (no reformatting) \u2014 use it when you need a specific reply format
|
|
1443
|
+
(a decision, a prediction). Costs ~1 completion.
|
|
1444
|
+
|
|
1445
|
+
surface.open(task) / surface.close(handle)
|
|
1446
|
+
Open a persistent artifact you manage yourself (remember to close in a finally).
|
|
1447
|
+
close is idempotent \u2014 closing an already-closed handle is a safe no-op.
|
|
1448
|
+
|
|
1449
|
+
listTools(handle): Promise<Array<{ name, description? }>>
|
|
1450
|
+
The tools THIS task actually offers. TOOL SETS VARY PER TASK \u2014 if you restrict a
|
|
1451
|
+
shot with \`tools\`, you MUST pick names from await listTools(handle); hardcoding
|
|
1452
|
+
names from an example kills your shots on every task whose tools differ.
|
|
1453
|
+
|
|
1454
|
+
Rules:
|
|
1455
|
+
- ALWAYS await every shot/critique/surface call \u2014 a floating promise that rejects
|
|
1456
|
+
crashes the whole benchmark run.
|
|
1457
|
+
- Stay within ~budget total shots; every shot/critique spends from a conserved pool.
|
|
1458
|
+
- For a FRESH attempt OMIT \`messages\` entirely (never pass \`[]\` \u2014 an empty array is a
|
|
1459
|
+
fresh conversation too, but be explicit). To CONTINUE, pass the previous
|
|
1460
|
+
ShotResult.messages unchanged.
|
|
1461
|
+
- Return { score, resolved, completions, progression, shots } \u2014 score = the BEST checkpoint
|
|
1462
|
+
you reached (keep-best, never final-state), progression = score after each shot.
|
|
1463
|
+
- The module must be EXACTLY this shape (no other imports, no commentary outside code):
|
|
1464
|
+
|
|
1465
|
+
import { defineStrategy } from '@tangle-network/agent-runtime/loops'
|
|
1466
|
+
export default defineStrategy('your-strategy-name', async ({ surface, task, budget, shot, critique, listTools }) => {
|
|
1467
|
+
// your composition (listTools comes from the destructured context \u2014 it is NOT a global)
|
|
1468
|
+
})
|
|
1469
|
+
`;
|
|
1470
|
+
function assertStrategyContract(code) {
|
|
1471
|
+
const allowedImport = /^\s*import\s+\{[^}]*\}\s+from\s+['"]@tangle-network\/agent-runtime\/loops['"]/;
|
|
1472
|
+
for (const line of code.split("\n")) {
|
|
1473
|
+
if (/^\s*import\s/.test(line) && !allowedImport.test(line)) {
|
|
1474
|
+
throw new Error(`authored code rejected: foreign import \u2014 ${line.trim().slice(0, 120)}`);
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
const banned = [
|
|
1478
|
+
[/\brequire\s*\(/, "require()"],
|
|
1479
|
+
[/\bimport\s*\(/, "dynamic import()"],
|
|
1480
|
+
[/\beval\s*\(/, "eval()"],
|
|
1481
|
+
[/new\s+Function\s*\(/, "new Function()"],
|
|
1482
|
+
[/\bprocess\s*[.[]/, "process access"],
|
|
1483
|
+
[/\bglobalThis\s*[.[]/, "globalThis access"],
|
|
1484
|
+
[/\bfetch\s*\(/, "network access"],
|
|
1485
|
+
[/child_process|node:fs|node:net|node:http|worker_threads/, "node builtin access"]
|
|
1486
|
+
];
|
|
1487
|
+
for (const [re, what] of banned) {
|
|
1488
|
+
if (re.test(code)) throw new Error(`authored code rejected: ${what}`);
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
async function requestAuthoredCode(opts, model) {
|
|
1492
|
+
const res = await opts.chat.chat(
|
|
1493
|
+
{
|
|
1494
|
+
...model ? { model } : {},
|
|
1495
|
+
...opts.temperature !== void 0 ? { temperature: opts.temperature } : {},
|
|
1496
|
+
...opts.maxTokens !== void 0 ? { maxTokens: opts.maxTokens } : {},
|
|
1497
|
+
messages: [
|
|
1498
|
+
{
|
|
1499
|
+
role: "system",
|
|
1500
|
+
content: "You are a senior engineer authoring optimization strategies for agent loops. Output exactly one fenced ```ts code block and nothing else."
|
|
1501
|
+
},
|
|
1502
|
+
{
|
|
1503
|
+
role: "user",
|
|
1504
|
+
content: `${opts.contract ?? strategyAuthorContract}
|
|
1505
|
+
|
|
1506
|
+
BASELINE RESULTS on the "${opts.environmentName}" environment (budget=${opts.budget}):
|
|
1507
|
+
${opts.lossesJson}
|
|
1508
|
+
|
|
1509
|
+
Author ONE new strategy that you expect to beat the baselines on THIS environment at the same budget. Use the losses to target the observed failure mode. Output only the module code block.`
|
|
1510
|
+
}
|
|
1511
|
+
]
|
|
1512
|
+
},
|
|
1513
|
+
{ ...opts.signal ? { signal: opts.signal } : {} }
|
|
1514
|
+
);
|
|
1515
|
+
const match = res.content.match(/```(?:ts|typescript)?\s*\n([\s\S]*?)```/);
|
|
1516
|
+
if (!match?.[1]) {
|
|
1517
|
+
throw new Error(
|
|
1518
|
+
`authorStrategy: no code block in the author's reply (model=${model ?? "default"}): ${res.content.slice(0, 300)}`
|
|
1519
|
+
);
|
|
1520
|
+
}
|
|
1521
|
+
return match[1];
|
|
1522
|
+
}
|
|
1523
|
+
async function authorStrategy(opts) {
|
|
1524
|
+
let code;
|
|
1525
|
+
try {
|
|
1526
|
+
code = await requestAuthoredCode(opts, opts.model);
|
|
1527
|
+
} catch (primaryError) {
|
|
1528
|
+
if (!opts.fallbackModel) throw primaryError;
|
|
1529
|
+
code = await requestAuthoredCode(opts, opts.fallbackModel);
|
|
1530
|
+
}
|
|
1531
|
+
assertStrategyContract(code);
|
|
1532
|
+
mkdirSync2(opts.outDir, { recursive: true });
|
|
1533
|
+
const file = join3(opts.outDir, `authored-${Date.now()}.mts`);
|
|
1534
|
+
writeFileSync2(file, code);
|
|
1535
|
+
const mod = await import(`file://${file}`);
|
|
1536
|
+
if (!mod.default || typeof mod.default.driver !== "function" || !mod.default.name) {
|
|
1537
|
+
throw new Error(`authorStrategy: ${file} does not export a default Strategy`);
|
|
1538
|
+
}
|
|
1539
|
+
return { strategy: mod.default, file, code };
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
// src/runtime/loop-author.ts
|
|
1543
|
+
var loopAuthorContract = `
|
|
1544
|
+
You author a LOOP ATOM for an agent supervisor. A loop runs a bounded, multi-round journey
|
|
1545
|
+
toward a deployable check; a supervisor spawns / observes / steers it exactly like a worker.
|
|
1546
|
+
You write ONE round; the runtime owns the round ceiling, the conserved budget, the gate, and
|
|
1547
|
+
folding a supervisor's steer into the next round. So write real control flow inside a round,
|
|
1548
|
+
but never write the loop's stop condition as "hope the model stops" \u2014 that is the runtime's job.
|
|
1549
|
+
|
|
1550
|
+
You export ONE module of EXACTLY this shape (no other imports, no commentary outside the code):
|
|
1551
|
+
|
|
1552
|
+
import { defineLoop } from '@tangle-network/agent-runtime/loops'
|
|
1553
|
+
export default defineLoop('your-loop-name', {
|
|
1554
|
+
maxRounds: 3,
|
|
1555
|
+
round: async ({ task, scope, round, maxRounds, steer, budget, signal }) => {
|
|
1556
|
+
// arbitrary code for ONE round. Do real work by spawning children on the nested scope:
|
|
1557
|
+
// const w = scope.spawn(childAgent, subtask, { budget: perRound, label: \`r\${round}\` })
|
|
1558
|
+
// if (!w.ok) throw new Error(w.reason) // fail loud: budget-exhausted | depth-exceeded
|
|
1559
|
+
// const settled = await scope.next() // conserved child work; settles gated
|
|
1560
|
+
// 'steer' is the supervisor's messages since the last round (fold them into what you do next).
|
|
1561
|
+
// 'signal' aborts if a forceful steer arrives mid-round \u2014 pass it to your awaited work.
|
|
1562
|
+
return { out: /* the running result */ undefined, done: false } // done:true stops early
|
|
1563
|
+
},
|
|
1564
|
+
check: (out) => /* the deployable completion oracle */ Boolean(out),
|
|
1565
|
+
})
|
|
1566
|
+
|
|
1567
|
+
For a MULTI-AGENT loop (a proposer then a verifier, a researcher then an engineer), do NOT
|
|
1568
|
+
hand-write the pipeline in 'round' \u2014 use 'agents' instead: an ordered list of named agents piped
|
|
1569
|
+
each round (task -> agents[0] -> agents[1] -> ... -> out). "How many agents" is then self-evident.
|
|
1570
|
+
|
|
1571
|
+
import { defineLoop } from '@tangle-network/agent-runtime/loops'
|
|
1572
|
+
export default defineLoop('your-loop-name', {
|
|
1573
|
+
maxRounds: 3,
|
|
1574
|
+
agents: [
|
|
1575
|
+
{ name: 'proposer', run: async (ctx, prior) => { /* spawn a worker, produce a draft */ return draft } },
|
|
1576
|
+
{ name: 'verifier', run: async (ctx, prior) => { /* verify/refine the proposer's draft */ return checked } },
|
|
1577
|
+
],
|
|
1578
|
+
check: (out) => Boolean(out),
|
|
1579
|
+
})
|
|
1580
|
+
|
|
1581
|
+
Provide EXACTLY one of 'round' or 'agents'. The round context (for the 'round' form, and passed to
|
|
1582
|
+
each agent's run as its first arg):
|
|
1583
|
+
task the spawn task, verbatim.
|
|
1584
|
+
scope the NESTED conserved scope. scope.spawn(agent, task, { budget, label }) reserves
|
|
1585
|
+
budget and fails closed; scope.next() awaits one child settlement. Budget NESTS \u2014
|
|
1586
|
+
the pool reserves each spawn's full ceiling until it settles, so give children a
|
|
1587
|
+
per-round budget smaller than the loop's own.
|
|
1588
|
+
round 1-based round index. maxRounds is the declared ceiling.
|
|
1589
|
+
steer readonly string[] \u2014 supervisor steer_agent messages that arrived since last round.
|
|
1590
|
+
budget conserved-pool readouts (tokensLeft, usdLeft, deadlineMs) for in-body awareness.
|
|
1591
|
+
signal AbortSignal \u2014 the spawn signal + a fresh per-round interrupt; honor it in awaits.
|
|
1592
|
+
|
|
1593
|
+
The round result: { out: unknown; done?: boolean }. 'out' is the running result the gate reads;
|
|
1594
|
+
'done: true' is YOUR early stop (distinct from the runtime's gate 'check').
|
|
1595
|
+
|
|
1596
|
+
check(out): boolean | Promise<boolean>. The DEPLOYABLE oracle \u2014 an executable test, a state
|
|
1597
|
+
verifier, a readiness score threshold \u2014 read off 'out', never the model judging itself. The loop
|
|
1598
|
+
settles valid IFF check passes, and the runtime polls it after each round to stop the instant the
|
|
1599
|
+
loop has delivered. A loop that exhausts maxRounds without check passing settles valid:false.
|
|
1600
|
+
|
|
1601
|
+
Rules:
|
|
1602
|
+
- ALWAYS await every scope.spawn drain / async call \u2014 a floating rejection crashes the run.
|
|
1603
|
+
- Do real work by SPAWNING children; raw un-metered inference in the body is not budget-conserved.
|
|
1604
|
+
- Give 'check' a real oracle. A loop whose check is a self-judged score cannot be trusted.
|
|
1605
|
+
- The only import allowed is '@tangle-network/agent-runtime/loops'. No require/eval/fetch/process/
|
|
1606
|
+
node builtins \u2014 the runtime meters and gates you; out-of-band compute breaks that.
|
|
1607
|
+
`;
|
|
1608
|
+
async function requestAuthoredCode2(opts, model) {
|
|
1609
|
+
const res = await opts.chat.chat(
|
|
1610
|
+
{
|
|
1611
|
+
...model ? { model } : {},
|
|
1612
|
+
...opts.temperature !== void 0 ? { temperature: opts.temperature } : {},
|
|
1613
|
+
...opts.maxTokens !== void 0 ? { maxTokens: opts.maxTokens } : {},
|
|
1614
|
+
messages: [
|
|
1615
|
+
{
|
|
1616
|
+
role: "system",
|
|
1617
|
+
content: "You are a senior engineer authoring coded loop atoms for an agent supervisor. Output exactly one fenced ```ts code block and nothing else."
|
|
1618
|
+
},
|
|
1619
|
+
{
|
|
1620
|
+
role: "user",
|
|
1621
|
+
content: `${opts.contract ?? loopAuthorContract}
|
|
1622
|
+
|
|
1623
|
+
GOAL: ${opts.goal}
|
|
1624
|
+
MAX ROUNDS: ${opts.maxRounds}${opts.context ? `
|
|
1625
|
+
|
|
1626
|
+
CONTEXT:
|
|
1627
|
+
${opts.context}` : ""}
|
|
1628
|
+
|
|
1629
|
+
Author ONE loop that reaches the goal within the round ceiling, gated on a real check. Output only the module code block.`
|
|
1630
|
+
}
|
|
1631
|
+
]
|
|
1632
|
+
},
|
|
1633
|
+
{ ...opts.signal ? { signal: opts.signal } : {} }
|
|
1634
|
+
);
|
|
1635
|
+
const match = res.content.match(/```(?:ts|typescript)?\s*\n([\s\S]*?)```/);
|
|
1636
|
+
if (!match?.[1]) {
|
|
1637
|
+
throw new Error(
|
|
1638
|
+
`authorLoop: no code block in the author's reply (model=${model ?? "default"}): ${res.content.slice(0, 300)}`
|
|
1639
|
+
);
|
|
1640
|
+
}
|
|
1641
|
+
return match[1];
|
|
1642
|
+
}
|
|
1643
|
+
function isLoopDef(value) {
|
|
1644
|
+
return typeof value === "object" && value !== null && typeof value.round === "function" && typeof value.name === "string" && Number.isInteger(value.maxRounds);
|
|
1645
|
+
}
|
|
1646
|
+
async function authorLoop(opts) {
|
|
1647
|
+
let code;
|
|
1648
|
+
try {
|
|
1649
|
+
code = await requestAuthoredCode2(opts, opts.model);
|
|
1650
|
+
} catch (primaryError) {
|
|
1651
|
+
if (!opts.fallbackModel) throw primaryError;
|
|
1652
|
+
code = await requestAuthoredCode2(opts, opts.fallbackModel);
|
|
1653
|
+
}
|
|
1654
|
+
assertStrategyContract(code);
|
|
1655
|
+
mkdirSync3(opts.outDir, { recursive: true });
|
|
1656
|
+
const file = join4(opts.outDir, `authored-loop-${Date.now()}.mts`);
|
|
1657
|
+
writeFileSync3(file, code);
|
|
1658
|
+
const mod = await import(`file://${file}`);
|
|
1659
|
+
if (!isLoopDef(mod.default)) {
|
|
1660
|
+
throw new Error(`authorLoop: ${file} does not default-export a LoopDef (defineLoop(...))`);
|
|
1661
|
+
}
|
|
1662
|
+
return { loop: mod.default, file, code };
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1408
1665
|
// src/runtime/mcp-environment.ts
|
|
1409
1666
|
async function rpc(endpoint, body) {
|
|
1410
1667
|
let lastErr;
|
|
@@ -3532,7 +3789,8 @@ async function openSandboxRun(client, options, deliverable) {
|
|
|
3532
3789
|
const r = await lineage.start(
|
|
3533
3790
|
options.agentRun,
|
|
3534
3791
|
prompt,
|
|
3535
|
-
options.signal
|
|
3792
|
+
options.signal,
|
|
3793
|
+
options.promptOptions
|
|
3536
3794
|
);
|
|
3537
3795
|
handle = r.handle;
|
|
3538
3796
|
const result = await settle2(handle.box, r.events);
|
|
@@ -3577,7 +3835,7 @@ async function openSandboxRun(client, options, deliverable) {
|
|
|
3577
3835
|
try {
|
|
3578
3836
|
const result = await settle2(
|
|
3579
3837
|
handle.box,
|
|
3580
|
-
await lineage.continue(handle, prompt, options.signal)
|
|
3838
|
+
await lineage.continue(handle, prompt, options.signal, options.promptOptions)
|
|
3581
3839
|
);
|
|
3582
3840
|
turnCount += 1;
|
|
3583
3841
|
emit({
|
|
@@ -3645,138 +3903,8 @@ function errorMessage(error) {
|
|
|
3645
3903
|
return error instanceof Error ? error.message : String(error);
|
|
3646
3904
|
}
|
|
3647
3905
|
|
|
3648
|
-
// src/runtime/strategy-author.ts
|
|
3649
|
-
import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
3650
|
-
import { join as join3 } from "path";
|
|
3651
|
-
var strategyAuthorContract = `
|
|
3652
|
-
You author an OPTIMIZATION STRATEGY for an agentic loop system. A strategy decides how to
|
|
3653
|
-
spend a compute budget to beat a task's deployable check. You compose exactly two steps:
|
|
3654
|
-
|
|
3655
|
-
shot(spec?: { handle?, messages?, steer?, persona?, tools? }): Promise<ShotResult | null>
|
|
3656
|
-
Runs ONE worker attempt (a bounded tool loop) over an artifact.
|
|
3657
|
-
- omit handle => the shot opens its OWN fresh artifact and closes it after (a sample).
|
|
3658
|
-
- pass handle => the shot CONTINUES that artifact (state accumulates across shots).
|
|
3659
|
-
- messages => the carried conversation (pass the previous ShotResult.messages to continue).
|
|
3660
|
-
- steer => a corrective instruction injected before the shot.
|
|
3661
|
-
- persona => { systemPrompt?, model? } \u2014 give THIS shot its own role and/or model
|
|
3662
|
-
(multi-agent strategies: a researcher shot then an engineer shot, a panel of k
|
|
3663
|
-
personas over one budget). On a fresh shot the systemPrompt replaces the task's; on
|
|
3664
|
-
a carried conversation it arrives as a hand-off message. Same conserved budget.
|
|
3665
|
-
- tools => string[] \u2014 restrict THIS shot to a subset of the task's tools by
|
|
3666
|
-
name (focus an explore shot on read-only tools, an execute shot on write tools).
|
|
3667
|
-
Restriction-only; unknown names make the shot fail. ALWAYS select from
|
|
3668
|
-
await listTools(handle) \u2014 never hardcode. Omitted => the shot sees every tool.
|
|
3669
|
-
ShotResult = { messages, score (0..1 on the task's check), passes, total, completions, toolErrors }
|
|
3670
|
-
Returns null if the attempt failed infra-wise.
|
|
3671
|
-
|
|
3672
|
-
critique(messages): Promise<string | null>
|
|
3673
|
-
A firewalled trace-analyst reads the attempt's trajectory and returns ONE corrective
|
|
3674
|
-
instruction (or null when it judges the work complete). Costs ~1 completion.
|
|
3675
|
-
|
|
3676
|
-
consult(messages, instruction): Promise<string | null>
|
|
3677
|
-
The RAW analyst channel: the same firewalled critic answers YOUR instruction over the
|
|
3678
|
-
trajectory verbatim (no reformatting) \u2014 use it when you need a specific reply format
|
|
3679
|
-
(a decision, a prediction). Costs ~1 completion.
|
|
3680
|
-
|
|
3681
|
-
surface.open(task) / surface.close(handle)
|
|
3682
|
-
Open a persistent artifact you manage yourself (remember to close in a finally).
|
|
3683
|
-
close is idempotent \u2014 closing an already-closed handle is a safe no-op.
|
|
3684
|
-
|
|
3685
|
-
listTools(handle): Promise<Array<{ name, description? }>>
|
|
3686
|
-
The tools THIS task actually offers. TOOL SETS VARY PER TASK \u2014 if you restrict a
|
|
3687
|
-
shot with \`tools\`, you MUST pick names from await listTools(handle); hardcoding
|
|
3688
|
-
names from an example kills your shots on every task whose tools differ.
|
|
3689
|
-
|
|
3690
|
-
Rules:
|
|
3691
|
-
- ALWAYS await every shot/critique/surface call \u2014 a floating promise that rejects
|
|
3692
|
-
crashes the whole benchmark run.
|
|
3693
|
-
- Stay within ~budget total shots; every shot/critique spends from a conserved pool.
|
|
3694
|
-
- For a FRESH attempt OMIT \`messages\` entirely (never pass \`[]\` \u2014 an empty array is a
|
|
3695
|
-
fresh conversation too, but be explicit). To CONTINUE, pass the previous
|
|
3696
|
-
ShotResult.messages unchanged.
|
|
3697
|
-
- Return { score, resolved, completions, progression, shots } \u2014 score = the BEST checkpoint
|
|
3698
|
-
you reached (keep-best, never final-state), progression = score after each shot.
|
|
3699
|
-
- The module must be EXACTLY this shape (no other imports, no commentary outside code):
|
|
3700
|
-
|
|
3701
|
-
import { defineStrategy } from '@tangle-network/agent-runtime/loops'
|
|
3702
|
-
export default defineStrategy('your-strategy-name', async ({ surface, task, budget, shot, critique, listTools }) => {
|
|
3703
|
-
// your composition (listTools comes from the destructured context \u2014 it is NOT a global)
|
|
3704
|
-
})
|
|
3705
|
-
`;
|
|
3706
|
-
function assertStrategyContract(code) {
|
|
3707
|
-
const allowedImport = /^\s*import\s+\{[^}]*\}\s+from\s+['"]@tangle-network\/agent-runtime\/loops['"]/;
|
|
3708
|
-
for (const line of code.split("\n")) {
|
|
3709
|
-
if (/^\s*import\s/.test(line) && !allowedImport.test(line)) {
|
|
3710
|
-
throw new Error(`authored code rejected: foreign import \u2014 ${line.trim().slice(0, 120)}`);
|
|
3711
|
-
}
|
|
3712
|
-
}
|
|
3713
|
-
const banned = [
|
|
3714
|
-
[/\brequire\s*\(/, "require()"],
|
|
3715
|
-
[/\bimport\s*\(/, "dynamic import()"],
|
|
3716
|
-
[/\beval\s*\(/, "eval()"],
|
|
3717
|
-
[/new\s+Function\s*\(/, "new Function()"],
|
|
3718
|
-
[/\bprocess\s*[.[]/, "process access"],
|
|
3719
|
-
[/\bglobalThis\s*[.[]/, "globalThis access"],
|
|
3720
|
-
[/\bfetch\s*\(/, "network access"],
|
|
3721
|
-
[/child_process|node:fs|node:net|node:http|worker_threads/, "node builtin access"]
|
|
3722
|
-
];
|
|
3723
|
-
for (const [re, what] of banned) {
|
|
3724
|
-
if (re.test(code)) throw new Error(`authored code rejected: ${what}`);
|
|
3725
|
-
}
|
|
3726
|
-
}
|
|
3727
|
-
async function requestAuthoredCode(opts, model) {
|
|
3728
|
-
const res = await opts.chat.chat(
|
|
3729
|
-
{
|
|
3730
|
-
...model ? { model } : {},
|
|
3731
|
-
...opts.temperature !== void 0 ? { temperature: opts.temperature } : {},
|
|
3732
|
-
...opts.maxTokens !== void 0 ? { maxTokens: opts.maxTokens } : {},
|
|
3733
|
-
messages: [
|
|
3734
|
-
{
|
|
3735
|
-
role: "system",
|
|
3736
|
-
content: "You are a senior engineer authoring optimization strategies for agent loops. Output exactly one fenced ```ts code block and nothing else."
|
|
3737
|
-
},
|
|
3738
|
-
{
|
|
3739
|
-
role: "user",
|
|
3740
|
-
content: `${opts.contract ?? strategyAuthorContract}
|
|
3741
|
-
|
|
3742
|
-
BASELINE RESULTS on the "${opts.environmentName}" environment (budget=${opts.budget}):
|
|
3743
|
-
${opts.lossesJson}
|
|
3744
|
-
|
|
3745
|
-
Author ONE new strategy that you expect to beat the baselines on THIS environment at the same budget. Use the losses to target the observed failure mode. Output only the module code block.`
|
|
3746
|
-
}
|
|
3747
|
-
]
|
|
3748
|
-
},
|
|
3749
|
-
{ ...opts.signal ? { signal: opts.signal } : {} }
|
|
3750
|
-
);
|
|
3751
|
-
const match = res.content.match(/```(?:ts|typescript)?\s*\n([\s\S]*?)```/);
|
|
3752
|
-
if (!match?.[1]) {
|
|
3753
|
-
throw new Error(
|
|
3754
|
-
`authorStrategy: no code block in the author's reply (model=${model ?? "default"}): ${res.content.slice(0, 300)}`
|
|
3755
|
-
);
|
|
3756
|
-
}
|
|
3757
|
-
return match[1];
|
|
3758
|
-
}
|
|
3759
|
-
async function authorStrategy(opts) {
|
|
3760
|
-
let code;
|
|
3761
|
-
try {
|
|
3762
|
-
code = await requestAuthoredCode(opts, opts.model);
|
|
3763
|
-
} catch (primaryError) {
|
|
3764
|
-
if (!opts.fallbackModel) throw primaryError;
|
|
3765
|
-
code = await requestAuthoredCode(opts, opts.fallbackModel);
|
|
3766
|
-
}
|
|
3767
|
-
assertStrategyContract(code);
|
|
3768
|
-
mkdirSync2(opts.outDir, { recursive: true });
|
|
3769
|
-
const file = join3(opts.outDir, `authored-${Date.now()}.mts`);
|
|
3770
|
-
writeFileSync2(file, code);
|
|
3771
|
-
const mod = await import(`file://${file}`);
|
|
3772
|
-
if (!mod.default || typeof mod.default.driver !== "function" || !mod.default.name) {
|
|
3773
|
-
throw new Error(`authorStrategy: ${file} does not export a default Strategy`);
|
|
3774
|
-
}
|
|
3775
|
-
return { strategy: mod.default, file, code };
|
|
3776
|
-
}
|
|
3777
|
-
|
|
3778
3906
|
// src/runtime/strategy-evolution.ts
|
|
3779
|
-
import { existsSync, readFileSync, writeFileSync as
|
|
3907
|
+
import { existsSync, readFileSync, writeFileSync as writeFileSync4 } from "fs";
|
|
3780
3908
|
import { gzipSync } from "zlib";
|
|
3781
3909
|
function discriminatingMeans(report, fieldOrder) {
|
|
3782
3910
|
const rows = report.perTask.filter((r) => {
|
|
@@ -3888,7 +4016,7 @@ async function runStrategyEvolution(cfg) {
|
|
|
3888
4016
|
}
|
|
3889
4017
|
const save = (state) => {
|
|
3890
4018
|
if (cfg.checkpoint)
|
|
3891
|
-
|
|
4019
|
+
writeFileSync4(cfg.checkpoint.path, JSON.stringify({ ...state, fingerprint }, null, 1));
|
|
3892
4020
|
};
|
|
3893
4021
|
const bench = async (phase, tasks, strategies) => {
|
|
3894
4022
|
await cfg.onPhase?.(phase);
|
|
@@ -5786,8 +5914,8 @@ function jjWorkspace(opts) {
|
|
|
5786
5914
|
async function runInWorkspace(ws, body, opts = {}) {
|
|
5787
5915
|
const { mkdtempSync: mkdtempSync2, rmSync: rmSync2 } = await import("fs");
|
|
5788
5916
|
const { tmpdir: tmpdir3 } = await import("os");
|
|
5789
|
-
const { join:
|
|
5790
|
-
const dir = mkdtempSync2(
|
|
5917
|
+
const { join: join5 } = await import("path");
|
|
5918
|
+
const dir = mkdtempSync2(join5(tmpdir3(), opts.tmpPrefix ?? "ws-run-"));
|
|
5791
5919
|
try {
|
|
5792
5920
|
await ws.materialize(dir);
|
|
5793
5921
|
const r = await body(dir);
|
|
@@ -5841,6 +5969,11 @@ export {
|
|
|
5841
5969
|
renderReport,
|
|
5842
5970
|
harvestCorpus,
|
|
5843
5971
|
inProcessSandboxClient,
|
|
5972
|
+
strategyAuthorContract,
|
|
5973
|
+
assertStrategyContract,
|
|
5974
|
+
authorStrategy,
|
|
5975
|
+
loopAuthorContract,
|
|
5976
|
+
authorLoop,
|
|
5844
5977
|
createMcpEnvironment,
|
|
5845
5978
|
assertTraceDerivedFindings,
|
|
5846
5979
|
createScopeAnalyst,
|
|
@@ -5877,9 +6010,6 @@ export {
|
|
|
5877
6010
|
printBenchmarkReport,
|
|
5878
6011
|
SandboxRunAbortError,
|
|
5879
6012
|
openSandboxRun,
|
|
5880
|
-
strategyAuthorContract,
|
|
5881
|
-
assertStrategyContract,
|
|
5882
|
-
authorStrategy,
|
|
5883
6013
|
discriminatingMeans,
|
|
5884
6014
|
pickChampion,
|
|
5885
6015
|
selectChampion,
|
|
@@ -5906,4 +6036,4 @@ export {
|
|
|
5906
6036
|
computeFindingId,
|
|
5907
6037
|
makeFinding2 as makeFinding
|
|
5908
6038
|
};
|
|
5909
|
-
//# sourceMappingURL=chunk-
|
|
6039
|
+
//# sourceMappingURL=chunk-22HPUH77.js.map
|