@tangle-network/agent-runtime 0.88.0 → 0.89.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 +2 -2
- package/dist/{chunk-JHULWWQD.js → chunk-5AVV7KAH.js} +2 -2
- package/dist/{chunk-HBE77SWV.js → chunk-BQPFZE2C.js} +3 -3
- package/dist/{chunk-LRNRPJAV.js → chunk-N7EJV7N3.js} +25 -269
- package/dist/chunk-N7EJV7N3.js.map +1 -0
- package/dist/{chunk-22HPUH77.js → chunk-PIPPLSOF.js} +139 -268
- package/dist/chunk-PIPPLSOF.js.map +1 -0
- package/dist/index.js +4 -4
- package/dist/loop-runner-bin.js +3 -3
- package/dist/loops.d.ts +2 -185
- package/dist/loops.js +2 -14
- package/dist/mcp/bin.js +1 -1
- package/dist/mcp/index.js +3 -3
- package/package.json +1 -1
- package/skills/build-with-agent-runtime/SKILL.md +0 -6
- package/skills/loop-writer/SKILL.md +0 -73
- package/dist/chunk-22HPUH77.js.map +0 -1
- package/dist/chunk-LRNRPJAV.js.map +0 -1
- /package/dist/{chunk-JHULWWQD.js.map → chunk-5AVV7KAH.js.map} +0 -0
- /package/dist/{chunk-HBE77SWV.js.map → chunk-BQPFZE2C.js.map} +0 -0
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
settledToIteration,
|
|
16
16
|
supervise,
|
|
17
17
|
withDriverExecutor
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-N7EJV7N3.js";
|
|
19
19
|
import {
|
|
20
20
|
addTokenUsage,
|
|
21
21
|
isAbortError,
|
|
@@ -1405,263 +1405,6 @@ 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
|
-
|
|
1665
1408
|
// src/runtime/mcp-environment.ts
|
|
1666
1409
|
async function rpc(endpoint, body) {
|
|
1667
1410
|
let lastErr;
|
|
@@ -3903,8 +3646,138 @@ function errorMessage(error) {
|
|
|
3903
3646
|
return error instanceof Error ? error.message : String(error);
|
|
3904
3647
|
}
|
|
3905
3648
|
|
|
3649
|
+
// src/runtime/strategy-author.ts
|
|
3650
|
+
import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
3651
|
+
import { join as join3 } from "path";
|
|
3652
|
+
var strategyAuthorContract = `
|
|
3653
|
+
You author an OPTIMIZATION STRATEGY for an agentic loop system. A strategy decides how to
|
|
3654
|
+
spend a compute budget to beat a task's deployable check. You compose exactly two steps:
|
|
3655
|
+
|
|
3656
|
+
shot(spec?: { handle?, messages?, steer?, persona?, tools? }): Promise<ShotResult | null>
|
|
3657
|
+
Runs ONE worker attempt (a bounded tool loop) over an artifact.
|
|
3658
|
+
- omit handle => the shot opens its OWN fresh artifact and closes it after (a sample).
|
|
3659
|
+
- pass handle => the shot CONTINUES that artifact (state accumulates across shots).
|
|
3660
|
+
- messages => the carried conversation (pass the previous ShotResult.messages to continue).
|
|
3661
|
+
- steer => a corrective instruction injected before the shot.
|
|
3662
|
+
- persona => { systemPrompt?, model? } \u2014 give THIS shot its own role and/or model
|
|
3663
|
+
(multi-agent strategies: a researcher shot then an engineer shot, a panel of k
|
|
3664
|
+
personas over one budget). On a fresh shot the systemPrompt replaces the task's; on
|
|
3665
|
+
a carried conversation it arrives as a hand-off message. Same conserved budget.
|
|
3666
|
+
- tools => string[] \u2014 restrict THIS shot to a subset of the task's tools by
|
|
3667
|
+
name (focus an explore shot on read-only tools, an execute shot on write tools).
|
|
3668
|
+
Restriction-only; unknown names make the shot fail. ALWAYS select from
|
|
3669
|
+
await listTools(handle) \u2014 never hardcode. Omitted => the shot sees every tool.
|
|
3670
|
+
ShotResult = { messages, score (0..1 on the task's check), passes, total, completions, toolErrors }
|
|
3671
|
+
Returns null if the attempt failed infra-wise.
|
|
3672
|
+
|
|
3673
|
+
critique(messages): Promise<string | null>
|
|
3674
|
+
A firewalled trace-analyst reads the attempt's trajectory and returns ONE corrective
|
|
3675
|
+
instruction (or null when it judges the work complete). Costs ~1 completion.
|
|
3676
|
+
|
|
3677
|
+
consult(messages, instruction): Promise<string | null>
|
|
3678
|
+
The RAW analyst channel: the same firewalled critic answers YOUR instruction over the
|
|
3679
|
+
trajectory verbatim (no reformatting) \u2014 use it when you need a specific reply format
|
|
3680
|
+
(a decision, a prediction). Costs ~1 completion.
|
|
3681
|
+
|
|
3682
|
+
surface.open(task) / surface.close(handle)
|
|
3683
|
+
Open a persistent artifact you manage yourself (remember to close in a finally).
|
|
3684
|
+
close is idempotent \u2014 closing an already-closed handle is a safe no-op.
|
|
3685
|
+
|
|
3686
|
+
listTools(handle): Promise<Array<{ name, description? }>>
|
|
3687
|
+
The tools THIS task actually offers. TOOL SETS VARY PER TASK \u2014 if you restrict a
|
|
3688
|
+
shot with \`tools\`, you MUST pick names from await listTools(handle); hardcoding
|
|
3689
|
+
names from an example kills your shots on every task whose tools differ.
|
|
3690
|
+
|
|
3691
|
+
Rules:
|
|
3692
|
+
- ALWAYS await every shot/critique/surface call \u2014 a floating promise that rejects
|
|
3693
|
+
crashes the whole benchmark run.
|
|
3694
|
+
- Stay within ~budget total shots; every shot/critique spends from a conserved pool.
|
|
3695
|
+
- For a FRESH attempt OMIT \`messages\` entirely (never pass \`[]\` \u2014 an empty array is a
|
|
3696
|
+
fresh conversation too, but be explicit). To CONTINUE, pass the previous
|
|
3697
|
+
ShotResult.messages unchanged.
|
|
3698
|
+
- Return { score, resolved, completions, progression, shots } \u2014 score = the BEST checkpoint
|
|
3699
|
+
you reached (keep-best, never final-state), progression = score after each shot.
|
|
3700
|
+
- The module must be EXACTLY this shape (no other imports, no commentary outside code):
|
|
3701
|
+
|
|
3702
|
+
import { defineStrategy } from '@tangle-network/agent-runtime/loops'
|
|
3703
|
+
export default defineStrategy('your-strategy-name', async ({ surface, task, budget, shot, critique, listTools }) => {
|
|
3704
|
+
// your composition (listTools comes from the destructured context \u2014 it is NOT a global)
|
|
3705
|
+
})
|
|
3706
|
+
`;
|
|
3707
|
+
function assertStrategyContract(code) {
|
|
3708
|
+
const allowedImport = /^\s*import\s+\{[^}]*\}\s+from\s+['"]@tangle-network\/agent-runtime\/loops['"]/;
|
|
3709
|
+
for (const line of code.split("\n")) {
|
|
3710
|
+
if (/^\s*import\s/.test(line) && !allowedImport.test(line)) {
|
|
3711
|
+
throw new Error(`authored code rejected: foreign import \u2014 ${line.trim().slice(0, 120)}`);
|
|
3712
|
+
}
|
|
3713
|
+
}
|
|
3714
|
+
const banned = [
|
|
3715
|
+
[/\brequire\s*\(/, "require()"],
|
|
3716
|
+
[/\bimport\s*\(/, "dynamic import()"],
|
|
3717
|
+
[/\beval\s*\(/, "eval()"],
|
|
3718
|
+
[/new\s+Function\s*\(/, "new Function()"],
|
|
3719
|
+
[/\bprocess\s*[.[]/, "process access"],
|
|
3720
|
+
[/\bglobalThis\s*[.[]/, "globalThis access"],
|
|
3721
|
+
[/\bfetch\s*\(/, "network access"],
|
|
3722
|
+
[/child_process|node:fs|node:net|node:http|worker_threads/, "node builtin access"]
|
|
3723
|
+
];
|
|
3724
|
+
for (const [re, what] of banned) {
|
|
3725
|
+
if (re.test(code)) throw new Error(`authored code rejected: ${what}`);
|
|
3726
|
+
}
|
|
3727
|
+
}
|
|
3728
|
+
async function requestAuthoredCode(opts, model) {
|
|
3729
|
+
const res = await opts.chat.chat(
|
|
3730
|
+
{
|
|
3731
|
+
...model ? { model } : {},
|
|
3732
|
+
...opts.temperature !== void 0 ? { temperature: opts.temperature } : {},
|
|
3733
|
+
...opts.maxTokens !== void 0 ? { maxTokens: opts.maxTokens } : {},
|
|
3734
|
+
messages: [
|
|
3735
|
+
{
|
|
3736
|
+
role: "system",
|
|
3737
|
+
content: "You are a senior engineer authoring optimization strategies for agent loops. Output exactly one fenced ```ts code block and nothing else."
|
|
3738
|
+
},
|
|
3739
|
+
{
|
|
3740
|
+
role: "user",
|
|
3741
|
+
content: `${opts.contract ?? strategyAuthorContract}
|
|
3742
|
+
|
|
3743
|
+
BASELINE RESULTS on the "${opts.environmentName}" environment (budget=${opts.budget}):
|
|
3744
|
+
${opts.lossesJson}
|
|
3745
|
+
|
|
3746
|
+
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.`
|
|
3747
|
+
}
|
|
3748
|
+
]
|
|
3749
|
+
},
|
|
3750
|
+
{ ...opts.signal ? { signal: opts.signal } : {} }
|
|
3751
|
+
);
|
|
3752
|
+
const match = res.content.match(/```(?:ts|typescript)?\s*\n([\s\S]*?)```/);
|
|
3753
|
+
if (!match?.[1]) {
|
|
3754
|
+
throw new Error(
|
|
3755
|
+
`authorStrategy: no code block in the author's reply (model=${model ?? "default"}): ${res.content.slice(0, 300)}`
|
|
3756
|
+
);
|
|
3757
|
+
}
|
|
3758
|
+
return match[1];
|
|
3759
|
+
}
|
|
3760
|
+
async function authorStrategy(opts) {
|
|
3761
|
+
let code;
|
|
3762
|
+
try {
|
|
3763
|
+
code = await requestAuthoredCode(opts, opts.model);
|
|
3764
|
+
} catch (primaryError) {
|
|
3765
|
+
if (!opts.fallbackModel) throw primaryError;
|
|
3766
|
+
code = await requestAuthoredCode(opts, opts.fallbackModel);
|
|
3767
|
+
}
|
|
3768
|
+
assertStrategyContract(code);
|
|
3769
|
+
mkdirSync2(opts.outDir, { recursive: true });
|
|
3770
|
+
const file = join3(opts.outDir, `authored-${Date.now()}.mts`);
|
|
3771
|
+
writeFileSync2(file, code);
|
|
3772
|
+
const mod = await import(`file://${file}`);
|
|
3773
|
+
if (!mod.default || typeof mod.default.driver !== "function" || !mod.default.name) {
|
|
3774
|
+
throw new Error(`authorStrategy: ${file} does not export a default Strategy`);
|
|
3775
|
+
}
|
|
3776
|
+
return { strategy: mod.default, file, code };
|
|
3777
|
+
}
|
|
3778
|
+
|
|
3906
3779
|
// src/runtime/strategy-evolution.ts
|
|
3907
|
-
import { existsSync, readFileSync, writeFileSync as
|
|
3780
|
+
import { existsSync, readFileSync, writeFileSync as writeFileSync3 } from "fs";
|
|
3908
3781
|
import { gzipSync } from "zlib";
|
|
3909
3782
|
function discriminatingMeans(report, fieldOrder) {
|
|
3910
3783
|
const rows = report.perTask.filter((r) => {
|
|
@@ -4016,7 +3889,7 @@ async function runStrategyEvolution(cfg) {
|
|
|
4016
3889
|
}
|
|
4017
3890
|
const save = (state) => {
|
|
4018
3891
|
if (cfg.checkpoint)
|
|
4019
|
-
|
|
3892
|
+
writeFileSync3(cfg.checkpoint.path, JSON.stringify({ ...state, fingerprint }, null, 1));
|
|
4020
3893
|
};
|
|
4021
3894
|
const bench = async (phase, tasks, strategies) => {
|
|
4022
3895
|
await cfg.onPhase?.(phase);
|
|
@@ -5914,8 +5787,8 @@ function jjWorkspace(opts) {
|
|
|
5914
5787
|
async function runInWorkspace(ws, body, opts = {}) {
|
|
5915
5788
|
const { mkdtempSync: mkdtempSync2, rmSync: rmSync2 } = await import("fs");
|
|
5916
5789
|
const { tmpdir: tmpdir3 } = await import("os");
|
|
5917
|
-
const { join:
|
|
5918
|
-
const dir = mkdtempSync2(
|
|
5790
|
+
const { join: join4 } = await import("path");
|
|
5791
|
+
const dir = mkdtempSync2(join4(tmpdir3(), opts.tmpPrefix ?? "ws-run-"));
|
|
5919
5792
|
try {
|
|
5920
5793
|
await ws.materialize(dir);
|
|
5921
5794
|
const r = await body(dir);
|
|
@@ -5969,11 +5842,6 @@ export {
|
|
|
5969
5842
|
renderReport,
|
|
5970
5843
|
harvestCorpus,
|
|
5971
5844
|
inProcessSandboxClient,
|
|
5972
|
-
strategyAuthorContract,
|
|
5973
|
-
assertStrategyContract,
|
|
5974
|
-
authorStrategy,
|
|
5975
|
-
loopAuthorContract,
|
|
5976
|
-
authorLoop,
|
|
5977
5845
|
createMcpEnvironment,
|
|
5978
5846
|
assertTraceDerivedFindings,
|
|
5979
5847
|
createScopeAnalyst,
|
|
@@ -6010,6 +5878,9 @@ export {
|
|
|
6010
5878
|
printBenchmarkReport,
|
|
6011
5879
|
SandboxRunAbortError,
|
|
6012
5880
|
openSandboxRun,
|
|
5881
|
+
strategyAuthorContract,
|
|
5882
|
+
assertStrategyContract,
|
|
5883
|
+
authorStrategy,
|
|
6013
5884
|
discriminatingMeans,
|
|
6014
5885
|
pickChampion,
|
|
6015
5886
|
selectChampion,
|
|
@@ -6036,4 +5907,4 @@ export {
|
|
|
6036
5907
|
computeFindingId,
|
|
6037
5908
|
makeFinding2 as makeFinding
|
|
6038
5909
|
};
|
|
6039
|
-
//# sourceMappingURL=chunk-
|
|
5910
|
+
//# sourceMappingURL=chunk-PIPPLSOF.js.map
|