dal-code 1.0.47 → 1.0.48
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/CHANGELOG.md +4 -0
- package/dist/bun/register-bedrock.js +1 -0
- package/dist/cli/experimental/auth.js +1 -0
- package/dist/cli/experimental/cli.js +1 -0
- package/dist/cli/experimental/command-options.js +1 -0
- package/dist/cli/experimental/command.js +1 -0
- package/dist/cli/experimental/commands/client.js +1 -0
- package/dist/cli/experimental/commands/pi.js +1 -0
- package/dist/cli/experimental/commands/server.js +1 -0
- package/dist/cli/experimental/transport-address.js +1 -0
- package/dist/client/index.js +1 -0
- package/dist/client/remote-session.js +1 -0
- package/dist/client/transcript.js +1 -0
- package/dist/core/extensions/engine-specifiers.js +1 -1
- package/dist/core/extensions/virtual-modules.js +1 -1
- package/dist/core/provider-attribution.js +1 -0
- package/dist/modes/interactive/components/daxnuts.js +1 -0
- package/dist/modes/interactive/theme/theme-json.js +12 -0
- package/dist/modes/interactive/theme/theme-schema.json +356 -0
- package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
- package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-sync/package.json +5 -4
- package/dist/node_modules/@dalcode/dal-sync/src/client.d.ts +12 -0
- package/dist/node_modules/@dalcode/dal-sync/src/core.d.ts +68 -0
- package/dist/node_modules/@dalcode/dal-sync/src/core.js +2 -2
- package/dist/node_modules/@dalcode/dal-sync/src/host.d.ts +25 -0
- package/dist/node_modules/@dalcode/dal-sync/src/host.js +2 -0
- package/dist/node_modules/@dalcode/dal-sync/src/index.js +3 -4
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +37 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +104 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/utils.js +16 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/config.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/context.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +10 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/events.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/assistant.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/effect-gate.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/tools.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/hooks.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +17 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bash.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bounded.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/chord.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/context.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/harness.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/hooks.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/jsonl.js +4 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/collapse.js +3 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/entries.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/frames.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/generation.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/job.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/plugin.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/post-tools.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/task-api.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/tool.js +3 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/membrane.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/memory.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/scheduler.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/session.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/system.js +8 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/view.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/prompt-templates.js +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/result.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/boundary.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/checkpoint.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/deferred.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/generation.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/reconcile.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/recovery.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/response.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/retry.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/structural.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/terminal.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tool-placement.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tools.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/harness.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/lane.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/progress.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/reducer.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/restore.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/transcript.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/commit.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork-policy.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/in-memory-storage-state.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/fork.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/io.js +3 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/legacy-v3.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.js +8 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-storage.js +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/mutation-line.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo-utils.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/datasets.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/session-repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/session-repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/gating-storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/instrumented-storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/storage-decorator.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/types.js +0 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/values.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js +10 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/system-prompt.js +2 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/telemetry.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/bash.js +12 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit-diff.js +16 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/file-mutation-queue.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/image.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/path-utils.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.js +14 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js +0 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/adaptive-publisher.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/output-capture.js +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/truncate.js +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/usage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/node.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/index.js +0 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/oauth-page.js +74 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/images-models.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.models.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-images.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/deferred-tools.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/dist/sdk/sync.d.ts +2 -0
- package/dist/sdk/sync.js +1 -0
- package/dist/server/create-harness.js +1 -0
- package/dist/utils/clipboard-native.js +1 -0
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +5 -1
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)})
|
|
3
|
-
`)},"
|
|
4
|
-
`)},"status");t.registerCommand("sync",{description:r("\u540C\u6B65\u4E2A\u4EBA\u6280\u80FD\u548C\u4E2A\u4EBA\u7ECF\u9A8C\u5230 DeepAILab \u8D26\u6237\uFF08/sync on | off | now | status\uFF09"),getArgumentCompletions:o(s=>{const u=["on","off","now","status"].filter(n=>n.startsWith(s.trim()));return u.length?u.map(n=>({value:n,label:n})):null},"getArgumentCompletions"),handler:o(async(s,u)=>{const[n="status",A]=s.trim().toLowerCase().split(/\s+/);if(n==="status"||n===""){i(u,I());return}if(n==="on"){m(e,!0),i(u,r("\u5DF2\u5F00\u542F\u3002\u4F1A\u540C\u6B65\uFF1A\u4F60\u7684\u4E2A\u4EBA\u6280\u80FD\uFF08~/.dal/agent/skills\uFF09\u548C\u9002\u7528\u4E8E\u6240\u6709\u9879\u76EE\u7684\u4E2A\u4EBA\u7ECF\u9A8C\u3002\u4E0D\u4F1A\u540C\u6B65\uFF1A\u9879\u76EE\u7ECF\u9A8C\u3001\u5BF9\u8BDD\u3001\u4EE3\u7801\u3001\u8BBE\u7F6E\u548C\u4EFB\u4F55\u51ED\u636E\u3002\u4E0A\u4F20\u524D\u4F1A\u53BB\u6389\u5BC6\u94A5\u3001\u5BC6\u7801\u548C\u4E3B\u76EE\u5F55\u8DEF\u5F84\u3002"));try{i(u,p(await B(u)))}catch(E){i(u,d(E),"warning")}return}if(n==="now"){if(!C(e)){i(u,r("\u540C\u6B65\u672A\u5F00\u542F\uFF0C\u5148\u8FD0\u884C /sync on\u3002"),"warning");return}try{i(u,p(await B(u)))}catch(E){i(u,d(E),"warning")}return}if(n==="off"){if(m(e,!1),!(A==="--delete-cloud"||u.hasUI&&await u.ui.confirm(r("\u5173\u95ED\u540C\u6B65"),r("\u540C\u65F6\u5220\u9664\u4E91\u7AEF\u7684\u526F\u672C\u5417\uFF1F\u7535\u8111\u4E0A\u7684\u6280\u80FD\u548C\u7ECF\u9A8C\u4E0D\u53D7\u5F71\u54CD\u3002")))){i(u,c(r("\u5DF2\u5173\u95ED\uFF0C\u4E0D\u518D\u4E0A\u4F20\u3002\u4E91\u7AEF\u526F\u672C\u4FDD\u7559\uFF0C\u53EF\u5728 {url} \u5220\u9664\u3002"),{url:v}));return}try{const E=await w(u).removeAll();K(e),i(u,c(r("\u5DF2\u5173\u95ED\uFF0C\u5E76\u5220\u9664\u4E86\u4E91\u7AEF\u7684 {n} \u6761\u3002"),{n:E}))}catch(E){i(u,`${r("\u5DF2\u5173\u95ED\uFF0C\u4F46\u4E91\u7AEF\u526F\u672C\u6CA1\u6709\u5220\u9664\uFF1A")}${d(E)}`,"warning")}return}i(u,r("\u7528\u6CD5\uFF1A/sync on | off | now | status"),"warning")},"handler")})}l(R,"W"),o(R,"default");export{D as SETTINGS_KEY,R as default,m as saveSyncEnabled,C as syncEnabled};
|
|
1
|
+
var b=Object.defineProperty;var l=(o,n)=>b(o,"name",{value:n,configurable:!0});var S=Object.defineProperty,a=l((o,n)=>S(o,"name",{value:n,configurable:!0}),"i");import{hostname as T}from"node:os";import{t as s}from"@dalcode/dal-pi-kit";import{deepAILabApiBase as R,resolveDeepAILabAccessToken as B}from"@dalcode/deepailab";import{decodeJwtPayload as I}from"@dalcode/deepailab/oidc";import{getAgentDir as L,VERSION as O}from"@earendil-works/pi-coding-agent";import{readState as _,SyncHttpError as j}from"./core.js";import{SYNC_CONSOLE_URL as y,syncErrorText as d,removeCloudCopies as k,syncOnce as N,saveSyncEnabled as g,syncEnabled as C,syncRemote as P}from"./host.js";import{SETTINGS_KEY as U,saveSyncEnabled as $,syncEnabled as Y}from"./host.js";const x=2e4,G="DALCODE_GATEWAY_URL";function r(o,n){return o.replace(/\{(\w+)\}/g,(c,E)=>E in n?String(n[E]):c)}l(r,"u"),a(r,"fill");function f(o){const n=[r(s("\u4E0A\u4F20 {n}"),{n:o.uploaded}),r(s("\u4E0B\u8F7D {n}"),{n:o.downloaded})];return o.deletedRemote&&n.push(r(s("\u4E91\u7AEF\u5220\u9664 {n}"),{n:o.deletedRemote})),o.conflicts&&n.push(r(s("\u51B2\u7A81 {n}\uFF08\u6309\u8F83\u65B0\u7684\u4FEE\u6539\u5904\u7406\uFF09"),{n:o.conflicts})),o.refused.length&&n.push(r(s("\u672A\u4E0A\u4F20 {n}\uFF08\u8FC7\u5927\u6216\u7591\u4F3C\u542B\u5BC6\u94A5\uFF09"),{n:o.refused.length})),n.join(s("\uFF0C"))}l(f,"C"),a(f,"reportText");function w(o){const n=L();let c=Promise.resolve(),E;const F=a((e,u,t="info")=>{e.hasUI?e.ui.notify(u,t):process.stdout.write(`${u}
|
|
2
|
+
`)},"say"),D=a(e=>P({apiBase:R(),token:a(()=>B(e.modelRegistry),"token"),device:`${T()} (dal ${O})`}),"remoteFor"),h=a(async e=>{const u=await B(e.modelRegistry),t=u?I(u)?.sub:void 0;return typeof t=="string"&&t?t:void 0},"accountOf"),A=a(async e=>{const u=await h(e);if(!u)throw new j(401);return N(n,u,D(e))},"syncOnce"),p=a(e=>{if(!C(n)||!e.hasUI||process.env[G])return;const u=a(()=>A(e),"work");c=c.then(u,u).catch(()=>{})},"background");o.on("session_start",(e,u)=>{u.mode==="print"||u.mode==="json"||p(u)}),o.on("agent_end",(e,u)=>{u.mode==="print"||u.mode==="json"||!C(n)||(E&&clearTimeout(E),E=setTimeout(()=>p(u),x),E.unref?.())}),o.on("session_shutdown",async()=>{E&&clearTimeout(E),await Promise.race([c,new Promise(e=>setTimeout(e,5e3).unref?.())])});const v=a(()=>{const e=C(n),u=_(n),t=[e?s("\u6280\u80FD\u4E0E\u7ECF\u9A8C\u540C\u6B65\uFF1A\u5DF2\u5F00\u542F\u3002"):s("\u6280\u80FD\u4E0E\u7ECF\u9A8C\u540C\u6B65\uFF1A\u672A\u5F00\u542F\uFF08/sync on \u5F00\u542F\uFF09\u3002")];if(u){const m=Object.values(u.items).filter(i=>!i.remoteDeleted&&i.version>0).length;t.push(r(s("\u5DF2\u540C\u6B65 {n} \u6761\u3002"),{n:m})),u.lastRun&&t.push(r(s("\u4E0A\u6B21\u540C\u6B65\uFF1A{time}"),{time:new Date(u.lastRun).toLocaleString()})),u.lastError&&t.push(u.lastError)}return t.push(r(s("\u5728 {url} \u67E5\u770B\u3001\u5220\u9664\u548C\u5BFC\u51FA\u3002"),{url:y})),t.join(`
|
|
3
|
+
`)},"status");o.registerCommand("sync",{description:s("\u540C\u6B65\u4E2A\u4EBA\u6280\u80FD\u548C\u4E2A\u4EBA\u7ECF\u9A8C\u5230 DeepAILab \u8D26\u6237\uFF08/sync on | off | now | status\uFF09"),getArgumentCompletions:a(e=>{const u=["on","off","now","status"].filter(t=>t.startsWith(e.trim()));return u.length?u.map(t=>({value:t,label:t})):null},"getArgumentCompletions"),handler:a(async(e,u)=>{const[t="status",m]=e.trim().toLowerCase().split(/\s+/);if(t==="status"||t===""){F(u,v());return}if(t==="on"){g(n,!0),F(u,s("\u5DF2\u5F00\u542F\u3002\u4F1A\u540C\u6B65\uFF1A\u4F60\u7684\u4E2A\u4EBA\u6280\u80FD\uFF08~/.dal/agent/skills\uFF09\u548C\u9002\u7528\u4E8E\u6240\u6709\u9879\u76EE\u7684\u4E2A\u4EBA\u7ECF\u9A8C\u3002\u4E0D\u4F1A\u540C\u6B65\uFF1A\u9879\u76EE\u7ECF\u9A8C\u3001\u5BF9\u8BDD\u3001\u4EE3\u7801\u3001\u8BBE\u7F6E\u548C\u4EFB\u4F55\u51ED\u636E\u3002\u4E0A\u4F20\u524D\u4F1A\u53BB\u6389\u5BC6\u94A5\u3001\u5BC6\u7801\u548C\u4E3B\u76EE\u5F55\u8DEF\u5F84\u3002"));try{F(u,f(await A(u)))}catch(i){F(u,d(i),"warning")}return}if(t==="now"){if(!C(n)){F(u,s("\u540C\u6B65\u672A\u5F00\u542F\uFF0C\u5148\u8FD0\u884C /sync on\u3002"),"warning");return}try{F(u,f(await A(u)))}catch(i){F(u,d(i),"warning")}return}if(t==="off"){if(g(n,!1),!(m==="--delete-cloud"||u.hasUI&&await u.ui.confirm(s("\u5173\u95ED\u540C\u6B65"),s("\u540C\u65F6\u5220\u9664\u4E91\u7AEF\u7684\u526F\u672C\u5417\uFF1F\u7535\u8111\u4E0A\u7684\u6280\u80FD\u548C\u7ECF\u9A8C\u4E0D\u53D7\u5F71\u54CD\u3002")))){F(u,r(s("\u5DF2\u5173\u95ED\uFF0C\u4E0D\u518D\u4E0A\u4F20\u3002\u4E91\u7AEF\u526F\u672C\u4FDD\u7559\uFF0C\u53EF\u5728 {url} \u5220\u9664\u3002"),{url:y}));return}try{const i=await k(n,D(u));F(u,r(s("\u5DF2\u5173\u95ED\uFF0C\u5E76\u5220\u9664\u4E86\u4E91\u7AEF\u7684 {n} \u6761\u3002"),{n:i}))}catch(i){F(u,`${s("\u5DF2\u5173\u95ED\uFF0C\u4F46\u4E91\u7AEF\u526F\u672C\u6CA1\u6709\u5220\u9664\uFF1A")}${d(i)}`,"warning")}return}F(u,s("\u7528\u6CD5\uFF1A/sync on | off | now | status"),"warning")},"handler")})}l(w,"H"),a(w,"default");export{U as SETTINGS_KEY,w as default,$ as saveSyncEnabled,Y as syncEnabled};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-telemetry",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.48",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -25,9 +25,9 @@
|
|
|
25
25
|
]
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@dalcode/dal-learn": "1.0.
|
|
29
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
30
|
-
"@dalcode/deepailab": "1.0.
|
|
28
|
+
"@dalcode/dal-learn": "1.0.48",
|
|
29
|
+
"@dalcode/dal-pi-kit": "1.0.48",
|
|
30
|
+
"@dalcode/deepailab": "1.0.48"
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|
|
33
33
|
"@earendil-works/pi-coding-agent": "^1.0.9"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-terminal",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.48",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Host terminal context: a terminal_read tool and @terminal mentions, registered only when the embedding host advertises the terminal capability.",
|
|
6
6
|
"type": "module",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
]
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
22
|
+
"@dalcode/dal-pi-kit": "1.0.48",
|
|
23
23
|
"typebox": "1.3.7"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-tool-catalog",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.48",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
]
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
22
|
+
"@dalcode/dal-pi-kit": "1.0.48",
|
|
23
23
|
"typebox": "1.3.7"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-usage",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.48",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "/usage: tokens and cost across all sessions, by day, model and project, with sub-agent spend counted once. Adapted from @tmustier/pi-usage-extension 0.9.5 (MIT).",
|
|
6
6
|
"license": "MIT",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
]
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
23
|
+
"@dalcode/dal-pi-kit": "1.0.48"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
26
|
"@earendil-works/pi-coding-agent": "^1.0.9"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-web",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.48",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
]
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
28
|
-
"@dalcode/deepailab": "1.0.
|
|
27
|
+
"@dalcode/dal-pi-kit": "1.0.48",
|
|
28
|
+
"@dalcode/deepailab": "1.0.48",
|
|
29
29
|
"typebox": "1.3.27",
|
|
30
30
|
"unpdf": "1.8.1"
|
|
31
31
|
},
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-workflow",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.48",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
]
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
20
|
+
"@dalcode/dal-pi-kit": "1.0.48",
|
|
21
21
|
"typebox": "1.3.27"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/deepailab",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.48",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
]
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
24
|
-
"@earendil-works/pi-ai": "1.0.
|
|
23
|
+
"@dalcode/dal-pi-kit": "1.0.48",
|
|
24
|
+
"@earendil-works/pi-ai": "1.0.48"
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
27
|
"@earendil-works/pi-coding-agent": "^1.0.9"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Closed as r,HarnessClosed as s,HarnessFault as i,InvalidLane as l,InvalidMessage as m,InvalidNavigation as p,LaneBusy as c,NoActiveOperation as g,NoActiveRun as d,NothingToCompact as v,NothingToResume as N,OperationMismatch as k,UnknownSkill as u,UnknownTarget as A,UnknownTemplate as H}from"./result.js";import{SliceNotImplemented as T}from"./runtime/types.js";import{createAgentHarness as e}from"./runtime/harness.js";const o={create:e};export{o as AgentHarness,r as Closed,s as HarnessClosed,i as HarnessFault,l as InvalidLane,m as InvalidMessage,p as InvalidNavigation,c as LaneBusy,g as NoActiveOperation,d as NoActiveRun,v as NothingToCompact,N as NothingToResume,k as OperationMismatch,T as SliceNotImplemented,u as UnknownSkill,A as UnknownTarget,H as UnknownTemplate};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
var S=Object.defineProperty;var p=(e,a)=>S(e,"name",{value:a,configurable:!0});import{contentText as F}from"@earendil-works/pi-ai";import{convertToLlm as b,createBranchSummaryMessage as R,createCompactionSummaryMessage as k}from"../messages.js";import{BranchSummaryError as w,err as x,ok as A}from"../types.js";import{completeSimpleWithRetries as T,createSummaryRequestOptions as B,estimateTokens as E,SUMMARIZATION_SYSTEM_PROMPT as P}from"./compaction.js";import{computeFileLists as v,createFileOps as I,extractFileOpsFromMessage as O,formatFileOperations as _,serializeConversation as C}from"./utils.js";async function K(e,a,i,c,r){if(!i)return{entries:[],commonAncestorId:null};const t=new Set((await e.findEntries({start:i},r)).map(n=>n.id)),s=await e.findEntries({start:c},r);let o=null;for(const n of s)if(t.has(n.id)){o=n.id;break}const m=[];let u=i;for(;u&&u!==o;){const n=await a.getEntry(u,r);if(!n)throw new Error(`Corrupt session: entry ${u} not found`);m.push(n),u=n.parentId}return m.reverse(),{entries:m,commonAncestorId:o}}p(K,"collectEntriesForBranchSummary");function W(e){switch(e.type){case"message":return e.message.role==="toolResult"?void 0:e.message;case"branch_summary":return R(e.summary,e.fromId,e.timestamp);case"compaction":return k(e.summary,e.tokensBefore,e.timestamp);case"custom":return}}p(W,"getMessageFromEntry");function N(e,a=0){const i=[],c=I();let r=0;for(const t of e)if(!(t.type!=="branch_summary"||typeof t.details!="object"||t.details===null||Array.isArray(t.details))){if(Array.isArray(t.details.readFiles))for(const s of t.details.readFiles)typeof s=="string"&&c.read.add(s);if(Array.isArray(t.details.modifiedFiles))for(const s of t.details.modifiedFiles)typeof s=="string"&&c.edited.add(s)}for(let t=e.length-1;t>=0;t--){const s=e[t],o=W(s);if(!o)continue;O(o,c);const m=E(o);if(a>0&&r+m>a){(s.type==="compaction"||s.type==="branch_summary")&&r<a*.9&&(i.unshift(o),r+=m);break}i.unshift(o),r+=m}return{messages:i,fileOps:c,totalTokens:r}}p(N,"prepareBranchEntries");const $=`The user explored a different conversation branch before returning here.
|
|
2
|
+
Summary of that exploration:
|
|
3
|
+
|
|
4
|
+
`,M=`Create a structured summary of this conversation branch for context when returning later.
|
|
5
|
+
|
|
6
|
+
Use this EXACT format:
|
|
7
|
+
|
|
8
|
+
## Goal
|
|
9
|
+
[What was the user trying to accomplish in this branch?]
|
|
10
|
+
|
|
11
|
+
## Constraints & Preferences
|
|
12
|
+
- [Any constraints, preferences, or requirements mentioned]
|
|
13
|
+
- [Or "(none)" if none were mentioned]
|
|
14
|
+
|
|
15
|
+
## Progress
|
|
16
|
+
### Done
|
|
17
|
+
- [x] [Completed tasks/changes]
|
|
18
|
+
|
|
19
|
+
### In Progress
|
|
20
|
+
- [ ] [Work that was started but not finished]
|
|
21
|
+
|
|
22
|
+
### Blocked
|
|
23
|
+
- [Issues preventing progress, if any]
|
|
24
|
+
|
|
25
|
+
## Key Decisions
|
|
26
|
+
- **[Decision]**: [Brief rationale]
|
|
27
|
+
|
|
28
|
+
## Next Steps
|
|
29
|
+
1. [What should happen next to continue this work]
|
|
30
|
+
|
|
31
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`;function j(e,a,i){const{models:c,model:r,customInstructions:t,replaceInstructions:s,reserveTokens:o=16384,retry:m,callbacks:u}=a,n=r.contextWindow||128e3,h=N(e,n-o);return U(h,{customInstructions:t,replaceInstructions:s},(d,f,l)=>T(c,r,d,f,m,u,l),i)}p(j,"generateBranchSummary");async function U(e,a,i,c){const{customInstructions:r,replaceInstructions:t}=a,{messages:s,fileOps:o}=e;if(s.length===0)return A({summary:"No content to summarize",readFiles:[],modifiedFiles:[]});const m=b(s),u=C(m);let n;t&&r?n=r:r?n=`${M}
|
|
32
|
+
|
|
33
|
+
Additional focus: ${r}`:n=M;const d=[{role:"user",content:[{type:"text",text:`<conversation>
|
|
34
|
+
${u}
|
|
35
|
+
</conversation>
|
|
36
|
+
|
|
37
|
+
${n}`}],timestamp:Date.now()}],f=await i({systemPrompt:P,messages:d},B({maxTokens:2048},c),c);if(f.stopReason==="aborted")return x(new w("aborted",f.errorMessage||"Branch summary aborted"));if(f.stopReason==="error")return x(new w("summarization_failed",`Branch summary failed: ${f.errorMessage||"Unknown error"}`));let l=F(f.content);l=$+l;const{readFiles:y,modifiedFiles:g}=v(o);return l+=_(y,g),A({summary:l||"No summary generated",usage:f.usage,readFiles:y,modifiedFiles:g})}p(U,"generateBranchSummaryWithRequest");export{K as collectEntriesForBranchSummary,j as generateBranchSummary,U as generateBranchSummaryWithRequest,N as prepareBranchEntries};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
var K=Object.defineProperty;var m=(e,t)=>K(e,"name",{value:t,configurable:!0});import{contentText as E,retryAssistantCall as B,uuidv7 as L}from"@earendil-works/pi-ai";import{getTelemetryContext as W}from"../context.js";import{convertToLlm as O,createBranchSummaryMessage as q,createCompactionSummaryMessage as Y}from"../messages.js";import{buildContextEntries as V,sessionEntryToContextMessages as X}from"../session/context.js";import{CompactionError as b,err as x,ok as k}from"../types.js";import{addUsage as G}from"../utils/usage.js";import{computeFileLists as Z,createFileOps as J,extractFileOpsFromMessage as U,formatFileOperations as j,serializeConversation as F}from"./utils.js";function H(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}m(H,"safeJsonStringify");function Q(e,t,r){const s=J();if(r>=0){const n=t[r];if(typeof n.details=="object"&&n.details!==null&&!Array.isArray(n.details)){if(Array.isArray(n.details.readFiles))for(const o of n.details.readFiles)typeof o=="string"&&s.read.add(o);if(Array.isArray(n.details.modifiedFiles))for(const o of n.details.modifiedFiles)typeof o=="string"&&s.edited.add(o)}}for(const n of e)U(n,s);return s}m(Q,"extractFileOperations");function ee(e){if(e.type==="message")return e.message;if(e.type==="branch_summary")return q(e.summary,e.fromId,e.timestamp);if(e.type==="compaction")return Y(e.summary,e.tokensBefore,e.timestamp)}m(ee,"getMessageFromEntry");function P(e){if(e.type!=="compaction")return ee(e)}m(P,"getMessageFromEntryForCompaction");function w(e,t){return{...e,signal:t.abortSignal,telemetryContext:W(t),cacheRetention:"none",sessionId:e.sessionId??L()}}m(w,"createSummaryRequestOptions");async function N(e,t,r,s,n,o,c){const i=w(s,c);return B(()=>e.completeSimple(t,r,i),n,i.signal,o)}m(N,"completeSimpleWithRetries");const Se={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4};function _(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}m(_,"calculateContextTokens");function D(e){if(e.role==="assistant"&&"usage"in e){const t=e;if(t.stopReason!=="aborted"&&t.stopReason!=="error"&&t.usage&&_(t.usage)>0)return t.usage}}m(D,"getAssistantUsage");function Ie(e){for(let t=e.length-1;t>=0;t--){const r=e[t];if(r.type==="message"){const s=D(r.message);if(s)return s}}}m(Ie,"getLastAssistantUsage");function te(e){for(let t=e.length-1;t>=0;t--){const r=D(e[t]);if(r)return{usage:r,index:t}}}m(te,"getLastAssistantUsageInfo");function ne(e){const t=te(e);if(!t){let n=0;for(const o of e)n+=C(o);return{tokens:n,usageTokens:0,trailingTokens:n,lastUsageIndex:null}}const r=_(t.usage);let s=0;for(let n=t.index+1;n<e.length;n++)s+=C(e[n]);return{tokens:r+s,usageTokens:r,trailingTokens:s,lastUsageIndex:t.index}}m(ne,"estimateContextTokens");function be(e,t,r){return r.enabled?e>t-r.reserveTokens:!1}m(be,"shouldCompact");const se=4800;function z(e){if(typeof e=="string")return e.length;let t=0;for(const r of e)r.type==="text"&&r.text?t+=r.text.length:r.type==="image"&&(t+=se);return t}m(z,"estimateTextAndImageContentChars");function C(e){let t=0;switch(e.role){case"user":return t=z(e.content),Math.ceil(t/4);case"assistant":{const r=e;for(const s of r.content)s.type==="text"?t+=s.text.length:s.type==="thinking"?t+=s.thinking.length:s.type==="toolCall"&&(t+=s.name.length+H(s.arguments).length);return Math.ceil(t/4)}case"custom":case"toolResult":return t=z(e.content),Math.ceil(t/4);case"bashExecution":return t=e.command.length+e.output.length,Math.ceil(t/4);case"branchSummary":case"compactionSummary":return t=e.summary.length,Math.ceil(t/4)}return 0}m(C,"estimateTokens");function re(e,t,r){const s=[];for(let n=t;n<r;n++){const o=e[n];switch(o.type){case"message":{switch(o.message.role){case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":case"user":case"assistant":s.push(n);break;case"toolResult":break}break}case"compaction":case"branch_summary":case"custom":break}o.type==="branch_summary"&&s.push(n)}return s}m(re,"findValidCutPoints");function oe(e,t,r){for(let s=t;s>=r;s--){const n=e[s];if(n.type==="branch_summary")return s;if(n.type==="message"){const o=n.message.role;if(o==="user"||o==="bashExecution")return s}}return-1}m(oe,"findTurnStartIndex");function ae(e,t,r,s){const n=re(e,t,r);if(n.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let o=0,c=n[0];for(let u=r-1;u>=t;u--){const h=e[u];if(h.type!=="message")continue;const p=C(h.message);if(o+=p,o>=s){for(let a=0;a<n.length;a++)if(n[a]>=u){c=n[a];break}break}}for(;c>t;){const u=e[c-1];if(u.type==="compaction"||u.type==="message")break;c--}const i=e[c],l=i.type==="message"&&i.message.role==="user",f=l?-1:oe(e,c,t);return{firstKeptEntryIndex:c,turnStartIndex:f,isSplitTurn:!l&&f!==-1}}m(ae,"findCutPoint");const $=`You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
|
|
2
|
+
|
|
3
|
+
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,ie=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
|
|
4
|
+
|
|
5
|
+
Use this EXACT format:
|
|
6
|
+
|
|
7
|
+
## Goal
|
|
8
|
+
[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
|
|
9
|
+
|
|
10
|
+
## Constraints & Preferences
|
|
11
|
+
- [Any constraints, preferences, or requirements mentioned by user]
|
|
12
|
+
- [Or "(none)" if none were mentioned]
|
|
13
|
+
|
|
14
|
+
## Progress
|
|
15
|
+
### Done
|
|
16
|
+
- [x] [Completed tasks/changes]
|
|
17
|
+
|
|
18
|
+
### In Progress
|
|
19
|
+
- [ ] [Current work]
|
|
20
|
+
|
|
21
|
+
### Blocked
|
|
22
|
+
- [Issues preventing progress, if any]
|
|
23
|
+
|
|
24
|
+
## Key Decisions
|
|
25
|
+
- **[Decision]**: [Brief rationale]
|
|
26
|
+
|
|
27
|
+
## Next Steps
|
|
28
|
+
1. [Ordered list of what should happen next]
|
|
29
|
+
|
|
30
|
+
## Critical Context
|
|
31
|
+
- [Any data, examples, or references needed to continue]
|
|
32
|
+
- [Or "(none)" if not applicable]
|
|
33
|
+
|
|
34
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,ce=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
35
|
+
|
|
36
|
+
Update the existing structured summary with new information. RULES:
|
|
37
|
+
- PRESERVE all existing information from the previous summary
|
|
38
|
+
- ADD new progress, decisions, and context from the new messages
|
|
39
|
+
- UPDATE the Progress section: move items from "In Progress" to "Done" when completed
|
|
40
|
+
- UPDATE "Next Steps" based on what was accomplished
|
|
41
|
+
- PRESERVE exact file paths, function names, and error messages
|
|
42
|
+
- If something is no longer relevant, you may remove it
|
|
43
|
+
|
|
44
|
+
Use this EXACT format:
|
|
45
|
+
|
|
46
|
+
## Goal
|
|
47
|
+
[Preserve existing goals, add new ones if the task expanded]
|
|
48
|
+
|
|
49
|
+
## Constraints & Preferences
|
|
50
|
+
- [Preserve existing, add new ones discovered]
|
|
51
|
+
|
|
52
|
+
## Progress
|
|
53
|
+
### Done
|
|
54
|
+
- [x] [Include previously done items AND newly completed items]
|
|
55
|
+
|
|
56
|
+
### In Progress
|
|
57
|
+
- [ ] [Current work - update based on progress]
|
|
58
|
+
|
|
59
|
+
### Blocked
|
|
60
|
+
- [Current blockers - remove if resolved]
|
|
61
|
+
|
|
62
|
+
## Key Decisions
|
|
63
|
+
- **[Decision]**: [Brief rationale] (preserve all previous, add new)
|
|
64
|
+
|
|
65
|
+
## Next Steps
|
|
66
|
+
1. [Update based on current state]
|
|
67
|
+
|
|
68
|
+
## Critical Context
|
|
69
|
+
- [Preserve important context, add new if needed]
|
|
70
|
+
|
|
71
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`;async function Me(e,t,r,s,n,o,c,i,l,f){const u=await ue(e,t,r,s,n,o,c,i,l,f);return u.ok?k(u.value.text):x(u.error)}m(Me,"generateSummary");function ue(e,t,r,s,n,o,c,i,l,f){return R(e,{model:r,reserveTokens:s,customInstructions:n,previousSummary:o,thinkingLevel:c},(u,h,p)=>N(t,r,u,h,i,l,p),f)}m(ue,"generateSummaryWithUsage");async function R(e,t,r,s){const{model:n,reserveTokens:o,customInstructions:c,previousSummary:i,thinkingLevel:l}=t,f=Math.min(Math.floor(.8*o),n.maxTokens>0?n.maxTokens:Number.POSITIVE_INFINITY);let u=i?ce:ie;c&&(u=`${u}
|
|
72
|
+
|
|
73
|
+
Additional focus: ${c}`);const h=O(e);let a=`<conversation>
|
|
74
|
+
${F(h)}
|
|
75
|
+
</conversation>
|
|
76
|
+
|
|
77
|
+
`;i&&(a+=`<previous-summary>
|
|
78
|
+
${i}
|
|
79
|
+
</previous-summary>
|
|
80
|
+
|
|
81
|
+
`),a+=u;const d=[{role:"user",content:[{type:"text",text:a}],timestamp:Date.now()}],y=n.reasoning&&l&&l!=="off"?{maxTokens:f,reasoning:l}:{maxTokens:f},g=await r({systemPrompt:$,messages:d},w(y,s),s);if(g.stopReason==="aborted")return x(new b("aborted",g.errorMessage||"Summarization aborted"));if(g.stopReason==="error")return x(new b("summarization_failed",`Summarization failed: ${g.errorMessage||"Unknown error"}`));const S=E(g.content);return k({text:S,usage:g.usage})}m(R,"generateSummaryWithRequest");function Pe(e,t){if(e.length===0||e[e.length-1].type==="compaction")return k(void 0);let r=-1;for(let a=e.length-1;a>=0;a--)if(e[a].type==="compaction"){r=a;break}let s,n=e;if(r>=0){const a=e[r];s=a.summary,n=[...a.retainedTail.map((y,g)=>({type:"message",id:`${a.id}:retained:${g}`,parentId:g===0?a.id:`${a.id}:retained:${g-1}`,seq:a.seq,timestamp:y.timestamp,message:y})),...e.slice(r+1)]}const o=n.length,c=ne(V(e).flatMap(X)).tokens,i=ae(n,0,o,t.keepRecentTokens),l=i.isSplitTurn?i.turnStartIndex:i.firstKeptEntryIndex,f=[];for(let a=0;a<l;a++){const d=P(n[a]);d&&f.push(d)}const u=[];if(i.isSplitTurn)for(let a=i.turnStartIndex;a<i.firstKeptEntryIndex;a++){const d=P(n[a]);d&&u.push(d)}const h=[];for(let a=i.firstKeptEntryIndex;a<o;a++){const d=P(n[a]);d&&h.push(d)}const p=Q(f,e,r);if(i.isSplitTurn)for(const a of u)U(a,p);return k({messagesToSummarize:f,turnPrefixMessages:u,retainedTail:h,isSplitTurn:i.isSplitTurn,tokensBefore:c,previousSummary:s,fileOps:p,settings:t})}m(Pe,"prepareCompaction");const me=`This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
|
|
82
|
+
|
|
83
|
+
Summarize the prefix to provide context for the retained suffix:
|
|
84
|
+
|
|
85
|
+
## Original Request
|
|
86
|
+
[What did the user ask for in this turn?]
|
|
87
|
+
|
|
88
|
+
## Early Progress
|
|
89
|
+
- [Key decisions and work done in the prefix]
|
|
90
|
+
|
|
91
|
+
## Context for Suffix
|
|
92
|
+
- [Information needed to understand the retained recent work]
|
|
93
|
+
|
|
94
|
+
Be concise. Focus on what's needed to understand the kept suffix.`;import{serializeConversation as Ae}from"./utils.js";function we(e,t,r,s,n,o,c,i){return le(e,{model:r,customInstructions:s,thinkingLevel:n},(l,f,u)=>N(t,r,l,f,o,c,u),i)}m(we,"compact");async function le(e,t,r,s){const{model:n,customInstructions:o,thinkingLevel:c}=t,{messagesToSummarize:i,turnPrefixMessages:l,retainedTail:f,isSplitTurn:u,tokensBefore:h,previousSummary:p,fileOps:a,settings:d}=e;let y,g;if(u&&l.length>0){let T="No prior history.",M;if(i.length>0){const I=await R(i,{model:n,reserveTokens:d.reserveTokens,customInstructions:o,previousSummary:p,thinkingLevel:c},r,s);if(!I.ok)return x(I.error);T=I.value.text,M=I.value.usage}const v=await fe(l,n,d.reserveTokens,c,r,s);if(!v.ok)return x(v.error);y=`${T}
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
**Turn Context (split turn):**
|
|
99
|
+
|
|
100
|
+
${v.value.text}`,g=M?G(M,v.value.usage):v.value.usage}else{const T=await R(i,{model:n,reserveTokens:d.reserveTokens,customInstructions:o,previousSummary:p,thinkingLevel:c},r,s);if(!T.ok)return x(T.error);y=T.value.text,g=T.value.usage}const{readFiles:S,modifiedFiles:A}=Z(a);return y+=j(S,A),k({summary:y,tokensBefore:h,usage:g,retainedTail:f,details:{readFiles:S,modifiedFiles:A}})}m(le,"compactWithRequest");async function fe(e,t,r,s,n,o){const c=Math.min(Math.floor(.5*r),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),i=O(e),u=[{role:"user",content:[{type:"text",text:`<conversation>
|
|
101
|
+
${F(i)}
|
|
102
|
+
</conversation>
|
|
103
|
+
|
|
104
|
+
${me}`}],timestamp:Date.now()}],h=t.reasoning&&s&&s!=="off"?{maxTokens:c,reasoning:s}:{maxTokens:c},p=await n({systemPrompt:$,messages:u},w(h,o),o);return p.stopReason==="aborted"?x(new b("aborted",p.errorMessage||"Turn prefix summarization aborted")):p.stopReason==="error"?x(new b("summarization_failed",`Turn prefix summarization failed: ${p.errorMessage||"Unknown error"}`)):k({text:E(p.content),usage:p.usage})}m(fe,"generateTurnPrefixSummary");export{Se as DEFAULT_COMPACTION_SETTINGS,$ as SUMMARIZATION_SYSTEM_PROMPT,_ as calculateContextTokens,we as compact,le as compactWithRequest,N as completeSimpleWithRetries,w as createSummaryRequestOptions,ne as estimateContextTokens,C as estimateTokens,ae as findCutPoint,oe as findTurnStartIndex,Me as generateSummary,R as generateSummaryWithRequest,ue as generateSummaryWithUsage,Ie as getLastAssistantUsage,Pe as prepareCompaction,Ae as serializeConversation,be as shouldCompact};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
var d=Object.defineProperty;var r=(t,e)=>d(t,"name",{value:e,configurable:!0});import{contentText as c}from"@earendil-works/pi-ai";function $(){return{read:new Set,written:new Set,edited:new Set}}r($,"createFileOps");function S(t,e){if(t.role==="assistant"&&!(!("content"in t)||!Array.isArray(t.content)))for(const n of t.content){if(typeof n!="object"||n===null||!("type"in n)||n.type!=="toolCall"||!("arguments"in n)||!("name"in n))continue;const o=n.arguments;if(!o)continue;const i=typeof o.path=="string"?o.path:void 0;if(i)switch(n.name){case"read":e.read.add(i);break;case"write":e.written.add(i);break;case"edit":e.edited.add(i);break}}}r(S,"extractFileOpsFromMessage");function j(t){const e=new Set([...t.edited,...t.written]),n=[...t.read].filter(i=>!e.has(i)).sort(),o=[...e].sort();return{readFiles:n,modifiedFiles:o}}r(j,"computeFileLists");function k(t,e){const n=[];return t.length>0&&n.push(`<read-files>
|
|
2
|
+
${t.join(`
|
|
3
|
+
`)}
|
|
4
|
+
</read-files>`),e.length>0&&n.push(`<modified-files>
|
|
5
|
+
${e.join(`
|
|
6
|
+
`)}
|
|
7
|
+
</modified-files>`),n.length===0?"":`
|
|
8
|
+
|
|
9
|
+
${n.join(`
|
|
10
|
+
|
|
11
|
+
`)}`}r(k,"formatFileOperations");const p=2e3;function h(t){try{return JSON.stringify(t)??"undefined"}catch{return"[unserializable]"}}r(h,"safeJsonStringify");function g(t,e){if(t.length<=e)return t;const n=t.length-e;return`${t.slice(0,e)}
|
|
12
|
+
|
|
13
|
+
[... ${n} more characters truncated]`}r(g,"truncateForSummary");function w(t){const e=[];for(const n of t)if(n.role==="user"){const o=c(n.content,"");o&&e.push(`[User]: ${o}`)}else if(n.role==="assistant"){const o=[],i=[];for(const s of n.content)if(s.type==="thinking")o.push(s.thinking);else if(s.type==="toolCall"){const a=s.arguments,f=Object.entries(a).map(([u,l])=>`${u}=${h(l)}`).join(", ");i.push(`${s.name}(${f})`)}o.length>0&&e.push(`[Assistant thinking]: ${o.join(`
|
|
14
|
+
`)}`),n.content.some(s=>s.type==="text")&&e.push(`[Assistant]: ${c(n.content)}`),i.length>0&&e.push(`[Assistant tool calls]: ${i.join("; ")}`)}else if(n.role==="toolResult"){const o=c(n.content,"");o&&e.push(`[Tool result]: ${g(o,p)}`)}return e.join(`
|
|
15
|
+
|
|
16
|
+
`)}r(w,"serializeConversation");export{j as computeFileLists,$ as createFileOps,S as extractFileOpsFromMessage,k as formatFileOperations,w as serializeConversation};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var r=Object.defineProperty;var a=(e,n)=>r(e,"name",{value:n,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as s}from"@earendil-works/pi-ai";const m={enabled:!0,maxRetries:3,baseDelayMs:1e3,maxAgentDelayMs:s};function f(e){const n=new Set;for(const t of e){if(n.has(t.name))throw new TypeError(`Duplicate tool name: ${JSON.stringify(t.name)}`);n.add(t.name)}}a(f,"validateToolNames");function u(e){if(!Number.isSafeInteger(e.maxRetries)||e.maxRetries<0||e.maxRetries===Number.MAX_SAFE_INTEGER||!Number.isSafeInteger(e.baseDelayMs)||e.baseDelayMs<0||e.maxAgentDelayMs!==void 0&&(!Number.isSafeInteger(e.maxAgentDelayMs)||e.maxAgentDelayMs<0))throw new RangeError("Retry policy values must be finite non-negative safe integers")}a(u,"validateRetryPolicy");function R(e){if(!Number.isSafeInteger(e.reserveTokens)||e.reserveTokens<0||!Number.isSafeInteger(e.keepRecentTokens)||e.keepRecentTokens<0)throw new RangeError("Compaction token counts must be finite non-negative safe integers")}a(R,"validateCompactionSettings");export{m as DEFAULT_RETRY_POLICY,R as validateCompactionSettings,u as validateRetryPolicy,f as validateToolNames};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var i=Object.defineProperty;var o=(t,e)=>i(t,"name",{value:e,configurable:!0});import{awaitWithContext as C,BACKGROUND_CONTEXT as E,createContextKey as r,TODO_CONTEXT as x,withAbortSignal as O,withCancel as a,withContextValue as n,withoutAbortSignal as l}from"@earendil-works/chord/context";import{NOOP_TELEMETRY_CONTEXT as m}from"@earendil-works/pi-telemetry";const T=r("pi.telemetryContext");function w(t){return t.value(T)??m}o(w,"getTelemetryContext");function N(t,e){return n(T,t,e)}o(N,"withTelemetryContext");export{E as BACKGROUND_CONTEXT,x as TODO_CONTEXT,C as awaitWithContext,r as createContextKey,w as getTelemetryContext,O as withAbortSignal,a as withCancel,n as withContextValue,N as withTelemetryContext,l as withoutAbortSignal};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
var de=Object.defineProperty;var o=(i,r)=>de(i,"name",{value:r,configurable:!0});import{spawn as z}from"node:child_process";import{randomUUID as le}from"node:crypto";import{constants as Y,createWriteStream as fe}from"node:fs";import{access as J,appendFile as he,lstat as Z,mkdir as H,mkdtemp as me,open as we,readdir as pe,readFile as ee,realpath as be,rename as ye,rm as ge,writeFile as te}from"node:fs/promises";import{homedir as re,constants as ve,tmpdir as Se}from"node:os";import{basename as Ee,isAbsolute as xe,join as $,resolve as B}from"node:path";import{fileURLToPath as Te}from"node:url";import{ExecutionError as y,err as u,FileError as T,ok as d,toError as D}from"../types.js";import{OutputCapture as Pe}from"../utils/output-capture.js";const ne=2147483647,Le=ne/1e3,_e=100,ke=8*1024*1024;function Fe(i){if(i===void 0)return d(void 0);if(!Number.isFinite(i)||i<=0)return u(new y("timeout","Invalid timeout: must be a finite number of seconds"));const r=i*1e3;return r>ne?u(new y("timeout",`Invalid timeout: maximum is ${Le} seconds`)):d(r)}o(Fe,"resolveTimeoutMs");function b(i,r){let e=r;if(e==="~")e=re();else if(e.startsWith("~/")||process.platform==="win32"&&e.startsWith("~\\"))e=$(re(),e.slice(2));else if(e.startsWith("file://"))try{e=Te(e)}catch{}return xe(e)?B(e):B(i,e)}o(b,"resolvePath");function Ce(i){if(i.isFile())return"file";if(i.isDirectory())return"directory";if(i.isSymbolicLink())return"symlink"}o(Ce,"fileKindFromStats");function ie(i,r){const e=Ce(r);return e?d({name:Ee(i),path:i,kind:e,size:r.size,mtimeMs:r.mtimeMs}):u(new T("invalid","Unsupported file type",i))}o(ie,"fileInfoFromStats");function Ie(i){return i instanceof Error&&"code"in i}o(Ie,"isNodeError");function p(i,r){if(i instanceof T)return i;const e=D(i),n=Ie(i)?i:void 0,t=typeof n?.path=="string"?n.path:r;if(n){const s=n.message;switch(n.code){case"ABORT_ERR":return new T("aborted",s,t,e);case"ENOENT":return new T("not_found",s,t,e);case"EACCES":case"EPERM":return new T("permission_denied",s,t,e);case"ENOTDIR":return new T("not_directory",s,t,e);case"EISDIR":return new T("is_directory",s,t,e);case"EINVAL":return new T("invalid",s,t,e)}}return new T("unknown",e.message,t,e)}o(p,"toFileError");function m(i,r){return i?.aborted?u(new T("aborted","aborted",r)):void 0}o(m,"abortResult");async function W(i){try{return await J(i,Y.F_OK),!0}catch{return!1}}o(W,"pathExists");async function se(i,r,e){return await new Promise(n=>{let t="",s;try{s=z(i,r,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{n({stdout:"",status:null});return}const a=setTimeout(()=>{s.pid&&K(s.pid)},e);s.stdout?.setEncoding("utf8"),s.stdout?.on("data",l=>{t+=l}),s.on("error",()=>{clearTimeout(a),n({stdout:"",status:null})}),s.on("close",l=>{clearTimeout(a),n({stdout:t,status:l})})})}o(se,"runCommand");async function ae(){const i=process.platform==="win32"?await se("where",["bash.exe"],5e3):await se("which",["bash"],5e3);if(i.status!==0||!i.stdout)return null;const r=i.stdout.trim().split(/\r?\n/)[0];return r&&await W(r)?r:null}o(ae,"findBashOnPath");function Ae(i){const r=i.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(r)}o(Ae,"isLegacyWslBashPath");function N(i){return Ae(i)?{shell:i,args:["-s"],commandTransport:"stdin"}:{shell:i,args:["-c"]}}o(N,"getBashShellConfig");async function Oe(i){if(i)return await W(i)?d(N(i)):u(new y("shell_unavailable",`Custom shell path not found: ${i}`));if(process.platform==="win32"){const e=[],n=process.env.ProgramFiles;n&&e.push(`${n}\\Git\\bin\\bash.exe`);const t=process.env["ProgramFiles(x86)"];t&&e.push(`${t}\\Git\\bin\\bash.exe`);for(const a of e)if(await W(a))return d(N(a));const s=await ae();return s?d(N(s)):u(new y("shell_unavailable",`No bash shell found. Options:
|
|
2
|
+
1. Install Git for Windows: https://git-scm.com/download/win
|
|
3
|
+
2. Add your bash to PATH (Cygwin, MSYS2, etc.)
|
|
4
|
+
3. Configure an explicit shellPath
|
|
5
|
+
|
|
6
|
+
Searched Git Bash in:
|
|
7
|
+
${e.map(a=>` ${a}`).join(`
|
|
8
|
+
`)}`))}if(await W("/bin/bash"))return d(N("/bin/bash"));const r=await ae();return r?d(N(r)):d({shell:"sh",args:["-c"]})}o(Oe,"getShellConfig");function Me(i,r,e=!0){return e?{...process.env,...i,...r}:{...r}}o(Me,"getShellEnv");function K(i){if(process.platform==="win32"){try{z($(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(i)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}return}try{process.kill(-i,"SIGKILL")}catch{try{process.kill(i,"SIGKILL")}catch{}}}o(K,"killProcessTree");function Re(i,r){return new Promise((e,n)=>{let t=!1,s=!1,a=null,l=null,w,P=i.stdout===null,v=i.stderr===null;const S=o(()=>{w&&clearTimeout(w),i.removeListener("error",R),i.removeListener("exit",A),i.removeListener("close",x),i.stdout?.removeListener("end",M),i.stderr?.removeListener("end",I),i.stdout?.removeListener("data",C),i.stderr?.removeListener("data",C)},"cleanup"),_=o(()=>{t||(t=!0,S(),i.stdout?.destroy(),i.stderr?.destroy(),e({code:a,signal:l}))},"finalize"),E=o(()=>{s&&P&&v&&_()},"maybeFinalizeAfterExit"),h=o(()=>{w&&clearTimeout(w),w=setTimeout(()=>{r()?h():_()},_e)},"armIdleTimer"),C=o(()=>{s&&!t&&h()},"onData"),M=o(()=>{P=!0,E()},"onStdoutEnd"),I=o(()=>{v=!0,E()},"onStderrEnd"),R=o(g=>{t||(t=!0,S(),n(g))},"onError"),A=o((g,L)=>{s=!0,a=g,l=L,E(),t||h()},"onExit"),x=o((g,L)=>{a=g,l=L,_()},"onClose");i.stdout?.once("end",M),i.stderr?.once("end",I),i.stdout?.on("data",C),i.stderr?.on("data",C),i.once("error",R),i.once("exit",A),i.once("close",x)})}o(Re,"waitForChildProcess");class De{static{o(this,"NodeTextLineReader")}file;path;decoder=new TextDecoder;chunk=new Uint8Array(64*1024);byteOffset=0;buffered="";ended=!1;closed=!1;constructor(r,e){this.file=r,this.path=e}async readLine(r){const e=m(r.abortSignal,this.path);if(e)return e;if(this.closed)return u(new T("invalid","Text line reader is closed",this.path));try{for(;;){const n=this.buffered.indexOf(`
|
|
9
|
+
`);if(n!==-1){const a=this.buffered.slice(0,n);return this.buffered=this.buffered.slice(n+1),d({text:a,terminated:!0})}if(this.ended){if(this.buffered.length===0)return d(void 0);const a=this.buffered;return this.buffered="",d({text:a,terminated:!1})}const{bytesRead:t}=await this.file.read(this.chunk,0,this.chunk.length,this.byteOffset),s=m(r.abortSignal,this.path);if(s)return s;this.byteOffset+=t,t===0?(this.buffered+=this.decoder.decode(),this.ended=!0):this.buffered+=this.decoder.decode(this.chunk.subarray(0,t),{stream:!0})}}catch(n){return u(p(n,this.path))}}async close(r){if(!this.closed){this.closed=!0,this.buffered="";try{await this.file.close()}catch{}}}}class je{static{o(this,"NodeExecutionEnv")}cwd;shellPath;shellEnv;activeChildPids=new Set;constructor(r){this.cwd=r.cwd,this.shellPath=r.shellPath,this.shellEnv=r.shellEnv}async absolutePath(r,e){return d(b(this.cwd,r))}async joinPath(r,e){return d($(...r))}async exec(r,e,n){const t=n.abortSignal;if(t?.aborted)return u(new y("aborted","aborted"));const s=Fe(e?.timeout);if(!s.ok)return u(s.error);const a=s.value,l=e?.cwd?b(this.cwd,e.cwd):this.cwd,w=await Oe(this.shellPath);if(!w.ok)return w;try{await J(l,Y.F_OK)}catch(P){const v=D(P);return u(new y("spawn_error",`Working directory does not exist: ${l}
|
|
10
|
+
Cannot execute bash commands.`,v))}return await new Promise(P=>{let v=!1,S=!1,_,E,h,C;const M=[];let I;const R=[];let A,x,g=!1;const L=o(()=>{h?.pid&&K(h.pid)},"onAbort"),U=o(c=>{if(_!==void 0)return;const f=D(c);_=new y("callback_error",f.message,f),L()},"failCallback");let k;try{k=new Pe(e?.capture,n,{onUpdate:e?.onUpdate,onError:U})}catch(c){const f=D(c);P(u(new y("unknown",f.message,f)));return}const O=o(c=>{v||(v=!0,C&&clearTimeout(C),t&&t.removeEventListener("abort",L),h?.pid&&this.activeChildPids.delete(h.pid),k.dispose(),P(c))},"settle"),X=o(()=>{h?.stdout?.pause(),h?.stderr?.pause()},"pauseOutput"),j=o(()=>{_||E||S||t?.aborted||g||(h?.stdout?.resume(),h?.stderr?.resume())},"resumeOutput"),q=o(c=>{if(E!==void 0)return;const f=D(c);E=new y("unknown",`Failed to preserve complete shell output: ${f.message}`,f),g=!1,L()},"failSpill"),Q=o(c=>{x===void 0||c.length===0||x.write(c)||g||(g=!0,X(),x.once("drain",()=>{g=!1,j()}))},"writeSpill"),G=o(c=>{if(x!==void 0){Q(c);return}R.push(c),A===void 0&&(X(),A=(async()=>{const f=await this.createTempFile({prefix:"pi-output-",suffix:".log"},n);if(!f.ok)throw f.error;I=f.value,k.setSpillPath(I),x=fe(I,{flags:"a",highWaterMark:ke}),x.on("error",q);for(const F of R)Q(F);R.length=0})().catch(q).finally(j))},"startSpill"),oe=o(async()=>{await A;const c=x;c===void 0||E!==void 0||c.destroyed||await new Promise(f=>{c.once("error",()=>f()),c.once("finish",f),c.end()})},"finishSpill");try{const c=w.value.commandTransport==="stdin";h=z(w.value.shell,c?w.value.args:[...w.value.args,r],{cwd:l,detached:process.platform!=="win32",env:Me(this.shellEnv,e?.env,e?.inheritEnv),stdio:[c?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),h.pid&&this.activeChildPids.add(h.pid),c&&(h.stdin?.on("error",()=>{}),h.stdin?.end(r))}catch(c){const f=D(c);O(u(new y("spawn_error",f.message,f)));return}C=a===void 0?void 0:setTimeout(()=>{S=!0,L()},a),t&&(t.aborted?L():t.addEventListener("abort",L,{once:!0}));const V=o(c=>{try{const f=k.truncated;if(k.push(c),!e?.capture?.spill||c.length===0)return;if(I!==void 0||f)G(c);else if(k.truncated){for(const F of M)G(F);M.length=0,G(c)}else M.push(c)}catch(f){U(f)}},"feed");h.stdout?.on("data",V),h.stderr?.on("data",V),Re(h,()=>E===void 0&&A!==void 0&&(x===void 0||g)).then(async({code:c,signal:f})=>{await oe();try{k.finish(),k.flush()}catch(ue){U(ue)}if(_){O(u(_));return}if(S){O(u(new y("timeout",`timeout:${e?.timeout}`)));return}if(t?.aborted){O(u(new y("aborted","aborted")));return}if(E){O(u(E));return}const F=k.snapshot(),ce=c??(f?128+(ve.signals[f]??0):1);O(d({exitCode:ce,truncation:F.truncation,...F.spillPath===void 0?{}:{spillPath:F.spillPath},...F.lastLineBytes===void 0?{}:{lastLineBytes:F.lastLineBytes}}))},c=>O(u(new y("spawn_error",c.message,c))))})}async openTextLineReader(r,e){const n=b(this.cwd,r),t=m(e.abortSignal,n);if(t)return t;try{const s=await we(n,"r"),a=m(e.abortSignal,n);return a?(await s.close().catch(()=>{}),a):d(new De(s,n))}catch(s){return u(p(s,n))}}async readTextFile(r,e){const n=b(this.cwd,r),t=e.abortSignal,s=m(t,n);if(s)return s;try{return d(await ee(n,{encoding:"utf8",signal:t}))}catch(a){return u(p(a,n))}}async readTextLines(r,e,n){if(e?.maxLines!==void 0&&e.maxLines<=0)return d([]);const t=await this.openTextLineReader(r,n);if(!t.ok)return t;const s=[];try{for(;e?.maxLines===void 0||s.length<e.maxLines;){const a=await t.value.readLine(n);if(!a.ok)return a;if(a.value===void 0)break;s.push(a.value.text)}return d(s)}finally{await t.value.close(n)}}async readBinaryFile(r,e){const n=b(this.cwd,r),t=e.abortSignal,s=m(t,n);if(s)return s;try{return d(await ee(n,{signal:t}))}catch(a){return u(p(a,n))}}async writeFile(r,e,n){const t=b(this.cwd,r),s=n.abortSignal,a=m(s,t);if(a)return a;try{await H(B(t,".."),{recursive:!0});const l=m(s,t);return l||(await te(t,e,{signal:s}),d(void 0))}catch(l){return u(p(l,t))}}async appendFile(r,e,n){const t=b(this.cwd,r),s=n.abortSignal,a=m(s,t);if(a)return a;try{await H(B(t,".."),{recursive:!0});const l=m(s,t);return l||(await he(t,e),m(s,t)??d(void 0))}catch(l){return u(p(l,t))}}async renameFile(r,e,n){const t=b(this.cwd,r),s=b(this.cwd,e),a=m(n.abortSignal,s);if(a)return a;try{return await ye(t,s),d(void 0)}catch(l){return u(p(l,t))}}async fileInfo(r,e){const n=b(this.cwd,r),t=m(e.abortSignal,n);if(t)return t;try{return ie(n,await Z(n))}catch(s){return u(p(s,n))}}async listDir(r,e){const n=b(this.cwd,r),t=e.abortSignal,s=m(t,n);if(s)return s;try{const a=await pe(n,{withFileTypes:!0}),l=[];for(const w of a){const P=m(t,n);if(P)return P;const v=B(n,w.name);try{const S=ie(v,await Z(v));S.ok&&l.push(S.value)}catch(S){return u(p(S,v))}}return d(l)}catch(a){return u(p(a,n))}}async canonicalPath(r,e){const n=b(this.cwd,r),t=m(e.abortSignal,n);if(t)return t;try{return d(await be(n))}catch(s){return u(p(s,n))}}async exists(r,e){const n=await this.fileInfo(r,e);return n.ok?d(!0):n.error.code==="not_found"?d(!1):u(n.error)}async createDir(r,e,n){const t=b(this.cwd,r),s=m(n.abortSignal,t);if(s)return s;try{return await H(t,{recursive:e?.recursive??!0}),d(void 0)}catch(a){return u(p(a,t))}}async remove(r,e,n){const t=b(this.cwd,r),s=m(n.abortSignal,t);if(s)return s;try{return await ge(t,{recursive:e?.recursive??!1,force:e?.force??!1}),d(void 0)}catch(a){return u(p(a,t))}}async createTempDir(r,e){const n=m(e.abortSignal);if(n)return n;try{return r??="tmp-",d(await me($(Se(),r)))}catch(t){return u(p(t))}}async createTempFile(r,e){const n=await this.createTempDir("tmp-",e);if(!n.ok)return n;const t=$(n.value,`${r?.prefix??""}${le()}${r?.suffix??""}`);try{return await te(t,""),d(t)}catch(s){return u(p(s,t))}}async cleanup(r){for(const e of this.activeChildPids)K(e);this.activeChildPids.clear()}}export{je as NodeExecutionEnv};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=Object.defineProperty;var c=(d,e)=>f(d,"name",{value:e,configurable:!0});class w{static{c(this,"HarnessEventBus")}listeners=new Map;watchListeners=new Set;deliveryTail=Promise.resolve();closedError;on(e,s){if(this.closedError!==void 0)throw this.closedError;const r=c((n,i)=>s(n,i),"wrapped");let t=this.listeners.get(e);return t===void 0&&(t=new Set,this.listeners.set(e,t)),t.add(r),()=>t?.delete(r)}emit(e,s){return this.emitBatch([e],s)}emitBatch(e,s){if(this.closedError!==void 0||e.length===0)return Promise.resolve();const r=e.map(n=>{const i=structuredClone(n);return{payload:i,recipients:this.snapshotRecipients(i)}}),t=this.deliveryTail.then(async()=>{for(const{payload:n,recipients:i}of r)await this.deliver(n,i,!0,s)});return this.deliveryTail=t.catch(()=>{}),t}watch(e,s,r,t){if(this.closedError!==void 0)throw this.closedError;return this.installWatcher(e,s,t)}async watchFromSnapshot(e,s,r){if(this.closedError!==void 0)throw this.closedError;const t=this.installWatcher(void 0,s,async(n,i)=>{const a=await e(n);return i(),a});try{return t.setSnapshot(await e(r)),t}catch(n){throw t.unsubscribe(),n}}close(e){this.closedError??=e,this.deliveryTail.finally(()=>{this.listeners.clear(),this.watchListeners.clear()})}installWatcher(e,s,r){let t;const n=r===void 0?void 0:async a=>{let h=!1;const o=await r(a,()=>{if(h)throw new Error("Resnapshot boundary was already marked");h=!0,this.enqueueBarrier(()=>t.markResnapshotBoundary())});if(!h)throw new Error("Resnapshot capture did not mark its boundary");return o};t=new p(e,n,async(a,h,o)=>{if(h.type==="handler_error")return;const l=a instanceof Error?a:new Error(String(a)),u="lane"in h&&typeof h.lane=="string"?h.lane:void 0;await this.emit({type:"handler_error",kind:"event",event:h.type,error:l.message,...l.stack===void 0?{}:{stack:l.stack},...u===void 0?{}:{lane:u}},o)});const i=c((a,h)=>{s(a)&&t.push(a,h)},"watchListener");return this.watchListeners.add(i),t.setUnsubscribe(()=>this.watchListeners.delete(i)),t}enqueueBarrier(e){const s=this.deliveryTail.then(e);this.deliveryTail=s.catch(()=>{})}snapshotRecipients(e){return[...this.listeners.get(e.type)??[],...this.watchListeners]}async deliver(e,s,r,t){for(const n of s)try{await n(structuredClone(e),t)}catch(i){if(!r||e.type==="handler_error")continue;const a=i instanceof Error?i:new Error(String(i)),h="lane"in e&&typeof e.lane=="string"?e.lane:void 0,o={type:"handler_error",kind:"event",event:e.type,error:a.message,...a.stack===void 0?{}:{stack:a.stack},...h===void 0?{}:{lane:h}};await this.deliver(o,this.snapshotRecipients(o),!1,t)}}}class p{static{c(this,"BufferedEventWatcher")}snapshot;resnapshotCallback;onError;buffer=[];listener;unsubscribeCallback;deliveryTail=Promise.resolve();epoch=0;resnapshotState;state="buffering";constructor(e,s,r){this.snapshot=e,this.resnapshotCallback=s,this.onError=r}setSnapshot(e){this.snapshot=e}start(e){if(this.state!=="buffering")throw new Error("WatchHandle.start() may be called only once");this.state="started",this.listener=e;const s=this.buffer;this.buffer=[];for(const r of s)this.enqueue(r.event,r.context,r.epoch)}async resnapshot(e){if(this.state==="unsubscribed")throw new Error("WatchHandle is unsubscribed");if(this.resnapshotCallback===void 0)throw new Error("WatchHandle does not support resnapshot");if(this.resnapshotState!==void 0)throw new Error("WatchHandle resnapshot is already in progress");let s;const r=new Promise(n=>{s=n}),t={phase:"dropping",held:[],reached:r,resolveReached:s};this.epoch++,this.resnapshotState=t;try{const n=await this.resnapshotCallback(e);await r,this.snapshot=n,this.resnapshotState=void 0;for(const i of t.held)this.push(i.event,i.context);return n}catch(n){this.resnapshotState=void 0;for(const i of t.held)this.push(i.event,i.context);throw n}}markResnapshotBoundary(){const e=this.resnapshotState;e===void 0||e.phase!=="dropping"||(e.phase="holding",e.resolveReached())}unsubscribe(){this.state!=="unsubscribed"&&(this.state="unsubscribed",this.buffer=[],this.listener=void 0,this.unsubscribeCallback?.(),this.unsubscribeCallback=void 0)}push(e,s){if(this.state!=="unsubscribed"&&this.resnapshotState?.phase!=="dropping"){if(this.resnapshotState?.phase==="holding"){this.resnapshotState.held.push({event:e,context:s});return}if(this.state==="buffering"){this.buffer.push({event:e,context:s,epoch:this.epoch});return}this.enqueue(e,s,this.epoch)}}setUnsubscribe(e){this.unsubscribeCallback=e}enqueue(e,s,r){const t=this.listener;t!==void 0&&(this.deliveryTail=this.deliveryTail.then(async()=>{this.state==="started"&&r===this.epoch&&await t(e,s)}).catch(async n=>{try{await this.onError(n,e,s)}catch{}}))}}export{w as HarnessEventBus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var u=Object.defineProperty;var m=(s,t)=>u(s,"name",{value:t,configurable:!0});import{getTelemetryContext as f}from"../context.js";import{AbortRequested as y}from"./effect-gate.js";function w(s,t,r){const e=s.streamOptions;return{transport:e.transport,timeoutMs:e.timeoutMs,maxRetries:e.maxRetries,maxRetryDelayMs:e.maxRetryDelayMs,headers:e.headers,metadata:e.metadata,cacheRetention:e.cacheRetention,deferred:e.deferred,...s.thinkingLevel==="off"?{}:{reasoning:s.thinkingLevel},signal:r.abortSignal,telemetryContext:f(r),onPayload:s.beforePayload===void 0?void 0:(n,o)=>s.beforePayload?.(n,o,r),onResponse:m(n=>{t({status:n.status,headers:n.headers})},"onResponse")}}m(w,"createRequestOptions");function h(s){return s.type!=="start"&&s.type!=="done"&&s.type!=="error"}m(h,"isUpdateEvent");async function R(s,t,r,e){let n=!1;for await(const a of s)if(a.type==="start"){if(n)throw new Error("Assistant message stream emitted more than one start event");n=!0,await t.start({...a.partial},a,e)}else if(h(a)){if(!n)throw new Error(`Assistant message stream emitted ${a.type} before start`);await t.update({...a.partial},a,e)}else if(a.type==="done"&&!n)throw new Error("Assistant message stream emitted done before start");const o=await s.result();let i=o;if(r!==void 0)try{i=await r(o,e)}catch(a){if(!(a instanceof y))throw a;await a.cancellation}return await t.end(i,e),i}m(R,"consumeAssistantStream");async function C(s,t,r){let e={messages:s.slice(),systemPrompt:t.systemPrompt};t.transformContext&&(e=await t.transformContext(e,r));const n=await t.toProviderMessages(e.messages,r),o={systemPrompt:e.systemPrompt,messages:n,tools:t.tools};let i={};const a=await t.request(o,w(t,d=>{i=d},r),r),l=t.afterResponse;return R(a,t.observer,l===void 0?void 0:(d,p)=>l(d,i,p),r)}m(C,"streamHarnessAssistant");export{R as consumeAssistantStream,C as streamHarnessAssistant};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var o=(t,e)=>a(t,"name",{value:e,configurable:!0});class s extends Error{static{o(this,"AbortRequested")}cancellation;constructor(e){super("Abort requested"),this.name="AbortRequested",this.cancellation=e}}function c(){let t={status:"open"};const e=new AbortController,n=o(()=>{if(t.status==="aborting")throw new s(t.cancellation);if(t.status==="closed")throw t.error},"check");return{gate:{admit(r){return n(),r()},signal:e.signal},control:{beginAbort(r){t.status==="open"&&(t={status:"aborting",cancellation:r})},signalAbort(){t.status!=="aborting"||e.signal.aborted||e.abort(new s(t.cancellation))},close(r){t.status!=="closed"&&(t={status:"closed",error:r},e.signal.aborted||e.abort(r))}}}}o(c,"createGate");export{s as AbortRequested,c as createGate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var E=Object.defineProperty;var n=(t,e)=>E(t,"name",{value:e,configurable:!0});import{validateToolArguments as m}from"@earendil-works/pi-ai";import{withAbortSignal as c}from"../context.js";function f(t){return{content:[{type:"text",text:t}],details:void 0}}n(f,"createErrorToolResult");function l(t,e,r=!1){return{kind:"immediate",toolCall:t,result:f(e),isError:!0,terminate:r}}n(l,"immediateError");function A(t,e){const r=e.find(o=>o.name===t.name);if(!r)return l(t,`Tool ${JSON.stringify(t.name)} is unavailable`);try{const o=r.prepareArguments?r.prepareArguments(t.arguments):t.arguments,i=o===t.arguments?t:{...t,arguments:o},u=m(r,i);return{toolCall:t,tool:r,args:u}}catch(o){return l(t,o instanceof Error?o.message:String(o))}}n(A,"prepareToolCall");function S(t,e){if(e?.block)return l(t.toolCall,e.block.reason,e.block.terminate===!0);if(!e?.args)return{toolCall:t.toolCall,tool:t.tool,args:t.args};try{const r=m(t.tool,{...t.toolCall,arguments:e.args});return{toolCall:t.toolCall,tool:t.tool,args:r}}catch(r){return l(t.toolCall,r instanceof Error?r.message:String(r))}}n(S,"applyBeforeToolDecision");function x(t,e,r,o,i,u){let a=!0;return e.admit(async()=>{const g=c(e.signal,u);g.abortSignal?.throwIfAborted();try{return{result:await t.tool.execute(t.toolCall.id,t.args,(d,C)=>{a&&r(d,C)},o,i,g),isError:!1}}catch(s){return{result:f(s instanceof Error?s.message:String(s)),isError:!0}}finally{a=!1}})}n(x,"executeToolCall");function k(t,e,r){const o=r?{...e.result,content:r.content===void 0?e.result.content:r.content,details:r.details===void 0?e.result.details:r.details,usage:r.usage===void 0?e.result.usage:r.usage,terminate:r.terminate===void 0?e.result.terminate:r.terminate}:e.result;return{toolCall:t.toolCall,result:o,isError:r?.isError??e.isError,terminate:o.terminate===!0}}n(k,"finalizeToolCall");function w(t,e){return{content:t.content,details:t.details,...t.usage===void 0?{}:{usage:t.usage},...e?{terminate:!0}:{}}}n(w,"toolResultFromMessage");function R(t){return{role:"toolResult",toolCallId:t.toolCall.id,toolName:t.toolCall.name,content:t.result.content??[],...t.result.details===void 0?{}:{details:t.result.details},...t.result.usage===void 0?{}:{usage:t.result.usage},isError:t.isError,timestamp:Date.now()}}n(R,"createToolResultMessage");export{S as applyBeforeToolDecision,R as createToolResultMessage,x as executeToolCall,k as finalizeToolCall,A as prepareToolCall,w as toolResultFromMessage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=Object.defineProperty;var d=(a,e)=>c(a,"name",{value:e,configurable:!0});import{withAbortSignal as f}from"./context.js";import{startHarnessSpan as u}from"./telemetry.js";class b{static{d(this,"HookRegistry")}registrations=new Map;reportError;closedError;constructor(e){this.reportError=e}on(e,o,r={}){if(this.closedError!==void 0)throw this.closedError;const s=this.registrations.get(e)??[],i={...r.id===void 0?{}:{id:r.id},handler:d((t,n)=>o(t,n),"handler")};return s.push(i),this.registrations.set(e,s),()=>{const t=s.indexOf(i);t!==-1&&s.splice(t,1)}}has(e){return(this.registrations.get(e)?.length??0)!==0}runWithGate(e,o,r,s){return r.admit(()=>{const i=f(r.signal,s);return i.abortSignal?.throwIfAborted(),this.runAdmitted(e,o,i)})}runToolWithGate(e,o,r,s){return r.admit(()=>{const i=f(r.signal,s);return i.abortSignal?.throwIfAborted(),e==="before_tool"?this.beforeTool(o,i):this.afterTool(o,i)})}close(e){this.closedError??=e}async runAdmitted(e,o,r){if(this.closedError!==void 0)throw this.closedError;return await this.aggregate(e,o,r)}async aggregate(e,o,r){switch(e){case"before_run":return this.beforeRun(o,r);case"before_drive":await this.invokeAllFailClosed(e,o,r);return;case"before_run_end":{let s;return await this.invokeAll(e,o,i=>{const t=i;t?.followUp!==void 0&&(s=t.followUp)},r),s===void 0?void 0:{followUp:s}}case"transform_context":return this.transformContext(o,r);case"before_request":return this.beforeRequest(o,r);case"before_payload":return this.beforePayload(o,r);case"after_response":return this.afterResponse(o,r);case"before_tool":return this.beforeTool(o,r);case"after_tool":return this.afterTool(o,r);case"before_compaction":return this.firstStructural(e,o,"compaction",r);case"before_navigation":return this.firstStructural(e,o,"summary",r)}}async beforeRun(e,o){let r=e.prompt,s=[];for(const i of this.registrationsFor("before_run"))try{const t=await i.handler({...e,prompt:r},o);t?.messages!==void 0&&(s=[...s,...t.messages],r=[...r,...t.messages])}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),"before_run",e.lane,o)}return s.length===0?void 0:{messages:s}}async beforeTool(e,o){let r=e.args,s;for(const i of this.registrationsFor("before_tool"))try{const t=await this.invokeToolRegistration("before_tool",i,{...e,args:r},o);if(t?.args!==void 0&&(r=t.args),t?.block!==void 0){s=t.block;break}}catch(t){const n=t instanceof Error?t:new Error(String(t));await this.reportError(n,"before_tool",e.lane,o),s={reason:n.message};break}return{...r===e.args?{}:{args:r},...s===void 0?{}:{block:s}}}async transformContext(e,o){let r=e.messages,s=e.systemPrompt;for(const i of this.registrationsFor("transform_context"))try{const t=await i.handler({...e,messages:r,systemPrompt:s},o);t?.messages!==void 0&&(r=t.messages),t?.systemPrompt!==void 0&&(s=t.systemPrompt)}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),"transform_context",e.lane,o)}return{messages:r,systemPrompt:s}}async beforeRequest(e,o){let r=e.streamOptions,s=!1;for(const i of this.registrationsFor("before_request"))try{const t=await i.handler({...e,streamOptions:r},o);t?.streamOptions!==void 0&&(r=h(r,t.streamOptions),s=!0)}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),"before_request",e.lane,o)}return s?{streamOptions:g(e.streamOptions,r)}:void 0}async beforePayload(e,o){let r=e.payload;for(const s of this.registrationsFor("before_payload"))try{const i=await s.handler({...e,payload:r},o);i?.payload!==void 0&&(r=i.payload)}catch(i){await this.reportError(i instanceof Error?i:new Error(String(i)),"before_payload",e.lane,o)}return{payload:r}}async afterResponse(e,o){let r=e.message;for(const s of this.registrationsFor("after_response"))try{const i=await s.handler({...e,message:r},o);i?.message!==void 0&&(r=i.message)}catch(i){await this.reportError(i instanceof Error?i:new Error(String(i)),"after_response",e.lane,o)}return{message:r}}async afterTool(e,o){let r={content:e.content,details:e.details,isError:e.isError,usage:e.usage};const s={};for(const i of this.registrationsFor("after_tool"))try{const t=await this.invokeToolRegistration("after_tool",i,{...e,...r},o);if(t===void 0)continue;t.content!==void 0&&(s.content=t.content),t.details!==void 0&&(s.details=t.details),t.isError!==void 0&&(s.isError=t.isError),t.usage!==void 0&&(s.usage=t.usage),t.terminate!==void 0&&(s.terminate=t.terminate),r={content:t.content===void 0?r.content:t.content,details:t.details===void 0?r.details:t.details,isError:t.isError===void 0?r.isError:t.isError,usage:t.usage===void 0?r.usage:t.usage}}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),"after_tool",e.lane,o)}return Object.keys(s).length===0?void 0:s}async firstStructural(e,o,r,s){for(const i of this.registrationsFor(e))try{const t=await i.handler(o,s);if(t==null||typeof t!="object")continue;const n=t;if(n.decline===!0&&n[r]!==void 0){await this.reportError(new Error(`${e} hook cannot return both decline and ${r}`),e,o.lane,s);continue}if(n.decline===!0||n[r]!==void 0)return t}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),e,o.lane,s)}}invokeToolRegistration(e,o,r,s){return u("pi.harness.hook",{"pi.lane.name":r.lane,"pi.operation.id":r.runId,"pi.hook.name":e,...o.id===void 0?{}:{"pi.hook.registration_id":o.id}},async(i,t)=>{try{const n=await o.handler(r,t),l=e==="before_tool"&&n!==null&&typeof n=="object"&&"block"in n&&n.block!==void 0;return i.setAttributes({"pi.hook.outcome":l?"blocked":"completed"}),n}catch(n){throw i.setAttributes({"pi.hook.outcome":"failed"}),i.setStatus({status:"error"}),n}},s)}registrationsFor(e){return[...this.registrations.get(e)??[]]}async invokeAllFailClosed(e,o,r){for(const s of this.registrationsFor(e))try{await s.handler(o,r)}catch(i){const t=i instanceof Error?i:new Error(String(i));throw await this.reportError(t,e,o.lane,r),t}}async invokeAll(e,o,r,s){for(const i of this.registrationsFor(e))try{r(await i.handler(o,s))}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),e,o.lane,s)}}}function h(a,e){const o={...a};for(const r of["transport","timeoutMs","maxRetries","maxRetryDelayMs","cacheRetention","deferred"]){if(!(r in e))continue;const s=e[r];s===void 0?delete o[r]:Object.assign(o,{[r]:s})}if("headers"in e)if(e.headers===void 0)delete o.headers;else{const r={...o.headers};for(const[s,i]of Object.entries(e.headers))i===void 0?delete r[s]:r[s]=i;o.headers=r}if("metadata"in e)if(e.metadata===void 0)delete o.metadata;else{const r={...o.metadata};for(const[s,i]of Object.entries(e.metadata))i===void 0?delete r[s]:r[s]=i;o.metadata=r}return o}d(h,"applyStreamOptionsPatch");function g(a,e){const o={};for(const r of["transport","timeoutMs","maxRetries","maxRetryDelayMs","cacheRetention","deferred"])a[r]!==e[r]&&Object.assign(o,{[r]:e[r]});if(a.headers!==e.headers)if(e.headers===void 0)o.headers=void 0;else{const r={};for(const s of Object.keys(a.headers??{}))s in e.headers||(r[s]=void 0);for(const[s,i]of Object.entries(e.headers))a.headers?.[s]!==i&&(r[s]=i);a.headers===void 0&&Object.keys(r).length===0?o.headers={}:Object.keys(r).length!==0&&(o.headers=r)}if(a.metadata!==e.metadata)if(e.metadata===void 0)o.metadata=void 0;else{const r={};for(const s of Object.keys(a.metadata??{}))s in e.metadata||(r[s]=void 0);for(const[s,i]of Object.entries(e.metadata))a.metadata?.[s]!==i&&(r[s]=i);a.metadata===void 0&&Object.keys(r).length===0?o.metadata={}:Object.keys(r).length!==0&&(o.metadata=r)}return o}d(g,"createStreamOptionsPatch");export{b as HookRegistry,h as applyStreamOptionsPatch};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
var a=Object.defineProperty;var o=(e,t)=>a(e,"name",{value:t,configurable:!0});const c=`The conversation history before this point was compacted into the following summary:
|
|
2
|
+
|
|
3
|
+
<summary>
|
|
4
|
+
`,s=`
|
|
5
|
+
</summary>`,i=`The following is a summary of a branch that this conversation came back from:
|
|
6
|
+
|
|
7
|
+
<summary>
|
|
8
|
+
`,m="</summary>";function p(e){let t=`Ran \`${e.command}\`
|
|
9
|
+
`;return e.output?t+=`\`\`\`
|
|
10
|
+
${e.output}
|
|
11
|
+
\`\`\``:t+="(no output)",e.cancelled?t+=`
|
|
12
|
+
|
|
13
|
+
(command cancelled)`:e.exitCode!==null&&e.exitCode!==void 0&&e.exitCode!==0&&(t+=`
|
|
14
|
+
|
|
15
|
+
Command exited with code ${e.exitCode}`),e.truncated&&e.fullOutputPath&&(t+=`
|
|
16
|
+
|
|
17
|
+
[Output truncated. Full output: ${e.fullOutputPath}]`),t}o(p,"bashExecutionToText");function x(e,t,n){return{role:"branchSummary",summary:e,fromId:t,timestamp:typeof n=="number"?n:new Date(n).getTime()}}o(x,"createBranchSummaryMessage");function f(e,t,n){return{role:"compactionSummary",summary:e,tokensBefore:t,timestamp:typeof n=="number"?n:new Date(n).getTime()}}o(f,"createCompactionSummaryMessage");function d(e,t,n,u,r){return{role:"custom",customType:e,content:t,display:n,details:u,timestamp:typeof r=="number"?r:new Date(r).getTime()}}o(d,"createCustomMessage");function y(e){return e.map(t=>{switch(t.role){case"bashExecution":return t.excludeFromContext?void 0:{role:"user",content:[{type:"text",text:p(t)}],timestamp:t.timestamp};case"custom":return{role:"user",content:typeof t.content=="string"?[{type:"text",text:t.content}]:t.content,timestamp:t.timestamp};case"branchSummary":return{role:"user",content:[{type:"text",text:i+t.summary+m}],timestamp:t.timestamp};case"compactionSummary":return{role:"user",content:[{type:"text",text:c+t.summary+s}],timestamp:t.timestamp};case"system":case"user":case"assistant":case"toolResult":return t;default:return}}).filter(t=>t!==void 0)}o(y,"convertToLlm");export{i as BRANCH_SUMMARY_PREFIX,m as BRANCH_SUMMARY_SUFFIX,c as COMPACTION_SUMMARY_PREFIX,s as COMPACTION_SUMMARY_SUFFIX,p as bashExecutionToText,y as convertToLlm,x as createBranchSummaryMessage,f as createCompactionSummaryMessage,d as createCustomMessage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=Object.defineProperty;var r=(n,a)=>g(n,"name",{value:a,configurable:!0});import{spawn as w}from"node:child_process";import{Type as o}from"typebox";const h=o.Object({command:o.String(),cwd:o.Optional(o.String())});function v(n={}){return{name:"bash",description:"Run a shell command",parameters:h,replay:"unsafe",output:n,async execute({command:a,cwd:m},s,i){const l=Date.now(),e=w("bash",["-c",a],{cwd:m,stdio:["ignore","pipe","pipe"]}),c=r(()=>e.kill("SIGKILL"),"onAbort");i.abortSignal?.addEventListener("abort",c),e.stdout.on("data",t=>s.stream(t)),e.stderr.on("data",t=>s.stream(t));const{code:d,signal:p}=await new Promise(t=>e.on("close",(b,u)=>t({code:b,signal:u})));return i.abortSignal?.removeEventListener("abort",c),{isError:d!==0,details:{exitCode:d,signal:p,ms:Date.now()-l}}}}}r(v,"bashTool");export{v as bashTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var p=Object.defineProperty;var n=(e,t)=>p(e,"name",{value:t,configurable:!0});class x{static{n(this,"Bounded")}bytes=new Uint8Array;maxBytes;maxLines;retain;droppedBytes=0;droppedLines=0;total=0;constructor(t,s,i){this.maxBytes=Math.max(0,t),this.maxLines=Math.max(0,s),this.retain=i}push(t){if(this.total+=t.length,t.length!==0){if(this.maxBytes===0||this.maxLines===0){this.drop(t);return}if(this.retain==="head"){this.pushHead(t);return}this.pushTail(t)}}pushHead(t){const s=this.maxBytes-this.bytes.length,i=this.maxLines-h(this.bytes);if(s<=0||i<=0){this.drop(t);return}let r=Math.min(t.length,s),o=0;for(let a=0;a<r;a++)if(t[a]===10&&(o++,o===i)){r=a+1;break}this.bytes=d(this.bytes,t.subarray(0,r)),this.drop(t.subarray(r))}pushTail(t){const s=l(t,this.maxBytes,this.maxLines);this.drop(t.subarray(0,s));const i=d(this.bytes,t.subarray(s)),r=l(i,this.maxBytes,this.maxLines);this.drop(i.subarray(0,r)),this.bytes=i.slice(r)}drop(t){this.droppedBytes+=t.length,this.droppedLines+=h(t)}get dropped(){return this.droppedBytes}text(){return new TextDecoder().decode(this.bytes)}}function l(e,t,s){let i=Math.max(0,e.length-t),r=h(e.subarray(i))-s;for(;i<e.length&&r>0;i++)e[i]===10&&r--;return i}n(l,"tailStart");function d(e,t){if(e.length===0)return t.slice();if(t.length===0)return e;const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}n(d,"concat");function h(e){let t=0;for(const s of e)s===10&&t++;return t}n(h,"countNewlines");export{x as Bounded};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var w=Object.defineProperty;var i=(c,n)=>w(c,"name",{value:n,configurable:!0});import{defineService as g}from"@earendil-works/chord";import{WATCH_CAPACITY as y}from"./view.js";const P=g("pi.harness",{local:!0}),S=g("pi.conversation");function E(c,n,r){return{view:r,send:i((e,t)=>n.send(e,t).then(o=>o.id),"send"),write:i((e,t)=>n.write(e,t),"write"),inputAbort:i((e,t)=>c.abortInput(e,t,n.id),"inputAbort"),configSet:i((e,t)=>n.config.set(e,t),"configSet"),abort:i(e=>n.abort(e),"abort"),reset:i((e,t)=>n.reset(e??void 0,t),"reset"),collapse:i((e,t)=>n.collapse(e??void 0,t),"collapse"),fork:i((e,t,o)=>n.fork(e,t,o).then(l=>l.id),"fork"),entries:i((e,t)=>c.entries({...e,conversationId:n.id},t),"entries")}}i(E,"createPicoConversationService");async function j(c,n,r,e={}){const t=await c.watch(r),o=n({...structuredClone(t.view),commit:{events:[]}});return v(t,o,r,e)}i(j,"attachChordView");function v(c,n,r,e){const t=e.capacity??y;if(!Number.isSafeInteger(t)||t<1)throw new RangeError("Chord view queue capacity must be positive");const o=[];let l=!1,s=!1;const f=i(a=>{if(!s){s=!0,o.length=0,c.stop();try{e.onFailure?.(a instanceof Error?a:new Error(String(a)))}catch{}}},"fail"),h=i(()=>{for(l=!1;!s&&o.length>0;){const a=o.shift();try{n.change(r,u=>{m(u,a.ops),u.commit.events=a.events})}catch(u){f(u)}}},"drain");return c.start(a=>{if(!s){if(o.length>=t){f(new Error(`Pico-to-Chord view queue exceeded ${t} envelopes`));return}o.push(a),!l&&(l=!0,queueMicrotask(h))}}),{view:n,get closed(){return s},close(){s||(s=!0,o.length=0,c.stop())}}}i(v,"bridgeWatch");function m(c,n){for(const r of n){if(r[0]==="r")throw new Error("live Pico envelope unexpectedly replaced the view root");const e=r[1];if(r[0]==="p"){const s=d(c,e);if(!Array.isArray(s))throw new Error(`Pico splice path is not an array: ${e.join(".")}`);s.splice(r[2],r[3],...r[4]);continue}if(r[0]==="m"){const s=d(c,e);if(!Array.isArray(s)||s.length!==r[2].length)throw new Error(`Pico permutation path is not a matching array: ${e.join(".")}`);const f=s,h=f.slice(),a=new Map;for(let u=0;u<r[2].length;u++){const p=h[r[2][u]];a.has(p)||a.set(p,u)}f.sort((u,p)=>a.get(u)-a.get(p));continue}const t=d(c,e.slice(0,-1));if(t===null||typeof t!="object")throw new Error(`Pico operation parent is not an object: ${e.join(".")}`);const o=e[e.length-1];if(r[0]==="d"){Array.isArray(t)?t.splice(o,1):delete t[o];continue}const l=t;r[0]==="s"?l[o]=r[2]:r[0]==="a"?l[o]=`${String(l[o])}${r[2]}`:l[o]=String(l[o]).slice(r[2])}}i(m,"applyTracked");function d(c,n){let r=c;for(const e of n){if(r===null||typeof r!="object")return;r=r[e]}return r}i(d,"resolve");export{S as PicoConversationService,P as PicoHarnessService,j as attachChordView,E as createPicoConversationService};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var m=Object.defineProperty;var a=(n,l)=>m(n,"name",{value:l,configurable:!0});async function w(n,l,i,r){const[d]=await n.scanEntries({conversationId:l,withHead:!0,...i===void 0?{}:{before:i+1},limit:1},r),f=d?.head,o=[];let e=i===void 0?void 0:i+1;for(;;){const t=await n.scanEntries({conversationId:l,...e===void 0?{}:{before:e},limit:256},r);let s=t.length<256;for(const p of t){if(f!==void 0&&p.id<f){s=!0;break}o.push(p)}if(s)break;e=t[t.length-1].id}o.reverse();const u=new Map;for(const t of o)for(const s of t.edits??[])u.set(s.target,s);const h=d===void 0?o:[d,...o.filter(t=>t.head===void 0)],c=[];for(const t of h){const s=u.get(t.id);if(s?.action!=="omit"){if(s?.action==="replace"){c.push(...s.messages??[]);continue}t.model&&c.push(...t.model)}}return{head:d,entries:h,messages:g(c)}}a(w,"deriveContext");function g(n){const l=[];for(let i=0;i<n.length;i++){const r=n[i];if(l.push(r),r.role!=="assistant")continue;const d=r.content.filter(e=>e.type==="toolCall");if(d.length===0)continue;const f=new Map;let o=i+1;for(;o<n.length&&n[o].role==="toolResult";){const e=n[o];f.set(e.toolCallId,e),o++}for(const e of d)l.push(f.get(e.id)??{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:"Tool result unavailable: history ends before this call completed."}],isError:!0,details:{reason:"missing_after_fork"},timestamp:r.timestamp});i=o-1}return l}a(g,"reorderToolResults");export{w as deriveContext};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var S=Object.defineProperty;var l=(g,e)=>S(g,"name",{value:e,configurable:!0});import{withAbortSignal as x}from"@earendil-works/chord/context";import{createHookRunners as M}from"./hooks.js";import{chooseThrough as F,collapse as y}from"./kinds/collapse.js";import{entries as b}from"./kinds/entries.js";import{generation as I}from"./kinds/generation.js";import{job as T}from"./kinds/job.js";import{plugin as E}from"./kinds/plugin.js";import{postTools as R}from"./kinds/post-tools.js";import{tool as $}from"./kinds/tool.js";import{Scheduler as K}from"./scheduler.js";import{isCoreKind as H,Session as L}from"./session.js";import{systemSections as A}from"./system.js";import{Forbidden as k}from"./types.js";import{ViewManager as j}from"./view.js";const p={type:"kernel"};class O{static{l(this,"Harness")}session;scheduler;views;kinds;namespaces=new Map;tools=new Map;sectionMap=new Map;entryKinds=new Map;revisions={sections:0,tools:0};plugins;hookRegistrations=[];conversationListeners=new Set;onReport;now;ctx;options;resumed=!1;suspended=!1;static async open(e,s,n){const c=new O(e,s,n);return await c.init(),c}constructor(e,s,n){this.ctx=n,this.options=s,this.now=s.now??Date.now,this.onReport=r=>{try{s.onReport?.(r)}catch{}};const c=[I,$,R,y,T,E];this.kinds=new Map(c.map(r=>[r.name,r]));for(const r of s.taskKinds??[]){if(r.name.startsWith("pi."))throw new Error(`task kind "${r.name}": names beginning with "pi." are reserved`);if(this.kinds.has(r.name))throw new Error(`task kind "${r.name}" registered twice`);this.kinds.set(r.name,r)}for(const r of s.tools??[])this.registerTool(r,"open");for(const r of Object.values(A))this.sectionMap.set(r.key,r);for(const r of s.sections??[])this.registerSection(r,"open");for(const r of Object.values(b))this.entryKinds.set(r.kind,r);this.plugins=new Map(Object.entries(s.plugins??{})),this.session=new L(e,this.kinds,this.namespaces,this.now),this.session.onReport=this.onReport,this.views=new j(this.session,this.onReport),this.session.lineListeners.add(r=>this.views.update(r)),this.session.listeners.add(r=>{this.views.deliver();for(const w of r.changes.conversations)this.notifyConversation(w)});const t=this,h=M(()=>this.hookRegistrations,r=>this.session.index.ancestors(r),this.onReport);this.scheduler=new K({session:this.session,kinds:this.kinds,onReport:this.onReport,ctx:n,runtime(r,w,d){return{taskId:r.id,conversationId:r.conversationId,kind:w.kind,commit:l((i,o)=>{const u=(t.session.liveTasks.get(r.id)?.owns??[]).flatMap(m=>[{doc:"rewindable",conversationId:m},{doc:"sticky",conversationId:m}]);return t.session.commit(w,(m,v)=>i(m,t.session.liveTasks.get(r.id),v),o,{docs:u}).then(m=>m.value)},"commit"),hooks:h(w.kind,{taskId:r.id,conversationId:r.conversationId}),models:s.models,tools:t.tools,registries:{sections:{map:t.sectionMap,get revision(){return t.revisions.sections}},tools:{map:t.tools,get revision(){return t.revisions.tools}}},kinds:t.kinds,processHost:s.processHost,plugins:t.plugins,now:t.now,sleep:l((i,o)=>new Promise((a,u)=>{const m=Math.max(0,i-Date.now()),v=setTimeout(()=>{o.abortSignal?.removeEventListener("abort",f),a()},m),f=l(()=>{clearTimeout(v),u(o.abortSignal?.reason??new Error("aborted"))},"onAbort");o.abortSignal?.addEventListener("abort",f,{once:!0})}),"sleep"),waitForInput:l((i,o)=>t.scheduler.waitForInput(i,o),"waitForInput"),waitForTask:l((i,o)=>t.scheduler.waitForTask(i,o),"waitForTask"),abortTask:l(async(i,o)=>(await t.session.onLine(async a=>{t.assertInvocation(w);const u=t.session.liveTasks.get(i)??await t.session.storage.task(i,a);if(u===void 0)throw new Error(`task ${i} not found`);t.assertTaskConversationScope(r.id,u.conversationId)},o),t.scheduler.abortTask(i,o)),"abortTask"),abortConversation:l(async(i,o)=>{await t.session.onLine(()=>{t.assertInvocation(w),t.assertOwnedConversation(r.id,i)},o);const a=await t.conversation(i,o);a&&await a.abort(o)},"abortConversation"),createOwnedConversation:l((i,o)=>t.session.commit(p,a=>(t.assertInvocation(w),a.createOwnedConversation(r.id,r.conversationId,i)),o).then(a=>a.value),"createOwnedConversation"),sendOwned:l((i,o,a)=>t.session.commit(p,u=>(t.assertInvocation(w),t.assertOwnedConversation(r.id,i),u.send(i,o)),a,{docs:[{doc:"rewindable",conversationId:i},{doc:"sticky",conversationId:i}]}).then(u=>u.value),"sendOwned"),context:l((i,o,a)=>t.session.commit(w,u=>u.context(i,o),a).then(u=>u.value),"context"),newestEntry:l((i,o,a)=>t.session.commit(w,u=>u.newestEntry(i,o),a).then(u=>u.value),"newestEntry"),rewindable:l((i,o)=>t.session.commit(w,a=>a.snapshot({doc:"rewindable",conversationId:i}),o,{docs:[{doc:"rewindable",conversationId:i}]}).then(a=>a.value),"rewindable"),sticky:l((i,o)=>t.session.commit(w,a=>a.snapshot({doc:"sticky",conversationId:i}),o,{docs:[{doc:"sticky",conversationId:i}]}).then(a=>a.value),"sticky"),rewindableAsOf:l((i,o,a)=>t.session.commit(w,u=>u.rewindableAsOf(i,o),a).then(u=>u.value),"rewindableAsOf")}}})}notifyConversation(e){if(this.conversationListeners.size===0)return;const s=this.handle(e);for(const n of[...this.conversationListeners])try{n(s)}catch(c){this.onReport(c)}}assertInvocation(e){if(!e.token.alive)throw new k("operation from a finished invocation");const s=this.session.liveTasks.get(e.id);if(s===void 0)throw new k("operation from a task that is not live");if(e.mode==="run"&&s.abort===!0)throw new k("operation from a marked run invocation")}assertTaskConversationScope(e,s){const n=this.session.liveTasks.get(e);if(n?.conversationId!==s&&!n?.owns.some(c=>this.session.index.subtree(c).has(s)))throw new k(`conversation ${s} is outside task ${e}'s subtree`)}assertOwnedConversation(e,s){const n=this.session.liveTasks.get(e);if(n===void 0||!n.owns.some(c=>this.session.index.subtree(c).has(s)))throw new k(`conversation ${s} is not owned by task ${e}`)}async init(){const{session:e}=this,s=await e.read((t,h)=>t.conversations(h),this.ctx);for(const t of s)e.conversationRecords.set(t.id,t);const n=await e.read((t,h)=>t.scanTasks({status:["pending","running"]},h),this.ctx);for(const t of n)e.liveTasks.set(t.id,t);const c=new Set(s.map(t=>t.owner).filter(t=>t!==void 0));for(const t of c)if(!e.liveTasks.has(t)){const h=await e.read((r,w)=>r.task(t,w),this.ctx);h&&e.ownerTaskCache.set(t,h)}s.length===0&&await e.commit(p,t=>t.createConversation({rewindable:this.options.root?.rewindable,sticky:this.options.root?.sticky}),this.ctx)}resume(){if(this.suspended)throw new Error("cannot resume a suspended harness; reopen storage with a new harness");this.resumed||(this.resumed=!0,this.reconcileOrphans().then(()=>{this.suspended||this.scheduler.resume()}).catch(e=>this.onReport(e)))}async reconcileOrphans(){const e=[...this.session.liveTasks.values()].filter(n=>!this.kinds.has(n.kind));if(e.length===0)return;const s=[...new Set(e.map(n=>n.conversationId))].map(n=>({doc:"sticky",conversationId:n}));await this.session.commit(p,n=>{for(const c of e)n.setTask({...c,status:"terminal",outcome:{status:"orphaned"}})},this.ctx,{docs:s})}quiescent(){return this.scheduler.quiescent()}hold(){if(!this.scheduler.quiescent())throw new Error("cannot hold a non-quiescent harness; suspend it instead");return this.scheduler.hold()}async suspend(e){if(this.suspended)return;this.suspended=!0,await this.scheduler.joinAll();const s=[...this.session.liveTasks.values()].filter(n=>n.kind==="pi.tool");if(s.length>0){const n=[...new Set(s.map(c=>c.conversationId))].map(c=>({doc:"sticky",conversationId:c}));await this.session.commit(p,c=>{for(const t of s){const h=t.input.index,r=c.sticky(t.conversationId).turn.tools[h];r?.waitingOn!==void 0&&delete r.waitingOn}},e,{docs:n})}this.views.close(),await this.session.close(e)}registerTaskKind(e){if(e.name.startsWith("pi."))throw new Error(`task kind "${e.name}": names beginning with "pi." are reserved`);if(this.kinds.has(e.name))throw new Error(`task kind "${e.name}" already registered`);return this.session.defaults.register(e),this.kinds.set(e.name,e),this.scheduler.kick(),()=>{this.kinds.get(e.name)===e&&(this.kinds.delete(e.name),this.session.defaults.unregister(e))}}namespace(e,s,n={}){if(!/^[a-z][a-z0-9_.-]*$/i.test(e)||e.startsWith("pi."))throw new Error(`invalid namespace "${e}"`);if(this.namespaces.has(e))throw new Error(`namespace "${e}" already registered`);const c=JSON.parse(JSON.stringify(s)),t=new Map;for(const w of["rewindable","sticky","session"])for(const d of Object.keys(c[w]??{})){if(t.has(d))throw new Error(`namespace "${e}" key "${d}" is declared in more than one document`);t.set(d,w)}let h;h={id:e,unregister:l(()=>{if(this.namespaces.get(e)?.token===h){this.namespaces.delete(e);for(let w=this.hookRegistrations.length-1;w>=0;w--)this.hookRegistrations[w].namespace===h&&this.hookRegistrations.splice(w,1)}},"unregister")};const r={token:h,defaults:{rewindable:c.rewindable??{},sticky:c.sticky??{},session:c.session??{}},routes:t,project:n.view===void 0?void 0:w=>n.view(w)};return this.namespaces.set(e,r),h}registerTool(e,s="runtime"){if(this.tools.has(e.name))throw new Error(`tool "${e.name}" already registered`);return this.tools.set(e.name,e),this.revisions.tools++,()=>{this.tools.get(e.name)===e&&(this.tools.delete(e.name),this.revisions.tools++)}}registerSection(e,s="runtime"){if(this.sectionMap.has(e.key))throw new Error(`section "${e.key}" already registered`);return this.sectionMap.set(e.key,e),this.revisions.sections++,()=>{this.sectionMap.get(e.key)===e&&(this.sectionMap.delete(e.key),this.revisions.sections++)}}registerEntryKind(e){if(e.kind.startsWith("pi."))throw new Error(`entry kind "${e.kind}": names beginning with "pi." are reserved`);if(this.entryKinds.has(e.kind))throw new Error(`entry kind "${e.kind}" already registered`);return this.entryKinds.set(e.kind,e),()=>{this.entryKinds.get(e.kind)===e&&this.entryKinds.delete(e.kind)}}hooks(e,s,n,c){return this.addHooks({namespace:this.checkNamespace(e),kind:this.checkKind(s),handlers:n})}checkKind(e){if(this.kinds.get(e.name)!==e)throw new Error(`kind "${e.name}" is not the registered token`);return e}checkNamespace(e){if(this.namespaces.get(e.id)?.token!==e)throw new k(`namespace "${e.id}" is stale`);return e}addHooks(e){this.hookRegistrations.push(e);let s=!1;return()=>{if(s)return;s=!0;const n=this.hookRegistrations.indexOf(e);n>=0&&this.hookRegistrations.splice(n,1)}}async root(e){return this.conversation(1,e).then(s=>s)}onConversation(e){this.conversationListeners.add(e);for(const s of this.session.conversationRecords.values())try{e(this.handle(s))}catch(n){this.onReport(n)}return()=>this.conversationListeners.delete(e)}async conversation(e,s){const n=await this.session.read((c,t)=>c.conversation(e,t),s);return n===void 0?void 0:this.handle(n)}async createConversation(e,s){const{input:n,...c}=e,t=await this.session.commit(p,async h=>{const r=h.createConversation(c);return n!==void 0&&await h.send(r,{content:n}),r},s).then(h=>h.value);return await this.conversation(t,s)}entries(e,s){return this.session.read((n,c)=>n.scanEntries(e,c),s)}getTask(e,s){return this.session.read((n,c)=>n.task(e,c),s)}async abortInput(e,s,n){if(n!==void 0){const c=await this.session.read((t,h)=>t.input(e,h),s);if(c!==void 0&&c.conversationId!==n)throw new k(`input ${e} is outside conversation ${n}`)}return this.inputHandle(e).abort(s)}abortTask(e,s){return this.scheduler.abortTask(e,s)}markTask(e,s){return this.session.commit(p,async n=>{const c=await n.task(e);if(c===void 0)throw new Error(`task ${e} not found`);return c.status==="terminal"?"terminal":(n.markTask(e),"marked")},s).then(n=>n.value)}waitForIdle(e){return this.scheduler.waitForIdle(void 0,e)}waitForTask(e,s){return this.scheduler.waitForTask(e,s)}async close(e){await this.suspend(e)}handle(e){const s=this,n=[{doc:"rewindable",conversationId:e.id},{doc:"sticky",conversationId:e.id}],c={type:"host",conversationId:e.id},t={type:"kernel",conversationId:e.id},h=l((d,i)=>s.session.commit(c,(o,a)=>d(o,a),i,{docs:n}).then(o=>o.value),"host"),r=l((d,i)=>s.session.commit(t,d,i,{docs:n}).then(o=>o.value),"kernel"),w={get:l(d=>h(i=>{const o=i.config(e.id),a={};for(const u of s.session.defaults.route.keys())a[u]=o.get(u);return a},d),"get"),set:l((d,i)=>h(o=>{const a=o.config(e.id);for(const[u,m]of Object.entries(d)){if(m===void 0)throw new Error(`config.set(${u}): use config.reset()`);a.set(u,m)}},i),"set"),reset:l((d,i)=>h(o=>{const a=o.config(e.id);for(const u of d)a.reset(String(u))},i),"reset")};return{id:e.id,config:w,async send(d,i){const o=await r(a=>a.send(e.id,d),i);return s.inputHandle(o)},write:l((d,i)=>h(o=>o.write(e.id,d),i),"write"),commit:h,rewindable:l(d=>h(i=>i.snapshot({doc:"rewindable",conversationId:e.id}),d),"rewindable"),sticky:l(d=>h(i=>i.snapshot({doc:"sticky",conversationId:e.id}),d),"sticky"),context:l(d=>h(i=>i.context(e.id),d),"context"),async fork(d,i,o){const a=await s.session.fork(e.id,d,i,o);return await s.conversation(a,o)},collapse:l((d,i)=>r(async o=>{const{entries:a}=await o.context(e.id),u=o.rewindable(e.id),m=F(a,u.keepRecent);if(m===void 0)throw new Error("nothing to collapse");return o.createTask({kind:"pi.collapse",conversationId:e.id,background:!0,input:{reason:"manual",through:m,...d===void 0?{}:{instructions:d}}})},i),"collapse"),reset:l(async(d,i)=>{await r(o=>o.write(e.id,d===void 0?{kind:"pi.reset",head:"self"}:{kind:"pi.handoff",head:"self",model:[{role:"user",content:d,timestamp:s.now()}]}),i)},"reset"),async abort(d){const i=[],o=await r(async a=>{const u=a.sticky(e.id),m=u.inbox.filter(f=>f.mode!=="write").map(f=>f.id);for(let f=u.inbox.length-1;f>=0;f--)u.inbox[f].mode!=="write"&&u.inbox.splice(f,1);await a.resolveInputs(m,{status:"unanswered",reason:"aborted"});for(const f of m)a.emit({type:"input.aborted",input:f});const v=[];for(const f of[...s.session.liveTasks.values()])if(!(f.conversationId!==e.id||f.background)){for(const C of f.owns)i.push(C);f.abort!==!0&&a.markTask(f.id),v.push(f.id)}return v},d);for(const a of o)await s.scheduler.abortTask(a,d);await s.scheduler.waitForIdle(e.id,d),await Promise.all(i.map(a=>s.scheduler.waitForIdle(a,d)))},waitForIdle:l(d=>s.scheduler.waitForIdle(e.id,d),"waitForIdle"),hooks:l((d,i,o,a)=>s.addHooks({namespace:s.checkNamespace(d),kind:s.checkKind(i),handlers:o,conversationId:e.id,subtree:a?.subtree}),"hooks"),watch:l(d=>s.watch(e,d),"watch")}}async watch(e,s){return this.session.commit({type:"host",conversationId:e.id},async n=>{const c=await N(t=>n.scanEntries(t),e.id);return this.views.watch(e,c)},s,{docs:[{doc:"rewindable",conversationId:e.id},{doc:"sticky",conversationId:e.id}]}).then(n=>n.value)}inputHandle(e){return{id:e,result:l(s=>this.session.read((n,c)=>n.input(e,c),s),"result"),wait:l(s=>this.scheduler.waitForInput(e,s),"wait"),abort:l(s=>this.session.commit(p,n=>n.withdrawInput(e),s,{docs:[]}).then(n=>n.value),"abort")}}}async function N(g,e){const[s]=await g({conversationId:e,withHead:!0,limit:1}),n=s?.head,c=[];let t;for(;;){const h=await g({conversationId:e,...t===void 0?{}:{before:t},limit:256});let r=h.length<256;for(const w of h){if(n!==void 0&&w.id<n){r=!0;break}c.push(w)}if(r)break;t=h[h.length-1].id}return c.reverse()}l(N,"captureActiveTranscript");import{applyEnvelope as ie,WATCH_CAPACITY as oe}from"./view.js";const ee={generation:I,tool:$,postTools:R,collapse:y,job:T,plugin:E},se=b;export{O as Harness,oe as WATCH_CAPACITY,ie as applyEnvelope,N as captureActiveTranscript,se as entries,H as isCoreKind,ee as kinds,x as withAbortSignal};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=Object.defineProperty;var d=(r,a)=>f(r,"name",{value:a,configurable:!0});function p(r,a,u){return(o,c)=>{const t=d(()=>r().filter(e=>e.kind===o).filter(e=>e.conversationId===void 0||e.conversationId===c.conversationId||e.subtree===!0&&a(c.conversationId).includes(e.conversationId)).map(e=>({handlers:e.handlers,namespace:e.namespace,api:{...c,kind:o.name}})),"handlers");return{handlers:t,async each(e,i,l){for(const s of t())try{const n=await i(s.handlers,s.api);if(n!==void 0&&l?.(n)===!0)return}catch(n){if(e.abortSignal?.aborted)throw n;u(n)}}}}}d(p,"createHookRunners");export{p as createHookRunners};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{bashTool as r}from"./bash.js";import{Bounded as n}from"./bounded.js";import{attachChordView as s,createPicoConversationService as a,PicoConversationService as c,PicoHarnessService as d}from"./chord.js";import{applyEnvelope as m,captureActiveTranscript as f,entries as C,Harness as l,isCoreKind as S,kinds as v,WATCH_CAPACITY as x,withAbortSignal as y}from"./harness.js";import{JsonlStorage as P}from"./jsonl.js";import{MemoryStorage as g}from"./memory.js";import{defineSystemSection as h,systemSections as b}from"./system.js";import{Closed as F,CollapseInProgress as H,ConversationBusy as I,defineEntry as w,defineTask as B,Faulted as E,Forbidden as W,GenerationInProgress as G,memoOnce as J,ReadAfterWrite as K,TaskContractFault as M,toStored as O}from"./types.js";export{n as Bounded,F as Closed,H as CollapseInProgress,I as ConversationBusy,E as Faulted,W as Forbidden,G as GenerationInProgress,l as Harness,P as JsonlStorage,g as MemoryStorage,c as PicoConversationService,d as PicoHarnessService,K as ReadAfterWrite,M as TaskContractFault,x as WATCH_CAPACITY,m as applyEnvelope,s as attachChordView,r as bashTool,f as captureActiveTranscript,a as createPicoConversationService,w as defineEntry,h as defineSystemSection,B as defineTask,C as entries,S as isCoreKind,v as kinds,J as memoOnce,b as systemSections,O as toStored,y as withAbortSignal};
|