@leuduan/lagent 0.1.2 → 44.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/README.md +28 -15
- package/dist/chunks/{UC3FVVJ2.js → 2GCIWSOA.js} +2 -2
- package/dist/chunks/2P47AHNK.js +7 -0
- package/dist/chunks/3UMZMPWW.js +1 -0
- package/dist/chunks/5IRF47YB.js +1 -0
- package/dist/chunks/6DRCKZ2C.js +1 -0
- package/dist/chunks/6FRNHMCV.js +1 -0
- package/dist/chunks/7LI64H5X.js +17 -0
- package/dist/chunks/{SL2YLB2F.js → 7VAPNE3L.js} +1 -1
- package/dist/chunks/{BM3S37EZ.js → ASSQZH3F.js} +1 -1
- package/dist/chunks/B4FXK5ER.js +77 -0
- package/dist/chunks/{37YOGDGY.js → BBCW2FZK.js} +1 -1
- package/dist/chunks/BPRCULZH.js +1 -0
- package/dist/chunks/CANPZYTH.js +24 -0
- package/dist/chunks/CQEVREBT.js +1 -0
- package/dist/chunks/CUK7CGC7.js +1 -0
- package/dist/chunks/D4PQP5MA.js +3 -0
- package/dist/chunks/{CDQG7RKA.js → DDZ7YF26.js} +1 -1
- package/dist/chunks/EMRB4KCN.js +6 -0
- package/dist/chunks/EPYQ5M3B.js +3 -0
- package/dist/chunks/G44LG6VL.js +1 -0
- package/dist/chunks/GGSVIIWJ.js +2 -0
- package/dist/chunks/IAAEP6VL.js +30 -0
- package/dist/chunks/{AP6Q4EPT.js → JCTBX33H.js} +1 -1
- package/dist/chunks/JFX2MXBA.js +4 -0
- package/dist/chunks/JFZZXVWD.js +15 -0
- package/dist/chunks/KUZCL2SH.js +1 -0
- package/dist/chunks/MHC6VPB4.js +7 -0
- package/dist/chunks/MMNNZCBO.js +5 -0
- package/dist/chunks/{C5LYCXJG.js → MNJ4SRF7.js} +1 -1
- package/dist/chunks/N6IXG2VL.js +1 -0
- package/dist/chunks/OCBPT7KE.js +1 -0
- package/dist/chunks/OL5A6ITQ.js +1 -0
- package/dist/chunks/Q75FUN7D.js +2 -0
- package/dist/chunks/Q7S5LFGN.js +1 -0
- package/dist/chunks/RCIHV3KG.js +1 -0
- package/dist/chunks/S34ZA2R6.js +1 -0
- package/dist/chunks/SS3B5W34.js +12 -0
- package/dist/chunks/VYMT4TXD.js +1 -0
- package/dist/chunks/W57RW55W.js +1 -0
- package/dist/compositions/base.d.ts +11 -0
- package/dist/{presets → compositions}/codex.d.ts +12 -6
- package/dist/{presets/prompts.d.ts → compositions/codexPrompts.d.ts} +1 -1
- package/dist/context.d.ts +18 -10
- package/dist/index.d.ts +31 -23
- package/dist/index.js +1 -77
- package/dist/journal/catalog.d.ts +1 -1
- package/dist/journal/journal.d.ts +3 -3
- package/dist/journal/projection.d.ts +1 -1
- package/dist/journal/store.d.ts +3 -3
- package/dist/llm/index.d.ts +19 -13
- package/dist/llm/index.js +1 -0
- package/dist/llm/provider.d.ts +11 -0
- package/dist/loop/agent.d.ts +16 -132
- package/dist/loop/authorization.d.ts +41 -0
- package/dist/loop/auxiliary.d.ts +7 -3
- package/dist/loop/chunks.d.ts +3 -3
- package/dist/loop/completion.d.ts +17 -0
- package/dist/loop/errors.d.ts +6 -29
- package/dist/loop/hooks.d.ts +39 -6
- package/dist/loop/index.d.ts +7 -28
- package/dist/loop/runner.d.ts +134 -0
- package/dist/loop/runtime.d.ts +7 -16
- package/dist/loop/strategy.d.ts +12 -3
- package/dist/loop/{prepare.d.ts → surfacePrepare.d.ts} +2 -2
- package/dist/loop/tool.d.ts +11 -6
- package/dist/loop/toolCalls.d.ts +3 -10
- package/dist/plugin.d.ts +31 -34
- package/dist/plugin.js +1 -1
- package/dist/plugins/agentsMd.d.ts +24 -20
- package/dist/plugins/agentsMd.js +1 -1
- package/dist/plugins/ask/index.d.ts +2 -2
- package/dist/plugins/ask/index.js +1 -1
- package/dist/plugins/ask/service.d.ts +2 -2
- package/dist/plugins/commands/index.d.ts +5 -2
- package/dist/plugins/commands/index.js +1 -1
- package/dist/plugins/commands/output.d.ts +1 -1
- package/dist/plugins/commands/record.d.ts +31 -22
- package/dist/plugins/commands/service.d.ts +18 -11
- package/dist/plugins/commands/{background.d.ts → tools.d.ts} +2 -0
- package/dist/plugins/compaction/checkpoint.d.ts +4 -1
- package/dist/plugins/compaction/config.d.ts +3 -3
- package/dist/plugins/compaction/estimate.d.ts +9 -1
- package/dist/plugins/compaction/index.d.ts +87 -2
- package/dist/plugins/compaction/index.js +5 -5
- package/dist/plugins/compaction/{records.d.ts → record.d.ts} +36 -36
- package/dist/plugins/compaction/{log.d.ts → state.d.ts} +8 -1
- package/dist/plugins/dateAndBranch.js +1 -1
- package/dist/plugins/delegations/answers.d.ts +1 -1
- package/dist/plugins/delegations/assignmentKey.d.ts +1 -1
- package/dist/plugins/delegations/cleanup.d.ts +1 -1
- package/dist/plugins/delegations/index.js +1 -1
- package/dist/plugins/delegations/notices.d.ts +8 -8
- package/dist/plugins/delegations/obligations.d.ts +13 -13
- package/dist/plugins/delegations/record.d.ts +11 -10
- package/dist/plugins/delegations/request.d.ts +8 -5
- package/dist/plugins/delegations/role.d.ts +1 -1
- package/dist/plugins/delegations/service.d.ts +9 -8
- package/dist/plugins/delegations/{waitBook.d.ts → waitResolver.d.ts} +9 -9
- package/dist/plugins/diagnostics/digest.d.ts +1 -1
- package/dist/plugins/diagnostics/index.d.ts +1 -1
- package/dist/plugins/diagnostics/index.js +1 -1
- package/dist/plugins/fileTools/config.d.ts +10 -0
- package/dist/plugins/{tools → fileTools}/editFiles.d.ts +16 -27
- package/dist/plugins/fileTools/gitDiscovery.d.ts +9 -0
- package/dist/plugins/fileTools/index.d.ts +18 -0
- package/dist/plugins/fileTools/index.js +1 -0
- package/dist/plugins/fileTools/tools.d.ts +6 -0
- package/dist/plugins/historyRecall/history.d.ts +1 -1
- package/dist/plugins/historyRecall/index.js +1 -1
- package/dist/plugins/historyRecall/render.d.ts +1 -1
- package/dist/plugins/mcp/catalog.d.ts +1 -1
- package/dist/plugins/mcp/index.d.ts +2 -2
- package/dist/plugins/mcp/index.js +1 -1
- package/dist/plugins/mcp/mount.d.ts +2 -2
- package/dist/plugins/mcp/render.d.ts +1 -1
- package/dist/plugins/mcp/{tool.d.ts → tools.d.ts} +1 -1
- package/dist/plugins/{routeContext.d.ts → routeNotice.d.ts} +2 -2
- package/dist/plugins/routeNotice.js +1 -0
- package/dist/{sandbox → plugins/sandbox}/absent.d.ts +11 -10
- package/dist/{sandbox → plugins/sandbox}/index.d.ts +5 -2
- package/dist/plugins/sandbox/index.js +4 -0
- package/dist/{sandbox → plugins/sandbox}/mode.d.ts +5 -5
- package/dist/plugins/sandbox/policy.d.ts +163 -0
- package/dist/{sandbox → plugins/sandbox}/service.d.ts +23 -13
- package/dist/plugins/schedules/index.js +3 -3
- package/dist/plugins/schedules/record.d.ts +18 -18
- package/dist/plugins/schedules/service.d.ts +2 -2
- package/dist/plugins/skills/discovery.d.ts +38 -9
- package/dist/plugins/skills/index.d.ts +1 -1
- package/dist/plugins/skills/index.js +1 -1
- package/dist/plugins/subAgents/index.js +1 -1
- package/dist/plugins/subAgents/{fork.d.ts → tools.d.ts} +36 -1
- package/dist/plugins/threadDirs.d.ts +36 -0
- package/dist/plugins/threadDirs.js +1 -0
- package/dist/plugins/toolPolicy/index.d.ts +2 -2
- package/dist/plugins/toolPolicy/index.js +1 -1
- package/dist/plugins/truncateToolOutput.d.ts +14 -10
- package/dist/plugins/truncateToolOutput.js +6 -1
- package/dist/plugins/usage/index.d.ts +4 -2
- package/dist/plugins/usage/index.js +1 -1
- package/dist/plugins/usage/tracker.d.ts +1 -1
- package/dist/plugins/verify/index.d.ts +7 -55
- package/dist/plugins/verify/index.js +6 -1
- package/dist/plugins/verify/judgement.d.ts +16 -0
- package/dist/plugins/verify/record.d.ts +382 -0
- package/dist/plugins/verify/service.d.ts +7 -4
- package/dist/plugins/verify/state.d.ts +58 -0
- package/dist/plugins/webTools/index.d.ts +34 -0
- package/dist/plugins/webTools/index.js +1 -0
- package/dist/plugins/workflows/assignment.d.ts +6 -2
- package/dist/plugins/workflows/cleanup.d.ts +1 -1
- package/dist/plugins/workflows/definition.d.ts +2 -2
- package/dist/plugins/workflows/{bindings.d.ts → entryPlan.d.ts} +2 -2
- package/dist/plugins/workflows/{providers.d.ts → hostBindings.d.ts} +2 -2
- package/dist/plugins/workflows/index.d.ts +4 -4
- package/dist/plugins/workflows/index.js +10 -5
- package/dist/plugins/workflows/observations.d.ts +3 -3
- package/dist/plugins/workflows/participantModels.d.ts +28 -0
- package/dist/plugins/workflows/participants.d.ts +2 -2
- package/dist/plugins/workflows/policy.d.ts +2 -2
- package/dist/plugins/workflows/record.d.ts +51 -65
- package/dist/plugins/workflows/routing.d.ts +2 -2
- package/dist/plugins/workflows/service.d.ts +24 -24
- package/dist/plugins/workflows/{fold.d.ts → state.d.ts} +2 -2
- package/dist/plugins/workflows/stopCheck.d.ts +13 -0
- package/dist/plugins/workflows/tools.d.ts +13 -0
- package/dist/plugins/workflows/view.d.ts +2 -2
- package/dist/plugins/{workspaceContext.d.ts → workspaceNotice.d.ts} +5 -7
- package/dist/plugins/workspaceNotice.js +1 -0
- package/dist/{plugins/providers → providers}/anthropic.d.ts +6 -3
- package/dist/{plugins/providers → providers}/anthropicMessages.d.ts +2 -1
- package/dist/{plugins/providers → providers}/codex.d.ts +14 -3
- package/dist/{plugins/providers → providers}/deepseek.d.ts +6 -2
- package/dist/{plugins/providers → providers}/failure.d.ts +1 -1
- package/dist/{plugins/providers → providers}/gateway.d.ts +2 -1
- package/dist/providers/index.d.ts +18 -0
- package/dist/providers/index.js +6 -0
- package/dist/{plugins/providers → providers}/openaiChat.d.ts +13 -2
- package/dist/{plugins/providers → providers}/openaiResponses.d.ts +12 -3
- package/dist/{plugins/providers → providers}/opencodeCopilot.d.ts +2 -2
- package/dist/{plugins/providers → providers}/opencodeGo.d.ts +18 -7
- package/dist/{plugins/providers → providers}/shared.d.ts +9 -1
- package/dist/{plugins/providers → providers}/stream.d.ts +4 -2
- package/dist/{models/door.d.ts → records/index.d.ts} +8 -7
- package/dist/records/index.js +1 -0
- package/dist/{models/wire → records}/journal.d.ts +210 -14
- package/dist/{models/wire/primitives.d.ts → records/toolResult.d.ts} +1 -1
- package/dist/services/agents.d.ts +26 -1
- package/dist/services/confinement/files.d.ts +118 -0
- package/dist/services/confinement/service.d.ts +219 -0
- package/dist/services/core.d.ts +2 -8
- package/dist/{kit/extension.d.ts → services/extensionEvents.d.ts} +5 -4
- package/dist/services/journal.d.ts +1 -1
- package/dist/services/llm.d.ts +4 -2
- package/dist/{kit → services}/modes.d.ts +1 -1
- package/dist/services/plugins.d.ts +34 -0
- package/dist/services/{preset.d.ts → presets/definition.d.ts} +4 -4
- package/dist/services/{presets.d.ts → presets/installations.d.ts} +3 -3
- package/dist/services/prompts.d.ts +23 -5
- package/dist/services/{threadActivation.d.ts → threads/activation.d.ts} +3 -3
- package/dist/services/{admission.d.ts → threads/admission.d.ts} +3 -3
- package/dist/services/{birth.d.ts → threads/birth.d.ts} +9 -10
- package/dist/services/threads/index.d.ts +14 -0
- package/dist/services/{runEvents.d.ts → threads/runEvents.d.ts} +2 -2
- package/dist/services/{owner.d.ts → threads/runOwner.d.ts} +5 -4
- package/dist/services/{threads.d.ts → threads/service.d.ts} +9 -8
- package/dist/services/{thread.d.ts → threads/thread.d.ts} +8 -7
- package/dist/services/{threadView.d.ts → threads/view.d.ts} +7 -6
- package/dist/services/tools.d.ts +79 -2
- package/dist/{loop/opening.d.ts → state/birth.d.ts} +22 -2
- package/dist/{loop → state}/chain.d.ts +3 -3
- package/dist/state/confirmations.d.ts +64 -0
- package/dist/{loop → state}/continuation.d.ts +3 -2
- package/dist/{loop → state}/decide.d.ts +10 -2
- package/dist/state/dispatches.d.ts +54 -0
- package/dist/state/errors.d.ts +26 -0
- package/dist/{loop → state}/forks.d.ts +1 -1
- package/dist/{loop → state}/holds.d.ts +1 -1
- package/dist/{loop → state}/inbox.d.ts +2 -2
- package/dist/state/index.d.ts +31 -0
- package/dist/state/inputs.d.ts +58 -0
- package/dist/state/installations.d.ts +28 -0
- package/dist/state/prompt.d.ts +13 -0
- package/dist/state/recovery.d.ts +7 -0
- package/dist/{loop → state}/replace.d.ts +2 -2
- package/dist/{loop → state}/requests.d.ts +3 -3
- package/dist/{loop → state}/route.d.ts +10 -2
- package/dist/state/summary.d.ts +16 -0
- package/dist/{loop → state}/surface.d.ts +3 -3
- package/dist/state/surfaceRead.d.ts +20 -0
- package/dist/{loop/threadState.d.ts → state/thread.d.ts} +12 -11
- package/dist/state/turns.d.ts +87 -0
- package/dist/state/waits.d.ts +38 -0
- package/dist/{loop → state}/wake.d.ts +1 -1
- package/dist/stores/durableObject.js +1 -0
- package/dist/{plugins/store → stores}/memory.d.ts +2 -2
- package/dist/{plugins/store → stores}/sql.d.ts +2 -2
- package/dist/stores/sqlite.js +1 -0
- package/dist/sys/environment.d.ts +0 -5
- package/dist/sys/git.d.ts +0 -13
- package/dist/sys/paths.d.ts +0 -47
- package/dist/sys/spawn.d.ts +16 -6
- package/dist/testing/clock.d.ts +1 -1
- package/dist/testing/fakeLlm.d.ts +4 -2
- package/dist/testing/fedLlm.d.ts +3 -1
- package/dist/testing/helpers.d.ts +31 -13
- package/dist/testing/index.js +1 -1
- package/dist/testing/settlement.d.ts +1 -1
- package/package.json +36 -28
- package/dist/chunks/2O7ZGEIT.js +0 -1
- package/dist/chunks/2OSESBIL.js +0 -1
- package/dist/chunks/3LQHQRIU.js +0 -6
- package/dist/chunks/3QCW4WDJ.js +0 -1
- package/dist/chunks/4XVRUSCQ.js +0 -1
- package/dist/chunks/6ECI2GGV.js +0 -1
- package/dist/chunks/74HKUGRR.js +0 -1
- package/dist/chunks/ADHERZLW.js +0 -2
- package/dist/chunks/D7E6EWIE.js +0 -3
- package/dist/chunks/DRYAN665.js +0 -1
- package/dist/chunks/DXFXAYDN.js +0 -17
- package/dist/chunks/EGZI4XQX.js +0 -24
- package/dist/chunks/ENWFSU27.js +0 -41
- package/dist/chunks/G6RXC3AL.js +0 -1
- package/dist/chunks/G74AGRAJ.js +0 -15
- package/dist/chunks/GQGNVSKB.js +0 -1
- package/dist/chunks/IJ2WNMD5.js +0 -7
- package/dist/chunks/JPZFKSWT.js +0 -1
- package/dist/chunks/KESCTXGO.js +0 -5
- package/dist/chunks/L3N4FIEN.js +0 -1
- package/dist/chunks/NAOUTU7A.js +0 -4
- package/dist/chunks/NDIM7MEW.js +0 -1
- package/dist/chunks/O4PPOM5Z.js +0 -2
- package/dist/chunks/OVZFGILJ.js +0 -1
- package/dist/chunks/P5ZHHOOM.js +0 -6
- package/dist/chunks/QMMLQJBS.js +0 -1
- package/dist/chunks/RK3VP2Q4.js +0 -3
- package/dist/chunks/SGGMBSBA.js +0 -1
- package/dist/chunks/TOOIB6J2.js +0 -1
- package/dist/chunks/TYTQRLTX.js +0 -1
- package/dist/chunks/UCTEU62F.js +0 -1
- package/dist/chunks/UD3VJER6.js +0 -1
- package/dist/chunks/WUUKTSRT.js +0 -7
- package/dist/chunks/X65X4KP5.js +0 -7
- package/dist/chunks/YIR5MYGU.js +0 -1
- package/dist/chunks/YLNJXQ3Z.js +0 -1
- package/dist/kit/claim.d.ts +0 -13
- package/dist/kit/drain.d.ts +0 -10
- package/dist/kit/grants.d.ts +0 -9
- package/dist/kit/scope.d.ts +0 -32
- package/dist/kit/service.d.ts +0 -7
- package/dist/kit/strategy.d.ts +0 -10
- package/dist/kit/tool.d.ts +0 -72
- package/dist/llm/door.d.ts +0 -21
- package/dist/llm/door.js +0 -1
- package/dist/loop/projections.d.ts +0 -307
- package/dist/loop/state.d.ts +0 -70
- package/dist/loop/summary.d.ts +0 -3
- package/dist/models/config/agent.d.ts +0 -18
- package/dist/models/config/prompt.d.ts +0 -18
- package/dist/models/door.js +0 -1
- package/dist/models/index.d.ts +0 -7
- package/dist/plugins/commands/foreground.d.ts +0 -4
- package/dist/plugins/compaction/preset.d.ts +0 -86
- package/dist/plugins/compaction/shared.d.ts +0 -14
- package/dist/plugins/delegations/testing.d.ts +0 -16
- package/dist/plugins/providers/door.d.ts +0 -61
- package/dist/plugins/providers/door.js +0 -1
- package/dist/plugins/providers/index.d.ts +0 -6
- package/dist/plugins/routeContext.js +0 -1
- package/dist/plugins/store/durableObject.js +0 -1
- package/dist/plugins/store/sqlite.js +0 -1
- package/dist/plugins/subAgents/tool.d.ts +0 -38
- package/dist/plugins/tools/index.d.ts +0 -59
- package/dist/plugins/tools/index.js +0 -1
- package/dist/plugins/verify/facts.d.ts +0 -356
- package/dist/plugins/workflows/submit.d.ts +0 -8
- package/dist/plugins/workspaceContext.js +0 -1
- package/dist/presets/agents.d.ts +0 -7
- package/dist/presets/base.d.ts +0 -10
- package/dist/presets/index.d.ts +0 -4
- package/dist/sandbox/index.js +0 -4
- package/dist/sandbox/policy.d.ts +0 -86
- package/dist/services/launches.d.ts +0 -104
- package/dist/services/threadDirs.d.ts +0 -38
- package/dist/testing/sandbox.d.ts +0 -71
- /package/dist/chunks/{UKXMCHHT.js → FJLU4UH3.js} +0 -0
- /package/dist/chunks/{J5S4URAW.js → HK6ZSONF.js} +0 -0
- /package/dist/plugins/ask/{askQuestion.d.ts → tools.d.ts} +0 -0
- /package/dist/plugins/delegations/{waits.d.ts → waitContracts.d.ts} +0 -0
- /package/dist/plugins/{tools → fileTools}/fsRead.d.ts +0 -0
- /package/dist/plugins/{tools → fileTools}/ripgrep.d.ts +0 -0
- /package/dist/plugins/{tools → fileTools}/textEdit.d.ts +0 -0
- /package/dist/{util → plugins/mcp}/version.d.ts +0 -0
- /package/dist/{sandbox → plugins/sandbox}/client.d.ts +0 -0
- /package/dist/{sandbox → plugins/sandbox}/files.d.ts +0 -0
- /package/dist/{sandbox → plugins/sandbox}/protocol.d.ts +0 -0
- /package/dist/{sandbox → plugins/sandbox}/worker.d.ts +0 -0
- /package/dist/{sandbox → plugins/sandbox}/worker.js +0 -0
- /package/dist/plugins/skills/{tool.d.ts → tools.d.ts} +0 -0
- /package/dist/plugins/{tools → webTools}/html.d.ts +0 -0
- /package/dist/plugins/{tools → webTools}/network.d.ts +0 -0
- /package/dist/plugins/{tools → webTools}/web.d.ts +0 -0
- /package/dist/plugins/workflows/{work.d.ts → workStatus.d.ts} +0 -0
- /package/dist/{plugins/providers → providers}/codexAuth.d.ts +0 -0
- /package/dist/services/{contributions.d.ts → catalogContributions.d.ts} +0 -0
- /package/dist/{loop → state}/limits.d.ts +0 -0
- /package/dist/{plugins/store → stores}/durableObject.d.ts +0 -0
- /package/dist/{plugins/store → stores}/durableObjectConnection.d.ts +0 -0
- /package/dist/{plugins/store → stores}/sqlite.d.ts +0 -0
- /package/dist/{models → util}/jsonSchema.d.ts +0 -0
- /package/dist/{kit → util}/retries.d.ts +0 -0
- /package/dist/{kit → util}/timers.d.ts +0 -0
package/dist/chunks/NAOUTU7A.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{a as m}from"./UKXMCHHT.js";import{ja as l}from"./YLNJXQ3Z.js";import{a as p,e as i}from"./DDANMY45.js";import{e as f}from"./KESCTXGO.js";import{m as d}from"./D7E6EWIE.js";import{scopeOf as g}from"@leuduan/cordis";import{z as _}from"zod";function z(t){let{name:e,description:s,parameters:r}=t,o=r instanceof _.ZodType?r:null,n=d.parse({name:e,description:s,input_schema:o===null?r.jsonSchema:m(o)});return{name:e,executionMode:t.executionMode,onInterrupted:t.onInterrupted,buildSpec:()=>n,async invoke(c,h){let T=Date.now(),a;try{let u=o===null?c.arguments:o.parse(c.arguments);a=await t.execute(u,h,c)}catch(u){a=u instanceof _.ZodError?{output:i(u),is_error:!0,metadata:{validation_errors:u.issues}}:{output:p(u)||v(u),is_error:!0}}return l(a)?a:E(c,a,T)}}}var v=t=>t instanceof Error?t.constructor.name:typeof t;function S(t,e,s={}){let r=g(t);return t.effect(()=>{let o=t.tools.register(r,e.name,e),n=s.agents===void 0?()=>{}:t.tools.grant(r,s.agents,e.name);return()=>{n(),o()}})}function D(t,e,s){for(let o of e)S(t,o);let r=g(t);t.effect(()=>t.prompts.contribute(r,{tag:s.tag,slot:"instruction",agents:"all",render:({tools:o})=>o.filter(n=>e.includes(n.tool)).map(n=>s.guidance.get(n.name)).filter(Boolean).join(`
|
|
2
|
-
`)||null}))}function E(t,e,s){let r={...e.metadata};"duration_ms"in r||(r.duration_ms=Date.now()-s);let o={call_id:t.call_id,name:t.name,output:e.output,is_error:e.is_error??!1,notes:e.notes??null,metadata:r};if(e.concludes_turn!==void 0){if(e.concludes_turn!==!0)return{...o,output:`${e.output}
|
|
3
|
-
[the tool's result is not valid: concludes_turn must be true or left out]`,is_error:!0};o.concludes_turn=!0}if(e.content===void 0)return o;let n=f.shape.content.safeParse(e.content);return n.success?{...o,content:n.data}:{...o,output:`${e.output}
|
|
4
|
-
[the tool's non-text content was dropped: ${i(n.error)}]`,is_error:!0}}export{z as a,S as b,D as c};
|
package/dist/chunks/NDIM7MEW.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var s=class{pending=0;finished=!1;over=!1;get ended(){return this.over}operation(t,n=!1){this.pending+=1;let e=t(),i=()=>{this.pending-=1,n&&(this.finished=!0),this.check()};return e.then(i,i),e}finish(){this.finished=!0,this.check()}check(){this.finished&&this.pending===0&&(this.over=!0)}};export{s as a};
|
package/dist/chunks/O4PPOM5Z.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{b as u,e as l}from"./OVZFGILJ.js";import{b as m,e as s}from"./DRYAN665.js";import{a as c}from"./2OSESBIL.js";import{h as o}from"./37YOGDGY.js";import{a as d}from"./KESCTXGO.js";import{z as t}from"zod";var g=t.discriminatedUnion("kind",[t.strictObject({kind:t.literal("branch"),name:t.string()}),t.strictObject({kind:t.literal("detached"),commit:t.string()})]),b=t.strictObject({date:t.string(),time_zone:t.string(),head:g.nullable()}),j=m({plugin:"lagent:date-and-branch",kind:"date-and-branch-notice",version:1,schema:b}),y=o({key:"lagent:date-and-branch:last-request-turn",init:()=>({turn:0}),apply(n,e){return e.type==="llm/request"&&(n.turn=e.data.turn),n}}),A=t.strictObject({agents:c}),_={name:"lagent:date-and-branch",inject:["journal"],apply(n,e){let{agents:a}=A.parse(e);s(n,{event:j,agents:a,current(r){if(n.journal.state(y,r.threadId).turn>=r.turn)return;let i=n.journal.summary(r.threadId);return i===void 0?void 0:D(i.environment.cwd,new Date)},render:S})}};function D(n,e){let a=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((i,f)=>String(i).padStart(f===0?4:2,"0")).join("-"),r=u(n);return{date:a,time_zone:Intl.DateTimeFormat().resolvedOptions().timeZone,head:r===null?null:l(r)}}function S(n,e){let a=[`Today's date: ${n.date} (time zone ${n.time_zone})${p(e?.date,n.date)}`];if(n.head!==null||(e?.head??null)!==null){let r=h(n.head);a.push(`Git: ${r}${p(e===null?void 0:h(e.head),r)}`)}return d("date_and_branch",a.join(`
|
|
2
|
-
`))}function h(n){return n===null?"no branch":n.kind==="branch"?`on branch ${n.name}`:`detached HEAD at ${n.commit}`}var p=(n,e)=>n===void 0||n===e?"":` (previously ${n})`;export{_ as a,D as b,S as c};
|
package/dist/chunks/OVZFGILJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a}from"./G6RXC3AL.js";import{lstatSync as T,readFileSync as I,realpathSync as E,statSync as d}from"node:fs";import{dirname as m,join as c,resolve as o}from"node:path";var k=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE"];function R(t){let r=y(t);for(;;){let n=c(r,".git"),e=O(n);if(e!==null){let i=u(n),f=e==="directory"?i:S(n)??i;return{worktree:r,dotGit:i,gitDir:f,commonDir:h(f)}}let s=m(r);if(s===r)return null;r=s}}function x(t){let r=R(t);return r===null||r.worktree===y(t)?[]:[r.worktree]}function y(t){try{return a(o(t))}catch{return o(t)}}var _=7;function A(t){let r=l(c(t.gitDir,"HEAD"))?.trim();if(r===void 0)return null;let n=/^ref:[ \t]*(\S+)$/.exec(r);if(n!==null){let e=n[1];return{kind:"branch",name:e.startsWith("refs/heads/")?e.slice(11):e}}return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(r)?{kind:"detached",commit:r.slice(0,_)}:null}function O(t){let r;try{r=T(t)}catch{return null}if(!r.isSymbolicLink())return r.isDirectory()?"directory":"file";try{return d(t).isDirectory()?"directory":"file"}catch{return"file"}}function S(t){let r=l(t),n=r===null?null:/^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(r);return n===null?null:u(o(m(t),n[1]))}function h(t){let n=l(c(t,"commondir"))?.trim();return n===void 0||n===""?null:u(o(t,n))}function l(t){try{return d(t).size>4096?null:I(t,"utf8")}catch{return null}}function u(t){try{return E.native(t)}catch{return t}}export{k as a,R as b,x as c,y as d,A as e};
|
package/dist/chunks/P5ZHHOOM.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{a as N}from"./6ECI2GGV.js";import{d as k}from"./OVZFGILJ.js";import{c as S}from"./3QCW4WDJ.js";import{a as $}from"./L3N4FIEN.js";import{a as u}from"./PUSUPTAT.js";import{a as _}from"./G6RXC3AL.js";import{b as E,c as v}from"./DRYAN665.js";import{d as w}from"./DDANMY45.js";import{m as b}from"./KESCTXGO.js";import{closeSync as F,fstatSync as J,lstatSync as U,openSync as W,readSync as H}from"node:fs";import{basename as K,dirname as B,join as O}from"node:path";import{scopeOf as Q}from"@leuduan/cordis";import{z as a}from"zod";var T=a.string().min(1).refine(t=>K(t)===t&&t!=="."&&t!=="..","A name, not a path"),V=a.strictObject({fileNames:a.array(T).min(1),rootMarkers:a.array(T).min(1),maxBytes:a.number().int().positive()}),j="agents-md",X="agents-md",Y=a.strictObject({discovery:a.strictObject({file_names:a.array(a.string()),root_markers:a.array(a.string()),max_bytes:a.number().int().positive()}),root:a.string(),files:a.array(a.strictObject({path:a.string(),bytes:a.number().int().nonnegative(),told_bytes:a.number().int().nonnegative()}))}),A=E({plugin:"lagent:agents-md",kind:"agents-md-notice",version:4,schema:Y}),Z=["ENOENT","ENOTDIR"],tt=(t,n)=>t.max_bytes===n.maxBytes&&M(t.file_names,n.fileNames)&&M(t.root_markers,n.rootMarkers),M=(t,n)=>t.length===n.length&&t.every((e,r)=>e===n[r]);function x(t,n){let{holder:e,fileNames:r,rootMarkers:i,maxBytes:s}=n,c=Q(t);if(c===void 0)throw new Error(`${e} tells one thread: mount it in that thread's scope`);N(t,"agents-md",c,e,o=>`This thread is already told its AGENTS.md by ${o}; a thread has one agents-md, not ${e} too`),t.on("lagent/llm/step",o=>{let{threadId:d}=o,l=v(t.journal.state(A.told,d));if(l!==null&&tt(l.value.discovery,n)){l.visible||et(t.journal,o,l.row.seq);return}let m=t.journal.summary(d);if(m===void 0)return;let{environment:p}=m,f=k(p.cwd),g=nt({ctx:t,environment:p}),h=rt(f,i,g),y=st(ot(h,f),r,s,g),G=y.length===0?lt(h,f,r):ct(y,r,s),L=y.map(({path:C,bytes:P,told_bytes:q})=>({path:C,bytes:P,told_bytes:q})),z={file_names:[...r],root_markers:[...i],max_bytes:s};o.contribute(A.contribution({content:G},{discovery:z,root:h,files:L}))})}var kt=$({id:j,placement:"thread",schema:V,inject:["journal","threadDirs"],setup(t,n,e){if(e.kind==="selected"){x(t,{holder:"agents-md for its agents",...n});return}x(t,{holder:`agents-md installation ${e.installationId}`,...n}),S(t,{presetId:j,config:n,installationId:X})}});function et(t,n,e){let r=t.eventAt(e);if(r?.type!=="input/message"||r.data.source===null)throw new Error(`Row ${e} is not the AGENTS.md notice it was folded from`);let{role:i,content:s,source:c}=r.data;n.contribute(b({role:i,content:s,source:c,source_seqs:[r.seq]}))}function nt(t){let n;try{n=_(t,"read")}catch(e){return u.warn("Reading no AGENTS.md: the roots the thread may read cannot be resolved",e),()=>!1}return e=>{try{return n.containsSync(e)}catch{return!1}}}function rt(t,n,e){for(let r=t;;){if(n.some(s=>D(O(r,s))))return r;let i=B(r);if(i===r||!e(i))return t;r=i}}function D(t){try{return U(t),!0}catch{return!1}}function ot(t,n){let e=[n];for(;e[0]!==t;)e.unshift(B(e[0]));return e}function st(t,n,e,r){let i=[],s=e;for(let c of t)for(let o of n){let d=O(c,o);if(!D(d))continue;if(!r(d)){u.warn(`Skipping ${d}`,new Error("it resolves outside what the thread may read"));continue}let l=it(d,s);if(l!==null){i.push(l),s-=l.told_bytes;break}}return i}function it(t,n){let e;try{e=W(t,"r")}catch(r){return w(r,...Z)||u.warn(`Skipping ${t}`,r),null}try{let r=J(e);if(!r.isFile())return u.warn(`Skipping ${t}`,new Error("not a regular file")),null;let i=Buffer.alloc(Math.min(r.size,n)+1),s=0;for(;s<i.byteLength;){let m=H(e,i,s,i.byteLength-s,s);if(m===0)break;s+=m}let c=i.subarray(0,s),o=s>n,d=o?c.subarray(0,at(c,n)):c,l=d.toString("utf8");return!o&&l.trim()===""?null:{path:t,bytes:Math.max(r.size,s),told_bytes:d.byteLength,text:l}}catch(r){return u.warn(`Skipping ${t}`,r),null}finally{F(e)}}function at(t,n){let e=n;for(;e>0&&(t[e]&192)===128;)e-=1;return e}var I=t=>t.length===1?t[0]:`${t.slice(0,-1).join(", ")} or ${t.at(-1)}`,R=t=>`When you work in a directory below the working directory, look there for ${I(t)} and follow it within that directory's tree.`;function ct(t,n,e){let r=["The following workspace instructions may be relevant to your work. Use them as guidance when applicable.",`They are the instruction files from the project root down to the working directory, root first. Each governs the directory tree it is in, and where two conflict, the deeper one wins. System, developer and direct user instructions take precedence over any of them. ${R(n)}`].join(`
|
|
2
|
-
`),i=t.filter(o=>o.told_bytes>0).map(o=>`<agents_md path=${JSON.stringify(o.path)}>
|
|
3
|
-
${o.text}
|
|
4
|
-
</agents_md>`),s=t.flatMap(o=>o.told_bytes>=o.bytes?[]:o.told_bytes===0?[`${o.path} (${o.bytes} bytes) was left out`]:[`${o.path} was cut after ${o.told_bytes} of its ${o.bytes} bytes`]),c=s.length===0?[]:[`[Truncated at ${e} bytes in all: ${s.join(", and ")}. Read the rest with read_file.]`];return[r,...i,...c].join(`
|
|
5
|
-
|
|
6
|
-
`)}function lt(t,n,e){let r=t===n?`in ${n}`:`in ${n} or above it up to the project root, ${t}`;return`There is no ${I(e)} ${r}: this workspace gives no instructions of its own. ${R(e)}`}export{V as a,j as b,X as c,x as d,kt as e};
|
package/dist/chunks/QMMLQJBS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function i(t,e,n){let r=t.get(e);if(r==null)throw new Error(`${n} needs ctx.${e}, which is not mounted: mount the ${e} plugin first`);return r}export{i as a};
|
package/dist/chunks/RK3VP2Q4.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{b as d}from"./2OSESBIL.js";import{r as u}from"./YLNJXQ3Z.js";import{a as m}from"./KESCTXGO.js";import{Service as k,scopeOf as w,scopeParentOf as S,ScopeLayers as B}from"@leuduan/cordis";function g(s){let t=[];s.basePrompt.trim()&&t.push({kind:"base",tag:null,text:s.basePrompt.trim()});let e=(i,n)=>i.filter(r=>r.content.trim().length>0).map(r=>({kind:n,tag:r.tag,text:m(r.tag,r.content.trim())}));return t.push(...e(s.instructions,"instruction")),t.push(...e(s.contextSections,"context")),t}var x=class extends k{static inject=["agents","tools"];layers=new B(()=>[]);constructor(t){super(t,"prompts")}contribute(t,e){let i=this.layers.layer(t);return i.push(e),()=>{let n=i.indexOf(e);n>=0&&i.splice(n,1)}}render(t,e,i){let n=this.ctx.agents.resolve(t,e);if(n===void 0)throw new u(e);let{agent:r}=n,b={agent:r,thread:i,tools:this.ctx.tools.toolsFor(t,e)},a={base:r.basePrompt?[{tag:"base",content:r.basePrompt}]:[],instruction:[],context:[]},y=new Set(n.layer===void 0?[]:this.layers.closestFirst(S(n.layer)));for(let l of this.layers.globalFirst(t)){let h=l.filter(o=>d(o.agents,e)).filter(o=>o.slot!=="base"||!y.has(l)).sort((o,c)=>(o.order??0)-(c.order??0)||o.tag.localeCompare(c.tag));for(let o of h){let c=a[o.slot],f=o.render(b),p=c.findIndex(P=>P.tag===o.tag);f===null?p>=0&&c.splice(p,1):p>=0?c[p]={tag:o.tag,content:f}:c.push({tag:o.tag,content:f})}}return g({basePrompt:a.base.map(l=>l.content).join(`
|
|
2
|
-
|
|
3
|
-
`),instructions:a.instruction,contextSections:a.context})}},I=(s,t)=>s.effect(()=>s.prompts.contribute(w(s),t));export{x as a,I as b};
|
package/dist/chunks/SGGMBSBA.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as l}from"./2OSESBIL.js";import{r as m}from"./YLNJXQ3Z.js";import{d as f}from"./KESCTXGO.js";import{scopeOf as c,ScopeLayers as d,Service as p}from"@leuduan/cordis";import{z as i}from"zod";var g=i.strictObject({name:i.string(),basePrompt:i.string().default("")});var u=class extends p{layers=new d(()=>new Map);constructor(e){super(e,"agents")}names(e){return f(this.all(e).map(r=>r.name))}all(e){let r=new Map;for(let t of this.layers.globalFirst(e))for(let[o,{agent:s}]of t)r.set(o,s);return[...r.values()]}has(e,r){return this.resolve(e,r)!==void 0}get(e,r){return this.resolve(e,r)?.agent}require(e,r){let t=this.get(e,r);if(t===void 0)throw new m(r);return t}resolve(e,r){for(let t of this.layers.closestFirst(e)){let o=t.get(r);if(o!==void 0)return o}}register(e,r){let t=g.parse(r),o=l(t.name);if(e===void 0&&o)throw new Error(`Agent ${t.name} is registered globally, so its name must not contain a dot`);if(e!==void 0&&!o)throw new Error(`Agent ${t.name} is registered in a scope, so its name must contain a dot`);let s=this.layers.layer(e);if(s.has(t.name))throw new Error(`Agent already registered for name: ${t.name}`);let a={agent:t,layer:e};return s.set(t.name,a),()=>{s.get(t.name)===a&&s.delete(t.name)}}},$=(n,e)=>n.effect(()=>n.agents.register(c(n),e));import{scopeOf as h}from"@leuduan/cordis";function F(n,e,r){return n.effect(()=>n.tools.grant(h(n),r,e))}export{u as a,$ as b,F as c};
|
package/dist/chunks/TOOIB6J2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as u,e as i}from"./DRYAN665.js";import{a as r}from"./KESCTXGO.js";import{e as o}from"./TYTQRLTX.js";var c=u({plugin:"lagent:route-context",kind:"route-notice",version:1,schema:o}),a={name:"lagent:route-context",inject:["journal"],apply(e){i(e,{event:c,current:t=>t.route,render:l})}};function l(e,t){let f=t===null?`You run on ${n(e)}.`:`You now run on ${n(e)} (previously ${n(t)}).`;return r("current_route",f)}function n(e){let t=e.thinking_effort===null?"the provider's default effort":`effort ${e.thinking_effort}`;return`${e.provider}, ${e.model}, ${t}`}export{a,l as b,n as c};
|
package/dist/chunks/TYTQRLTX.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a,c,d as l,e as m,k as p}from"./D7E6EWIE.js";import{z as k}from"zod";var g=["rate_limit","overloaded","transport","timeout","empty","length","invalid","auth","quota","overflow","other"],x=k.enum(g),h=class extends Error{provider;kind;attempts;retryAfterMs;constructor(n,r,t,i,o){super(E(o.cause),o),this.provider=n,this.kind=r,this.attempts=t,this.retryAfterMs=i,this.name="ModelCallError"}},E=e=>e instanceof Error?e.message:String(e);function M(e,n){let r=d(n,c);if(r!==void 0)return{kind:r.kind};if(d(n,a)!==void 0)return{kind:"overflow"};if(d(n,l)!==void 0)return{kind:"timeout"};let t=d(n,m),i;try{i=e.classify(t===void 0?n:t.cause)}catch{return{kind:"other"}}let o=x.safeParse(i?.kind).success?i.kind:"other",s=i?.retryAfterMs,f=typeof s=="number"&&Number.isFinite(s)&&s>=0?Math.ceil(s):void 0;return f===void 0||!Number.isSafeInteger(f)?{kind:o}:{kind:o,retryAfterMs:f}}function d(e,n){let r=new Set,t=e;for(;t instanceof Error&&!r.has(t);){if(t instanceof n)return t;r.add(t),t=t.cause}}import{z as u}from"zod";var I=u.object({provider:u.string(),model:u.string(),thinking_effort:p.nullable()}),R=e=>y(e,void 0,void 0),y=(e,n,r)=>({provider:e.name,model:n??e.defaultModel,thinking_effort:r??e.defaultThinkingEffort??null});export{x as a,h as b,M as c,d,I as e,R as f,y as g};
|
package/dist/chunks/UCTEU62F.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as b}from"./C5LYCXJG.js";import{a as S,d as v}from"./J5S4URAW.js";import{a as l}from"./QMMLQJBS.js";import{a as k}from"./YIR5MYGU.js";import{a as y,b as q}from"./NAOUTU7A.js";import{a as w,d as g}from"./2OSESBIL.js";import{b as p,ia as f}from"./YLNJXQ3Z.js";import{z as E}from"zod";import{z as n}from"zod";import{Service as T}from"@leuduan/cordis";import{z as s}from"zod";var a="lagent:ask",x=s.strictObject({deadlineMs:s.number().int().positive().max(Number.MAX_SAFE_INTEGER).nullable(),clock:S}),I=s.strictObject({id:s.string(),label:s.string(),description:s.string()}),_=s.strictObject({v:s.literal(1),question:s.string(),options:s.array(I).nullable(),agent:s.string()}),O=s.union([s.strictObject({v:s.literal(1),answer:s.string()}),s.strictObject({v:s.literal(1),timeout:s.literal(!0)})]),c=class extends Error{threadId;callSeq;recorded;constructor(e,r,t){super(`The question of call ${r} on thread ${e} was already ${"answer"in t?"answered":"closed by its deadline"}`),this.threadId=e,this.callSeq=r,this.recorded=t,this.name="QuestionAnsweredError"}},u=class extends Error{threadId;callSeq;constructor(e,r){super(`No question of call ${r} on thread ${e} is open`),this.threadId=e,this.callSeq=r,this.name="QuestionClosedError"}};function j(o){return{question:_.parse(o.dependency).question,value:O.parse(o.value)}}var d=(o,e)=>`${o}\0${e}`,h=class extends T{static inject=["threads","journal"];config;deadlines;handle;timingOut=new Set;retries;closing=!1;constructor(e,r){super(e,"ask"),this.config=x.parse(r),this.deadlines=v(this.config.clock,t=>e.reportError(t)),this.retries=b(this.config.clock,t=>e.reportError(t)),e.effect(()=>()=>{this.deadlines.dispose(),this.retries.dispose()}),e.effect(()=>e.journal.subscribe(t=>this.onRow(t))),e.effect(()=>{let t=e.threads.registerOwner({owner:a,repair:()=>this.repair()});return this.handle=t,()=>{this.handle=void 0,t.dispose()}}),k(e,()=>this.shutdown())}ask(e,r){let{deadlineMs:t,clock:i}=this.config,m=t===null||this.ctx.threads.chain(e.threadId).atLimit;return f({owner:a,dependency:{v:1,question:r.question,options:r.options,agent:e.agentName},deadlineAt:m?null:i.now()+t,reason:"waiting for the user's answer"})}open(e){return this.ctx.threads.view(e).waits({owner:a}).flatMap(r=>{let{declaration:t}=r;if(!p(r))return[];let{question:i,options:m,agent:Q}=_.parse(t.dependency);return[{threadId:e,callSeq:t.call_seq,question:i,options:m,agent:Q,deadlineAt:t.deadline_at}]})}async answer(e,r){let t=await this.registration().resolveWait(e,()=>({value:{v:1,answer:r},chain:"person"}));if(t.status!=="resolved")throw t.status==="resolved-before"?new c(e.threadId,e.callSeq,O.parse(t.value)):new u(e.threadId,e.callSeq)}registration(){if(this.handle===void 0)throw new Error("The ask service is not registered");return this.handle}onRow(e){if(e.type==="wait/declared"){if(e.data.owner!==a)return;this.arm(e.thread_id,e.data)}else e.type==="wait/resolved"?this.disarm(d(e.thread_id,e.data.call_seq)):e.type==="tool/result"&&this.disarm(d(e.thread_id,e.source_seqs[0]??0))}disarm(e){this.deadlines.delete(e),this.retries.clear(e)}arm(e,r){let t=r.deadline_at;if(t===null)return;let i={threadId:e,callSeq:r.call_seq};this.deadlines.set(d(e,r.call_seq),t,()=>{this.timeout(i)})}timeout(e){if(this.closing||this.handle===void 0)return Promise.resolve();let r=d(e.threadId,e.callSeq),t=this.handle.resolveWait(e,()=>({value:{v:1,timeout:!0}})).then(()=>this.retries.succeeded(r),i=>{this.ctx.reportError(i),this.closing||this.retries.failed(r,()=>{this.timeout(e)})});return this.timingOut.add(t),t.finally(()=>this.timingOut.delete(t)),t}async repair(){let e=this.config.clock.now(),r=[];for(let t of this.ctx.journal.summaries())for(let i of t.waits)i.owner!==a||i.resolved||i.deadline_at===null||(i.deadline_at>e?this.arm(t.thread_id,i):r.push(this.timeout({threadId:t.thread_id,callSeq:i.call_seq})));await Promise.all(r)}async shutdown(){this.closing=!0,await Promise.allSettled([...this.timingOut])}};var N=n.strictObject({question:n.string().describe("The question to ask the user."),options:n.array(n.strictObject({id:n.string(),label:n.string(),description:n.string().default("")})).nullable().default(null).describe("Optional predefined answers; the user may always reply freely.")}),A=o=>y({name:o,description:"Ask the user a question and wait for their answer. Use it only when you cannot proceed without their input.",parameters:N,onInterrupted:"rerun",executionMode:"exclusive",async execute(e,r){if(r.wait===null)return l(r.ctx,"ask",o).ask(r,e);let{question:t,value:i}=j(r.wait);return"answer"in i?{output:i.answer,metadata:{question:t}}:{output:"No answer came before the question's deadline. Continue with work that does not depend on it, and state the assumption you make; the user can still reply in a later message.",metadata:{question:t,timed_out:!0}}}});var Z={name:"lagent:ask",inject:["threads","journal"],async apply(o,e){g(o,"ask"),await o.plugin(h,e)}},$=E.object({name:E.string().default("ask_question"),agents:w}),ee={name:"lagent:ask-question",inject:["tools","agents"],apply(o,e){let{name:r,agents:t}=$.parse(e);l(o,"ask","askQuestion"),q(o,A(r),{agents:t})}};export{a,c as b,u as c,Z as d,ee as e};
|
package/dist/chunks/UD3VJER6.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function f(e){if(e.durable.state==="unknown")return null;if(e.executing)return{state:"running"};if(e.durable.state==="settled"){let{outcome:r,reason:n,errorText:s}=e.durable.settlement;return{state:"settled",outcome:r,reason:n,errorText:s}}return e.held===null?{state:"requested"}:{state:"held",...e.held}}var l=class extends Error{threadId;runId;constructor(r,n){super(`Run ${n} of thread ${r} is unknown to the catalog`),this.threadId=r,this.runId=n,this.name="UnknownRunError"}};function x(e,r,n,s,o){return new Promise((h,a)=>{let i=!1,u=t=>{i||(i=!0,b(),o?.removeEventListener("abort",d),t())},c=()=>{try{let t=e.runState(r,n);t===null?u(()=>a(new l(r,n))):s(t)&&u(()=>h(t))}catch(t){u(()=>a(t))}},d=()=>u(()=>a(o.reason)),b=e.onRunEvent(t=>{t.threadId===r&&t.runId===n&&c()});if(o?.aborted)return d();o?.addEventListener("abort",d,{once:!0}),c()})}var m=e=>e.state==="held"||e.state==="settled";export{f as a,l as b,x as c,m as d};
|
package/dist/chunks/WUUKTSRT.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{a as Qe}from"./NDIM7MEW.js";import{a as Ee,b as W}from"./34KW6VNQ.js";import{a as et}from"./PUSUPTAT.js";import{d as Ze,h as Z}from"./DDANMY45.js";import{A as Q,a as c,b as I,c as ge,d as Ve,e as Je,i as J,j as f,q as Y,s as Ye,u as w,w as E}from"./D7E6EWIE.js";import{createHash as Ro}from"node:crypto";import{isAbsolute as Ao}from"node:path";import{promisify as mt}from"node:util";import*as G from"node:zlib";import"openai";import{z as L}from"zod";import{chmod as Yt,readFile as Qt,rename as Zt,rm as eo,writeFile as to}from"node:fs/promises";import{AsyncLocalStorage as oo}from"node:async_hooks";import{randomUUID as no}from"node:crypto";import{basename as ro,dirname as so,isAbsolute as io,join as be,normalize as ao}from"node:path";import"openai";import A from"openai";import{z as y}from"zod";function ee(o){switch(o){case 401:case 403:return"auth";case 402:return"quota";case 408:return"timeout";case 409:case 503:case 529:return"overloaded";case 429:return"rate_limit";default:return o>=500?"transport":void 0}}function te(o,e,t){if(o==="auth"||o==="other")return{kind:o};let n=jt(e,t);return n===void 0?{kind:o}:{kind:o,retryAfterMs:n}}var tt={ECONNRESET:"transport",ECONNREFUSED:"transport",EPIPE:"transport",EAI_AGAIN:"transport",UND_ERR_SOCKET:"transport",UND_ERR_CLOSED:"transport",ETIMEDOUT:"timeout",UND_ERR_CONNECT_TIMEOUT:"timeout",UND_ERR_HEADERS_TIMEOUT:"timeout",UND_ERR_BODY_TIMEOUT:"timeout"};function oe(o){let e=new Set,t=o;for(;typeof t=="object"&&t!==null&&!e.has(t);){e.add(t);let n=t.code;if(typeof n=="string"&&Object.hasOwn(tt,n))return tt[n];t=t.cause}return"other"}function jt(o,e){if(o===void 0)return;let t=o.get("retry-after-ms");if(t!==null&&/^\d+(\.\d+)?$/.test(t.trim()))return ye(Math.ceil(Number(t.trim())));let n=o.get("retry-after")?.trim();if(n===void 0||n==="")return;if(/^\d+$/.test(n))return ye(Number(n)*1e3);let r=Kt(n,e);return r===void 0?void 0:ye(Math.max(0,r-e))}var ot="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)",Ft="(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)",nt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],xe=`(${nt.join("|")})`,we="(\\d{2}):(\\d{2}):(\\d{2})",Wt=new RegExp(`^${ot}, (\\d{2}) ${xe} (\\d{4}) ${we} GMT$`),Bt=new RegExp(`^${Ft}, (\\d{2})-${xe}-(\\d{2}) ${we} GMT$`),Ht=new RegExp(`^${ot} ${xe} ( \\d|\\d{2}) ${we} (\\d{4})$`);function Kt(o,e){let t,n=Wt.exec(o);if(n!==null)t=[n[1],n[2],n[3],n[4],n[5],n[6]];else if((n=Bt.exec(o))!==null){let N=new Date(e).getUTCFullYear(),V=Math.floor(N/100)*100+Number(n[3]);V>N+50&&(V-=100),t=[n[1],n[2],String(V),n[4],n[5],n[6]]}else if((n=Ht.exec(o))!==null)t=[n[2].trim(),n[1],n[6],n[3],n[4],n[5]];else return;let[r,s,i,a,l,u]=[Number(t[0]),nt.indexOf(t[1]),Number(t[2]),Number(t[3]),Number(t[4]),Number(t[5])],x=new Date(Date.UTC(i,s+1,0)).getUTCDate();if(!(r<1||r>x||a>23||l>59||u>60))return Date.UTC(i,s,r,a,l,u)}var ye=o=>Number.isSafeInteger(o)?o:void 0;import{AsyncLocalStorage as qt}from"node:async_hooks";import{z as zt}from"zod";var O=zt.number().int().positive().max(W).nullable();function M(o,e,t){if(t==null||t==="")return{call_id:o,name:e,arguments:{}};if(typeof t=="object"&&!Array.isArray(t))return{call_id:o,name:e,arguments:t};let n=(s,i)=>({call_id:o,name:e,arguments:null,malformed:{raw:s,error:i}});if(typeof t!="string")return n(JSON.stringify(t)??String(t),"not a JSON object");let r;try{r=JSON.parse(t)}catch(s){return n(t,`invalid JSON: ${s instanceof Error?s.message:String(s)}`)}return r===null||typeof r!="object"||Array.isArray(r)?n(t,"JSON that is not an object"):{call_id:o,name:e,arguments:r}}var rt=new qt;async function ne(o){let e=rt.getStore();e?.hold();try{return await o()}finally{e?.release()}}var ke=class{controller=new AbortController;closure=new Error("The reader closed the stream");timer;expiredAt=!1;holds=0;forward;provider;requestSignal;idleMs;constructor(e,t,n){this.provider=e,this.requestSignal=t,this.idleMs=n,this.forward=()=>{this.clearTimer(),this.controller.abort(this.requestSignal?.reason)},t?.aborted===!0?this.forward():t?.addEventListener("abort",this.forward,{once:!0}),this.arm()}opening(e){return rt.run(this,e)}hold(){this.holds+=1,this.clearTimer()}release(){this.holds-=1,this.holds===0&&this.arm()}get signal(){return this.controller.signal}get expired(){return this.expiredAt}idleError(){return new Ve(this.provider,this.idleMs??0)}async*events(e){for await(let t of e){if(this.expiredAt)return;this.arm(),yield t}}close(){this.dispose(),this.controller.signal.aborted||this.controller.abort(this.closure)}closedBy(e){return e===this.closure}dispose(){this.clearTimer(),this.requestSignal?.removeEventListener("abort",this.forward)}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}arm(){this.idleMs===null||this.expiredAt||this.holds>0||this.controller.signal.aborted||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=void 0,this.expiredAt=!0,this.controller.abort(this.idleError()),this.requestSignal?.removeEventListener("abort",this.forward)},this.idleMs),this.timer.unref?.())}};async function P(o,e,t,n,r){let s=new ke(o,e,t);try{return{lifetime:s,opened:await s.opening(()=>n(s.signal))}}catch(i){throw s.dispose(),s.expired?s.idleError():r(i)}}var k=class{claimed=!1;ledger=new Qe;abortedAtEnd=!1;drained=!1;closedByReader=!1;readFailure;providerName;signal;lifetime;constructor(e,t,n){this.providerName=e,this.signal=t,this.lifetime=n}[Symbol.asyncIterator](){if(this.claimed)throw new Error("A response is read once: it has been claimed already");this.claimed=!0;let e=this.readThrough(),t=()=>{this.closedByReader=!0,this.lifetime.close()};return{next:()=>this.ledger.operation(()=>e.next()),return:n=>(t(),this.ledger.operation(()=>e.return(n),!0)),throw:n=>(t(),this.ledger.operation(()=>e.throw(n),!0))}}async*readThrough(){try{try{yield*this.read()}catch(e){if(!this.lifetime.expired&&!this.lifetime.closedBy(e)&&!this.cancelled(e))throw this.failed(this.interrupted(e))}if(this.lifetime.expired&&this.settle()===void 0)throw this.failed(this.interrupted(this.lifetime.idleError()));this.closedByReader||(this.drained=!0)}finally{this.lifetime.dispose(),this.abortedAtEnd=this.signal?.aborted===!0,this.ledger.finish()}}cancelled(e){return this.signal!==void 0&&Z(this.signal,e)}interrupted(e){let{message:t,providerMetadata:n}=this.partial();return E(t)!==""||(t.reasoning_content??"")!==""?new Je(this.providerName,t,n,{cause:e}):e}failed(e){return this.readFailure={error:e},e}async completed(){if(this.claimed){if(!this.ledger.ended)throw new Error("A response is settled before its read or after it, not while the read is under way")}else for await(let t of this);if(this.readFailure!==void 0)throw this.readFailure.error;if(!this.drained||this.abortedAtEnd){let{message:t,providerMetadata:n}=this.partial();return{message:t,finish:"other",provider_metadata:n}}let e=this.settle();if(e===void 0){let{message:t,providerMetadata:n}=this.partial();throw new ge(this.providerName,"transport",t,n,`the response from '${this.providerName}' ended before the provider said it was complete`)}if(E(e.message)===""&&e.message.tool_calls.length===0){let t=e.finish==="completed"?"empty":e.finish;throw new ge(this.providerName,t,null,e.provider_metadata,`'${this.providerName}' ended a response with no text and no tool call (finish: ${e.finish})`)}return e}};var Gt=["tools","tool_choice","parallel_tool_calls","truncation","context_management"],Oe=y.record(y.string(),y.unknown()).superRefine((o,e)=>{let t=Gt.filter(n=>Object.hasOwn(o,n));t.length!==0&&e.addIssue({code:"custom",message:`extraBody may not set ${t.join(", ")}: the typed tool lists are the only tools a request may carry, and nothing may drop input before a context overflow can be seen`})}),K=(o,e)=>Object.hasOwn(o,e)?o[e]:null,q="context_length_exceeded",B=class extends Error{};function T(o,e,t,n){if(e instanceof A.APIUserAbortError&&n?.aborted===!0)return n.reason;if(e instanceof A.APIConnectionError&&e.cause instanceof B)return e.cause;if(!(e instanceof A.APIError))return e;let r=e.error,s={code:e.code,type:e.type,message:r?.message??e.message};return t(s)?new I(o,{cause:e}):e}var H=class extends Error{code;type;constructor(e,t){super(typeof e.message=="string"&&e.message?e.message:t),this.name="ProviderStreamError",this.code=e.code,this.type=e.type}},st={rate_limit_exceeded:"rate_limit",server_error:"transport",server_overloaded:"overloaded",[q]:"overflow"},Xt=new Set(["insufficient_quota","usage_limit_reached","workspace_owner_usage_limit_reached","workspace_member_usage_limit_reached","workspace_owner_credits_depleted","workspace_member_credits_depleted"]),at=o=>[o.code,o.type].some(e=>typeof e=="string"&&Xt.has(e));function b(o,e=Date.now()){if(o instanceof A.APIConnectionTimeoutError)return{kind:"timeout"};if(o instanceof A.APIConnectionError)return{kind:"transport"};if(o instanceof A.APIError){let{status:t}=o;if(t===void 0)return{kind:it(o)};let n=at(o)?"quota":ee(t)??"other";return te(n,o.headers,e)}return o instanceof H?{kind:it(o)}:{kind:oe(o)}}function it(o){if(at(o))return"quota";let{code:e}=o;return typeof e=="string"&&Object.hasOwn(st,e)?st[e]:"other"}var re={maxRetries:0},se="https://api.openai.com/v1",v=y.object({apiKey:y.string().min(1).optional(),streamIdleTimeoutMs:O,baseURL:y.string().optional(),defaultHeaders:y.record(y.string(),y.string()).optional(),extraBody:Oe.optional(),thinkingEffort:y.enum(f).optional()}),Vt=A,Jt=class extends Vt{constructor(e){super(e),this._options={...this._options,defaultHeaders:e.defaultHeaders}}};function z(o){return new Jt({apiKey:o.apiKey,baseURL:o.baseURL,organization:null,project:null,adminAPIKey:null,webhookSecret:null,logLevel:"warn",...o.defaultHeaders===void 0?{}:{defaultHeaders:o.defaultHeaders},maxRetries:0,...o.fetch===void 0?{}:{fetch:o.fetch}})}function D(o,e,t){if(t!==void 0)return t;let{apiKey:n,baseURL:r,defaultHeaders:s}=e;if(n===void 0)throw new Error(`${o} needs an \`apiKey\`: lagent reads no environment, so the host resolves the credential`);return z({apiKey:n,baseURL:r,...s===void 0?{}:{defaultHeaders:s}})}var Se="https://chatgpt.com/backend-api/codex",lo="https://auth.openai.com/oauth/token",co="app_EMoamEEZ73f0CkXaXp7hrann",uo=300*1e3,po=11520*60*1e3,p=class extends B{constructor(e){super(e),this.name="CodexCredentialError"}},ho=(o,e)=>be(o.CODEX_HOME||be(e,".codex"),"auth.json"),lt=o=>{if(!io(o))throw new Error(`The Codex login file must be an absolute path: ${o}`);return ao(o)},ve=class{authPath;refreshTimeoutMs;refreshUrl;oauthClientId;fetchImpl;queue=Promise.resolve();constructor(e){if(this.authPath=lt(e.authPath),!Number.isInteger(e.refreshTimeoutMs)||e.refreshTimeoutMs<=0||e.refreshTimeoutMs>W)throw new Error(`The Codex refresh timeout must be a whole number of milliseconds from 1 to ${W}: ${e.refreshTimeoutMs}`);this.refreshTimeoutMs=e.refreshTimeoutMs,this.refreshUrl=e.refreshUrl??lo,this.oauthClientId=e.oauthClientId??co,this.fetchImpl=e.fetch??globalThis.fetch}credentials(){return this.serialize(async()=>{let e=await this.read();return this.needsRefresh(e)?(await this.refresh(e)).credentials:e.credentials})}recoverUnauthorized(e){return this.serialize(async()=>{let t=await this.read();if(t.credentials.accountId!==e.accountId)throw new p("Codex account changed while recovering authentication");return t.credentials.accessToken!==e.accessToken?t.credentials:(await this.refresh(t)).credentials})}serialize(e){let t=this.queue.then(e,e);return this.queue=t.then(()=>{},()=>{}),t}async read(){let e;try{e=JSON.parse(await Qt(this.authPath,"utf8"))}catch(r){throw Ze(r,"ENOENT")?new p(`Codex auth file not found: ${this.authPath}; run \`codex login\``):new p(`Unable to read Codex auth file: ${this.authPath}`)}let t=ie(e)?e:{};if(t.auth_mode!=="chatgpt")throw new p("CodexLLMClient requires file-backed ChatGPT auth; run `codex login`");let n=t.tokens;if(!ie(n))throw new p("Codex auth file does not contain ChatGPT tokens; run `codex login`");return{credentials:{accessToken:Te(n,"access_token"),refreshToken:Te(n,"refresh_token"),accountId:Te(n,"account_id")},raw:t,lastRefresh:fo(t.last_refresh)}}needsRefresh(e){let t=Date.now(),n=mo(e.credentials.accessToken);return n!==null?n<=t+uo:e.lastRefresh!==null&&e.lastRefresh.getTime()<t-po}async refresh(e){let t=await this.requestRefresh(e.credentials.refreshToken),n=await this.read();if(n.credentials.accountId!==e.credentials.accountId)throw new p("Codex account changed during credential refresh");if(n.credentials.refreshToken!==e.credentials.refreshToken)return n;let r=n.raw.tokens;for(let s of["access_token","refresh_token","id_token"]){let i=t[s];typeof i=="string"&&i&&(r[s]=i)}return n.raw.last_refresh=new Date().toISOString(),await this.write(n.raw),this.read()}async requestRefresh(e){let t=AbortSignal.timeout(this.refreshTimeoutMs),n=async()=>{let r=await this.fetchImpl(this.refreshUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:this.oauthClientId,grant_type:"refresh_token",refresh_token:e}),signal:t});if(!r.ok)throw new Error(`refresh failed with status ${r.status}`);let s=await r.json();return ie(s)?s:{}};try{return await Ee(n(),t)}catch{throw new p(t.aborted?`Codex ChatGPT credential refresh did not finish within ${this.refreshTimeoutMs} ms; try again, or run \`codex login\``:"Unable to refresh Codex ChatGPT credentials; run `codex login`")}}async write(e){let t=be(so(this.authPath),`.${ro(this.authPath)}.${no().replaceAll("-","")}.tmp`);try{await to(t,`${JSON.stringify(e,null,2)}
|
|
2
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),await Yt(t,384),await Zt(t,this.authPath)}finally{await eo(t,{force:!0})}}},dt=new Map;function Re(o,e){let t=lt(o),n=dt.get(t);if(n===void 0)n=new ve({authPath:t,refreshTimeoutMs:e.refreshTimeoutMs}),dt.set(t,n);else if(n.refreshTimeoutMs!==e.refreshTimeoutMs)throw new Error(`The Codex login ${t} is already in use with a refresh timeout of ${n.refreshTimeoutMs} ms, not ${e.refreshTimeoutMs} ms: every client of one login shares one setting`);return n}var ie=o=>typeof o=="object"&&o!==null&&!Array.isArray(o);function Te(o,e){let t=o[e];if(typeof t!="string"||!t)throw new p("Codex auth file contains incomplete ChatGPT credentials; run `codex login`");return t}function fo(o){if(typeof o!="string")return null;let e=new Date(o);return Number.isNaN(e.getTime())?null:e}function mo(o){let e=o.split(".");if(e.length!==3)return null;try{let t=JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")),n=ie(t)?t.exp:void 0;return typeof n!="number"||!Number.isFinite(n)?null:n*1e3}catch{return null}}var _o=(o,e=globalThis.fetch)=>async(t,n={})=>{let r=ct.getStore(),s=r?.owner===o?r.credentials:void 0;r!==void 0&&s!==void 0&&(r.credentials=void 0);let i=s??await ne(()=>Ce(o.credentials(),n.signal));for(let a=0;;a+=1){let l=new Headers(n.headers);l.set("Authorization",`Bearer ${i.accessToken}`),l.set("ChatGPT-Account-ID",i.accountId);let u=await e(t,{...n,headers:l});if(u.status!==401||a>0)return u;await u.body?.cancel(),i=await ne(()=>Ce(o.recoverUnauthorized(i),n.signal))}},Ce=(o,e)=>e?Ee(o,e):o,ct=new oo;async function Ae(o,e,t){let n=await ne(()=>Ce(o.credentials(),e)),r={owner:o,credentials:n};try{return await ct.run(r,t)}finally{r.credentials=void 0}}var go="codex-auth-managed-per-request";function Ne(o){return z({apiKey:go,baseURL:o.baseURL,defaultHeaders:{originator:"lagent"},fetch:_o(o.credentials,o.fetch)})}function Vn(o){let e=Re(o.authPath,{refreshTimeoutMs:o.refreshTimeoutMs}),t=Ne({credentials:e,baseURL:Se});return{async post(n,r,s){try{let{data:i,response:a}=await Ae(e,s,()=>t.post(n,{body:r,signal:s}).withResponse());return{status:a.status,data:i}}catch(i){throw T("codex",i,()=>!1,s)}}}}import"openai";import{z as ut}from"zod";var Me=class extends Error{constructor(e){super(`The model returned output items lagent cannot execute: ${e.join(", ")}`),this.name="UnsupportedResponseOutputError"}},Eo=new Set(["file_search_call","web_search_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_response","image_generation_call","computer_call_output","function_call_output","local_shell_call_output","exec","reasoning_summary","item_reference","custom_tool_call_output"]),yo=new Set(["file_search_call","web_search_call","code_interpreter_call","mcp_call","image_generation_call"]);function ht(o){if(!yo.has(o.type))return;let e=o,t=e.action,n=e.status;return Ye.parse({id:e.id??o.type,type:o.type,name:e.name??e.server_label??null,status:n==="in_progress"||n==="failed"?n:"completed",summary:t?.query??e.code??null})}var xo=new Set(["apply_patch_call","computer_call","custom_tool_call","local_shell_call","mcp_approval_request","shell_call"]),De="openai-responses",ae="gpt-5.4",Ie=["low","medium","high","max"],de=[{id:"gpt-6-sol",description:"Workhorse for coding and everyday work",thinkingEfforts:Ie},{id:"gpt-6-astra",description:"Frontier intelligence for the most demanding work",thinkingEfforts:Ie},{id:"gpt-6-luna",description:"Fast and affordable, for easier tasks",thinkingEfforts:Ie}],ft={"gpt-6-sol":258400,"gpt-6-astra":258400,"gpt-6-luna":258400,[ae]:258400},Le=v.extend({baseURL:ut.string().default(se),defaultModel:ut.string().default(ae)}),h=class{providerName;client;callHeaders;replayByModel;thinkingEffort;extraBody;streamIdleTimeoutMs;constructor(e){let t=Le.parse(e);this.providerName=e.name??De,this.callHeaders=e.headers,this.replayByModel=e.replayByModel??!1,this.streamIdleTimeoutMs=t.streamIdleTimeoutMs,this.thinkingEffort=t.thinkingEffort??"none",this.extraBody=t.extraBody??{},this.client=D("OpenAI Responses",t,e.client)}buildRequest(e){let t=Q(e.systemPrompt),n=e.thinkingEffort??this.thinkingEffort,r={...this.extraBody,model:e.model,...t?{instructions:t}:{},input:To(e.messages,this.replayTag(e.model)),stream:!0,store:!1,include:["reasoning.encrypted_content"],reasoning:n==="none"?{effort:n}:{effort:n,summary:"auto"}};e.maxOutputTokens!==void 0&&(r.max_output_tokens=e.maxOutputTokens);let s=ko(e.responseFormat);return s!==void 0&&(r.text={format:s}),(e.tools.length>0||e.providerTools.length>0)&&(r.tools=[...e.tools.map(Oo),...e.providerTools],r.tool_choice=wo(e.toolChoice),r.parallel_tool_calls=e.parallelToolCalls),r}replayTag(e){return this.replayByModel?`${this.providerName}/${e}`:this.providerName}async openStream(e,t,n){return await this.client.responses.create(e,{signal:n,headers:t,...re})}async chat(e){let t=this.buildRequest(e),n=this.callHeaders?.(e,t)??{},{lifetime:r,opened:s}=await P(this.providerName,e.signal,this.streamIdleTimeoutMs,i=>this.openStream(t,n,i),i=>T(this.providerName,i,a=>this.isContextOverflow(a),e.signal));return new Pe(r.events(s),this.providerName,this.replayTag(e.model),i=>this.isContextOverflow(i),e.signal,r)}isContextOverflow(e){return e.code===q}},wo=o=>typeof o=="string"?o:{type:"function",name:o.name},ko=o=>{switch(o.kind){case"text":return;case"json_object":return{type:"json_object"};case"json_schema":return{type:"json_schema",name:o.name,schema:o.schema,strict:o.strict}}},Oo=o=>({type:"function",name:o.name,description:o.description,parameters:o.input_schema,strict:!1}),pt=o=>o.every(e=>e.type==="text")?J(o):o.map(e=>{switch(e.type){case"text":return{type:"input_text",text:e.text};case"image":return{type:"input_image",detail:e.detail,...e.url?{image_url:e.url}:e.data?{image_url:`data:${e.media_type??"image/png"};base64,${e.data}`}:{}};case"file":return{type:"input_file",...e.file_id?{file_id:e.file_id}:{},...e.url?{file_url:e.url}:{},...e.data?{file_data:e.data}:{},...e.filename?{filename:e.filename}:{}}}});function To(o,e=De){let t=[];for(let n of o){if(n.role==="tool"){t.push({type:"function_call_output",call_id:n.tool_call_id??"",output:pt(n.content)});continue}if(n.role!=="assistant"){t.push({role:n.role,content:pt(n.content)});continue}if(n.provider_state?.provider===e&&Array.isArray(n.provider_state.data.output)){t.push(...n.provider_state.data.output);continue}let r=E(n);r&&t.push({role:"assistant",content:r});for(let s of n.tool_calls)t.push({type:"function_call",call_id:s.call_id,name:s.name,arguments:Y(s)})}return t}function bo(o){let e=o.usage,t=e?.input_tokens_details;return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,cache_read_input_tokens:t?.cached_tokens??0,cache_write_input_tokens:t?.cache_write_tokens??0,reasoning_output_tokens:e?.output_tokens_details?.reasoning_tokens??0}}function vo(o,e=De){let t=[],n=[],r=[],s=[];for(let i of o.output??[])switch(i.type){case"message":{for(let a of i.content??[])a.type==="output_text"?t.push(a.text):a.type==="refusal"&&t.push(a.refusal);break}case"reasoning":{for(let a of i.content??[])n.push(a.text);for(let a of i.summary??[])n.push(a.text);break}case"function_call":{r.push(M(i.call_id,i.name,i.arguments));break}default:{let a=i.type;(xo.has(a)||!Eo.has(a))&&s.push(a)}}if(s.length>0)throw new Me([...new Set(s)]);return w.parse({role:"assistant",content:t.join("")||null,reasoning_content:n.join(`
|
|
3
|
-
`)||null,tool_calls:r,provider_calls:(o.output??[]).map(ht).filter(i=>i!==void 0),usage:bo(o),provider_state:{provider:e,data:{output:o.output??[]}}})}var Co=o=>o.status==="completed"?"completed":o.status==="incomplete"&&o.incomplete_details?.reason==="max_output_tokens"?"length":"other",So=o=>({response_id:o.id,model:o.model,status:o.status??null,...o.service_tier?{service_tier:o.service_tier}:{},...o.incomplete_details?{incomplete_details:o.incomplete_details}:{}}),Pe=class extends k{response;itemsByIndex=new Map;text="";reasoning="";events;replayTag;isContextOverflow;constructor(e,t,n,r,s,i){super(t,s,i),this.events=e,this.replayTag=n,this.isContextOverflow=r}async*read(){try{yield*this.readEvents()}catch(e){throw T(this.providerName,e,this.isContextOverflow,this.signal)}}failure(e,t){let n=new H(e,t);return this.isContextOverflow(e)?new I(this.providerName,{cause:n}):n}async*readEvents(){for await(let e of this.events)switch(e.type){case"response.output_text.delta":this.text+=e.delta,yield{text_delta:e.delta,reasoning_delta:"",provider_call:null};break;case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":this.reasoning+=e.delta,yield{text_delta:"",reasoning_delta:e.delta,provider_call:null};break;case"response.output_item.done":{this.itemsByIndex.set(e.output_index,e.item);let t=ht(e.item);t!==void 0&&(yield{text_delta:"",reasoning_delta:"",provider_call:t});break}case"response.completed":case"response.incomplete":this.response=this.withOutput(e.response);return;case"response.failed":throw this.failure(e.response.error??{},"The model request failed");case"error":throw this.failure(e,"The model stream reported an error");default:break}}withOutput(e){if(e.output&&e.output.length>0)return e;let t=[...this.itemsByIndex.entries()].sort(([n],[r])=>n-r).map(([,n])=>n);return{...e,output:t}}settle(){if(this.response!==void 0)return{message:vo(this.response,this.replayTag),finish:Co(this.response),provider_metadata:So(this.response)}}partial(){return{message:w.parse({role:"assistant",content:this.text||null,reasoning_content:this.reasoning||null}),providerMetadata:{}}}};var ue="codex",pe="gpt-5.6-luna",le=["low","medium","high","max"],gt=[{id:"gpt-6.1-sol",description:"Latest workhorse for coding and everyday work",thinkingEfforts:le},...de,{id:"gpt-5.6-sol",description:"Older workhorse generation",thinkingEfforts:le},{id:"gpt-5.6-terra",description:"Older balanced model for straightforward work",thinkingEfforts:le},{id:pe,description:"Older fast and efficient model",thinkingEfforts:le}],Et={"gpt-6.1-sol":258400,"gpt-6-astra":258400,"gpt-6-sol":258400,"gpt-6-luna":258400,"gpt-reserve":258400,"gpt-5.6-sol":258400,"gpt-5.6-terra":258400,"gpt-5.6-luna":258400,"gpt-5.5":258400,"codex-auto-review":258400},Ue=L.object({authPath:L.string().refine(Ao,"the Codex login file must be an absolute path").optional(),refreshTimeoutMs:L.number().int().positive().optional(),streamIdleTimeoutMs:O,baseURL:L.string().default(Se),defaultModel:L.string().default(pe),thinkingEffort:L.enum(f).default("high"),extraBody:Oe.optional()}),ce=class extends h{credentials;constructor(e){let t=Ue.parse(e),n=e.credentials;if(n===void 0&&t.authPath!==void 0){if(t.refreshTimeoutMs===void 0)throw new Error("Codex needs a `refreshTimeoutMs` with its `authPath`: the host bounds how long a refresh may take");n=Re(t.authPath,{refreshTimeoutMs:t.refreshTimeoutMs})}if(n===void 0)throw new Error("Codex needs an `authPath`: lagent reads no environment, so the host names the login file");super({name:ue,headers:(r,s)=>{let i=Io(s);return et.debug(`codex session_id=${i} model=${String(s.model)} input_items=${Array.isArray(s.input)?s.input.length:0}`),{session_id:i}},streamIdleTimeoutMs:t.streamIdleTimeoutMs,thinkingEffort:t.thinkingEffort,extraBody:t.extraBody,client:e.client??Ne({credentials:n,baseURL:t.baseURL,fetch:No(e.fetch)})}),this.credentials=n}openStream(e,t,n){return Ae(this.credentials,n,()=>super.openStream(e,t,n))}},_t=typeof G.zstdCompress=="function"?{name:"zstd",compress:mt(G.zstdCompress)}:{name:"gzip",compress:mt(G.gzip)},No=(o=globalThis.fetch)=>async(e,t)=>{if(typeof t?.body!="string")return o(e,t);let n=new Headers(t.headers);return n.set("Content-Encoding",_t.name),n.delete("Content-Length"),o(e,{...t,headers:n,body:await _t.compress(t.body)})},Io=o=>Ro("sha256").update(JSON.stringify([o.model,o.instructions??null,o.tools??null])).digest("hex").slice(0,32);import"openai";import{z as U}from"zod";var yt="openai-chat-completions",je="gpt-5.4",Fe=v.extend({baseURL:U.string().default(se),defaultModel:U.string().default(je),systemRole:U.enum(["system","developer"]).default("system"),contextWindows:U.record(U.string(),U.number().int().positive()).optional()}),C=class{providerName;client;callHeaders;thinkingEffort;extraBody;systemRole;streamIdleTimeoutMs;constructor(e){let t=Fe.parse(e);this.providerName=e.name??yt,this.callHeaders=e.headers,this.streamIdleTimeoutMs=t.streamIdleTimeoutMs,this.thinkingEffort=t.thinkingEffort,this.extraBody=t.extraBody??{},this.systemRole=t.systemRole,this.client=D("OpenAI Chat Completions",t,e.client)}buildRequest(e){if(e.providerTools.length>0)throw new c(this.providerName,"provider-executed tools");let t=Q(e.systemPrompt),n=e.thinkingEffort??this.thinkingEffort,r={...this.extraBody,model:e.model,messages:[...t?[{role:this.systemRole,content:t}]:[],...e.messages.map(i=>$o(i,this.providerName))],stream:!0,stream_options:{include_usage:!0}};n!==void 0&&(r.reasoning_effort=n),e.maxOutputTokens!==void 0&&(r.max_completion_tokens=e.maxOutputTokens);let s=Do(e.responseFormat);return s!==void 0&&(r.response_format=s),e.tools.length>0&&(r.tools=e.tools.map(Lo),r.tool_choice=Po(e.toolChoice),r.parallel_tool_calls=e.parallelToolCalls),r}async openStream(e,t,n){return await this.client.chat.completions.create(e,{signal:n,headers:t,...re})}async chat(e){let t=this.buildRequest(e),n=this.callHeaders?.(e,t)??{},{lifetime:r,opened:s}=await P(this.providerName,e.signal,this.streamIdleTimeoutMs,i=>this.openStream(t,n,i),i=>T(this.providerName,i,xt,e.signal));return new $e(r.events(s),this.providerName,e.signal,r)}},xt=o=>o.code===q,Mo=o=>{switch(o){case"stop":case"tool_calls":case"function_call":return"completed";case"length":return"length";default:return"other"}},Po=o=>typeof o=="string"?o:{type:"function",function:{name:o.name}},Do=o=>{switch(o.kind){case"text":return;case"json_object":return{type:"json_object"};case"json_schema":return{type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict}}}},Lo=o=>({type:"function",function:{name:o.name,description:o.description,parameters:o.input_schema,strict:!1}}),Uo=(o,e)=>o.every(t=>t.type==="text")?J(o):o.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":return{type:"image_url",image_url:{url:t.url||`data:${t.media_type??"image/png"};base64,${t.data??""}`,detail:t.detail}};case"file":{if(!t.file_id&&!t.data)throw new c(e,"files by URL \u2014 upload the file or inline its data");return{type:"file",file:{...t.file_id?{file_id:t.file_id}:{},...t.data?{file_data:t.data}:{},...t.filename?{filename:t.filename}:{}}}}}});function $o(o,e=yt){switch(o.role){case"tool":{let t=o.content.find(n=>n.type!=="text");if(t!==void 0)throw new c(e,`a ${t.type} in a tool result`);return{role:"tool",tool_call_id:o.tool_call_id??"",content:E(o)}}case"assistant":{let t={role:"assistant",content:E(o)||null};return o.tool_calls.length>0&&(t.tool_calls=o.tool_calls.map(n=>({id:n.call_id,type:"function",function:{name:n.name,arguments:Y(n)}}))),o.reasoning_content!==null&&(t.reasoning_content=o.reasoning_content),t}default:return{role:o.role,content:Uo(o.content,e)}}}var $e=class extends k{toolCalls=new Map;lastToolCallKey;text="";reasoning="";finishReason=null;usage=null;metadata={};events;constructor(e,t,n,r){super(t,n,r),this.events=e}async*read(){try{yield*this.readEvents()}catch(e){throw T(this.providerName,e,xt,this.signal)}}async*readEvents(){for await(let e of this.events){this.recordMetadata(e);let t=jo(e);t!==null&&(this.usage=t);let n=e.choices[0];if(n===void 0)continue;n.finish_reason&&(this.finishReason=n.finish_reason);let r=n.delta,s=new Set;for(let l of r.tool_calls??[])this.recordToolCall(l,s);let i=r.content??"",a=r.reasoning_content||r.reasoning||"";this.text+=i,this.reasoning+=a,(i||a)&&(yield{text_delta:i,reasoning_delta:a,provider_call:null})}}recordMetadata(e){if(Object.keys(this.metadata).length>0)return;let t=e;this.metadata={response_id:e.id,model:e.model,...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{},...t.service_tier?{service_tier:t.service_tier}:{}}}recordToolCall(e,t){let n=this.toolCallKey(e,t),r=this.toolCalls.get(n)??{order:this.toolCalls.size,id:"",name:"",arguments:""};this.toolCalls.set(n,{order:e.index??r.order,id:e.id??r.id,name:e.function?.name??r.name,arguments:r.arguments+(e.function?.arguments??"")}),this.lastToolCallKey=n}toolCallKey(e,t){if(e.index!==void 0&&e.index!==null)return`index:${e.index}`;if(e.id){let n=t.has(e.id)?`id:${e.id}#${this.toolCalls.size}`:`id:${e.id}`;return t.add(e.id),n}return this.lastToolCallKey??"index:0"}settle(){if(this.finishReason===null)return;let e=[...this.toolCalls.values()].sort((n,r)=>n.order-r.order).map(n=>M(n.id,n.name,n.arguments));return{message:w.parse({role:"assistant",content:this.text||null,reasoning_content:this.reasoning||null,tool_calls:e,usage:this.usage}),finish:Mo(this.finishReason),provider_metadata:{...this.metadata,finish_reason:this.finishReason}}}partial(){return{message:w.parse({role:"assistant",content:this.text||null,reasoning_content:this.reasoning||null,usage:this.usage}),providerMetadata:{...this.metadata,finish_reason:"incomplete"}}}};function jo(o){let e=o;if(o.usage)return{input_tokens:o.usage.prompt_tokens,output_tokens:o.usage.completion_tokens,cache_read_input_tokens:o.usage.prompt_tokens_details?.cached_tokens??0,cache_write_input_tokens:0,reasoning_output_tokens:o.usage.completion_tokens_details?.reasoning_tokens??0};let t=e.normalizedUsage;if(t===void 0)return null;let n=r=>Number(t[r]??0)||0;return{input_tokens:n("inputTokens"),output_tokens:n("outputTokens"),cache_read_input_tokens:n("cacheReadTokens"),cache_write_input_tokens:n("cacheWriteTokens"),reasoning_output_tokens:0}}import{z as wt}from"zod";var Fo="https://api.deepseek.com",Ot="deepseek-responses",X="deepseek-flash",kt=["low","high","max"],Tt=[{id:X,description:"Fast frontier coding model with image input",thinkingEfforts:kt},{id:"deepseek-v4-pro",description:"Most capable DeepSeek model, for the hardest work",thinkingEfforts:kt}],bt={[X]:996147,"deepseek-v4-pro":996147},Wo=/maximum context length is \d+ tokens/i,We=v.extend({baseURL:wt.string().default(Fo),defaultModel:wt.string().default(X)}),he=class extends h{constructor(e){let t=We.parse(e);if(t.apiKey===void 0&&e.client===void 0)throw new Error("DeepSeek needs an `apiKey`: lagent reads no environment, so the host resolves the credential");let n={...t,client:e.client,name:Ot};super(n)}buildRequest(e){if(e.providerTools.length>0)throw new c(this.providerName,"provider-executed tools");if(e.messages.some(n=>n.content.some(r=>r.type==="file")))throw new c(this.providerName,"file inputs");let t=super.buildRequest(e);return delete t.include,t}isContextOverflow(e){return super.isContextOverflow(e)?!0:typeof e.message=="string"&&Wo.test(e.message)}};import{z as g}from"zod";import{z as _}from"zod";import{createHash as Bo}from"node:crypto";var Ho=/^[a-zA-Z0-9_-]+$/,Ct=o=>Ho.test(o)?o:`lg_${Bo("sha256").update(o).digest("base64url").slice(0,32)}`;function Ko(o,e){let t=o.provider_state;return t?.provider!==e||!Array.isArray(t.data.thinking)?[]:t.data.thinking.filter(n=>n.type==="thinking"?typeof n.signature=="string"&&n.signature!=="":n.type==="redacted_thinking"&&typeof n.data=="string")}function St(o,e){let t=[],n=(r,s)=>{if(s.length===0)return;let i=t.at(-1);i?.role===r?i.content.push(...s):t.push({role:r,content:s})};for(let r of o)switch(r.role){case"assistant":n("assistant",zo(r,e.replayTag));break;case"tool":n("user",[Go(r,e.provider)]);break;case"user":n("user",Be(r.content,e.provider));break;default:n("user",Xo(r.content,e.provider))}for(let r of t)r.role==="user"&&(r.content=qo(r.content));return t}var qo=o=>[...o.filter(e=>e.type==="tool_result"),...o.filter(e=>e.type!=="tool_result")];function zo(o,e){let t=[...Ko(o,e)],n=E(o);n!==""&&t.push({type:"text",text:n});for(let r of o.tool_calls)t.push({type:"tool_use",id:Ct(r.call_id),name:r.name,input:r.arguments??{}});return t}function Go(o,e){let t=Be(o.content,e);if(t.find(r=>r.type==="document")!==void 0)throw new c(e,"a file in a tool result");return{type:"tool_result",tool_use_id:Ct(o.tool_call_id??""),...t.length===0?{}:{content:t}}}function Xo(o,e){let t=Be(o,e);return t.length===0?[]:[{type:"text",text:"<system-reminder>"},...t,{type:"text",text:"</system-reminder>"}]}function Be(o,e){let t=[];for(let n of o)switch(n.type){case"text":n.text!==""&&t.push({type:"text",text:n.text});break;case"image":t.push({type:"image",source:n.url?{type:"url",url:n.url}:{type:"base64",media_type:n.media_type??"image/png",data:n.data??""}});break;case"file":t.push(Vo(n,e))}return t}function Vo(o,e){let t=o.filename?{title:o.filename}:{};if(o.url)return{type:"document",source:{type:"url",url:o.url},...t};if(o.data&&o.media_type==="application/pdf")return{type:"document",source:{type:"base64",media_type:"application/pdf",data:o.data},...t};if(o.data&&o.media_type==="text/plain")return{type:"document",source:{type:"text",media_type:"text/plain",data:Buffer.from(o.data,"base64").toString("utf8")},...t};throw new c(e,o.file_id?"files by provider id":`a file of type '${o.media_type??"unknown"}'`)}var Rt=o=>o.map(e=>({name:e.name,...e.description?{description:e.description}:{},input_schema:e.input_schema}));function At(o,e){let t=e?{}:{disable_parallel_tool_use:!0};return o==="none"?{type:"none"}:o==="auto"?{type:"auto",...t}:o==="required"?{type:"any",...t}:{type:"tool",name:o.name,...t}}function Nt(o){return o===void 0?{}:o==="none"?{thinking:{type:"disabled"}}:{thinking:{type:"adaptive",display:"summarized"},output_config:{effort:o}}}var m=class extends Error{errorType;status;headers;constructor(e,t,n,r){super(t),this.errorType=e,this.status=n,this.headers=r,this.name="AnthropicAPIError"}},It=o=>o.errorType==="invalid_request_error"&&/prompt is too long/i.test(o.message),vt={rate_limit_error:"rate_limit",overloaded_error:"overloaded",api_error:"transport",timeout_error:"timeout",authentication_error:"auth",permission_error:"auth",billing_error:"quota"};function me(o,e=Date.now()){if(!(o instanceof m))return{kind:oe(o)};let t=o.errorType!==void 0&&Object.hasOwn(vt,o.errorType)?vt[o.errorType]:void 0,{status:n}=o;return n===void 0?{kind:t??"other"}:te(t??ee(n)??"other",o.headers,e)}var Jo=o=>{switch(o){case"end_turn":case"tool_use":case"stop_sequence":return"completed";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}},fe=class{id=null;model=null;blocks=new Map;stopReason=null;stopSequence=null;stopped=!1;usage=null;options;constructor(e){this.options=e}apply(e){switch(e.type){case"message_start":return this.id=e.message.id,this.model=e.message.model,this.addUsage(e.message.usage),null;case"content_block_start":return this.blocks.set(e.index,Yo(e.content_block)),null;case"content_block_delta":return this.applyDelta(e.index,e.delta);case"message_delta":return e.delta.stop_reason&&(this.stopReason=e.delta.stop_reason),e.delta.stop_sequence&&(this.stopSequence=e.delta.stop_sequence),this.addUsage(e.usage),null;case"message_stop":return this.stopped=!0,null;case"error":throw new m(e.error.type,e.error.message??"The stream reported an error");default:return null}}get complete(){return this.stopReason!==null&&this.stopped}get stop(){return this.stopReason}applyDelta(e,t){let n=this.blocks.get(e);return n===void 0?null:n.type==="text"&&t.type==="text_delta"&&typeof t.text=="string"?(n.text+=t.text,{text_delta:t.text,reasoning_delta:"",provider_call:null}):n.type==="thinking"&&t.type==="thinking_delta"&&typeof t.thinking=="string"?(n.thinking+=t.thinking,{text_delta:"",reasoning_delta:t.thinking,provider_call:null}):(n.type==="thinking"&&t.type==="signature_delta"&&typeof t.signature=="string"?n.signature+=t.signature:n.type==="tool_use"&&t.type==="input_json_delta"&&typeof t.partial_json=="string"&&(n.json+=t.partial_json),null)}addUsage(e){if(e==null)return;let t=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==null));this.usage={...this.usage,...t}}normalizedUsage(){if(this.usage===null)return null;let e=this.usage.cache_read_input_tokens??0,t=this.usage.cache_creation_input_tokens??0;return{input_tokens:(this.usage.input_tokens??0)+e+t,output_tokens:this.usage.output_tokens??0,cache_read_input_tokens:e,cache_write_input_tokens:t,reasoning_output_tokens:this.usage.output_tokens_details?.thinking_tokens??0}}ordered(){return[...this.blocks.entries()].sort(([e],[t])=>e-t).map(([,e])=>e)}text(){return this.ordered().flatMap(e=>e.type==="text"?[e.text]:[]).join("")}reasoning(){return this.ordered().flatMap(e=>e.type==="thinking"&&e.thinking!==""?[e.thinking]:[]).join(`
|
|
4
|
-
|
|
5
|
-
`)}metadata(){return{...this.id===null?{}:{message_id:this.id},...this.model===null?{}:{model:this.model},stop_reason:this.stopReason??"incomplete",...this.stopSequence===null?{}:{stop_sequence:this.stopSequence}}}settle(){if(!this.complete)return;let e=this.options.toolName??(i=>i),t=[],n=[];for(let i of this.ordered())i.type==="thinking"?t.push({type:"thinking",thinking:i.thinking,signature:i.signature}):i.type==="redacted_thinking"?t.push({type:"redacted_thinking",data:i.data}):i.type==="tool_use"&&n.push(M(i.id,e(i.name),i.json===""?i.input:i.json));let r={id:this.id??"",thinking:t};return{message:w.parse({role:"assistant",content:this.text()||null,reasoning_content:this.reasoning()||null,tool_calls:n,usage:this.normalizedUsage(),provider_state:{provider:this.options.replayTag,data:r}}),finish:Jo(this.stopReason),provider_metadata:this.metadata()}}partial(){return{message:w.parse({role:"assistant",content:this.text()||null,reasoning_content:this.reasoning()||null,usage:this.normalizedUsage()}),providerMetadata:this.metadata()}}};function Yo(o){switch(o.type){case"text":return{type:"text",text:typeof o.text=="string"?o.text:""};case"thinking":return{type:"thinking",thinking:typeof o.thinking=="string"?o.thinking:"",signature:typeof o.signature=="string"?o.signature:""};case"redacted_thinking":return{type:"redacted_thinking",data:typeof o.data=="string"?o.data:""};case"tool_use":return{type:"tool_use",id:String(o.id??""),name:String(o.name??""),json:"",input:o.input};default:return{type:"other",raw:o}}}var Qo="2023-06-01",Zo=_.object({apiKey:_.string().min(1).optional(),baseURL:_.string().min(1),streamIdleTimeoutMs:O,authorization:_.enum(["x-api-key","bearer"]).default("x-api-key"),defaultHeaders:_.record(_.string(),_.string()).optional(),thinkingEffort:_.enum(f).optional(),maxOutputTokens:_.record(_.string(),_.number().int().positive())}),en=o=>o.type!=="thinking"&&o.type!=="redacted_thinking";function tn(o,e){let t=r=>{for(let s=r.length-1;s>=0;s--)if(en(r[s])){r[s]={...r[s],cache_control:{type:"ephemeral"}};return}};t(o);let n=e.at(-1);n!==void 0&&t(n.content)}var $=class{providerName;config;fetchImpl;callHeaders;constructor(e){this.providerName=e.name,this.config=Zo.parse(e),this.fetchImpl=e.fetch??globalThis.fetch,this.callHeaders=e.headers}replayTag(e){return`${this.providerName}/${e}`}maxOutputTokens(e){if(e.maxOutputTokens!==void 0)return e.maxOutputTokens;let t=this.config.maxOutputTokens;if(Object.hasOwn(t,e.model))return t[e.model];throw new c(this.providerName,`model '${e.model}' with no output cap \u2014 name it in the provider's \`maxOutputTokens\``)}headers(e,t){let{apiKey:n,authorization:r}=this.config;if(n===void 0)throw new Error(`${this.providerName} needs an \`apiKey\`: lagent reads no environment, so the host resolves the credential`);return{...this.config.defaultHeaders,...r==="bearer"?{Authorization:`Bearer ${n}`}:{"x-api-key":n},"anthropic-version":Qo,"content-type":"application/json",accept:"text/event-stream",...this.callHeaders?.(e,t)}}buildRequest(e){if(e.providerTools.length>0)throw new c(this.providerName,"provider-executed tools");if(e.responseFormat.kind!=="text")throw new c(this.providerName,`response format '${e.responseFormat.kind}'`);let t=e.thinkingEffort??this.config.thinkingEffort;if(e.toolChoice!=="auto"&&e.toolChoice!=="none"&&t!==void 0&&t!=="none"&&e.tools.length>0)throw new c(this.providerName,"a forced tool choice while thinking");let r=e.systemPrompt.filter(a=>a.text!=="").map(a=>({type:"text",text:a.text})),s=St(e.messages,{provider:this.providerName,replayTag:this.replayTag(e.model)});tn(r,s);let i={model:e.model,max_tokens:this.maxOutputTokens(e),messages:s,stream:!0,...Nt(t)};return r.length>0&&(i.system=r),e.tools.length>0&&(i.tools=Rt(e.tools),i.tool_choice=At(e.toolChoice,e.parallelToolCalls)),i}async chat(e){let t=this.buildRequest(e),n=this.headers(e,t),{lifetime:r,opened:s}=await P(this.providerName,e.signal,this.config.streamIdleTimeoutMs,a=>this.open(t,n,a),a=>Z(e.signal,a)?e.signal.reason:this.classified(a)),i=new fe({replayTag:this.replayTag(e.model)});return new He(r.events(nn(s)),i,this,e.signal,r)}async open(e,t,n){let r=await this.fetchImpl(`${this.config.baseURL.replace(/\/+$/,"")}/messages`,{method:"POST",headers:t,body:JSON.stringify(e),signal:n});if(!r.ok||r.body===null)throw await on(r);return r.body}classified(e){return e instanceof m&&It(e)?new I(this.providerName,{cause:e}):e}};async function on(o){let e=await o.text().catch(()=>""),t;try{t=JSON.parse(e).error}catch{t=void 0}let n=typeof t?.message=="string"&&t.message!==""?t.message:e||o.statusText;return new m(typeof t?.type=="string"?t.type:void 0,`${o.status} ${n}`,o.status,o.headers)}async function*nn(o){let e=new TextDecoder,t="",n=[];for await(let r of o){t+=e.decode(r,{stream:!0});let s;for(;(s=t.search(/[\r\n]/))>=0&&!(t[s]==="\r"&&s===t.length-1);){let i=t.slice(0,s);t=t.slice(t.startsWith(`\r
|
|
6
|
-
`,s)?s+2:s+1),i===""?(n.length>0&&(yield JSON.parse(n.join(`
|
|
7
|
-
`))),n=[]):i.startsWith("data:")&&n.push(i.slice(5).replace(/^ /,""))}}}var He=class extends k{events;assembly;client;constructor(e,t,n,r,s){super(n.providerName,r,s),this.events=e,this.assembly=t,this.client=n}async*read(){try{for await(let e of this.events){let t=this.assembly.apply(e);if(t!==null&&(yield t),this.assembly.complete)return}}catch(e){throw this.client.classified(e)}}settle(){return this.assembly.settle()}partial(){return this.assembly.partial()}};var j=class{providerName;prepare;adapters;constructor(e,t,n){this.providerName=e,this.prepare=t,this.adapters=n}async chat(e){let t=this.prepare(e);return this.adapters[t.protocol].chat(t.call)}};var rn="https://opencode.ai/zen/go/v1",S="opencode-go",sn="deepseek-v4.1-flash",an="x-opencode-session",F=["low","medium","high","max"],Mt=["low","medium","high"],dn={"grok-4.7":{protocol:"responses",contextWindow:5e5,thinkingEfforts:Mt},"gpt-6-luna":{protocol:"responses",contextWindow:922e3},"muse-spark-1.3-contributor":{protocol:"responses",contextWindow:1048576,thinkingEfforts:F},"muse-spark-1.2-contributor":{protocol:"responses",contextWindow:1048576,thinkingEfforts:Mt},"claude-haiku-5-5":{protocol:"messages",contextWindow:1e6,maxOutputTokens:128e3},"minimax-m3":{protocol:"messages",contextWindow:1e6,maxOutputTokens:131072},"minimax-m2.7":{protocol:"messages",contextWindow:204800,thinkingEfforts:F,maxOutputTokens:131072},"qwen3.8-max":{protocol:"messages",contextWindow:1e6,maxOutputTokens:131072},"qwen3.8-flash":{protocol:"messages",contextWindow:1e6,maxOutputTokens:131072},"qwen3.7-plus":{protocol:"messages",contextWindow:1e6,maxOutputTokens:65536},"glm-5.3-flash":{protocol:"chat",contextWindow:1e6,developerRole:"system"},"glm-5.3":{protocol:"chat",contextWindow:1e6,thinkingEfforts:F},"kimi-k3":{protocol:"chat",contextWindow:1048576},"kimi-k2.7-code":{protocol:"chat",contextWindow:262144,thinkingEfforts:F,developerRole:"system"},"longcat-2.5-preview-free":{protocol:"chat",contextWindow:1e6,thinkingEfforts:F},"step-5-preview-free":{protocol:"chat",contextWindow:1e6,thinkingEfforts:F},"deepseek-v4.1-flash":{protocol:"chat",contextWindow:1e6},"deepseek-v4-flash-vision-exp":{protocol:"chat",contextWindow:1e6},"mimo-v2.6-flash":{protocol:"chat",contextWindow:1048576},"mimo-v2.6-pro":{protocol:"chat",contextWindow:1048576}},ln=g.strictObject({protocol:g.enum(["responses","chat","messages"]),contextWindow:g.number().int().positive().optional(),thinkingEfforts:g.array(g.enum(f)).min(1).optional(),maxOutputTokens:g.number().int().positive().optional(),developerRole:g.enum(["developer","system"]).optional()}),cn=o=>Object.entries(o??{}).some(([e,t])=>e.toLowerCase()==="user-agent"&&t.trim()!==""),un=v.extend({baseURL:g.string().default(rn),defaultModel:g.string().default(sn),models:g.record(g.string(),ln).optional()}).refine(o=>cn(o.defaultHeaders),{message:"OpenCode Go needs a `User-Agent` in `defaultHeaders` naming the application, such as `my-agent/1.0`",path:["defaultHeaders"]}),pn=o=>{let e={...dn};for(let[t,n]of Object.entries(o.models??{})){let r=Object.hasOwn(e,t)?e[t]:void 0;e[t]={...r,protocol:n.protocol,...n.contextWindow===void 0?{}:{contextWindow:n.contextWindow},...n.thinkingEfforts===void 0?{}:{thinkingEfforts:n.thinkingEfforts},...n.maxOutputTokens===void 0?{}:{maxOutputTokens:n.maxOutputTokens},...n.developerRole===void 0?{}:{developerRole:n.developerRole}}}return e};function Ke(o){let e=un.parse(o),t=pn(e);return Pt(t,e.defaultModel),{config:e,table:t}}function Pt(o,e){let t=Object.hasOwn(o,e)?o[e]:void 0;if(t===void 0)throw new c(S,`model '${e}', whose protocol is unknown \u2014 name it in the provider's \`models\``);if(t.protocol==="messages"&&t.maxOutputTokens===void 0)throw new c(S,`Messages model '${e}' with no output cap \u2014 name its \`maxOutputTokens\` in the provider's \`models\``);return t.protocol}var Dt=o=>Object.entries(o).map(([e,t])=>t.thinkingEfforts===void 0?{id:e}:{id:e,thinkingEfforts:t.thinkingEfforts}),Lt=(o,e)=>(Object.hasOwn(o,e)?o[e].contextWindow:void 0)??null,hn=(o,e)=>e!=="system"||!o.messages.some(t=>t.role==="developer")?o:{...o,messages:o.messages.map(t=>t.role==="developer"?{...t,role:e}:t)},fn=o=>({[an]:o.threadId}),_e=class extends j{constructor(e){let{config:t,table:n}=Ke(e),r=D("OpenCode Go",t,e.client),s={name:S,headers:fn,streamIdleTimeoutMs:t.streamIdleTimeoutMs,...t.thinkingEffort===void 0?{}:{thinkingEffort:t.thinkingEffort}},i={...s,client:r,...t.extraBody===void 0?{}:{extraBody:t.extraBody}};super(S,a=>{let l=Pt(n,a.model);if(a.providerTools.length>0)throw new c(S,"provider-executed tools");return{protocol:l,call:l==="chat"?hn(a,n[a.model].developerRole):a}},{responses:new h({...i,replayByModel:!0}),chat:new C(i),messages:new $({...s,...t.apiKey===void 0?{}:{apiKey:t.apiKey},baseURL:t.baseURL,...t.defaultHeaders===void 0?{}:{defaultHeaders:t.defaultHeaders},maxOutputTokens:Object.fromEntries(Object.entries(n).flatMap(([a,l])=>l.maxOutputTokens===void 0?[]:[[a,l.maxOutputTokens]])),...e.fetch===void 0?{}:{fetch:e.fetch}})})}};import{readFile as mn}from"node:fs/promises";import{isAbsolute as _n}from"node:path";import{z as d}from"zod";var R="opencode-copilot",gn="https://api.githubcopilot.com",qe={"User-Agent":"opencode/2.0.26","X-GitHub-Api-Version":"2026-08-01"},En=d.strictObject({authPath:d.string().refine(_n,"authPath must be an absolute path"),streamIdleTimeoutMs:O,defaultModel:d.string().min(1).optional(),thinkingEffort:d.enum(f).optional()}),yn=d.object({"github-copilot":d.object({type:d.literal("oauth"),access:d.string().min(1),metadata:d.object({apiEndpoint:d.url().optional()}).optional()})}),xn=d.object({id:d.string().min(1),name:d.string().optional(),model_picker_enabled:d.boolean().optional(),policy:d.object({state:d.string().optional()}).optional(),supported_endpoints:d.array(d.string()).optional(),capabilities:d.object({type:d.string().optional(),limits:d.object({max_context_window_tokens:d.number().int().positive().optional(),max_prompt_tokens:d.number().int().positive(),max_output_tokens:d.number().int().positive()}),supports:d.object({streaming:d.boolean().optional(),tool_calls:d.boolean(),vision:d.boolean().optional(),reasoning_effort:d.array(d.string()).optional(),adaptive_thinking:d.boolean().optional(),min_thinking_budget:d.number().int().positive().optional(),max_thinking_budget:d.number().int().positive().optional()})})});function wn(o){let e=o.supported_endpoints;if(e?.includes("/v1/messages"))return"messages";if(e?.includes("/responses"))return"responses";if(e?.includes("/chat/completions"))return"chat";if(e?.length)return;if(o.id.startsWith("claude-"))return"messages";let t=/^gpt-(\d+)/.exec(o.id);return t&&Number(t[1])>=5&&!o.id.startsWith("gpt-5-mini")||o.id.startsWith("grok-")||o.id.startsWith("mai-code-")?"responses":"chat"}function kn(o){let e=d.object({data:d.array(d.unknown())}).safeParse(o);if(!e.success)throw new Error("Copilot model discovery returned an invalid catalog");let t=new Map;for(let n of e.data.data){let r=xn.safeParse(n);if(!r.success)continue;let s=r.data;if(s.policy?.state==="disabled"||s.capabilities.supports.streaming===!1||s.capabilities.type!==void 0&&s.capabilities.type!=="chat")continue;let i=wn(s);if(i===void 0)continue;let a=s.capabilities.supports,l=a.reasoning_effort?.filter(x=>f.some(N=>N===x)),u=i==="messages"&&!a.adaptive_thinking&&a.max_thinking_budget?["none","high","max"]:l?.length?l:a.adaptive_thinking?void 0:["none"];t.set(s.id,{...s,protocol:i,...u?{thinkingEfforts:u}:{}})}if(t.size===0)throw new Error("Copilot model discovery returned no usable models");return new Map([...t].sort((n,r)=>+!!r[1].model_picker_enabled-+!!n[1].model_picker_enabled))}var On=o=>({"Openai-Intent":"conversation-edits","X-Interaction-Type":o.purpose==="auxiliary"?"conversation-background":"conversation-agent","X-Interaction-Id":o.threadId,"x-initiator":o.purpose==="step"&&o.messages.at(-1)?.role==="user"?"user":"agent",...o.messages.some(e=>e.content.some(t=>t.type==="image"))?{"Copilot-Vision-Request":"true"}:{}}),ze=class extends h{buildRequest(e){let t=super.buildRequest(e);return e.thinkingEffort===void 0&&delete t.reasoning,t}},Ge=class extends ${models;constructor(e,t){super(e),this.models=t}buildRequest(e){let t=super.buildRequest(e),n=this.models.get(e.model).capabilities.supports;if(!n.adaptive_thinking&&e.thinkingEffort&&e.thinkingEffort!=="none"){let r=n.max_thinking_budget;if(r===void 0)throw new c(this.providerName,`thinking on '${e.model}'`);let s=e.thinkingEffort==="max"?r-1:Math.floor(r/2),i=Math.min(s,Number(t.max_tokens)-1);if(i<(n.min_thinking_budget??1))throw new c(this.providerName,`thinking budget above the output cap for '${e.model}'`);t.thinking={type:"enabled",budget_tokens:i},delete t.output_config}return t}},Xe=class extends j{constructor(e,t,n,r){let s=z({apiKey:n,baseURL:r,defaultHeaders:qe}),i={name:R,headers:On,streamIdleTimeoutMs:e.streamIdleTimeoutMs},a={...i,client:s};super(R,l=>{let u=t.get(l.model);if(!u)throw new c(R,`undiscovered model '${l.model}'`);if(l.providerTools.length)throw new c(R,"provider-executed tools");if(l.tools.length&&!u.capabilities.supports.tool_calls)throw new c(R,`tools on '${l.model}'`);let x=l.thinkingEffort??e.thinkingEffort;if(x!==void 0&&u.thinkingEfforts&&!u.thinkingEfforts.includes(x))throw new c(R,`thinking effort '${x}' on '${l.model}'`);let N=u.thinkingEfforts?.some($t=>$t!=="none")??!0,{thinkingEffort:V,...Ut}=l;return{protocol:u.protocol,call:{...Ut,...x===void 0||!N?{}:{thinkingEffort:x}}}},{responses:new ze({...a,replayByModel:!0}),chat:new C(a),messages:new Ge({...i,apiKey:n,authorization:"bearer",baseURL:`${r}/v1`,defaultHeaders:{...qe,"anthropic-beta":"interleaved-thinking-2025-05-14"},maxOutputTokens:Object.fromEntries([...t].map(([l,u])=>[l,u.capabilities.limits.max_output_tokens]))},t)})}};async function Tn(o){let e=En.parse(o),t;try{t=yn.parse(JSON.parse(await mn(e.authPath,"utf8")))["github-copilot"]}catch{throw new Error(`opencode-copilot needs an OAuth login in ${e.authPath}; run opencode auth login`)}let n=(t.metadata?.apiEndpoint??gn).replace(/\/+$/,""),r=await fetch(`${n}/models`,{headers:{...qe,Authorization:`Bearer ${t.access}`},signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Copilot model discovery failed: HTTP ${r.status}`);let s=kn(await r.json()),i=e.defaultModel??(s.has("gpt-6-luna")?"gpt-6-luna":s.keys().next().value);if(!s.has(i))throw new Error(`Copilot default model '${i}' is unavailable`);return{name:R,defaultModel:i,...e.thinkingEffort===void 0?{}:{defaultThinkingEffort:e.thinkingEffort},models:[...s.values()].map(a=>({id:a.id,...a.name?{description:a.name}:{},...a.thinkingEfforts?{thinkingEfforts:a.thinkingEfforts}:{}})),capacity:a=>{let l=s.get(a),u=l?.capabilities.limits;return{contextWindow:u?Math.min(u.max_prompt_tokens,u.max_context_window_tokens??u.max_prompt_tokens):null,providerTools:!1,toolResultImages:l?.protocol!=="chat"&&l?.capabilities.supports.vision===!0}},createClient:()=>new Xe(e,s,t.access,n),classify:a=>a instanceof m?me(a):b(a)}}var ms=o=>{let e=Le.parse(o);return{name:"openai-responses",defaultModel:e.defaultModel||ae,defaultThinkingEffort:e.thinkingEffort,models:de,capacity:t=>({contextWindow:K(ft,t),providerTools:!0,toolResultImages:!0}),createClient:()=>new h(o),classify:t=>b(t)}},_s=o=>{let e=We.parse(o);return{name:"deepseek-responses",defaultModel:e.defaultModel||X,defaultThinkingEffort:e.thinkingEffort,models:Tt,capacity:t=>({contextWindow:K(bt,t),providerTools:!1,toolResultImages:!1}),createClient:()=>new he(o),classify:t=>b(t)}},gs=o=>{let e=Ue.parse(o);return{name:ue,defaultModel:e.defaultModel||pe,defaultThinkingEffort:e.thinkingEffort,models:gt,capacity:t=>({contextWindow:K(Et,t),providerTools:!0,toolResultImages:!0}),createClient:()=>new ce(o),classify:t=>t instanceof p?{kind:"auth"}:b(t)}},Es=o=>{let e=Fe.parse(o);return{name:"openai-chat-completions",defaultModel:e.defaultModel||je,defaultThinkingEffort:e.thinkingEffort,capacity:t=>({contextWindow:K(e.contextWindows??{},t),providerTools:!1,toolResultImages:!1}),createClient:()=>new C(o),classify:t=>b(t)}},ys=o=>{let{config:e,table:t}=Ke(o);return{name:S,defaultModel:e.defaultModel,defaultThinkingEffort:e.thinkingEffort,models:Dt(t),capacity:n=>({contextWindow:Lt(t,n),providerTools:!1,toolResultImages:!1}),createClient:()=>new _e(o),classify:n=>n instanceof m?me(n):b(n)}};export{p as a,ho as b,Vn as c,ue as d,Ot as e,S as f,R as g,Tn as h,ms as i,_s as j,gs as k,Es as l,ys as m};
|
package/dist/chunks/X65X4KP5.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{a as _,b as v}from"./NAOUTU7A.js";import{d as w}from"./G6RXC3AL.js";import{a as O,d as $}from"./2OSESBIL.js";import{isAbsolute as X}from"node:path";import{scopeOf as Y}from"@leuduan/cordis";import{z as u}from"zod";import{existsSync as x,readFileSync as F,readdirSync as I,realpathSync as U,statSync as j}from"node:fs";import{join as L,resolve as A}from"node:path";import{parse as D}from"yaml";var W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;function P(e){let o=W.exec(e);if(o===null)return{frontmatter:{},body:e};let t=D(o[1])??{};return{frontmatter:t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{},body:e.slice(o[0].length)}}var b=[".claude/skills",".agents/skills"],M=e=>[L(e,".claude","skills")];function N(e,o){return[...o.workspace.map(t=>A(e,t)),...o.host]}var S=e=>typeof e=="string"?e.trim():"",z=e=>Array.isArray(e)?e.filter(o=>typeof o=="string"):[];function B(e,o){let{frontmatter:t,body:r}=P(F(e,"utf8"));return{name:S(t.name)||o,directoryName:o,path:e,description:S(t.description),whenToUse:S(t.when_to_use)||S(t.whenToUse),aliases:z(t.aliases),body:r,frontmatter:t}}var q=e=>[e.name,e.directoryName,...e.aliases].map(o=>o.toLowerCase());function G(e,o=()=>{}){let t=[],r=new Set,i=new Set,d=(l,n)=>o({path:l,reason:n instanceof Error?n.message:String(n)}),f=l=>{let n=A(l),m;try{if(!j(n).isDirectory())return;m=U(n)}catch{return}if(i.has(m))return;i.add(m);let k;try{k=I(n,{withFileTypes:!0})}catch(s){d(n,s);return}if(k.find(s=>s.name==="SKILL.md"&&s.isFile())!==void 0){let s=L(n,"SKILL.md"),a;try{a=B(s,H(n))}catch(p){d(s,p);return}let c=q(a);if(c.some(p=>r.has(p)))i.delete(m);else{for(let p of c)r.add(p);t.push(a)}return}for(let s of k)(s.isDirectory()||s.isSymbolicLink())&&f(L(n,s.name))};for(let l of e)x(l)&&f(l);return t}function C(e,o,t){let r=N(e,o);return{workspaceRoot:e,roots:r,skills:G(r,t)}}var H=e=>e.split(/[\\/]/).filter(Boolean).pop()??e,J=e=>e.split(`
|
|
2
|
-
`).map(t=>t.trim()).find(t=>t.length>0&&!t.startsWith("#"))??"";function y({skills:e,workspaceRoot:o,roots:t}){return e.length===0?t.length>0?`No skills were discovered in:
|
|
3
|
-
${t.map(i=>`- ${w(o,i)}`).join(`
|
|
4
|
-
`)}`:"No skills were discovered.":[...e].sort((r,i)=>r.name.toLowerCase().localeCompare(i.name.toLowerCase())).map(r=>{let i=r.description||J(r.body);r.whenToUse&&(i=i?`${i} When to use: ${r.whenToUse}`:`When to use: ${r.whenToUse}`);let d=r.aliases.length>0?` (aliases: ${r.aliases.join(", ")})`:"";return`- ${r.name}${d}: ${i} [${w(o,r.path)}]`}).join(`
|
|
5
|
-
`)}import{dirname as Q}from"node:path";import{z as K}from"zod";var g="skill",V=K.strictObject({skill:K.string().nullable().default(null).describe("Skill name to load; omit to list the available skills.")}),R=e=>_({name:g,description:"List filesystem-backed skills, or load one by name to get its full instructions.",parameters:V,onInterrupted:"rerun",executionMode:"parallel",async execute(o,t){let r=e(t.threadId);if(r===void 0)throw new Error("This thread has no skill catalog yet: skills was mounted after it was activated");let{skills:i}=r;if(o.skill===null)return{output:y(r),metadata:{skill_count:i.length}};let d=o.skill.toLowerCase(),f=i.find(n=>n.name.toLowerCase()===d||n.directoryName.toLowerCase()===d||n.aliases.some(m=>m.toLowerCase()===d));if(f===void 0){let n=i.map(m=>m.name).join(", ")||"(none)";throw new Error(`Unknown skill '${o.skill}'. Available: ${n}`)}let l=Q(f.path);return{output:`Skill directory: ${l}
|
|
6
|
-
|
|
7
|
-
${f.body.trim()}`,metadata:{skill:f.name,path:f.path,directory:l,no_truncation:!0}}}});var Z=u.strictObject({roots:u.array(u.string().refine(X,"a skill root the host names must be absolute")),workspaceRoots:u.array(u.string()).default([...b]),agents:O.optional(),autoload:u.boolean().default(!0)}),ye={name:"lagent:skills",inject:["tools","prompts"],apply(e,o){$(e,"skills");let{roots:t,workspaceRoots:r,agents:i,autoload:d}=Z.parse(o),f={workspace:r,host:t},l=new Map,n=new Map;v(e,R(s=>l.get(s)),i===void 0?{}:{agents:i});let m=new Set,k=({path:s,reason:a})=>{let c=`${s}\0${a}`;m.has(c)||(m.add(c),e.reportError(new Error(`Skipped the skill at ${s}: ${a}`)))},h=new Set;e.effect(()=>()=>{for(let s of[...h])s()}),e.on("lagent/thread/activate",s=>{let a=s.environment.cwd,c=n.get(a)??{catalog:C(a,f,k),holders:0};n.set(a,c),c.holders+=1;let{catalog:p}=c;l.set(s.id,p);let E=d?e.prompts.contribute(Y(s.ctx),ee(p)):()=>{},T=s.ctx.effect(()=>()=>{h.delete(T),E(),l.get(s.id)===p&&l.delete(s.id),c.holders-=1,c.holders===0&&n.get(a)===c&&n.delete(a)});h.add(T)})}},ee=e=>({tag:"availableSkills",slot:"instruction",agents:"all",render:({tools:o})=>e.skills.length>0&&o.some(t=>t.name===g)?y(e):null});export{b as a,M as b,g as c,ye as d};
|
package/dist/chunks/YIR5MYGU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function a(o,f){let n=new Set;for(let e=o.fiber;!n.has(e);e=e.parent.fiber)n.add(e);let r=o.reflect.inspect("journal")?.fiber;r!==void 0&&n.add(r);for(let e of n)o.effect(()=>e.beforeUnload(f))}export{a};
|
package/dist/chunks/YLNJXQ3Z.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as T,f as v,g as ze,h as B}from"./DDANMY45.js";import{A as Ne,a as k,d as ce,f as Ee,g as je,i as Oe,x as ve,y as Me}from"./37YOGDGY.js";import{f as Ie,g as Te,k as $e,l as Se,m as de,p as Re,q as Ae,r as Ce,s as X}from"./KESCTXGO.js";import{b as D,d as R}from"./TYTQRLTX.js";import{c as le,e as ke,g as qe,p as be,v as A,w as Y}from"./D7E6EWIE.js";var Pe=class extends ReferenceError{agentName;constructor(t){super(`Unknown agent: ${t}`),this.agentName=t,this.name="UnknownAgentError"}},U=class extends ReferenceError{threadId;constructor(t){super(`Unknown thread: ${t}`),this.threadId=t,this.name="UnknownThreadError"}},De=class extends Error{threadId;holding;constructor(t,r){super(r==="release"?`Thread ${t} is being released`:r==="cancel"?`Thread ${t} is being cancelled`:r==="configure"?`Thread ${t} is being configured`:r==="rebuild"?`Thread ${t} is rebuilding its prompt`:r==="compact"?`A compaction is running on thread ${t}`:`A turn is already running on thread ${t}`),this.threadId=t,this.holding=r,this.name="ThreadBusyError"}},Be=class extends Error{threadId;constructor(t,r){super(`Thread ${t} is configured as asked, but its plugins could not be restored: ${r instanceof Error?r.message:String(r)}`,{cause:r}),this.threadId=t,this.name="RestoreFailedError"}},Ue=class extends Error{threadId;limit;constructor(t,r){super(`Delegation is ${r} levels deep; ${t} was not started`),this.threadId=t,this.limit=r,this.name="DepthExceededError"}},M=class extends Error{constructor(){super("The thread's plugins changed under the turn"),this.name="StaleActivation"}},W=class extends Error{constructor(){super("The facts or registrations the answer's stop checks judged under changed"),this.name="JudgmentInvalidated"}},H=class extends Error{cause;constructor(t){super("Turn failed; its ending is recorded"),this.cause=t,this.name="RecordedTurnFailure"}},$=class extends Error{threadId;seq;constructor(t,r,n){super(`Cannot fork thread ${t} at row ${r}: ${n}`),this.threadId=t,this.seq=r,this.name="ForkCutError"}},Fe=class extends Error{threadId;conflicts;constructor(t,r){let n=r.map(({field:i})=>i),s=r.find(({field:i})=>i==="agent"),o=r.find(({field:i})=>i==="kind"),a=[...s===void 0?[]:[`belongs to ${String(s.recorded)}, not ${String(s.requested)}`],...o===void 0?[]:[`already exists and is ${o.recorded==="fork"?"a":"not a"} fork`],...n.includes("cut")?["was forked with a different source or cut"]:[],...n.filter(i=>!["agent","kind","cut"].includes(i)).length===0?[]:[`was created with a different ${n.filter(i=>!["agent","kind","cut"].includes(i)).join(", ")}`]];super(`Thread ${t} ${a.join("; ")}`),this.threadId=t,this.conflicts=r,this.name="BirthConflictError"}},Le=class extends Error{refusal;operation;constructor(t,r){super(t.message),this.refusal=t,this.operation=r,this.name="WriteRefusedError"}},Je=class extends Error{threadId;constructor(t){super(`Thread ${t} is activating; await thread.whenReady(), or close the thread, first`),this.threadId=t,this.name="ThreadActivatingError"}},We=class extends Error{threadId;requestId;decision;constructor(t,r,n){super(`Confirmation request_id=${r} on thread ${t} was already ${n.approved?"approved":"rejected"}`),this.threadId=t,this.requestId=r,this.decision=n,this.name="ConfirmationAnsweredError"}},F=class extends Error{threadId;constructor(t,r){super(`Thread ${t} is not settled: ${r}`),this.threadId=t,this.name="ThreadUnsettledError"}},Z=class extends Error{index;rule;constructor(t,r,n){super(t),this.index=r,this.rule=n,this.name="ReplacementRefusedError"}},He=class extends Error{threadId;row;reason;constructor(t,r,n){super(`Thread ${t} cannot be continued: its surface refused surface/replaced row ${r.seq} of thread ${r.threadId} (${n}); it can be read, and forked before that row`),this.threadId=t,this.row=r,this.reason=n,this.name="CorruptHistoryError"}},E=class extends Error{constructor(t){super(t),this.name="AuxiliaryRefusedError"}};var ee=class extends Error{threadId;route;constructor(t,r,n){super(`Thread ${t} runs on ${pe(r)}: ${n}`),this.threadId=t,this.route=r,this.name="RouteConflictError"}},L=class extends Error{route;constructor(t){super(`Provider '${t.provider}' is not registered`),this.route=t,this.name="RouteUnavailableError"}},Ve=(e,t)=>e.provider===t.provider&&e.model===t.model&&e.thinking_effort===t.thinking_effort,pe=e=>`${e.provider}/${e.model}${e.thinking_effort===null?"":` (${e.thinking_effort})`}`;function Ge(e,t,r){let n=r.target(e);if("expect"in t){if(n.blocked!==null)throw new L(n.route);if(!Ve(t.expect,n.route))throw new ee(e,n.route,`expected ${pe(t.expect)}`);return null}let s=r.resolve(t.select,n.route);if(Ve(s,n.route))return null;if(!n.selectable)throw new ee(e,n.route,`it cannot change to ${pe(s)} while its pending request can run or is running`);return s}function V(e,t){if(e.parked.length>0)return{kind:"end",reason:{kind:"blocked"}};let r=e.step>=t.maxStepsPerTurn;return e.unanswered.length>0?r?{kind:"end",reason:{kind:"max-steps",limit:t.maxStepsPerTurn}}:{kind:"answer-calls",calls:e.unanswered}:e.provisional!==null&&(e.concluded||e.queued.length===0)?{kind:"check"}:e.concluded?{kind:"end",reason:{kind:"completed"}}:e.queued.length>0||e.owed?r?{kind:"end",reason:{kind:"max-steps",limit:t.maxStepsPerTurn}}:{kind:"ask-model",claim:e.queued}:{kind:"end",reason:{kind:"completed"}}}var Ke=(e,t)=>V(e,t).kind!=="end";import{randomUUID as Xt}from"node:crypto";var j=e=>`${e}_${Xt()}`;var Ye={init:()=>({lastTurn:0,step:0,lastReason:null,turnOpen:!1,concludedTurn:null}),apply(e,t){return t.type==="turn/start"?(e.lastTurn=t.data.turn,e.step=0,e.lastReason=null,e.turnOpen=!0):t.type==="step/start"?e.step+=1:t.type==="turn/end"?(e.lastReason=t.data.reason,e.turnOpen=!1):t.type==="input/message"?e.concludedTurn=null:t.type==="tool/result"&&t.data.result.concludes_turn===!0&&(e.concludedTurn=e.lastTurn),e}},te={init:()=>({status:"none"}),apply(e,t){switch(t.type){case"assistant/message":{if(t.data.interrupted)return e;let r=t.data.response.message;return r.tool_calls.length>0?{status:"none"}:{status:"pending",seq:t.seq,kind:"reply",text:Y(r),finish:t.data.response.finish}}case"tool/result":return t.data.result.concludes_turn!==!0?e:{status:"pending",seq:t.seq,kind:"concluded",text:t.data.result.output};case"input/message":return{status:"none"};case"turn/end":{if(e.status!=="pending")return e;let{kind:r}=t.data.reason;return r==="completed"?{...e,status:"accepted"}:r==="rejected"?{...e,status:"rejected"}:e}default:return e}}},Xe={init:()=>new Map,apply(e,t){return t.type==="tool/call"?e.set(t.data.call_id,t.seq):t.type==="tool/result"&&e.delete(t.data.result.call_id),e}},Ze={init:()=>new Map,apply(e,t){switch(t.type){case"tool/call":e.delete(t.data.call_id);break;case"tool/authorization":{let{call_id:r,call_seq:n,turn:s,decision:o,policy:a}=t.data;e.set(r,{seq:t.seq,call_seq:n,turn:s,decision:o,policy:a});break}case"tool/result":e.delete(t.data.result.call_id);break;default:break}return e}};function et(e,t,r,n,s){let o=e.get(r);if(!(o===void 0||o.call_seq!==n)&&!(o.decision!=="allow"||o.turn>=s||fe(t.get(n))))return o}var tt={init:()=>new Map,apply(e,t){if(t.type==="wait/declared"){let{data:r}=t;e.has(r.call_seq)||e.set(r.call_seq,{declaration:{seq:t.seq,turn:r.turn,step:r.step,call_id:r.call_id,call_seq:r.call_seq,owner:r.owner,dependency:r.dependency,deadline_at:r.deadline_at,reason:r.reason},value:null,answered:!1})}else if(t.type==="wait/resolved"){let r=e.get(t.data.call_seq);r!==void 0&&r.value===null&&!r.answered&&(r.value=t.data.value)}else if(t.type==="tool/result"){let r=e.get(t.source_seqs[0]??0);r!==void 0&&(r.answered=!0)}return e}},Zt=e=>e!==void 0&&e.value===null&&!e.answered,fe=e=>e!==void 0&&!e.answered,rt=e=>[...e.values()].filter(t=>!t.answered);function re(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r.role!=="assistant"||r.tool_calls.length===0)continue;let n=new Set;for(let s of e.slice(t+1))s.role==="tool"&&s.tool_call_id!==null&&n.add(s.tool_call_id);return r.tool_calls.filter(s=>!n.has(s.call_id))}return[]}var nt={init:()=>new Map,apply(e,t){if(t.type==="confirm/requested"){let{request_id:r,tool_call:n,reason:s}=t.data;e.set(r,{request_id:r,thread_id:t.thread_id,call_seq:t.source_seqs[0]??null,tool_call:n,reason:s,resolution:null})}else if(t.type==="confirm/resolved"){let r=e.get(t.data.request_id);r!==void 0&&(r.resolution={approved:t.data.approved,rejection_message:t.data.rejection_message})}return e}},G=(e,t)=>[...e.values()].filter(r=>r.resolution===null&&r.thread_id===t),st=(e,t,r)=>{let n=new Set;for(let s of G(e,r))n.add(s.tool_call.call_id);for(let s of t.values())Zt(s)&&n.add(s.declaration.call_id);return n},ot=(e,t)=>{for(let r of e.values()){if(r.resolution===null)continue;if(r.call_seq===null?r.thread_id===t.threadId&&r.tool_call.call_id===t.callId:r.call_seq===t.callSeq)return r.resolution}},at={init:()=>null,apply(e,t){return t.type==="thread/spawned"?{thread_id:t.thread_id,agent_name:t.data.agent_name,metadata:t.data.metadata,fork:t.data.fork,origin:t.data.origin,environment:t.data.environment,requires:t.data.requires,seq:t.seq}:e}},it={init:()=>null,apply:(e,t)=>t.type==="confirm/resolved"?t.seq:e},ut={init:()=>null,apply(e,t){return t.type==="thread/spawned"||t.type==="run/cause"?t.data.route??e:e}},lt={init:()=>null,apply:(e,t)=>t.type==="thread/prompt"?t.data.blocks:e},dt={init:()=>null,apply:(e,t)=>t.type==="thread/tools"?t.data.tools:e},ct={init:()=>({spawnSeq:null,unclaimed:!1}),apply(e,t){return t.type==="inbox/spliced"&&e.spawnSeq!==null&&t.source_seqs.includes(e.spawnSeq)?{...e,unclaimed:!0}:t.type==="input/message"?{spawnSeq:null,unclaimed:!1}:e}},pt={init:()=>({"next-turn":[],"next-step":[]}),apply(e,t){if(t.type==="inbox/spliced"){let{target:r,start:n,removed:s,inserted:o}=t.data;return e[r].splice(n,s.length,...o),e}if(t.type==="input/message"&&t.data.input_id!==null)for(let r of["next-turn","next-step"]){let n=e[r].findIndex(s=>s.id===t.data.input_id);n>=0&&e[r].splice(n,1)}return e}},ft={init:()=>new Map,apply(e,t){if(t.type==="inbox/spliced")for(let r of t.data.inserted)e.has(r.id)||e.set(r.id,{queuedAt:t.seq,claimedAt:null});else if(t.type==="input/message"&&t.data.input_id!==null){let r=e.get(t.data.input_id);r!==void 0&&r.claimedAt===null&&e.set(t.data.input_id,{...r,claimedAt:t.seq})}return e}};function en(e,t,r){let n=te.init(),s=null;for(let o of e.rowsAfter(t,r))if(n=te.apply(n,o),o.type==="turn/end"&&(s=o.data.reason,n.status==="accepted"||er(s)))break;return n.status!=="accepted"?{reason:s,output:"",answered:!1}:{reason:s,output:n.text,answered:!0}}var er=e=>e!==null&&(e.kind==="error"||e.kind==="aborted"||e.kind==="max-steps"||e.kind==="rejected"),Qe=(e,t,r)=>{e.current.set(t.installation_id,{installationId:t.installation_id,presetId:t.preset_id,config:t.config,lifetime:r}),e.used.add(t.installation_id)},ht={init:()=>({current:new Map,used:new Set}),apply(e,t){if(t.type==="thread/spawned")for(let{lifetime:r,...n}of t.data.installations)Qe(e,n,r);else t.type==="installation/applied"?Qe(e,t.data,"configurable"):t.type==="installation/removed"&&e.current.delete(t.data.installation_id);return e}};var mt={reactive:0,fresh:1,person:2},xt={init:()=>({byInput:new Map,inputless:[],open:null,count:0}),apply(e,t){switch(t.type){case"run/cause":{let{input_id:r,run_id:n,chain:s}=t.data;return r!==null?e.byInput.set(r,s):e.inputless=[...e.inputless,{seq:t.seq,runId:n,chain:s}],e}case"run/requested":return e.inputless.some(r=>r.runId===null)&&(e.inputless=e.inputless.map(r=>r.runId===null?{...r,runId:t.data.run_id}:r)),e;case"run/settled":{let r=new Set(t.data.residual);return e.inputless=e.inputless.flatMap(n=>n.runId!==t.data.run_id?[n]:r.has(n.seq)?[{...n,runId:null}]:[]),e}case"turn/start":{gt(e),e.open={turn:t.data.turn,class:null};let r=t.data.run_id;for(let n of e.inputless)n.runId===r&&wt(e,n.chain);return e.inputless=e.inputless.filter(n=>n.runId!==r),e}case"inbox/spliced":for(let r of t.data.removed)e.byInput.delete(r);return e;case"input/message":{let r=t.data.input_id;if(r===null)return e;let n=e.byInput.get(r);return n===void 0||(e.byInput.delete(r),e.open!==null&&wt(e,n)),e}case"turn/end":return gt(e),e;default:return e}}};function wt(e,t){let r=e.open;(r.class===null||mt[t]>mt[r.class])&&(e.open={...r,class:t}),t!=="reactive"&&(e.count=0)}function gt(e){e.open?.class==="reactive"&&(e.count+=1),e.open=null}function tr(e,t){let r=e.count+(e.open?.class==="reactive"?1:0);return{personTurn:e.open?.class==="person",turns:r,atLimit:r>=t}}var yt={init:()=>({pending:null,pendingCancel:null,latestSettlement:null,latestUserCancel:null,latestReleasing:null,runs:new Map,latestTurn:null,interruptions:0,carried:[],inconsistencies:[]}),apply(e,t){switch(t.type){case"run/requested":return rr(e,t);case"run/cause":return nr(e,t);case"run/settled":return sr(e,t);case"turn/start":return e.pending?.runId!==t.data.run_id&&e.inconsistencies.push(`turn/start ${t.seq} serves ${t.data.run_id}, which is not pending`),e.latestTurn={seq:t.seq,runId:t.data.run_id,attemptCutoff:t.data.attempt_cutoff},e;case"turn/end":{let{reason:r}=t.data;return r.kind!=="interrupted"?e.interruptions=0:r.cause!=="abandoned"&&(e.interruptions+=1),e}case"thread/cancel":{let r={seq:t.seq,cancelId:t.data.cancel_id,intent:t.data.intent,runId:t.data.run_id,reason:t.data.reason};return r.intent==="user"&&(e.latestUserCancel=r),e.pendingCancel===null&&r.runId!==null&&r.runId===e.pending?.runId&&(e.pendingCancel=r),e}default:return e}}};function rr(e,t){let r=t.data.run_id;return e.pending!==null||e.runs.has(r)?(e.inconsistencies.push(`run/requested ${t.seq} opens ${r} while ${e.pending?.runId??r} exists`),e):(e.pending={runId:r,requestedAt:t.seq,causes:e.carried},e.carried=[],e.runs.set(r,{requestedAt:t.seq,settlement:null}),e)}function nr(e,t){let{pending:r}=e;if(r===null||r.runId!==t.data.run_id)return e.inconsistencies.push(`run/cause ${t.seq} names ${t.data.run_id}, which is not pending`),e;let n={seq:t.seq,at:t.timestamp,inputId:t.data.input_id,releases:t.data.releases,chain:t.data.chain};return e.pending={...r,causes:[...r.causes,n]},n.releases&&(e.latestReleasing=t.seq,e.interruptions=0),e}function sr(e,t){let{pending:r}=e,{data:n}=t;if(r===null||r.runId!==n.run_id)return e.inconsistencies.push(`run/settled ${t.seq} names ${n.run_id}, which is not pending`),e;let s={runId:n.run_id,seq:t.seq,outcome:n.outcome,reason:n.reason,errorText:n.error_text,through:n.through,residual:n.residual},o=new Set(n.residual);return e.carried=r.causes.filter(a=>o.has(a.seq)),e.pending=null,e.pendingCancel=null,e.interruptions=0,e.latestSettlement=s,e.runs.get(n.run_id).settlement=s,e}function nn(e,t){let r=e.runs.get(t);return r===void 0?{state:"unknown"}:r.settlement===null?{state:"pending"}:{state:"settled",settlement:r.settlement}}function sn(e,t,r){if(t.reason==="obsolete")return[];let n=t.reason==="cancel"?t.cancelSeq??t.attemptCutoff:t.attemptCutoff,s=t.outcome==="failed";return e.causes.filter(o=>o.inputId!==null&&r(o.inputId)!=="queued"?!1:o.seq>n&&(o.releases||!s)).map(o=>o.seq)}var kt={init:()=>({entries:[],refused:[]}),apply(e,t){if(t.type==="surface/replaced"){let n=It(e.entries,t);return n.accepted?Tt(e.entries,t,n):e.refused.push({row:he(t),refusal:n}),e}let r=ar(t);return r!==null&&e.entries.push(r),e}};function qt(e,t){let r=[...e];for(let[n,s]of t.entries()){let o=It(r,s);if(!o.accepted)return{index:n,refusal:o};Tt(r,s,o)}return null}var bt=e=>X(e)&&!(e.type==="assistant/message"&&e.data.interrupted);function or(e){if(!X(e)||!bt(e))return null;switch(e.type){case"input/message":return A({role:e.data.role,content:e.data.content});case"assistant/message":return e.data.response.message;case"tool/result":return A({role:"tool",content:Ie(e.data.result),tool_call_id:e.data.result.call_id})}}function ar(e){return!X(e)||!bt(e)?null:k({row:he(e),type:e.type,directDeveloperInput:e.type==="input/message"&&e.data.role==="developer"&&e.data.source===null,message:or(e)})}function It(e,t){let{data:r,source_seqs:n}=t;if(r.kind==="span"&&n.length===0)return O("empty","A span replaces at least one message");if(r.kind==="rewrite"&&n.length!==1)return O("empty",`A rewrite replaces exactly one message, not ${n.length}`);let s=e.findIndex(i=>i.row.seq===n[0]);if(s<0)return O("not-current",`Row ${n[0]} is not behind a message on the current surface`);for(let i=1;i<n.length;i+=1)if(e[s+i]?.row.seq!==n[i])return O("not-current",`The cited rows are not a contiguous run of the current surface: row ${n[i]} does not follow row ${n[i-1]}`);let o=s+n.length,a=e.slice(s,o).find(i=>i.directDeveloperInput);if(a!==void 0)return O("developer-input",`Row ${a.row.seq} is developer input a host sent, which nothing replaces`);if(r.kind==="rewrite"){let i=e[s];return ir(i)?{accepted:!0,start:s,count:1}:O("rewrite-target",`A rewrite replaces a tool result, a user message or a rewrite's stand-in, not ${ur(i)}`)}return o===e.length?O("newest-message","A span never replaces the newest message"):!ne(e,s)||!ne(e,o)?O("unbalanced","A span may not separate a tool call from its result, nor end just before a tool result"):{accepted:!0,start:s,count:n.length}}var O=(e,t)=>({accepted:!1,rule:e,message:t}),ir=e=>e.type==="tool/result"||e.type==="input/message"&&e.message.role==="user"||e.type==="surface/replaced"&&e.kind==="rewrite",ur=e=>e.type==="surface/replaced"?`a ${e.kind}'s stand-in`:`a ${e.message.role} message`;function ne(e,t){if(!Number.isInteger(t)||t<0||t>e.length)throw new RangeError(`A cut is at 0 to ${e.length}, not ${t}`);for(let r=t;r<e.length;r+=1){let{message:n}=e[r];if(n.role==="tool")return!1;if(_t(n))break}for(let r=t-1;r>=0;r-=1){let{message:n}=e[r];if(!_t(n))continue;let s=new Set;for(let o=r+1;o<t;o+=1){let a=e[o].message;a.role==="tool"&&a.tool_call_id!==null&&s.add(a.tool_call_id)}return n.tool_calls.every(o=>s.has(o.call_id))}return!0}var _t=e=>e.role==="assistant"&&e.tool_calls.length>0;function Tt(e,t,r){let n=he(t),{data:s}=t;if(s.kind==="span"){e.splice(r.start,r.count,k({row:n,type:"surface/replaced",kind:"span",directDeveloperInput:!1,message:A({role:s.stand_in.role,content:s.stand_in.content})}));return}let o=e[r.start].message;e[r.start]=k({row:n,type:"surface/replaced",kind:"rewrite",directDeveloperInput:!1,message:A({role:o.role,content:s.stand_in.content,tool_call_id:o.tool_call_id})})}function $t(e,t){let r=[],n=[t];for(;n.length>0;){let s=n.pop(),o=e.eventAt(s.seq);if(o===void 0)throw new RangeError(`The journal has no row ${s.seq}`);if(o.type!=="surface/replaced"){r.push(s);continue}for(let a=o.source_seqs.length-1;a>=0;a-=1){let i=o.source_seqs[a],u=e.eventAt(i);if(u===void 0)throw new RangeError(`Row ${o.seq} cites row ${i}, which no thread holds`);n.push({threadId:u.thread_id,seq:i})}}return r}var he=e=>({threadId:e.thread_id,seq:e.seq});var se={surface:kt,turnBoundary:Ye,answerCheck:te,dispatchedCalls:Xe,dispatchAttempts:Ze,waits:tt,confirmations:nt,threadRecord:at,threadRoute:ut,threadPrompt:lt,threadTools:dt,forkTask:ct,inbox:pt,inputs:ft,installations:ht,lastAnswer:it,requests:yt,chain:xt},lr={surface:"inherit",turnBoundary:e=>({...e,step:0,lastReason:null,turnOpen:!1}),answerCheck:"reset",dispatchedCalls:"reset",dispatchAttempts:"reset",waits:"reset",confirmations:"reset",threadRecord:"inherit",threadRoute:"inherit",threadPrompt:"inherit",threadTools:"inherit",forkTask:(e,t)=>({spawnSeq:t.seq,unclaimed:!1}),inbox:"reset",inputs:"reset",installations:"inherit",lastAnswer:"reset",requests:"reset",chain:"reset"},St=Object.keys(se);function Rt(e,t,r){let n=se[e],s=t;if(Ce(r)){let o=lr[e];o==="reset"?s=n.init():o!=="inherit"&&(s=o(s,r))}return n.apply(s,r)}var m=Oe({key:"threadState",init:()=>Object.fromEntries(St.map(e=>[e,se[e].init()])),apply(e,t){let r=e;for(let n of St)r[n]=Rt(n,r[n],t);return e}});function K(e){return{init:()=>se[e].init(),apply:(t,r)=>Rt(e,t,r)}}function At(e,t,r,n,s){let o=null;if(r.route!==void 0){if(s===void 0)throw new Error(`This write on thread ${e} takes no route statement`);o=Ge(e,r.route,s)}let a=t?.runId??j("run"),i=r.releases??!0,u=r.chain??"person",d={type:"run/cause",data:{run_id:a,input_id:n,releases:i,chain:u,route:o},options:{threadId:e}};return{runId:a,rows:t===null?[{type:"run/requested",data:{run_id:a},options:{threadId:e}},d]:[d]}}var me=e=>!Array.isArray(e);function dr(e){let[t]=e;if(t===void 0)return[];if(t.source===null)return[t];let r=e.findIndex(n=>n.source===null);return e.slice(0,r===-1?e.length:r)}var N=class{journal;threadId;constructor(t,r){this.journal=t,this.threadId=r}get queues(){return this.journal.state(m,this.threadId).inbox}get state(){return this.journal.state(m,this.threadId)}get nextTurn(){return this.queues["next-turn"]}get nextStep(){return this.queues["next-step"]}queuedAt(t){return this.journal.state(m,this.threadId).inputs.get(t)?.queuedAt}get pending(){return[...this.nextStep,...this.nextTurn].sort((t,r)=>(this.queuedAt(t.id)??0)-(this.queuedAt(r.id)??0))}async send(t,r,n={},s){if(n.source!==void 0&&n.id===void 0)throw new Error(`Input from ${n.source.plugin} needs an id: a redelivery must queue nothing twice`);let o=n.source??null,a=n.id??j("in"),{events:i,value:u}=await this.journal.transact(this.threadId,()=>{let d=this.queuedAt(a);if(d!==void 0)return{rows:[],value:{status:"known",inputId:a,queuedAt:d}};let l=n.target??r(),c=this.spliceEntry(l,this.queues[l].length,0,[Se(t,a,o)]),{wake:h}=n,f=h===void 0?null:At(this.threadId,this.state.requests.pending,h,a,s),p=f?.runId??null,g=n.rows?.({kind:"send",threadId:this.threadId,target:l,runId:p,inputId:a})??[];return me(g)?{rows:[],value:{status:"refused",refusal:g.refuse}}:{rows:[c,...f?.rows??[],...g],value:{runId:p}}});return"runId"in u?{status:"queued",inputId:a,queuedAt:i[0].seq,runId:u.runId}:u}async withdraw(t,r={}){let{value:n}=await this.journal.transact(this.threadId,()=>{let s;for(let a of["next-step","next-turn"]){let i=this.queues[a].findIndex(u=>u.id===t);i>=0&&(s=this.spliceEntry(a,i,1,[]))}let o=r.rows?.({threadId:this.threadId,withdrawn:s!==void 0})??[];return me(o)?{rows:[],value:{status:"refused",refusal:o.refuse}}:{rows:[...s===void 0?[]:[s],...o],value:{status:s===void 0?"not-queued":"withdrawn"}}});return n}clearRows(){return[this.spliceEntry("next-step",0,this.nextStep.length,[]),this.spliceEntry("next-turn",0,this.nextTurn.length,[])].filter(t=>t!==void 0)}peek(t,r=!1){let n=[...this.nextStep];(t==="next-turn"||r)&&n.push(...dr(this.nextTurn));let s=n.map(o=>{let a=this.queuedAt(o.id);if(a===void 0)throw new Error(`Missing queued sequence for input ${o.id} on thread ${this.threadId}`);return{input:o,seq:a}});return s.sort((o,a)=>o.seq-a.seq),s.map(({input:o})=>o)}spliceEntry(t,r,n,s){let o=this.queues[t],a=Math.min(Math.max(Math.trunc(r)||0,0),o.length),i=Math.min(Math.max(Math.trunc(n)||0,0),o.length-a);if(!(i===0&&s.length===0))return{type:"inbox/spliced",data:{target:t,start:a,removed:o.slice(a,a+i).map(u=>u.id),inserted:s},options:{threadId:this.threadId}}}};function J(e,t,r,n,s,o=!1){let a=e.state(m,t).surface.entries.map(h=>h.message),i=re(a),u=st(e.state(m,t).confirmations,e.state(m,t).waits,t),d=a.at(-1),l=e.state(m,t).turnBoundary,c=e.state(m,t).answerCheck;return{unanswered:i,parked:i.filter(h=>u.has(h.call_id)),queued:i.length>0?[]:new N(e,t).peek(r,o),owed:!e.state(m,t).forkTask.unclaimed&&(cr(d)||d?.role==="tool"&&l.concludedTurn===null),concluded:l.concludedTurn===s,provisional:c.status==="pending"?c.seq:null,step:n}}var cr=e=>e!==void 0&&$e.includes(e.role);function we(e,t,r){let n=e.state(m,t).turnBoundary.lastTurn+1;return Ke(J(e,t,"next-turn",0,n),r)}async function oe(e,t,r){await e.transact(t,()=>{let{lastTurn:n,turnOpen:s,step:o}=e.state(m,t).turnBoundary;if(!s)return{rows:[],value:void 0};let a=V(J(e,t,"next-step",o,n),r),i=a.kind==="end"?a.reason:{kind:"interrupted",cause:"abandoned"};return{rows:[{type:"turn/end",data:{turn:n,reason:i},options:{threadId:t}}],value:void 0}})}function pr(e,t){let r=e.inputs.get(t);if(r===void 0)return{state:"unknown"};let{queuedAt:n,claimedAt:s}=r;if(s!==null)return{state:"claimed",queuedAt:n,claimedAt:s};for(let o of["next-step","next-turn"])if(e.inbox[o].some(a=>a.id===t))return{state:"queued",queuedAt:n,target:o};return{state:"discarded",queuedAt:n}}function fr(e,t){let r=e.state(m,t);return[...r.confirmations.values()].filter(n=>{if(n.thread_id!==t||n.resolution?.approved===!1)return!1;let s=r.dispatchedCalls.get(n.tool_call.call_id);return s!==void 0&&(n.call_seq===null||s===n.call_seq)})}function hr(e,t){return e.state(m,t).surface.refused[0]??null}function mr(e,t){let{entries:r}=e.state(m,t).surface;for(let n=r.length-1;n>=0;n-=1){let s=r[n];if(s.type==="assistant/message")return s.message;if(s.type!=="surface/replaced")continue;let o=$t(e,s.row);for(let a=o.length-1;a>=0;a-=1){let i=e.eventAt(o[a].seq);if(i?.type==="assistant/message")return i.data.response.message}}return null}var On=e=>({kind:"wait",...e}),Ct=e=>"kind"in e&&e.kind==="wait";import{isDeepStrictEqual as Et}from"node:util";var wr=["deny","confirm","approve"];async function jt(e,t,r){let n=k(structuredClone(t)),s=await e.ctx.collect(e.target,"lagent/tool/authorize",n),o=s.map(gr);return o.includes("deny")?{decision:"deny",confirmedBy:null,reasons:xr(s)}:o.includes("confirm")?r.userApproved?{decision:"allow",confirmedBy:"user"}:o.includes("approve")?{decision:"allow",confirmedBy:"policy"}:{decision:"confirm",confirmedBy:null}:{decision:"allow",confirmedBy:null}}function gr(e){if(e!==void 0){if(typeof e=="string"&&wr.includes(e))return e;if(Ot(e))return"deny";throw new TypeError("A tool policy returned an invalid authorization decision")}}function Ot(e){if(typeof e!="object"||e===null)return!1;let{decision:t,reason:r}=e;return t==="deny"&&typeof r=="string"&&r.trim()!==""}var xr=e=>[...new Set(e.filter(Ot).map(t=>t.reason.trim()))];function yr(e){if(e===void 0||e===0)return 0;if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`A step contribution rank must be a finite number, not ${String(e)}`);return e}function vt(e,t){let r=[],n=!0,s=Object.freeze({threadId:t.threadId,turn:t.turn,step:t.step,route:k(structuredClone(t.route)),claimed:k(structuredClone(t.claimed)),contribute(o,a){if(!n)throw new Error("A step contribution arrived after its lagent/llm/step dispatch returned");let i=yr(a),u=de(o),d=r.find(f=>Et(f.contribution,u));if(d===void 0){r.push({contribution:u,rank:i});return}if(d.rank===i)return;let{plugin:l,kind:c,instance_id:h}=u.source;throw new Error(`Step contribution ${l}/${c}/${h} was made at rank ${d.rank} and at rank ${i}; identical contributions must share one rank`)}});try{e.ctx.emit(e.target,"lagent/llm/step",s)}finally{n=!1}return r.sort((o,a)=>o.rank-a.rank).map(o=>o.contribution)}async function Mt(e,t,r){let{signal:n,...s}=t,o=!0,a=Object.freeze({...k(structuredClone(s)),signal:n,observe(l){if(!o)throw new Error("A stop check declared an observation after its judgment ended");let c=null;try{c=l()}catch{}r.push({read:l,value:c})}}),i;try{i=await e.ctx.collect(e.target,"lagent/turn/stop",a)}catch(l){throw l instanceof AggregateError?new Error(`A stop check failed: ${l.errors.map(T).join("; ")}`,{cause:l}):l}finally{o=!1}let u=new Map,d=[];for(let l of i)if(l!==void 0)if(l.decision==="continue")d.push(de(l.message));else if(l.decision==="reject"&&typeof l.reason=="string"&&l.reason.trim()!==""){let c={reason:l.reason.trim(),source:Te.parse(l.source)};u.set(JSON.stringify(c),c)}else throw new TypeError("A stop check returned an invalid verdict");return u.size>0?{kind:"reject",rejections:[...u.values()]}:d.length>0?{kind:"continue",messages:d}:{kind:"accept"}}var Nt=(e,t,r)=>e.ctx.waterfall(e.target,"lagent/tool/execute",t,()=>(t.context.signal.throwIfAborted(),r()));function _r(e,t){let{signal:r,...n}=e,s=t,o={};for(let[a,i]of Object.entries(n))o[a]=i===s[a]?i:kr(i,s[a]);return Object.freeze({...o,signal:r})}var kr=(e,t)=>{if(!Array.isArray(e)||!Array.isArray(t))return k(structuredClone(e));let r=new Set(t);return Object.freeze(e.map(n=>r.has(n)?n:k(structuredClone(n))))};function qr(e,t){let r=["model","thinkingEffort","agentName","threadId","llmCallId","purpose","signal"];for(let n of[...r,...t])Object.defineProperty(e,n,{value:e[n],enumerable:!0,writable:!1,configurable:!1});return e}function ae(e,t){let{threadId:r,agentName:n,route:s}=t;return{model:s.model,tools:e.toolsFor(n).map(o=>o.spec),providerTools:[],parallelToolCalls:!0,responseFormat:{kind:"text"},...s.thinking_effort===null?{}:{thinkingEffort:s.thinking_effort},systemPrompt:e.journal.state(m,r).threadPrompt??[],signal:t.signal,agentName:n,threadId:r,llmCallId:t.llmCallId,purpose:t.purpose}}function ie(e,t,r,n,s=[]){let o,a;return{get row(){return o},get attempts(){return a?.attempts??0},call(i){let{signal:u,...d}=i,l=k(d),c=qr({...l,signal:u},s),h=()=>{e.signal.throwIfAborted(),u.throwIfAborted()};return e.ctx.waterfall(e.target,"lagent/llm/request",c,async()=>{h();let f=_r(c,l),p={threadId:f.threadId},g={type:r,data:{...n,llm_call_id:f.llmCallId,model:f.model,message_count:f.messages.length},options:p},{events:x}=await e.journal.transact(f.threadId,()=>{let y=e.journal.state(m,f.threadId).threadTools,_=JSON.parse(JSON.stringify(f.tools));return Et(_,y)?{rows:[g],value:void 0}:{rows:[{type:"thread/tools",data:{tools:f.tools},options:p},g],value:void 0}});return o=x.at(-1),await br(e,f,o),h(),a=t.call(f),a.response})}}}async function br(e,t,r){let{signal:n,...s}=t,o=Object.freeze({request:Object.freeze(s),row:r});try{await e.ctx.parallel(e.target,"lagent/llm/sent",o)}catch(a){for(let i of a instanceof AggregateError?a.errors:[a])e.ctx.reportError(i)}}function zt(e,t){e.ctx.reportError(t)}var Pt=["thread/spawned","turn/start","llm/request","turn/end","surface/replaced"];function Dt(e,t){return re(e.map(r=>r.message)).length>0?"the conversation there has tool calls without results":t.status==="pending"?"its answer is still owed its stop checks; resume the thread first":null}function Wn(e,t,r){let n=typeof r=="number"?r:r.seq,s;try{s=e.eventAt(n)}catch(i){throw i instanceof Ne?new $(t,n,`the row is not on thread ${t}'s lineage`):i}if(s===void 0)throw new $(t,n,"no thread has that row");if(typeof r!="number"&&s.thread_id!==r.threadId)throw new $(t,n,`the row belongs to thread ${s.thread_id}, not ${r.threadId}`);if(!Pt.includes(s.type))throw new $(t,n,`a ${s.type} row is not a cut; cut at ${Pt.join(", ")}`);if(!e.inLineage(t,s))throw new $(t,n,"the row is not part of this thread's conversation");let o=s.thread_id,a=Dt(e.stateAt(K("surface"),o,n).entries,e.stateAt(K("answerCheck"),o,n));if(a!==null)throw new $(t,n,a);return{threadId:o,seq:n}}function Hn(e,t,r,n){let s=typeof r=="number"?r:r.seq,o=e.lineage(t),a=o.findIndex(l=>l.seq===s),i=o[a];if(i===void 0)throw new $(t,s,"the row is not part of this thread's conversation");if(typeof r!="number"&&i.thread_id!==r.threadId)throw new $(t,s,`the row belongs to thread ${i.thread_id}, not ${r.threadId}`);let u=Ir(o,a);if(u===void 0)throw new $(t,s,"the row is not inside a turn");if(n)return Q(o[u]);let d=o[u].thread_id;for(let l=u+1;l<o.length;l+=1){let c=o[l];if(c.type==="turn/end"&&c.thread_id===d)return Q(c);if(c.type==="thread/spawned")break}throw new $(t,s,"its turn has not ended")}function Ir(e,t){for(let r=t;r>=0;r-=1){let n=e[r];if(n.type==="turn/start")return r;if(n.type==="thread/spawned"||n.type==="turn/end"&&r!==t)return}}function Vn(e,t){let r=[],n=K("surface"),s=K("answerCheck"),o=n.init(),a=s.init(),i=null;for(let u of e.lineage(t))o=n.apply(o,u),a=s.apply(a,u),u.type==="turn/end"&&(i=u.data.turn),Dt(o.entries,a)===null&&(u.type==="turn/end"?r.push({...Q(u),kind:"turn/end",turn:u.data.turn,reason:u.data.reason}):u.type==="surface/replaced"&&u.data.turn===null&&!$r(o,u.seq)&&r.push({...Q(u),kind:"surface/replaced",afterTurn:i}));return r}function Tr(e,t){let r=e.rows(t.threadId),n=r.length-1;for(;n>=0&&r[n].seq>t.seq;)n-=1;let s=r[n];if(s?.seq!==t.seq||s.type!=="assistant/message")return null;for(let o=n-1;o>=0;o-=1){let a=r[o];if(a.type==="llm/request"&&a.data.llm_call_id===s.data.llm_call_id)return Q(a)}return null}function Bt(e,t){let r=ge(e,t);return r===null?null:Tr(e,r)}function ge(e,t){let{entries:r}=e.state(m,t).surface;for(let n=r.length-1;n>=0;n-=1)if(r[n].type==="assistant/message")return r[n].row;return null}var $r=(e,t)=>e.refused.some(r=>r.row.seq===t),Q=e=>({threadId:e.thread_id,seq:e.seq});var I=(e,t)=>({call_id:e.call_id,name:e.name,output:t,is_error:!0,notes:null,metadata:{}}),Sr=(e,t)=>({...I(e,`Tool "${e.name}" was interrupted before its result was recorded, so whether it took effect is unknown. Check what became of it before repeating it; do not simply call it again.`),metadata:{interrupted:!0,attempt_seq:t.seq}}),Rr=e=>({...I(e,`Tool "${e.name}" was not run: its arguments are not a JSON object (${e.malformed.error}). Received: ${e.malformed.raw.slice(0,500)}`),metadata:{malformed_arguments:!0}});function Ar(e,t){let r=[];for(let n of e){let s=t(n.name)==="exclusive",o=r.at(-1);s||o===void 0||o.exclusive?r.push({calls:[n],exclusive:s}):o.calls.push(n)}return r}async function Ut(e){let{runtime:t,threadId:r,agentName:n,turn:s,step:o,calls:a,signal:i}=e,{journal:u}=t,d=ge(u,r),l={...e,requestSeq:Bt(u,r)?.seq??null},c=w=>t.tool(n,w)?.tool.executionMode??"parallel",h=new Map,f=!1,p=()=>{let w=u.state(m,r).dispatchedCalls;return a.filter(b=>!w.has(b.call_id))};await u.transact(r,()=>({rows:p().map(w=>({type:"tool/call",data:{turn:s,step:o,call_id:w.call_id,name:w.name},options:{threadId:r,sourceSeqs:d===null?[]:[d.seq]}})),value:void 0}));let g=u.state(m,r).dispatchedCalls;for(let w of a)h.set(w.call_id,g.get(w.call_id));let x=w=>h.get(w.call_id),y=new Map;for(let w of a){let{dispatchAttempts:b,waits:P}=u.state(m,r),ue=et(b,P,w.call_id,x(w),s);ue?.policy==="report"&&y.set(w.call_id,{result:Sr(w,ue),attempt:ue})}let _=w=>u.state(m,r).dispatchedCalls.get(w.call_id)===x(w),z=w=>fe(u.state(m,r).waits.get(x(w))),S=async(w,b,P=[])=>{await u.transact(r,()=>({rows:_(w)&&!(i.aborted&&z(w))?[{type:"tool/result",data:{turn:s,step:o,result:b},options:{threadId:r,sourceSeqs:[x(w),...P]}}]:[],value:void 0}))},q=(w,b)=>{let P=y.get(w.call_id);return S(w,b,P===void 0?[]:[P.attempt.seq])};for(let w of Ar(a,c)){if(f||i.aborted||t.stale())break;let b=await Cr(w,l,y,q);f||=b.stopLater}if(i.aborted)for(let w of a){let b=y.get(w.call_id);b!==void 0?await S(w,b.result,[b.attempt.seq]):await S(w,I(w,"Tool call aborted before dispatch"))}}async function Cr(e,t,r,n){let{runtime:s,signal:o}=t,a=e.exclusive?1:Math.max(s.limits.maxParallelToolCalls,1),i=Array.from({length:e.calls.length}),u=new Map,d=0,l=0,c=!1,h=!1,f=async()=>{for(;l<e.calls.length;){let g=i[l];if(g===void 0)break;g.kind==="result"?await n(e.calls[l],g.result):g.kind==="confirm"?c=h=!0:g.kind==="wait"&&(h=!0),l+=1}},p=()=>{for(;d<e.calls.length&&u.size<a&&!o.aborted&&!c&&!s.stale();){let g=d++,x=e.calls[g];u.set(g,Er(x,t,r.get(x.call_id)).then(y=>(i[g]=y,g)))}};p();try{for(;u.size>0;){let g=await Promise.race(u.values());u.delete(g),await f(),p()}await f()}catch(g){throw await Promise.allSettled(u.values()),g}return{stopLater:h}}async function Er(e,t,r){if(r!==void 0)return{kind:"result",result:r.result};if(!be(e))return{kind:"result",result:Rr(e)};let{runtime:n,threadId:s,agentName:o,environment:a,route:i,turn:u,step:d,signal:l,requestSeq:c}=t,{journal:h}=n,f=n.tool(o,e.name);if(f===void 0)return{kind:"result",result:I(e,`No such tool named "${e.name}"`)};let p=h.state(m,s).dispatchedCalls.get(e.call_id);if(p===void 0)return{kind:"result",result:I(e,`Call ${e.call_id} was dispatched before it was recorded`)};let g=h.state(m,s).waits.get(p),x=g?.value==null||g.answered?null:{dependency:g.declaration.dependency,value:g.value},y=await jr(e,f.tool.onInterrupted,p,x!==null,t);if(y.kind!=="decided")return y;let{authorization:_,attempt:z}=y;if(_.decision==="deny"){let{reasons:q}=_,w=q.length===0?`Tool "${e.name}" was denied.`:`Tool "${e.name}" was denied: ${q.join(" ")}`;return{kind:"result",result:I(e,w)}}if(_.decision==="confirm")return await h.append("confirm/requested",{turn:u,step:d,request_id:`cf_${p}`,tool_call:e,reason:`Tool '${e.name}' requires user confirmation`},{threadId:s,sourceSeqs:[p]}),{kind:"confirm"};let S={tool:f.tool,call:e,context:{ctx:n.ctx,signal:l,agentName:o,threadId:s,callId:e.call_id,callSeq:p,requestSeq:c,environment:a,route:i,wait:x},toolName:f.name,threadId:s};try{let q=await Nt(n,S,()=>S.tool.invoke(S.call,S.context));if(Ct(q)){let w=await Or(t,e,p,z.seq,q);return w===null?{kind:"wait"}:{kind:"result",result:I(e,w)}}if(q.call_id!==e.call_id){let w=`Tool "${f.name}" answered call ${q.call_id} instead of ${e.call_id}`,b={...q.metadata,stray_output:q.output};return{kind:"result",result:{...I(e,w),notes:q.notes,metadata:b}}}return{kind:"result",result:q}}catch(q){return l.aborted&&q===l.reason?{kind:"result",result:I(e,`The call was cancelled: ${T(q)}`)}:{kind:"result",result:I(e,T(q))}}}async function jr(e,t,r,n,s){let{runtime:o,threadId:a,agentName:i,turn:u,step:d,signal:l}=s,{journal:c}=o;for(let h=1;;h+=1){await c.flush();let f=c.head,p=ot(c.state(m,a).confirmations,{threadId:a,callId:e.call_id,callSeq:r});if(p?.approved===!1){let y=p.rejection_message?`Tool "${e.name}" was rejected by the user with message: ${p.rejection_message}`:`Tool "${e.name}" was rejected by the user.`;return{kind:"result",result:I(e,y)}}let g;try{g=await jt(o,{toolCall:e,agent:o.agent(i),threadId:a},{userApproved:p?.approved===!0})}catch(y){let _=y instanceof AggregateError?y.errors.map(T).join("; "):T(y);return{kind:"result",result:I(e,`Tool authorization failed: ${_}`)}}if(l.aborted)return n?{kind:"unstarted"}:{kind:"result",result:I(e,"Tool call aborted before dispatch")};if(o.stale())return{kind:"unstarted"};let{events:[x]}=await c.transact(a,()=>({rows:zr(c,a,f)?[]:[{type:"tool/authorization",data:{turn:u,step:d,call_id:e.call_id,call_seq:r,decision:g.decision,confirmed_by:g.confirmedBy,policy:t},options:{threadId:a,sourceSeqs:[r]}}],value:void 0}));if(x!==void 0)return{kind:"decided",authorization:g,attempt:x};if(h===vr)return{kind:"result",result:I(e,`Tool "${e.name}" was not run: its permissions kept changing while it was authorized`)}}}async function Or(e,t,r,n,s){let{runtime:o,threadId:a,turn:i,step:u,signal:d}=e,{journal:l}=o,c=Re["wait/declared"].safeParse({turn:i,step:u,call_id:t.call_id,call_seq:r,owner:s.owner,dependency:s.dependency,deadline_at:s.deadlineAt,reason:s.reason});if(!c.success)return`Tool "${t.name}" asked to wait with a declaration that is not valid: ${c.error.message}`;let{value:h}=await l.transact(a,()=>{let f=null;return d.aborted?f="Tool call aborted before its wait was recorded":o.waitOwner(s.owner)?l.state(m,a).waits.has(r)&&(f=`Tool "${t.name}" asked to wait again for a call that already waited`):f=`Tool "${t.name}" cannot wait: nothing registered as ${s.owner} would resolve it`,f!==null?{rows:[],value:f}:{rows:[{type:"wait/declared",data:c.data,options:{threadId:a,sourceSeqs:[r,n]}}],value:null}});return h}var vr=5,Ft=new Set,Lt=e=>JSON.stringify([e.plugin,e.instance_id??null,e.kind]);function Mr(e){Ft.add(Lt(e))}var Nr=e=>e.type==="confirm/resolved"||e.type==="ext"&&Ft.has(Lt(e.data));function zr(e,t,r){return e.origins.callers(t).threads.some(n=>n.through_seq>r&&(!e.isLoaded(n.thread_id)||e.rowsAfter(n.thread_id,r).some(Nr)))}var Jt=class{listeners=new Set;report;constructor(t){this.report=t}emit(t){this.listeners.size!==0&&je(this.listeners,k(structuredClone(t)),this.report)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}};var Wt={maxStepsPerTurn:4096,maxThreadDepth:8,maxParallelToolCalls:8},is=(e={})=>{let t={...Wt,...e};for(let r of Object.keys(Wt)){let n=r==="maxThreadDepth"?0:1,s=t[r];if(!Number.isFinite(s)||!Number.isInteger(s)||s<n)throw new RangeError(`${r} must be a finite integer >= ${n}; received ${String(s)}`)}return t};var Ht=200;function ps(e,t,r){let n=e.rows(t),s=e.state(m,t).threadRecord;if(s===null)throw new Error(`Thread ${t} has no spawn row`);let o=e.state(m,t).turnBoundary,{inbox:a,threadRoute:i,requests:u,lastAnswer:d,waits:l}=e.state(m,t);if(i===null)throw new Error(`Thread ${t} has no route`);let{pending:c,latestSettlement:h,latestUserCancel:f}=u;return{thread_id:t,spawn_seq:s.seq,through_seq:n.at(-1)?.seq??s.seq,agent_name:s.agent_name,metadata:s.metadata,fork:s.fork,origin:s.origin,environment:s.environment,has_work:o.turnOpen||we(e,t,r),turn_open:o.turnOpen,last_reason:o.lastReason,route:i,queued_input:a["next-turn"].length+a["next-step"].length,unanswered_confirmations:G(e.state(m,t).confirmations,t).map(p=>({request_id:p.request_id,call_seq:p.call_seq,tool_name:p.tool_call.name,reason:p.reason.slice(0,Ht)})),waits:rt(l).map(({declaration:p,value:g})=>({call_seq:p.call_seq,owner:p.owner,deadline_at:p.deadline_at,reason:p.reason.slice(0,Ht),resolved:g!==null})),pending_run:c===null?null:{run_id:c.runId,newest_cause_at:c.causes.at(-1)?.at??null,releasing:c.causes.some(p=>p.releases),cancelled:u.pendingCancel?.runId===c.runId},latest_settlement:h===null?null:{run_id:h.runId,outcome:h.outcome,reason:h.reason,error_text:h.errorText},latest_user_cancel:f===null?null:{seq:f.seq,released:u.latestReleasing!==null&&u.latestReleasing>f.seq},requires:[...s.requires],answered_at:d}}var ms=(e,t)=>ce(e)===ce(t),ws=e=>e.reason==="wait"||e.reason==="constraint"||e.reason==="rejudge"?e.text:null;function gs(e){let t=[];e.approval&&t.push({reason:"approval"}),e.failed&&t.push({reason:"failure"}),e.cancelled&&t.push({reason:"cancellation"}),e.startupDeclined&&t.push({reason:"startup"}),e.missing.length>0&&t.push({reason:"missing"});let r=e.unresolvedWait;return r!==null&&t.push({reason:"wait",callSeq:r.callSeq,owner:r.owner,ownerRegistered:r.registered,deadline:r.deadlineAt,text:Pr(r)}),t}function Pr(e){return e.registered?e.reason:`${e.reason} (its owner ${e.owner} is not registered)`}function xs(e){let t=e.pending?.causes.some(r=>r.releases)??!1;return e.latestSettlement?.outcome==="failed"&&!t}function ys(e){let t=e.latestUserCancel;return t!==null&&(e.latestReleasing===null||e.latestReleasing<t.seq)}var Dr=e=>e==="user"?"cancelled":"superseded",C=(e,t)=>({kind:"settle",outcome:e,reason:t}),Br=1,bs=e=>Math.max(0,Br+1-Math.max(1,e.interruptions)),Ur={reason:"rejudge",text:"the facts or registrations the answer's stop checks judged under kept changing; it is judged again on the next releasing cause"};function Vt(e){let[t]=e.holds.filter(r=>!(e.answeredUnder&&r.reason==="approval"));return t!==void 0?t:e.constraint.kind==="hold"?Fr(e.constraint):null}function Fr(e){let{owner:t,reason:r,code:n,data:s}=e;return k({reason:"constraint",owner:t,...n===void 0?{}:{code:n},...s===void 0?{}:{data:Ee(s)},text:r})}function Is(e){if(e.cancel!==null)return C(Dr(e.cancel),"cancel");if(e.constraint.kind==="obsolete")return C("superseded","obsolete");let{ending:t,work:r}=e,n=e.holds.some(a=>a.reason==="approval"),s;switch(t?.kind){case void 0:s=C("completed","nothing");break;case"aborted":return{kind:"hold",hold:{reason:"shutdown"}};case"interrupted":{if(t.cause==="abandoned"){s=C("completed","nothing");break}let a=Vt(e);return a!==null?{kind:"hold",hold:a}:e.repairsLeft>0&&r.hasWork?{kind:"repair"}:t.cause==="activation-changed"?C("failed","turn"):{kind:"hold",hold:Ur}}case"error":return C("failed","turn");case"max-steps":case"rejected":if(s=C("failed","turn"),!r.nextStepQueued)return s;break;case"blocked":if(n&&!e.answeredUnder)return{kind:"hold",hold:{reason:"approval"}};s=C("completed","nothing");break;case"completed":if(s=C("completed","answered"),!r.anyQueued)return s;break}let o=Vt(e);if(o!==null)return{kind:"hold",hold:o};if(r.hasWork)return{kind:"advance"};if(n)return{kind:"hold",hold:{reason:"approval"}};if(t?.kind==="blocked"&&r.unanswered)throw new Error("A blocked turn left calls that nothing holds and none of which can be dispatched");return s}function Ts(e,t){return e===null||e.runId===t?null:e.runId}function Lr(e,t){let{requests:r,turnBoundary:n}=e,s=r.latestTurn;return s?.runId!==t||n.turnOpen||n.lastReason===null?null:{ending:n.lastReason,start:s.seq,attemptCutoff:s.attemptCutoff}}function Jr(e,t){let r=Lr(e,t);if(r===null)return null;let{kind:n}=r.ending;if(n==="aborted"||n==="interrupted"&&r.ending.cause==="abandoned")return null;if(n==="completed"||n==="blocked"||n==="interrupted"){let{pending:s}=e.requests;if(s?.causes.some(o=>o.releases&&o.seq>r.start))return null}return r}function $s(e){let{pending:t,latestTurn:r}=e.requests,n=t===null?null:Jr(e,t.runId);return{resumed:n,ending:n?.ending??null,start:n?.start??r?.seq??null}}async function xe(e,t,r,n){if(n.length===0)return[];let s=n.map(({source_seqs:a,auxiliary_request_seq:i,...u})=>({type:"surface/replaced",data:{...u,trigger:r.trigger,turn:r.turn,step:r.step,auxiliary_request_seq:i??null},options:{threadId:t,sourceSeqs:a}})),{events:o}=await e.transact(t,()=>{if(e.summary(t)===void 0)throw new U(t);let a=e.head,i=s.map((d,l)=>Ae({seq:a+l+1,type:d.type,thread_id:t,data:d.data,source_seqs:d.options.sourceSeqs})),u=qt(e.state(m,t).surface.entries,i);if(u!==null)throw new Z(u.refusal.message,u.index,u.refusal.rule);return{rows:s,value:void 0}});return o.map(a=>({threadId:t,seq:a.seq}))}async function Kt(e,t,r){let{journal:n}=e,{threadId:s,signal:o}=t,a,i=!1;try{o.throwIfAborted();let{entries:u}=n.state(m,s).surface,d=u.findIndex(w=>w.row.seq===r.through);if(d<0)throw new E(`Row ${r.through} is not behind a message on the current surface`);if(!ne(u,d+1))throw new E(`A prefix ending on row ${r.through} separates a tool call from its result; end it on a balanced cut`);if(r.instructions.length===0)throw new E("An auxiliary call needs an instruction");let l=r.instructions.map(w=>qe.parse(w)),c=Wr(e,t.route,r.route),h=e.client(c),f=u.slice(0,d+1).map(w=>w.message),p=j("llm"),g={messages:[...f,...l.map(w=>k(A({role:"user",content:w})))],toolChoice:structuredClone(r.toolChoice??"auto"),...r.maxOutputTokens===void 0?{}:{maxOutputTokens:r.maxOutputTokens},...ae(e,{threadId:s,agentName:t.agentName,route:c,signal:o,llmCallId:p,purpose:"auxiliary"})};a=ie(e,h,"auxiliary/request",{turn:t.turn,step:t.step,route:c,surface_message_count:f.length,instructions:l},["toolChoice","maxOutputTokens"]);let x=await a.call(g),y=a.row;if(y===void 0)throw new Error("Request middleware answered an auxiliary call itself; an auxiliary call goes to its route");let _=await x.completed();o.throwIfAborted();let z=Y(_.message),S=_.message.usage;i=!0;let q=await Gt(e,t,y,p,{usage:S,text:z,finish:_.finish,tool_calls:_.message.tool_calls,provider_calls:_.message.provider_calls,error_text:null,error_kind:null,attempts:a.attempts});return{requestSeq:y.seq,resultSeq:q.seq,message:_.message,text:z,finish:_.finish,usage:S}}catch(u){let d=a?.row;if(d!==void 0&&!i){i=!0;let l=B(o,u),c=R(u,D);await Gt(e,t,d,d.data.llm_call_id,{usage:null,text:null,finish:null,error_text:l?`aborted: ${T(o.reason)}`:v(u),error_kind:l?"aborted":c?.kind??"other",attempts:c?.attempts??a?.attempts??0})}throw u}}var Wr=(e,t,r)=>r===void 0?t:e.resolveRoute(r,t);async function Gt(e,t,r,n,s){if(r===void 0)throw new Error("An auxiliary result needs its request row");return e.journal.append("auxiliary/result",{turn:t.turn,step:t.step,llm_call_id:n,...s},{threadId:t.threadId,sourceSeqs:[r.seq]})}async function Yt(e,t){let{threadId:r,signal:n,lease:s}=t,o=e.strategy();if(o===void 0)return{outcome:{committed:[],ended:"skipped",reason:"no strategy prepares this thread"},error:void 0};let a=Object.freeze({threadId:r,turn:t.turn,step:t.step,route:k(structuredClone(t.route)),trigger:t.trigger,queued:k(structuredClone(t.queued)),options:k(structuredClone(t.options)),signal:n}),i=()=>{if(n.throwIfAborted(),!s.held)throw new Error(`Thread ${r}'s lease passed to another holder while it was prepared`)};try{let u=await o.plan(a),d,l=null;if(u.kind==="ask"){i();let h;try{let f=await Kt(e,{threadId:r,agentName:t.agentName,turn:t.turn,step:t.step,route:t.route,signal:n},u.call);l=f.requestSeq,h={reply:f}}catch(f){if(Qt(f)||R(f,E)!==void 0)throw f;if(B(n,f))throw n.reason;h={failure:f}}i(),d=await u.finish(h)}else d=u;if(i(),d.kind==="skip")return{outcome:{committed:[],ended:"skipped",reason:d.reason},error:void 0};if(d.kind==="fail")return d.facts!==void 0&&d.facts.length>0&&await e.journal.appendAll(d.facts.map(h=>({type:"ext",data:h,options:{threadId:r}}))),n.aborted?{outcome:ye([],n),error:void 0}:{outcome:{committed:[],ended:"failed",reason:d.reason},error:void 0};if(d.replacements.length===0)throw new TypeError("A replace plan names no replacement; a plan with nothing to replace is a skip");for(let h of d.replacements){let f=h.auxiliary_request_seq;if(f!=null&&f!==l)throw new TypeError(`Row ${f} is not the auxiliary request this plan made`)}let c=await xe(e.journal,r,t,d.replacements);return n.aborted?{outcome:ye(c,n),error:void 0}:{outcome:{committed:c,ended:"completed",...d.reason===void 0?{}:{reason:d.reason}},error:void 0}}catch(u){if(Qt(u))throw u;return n.aborted&&ze(n,u)?{outcome:ye([],n),error:void 0}:{outcome:{committed:[],ended:"failed",reason:v(u)},error:u}}}var Qt=e=>e instanceof ve||e instanceof Me,ye=(e,t)=>({committed:e,ended:"cancelled",reason:T(t.reason)});function Hr(e){try{return e.value===null||e.read()!==e.value}catch{return!0}}var _e=class{runtime;threadId;agentName;inbox;constructor(t){this.runtime=t.runtime,this.threadId=t.threadId,this.agentName=t.agentName,this.inbox=new N(t.runtime.journal,t.threadId)}stepsTaken(){return this.runtime.journal.state(m,this.threadId).turnBoundary.step}async run(t){let{signal:r,lease:n,served:s}=t;r.throwIfAborted();try{let{journal:o,limits:a}=this.runtime;for(await oe(o,this.threadId,a);;){let i=await this.turn(r,n,s);if(r.aborted||this.runtime.stale())break;let u=o.state(m,this.threadId).turnBoundary.lastReason;if(u===null||!s.continueAfter(u,i))break}}catch(o){if(!(o instanceof H))throw o}}async turn(t,r,n){let{journal:s,limits:o}=this.runtime,a=s.state(m,this.threadId).turnBoundary.lastTurn+1,i=await this.openTurn(a,t,n),u={turn:a,signal:t,route:i.route,lease:r},d,l=null,c="next-turn",h=!1,f=!1;try{for(;;){t.throwIfAborted();let p=V(J(s,this.threadId,c,this.stepsTaken(),a,f),o);if(p.kind==="end"){d=p.reason;break}if(this.runtime.stale()){d={kind:"interrupted",cause:"activation-changed"};break}if(p.kind==="check"){l={registrations:this.runtime.requiredRegistrations(this.threadId),observations:[]};let x=await this.judge(a,t,l);if(x!==null){d=x;break}l=null,h&&(f=!0),c="next-step";continue}let g=this.stepsTaken()+1;await s.append("step/start",{turn:a,step:g},{threadId:this.threadId});try{p.kind==="ask-model"?await this.askModel(u,g,p.claim):await this.answerCalls(u,g,p.calls)}finally{await s.append("step/end",{turn:a,step:g},{threadId:this.threadId})}c==="next-turn"&&p.kind==="answer-calls"&&(h=!0),c="next-step"}}catch(p){if((p instanceof M||p instanceof W)&&!t.aborted){let x=p instanceof M?"activation-changed":"judgment-invalidated";return await s.append("turn/end",{turn:a,reason:{kind:"interrupted",cause:x}},{threadId:this.threadId}),i.seq}let g=R(p,D);if(d=t.aborted?{kind:"aborted",reason:T(t.reason)}:{kind:"error",error_text:v(p),failure_kind:g?.kind??"other",retry_after_ms:g?.retryAfterMs??null},t.aborted||l===null)await s.append("turn/end",{turn:a,reason:d},{threadId:this.threadId});else if((await this.endJudged(a,d,l)).kind==="interrupted")return i.seq;throw new H(p)}return l===null?await s.append("turn/end",{turn:a,reason:d},{threadId:this.threadId}):await this.endJudged(a,d,l),i.seq}fenced(t){if(this.runtime.stale())return"activation-changed";let r=this.runtime.requiredRegistrations(this.threadId);return t.registrations===null||r!==t.registrations||t.observations.some(Hr)?"judgment-invalidated":null}async endJudged(t,r,n){let s=this.threadId,{value:o}=await this.runtime.journal.transact(s,()=>{let a=this.fenced(n),i=a===null?r:{kind:"interrupted",cause:a};return{rows:[{type:"turn/end",data:{turn:t,reason:i},options:{threadId:s}}],value:i}});return o}async openTurn(t,r,n){let{journal:s}=this.runtime,{events:o,value:a}=await s.transact(this.threadId,()=>{r.throwIfAborted();let i=this.threadRoute();if(this.runtime.unavailable(i)!==null)throw new L(i);return{rows:[{type:"turn/start",data:{turn:t,route:i,run_id:n.id,attempt_cutoff:n.attemptCutoff},options:{threadId:this.threadId}}],value:i}});return{route:a,seq:o[0].seq}}threadRoute(){let t=this.runtime.journal.state(m,this.threadId).threadRoute;if(t===null)throw new Error(`Thread ${this.threadId} has no route`);return t}async compact(t){let{journal:r,limits:n}=this.runtime,s=this.threadId;await oe(r,s,n);let{lastTurn:o}=r.state(m,s).turnBoundary;if(J(r,s,"next-turn",0,o+1).unanswered.length>0)throw new F(s,"it has tool calls without results");if(G(r.state(m,s).confirmations,s).length>0)throw new F(s,"a confirmation is open");if(r.state(m,s).answerCheck.status==="pending")throw new F(s,"its answer is still owed its stop checks");if(t.signal.aborted)return{committed:[],ended:"cancelled",reason:T(t.signal.reason)};let a=this.threadRoute();if(this.runtime.unavailable(a)!==null)throw new L(a);let{outcome:i}=await this.prepare({turn:null,step:null,route:a,trigger:"request",queued:[],options:t.options,signal:t.signal,lease:t.lease});return i}prepare(t){return Yt(this.runtime,{...t,threadId:this.threadId,agentName:this.agentName})}async judge(t,r,n){let{journal:s,limits:o}=this.runtime,a=this.threadId,i=s.state(m,a).answerCheck;if(i.status!=="pending")throw new Error(`Thread ${a} has no answer to judge`);let u=await Mt(this.runtime,{threadId:a,turn:t,answer:i.kind==="reply"?{seq:i.seq,kind:i.kind,text:i.text,finish:i.finish}:{seq:i.seq,kind:i.kind,text:i.text},stepsLeft:Math.max(0,o.maxStepsPerTurn-this.stepsTaken()),signal:r},n.observations);if(r.throwIfAborted(),u.kind==="accept")return{kind:"completed"};if(u.kind==="reject")return{kind:"rejected",rejections:u.rejections};let{value:d}=await s.transact(a,()=>{let l=this.fenced(n);return l!==null?{rows:[],value:l}:{rows:u.messages.map(c=>({type:"input/message",data:{turn:t,role:c.role,content:c.content,source:c.source},options:{threadId:a,sourceSeqs:c.source_seqs}})),value:null}});if(d==="activation-changed")throw new M;if(d!==null)throw new W;return null}async askModel(t,r,n){let{turn:s,signal:o,route:a}=t,i=this.threadId,u=await this.prepare({turn:s,step:r,route:a,trigger:"pressure",queued:n,options:null,signal:o,lease:t.lease});if(this.reportFailedDispatch(u),o.throwIfAborted(),this.runtime.stale())throw new M;let{value:d}=await this.runtime.journal.transact(i,()=>{let l=new Set(this.inbox.pending.map(p=>p.id)),c=n.filter(p=>l.has(p.id));return c.length===0&&!J(this.runtime.journal,i,"next-step",r,s).owed?{rows:[],value:!1}:{rows:[...vt(this.runtime,{threadId:i,turn:s,step:r,route:a,claimed:c}).map(p=>({type:"input/message",data:{turn:s,role:p.role,content:p.content,source:p.source},options:{threadId:i,sourceSeqs:p.source_seqs}})),...c.map(p=>({type:"input/message",data:{turn:s,role:p.role,content:p.content,input_id:p.id,source:p.source},options:{threadId:i}}))],value:!0}});d&&await this.callModel(t,r)}reportFailedDispatch({outcome:t,error:r}){t.ended==="failed"&&zt(this.runtime,r??new Error(`Thread ${this.threadId}: preparing the surface failed: ${t.reason??"no reason given"}`))}answerCalls(t,r,n){let{turn:s,signal:o,route:a}=t,i=this.runtime.journal.state(m,this.threadId).threadRecord;if(i===null)throw new U(this.threadId);return Ut({runtime:this.runtime,threadId:this.threadId,agentName:this.agentName,environment:i.environment,route:a,turn:s,step:r,calls:n,signal:o})}async callModel(t,r){let{turn:n,signal:s,route:o}=t,{journal:a}=this.runtime,i=j("llm"),u=!1,d,l=()=>d?.attempts??0;try{let c=this.runtime.client(o),h={messages:a.state(m,this.threadId).surface.entries.map(_=>_.message),toolChoice:"auto",...ae(this.runtime,{threadId:this.threadId,agentName:this.agentName,route:o,signal:s,llmCallId:i,purpose:"step"})};d=ie(this.runtime,c,"llm/request",{turn:n,step:r,route:o});let f=await d.call(h);for await(let _ of f){if(s.aborted){u=!0;break}this.runtime.chunks.emit({thread_id:this.threadId,llm_call_id:i,turn:n,step:r,chunk:_})}s.aborted&&(u=!0);let{message:p,finish:g,provider_metadata:x}=await f.completed();u||Vr(o.provider,p,x,l());let y=u&&p.tool_calls.length>0?{...p,tool_calls:[]}:p;await a.append("assistant/message",{turn:n,step:r,llm_call_id:i,response:{message:y,finish:u?"other":g,provider_metadata:x},usage:y.usage,interrupted:u,attempts:l()},{threadId:this.threadId}),u&&s.throwIfAborted()}catch(c){if(B(s,c))throw c;let h=R(c,D),f=h?.kind??"other",p=h?.attempts??l(),g=h?.retryAfterMs??null,x=R(c,le)??R(c,ke);x!==void 0&&x.partial!==null&&await a.append("assistant/message",{turn:n,step:r,llm_call_id:i,response:{message:x.partial,finish:"other",provider_metadata:x.providerMetadata},usage:x.partial.usage,interrupted:!0,attempts:p},{threadId:this.threadId});let y=v(c);if(await a.append("assistant/attempt",{turn:n,step:r,llm_call_id:i,error_text:y,failure_kind:f,attempts:p,retry_after_ms:g},{threadId:this.threadId}),f==="overflow"&&!s.aborted){let _=await this.prepare({turn:n,step:r,route:o,trigger:"overflow",queued:[],options:null,signal:s,lease:t.lease});if(this.reportFailedDispatch(_),s.throwIfAborted(),_.outcome.committed.length>0)return}throw await a.append("error",{turn:n,step:r,llm_call_id:i,error_text:y,failure_kind:f},{threadId:this.threadId}),c}}};function Vr(e,t,r,n){let s=new Set,o=new Set;for(let u of t.tool_calls)(s.has(u.call_id)?o:s).add(u.call_id);if(o.size===0)return;let a=A({role:"assistant",content:t.content,reasoning_content:t.reasoning_content,usage:t.usage}),i=new le(e,"invalid",a,r,`'${e}' asked for tool calls that share an id: ${[...o].join(", ")}`);throw new D(e,"invalid",n,null,{cause:i})}export{te as a,Zt as b,fe as c,rt as d,re as e,G as f,en as g,bt as h,or as i,ne as j,$t as k,tr as l,nn as m,sn as n,m as o,K as p,Jt as q,Pe as r,U as s,De as t,Be as u,Ue as v,$ as w,Fe as x,Le as y,Je as z,We as A,F as B,Z as C,He as D,E,is as F,j as G,ee as H,L as I,At as J,me as K,N as L,we as M,oe as N,pr as O,fr as P,hr as Q,mr as R,ps as S,ms as T,ws as U,gs as V,xs as W,ys as X,Dr as Y,bs as Z,Fr as _,Is as $,Ts as aa,Lr as ba,$s as ca,Wn as da,Hn as ea,Vn as fa,Tr as ga,xe as ha,On as ia,Ct as ja,I as ka,Mr as la,_e as ma};
|
package/dist/kit/claim.d.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import type { Context } from '@leuduan/cordis';
|
|
2
|
-
/**
|
|
3
|
-
* Claims `key`, a thread by its id or by its activation's scope, for the calling plugin within
|
|
4
|
-
* `kind`, for as long as the calling plugin's fiber lives: for a behaviour a thread runs at most
|
|
5
|
-
* once, such as an `AGENTS.md` briefing. `holder` is
|
|
6
|
-
* how a later refusal names this claim. Throws `refusal(holder)` with the holder of a live claim of
|
|
7
|
-
* the same kind on the same key, so the plugin that claimed later fails, and with it the
|
|
8
|
-
* activation, rather than running beside the first. Claims of different kinds never meet.
|
|
9
|
-
*
|
|
10
|
-
* Synchronous: the check and the claim are one step, and the claim is an effect of the caller's
|
|
11
|
-
* fiber, so a release, an unload or a failed setup frees the thread for the next activation.
|
|
12
|
-
*/
|
|
13
|
-
export declare function claimThread(ctx: Context, kind: string, key: unknown, holder: string, refusal: (holder: string) => string): void;
|
package/dist/kit/drain.d.ts
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { Context } from '@leuduan/cordis';
|
|
2
|
-
/**
|
|
3
|
-
* Runs `drain` before any owner of `ctx` starts its cleanup, and before the journal's owner does:
|
|
4
|
-
* as an unload guard on every fiber from `ctx` up to the root, and on the fiber that provides the
|
|
5
|
-
* journal. Guards on one fiber run together before its disposers, so every service draining this
|
|
6
|
-
* way is signalled before any of them is awaited, and the journal is still writable for their final
|
|
7
|
-
* rows. `drain` must be idempotent, since several owners can unload, and must not await its own
|
|
8
|
-
* owner's teardown, which waits for the guard.
|
|
9
|
-
*/
|
|
10
|
-
export declare function drainBeforeUnload(ctx: Context, drain: () => Promise<void>): void;
|
package/dist/kit/grants.d.ts
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { type Context } from '@leuduan/cordis';
|
|
2
|
-
import type { AgentSelector } from './scope.js';
|
|
3
|
-
/**
|
|
4
|
-
* Grants `toolName` to the agents `agents` selects, for the life of the calling plugin's fiber, or
|
|
5
|
-
* until the returned disposer runs. The selector is stored as given: registries are live, so
|
|
6
|
-
* a grant to `'global'` or `'all'` is matched against each agent when it asks, agents registered
|
|
7
|
-
* later included.
|
|
8
|
-
*/
|
|
9
|
-
export declare function grantTool(ctx: Context, toolName: string, agents: AgentSelector): () => void | Promise<void>;
|
package/dist/kit/scope.d.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { type Context } from '@leuduan/cordis';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
/**
|
|
4
|
-
* The agents a plugin's `agents` option selects. Required wherever it appears: which agents a
|
|
5
|
-
* composition has is the host's to say, so none of the shipped plugins defaults it. `'global'` is
|
|
6
|
-
* every globally registered agent, those registered later included; `'all'` is every thread's agent,
|
|
7
|
-
* scoped ones included; a list names agents, global or scoped.
|
|
8
|
-
*/
|
|
9
|
-
export declare const AgentSelectorSchema: z.ZodUnion<readonly [z.ZodArray<z.ZodString>, z.ZodLiteral<"global">, z.ZodLiteral<"all">]>;
|
|
10
|
-
export type AgentSelector = readonly string[] | 'global' | 'all';
|
|
11
|
-
/**
|
|
12
|
-
* Whether `selector` selects `agentName`. One meaning wherever a selector appears, whether the plugin
|
|
13
|
-
* equips (a grant, a prompt section, a notice) or restricts (a mode, a stop check). `'global'` never
|
|
14
|
-
* selects a scoped agent (`isScopedAgentName`), so a role child gets only what names it or says
|
|
15
|
-
* `'all'`; a gate that must cover role children says `'all'`.
|
|
16
|
-
*
|
|
17
|
-
* Registries are live, so a selector is a predicate evaluated when the plugin acts — granting,
|
|
18
|
-
* rendering a prompt section, authorizing a call — rather than a list resolved once at mount.
|
|
19
|
-
*/
|
|
20
|
-
export declare const selects: (selector: AgentSelector, agentName: string) => boolean;
|
|
21
|
-
/**
|
|
22
|
-
* Whether `name` is an agent name for a scoped registration: one containing a dot, such as
|
|
23
|
-
* `codex.explore`. Global agent names never contain one, so the two kinds cannot collide, and the
|
|
24
|
-
* agents registry refuses a registration of the wrong kind.
|
|
25
|
-
*/
|
|
26
|
-
export declare const isScopedAgentName: (name: string) => boolean;
|
|
27
|
-
/**
|
|
28
|
-
* Refuses a plugin mounted in a thread's scope when `name`, the thing mounted, serves every thread
|
|
29
|
-
* from the application root. The predicate is `scopeOf(ctx) === undefined`: an untagged application
|
|
30
|
-
* context passes, so this is not a root-identity check.
|
|
31
|
-
*/
|
|
32
|
-
export declare function requireUnscoped(ctx: Context, name: string): void;
|
package/dist/kit/service.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import type { Context } from '@leuduan/cordis';
|
|
2
|
-
/**
|
|
3
|
-
* The root service `name`, or a refusal naming `user`, the plugin or tool that depends on it, when
|
|
4
|
-
* it is not mounted. Checked where a plugin mounts, so a composition without the service fails
|
|
5
|
-
* there rather than leaving the plugin silently inactive, and looked up again at each call.
|
|
6
|
-
*/
|
|
7
|
-
export declare function requireService<K extends string & keyof Context>(ctx: Context, name: K, user: string): NonNullable<Context[K]>;
|
package/dist/kit/strategy.d.ts
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { Context } from '@leuduan/cordis';
|
|
2
|
-
import type { SurfaceStrategy } from '../loop/index.js';
|
|
3
|
-
/**
|
|
4
|
-
* Makes `strategy` the one that prepares `threadId`'s surface, for as long as the calling plugin's
|
|
5
|
-
* fiber lives. A thread runs one strategy: a second, from another mount or installation, throws, so
|
|
6
|
-
* the plugin that came later fails, and with it the activation, rather than running beside the first.
|
|
7
|
-
*/
|
|
8
|
-
export declare function provideStrategy(ctx: Context, threadId: string, strategy: SurfaceStrategy): void;
|
|
9
|
-
/** The strategy that prepares `threadId`'s surface, if any. */
|
|
10
|
-
export declare function strategyOf(ctx: Context, threadId: string): SurfaceStrategy | undefined;
|
package/dist/kit/tool.d.ts
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { type Context } from '@leuduan/cordis';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import type { ParsedToolCall, ToolCall } from '../llm/index.js';
|
|
4
|
-
import type { InvocationContext, Tool, ToolExecutionMode, WaitRequest } from '../loop/index.js';
|
|
5
|
-
import type { InterruptionPolicy, ToolResult, ToolResultPayloadInput } from '../models/index.js';
|
|
6
|
-
import type { JsonValue } from '../util/json.js';
|
|
7
|
-
import type { AgentSelector } from './scope.js';
|
|
8
|
-
/**
|
|
9
|
-
* Parameters described elsewhere, as JSON schema: advertised as given and handed to `execute`
|
|
10
|
-
* unvalidated, for a tool whose real validator is someone else's, such as an MCP server.
|
|
11
|
-
*/
|
|
12
|
-
export type JsonSchemaParameters = {
|
|
13
|
-
readonly jsonSchema: Record<string, JsonValue>;
|
|
14
|
-
};
|
|
15
|
-
type ParametersOf<P> = P extends z.ZodType ? z.output<P> : Record<string, unknown>;
|
|
16
|
-
/** What `execute` returns: a result with `is_error`, `notes` and `metadata` optional, or a wait (`waitFor`). */
|
|
17
|
-
export type ToolReply = ToolResultPayloadInput | WaitRequest;
|
|
18
|
-
/** One tool, as {@link defineTool} takes it. */
|
|
19
|
-
export type ToolDefinition<P extends z.ZodType | JsonSchemaParameters> = {
|
|
20
|
-
/** The name it is registered under, and advertised to the model by. */
|
|
21
|
-
readonly name: string;
|
|
22
|
-
/** One paragraph advertised to the model. */
|
|
23
|
-
readonly description: string;
|
|
24
|
-
/** A zod schema the arguments are validated against and advertised from, or JSON schema. */
|
|
25
|
-
readonly parameters: P;
|
|
26
|
-
/**
|
|
27
|
-
* What a re-dispatch may do with a call that may have begun when its turn was interrupted; see
|
|
28
|
-
* `Tool.onInterrupted`. Every tool says which; there is no default.
|
|
29
|
-
*/
|
|
30
|
-
readonly onInterrupted: InterruptionPolicy;
|
|
31
|
-
/** Whether a call may overlap its batch's others; see `Tool.executionMode`. No default either. */
|
|
32
|
-
readonly executionMode: ToolExecutionMode;
|
|
33
|
-
/** Runs one call. A throw becomes an `is_error` result: a tool never fails a turn. */
|
|
34
|
-
execute(parameters: ParametersOf<P>, context: InvocationContext, call: ParsedToolCall): Promise<ToolReply>;
|
|
35
|
-
};
|
|
36
|
-
/**
|
|
37
|
-
* Defines a tool: the one way to write one. Arguments are validated against `parameters` when it is
|
|
38
|
-
* a zod schema, and a validation failure or a throw from `execute` becomes an `is_error` result, so
|
|
39
|
-
* a tool can never crash a turn; the result is timed. A tool that needs configuration closes over it.
|
|
40
|
-
*
|
|
41
|
-
* ```ts
|
|
42
|
-
* const echo = defineTool({
|
|
43
|
-
* name: 'echo',
|
|
44
|
-
* description: 'Repeat the text.',
|
|
45
|
-
* parameters: z.strictObject({ text: z.string() }),
|
|
46
|
-
* onInterrupted: 'rerun',
|
|
47
|
-
* executionMode: 'parallel',
|
|
48
|
-
* execute: async ({ text }) => ({ output: text }),
|
|
49
|
-
* })
|
|
50
|
-
* ```
|
|
51
|
-
*/
|
|
52
|
-
export declare function defineTool<P extends z.ZodType | JsonSchemaParameters>(definition: ToolDefinition<P>): Tool;
|
|
53
|
-
/**
|
|
54
|
-
* Offers `tool` in the calling plugin's scope for the life of its fiber, and grants it to the agents
|
|
55
|
-
* `agents` selects when given; without them it is registered for a grant elsewhere, a preset's say.
|
|
56
|
-
* Returns the disposer.
|
|
57
|
-
*/
|
|
58
|
-
export declare function provideTool(ctx: Context, tool: Tool, options?: {
|
|
59
|
-
readonly agents?: AgentSelector;
|
|
60
|
-
}): () => void | Promise<void>;
|
|
61
|
-
/**
|
|
62
|
-
* {@link provideTool} for each of `tools`, then a prompt instruction under `tag` for every agent that
|
|
63
|
-
* is granted one of them: the `guidance` of each granted tool, in tool order, and nothing when none
|
|
64
|
-
* is granted or none has any.
|
|
65
|
-
*/
|
|
66
|
-
export declare function provideTools(ctx: Context, tools: readonly Tool[], options: {
|
|
67
|
-
readonly tag: string;
|
|
68
|
-
readonly guidance: ReadonlyMap<string, string>;
|
|
69
|
-
}): void;
|
|
70
|
-
/** A tool's result for `call`, its defaults applied and its duration recorded. */
|
|
71
|
-
export declare function toToolResult(call: ToolCall, reply: ToolResultPayloadInput, startedAt: number): ToolResult;
|
|
72
|
-
export { errorResult } from '../loop/index.js';
|