botmancers 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +107 -1
- package/README.md +178 -32
- package/app/.next/BUILD_ID +1 -1
- package/app/.next/app-path-routes-manifest.json +27 -1
- package/app/.next/build-manifest.json +3 -3
- package/app/.next/prerender-manifest.json +33 -5
- package/app/.next/required-server-files.json +2 -2
- package/app/.next/routes-manifest.json +198 -0
- package/app/.next/server/app/_global-error/page.js +1 -1
- package/app/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/app/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/_global-error.html +1 -1
- package/app/.next/server/app/_global-error.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/app/.next/server/app/_not-found/page.js +1 -1
- package/app/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/app/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/_not-found.html +1 -1
- package/app/.next/server/app/_not-found.rsc +2 -2
- package/app/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/app/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
- package/app/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/app/.next/server/app/api/agent-deck/decks/route.js +3 -3
- package/app/.next/server/app/api/agent-deck/decks/route.js.nft.json +1 -1
- package/app/.next/server/app/api/agent-deck/settings/route.js +3 -3
- package/app/.next/server/app/api/agent-deck/settings/route.js.nft.json +1 -1
- package/app/.next/server/app/api/bots/[id]/config/route.js +3 -3
- package/app/.next/server/app/api/bots/[id]/config/route.js.nft.json +1 -1
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/pins/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/pins/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/pins/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/pins/route.js +12 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/pins/route.js.nft.json +1 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/pins/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/route.js +9 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/route.js.nft.json +1 -0
- package/app/.next/server/app/api/bots/[id]/sessions/[ref]/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/bots/[id]/sessions/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/bots/[id]/sessions/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/bots/[id]/sessions/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/bots/[id]/sessions/route.js +12 -0
- package/app/.next/server/app/api/bots/[id]/sessions/route.js.nft.json +1 -0
- package/app/.next/server/app/api/bots/[id]/sessions/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/bots/[id]/skill/route.js +3 -3
- package/app/.next/server/app/api/bots/[id]/skill/route.js.nft.json +1 -1
- package/app/.next/server/app/api/bots/availability/route.js +2 -2
- package/app/.next/server/app/api/bots/availability/route.js.nft.json +1 -1
- package/app/.next/server/app/api/bots/delete-preview/route.js +4 -4
- package/app/.next/server/app/api/bots/delete-preview/route.js.nft.json +1 -1
- package/app/.next/server/app/api/bots/import/route.js +3 -3
- package/app/.next/server/app/api/bots/import/route.js.nft.json +1 -1
- package/app/.next/server/app/api/bots/manage/route.js +3 -3
- package/app/.next/server/app/api/bots/manage/route.js.nft.json +1 -1
- package/app/.next/server/app/api/bots/name-migrations/route.js +3 -3
- package/app/.next/server/app/api/bots/name-migrations/route.js.nft.json +1 -1
- package/app/.next/server/app/api/bots/route.js +7 -7
- package/app/.next/server/app/api/bots/route.js.nft.json +1 -1
- package/app/.next/server/app/api/conversations/[id]/approve/route.js +3 -3
- package/app/.next/server/app/api/conversations/[id]/approve/route.js.nft.json +1 -1
- package/app/.next/server/app/api/conversations/[id]/deny/route.js +3 -3
- package/app/.next/server/app/api/conversations/[id]/deny/route.js.nft.json +1 -1
- package/app/.next/server/app/api/conversations/[id]/draft/route.js +3 -3
- package/app/.next/server/app/api/conversations/[id]/draft/route.js.nft.json +1 -1
- package/app/.next/server/app/api/conversations/[id]/messages/[messageId]/stop/route.js +3 -3
- package/app/.next/server/app/api/conversations/[id]/messages/[messageId]/stop/route.js.nft.json +1 -1
- package/app/.next/server/app/api/conversations/[id]/messages/route.js +6 -6
- package/app/.next/server/app/api/conversations/[id]/messages/route.js.nft.json +1 -1
- package/app/.next/server/app/api/conversations/[id]/route.js +3 -3
- package/app/.next/server/app/api/conversations/[id]/route.js.nft.json +1 -1
- package/app/.next/server/app/api/conversations/[id]/stop/route.js +4 -4
- package/app/.next/server/app/api/conversations/[id]/stop/route.js.nft.json +1 -1
- package/app/.next/server/app/api/conversations/route.js +3 -3
- package/app/.next/server/app/api/conversations/route.js.nft.json +1 -1
- package/app/.next/server/app/api/exchanges/[id]/cancel/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/exchanges/[id]/cancel/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/exchanges/[id]/cancel/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/exchanges/[id]/cancel/route.js +11 -0
- package/app/.next/server/app/api/exchanges/[id]/cancel/route.js.nft.json +1 -0
- package/app/.next/server/app/api/exchanges/[id]/cancel/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/exchanges/[id]/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/exchanges/[id]/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/exchanges/[id]/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/exchanges/[id]/route.js +11 -0
- package/app/.next/server/app/api/exchanges/[id]/route.js.nft.json +1 -0
- package/app/.next/server/app/api/exchanges/[id]/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/exchanges/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/exchanges/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/exchanges/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/exchanges/route.js +12 -0
- package/app/.next/server/app/api/exchanges/route.js.nft.json +1 -0
- package/app/.next/server/app/api/exchanges/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/files/[name]/route.js +3 -2
- package/app/.next/server/app/api/files/[name]/route.js.nft.json +1 -1
- package/app/.next/server/app/api/groups/route.js +3 -3
- package/app/.next/server/app/api/groups/route.js.nft.json +1 -1
- package/app/.next/server/app/api/health/route.js +3 -2
- package/app/.next/server/app/api/health/route.js.nft.json +1 -1
- package/app/.next/server/app/api/import-capabilities/route.js +1 -1
- package/app/.next/server/app/api/import-capabilities/route.js.nft.json +1 -1
- package/app/.next/server/app/api/marketplace-handoff/route.js +1 -1
- package/app/.next/server/app/api/marketplace-handoff/route.js.nft.json +1 -1
- package/app/.next/server/app/api/marketplace-handoff/status/route.js +1 -1
- package/app/.next/server/app/api/marketplace-handoff/status/route.js.nft.json +1 -1
- package/app/.next/server/app/api/mcp/route.js +3 -3
- package/app/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/app/.next/server/app/api/messages/[id]/between/route.js +3 -3
- package/app/.next/server/app/api/messages/[id]/between/route.js.nft.json +1 -1
- package/app/.next/server/app/api/runtime-connections/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/runtime-connections/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/runtime-connections/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/runtime-connections/route.js +9 -0
- package/app/.next/server/app/api/runtime-connections/route.js.nft.json +1 -0
- package/app/.next/server/app/api/runtime-connections/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/service-grants/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/service-grants/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/service-grants/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/service-grants/route.js +9 -0
- package/app/.next/server/app/api/service-grants/route.js.nft.json +1 -0
- package/app/.next/server/app/api/service-grants/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/[conversationId]/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/[conversationId]/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/[conversationId]/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/[conversationId]/route.js +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/[conversationId]/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/[conversationId]/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/route.js +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/conversations/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/messages/route.js +5 -4
- package/app/.next/server/app/api/v0/agents/[agentId]/messages/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v0/agents/[agentId]/pins/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/pins/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/pins/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/pins/route.js +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/pins/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/pins/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/route.js +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/[ref]/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/[ref]/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/[ref]/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/[ref]/route.js +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/[ref]/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/[ref]/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/route.js +12 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/agents/[agentId]/sessions/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/agents/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/agents/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/agents/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/agents/route.js +12 -0
- package/app/.next/server/app/api/v0/agents/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/agents/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/capabilities/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/capabilities/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/capabilities/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/capabilities/route.js +12 -0
- package/app/.next/server/app/api/v0/capabilities/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/capabilities/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/conversations/[id]/route.js +5 -4
- package/app/.next/server/app/api/v0/conversations/[id]/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v0/exchanges/[id]/cancel/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/cancel/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/cancel/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/cancel/route.js +12 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/cancel/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/cancel/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/route.js +12 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/exchanges/[id]/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/exchanges/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/exchanges/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/exchanges/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/exchanges/route.js +12 -0
- package/app/.next/server/app/api/v0/exchanges/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/exchanges/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/mcp/route.js +7 -4
- package/app/.next/server/app/api/v0/mcp/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v0/pins/[pinRef]/detach/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/detach/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/detach/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/detach/route.js +12 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/detach/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/detach/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/messages/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/messages/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/messages/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/messages/route.js +12 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/messages/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/messages/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/route.js +12 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/pins/[pinRef]/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/requests/[id]/route.js +5 -4
- package/app/.next/server/app/api/v0/requests/[id]/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v0/sessions/[ref]/messages/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/messages/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/messages/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/messages/route.js +12 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/messages/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/messages/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/pins/route/app-paths-manifest.json +3 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/pins/route/build-manifest.json +12 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/pins/route/server-reference-manifest.json +4 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/pins/route.js +12 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/pins/route.js.nft.json +1 -0
- package/app/.next/server/app/api/v0/sessions/[ref]/pins/route_client-reference-manifest.js +3 -0
- package/app/.next/server/app/api/wake-grants/[id]/revoke/route.js +5 -5
- package/app/.next/server/app/api/wake-grants/[id]/revoke/route.js.nft.json +1 -1
- package/app/.next/server/app/api/wakes/[id]/decision/route.js +5 -5
- package/app/.next/server/app/api/wakes/[id]/decision/route.js.nft.json +1 -1
- package/app/.next/server/app/api/wakes/[id]/retry/route.js +5 -5
- package/app/.next/server/app/api/wakes/[id]/retry/route.js.nft.json +1 -1
- package/app/.next/server/app/bots/[id]/config/page.js +1 -1
- package/app/.next/server/app/bots/[id]/config/page.js.nft.json +1 -1
- package/app/.next/server/app/bots/[id]/config/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/exchanges/page/app-paths-manifest.json +3 -0
- package/app/.next/server/app/exchanges/page/build-manifest.json +20 -0
- package/app/.next/server/app/exchanges/page/next-font-manifest.json +11 -0
- package/app/.next/server/app/exchanges/page/react-loadable-manifest.json +1 -0
- package/app/.next/server/app/exchanges/page/server-reference-manifest.json +4 -0
- package/app/.next/server/app/exchanges/page.js +13 -0
- package/app/.next/server/app/exchanges/page.js.nft.json +1 -0
- package/app/.next/server/app/exchanges/page_client-reference-manifest.js +3 -0
- package/app/.next/server/app/exchanges.html +1 -0
- package/app/.next/server/app/exchanges.meta +34 -0
- package/app/.next/server/app/exchanges.rsc +22 -0
- package/app/.next/server/app/exchanges.segments/_full.segment.rsc +22 -0
- package/app/.next/server/app/exchanges.segments/_tree.segment.rsc +4 -0
- package/app/.next/server/app/exchanges.segments/exchanges/__PAGE__.segment.rsc +26 -0
- package/app/.next/server/app/index.html +1 -1
- package/app/.next/server/app/index.rsc +3 -3
- package/app/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/app/.next/server/app/index.segments/_full.segment.rsc +3 -3
- package/app/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/app/.next/server/app/page.js +1 -1
- package/app/.next/server/app/page.js.nft.json +1 -1
- package/app/.next/server/app/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/settings/page.js +1 -1
- package/app/.next/server/app/settings/page.js.nft.json +1 -1
- package/app/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/settings.html +1 -1
- package/app/.next/server/app/settings.rsc +3 -3
- package/app/.next/server/app/settings.segments/_full.segment.rsc +3 -3
- package/app/.next/server/app/settings.segments/_tree.segment.rsc +2 -2
- package/app/.next/server/app/settings.segments/settings/__PAGE__.segment.rsc +3 -3
- package/app/.next/server/app/threads/[id]/page/app-paths-manifest.json +3 -0
- package/app/.next/server/app/threads/[id]/page/build-manifest.json +20 -0
- package/app/.next/server/app/threads/[id]/page/next-font-manifest.json +11 -0
- package/app/.next/server/app/threads/[id]/page/react-loadable-manifest.json +1 -0
- package/app/.next/server/app/threads/[id]/page/server-reference-manifest.json +4 -0
- package/app/.next/server/app/threads/[id]/page.js +13 -0
- package/app/.next/server/app/threads/[id]/page.js.nft.json +1 -0
- package/app/.next/server/app/threads/[id]/page_client-reference-manifest.js +3 -0
- package/app/.next/server/app-paths-manifest.json +27 -1
- package/app/.next/server/chunks/0ivl_api_v0_agents_[agentId]_conversations_[conversationId]_route_actions_0lvijtu.js +3 -0
- package/app/.next/server/chunks/1oeh_server_app_api_bots_[id]_sessions_[ref]_pins_route_actions_0e1st6o.js +3 -0
- package/app/.next/server/chunks/1oeh_server_app_api_v0_agents_[agentId]_conversations_route_actions_0ko3117.js +3 -0
- package/app/.next/server/chunks/1oeh_server_app_api_v0_agents_[agentId]_sessions_[ref]_route_actions_0o7q3vt.js +3 -0
- package/app/.next/server/chunks/{[externals]__18bqksw._.js → [externals]__06lqs5i._.js} +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__1vxmbdl._.js → [root-of-the-server]__0-45blq._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__02kssr-._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__06qkt0f._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__08qhrch._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__097ptn_._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__09m9-pe._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__0b7w1z3._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__0f5yqjs._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__0g4um3-._.js +44 -0
- package/app/.next/server/chunks/[root-of-the-server]__0hro5ey._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__0hwpgxq._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__0izjfmr._.js +582 -55
- package/app/.next/server/chunks/{[root-of-the-server]__07l_rgn._.js → [root-of-the-server]__0j0i8xz._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0lwsto-._.js +5 -0
- package/app/.next/server/chunks/[root-of-the-server]__0s1enbp._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__0uq7sci._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__0wg992i._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__13cd2fb._.js +44 -0
- package/app/.next/server/chunks/[root-of-the-server]__17mum5-._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1879cge._.js +3 -0
- package/app/.next/server/chunks/{[root-of-the-server]__17oz13o._.js → [root-of-the-server]__1_01-13._.js} +3 -3
- package/app/.next/server/chunks/[root-of-the-server]__1a2dh11._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1bhzfu_._.js +7 -0
- package/app/.next/server/chunks/{[root-of-the-server]__1khwkvb._.js → [root-of-the-server]__1c3e2ds._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__1co3sok._.js +44 -0
- package/app/.next/server/chunks/[root-of-the-server]__1eh30sp._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1fmsid0._.js +44 -0
- package/app/.next/server/chunks/[root-of-the-server]__1i388e2._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1kvvs4u._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1qbgs3m._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1s6h1sj._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1slu7d7._.js +7 -0
- package/app/.next/server/chunks/[root-of-the-server]__1tuqc5v._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1v609eq._.js +44 -0
- package/app/.next/server/chunks/[root-of-the-server]__1y_j43n._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1zdv-vb._.js +3 -0
- package/app/.next/server/chunks/[root-of-the-server]__1zjs2tr._.js +3 -0
- package/app/.next/server/chunks/_0061c2q._.js +3 -0
- package/app/.next/server/chunks/_023se5j._.js +44 -0
- package/app/.next/server/chunks/_02pb_qv._.js +44 -0
- package/app/.next/server/chunks/_05ro-21._.js +44 -0
- package/app/.next/server/chunks/_07on0dc._.js +44 -0
- package/app/.next/server/chunks/_08208nz._.js +44 -0
- package/app/.next/server/chunks/_0a2do3x._.js +1 -1
- package/app/.next/server/chunks/_0fe5qz5._.js +44 -0
- package/app/.next/server/chunks/_0i8_xso._.js +3 -0
- package/app/.next/server/chunks/_0qoji5a._.js +44 -0
- package/app/.next/server/chunks/_0uv2pi5._.js +44 -0
- package/app/.next/server/chunks/_0wdl90-._.js +44 -0
- package/app/.next/server/chunks/_1-5mthb._.js +1 -1
- package/app/.next/server/chunks/_11-q8k1._.js +3 -0
- package/app/.next/server/chunks/_11ijk9k._.js +44 -0
- package/app/.next/server/chunks/_198sn69._.js +44 -0
- package/app/.next/server/chunks/_1ba_5hd._.js +44 -0
- package/app/.next/server/chunks/_1ess5if._.js +3 -0
- package/app/.next/server/chunks/_1i0zod4._.js +3 -0
- package/app/.next/server/chunks/_1m89jq5._.js +44 -0
- package/app/.next/server/chunks/_1n39wr_._.js +44 -0
- package/app/.next/server/chunks/_1ryxqo1._.js +44 -0
- package/app/.next/server/chunks/_1vemgly._.js +44 -0
- package/app/.next/server/chunks/_20azcus._.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_bots_[id]_sessions_[ref]_route_actions_02gp9-5.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_bots_[id]_sessions_route_actions_1s_wxg4.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_exchanges_[id]_cancel_route_actions_0lh0fl4.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_exchanges_[id]_route_actions_1w4jhin.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_exchanges_route_actions_028wchg.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_runtime-connections_route_actions_06rulng.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_service-grants_route_actions_1459xk1.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_agents_[agentId]_pins_route_actions_08uftk9.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_agents_[agentId]_route_actions_127sxvv.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_agents_[agentId]_sessions_route_actions_0pm6tcu.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_agents_route_actions_00azkhd.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_capabilities_route_actions_0d-eefd.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_exchanges_[id]_cancel_route_actions_1hb2q7i.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_exchanges_[id]_route_actions_098f50-.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_exchanges_route_actions_1ftmhhm.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_pins_[pinRef]_detach_route_actions_0nk3268.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_pins_[pinRef]_messages_route_actions_1wenu96.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_pins_[pinRef]_route_actions_0z7fu_c.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_sessions_[ref]_messages_route_actions_1-rgf_k.js +3 -0
- package/app/.next/server/chunks/_next-internal_server_app_api_v0_sessions_[ref]_pins_route_actions_0y3ere3.js +3 -0
- package/app/.next/server/chunks/lib_0kik6bx._.js +1 -1
- package/app/.next/server/chunks/lib_0lqoyb4._.js +217 -0
- package/app/.next/server/chunks/lib_0pe3tiv._.js +1 -1
- package/app/.next/server/chunks/lib_0riiofz._.js +44 -0
- package/app/.next/server/chunks/lib_16j2293._.js +217 -0
- package/app/.next/server/chunks/lib_1nb_61e._.js +217 -0
- package/app/.next/server/chunks/lib_service-api-http_ts_0xzqhny._.js +25 -0
- package/app/.next/server/chunks/lib_session-pins_ts_0lmxnwj._.js +20 -0
- package/app/.next/server/chunks/ssr/{[root-of-the-server]__0sq4frf._.js → [root-of-the-server]__03186rx._.js} +1 -1
- package/app/.next/server/chunks/ssr/[root-of-the-server]__03xw2d9._.js +3 -0
- package/app/.next/server/chunks/ssr/{[root-of-the-server]__1x7o-fe._.js → [root-of-the-server]__0zzcbqg._.js} +1 -1
- package/app/.next/server/chunks/ssr/{[root-of-the-server]__029oxo_._.js → [root-of-the-server]__1feicqq._.js} +1 -1
- package/app/.next/server/chunks/ssr/[root-of-the-server]__1t063pe._.js +3 -0
- package/app/.next/server/chunks/ssr/_0epgorw._.js +3 -0
- package/app/.next/server/chunks/ssr/_1cvuhjt._.js +3 -0
- package/app/.next/server/chunks/ssr/_1n5mvo5._.js +3 -0
- package/app/.next/server/chunks/ssr/_1o94bnv._.js +1 -1
- package/app/.next/server/chunks/ssr/_next-internal_server_app_exchanges_page_actions_0hcso2x.js +3 -0
- package/app/.next/server/chunks/ssr/_next-internal_server_app_threads_[id]_page_actions_1fte2n3.js +3 -0
- package/app/.next/server/chunks/ssr/app_bots_[id]_config_page_tsx_1e0uue9._.js +3 -0
- package/app/.next/server/chunks/ssr/app_components_AgentDeckRuntime_tsx_024janf._.js +3 -0
- package/app/.next/server/chunks/ssr/app_components_ExchangeCard_tsx_1shfcgn._.js +3 -0
- package/app/.next/server/chunks/ssr/app_exchanges_page_tsx_0j-n2a1._.js +3 -0
- package/app/.next/server/chunks/ssr/node_modules_1nkgb45._.js +23 -0
- package/app/.next/server/chunks/ssr/node_modules_next_0x3i8za._.js +131 -0
- package/app/.next/server/middleware-build-manifest.js +3 -3
- package/app/.next/server/middleware.js +1 -1
- package/app/.next/server/next-font-manifest.js +1 -1
- package/app/.next/server/next-font-manifest.json +8 -0
- package/app/.next/server/pages/404.html +1 -1
- package/app/.next/server/pages/500.html +1 -1
- package/app/.next/server/prefetch-hints.json +14 -0
- package/app/.next/server/server-reference-manifest.js +1 -1
- package/app/.next/server/server-reference-manifest.json +1 -1
- package/app/.next/static/chunks/0bhd8eso48g27.js +1 -0
- package/app/.next/static/chunks/1ku9himlsx-hn.js +1 -0
- package/app/.next/static/chunks/21aqekm5z0j47.js +1 -0
- package/app/.next/static/chunks/2a8bomryx66oj.css +3 -0
- package/app/.next/static/chunks/3230ywnpii0s6.js +3 -0
- package/app/.next/static/chunks/35l2c95bd-jud.js +1 -0
- package/app/.next/static/chunks/3cijpn6vx3yzv.js +1 -0
- package/app/.next/static/chunks/3ue9194j59kem.js +1 -0
- package/app/.next/static/chunks/44ese2s4gzze_.js +1 -0
- package/app/BUILD_INFO.json +2 -2
- package/app/package.json +1 -1
- package/app/server.js +1 -1
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +35 -7
- package/dist/clients.d.ts +86 -0
- package/dist/clients.js +639 -0
- package/dist/config.d.ts +2 -1
- package/dist/config.js +7 -6
- package/dist/contract.d.ts +7 -1
- package/dist/contract.js +33 -8
- package/dist/home.d.ts +1 -1
- package/dist/home.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/managed.js +7 -0
- package/dist/product.d.ts +2 -0
- package/dist/product.js +7 -1
- package/dist/server.js +5 -4
- package/dist/upstream.js +21 -7
- package/package.json +7 -6
- package/schemas/botmancers.mcp.v2.tools.json +4565 -0
- package/skills/botmancers-collaboration/SKILL.md +114 -0
- package/skills/botmancers-collaboration/references/workflows.md +281 -0
- package/app/.next/server/chunks/[root-of-the-server]__08i4wq6._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__09d-yrq._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__0ab4e_k._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__0qozubc._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__0za34e1._.js +0 -7
- package/app/.next/server/chunks/[root-of-the-server]__10m3szc._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__19hjzs0._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__1afl75n._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__1fjpie4._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__1kvvdpx._.js +0 -7
- package/app/.next/server/chunks/[root-of-the-server]__1qanlbg._.js +0 -3
- package/app/.next/server/chunks/[root-of-the-server]__1qoa704._.js +0 -7
- package/app/.next/server/chunks/[root-of-the-server]__20wve4_._.js +0 -3
- package/app/.next/server/chunks/_0ggf7vy._.js +0 -3
- package/app/.next/server/chunks/_0gtqbub._.js +0 -3
- package/app/.next/server/chunks/_0i7ga8c._.js +0 -3
- package/app/.next/server/chunks/_0orubev._.js +0 -3
- package/app/.next/server/chunks/_0sfpe9z._.js +0 -3
- package/app/.next/server/chunks/_0th2j4w._.js +0 -3
- package/app/.next/server/chunks/_1ee4ej2._.js +0 -3
- package/app/.next/server/chunks/_1esxu1s._.js +0 -3
- package/app/.next/server/chunks/_1gn7eh7._.js +0 -3
- package/app/.next/server/chunks/_1gw7qwf._.js +0 -3
- package/app/.next/server/chunks/_1inyx08._.js +0 -3
- package/app/.next/server/chunks/_1kjsnlr._.js +0 -3
- package/app/.next/server/chunks/_1p8rola._.js +0 -3
- package/app/.next/server/chunks/app_api_import-capabilities_route_ts_013w1kt._.js +0 -3
- package/app/.next/server/chunks/lib_051fv4x._.js +0 -111
- package/app/.next/server/chunks/lib_07adeq3._.js +0 -111
- package/app/.next/server/chunks/lib_draft_ts_1atoius._.js +0 -3
- package/app/.next/server/chunks/ssr/_0k_7i66._.js +0 -131
- package/app/.next/server/chunks/ssr/_1flnty7._.js +0 -23
- package/app/.next/server/chunks/ssr/app_components_0bhuhd-._.js +0 -3
- package/app/.next/server/chunks/ssr/app_components_0w2_b3t._.js +0 -3
- package/app/.next/static/chunks/0774d7ob6aze_.js +0 -1
- package/app/.next/static/chunks/0d3ein53nlgja.js +0 -1
- package/app/.next/static/chunks/0qbtymorcz-l9.js +0 -3
- package/app/.next/static/chunks/3wdlh25l1vww9.js +0 -1
- package/app/.next/static/chunks/3zqbpbm93yqzh.css +0 -3
- /package/app/.next/static/{u4r8RPgEfpxk-DGXeKV6g → gh3shm8hnVqXLr75rmvsL}/_buildManifest.js +0 -0
- /package/app/.next/static/{u4r8RPgEfpxk-DGXeKV6g → gh3shm8hnVqXLr75rmvsL}/_clientMiddlewareManifest.js +0 -0
- /package/app/.next/static/{u4r8RPgEfpxk-DGXeKV6g → gh3shm8hnVqXLr75rmvsL}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,41 @@
|
|
|
1
|
-
module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",()=>require("better-sqlite3-90e2652d1716b047"))},62294,64974,11626,35613,30098,e=>{"use strict";var t=e.i(85148),n=e.i(22734),r=e.i(14747),i=e.i(54799),a=e.i(62349),s=e.i(16979);let o=Object.freeze(["conversation","implementation","review","revision"]),d=Object.freeze(["readonly","edit"]);Object.freeze(["ui","api","wake","continuation"]);let _=Object.freeze({conversation:"readonly",implementation:"edit",review:"readonly",revision:"edit"});function E(e){return"string"==typeof e&&o.includes(e)}function u(e,t){return{ok:!1,code:e,reason:t}}function c(e){var t,n,r,i;if(!E(e.executionKind))return u("unknown_execution_kind",`Unknown execution kind ${JSON.stringify(String(e.executionKind))}.`);let a=e.executionKind,s=(t=e.entryPoint,n=a,r=e.wakeSyntax,i=!0===e.resumesWorkRequest,"ui"===t||"api"===t?"conversation"!==n?{code:"unsupported_authority",reason:`A direct message runs as a read-only conversation turn, not ${n}.`}:"direct_message_conversation":"continuation"===t?"conversation"!==n?{code:"unsupported_authority",reason:`A coordinator continuation runs as a read-only conversation turn, not ${n}.`}:"coordinator_continuation":"wake"!==t?{code:"unsupported_authority",reason:"Unknown policy entry point."}:"legacy"===r?"conversation"!==n?{code:"unsupported_authority",reason:`A legacy WAKE directive runs as a conversation turn, not ${n}.`}:"legacy_wake_conversation":"structured"!==r?{code:"unsupported_authority",reason:"Unknown Wake syntax."}:"revision"===n!==i?{code:"unsupported_authority",reason:"revision"===n?"A revision names the Work Request it resumes.":"Only a revision resumes a Work Request."}:"structured_wake");return"string"!=typeof s?u(s.code,s.reason):{ok:!0,policy:Object.freeze({policy_version:1,execution_kind:a,tool_profile:_[a],entry_point:e.entryPoint,rule:s})}}let T=new Set(["policy_version","execution_kind","tool_profile","entry_point","rule"]);function l(e){if(!e||"object"!=typeof e||Array.isArray(e))return u("malformed_policy","The execution policy snapshot is missing.");let t=Object.keys(e);if(t.length!==T.size||t.some(e=>!T.has(e)))return u("malformed_policy","The execution policy snapshot has unexpected fields.");if(1!==e.policy_version)return u("malformed_policy","Unsupported execution policy version.");if(!E(e.execution_kind))return u("unknown_execution_kind",`Unknown execution kind ${JSON.stringify(String(e.execution_kind))}.`);if(!d.includes(e.tool_profile))return u("unsupported_authority",`Unsupported tool profile ${JSON.stringify(String(e.tool_profile))}.`);if(_[e.execution_kind]!==e.tool_profile)return u("unsupported_authority",`Execution kind ${e.execution_kind} requires the ${_[e.execution_kind]} tool profile.`);let n={direct_message_conversation:{entry:["ui","api"],kinds:["conversation"]},legacy_wake_conversation:{entry:["wake"],kinds:["conversation"]},coordinator_continuation:{entry:["continuation"],kinds:["conversation"]},structured_wake:{entry:["wake"],kinds:[...o]}},r="string"==typeof e.rule?n[e.rule]:void 0;return r&&r.entry.includes(e.entry_point)?r.kinds.includes(e.execution_kind)?{ok:!0,policy:Object.freeze({...e})}:u("unsupported_authority",`Rule ${e.rule} does not grant ${e.execution_kind}.`):u("malformed_policy","The execution policy rule does not match its entry point.")}e.s(["TOOL_PROFILE_FOR_KIND",0,_,"authorizeWorkRequest",0,function(e){let t;if(!E(e.execution_kind))return u("unknown_execution_kind",`Unknown execution kind ${JSON.stringify(String(e.execution_kind))}.`);try{t="string"==typeof e.policy_snapshot?JSON.parse(e.policy_snapshot):null}catch{return u("malformed_policy","The policy snapshot is not valid JSON.")}let n=l(t&&"object"==typeof t&&!Array.isArray(t)?t.execution_policy:void 0);return n.ok?n.policy.execution_kind!==e.execution_kind||n.policy.tool_profile!==e.tool_profile?u("unsupported_authority","The Work Request authority does not match its policy snapshot."):t.tool_profile!==e.tool_profile?u("malformed_policy","The policy snapshot tool profile does not match the Work Request."):n:n},"isExecutionKind",0,E,"selectExecutionPolicy",0,c,"validateExecutionPolicy",0,l],64974);let p=Object.freeze({max_attempts:1,base_delay_ms:1e3,max_delay_ms:6e4,attempt_timeout_ms:null});function N(e){if(void 0===e||!/^\d+$/.test(e.trim()))return null;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:null}function R(e=process.env){let t=N(e.BOTMANCERS_RETRY_MAX_ATTEMPTS),n=N(e.BOTMANCERS_RETRY_BASE_DELAY_MS)??p.base_delay_ms,r=N(e.BOTMANCERS_RETRY_MAX_DELAY_MS)??p.max_delay_ms,i=m({max_attempts:null===t?p.max_attempts:Math.min(t,10),base_delay_ms:n,max_delay_ms:Math.max(r,n),attempt_timeout_ms:N(e.BOTMANCERS_ATTEMPT_TIMEOUT_MS)});return{deadlineMs:N(e.BOTMANCERS_REQUEST_DEADLINE_MS),retryPolicy:i.ok?i.policy:{...p}}}function m(e){if(!e||"object"!=typeof e||Array.isArray(e))return{ok:!1,reason:"A retry policy is an object."};let t=e=>"number"==typeof e&&Number.isSafeInteger(e);if(!t(e.max_attempts)||e.max_attempts<1||e.max_attempts>10)return{ok:!1,reason:"max_attempts must be an integer from 1 to 10."};if(!t(e.base_delay_ms)||e.base_delay_ms<0)return{ok:!1,reason:"base_delay_ms must be a non-negative integer."};if(!t(e.max_delay_ms)||e.max_delay_ms<e.base_delay_ms)return{ok:!1,reason:"max_delay_ms must be an integer no smaller than base_delay_ms."};let n=e.attempt_timeout_ms??null;return null!==n&&(!t(n)||n<1)?{ok:!1,reason:"attempt_timeout_ms must be a positive integer or null."}:{ok:!0,policy:{max_attempts:e.max_attempts,base_delay_ms:e.base_delay_ms,max_delay_ms:e.max_delay_ms,attempt_timeout_ms:n}}}let L=["agent_deck_token_missing","agent_deck_unauthorized","agent_deck_forbidden"],O={unavailable:"retryable",runtime_failed:"retryable",timed_out:"retryable",launch_failed:"terminal",unsupported_authority:"terminal",result_contract:"terminal",cancelled:"terminal",session_mismatch:"manual_attention"};e.s(["attemptDeadline",0,function(e,t,n){let r=null===e.attempt_timeout_ms?null:n+e.attempt_timeout_ms;return null===r?t:null===t?r:Math.min(r,t)},"classifyFailure",0,function(e,t=null){return t&&L.includes(t)?"manual_attention":O[e??"runtime_failed"]??"terminal"},"decideRetry",0,function(e){var t;let n;if("terminal"===e.disposition)return{action:"fail",disposition:"terminal"};let r=e.attemptCount<e.policy.max_attempts;if("manual_attention"===e.disposition)return r?{action:"attention"}:{action:"fail",disposition:"terminal"};if(!r)return{action:"exhausted"};let i=e.attemptCount,a=(t=e.policy,n=Math.max(0,i-1),Math.min(t.max_delay_ms,t.base_delay_ms*2**Math.min(n,30))),s=e.now+a;return null!==e.deadlineAt&&s>=e.deadlineAt?{action:"deadline"}:{action:"retry",nextEligibleAt:s,delayMs:a,retry:i}},"requestControlDefaultsFromEnv",0,R,"storedRetryPolicy",0,function(e){if(!e)return{...p};try{let t=m(JSON.parse(e));return t.ok?t.policy:{...p}}catch{return{...p}}},"validateRetryPolicy",0,m],11626);let g=["queued","blocked","running","waiting","completed","failed","cancelled"],I=["completed","failed","cancelled"],A={queued:["running","blocked","cancelled","failed"],blocked:["queued","cancelled","failed"],running:["waiting","queued","completed","failed","cancelled"],waiting:["running","queued","cancelled","failed"],completed:[],failed:[],cancelled:[]},S=["dispatcher","ui_message","ui_continuation"];class k extends Error{code;constructor(e,t){super(t),this.code=e}}let v=I.map(e=>`'${e}'`).join(", "),f=g.map(e=>`'${e}'`).join(", "),q=[{version:1,name:"core_engine_tables",up:e=>{e.exec(`
|
|
1
|
+
module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",()=>require("better-sqlite3-90e2652d1716b047"))},62294,18966,64974,11626,40596,28420,35613,30098,e=>{"use strict";let t;var n=e.i(85148),i=e.i(22734),r=e.i(14747),s=e.i(54799),a=e.i(62349);let o=["direct","agent_deck"],_=["read_only","workspace_write"],d=["workspaces","sessions","all_provider_sessions"],E="This computer",u={mode:"read_only",allow_new_sessions:!0,allow_resume_with_edits:!1},c="Runtime connection is required. Pick the runtime this Agent uses.",l="Runtime connection not found.",T="Launch profile is required. Choose direct or agent_deck.",p="Invalid launch profile. Expected direct or agent_deck.",N="A direct launch profile does not use Agent Deck. Remove deck_id or choose agent_deck.",R="working_directory is an Agent Deck setting. Use default_workspace for a direct launch profile.",m="Session scope is required. Select workspaces, select sessions, or explicitly choose all_provider_sessions.",L="A session scope selects workspaces or sessions, not both.",g="Workspaces must be absolute paths (or start with ~/).",O="Launch policy is required. Choose read_only or workspace_write.",I=`Provider is required. Expected one of ${a.AGENTS.join("|")}.`;function A(e){return"string"==typeof e&&o.includes(e)}function S(e){return"string"==typeof e&&d.includes(e)}function k(e){return"string"==typeof e&&_.includes(e)}function f(e){return null==e?null:String(e).trim()||null}function v(e){return`rc-local-${e}`}function h(e){return`${a.AGENT_LABELS[e]} on ${E.toLowerCase()}`}function w(e){return e.startsWith("/")||"~"===e||e.startsWith("~/")}function C(e){return e.length>1?e.replace(/\/+$/,""):e}function q(e,t){let n=C(e),i=C(t);return n===i||i.startsWith("/"===n?"/":`${n}/`)}function y(e){if(null==e)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if("string"!=typeof n)return null;let e=n.trim();e&&!t.includes(e)&&t.push(e)}return t}function b(e){let t=e.session_scope_kind;if(!S(t))return null;let n=[];if(e.session_scope_items)try{let t=y(JSON.parse(e.session_scope_items));if(null===t)return null;n=t}catch{return null}return"all_provider_sessions"===t?0===n.length?{kind:t,workspaces:[],sessions:[]}:null:0===n.length?null:"workspaces"===t?{kind:t,workspaces:n,sessions:[]}:{kind:t,workspaces:[],sessions:n}}function D(e){return!0===e||1===e||"1"===e}function U(e){return k(e.policy_mode)?{mode:e.policy_mode,allow_new_sessions:D(e.allow_new_sessions),allow_resume_with_edits:D(e.allow_resume_with_edits)}:null}function F(e){return A(e.launch_profile)?e.launch_profile:null}function W(e){var t;return{runtime_connection_id:e.runtime_connection_id,launch_profile:e.launch_profile,deck_id:"agent_deck"===e.launch_profile?e.deck_id:null,working_directory:"agent_deck"===e.launch_profile?e.working_directory:null,session_scope_kind:e.session_scope.kind,session_scope_items:JSON.stringify("workspaces"===(t=e.session_scope).kind?t.workspaces:"sessions"===t.kind?t.sessions:[]),default_workspace:e.default_workspace,policy_mode:e.policy.mode,allow_new_sessions:+!!e.policy.allow_new_sessions,allow_resume_with_edits:+!!e.policy.allow_resume_with_edits,home_session_id:e.home_session_id,needs_deck_selection:0}}function X(e){let t="hermes";try{t=(0,a.normalizeAgent)(e.agent)??"hermes"}catch{t="hermes"}let n=f(e.deck_id),i=D(e.needs_deck_selection),r=f(e.working_directory)??`~/.botmancers/${e.id}`;return{runtime_connection_id:v(t),provider:t,launch_profile:n&&!i?"agent_deck":null,session_scope_kind:"workspaces",session_scope_items:JSON.stringify([r]),policy_mode:u.mode,allow_new_sessions:+!!u.allow_new_sessions,allow_resume_with_edits:+!!u.allow_resume_with_edits}}let x=["runtime_connection_id","launch_profile","session_scope","default_workspace","policy","home_session_id"];function G(e){return x.some(t=>void 0!==e[t])}function H(e,t){if(null==e||"object"!=typeof e||Array.isArray(e)||void 0===e.kind||null===e.kind||""===e.kind)return t.push(m),null;if(!S(e.kind))return t.push("Invalid session scope kind. Expected workspaces, sessions, or all_provider_sessions."),null;let n=y(e.workspaces),i=y(e.sessions);if(null===n||null===i)return t.push("session_scope.workspaces and session_scope.sessions must be lists of strings."),null;let r=e.kind;return"all_provider_sessions"===r?n.length>0||i.length>0?(t.push("all_provider_sessions takes no workspace or session list."),null):{kind:r,workspaces:[],sessions:[]}:n.length>0&&i.length>0?(t.push(L),null):"workspaces"===r?i.length>0?(t.push(L),null):0===n.length?(t.push("Select at least one workspace. An empty scope is never unrestricted."),null):n.every(w)?{kind:r,workspaces:n,sessions:[]}:(t.push(g),null):n.length>0?(t.push(L),null):0===i.length?(t.push("Select at least one session. An empty scope is never unrestricted."),null):{kind:r,workspaces:[],sessions:i}}function B(e,t){if(null==e||"object"!=typeof e||Array.isArray(e)||void 0===e.mode||null===e.mode||""===e.mode)return t.push(O),null;if(!k(e.mode))return t.push("Invalid policy mode. Expected read_only or workspace_write."),null;let n=[];for(let i of["allow_new_sessions","allow_resume_with_edits"]){let r=e[i];if(void 0===r)n.push(!1);else{if("boolean"!=typeof r)return t.push("Policy flags allow_new_sessions and allow_resume_with_edits must be true or false."),null;n.push(r)}}let i={mode:e.mode,allow_new_sessions:n[0],allow_resume_with_edits:n[1]};return i.allow_resume_with_edits&&"workspace_write"!==i.mode?(t.push("allow_resume_with_edits requires the workspace_write policy mode."),null):i}function M(e,t){if(null==e)return null;if("string"!=typeof e)return t.push(g),null;let n=e.trim();return n?w(n)?n:(t.push(g),null):null}function K(e,t,n,i){"agent_deck"!==e.launch_profile||e.deck_id||i.push(a.DECK_REQUIRED_ERROR);let r=e.session_scope;"sessions"!==r.kind||r.sessions.every(e=>n.sessionBelongsTo(t,e))||i.push("A selected session does not belong to this Agent."),e.default_workspace&&"workspaces"===r.kind&&!r.workspaces.some(t=>q(t,e.default_workspace))&&i.push("default_workspace must be inside one of the selected workspaces."),e.home_session_id&&(n.sessionBelongsTo(t,e.home_session_id)?"sessions"!==r.kind||r.sessions.includes(e.home_session_id)||i.push("home_session_id must be one of the selected sessions."):i.push("home_session_id must be one of this Agent’s own sessions."))}function Y(e,t,n){let i=f(e.runtime_connection_id);if(!i)return n.push(c),null;let r=t.getConnection(i);return r?void 0!==e.agent&&null!==e.agent&&String(e.agent).trim()&&String(e.agent).trim()!==r.provider?(n.push("agent does not match the runtime connection provider."),null):r:(n.push(l),null)}function P(e,t){try{return(0,a.parseRequestDeckId)(e)}catch(e){return t.push(e instanceof Error?e.message:String(e)),null}}function $(e){return!G(e)&&void 0!==e.deck_id}function z(e){return{runtime_connection_id:f(e.runtime_connection_id),launch_profile:F(e),deck_id:f(e.deck_id),working_directory:f(e.working_directory),session_scope:b(e),default_workspace:f(e.default_workspace),policy:U(e),home_session_id:f(e.home_session_id)}}function j(e,t){let n=z(e);return{runtime_connection_id:n.runtime_connection_id,runtime_connection:t?{id:t.id,provider:t.provider,label:t.label,host:t.host}:null,launch_profile:n.launch_profile,needs_launch_profile:null===n.launch_profile,session_scope:n.session_scope,default_workspace:n.default_workspace,policy:n.policy,home_session_id:n.home_session_id}}e.s(["LOCAL_HOST",0,E,"hasRegistrationUpdate",0,G,"isLegacyCreate",0,$,"localConnectionId",0,v,"localConnectionLabel",0,h,"migrateRegistration",0,X,"readStoredPolicy",0,U,"readStoredScope",0,b,"registrationColumns",0,W,"serializeRegistration",0,j,"storedLaunchProfile",0,F,"validateConnectionInput",0,function(e){let t=[],n=null;try{(n=(0,a.normalizeAgent)(e.provider))||t.push(I)}catch(e){t.push(e instanceof Error?e.message:String(e))}let i=f(e.label);i?i.length>80&&t.push("Connection name must be 80 characters or fewer."):t.push("Connection name is required.");let r=f(e.host)??E;for(let n of(r.length>80&&t.push("Host must be 80 characters or fewer."),["token","api_key","apiKey","credentials","password","secret"]))void 0!==e[n]&&t.push("Runtime credentials stay with the runtime; a connection stores no secrets.");return!(t.length>0)&&n&&i?{errors:t,fields:{provider:n,label:i,host:r}}:{errors:[...new Set(t)],fields:null}},"validateCreateRegistration",0,function(e,t){let n=[];if($(e)){let i="hermes";try{i=(0,a.normalizeAgent)(e.agent)??"hermes"}catch(e){n.push(e instanceof Error?e.message:String(e))}let r=P(e.deck_id,n);r||0!==n.length||n.push(a.DECK_REQUIRED_ERROR);let s=f(e.working_directory);return n.length>0?{errors:n,registration:null,provider:null}:{errors:n,provider:i,registration:{runtime_connection_id:t.localConnectionFor(i),launch_profile:"agent_deck",deck_id:r,working_directory:s,session_scope:{kind:"workspaces",workspaces:s?[s]:[],sessions:[]},default_workspace:null,policy:{...u},home_session_id:null}}}let i=Y(e,t,n),r=null;void 0===e.launch_profile||null===e.launch_profile||""===e.launch_profile?n.push(T):A(e.launch_profile)?r=e.launch_profile:n.push(p);let s=null,o=null;"direct"===r?(f(e.deck_id)&&n.push(N),f(e.working_directory)&&n.push(R)):"agent_deck"===r&&(s=P(e.deck_id,n),o=f(e.working_directory));let _=H(e.session_scope,n),d=M(e.default_workspace,n),E=B(e.policy,n),c=f(e.home_session_id);if(!i||!r||!_||!E||n.length>0)return{errors:n,registration:null,provider:null};let l={runtime_connection_id:i.id,launch_profile:r,deck_id:s,working_directory:o,session_scope:_,default_workspace:d,policy:E,home_session_id:c};return K(l,null,t,n),n.length>0?{errors:n,registration:null,provider:null}:{errors:n,registration:l,provider:i.provider}},"validateUpdateRegistration",0,function(e,t,n,i){let r=[],s=z(t),o=null;if(void 0!==n.runtime_connection_id)o=Y(n,i,r);else if(void 0!==n.agent)try{let e=(0,a.normalizeAgent)(n.agent);if(e){let t=s.runtime_connection_id?i.getConnection(s.runtime_connection_id):void 0;o=t&&t.provider===e?t:i.getConnection(i.localConnectionFor(e))??null}else r.push(`Agent is required. Expected one of ${a.AGENTS.join("|")}.`)}catch(e){r.push(e instanceof Error?e.message:String(e))}else s.runtime_connection_id?(o=i.getConnection(s.runtime_connection_id)??null)||r.push(l):r.push(c);let _=s.launch_profile;void 0!==n.launch_profile?A(n.launch_profile)?_=n.launch_profile:(r.push(null===n.launch_profile||""===n.launch_profile?T:p),_=null):void 0!==n.deck_id&&"direct"!==_&&(_="agent_deck");let d=s.deck_id,E=s.working_directory;"direct"===_?(void 0!==n.deck_id&&f(n.deck_id)&&r.push(N),void 0!==n.working_directory&&f(n.working_directory)&&r.push(R),d=null,E=null):"agent_deck"===_?(void 0!==n.deck_id?d=P(n.deck_id,r):("agent_deck"!==s.launch_profile||D(t.needs_deck_selection))&&(d=null),void 0!==n.working_directory&&(E=f(n.working_directory))):0===r.length&&r.push(T);let u=void 0!==n.session_scope?H(n.session_scope,r):s.session_scope;void 0!==n.session_scope||u||r.push(m);let L=void 0!==n.default_workspace?M(n.default_workspace,r):s.default_workspace,g=void 0!==n.policy?B(n.policy,r):s.policy;void 0!==n.policy||g||r.push(O);let I=void 0!==n.home_session_id?f(n.home_session_id):s.home_session_id;if(!o||!_||!u||!g||r.length>0)return{errors:r,registration:null,provider:null};let S={runtime_connection_id:o.id,launch_profile:_,deck_id:"agent_deck"===_?d:null,working_directory:"agent_deck"===_?E:null,session_scope:u,default_workspace:L,policy:g,home_session_id:I};return K(S,e,i,r),r.length>0?{errors:r,registration:null,provider:null}:{errors:r,registration:S,provider:o.provider}},"workspaceContains",0,q],18966);var J=e.i(16979);let Q=Object.freeze(["conversation","implementation","review","revision"]),V=Object.freeze(["readonly","edit"]);Object.freeze(["ui","api","wake","continuation","exchange"]);let Z=Object.freeze({conversation:"readonly",implementation:"edit",review:"readonly",revision:"edit"});function ee(e){return"string"==typeof e&&Q.includes(e)}function et(e,t){return{ok:!1,code:e,reason:t}}function en(e){var t,n,i,r;if(!ee(e.executionKind))return et("unknown_execution_kind",`Unknown execution kind ${JSON.stringify(String(e.executionKind))}.`);let s=e.executionKind,a=(t=e.entryPoint,n=s,i=e.wakeSyntax,r=!0===e.resumesWorkRequest,"ui"===t||"api"===t?"conversation"!==n?{code:"unsupported_authority",reason:`A direct message runs as a read-only conversation turn, not ${n}.`}:"direct_message_conversation":"continuation"===t?"conversation"!==n?{code:"unsupported_authority",reason:`A coordinator continuation runs as a read-only conversation turn, not ${n}.`}:"coordinator_continuation":"exchange"===t?"conversation"!==n?{code:"unsupported_authority",reason:`A session exchange runs as a read-only conversation turn, not ${n}.`}:"session_exchange_conversation":"wake"!==t?{code:"unsupported_authority",reason:"Unknown policy entry point."}:"legacy"===i?"conversation"!==n?{code:"unsupported_authority",reason:`A legacy WAKE directive runs as a conversation turn, not ${n}.`}:"legacy_wake_conversation":"structured"!==i?{code:"unsupported_authority",reason:"Unknown Wake syntax."}:"revision"===n!==r?{code:"unsupported_authority",reason:"revision"===n?"A revision names the Work Request it resumes.":"Only a revision resumes a Work Request."}:"structured_wake");return"string"!=typeof a?et(a.code,a.reason):{ok:!0,policy:Object.freeze({policy_version:1,execution_kind:s,tool_profile:Z[s],entry_point:e.entryPoint,rule:a})}}let ei=new Set(["policy_version","execution_kind","tool_profile","entry_point","rule"]);function er(e){if(!e||"object"!=typeof e||Array.isArray(e))return et("malformed_policy","The execution policy snapshot is missing.");let t=Object.keys(e);if(t.length!==ei.size||t.some(e=>!ei.has(e)))return et("malformed_policy","The execution policy snapshot has unexpected fields.");if(1!==e.policy_version)return et("malformed_policy","Unsupported execution policy version.");if(!ee(e.execution_kind))return et("unknown_execution_kind",`Unknown execution kind ${JSON.stringify(String(e.execution_kind))}.`);if(!V.includes(e.tool_profile))return et("unsupported_authority",`Unsupported tool profile ${JSON.stringify(String(e.tool_profile))}.`);if(Z[e.execution_kind]!==e.tool_profile)return et("unsupported_authority",`Execution kind ${e.execution_kind} requires the ${Z[e.execution_kind]} tool profile.`);let n={direct_message_conversation:{entry:["ui","api"],kinds:["conversation"]},legacy_wake_conversation:{entry:["wake"],kinds:["conversation"]},coordinator_continuation:{entry:["continuation"],kinds:["conversation"]},session_exchange_conversation:{entry:["exchange"],kinds:["conversation"]},structured_wake:{entry:["wake"],kinds:[...Q]}},i="string"==typeof e.rule?n[e.rule]:void 0;return i&&i.entry.includes(e.entry_point)?i.kinds.includes(e.execution_kind)?{ok:!0,policy:Object.freeze({...e})}:et("unsupported_authority",`Rule ${e.rule} does not grant ${e.execution_kind}.`):et("malformed_policy","The execution policy rule does not match its entry point.")}e.s(["TOOL_PROFILE_FOR_KIND",0,Z,"authorizeWorkRequest",0,function(e){let t;if(!ee(e.execution_kind))return et("unknown_execution_kind",`Unknown execution kind ${JSON.stringify(String(e.execution_kind))}.`);try{t="string"==typeof e.policy_snapshot?JSON.parse(e.policy_snapshot):null}catch{return et("malformed_policy","The policy snapshot is not valid JSON.")}let n=er(t&&"object"==typeof t&&!Array.isArray(t)?t.execution_policy:void 0);return n.ok?n.policy.execution_kind!==e.execution_kind||n.policy.tool_profile!==e.tool_profile?et("unsupported_authority","The Work Request authority does not match its policy snapshot."):t.tool_profile!==e.tool_profile?et("malformed_policy","The policy snapshot tool profile does not match the Work Request."):n:n},"isExecutionKind",0,ee,"selectExecutionPolicy",0,en,"validateExecutionPolicy",0,er],64974);let es=Object.freeze({max_attempts:1,base_delay_ms:1e3,max_delay_ms:6e4,attempt_timeout_ms:null});function ea(e){if(void 0===e||!/^\d+$/.test(e.trim()))return null;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:null}function eo(e=process.env){let t=ea(e.BOTMANCERS_RETRY_MAX_ATTEMPTS),n=ea(e.BOTMANCERS_RETRY_BASE_DELAY_MS)??es.base_delay_ms,i=ea(e.BOTMANCERS_RETRY_MAX_DELAY_MS)??es.max_delay_ms,r=e_({max_attempts:null===t?es.max_attempts:Math.min(t,10),base_delay_ms:n,max_delay_ms:Math.max(i,n),attempt_timeout_ms:ea(e.BOTMANCERS_ATTEMPT_TIMEOUT_MS)});return{deadlineMs:ea(e.BOTMANCERS_REQUEST_DEADLINE_MS),retryPolicy:r.ok?r.policy:{...es}}}function e_(e){if(!e||"object"!=typeof e||Array.isArray(e))return{ok:!1,reason:"A retry policy is an object."};let t=e=>"number"==typeof e&&Number.isSafeInteger(e);if(!t(e.max_attempts)||e.max_attempts<1||e.max_attempts>10)return{ok:!1,reason:"max_attempts must be an integer from 1 to 10."};if(!t(e.base_delay_ms)||e.base_delay_ms<0)return{ok:!1,reason:"base_delay_ms must be a non-negative integer."};if(!t(e.max_delay_ms)||e.max_delay_ms<e.base_delay_ms)return{ok:!1,reason:"max_delay_ms must be an integer no smaller than base_delay_ms."};let n=e.attempt_timeout_ms??null;return null!==n&&(!t(n)||n<1)?{ok:!1,reason:"attempt_timeout_ms must be a positive integer or null."}:{ok:!0,policy:{max_attempts:e.max_attempts,base_delay_ms:e.base_delay_ms,max_delay_ms:e.max_delay_ms,attempt_timeout_ms:n}}}let ed=["agent_deck_token_missing","agent_deck_unauthorized","agent_deck_forbidden"],eE={unavailable:"retryable",runtime_failed:"retryable",timed_out:"retryable",launch_failed:"terminal",unsupported_authority:"terminal",result_contract:"terminal",cancelled:"terminal",session_mismatch:"manual_attention"};e.s(["DEFAULT_RETRY_POLICY",0,es,"attemptDeadline",0,function(e,t,n){let i=null===e.attempt_timeout_ms?null:n+e.attempt_timeout_ms;return null===i?t:null===t?i:Math.min(i,t)},"classifyFailure",0,function(e,t=null){return t&&ed.includes(t)?"manual_attention":eE[e??"runtime_failed"]??"terminal"},"decideRetry",0,function(e){var t;let n;if("terminal"===e.disposition)return{action:"fail",disposition:"terminal"};let i=e.attemptCount<e.policy.max_attempts;if("manual_attention"===e.disposition)return i?{action:"attention"}:{action:"fail",disposition:"terminal"};if(!i)return{action:"exhausted"};let r=e.attemptCount,s=(t=e.policy,n=Math.max(0,r-1),Math.min(t.max_delay_ms,t.base_delay_ms*2**Math.min(n,30))),a=e.now+s;return null!==e.deadlineAt&&a>=e.deadlineAt?{action:"deadline"}:{action:"retry",nextEligibleAt:a,delayMs:s,retry:r}},"requestControlDefaultsFromEnv",0,eo,"storedRetryPolicy",0,function(e){if(!e)return{...es};try{let t=e_(JSON.parse(e));return t.ok?t.policy:{...es}}catch{return{...es}}},"validateRetryPolicy",0,e_],11626);let eu={cached_input_tokens:"cached_input_tokens",cachedInputTokens:"cached_input_tokens",cache_read_input_tokens:"cache_read_input_tokens",cacheReadInputTokens:"cache_read_input_tokens",cacheReadTokens:"cache_read_input_tokens",cache_creation_input_tokens:"cache_creation_input_tokens",cacheCreationInputTokens:"cache_creation_input_tokens",cacheWriteTokens:"cache_creation_input_tokens",reasoning_output_tokens:"reasoning_output_tokens",reasoningOutputTokens:"reasoning_output_tokens",reasoningTokens:"reasoning_output_tokens"};function ec(e){return null===e||"object"!=typeof e||Array.isArray(e)?null:e}function el(e){return"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=Number.MAX_SAFE_INTEGER?e:null}function eT(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<1e9?e:null}function ep(e,t,n){for(let i of t)if(i in e){let t=n(e[i]);if(null!==t)return t}return null}function eN(e,t,n){let i=e?ep(e,["input_tokens","inputTokens"],el):null,r=e?ep(e,["output_tokens","outputTokens"],el):null;return null===i&&null===r&&null===t?null:{input_tokens:i,output_tokens:r,cost_usd:t,source:n,breakdown:e?function(e){let t={};for(let[n,i]of Object.entries(eu)){let r=el(e[n]);null!==r&&void 0===t[i]&&(t[i]=r)}return Object.keys(t).length>0?t:null}(e):null}}function eR(e){let t=ec(e);if(!t)return null;let n="string"==typeof t.type?t.type:null,i=ec(t.usage);if("turn.completed"===n)return eN(i,null,"codex.turn_completed");if("result"===n)return eN(i,ep(t,["total_cost_usd","totalCostUsd","cost_usd","costUsd"],eT),"result");if(null===n||"usage"===n){let e=i??t,n=ep(e,["cost_usd","costUsd","total_cost_usd","totalCostUsd"],eT)??(i?ep(t,["cost_usd","costUsd","total_cost_usd","totalCostUsd"],eT):null);return eN(e,n,"normalized")}return null}function em(e,t){return null===e?t:null===t?e:e+t}function eL(e){let t=ec(e);if(!t)return null;let n="codex.turn_completed"===t.source||"result"===t.source||"normalized"===t.source?t.source:"normalized",i=el(t.input_tokens),r=el(t.output_tokens),s=eT(t.cost_usd);if(null===i&&null===r&&null===s)return null;let a=ec(t.breakdown),o={};if(a)for(let e of new Set(Object.values(eu))){let t=el(a[e]);null!==t&&(o[e]=t)}return{input_tokens:i,output_tokens:r,cost_usd:s,source:n,breakdown:Object.keys(o).length>0?o:null}}function eg(e){let t=t=>{var n,i;let r=null,s=0;for(let n of e){let e=n[t];null!=e&&(s++,r=(r??0)+e)}return null!==r&&"cost_usd"===t&&(r=Math.round(1e6*r)/1e6),{sum:r,known:s,total:e.length,quality:(n=s,0===(i=e.length)||0===n?"unavailable":n===i?"complete":"partial")}};return{input_tokens:t("input_tokens"),output_tokens:t("output_tokens"),cost_usd:t("cost_usd")}}function eO(e){return!!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage_samples'").get()}function eI(e,t,n,i){if(!eO(e))return;let r=eL(i.usage),a=i.now??Date.now();e.prepare(`
|
|
2
|
+
INSERT INTO usage_samples (
|
|
3
|
+
id, sample_key, agent_id, attempt_id, session_ref, turn_id, provider, source,
|
|
4
|
+
input_tokens, output_tokens, cost_usd, breakdown, observed_at, created_at, updated_at
|
|
5
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
+
ON CONFLICT(sample_key) DO UPDATE SET
|
|
7
|
+
input_tokens = COALESCE(usage_samples.input_tokens, excluded.input_tokens),
|
|
8
|
+
output_tokens = COALESCE(usage_samples.output_tokens, excluded.output_tokens),
|
|
9
|
+
cost_usd = COALESCE(usage_samples.cost_usd, excluded.cost_usd),
|
|
10
|
+
breakdown = COALESCE(usage_samples.breakdown, excluded.breakdown),
|
|
11
|
+
source = CASE WHEN usage_samples.source = 'none' THEN excluded.source ELSE usage_samples.source END,
|
|
12
|
+
updated_at = CASE
|
|
13
|
+
WHEN (usage_samples.input_tokens IS NULL AND excluded.input_tokens IS NOT NULL)
|
|
14
|
+
OR (usage_samples.output_tokens IS NULL AND excluded.output_tokens IS NOT NULL)
|
|
15
|
+
OR (usage_samples.cost_usd IS NULL AND excluded.cost_usd IS NOT NULL)
|
|
16
|
+
THEN excluded.updated_at ELSE usage_samples.updated_at END
|
|
17
|
+
`).run((0,s.randomUUID)(),t,i.agentId,n.attemptId,n.sessionRef,n.turnId,String(i.provider).slice(0,100),r?.source??"none",r?.input_tokens??null,r?.output_tokens??null,r?.cost_usd??null,r?.breakdown?JSON.stringify(r.breakdown):null,i.observedAt,a,a)}function eA(e,t,n){eI(e,`attempt:${t}`,{attemptId:t,sessionRef:null,turnId:null},n)}function eS(e,t,n){if(!eO(e))return[];let i=null===n?"":"AND b.id = ?",r=null===n?"":"AND s.session_ref = ?";return e.prepare(`
|
|
18
|
+
SELECT b.id AS ref, 'attempt' AS kind, a.attempt_number, a.kind AS turn_kind, s.provider, s.source,
|
|
19
|
+
s.input_tokens, s.output_tokens, s.cost_usd, s.observed_at, s.sample_key
|
|
20
|
+
FROM session_bindings b
|
|
21
|
+
JOIN work_attempts a ON a.id = b.source_attempt_id
|
|
22
|
+
JOIN usage_samples s ON s.attempt_id = a.id
|
|
23
|
+
WHERE b.agent_id = ? ${i}
|
|
24
|
+
UNION ALL
|
|
25
|
+
SELECT b.id AS ref, 'attempt' AS kind, a.attempt_number, a.kind AS turn_kind, s.provider, s.source,
|
|
26
|
+
s.input_tokens, s.output_tokens, s.cost_usd, s.observed_at, s.sample_key
|
|
27
|
+
FROM session_bindings b
|
|
28
|
+
JOIN work_attempts a ON a.resumed_session_binding_id = b.id AND a.id IS NOT b.source_attempt_id
|
|
29
|
+
JOIN usage_samples s ON s.attempt_id = a.id
|
|
30
|
+
WHERE b.agent_id = ? ${i}
|
|
31
|
+
UNION ALL
|
|
32
|
+
SELECT s.session_ref AS ref, 'turn' AS kind, NULL AS attempt_number, t.kind AS turn_kind, s.provider, s.source,
|
|
33
|
+
s.input_tokens, s.output_tokens, s.cost_usd, s.observed_at, s.sample_key
|
|
34
|
+
FROM usage_samples s
|
|
35
|
+
LEFT JOIN provider_session_turns t ON t.id = s.turn_id
|
|
36
|
+
WHERE s.agent_id = ? AND s.turn_id IS NOT NULL ${r}
|
|
37
|
+
ORDER BY observed_at ASC, sample_key ASC
|
|
38
|
+
`).all(...null===n?[t,t,t]:[t,n,t,n,t,n])}function ek(e){return{kind:e.kind,attempt_number:e.attempt_number,turn_kind:e.turn_kind,provider:e.provider,source:e.source,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cost_usd:e.cost_usd,observed_at:e.observed_at}}e.s(["aggregateUsage",0,eg,"normalizeUsage",0,eL,"usageFromEvent",0,eR,"usageFromEvents",0,function(e){if(!e)return null;let t=null,n=null,i=null,r=new Set;for(let s of e){let e=ec(s),a=e&&("number"==typeof e.seq||"string"==typeof e.id)?`${e.type}:${e.seq??e.id}`:null;if(a){if(r.has(a))continue;r.add(a)}let o=eR(s);o&&("result"===o.source?t=o:"codex.turn_completed"===o.source?n=null===n?o:{input_tokens:em(n.input_tokens,o.input_tokens),output_tokens:em(n.output_tokens,o.output_tokens),cost_usd:null,source:"codex.turn_completed",breakdown:function(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,i]of Object.entries(t))n[e]=(n[e]??0)+i;return n}(n.breakdown,o.breakdown)}:i=o)}return t??n??i}],40596),e.s(["agentSessionUsage",0,function(e,t){let n=new Map;for(let i of eS(e,t,null)){let e=n.get(i.ref)??[];e.push(i),n.set(i.ref,e)}return new Map([...n].map(([e,t])=>[e,eg(t)]))},"emptyUsage",0,function(){return eg([])},"recordAttemptUsageSample",0,eA,"recordTurnUsageSample",0,function(e,t,n,i){eI(e,`turn:${t}`,{attemptId:null,sessionRef:n,turnId:t},i)},"sessionUsageSamples",0,function(e,t,n){let i=eS(e,t,n);return{usage:eg(i),samples:i.map(ek)}}],28420);let ef=["queued","extracting","delivering","completed","failed","cancelled"],ev=["completed","failed","cancelled"],eh={queued:["extracting","failed","cancelled"],extracting:["delivering","completed","failed","cancelled"],delivering:["completed","failed","cancelled"],completed:[],failed:[],cancelled:[]},ew=Object.freeze({instructionChars:4e3,packetChars:16e3,packetObjectiveChars:2e3,packetListItems:20,packetItemChars:500,answerChars:16e3,replyChars:16e3,extractionOutputChars:32e3,promptChars:24e3}),eC=["queued","blocked","running","waiting","completed","failed","cancelled"],eq=["completed","failed","cancelled"],ey={queued:["running","blocked","cancelled","failed"],blocked:["queued","cancelled","failed"],running:["waiting","queued","completed","failed","cancelled"],waiting:["running","queued","cancelled","failed"],completed:[],failed:[],cancelled:[]},eb=["dispatcher","ui_message","ui_continuation"];class eD extends Error{code;constructor(e,t){super(t),this.code=e}}let eU=eq.map(e=>`'${e}'`).join(", "),eF=eC.map(e=>`'${e}'`).join(", "),eW=[{version:1,name:"core_engine_tables",up:e=>{e.exec(`
|
|
2
39
|
CREATE TABLE work_request_transitions (
|
|
3
40
|
from_state TEXT NOT NULL,
|
|
4
41
|
to_state TEXT NOT NULL,
|
|
@@ -22,7 +59,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
22
59
|
idempotency_key TEXT NOT NULL CHECK (length(idempotency_key) > 0),
|
|
23
60
|
request_hash TEXT NOT NULL,
|
|
24
61
|
policy_snapshot TEXT NOT NULL,
|
|
25
|
-
state TEXT NOT NULL CHECK (state IN (${
|
|
62
|
+
state TEXT NOT NULL CHECK (state IN (${eF})),
|
|
26
63
|
state_reason TEXT,
|
|
27
64
|
result TEXT,
|
|
28
65
|
error_code TEXT,
|
|
@@ -32,7 +69,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
32
69
|
created_at INTEGER NOT NULL,
|
|
33
70
|
updated_at INTEGER NOT NULL,
|
|
34
71
|
terminal_at INTEGER,
|
|
35
|
-
CHECK ((state IN (${
|
|
72
|
+
CHECK ((state IN (${eU})) = (terminal_at IS NOT NULL)),
|
|
36
73
|
FOREIGN KEY (source_conversation_id) REFERENCES conversations(id),
|
|
37
74
|
FOREIGN KEY (target_agent_id) REFERENCES bots(id),
|
|
38
75
|
FOREIGN KEY (parent_request_id) REFERENCES work_requests(id),
|
|
@@ -146,7 +183,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
146
183
|
END;
|
|
147
184
|
|
|
148
185
|
CREATE TRIGGER trg_work_requests_terminal BEFORE UPDATE ON work_requests
|
|
149
|
-
WHEN OLD.state IN (${
|
|
186
|
+
WHEN OLD.state IN (${eU})
|
|
150
187
|
BEGIN
|
|
151
188
|
SELECT RAISE(ABORT, 'terminal work_requests are immutable');
|
|
152
189
|
END;
|
|
@@ -218,7 +255,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
218
255
|
BEGIN
|
|
219
256
|
SELECT RAISE(ABORT, 'engine_events are append-only');
|
|
220
257
|
END;
|
|
221
|
-
`);let t=e.prepare("INSERT INTO work_request_transitions (from_state, to_state) VALUES (?, ?)");for(let e of
|
|
258
|
+
`);let t=e.prepare("INSERT INTO work_request_transitions (from_state, to_state) VALUES (?, ?)");for(let e of eC)for(let n of ey[e])t.run(e,n)}},{version:2,name:"core_engine_referential_integrity",up:e=>{e.exec(`
|
|
222
259
|
-- Foreign keys (delete side): RESTRICT. A referenced row cannot be
|
|
223
260
|
-- deleted while anything still points at it; deleteEngineRecords
|
|
224
261
|
-- removes dependants first, in one transaction.
|
|
@@ -304,7 +341,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
304
341
|
AND (b.request_id IS NULL OR br.root_request_id = r.root_request_id)
|
|
305
342
|
);
|
|
306
343
|
END;
|
|
307
|
-
`)}},{version:3,name:"core_engine_hardening",up:e=>{let t=
|
|
344
|
+
`)}},{version:3,name:"core_engine_hardening",up:e=>{let t=eC.flatMap(e=>ey[e].map(t=>`'${e}>${t}'`)).join(", ");e.exec(`
|
|
308
345
|
-- The lifecycle allowlist lives in the trigger itself, so no data
|
|
309
346
|
-- write can widen or break it. work_request_transitions stays as a
|
|
310
347
|
-- readable copy and is locked against writes.
|
|
@@ -502,7 +539,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
502
539
|
'request_waiting', 'request_completed', 'request_failed', 'request_cancelled',
|
|
503
540
|
'question', 'result', 'artifact'
|
|
504
541
|
)),
|
|
505
|
-
state TEXT CHECK (state IN (${
|
|
542
|
+
state TEXT CHECK (state IN (${eF})),
|
|
506
543
|
text TEXT NOT NULL,
|
|
507
544
|
data TEXT NOT NULL,
|
|
508
545
|
sort_at INTEGER NOT NULL,
|
|
@@ -715,7 +752,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
715
752
|
'finalization_preparing', 'finalization_committed', 'finalization_blocked',
|
|
716
753
|
'finalization_failed', 'finalization_canceled', 'finalization_rejected'
|
|
717
754
|
)),
|
|
718
|
-
state TEXT CHECK (state IN (${
|
|
755
|
+
state TEXT CHECK (state IN (${eF})),
|
|
719
756
|
text TEXT NOT NULL,
|
|
720
757
|
data TEXT NOT NULL,
|
|
721
758
|
sort_at INTEGER NOT NULL,
|
|
@@ -860,7 +897,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
860
897
|
'finalization_failed', 'finalization_canceled', 'finalization_rejected',
|
|
861
898
|
'request_cancel_requested', 'request_timed_out', 'request_retry_scheduled', 'request_retries_exhausted'
|
|
862
899
|
)),
|
|
863
|
-
state TEXT CHECK (state IN (${
|
|
900
|
+
state TEXT CHECK (state IN (${eF})),
|
|
864
901
|
text TEXT NOT NULL,
|
|
865
902
|
data TEXT NOT NULL,
|
|
866
903
|
sort_at INTEGER NOT NULL,
|
|
@@ -981,7 +1018,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
981
1018
|
'request_cancel_requested', 'request_timed_out', 'request_retry_scheduled', 'request_retries_exhausted',
|
|
982
1019
|
'wake_rejected', 'lineage_stopped'
|
|
983
1020
|
)),
|
|
984
|
-
state TEXT CHECK (state IN (${
|
|
1021
|
+
state TEXT CHECK (state IN (${eF})),
|
|
985
1022
|
text TEXT NOT NULL,
|
|
986
1023
|
data TEXT NOT NULL,
|
|
987
1024
|
sort_at INTEGER NOT NULL,
|
|
@@ -1012,14 +1049,14 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1012
1049
|
SELECT id, parent_request_id, root_request_id, wake_event_id, requester_kind, requester_id, policy_snapshot, state,
|
|
1013
1050
|
target_agent_id, execution_kind, legacy_agent_request_id, created_at
|
|
1014
1051
|
FROM work_requests ORDER BY created_at ASC, rowid ASC
|
|
1015
|
-
`).all(),n=new Map(t.map(e=>[e.id,e])),
|
|
1052
|
+
`).all(),n=new Map(t.map(e=>[e.id,e])),i=e=>{try{let t=JSON.parse(e.policy_snapshot);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}},r=new Map,a=e=>{let t=r.get(e.id);if(void 0!==t)return t;let i=[],s=new Set,a=e,o=!1;for(;a&&!s.has(a.id)&&a.root_request_id===e.root_request_id;){let t=r.get(a.id);if(void 0!==t){o=t;break}if(s.add(a.id),i.push(a),null===a.parent_request_id){o=a.id===e.root_request_id;break}a=n.get(a.parent_request_id)}for(let e of i)r.set(e.id,o);return o},o=new Map,_=e=>{let t=o.get(e.id);if(void 0!==t)return t;let r=0,s=e.parent_request_id?n.get(e.parent_request_id):void 0;if(s){let t=_(s),n=i(e);r=e.wake_event_id?t+1:"coordinator_continuation"===n.source&&"result"===n.continues?Math.max(t-1,0):t}return o.set(e.id,r),r},d=e.prepare("UPDATE work_requests SET wake_depth = ?, root_principal_kind = ?, root_principal_id = ? WHERE id = ?"),E=e.prepare(`
|
|
1016
1053
|
INSERT INTO wake_safety_decisions (
|
|
1017
1054
|
id, request_id, sequence, wake_id, principal_type, principal_kind, principal_id, target_agent_id, execution_kind,
|
|
1018
1055
|
decision, reason_code, grant_rule, grant_id, policy_snapshot, created_at
|
|
1019
1056
|
) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, 'allowed', NULL, 'pre_safety_migration', NULL, ?, ?)
|
|
1020
|
-
`);for(let
|
|
1057
|
+
`);for(let r of(e.exec("DROP TRIGGER trg_work_requests_terminal"),t)){let e=n.get(r.root_request_id),t=!!e&&a(r),o=t?_(r):0,u=t&&e?{kind:e.requester_kind,id:e.requester_id}:{kind:"unknown",id:"unknown"};if(d.run(o,u.kind,u.id,r.id),null===r.legacy_agent_request_id&&["queued","running","waiting"].includes(r.state)){let e=i(r),t="wake"===e.source?"agent_principal":"coordinator_continuation"===e.source?"engine":"api"===e.surface?"api_principal":"human_owner";E.run((0,s.randomUUID)(),r.id,r.wake_event_id,t,r.requester_kind,r.requester_id,r.target_agent_id,r.execution_kind,JSON.stringify({safety_version:1,migrated:!0,root_principal:u,wake_depth:o,grant_rule:"pre_safety_migration"}),r.created_at)}}e.exec(`
|
|
1021
1058
|
CREATE TRIGGER trg_work_requests_terminal BEFORE UPDATE ON work_requests
|
|
1022
|
-
WHEN OLD.state IN (${
|
|
1059
|
+
WHEN OLD.state IN (${eU})
|
|
1023
1060
|
BEGIN
|
|
1024
1061
|
SELECT RAISE(ABORT, 'terminal work_requests are immutable');
|
|
1025
1062
|
END;
|
|
@@ -1031,7 +1068,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1031
1068
|
BEGIN
|
|
1032
1069
|
SELECT RAISE(ABORT, 'work_requests wake depth and root principal are immutable');
|
|
1033
1070
|
END;
|
|
1034
|
-
`)}},{version:14,name:"retire_legacy_agent_requests",up:e=>{!function(e){let t=t=>!!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t);if(!t("agent_requests"))return;let n=t("agent_request_events"),
|
|
1071
|
+
`)}},{version:14,name:"retire_legacy_agent_requests",up:e=>{!function(e){let t=t=>!!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t);if(!t("agent_requests"))return;let n=t("agent_request_events"),i=e.prepare(`
|
|
1035
1072
|
SELECT r.*, m.content AS content FROM agent_requests r
|
|
1036
1073
|
JOIN conversations c ON c.id = r.conversation_id
|
|
1037
1074
|
JOIN bots b ON b.id = r.target_bot_id
|
|
@@ -1040,14 +1077,14 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1040
1077
|
AND r.principal_kind IN ('person', 'bot', 'service')
|
|
1041
1078
|
AND NOT EXISTS (SELECT 1 FROM work_requests w WHERE w.legacy_agent_request_id = r.id)
|
|
1042
1079
|
ORDER BY r.created_at ASC, r.rowid ASC
|
|
1043
|
-
`).all(),
|
|
1080
|
+
`).all(),r=e.prepare("SELECT 1 FROM work_requests WHERE requester_kind = ? AND requester_id = ? AND idempotency_key = ?"),a=n?e.prepare("SELECT type, data, created_at FROM agent_request_events WHERE request_id = ? ORDER BY created_at ASC, rowid ASC"):null,o=e.prepare(`
|
|
1044
1081
|
INSERT INTO work_requests (
|
|
1045
1082
|
id, source_conversation_id, source_event_id, requester_kind, requester_id, target_agent_id,
|
|
1046
1083
|
intent, execution_kind, tool_profile, parent_request_id, root_request_id, wake_event_id, depth,
|
|
1047
1084
|
idempotency_key, request_hash, policy_snapshot, state, state_reason, result, error_code, error_message,
|
|
1048
1085
|
version, legacy_agent_request_id, created_at, updated_at, terminal_at, root_principal_kind, root_principal_id
|
|
1049
1086
|
) VALUES (?, ?, ?, ?, ?, ?, ?, 'conversation', 'readonly', NULL, ?, NULL, 0, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)
|
|
1050
|
-
`),
|
|
1087
|
+
`),_=e.prepare("INSERT INTO engine_events (id, request_id, sequence, attempt_id, type, data, created_at) VALUES (?, ?, ?, NULL, ?, ?, ?)"),d=Date.now();for(let e of i){if(r.get(e.principal_kind,e.principal_id,e.idempotency_key))continue;let t=(0,s.randomUUID)(),n=eB({sourceConversationId:e.conversation_id,sourceEventId:e.accepted_message_id,targetAgentId:e.target_bot_id,intent:e.content,executionKind:"conversation",toolProfile:"readonly"}),i="accepted"===e.state||"dispatched"===e.state,E=JSON.stringify({tool_profile:"readonly",source:"legacy_agent_requests",legacy_operation:e.operation,legacy_runtime:e.runtime,...i?{legacy_state:e.state}:{}}),u=i?Math.max(d,e.updated_at):e.updated_at;o.run(t,e.conversation_id,e.accepted_message_id,e.principal_kind,e.principal_id,e.target_bot_id,e.content,t,e.idempotency_key,n,E,i?"failed":e.state,i?eM:null,"completed"===e.state?JSON.stringify({reply_message_id:e.reply_message_id}):null,i?eM:"failed"===e.state?e.failure_code:null,i?eK:"failed"===e.state?e.failure_message:null,e.id,e.created_at,u,u,e.principal_kind,e.principal_id);let c=0;for(let n of a?.all(e.id)??[])_.run((0,s.randomUUID)(),t,++c,n.type,n.data,n.created_at);i&&_.run((0,s.randomUUID)(),t,++c,"state_changed",JSON.stringify({from:"accepted"===e.state?"queued":"running",to:"failed",reason:eM}),u),_.run((0,s.randomUUID)(),t,++c,"backfilled",JSON.stringify({legacy_agent_request_id:e.id}),u)}(function(e){let t=e.prepare(`
|
|
1051
1088
|
SELECT w.id AS request_id, r.principal_kind, r.principal_id, r.idempotency_key, r.payload_hash,
|
|
1052
1089
|
r.conversation_id, r.target_bot_id, r.accepted_message_id, r.created_at, m.content AS content
|
|
1053
1090
|
FROM work_requests w
|
|
@@ -1063,7 +1100,7 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1063
1100
|
requester_kind, requester_id, idempotency_key, request_hash, surface,
|
|
1064
1101
|
conversation_id, source_event_id, work_request_ids, created_at
|
|
1065
1102
|
) VALUES (?, ?, ?, ?, 'api', ?, ?, ?, ?)
|
|
1066
|
-
`);for(let e of t){let t=[e.conversation_id,null].map(t=>[e.target_bot_id,t,e.content]).find(t=>
|
|
1103
|
+
`);for(let e of t){let t=[e.conversation_id,null].map(t=>[e.target_bot_id,t,e.content]).find(t=>eJ(JSON.stringify(t))===e.payload_hash);t&&n.run(e.principal_kind,e.principal_id,e.idempotency_key,eJ(JSON.stringify(["api",t])),e.conversation_id,e.accepted_message_id,JSON.stringify([e.request_id]),e.created_at)}})(e),t("legacy_agent_requests_archive")?e.exec("INSERT INTO legacy_agent_requests_archive SELECT * FROM agent_requests; DROP TABLE agent_requests;"):e.exec("ALTER TABLE agent_requests RENAME TO legacy_agent_requests_archive"),n&&(t("legacy_agent_request_events_archive")?e.exec("INSERT INTO legacy_agent_request_events_archive SELECT * FROM agent_request_events; DROP TABLE agent_request_events;"):e.exec("ALTER TABLE agent_request_events RENAME TO legacy_agent_request_events_archive"))}(e)}},{version:15,name:"ui_turns_on_work_requests",up:e=>{e.exec(`
|
|
1067
1104
|
ALTER TABLE work_requests ADD COLUMN executor TEXT NOT NULL DEFAULT 'dispatcher'
|
|
1068
1105
|
CHECK (executor IN ('dispatcher', 'ui_message', 'ui_continuation'));
|
|
1069
1106
|
CREATE INDEX idx_work_requests_executor ON work_requests(executor, state, created_at);
|
|
@@ -1085,27 +1122,27 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1085
1122
|
PRIMARY KEY (conversation_id, user_message_id),
|
|
1086
1123
|
FOREIGN KEY (conversation_id) REFERENCES conversations(id)
|
|
1087
1124
|
);
|
|
1088
|
-
`),function(e){let t=t=>!!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t);if(!t("processing_queue"))return;let n=new Set(e.prepare("PRAGMA table_info(processing_queue)").all().map(e=>e.name)).has("work_request_id")?"q.work_request_id":"NULL",
|
|
1125
|
+
`),function(e){let t=t=>!!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t);if(!t("processing_queue"))return;let n=new Set(e.prepare("PRAGMA table_info(processing_queue)").all().map(e=>e.name)).has("work_request_id")?"q.work_request_id":"NULL",i=e.prepare(`
|
|
1089
1126
|
SELECT q.id, q.conversation_id, q.bot_id, q.status, ${n} AS work_request_id, q.created_at, q.started_at, q.completed_at
|
|
1090
1127
|
FROM processing_queue q
|
|
1091
1128
|
JOIN conversations c ON c.id = q.conversation_id
|
|
1092
1129
|
JOIN bots b ON b.id = q.bot_id
|
|
1093
1130
|
ORDER BY q.created_at ASC, q.rowid ASC
|
|
1094
|
-
`).all(),
|
|
1131
|
+
`).all(),r=e.prepare("SELECT * FROM work_requests WHERE id = ?"),a=e.prepare(`
|
|
1095
1132
|
UPDATE work_requests SET state = ?, state_reason = ?, version = version + 1, updated_at = ?,
|
|
1096
1133
|
error_code = ?, error_message = ?, terminal_at = ?, executor = 'ui_message'
|
|
1097
1134
|
WHERE id = ?
|
|
1098
1135
|
`),o=e.prepare(`
|
|
1099
1136
|
INSERT INTO engine_events (id, request_id, sequence, attempt_id, type, data, created_at)
|
|
1100
1137
|
SELECT ?, ?, COALESCE(MAX(sequence), 0) + 1, NULL, ?, ?, ? FROM engine_events WHERE request_id = ?
|
|
1101
|
-
`),
|
|
1138
|
+
`),_=(e,t,n,i)=>o.run((0,s.randomUUID)(),e,t,JSON.stringify(n),i,e),d=e.prepare("SELECT id FROM messages WHERE conversation_id = ? AND created_at <= ? ORDER BY created_at DESC, rowid DESC LIMIT 1"),E=e.prepare(`
|
|
1102
1139
|
INSERT INTO work_requests (
|
|
1103
1140
|
id, source_conversation_id, source_event_id, requester_kind, requester_id, target_agent_id,
|
|
1104
1141
|
intent, execution_kind, tool_profile, parent_request_id, root_request_id, wake_event_id, depth,
|
|
1105
1142
|
idempotency_key, request_hash, policy_snapshot, state, version, created_at, updated_at,
|
|
1106
1143
|
wake_depth, root_principal_kind, root_principal_id, executor
|
|
1107
1144
|
) VALUES (?, ?, ?, ?, ?, ?, ?, 'conversation', 'readonly', NULL, ?, NULL, 0, ?, ?, ?, 'queued', 0, ?, ?, 0, ?, ?, 'ui_continuation')
|
|
1108
|
-
`),u=
|
|
1145
|
+
`),u=eP(!1),c=0;for(let t of i){if(t.work_request_id){let n=r.get(t.work_request_id);if(!n||"queued"!==n.state)continue;let i=t.started_at??t.created_at,s=Math.max(t.completed_at??i,i);if("pending"===t.status)e.prepare("UPDATE work_requests SET executor = 'ui_message' WHERE id = ?").run(n.id);else if("completed"===t.status||"failed"===t.status)a.run("running",null,i,null,null,null,n.id),_(n.id,"state_changed",{from:"queued",to:"running",reason:null,legacy_queue_id:t.id},i),a.run(t.status,"legacy_queue_turn",s,"failed"===t.status?"ui_turn_failed":null,"failed"===t.status?"The UI turn failed in the retired processing queue.":null,s,n.id),_(n.id,"state_changed",{from:"running",to:t.status,reason:"legacy_queue_turn",legacy_queue_id:t.id},s);else{let e=Math.max(Date.now(),i);a.run("running",null,i,null,null,null,n.id),_(n.id,"state_changed",{from:"queued",to:"running",reason:null,legacy_queue_id:t.id},i),a.run("failed",e$,e,e$,ez,e,n.id),_(n.id,"state_changed",{from:"running",to:"failed",reason:e$,error_code:e$,legacy_queue_id:t.id},e)}c++;continue}if("pending"!==t.status)continue;let n=(0,s.randomUUID)(),i=d.get(t.conversation_id,t.created_at)?.id??t.conversation_id,o={source:"legacy_processing_queue",legacy_queue_id:t.id},l=eB({sourceConversationId:t.conversation_id,sourceEventId:i,targetAgentId:t.bot_id,intent:"turn",executionKind:"conversation",toolProfile:"readonly",policy:{...o,execution_policy:u}});E.run(n,t.conversation_id,i,eY.kind,eY.id,t.bot_id,"turn",n,`legacy-queue:${t.id}`,l,JSON.stringify({...o,execution_policy:u,tool_profile:"readonly"}),t.created_at,t.created_at,eY.kind,eY.id),_(n,"accepted",{state:"queued",execution_kind:"conversation",tool_profile:"readonly"},t.created_at),_(n,"backfilled",{legacy_queue_id:t.id},t.created_at),c++}c+=e.prepare(`
|
|
1109
1146
|
UPDATE work_requests SET executor = 'ui_message'
|
|
1110
1147
|
WHERE state = 'queued' AND executor = 'dispatcher' AND legacy_agent_request_id IS NULL
|
|
1111
1148
|
AND parent_request_id IS NULL AND wake_event_id IS NULL
|
|
@@ -1116,56 +1153,505 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1116
1153
|
WHERE i.surface = 'ui' AND r.value = work_requests.id
|
|
1117
1154
|
)
|
|
1118
1155
|
)
|
|
1119
|
-
`).run().changes,t("legacy_processing_queue_archive")?e.exec("INSERT INTO legacy_processing_queue_archive SELECT * FROM processing_queue; DROP TABLE processing_queue;"):e.exec("ALTER TABLE processing_queue RENAME TO legacy_processing_queue_archive")}(e)}}
|
|
1156
|
+
`).run().changes,t("legacy_processing_queue_archive")?e.exec("INSERT INTO legacy_processing_queue_archive SELECT * FROM processing_queue; DROP TABLE processing_queue;"):e.exec("ALTER TABLE processing_queue RENAME TO legacy_processing_queue_archive")}(e)}},{version:16,name:"session_exchanges",up:e=>{let t=ef.flatMap(e=>eh[e].map(t=>`'${e}>${t}'`)).join(", "),n=ef.map(e=>`'${e}'`).join(", "),i=ev.map(e=>`'${e}'`).join(", ");e.exec(`
|
|
1157
|
+
-- One row per owner-requested exchange against one selected Session
|
|
1158
|
+
-- Binding. It names Botmancers rows only (binding, Work Requests,
|
|
1159
|
+
-- Attempts, messages): never a provider session id or credential.
|
|
1160
|
+
-- Hop Work Requests run through the dispatcher; the exchange state
|
|
1161
|
+
-- advances from their durable outcome.
|
|
1162
|
+
CREATE TABLE session_exchanges (
|
|
1163
|
+
id TEXT PRIMARY KEY,
|
|
1164
|
+
requester_kind TEXT NOT NULL CHECK (requester_kind IN ('person', 'bot', 'service')),
|
|
1165
|
+
requester_id TEXT NOT NULL,
|
|
1166
|
+
idempotency_key TEXT NOT NULL CHECK (length(idempotency_key) > 0),
|
|
1167
|
+
request_hash TEXT NOT NULL,
|
|
1168
|
+
mode TEXT NOT NULL CHECK (mode IN ('ask', 'continue')),
|
|
1169
|
+
origin_conversation_id TEXT NOT NULL,
|
|
1170
|
+
source_agent_id TEXT NOT NULL,
|
|
1171
|
+
source_binding_id TEXT NOT NULL,
|
|
1172
|
+
destination_agent_id TEXT,
|
|
1173
|
+
destination_conversation_id TEXT,
|
|
1174
|
+
destination_binding_id TEXT,
|
|
1175
|
+
instruction TEXT NOT NULL CHECK (length(instruction) BETWEEN 1 AND ${ew.instructionChars}),
|
|
1176
|
+
state TEXT NOT NULL CHECK (state IN (${n})),
|
|
1177
|
+
source_request_id TEXT,
|
|
1178
|
+
source_attempt_id TEXT,
|
|
1179
|
+
destination_request_id TEXT,
|
|
1180
|
+
destination_attempt_id TEXT,
|
|
1181
|
+
answer_message_id TEXT,
|
|
1182
|
+
packet TEXT CHECK (packet IS NULL OR length(packet) <= ${ew.packetChars}),
|
|
1183
|
+
failure_code TEXT,
|
|
1184
|
+
failure_message TEXT,
|
|
1185
|
+
cancel_requested_at INTEGER,
|
|
1186
|
+
cancel_requested_by TEXT,
|
|
1187
|
+
cancel_reason TEXT,
|
|
1188
|
+
version INTEGER NOT NULL DEFAULT 0,
|
|
1189
|
+
created_at INTEGER NOT NULL,
|
|
1190
|
+
updated_at INTEGER NOT NULL,
|
|
1191
|
+
terminal_at INTEGER,
|
|
1192
|
+
UNIQUE (requester_kind, requester_id, idempotency_key),
|
|
1193
|
+
CHECK ((state IN (${i})) = (terminal_at IS NOT NULL)),
|
|
1194
|
+
CHECK (state <> 'failed' OR failure_code IS NOT NULL),
|
|
1195
|
+
CHECK ((mode = 'continue') = (destination_agent_id IS NOT NULL AND destination_conversation_id IS NOT NULL)),
|
|
1196
|
+
CHECK (destination_agent_id IS NULL OR destination_agent_id <> source_agent_id),
|
|
1197
|
+
CHECK (mode = 'continue' OR (packet IS NULL AND destination_request_id IS NULL AND destination_binding_id IS NULL)),
|
|
1198
|
+
CHECK (mode = 'ask' OR answer_message_id IS NULL),
|
|
1199
|
+
CHECK (state = 'queued' OR state = 'failed' OR state = 'cancelled' OR source_request_id IS NOT NULL),
|
|
1200
|
+
CHECK (state <> 'delivering' OR (packet IS NOT NULL AND destination_request_id IS NOT NULL)),
|
|
1201
|
+
FOREIGN KEY (origin_conversation_id) REFERENCES conversations(id),
|
|
1202
|
+
FOREIGN KEY (source_agent_id) REFERENCES bots(id),
|
|
1203
|
+
FOREIGN KEY (source_binding_id) REFERENCES session_bindings(id),
|
|
1204
|
+
FOREIGN KEY (destination_agent_id) REFERENCES bots(id),
|
|
1205
|
+
FOREIGN KEY (destination_conversation_id) REFERENCES conversations(id),
|
|
1206
|
+
FOREIGN KEY (destination_binding_id) REFERENCES session_bindings(id),
|
|
1207
|
+
FOREIGN KEY (source_request_id) REFERENCES work_requests(id),
|
|
1208
|
+
FOREIGN KEY (source_attempt_id) REFERENCES work_attempts(id),
|
|
1209
|
+
FOREIGN KEY (destination_request_id) REFERENCES work_requests(id),
|
|
1210
|
+
FOREIGN KEY (destination_attempt_id) REFERENCES work_attempts(id),
|
|
1211
|
+
FOREIGN KEY (answer_message_id) REFERENCES messages(id)
|
|
1212
|
+
);
|
|
1213
|
+
CREATE INDEX idx_session_exchanges_open ON session_exchanges(created_at) WHERE terminal_at IS NULL;
|
|
1214
|
+
CREATE INDEX idx_session_exchanges_binding ON session_exchanges(source_binding_id);
|
|
1215
|
+
CREATE UNIQUE INDEX idx_session_exchanges_source_request ON session_exchanges(source_request_id) WHERE source_request_id IS NOT NULL;
|
|
1216
|
+
CREATE UNIQUE INDEX idx_session_exchanges_destination_request ON session_exchanges(destination_request_id) WHERE destination_request_id IS NOT NULL;
|
|
1217
|
+
|
|
1218
|
+
CREATE TABLE session_exchange_events (
|
|
1219
|
+
id TEXT PRIMARY KEY,
|
|
1220
|
+
exchange_id TEXT NOT NULL,
|
|
1221
|
+
sequence INTEGER NOT NULL CHECK (sequence >= 1),
|
|
1222
|
+
type TEXT NOT NULL CHECK (length(type) > 0),
|
|
1223
|
+
data TEXT,
|
|
1224
|
+
created_at INTEGER NOT NULL,
|
|
1225
|
+
UNIQUE (exchange_id, sequence),
|
|
1226
|
+
FOREIGN KEY (exchange_id) REFERENCES session_exchanges(id)
|
|
1227
|
+
);
|
|
1228
|
+
|
|
1229
|
+
CREATE TRIGGER trg_session_exchanges_fk BEFORE INSERT ON session_exchanges
|
|
1230
|
+
BEGIN
|
|
1231
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.origin_conversation_id')
|
|
1232
|
+
WHERE NOT EXISTS (SELECT 1 FROM conversations WHERE id = NEW.origin_conversation_id);
|
|
1233
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.source_agent_id')
|
|
1234
|
+
WHERE NOT EXISTS (SELECT 1 FROM bots WHERE id = NEW.source_agent_id);
|
|
1235
|
+
SELECT RAISE(ABORT, 'session exchange source binding does not belong to its source agent')
|
|
1236
|
+
WHERE NOT EXISTS (SELECT 1 FROM session_bindings WHERE id = NEW.source_binding_id AND agent_id = NEW.source_agent_id);
|
|
1237
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.destination_agent_id')
|
|
1238
|
+
WHERE NEW.destination_agent_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM bots WHERE id = NEW.destination_agent_id);
|
|
1239
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.destination_conversation_id')
|
|
1240
|
+
WHERE NEW.destination_conversation_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM conversations WHERE id = NEW.destination_conversation_id);
|
|
1241
|
+
SELECT RAISE(ABORT, 'a session exchange starts queued')
|
|
1242
|
+
WHERE NEW.state <> 'queued';
|
|
1243
|
+
END;
|
|
1244
|
+
|
|
1245
|
+
-- Identity, target, and instruction are fixed at creation.
|
|
1246
|
+
CREATE TRIGGER trg_session_exchanges_immutable BEFORE UPDATE OF
|
|
1247
|
+
id, requester_kind, requester_id, idempotency_key, request_hash, mode, origin_conversation_id,
|
|
1248
|
+
source_agent_id, source_binding_id, destination_agent_id, destination_conversation_id, instruction, created_at
|
|
1249
|
+
ON session_exchanges
|
|
1250
|
+
BEGIN
|
|
1251
|
+
SELECT RAISE(ABORT, 'session_exchanges identity and target are immutable');
|
|
1252
|
+
END;
|
|
1253
|
+
|
|
1254
|
+
CREATE TRIGGER trg_session_exchanges_transition BEFORE UPDATE OF state ON session_exchanges
|
|
1255
|
+
WHEN NEW.state <> OLD.state
|
|
1256
|
+
BEGIN
|
|
1257
|
+
SELECT RAISE(ABORT, 'invalid session_exchanges state transition')
|
|
1258
|
+
WHERE (OLD.state || '>' || NEW.state) NOT IN (${t})
|
|
1259
|
+
OR (OLD.mode = 'ask' AND NEW.state = 'delivering')
|
|
1260
|
+
OR (OLD.mode = 'continue' AND OLD.state = 'extracting' AND NEW.state = 'completed');
|
|
1261
|
+
END;
|
|
1262
|
+
|
|
1263
|
+
CREATE TRIGGER trg_session_exchanges_terminal BEFORE UPDATE ON session_exchanges
|
|
1264
|
+
WHEN OLD.state IN (${i})
|
|
1265
|
+
BEGIN
|
|
1266
|
+
SELECT RAISE(ABORT, 'terminal session_exchanges are immutable');
|
|
1267
|
+
END;
|
|
1268
|
+
|
|
1269
|
+
-- Causal references, the packet, and the cancellation intent are
|
|
1270
|
+
-- recorded once; a set reference must name an existing row.
|
|
1271
|
+
CREATE TRIGGER trg_session_exchanges_set_once BEFORE UPDATE ON session_exchanges
|
|
1272
|
+
BEGIN
|
|
1273
|
+
SELECT RAISE(ABORT, 'session_exchanges references are set once')
|
|
1274
|
+
WHERE (OLD.source_request_id IS NOT NULL AND NEW.source_request_id IS NOT OLD.source_request_id)
|
|
1275
|
+
OR (OLD.source_attempt_id IS NOT NULL AND NEW.source_attempt_id IS NOT OLD.source_attempt_id)
|
|
1276
|
+
OR (OLD.destination_request_id IS NOT NULL AND NEW.destination_request_id IS NOT OLD.destination_request_id)
|
|
1277
|
+
OR (OLD.destination_attempt_id IS NOT NULL AND NEW.destination_attempt_id IS NOT OLD.destination_attempt_id)
|
|
1278
|
+
OR (OLD.destination_binding_id IS NOT NULL AND NEW.destination_binding_id IS NOT OLD.destination_binding_id)
|
|
1279
|
+
OR (OLD.answer_message_id IS NOT NULL AND NEW.answer_message_id IS NOT OLD.answer_message_id)
|
|
1280
|
+
OR (OLD.packet IS NOT NULL AND NEW.packet IS NOT OLD.packet)
|
|
1281
|
+
OR (OLD.cancel_requested_at IS NOT NULL AND (NEW.cancel_requested_at IS NOT OLD.cancel_requested_at
|
|
1282
|
+
OR NEW.cancel_requested_by IS NOT OLD.cancel_requested_by OR NEW.cancel_reason IS NOT OLD.cancel_reason));
|
|
1283
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.source_request_id')
|
|
1284
|
+
WHERE NEW.source_request_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM work_requests WHERE id = NEW.source_request_id AND target_agent_id = NEW.source_agent_id);
|
|
1285
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.source_attempt_id')
|
|
1286
|
+
WHERE NEW.source_attempt_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM work_attempts WHERE id = NEW.source_attempt_id AND request_id = NEW.source_request_id);
|
|
1287
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.destination_request_id')
|
|
1288
|
+
WHERE NEW.destination_request_id IS NOT NULL AND NOT EXISTS (
|
|
1289
|
+
SELECT 1 FROM work_requests WHERE id = NEW.destination_request_id AND target_agent_id = NEW.destination_agent_id
|
|
1290
|
+
AND source_conversation_id = NEW.destination_conversation_id);
|
|
1291
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.destination_attempt_id')
|
|
1292
|
+
WHERE NEW.destination_attempt_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM work_attempts WHERE id = NEW.destination_attempt_id AND request_id = NEW.destination_request_id);
|
|
1293
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.destination_binding_id')
|
|
1294
|
+
WHERE NEW.destination_binding_id IS NOT NULL AND NOT EXISTS (
|
|
1295
|
+
SELECT 1 FROM session_bindings WHERE id = NEW.destination_binding_id AND agent_id = NEW.destination_agent_id
|
|
1296
|
+
AND request_id = NEW.destination_request_id AND id <> NEW.source_binding_id);
|
|
1297
|
+
-- The answer is the source Agent's message in the origin
|
|
1298
|
+
-- conversation, produced by the source hop request.
|
|
1299
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.answer_message_id')
|
|
1300
|
+
WHERE NEW.answer_message_id IS NOT NULL AND NOT EXISTS (
|
|
1301
|
+
SELECT 1 FROM messages WHERE id = NEW.answer_message_id AND conversation_id = NEW.origin_conversation_id
|
|
1302
|
+
AND sender_type = 'bot' AND sender_id = NEW.source_agent_id
|
|
1303
|
+
AND NEW.source_request_id IS NOT NULL AND request_id = NEW.source_request_id);
|
|
1304
|
+
END;
|
|
1305
|
+
|
|
1306
|
+
CREATE TRIGGER trg_session_exchange_events_fk BEFORE INSERT ON session_exchange_events
|
|
1307
|
+
BEGIN
|
|
1308
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchange_events.exchange_id')
|
|
1309
|
+
WHERE NOT EXISTS (SELECT 1 FROM session_exchanges WHERE id = NEW.exchange_id);
|
|
1310
|
+
END;
|
|
1311
|
+
CREATE TRIGGER trg_session_exchange_events_append_only BEFORE UPDATE ON session_exchange_events
|
|
1312
|
+
BEGIN
|
|
1313
|
+
SELECT RAISE(ABORT, 'session_exchange_events are append-only');
|
|
1314
|
+
END;
|
|
1315
|
+
-- Removed only with their exchange, by the aggregate cleanup
|
|
1316
|
+
-- (deleteSessionExchanges), under the same purge authority as
|
|
1317
|
+
-- engine events.
|
|
1318
|
+
CREATE TRIGGER trg_session_exchange_events_no_delete BEFORE DELETE ON session_exchange_events
|
|
1319
|
+
BEGIN
|
|
1320
|
+
SELECT RAISE(ABORT, 'session_exchange_events are append-only')
|
|
1321
|
+
WHERE NOT engine_event_purge_authorized(OLD.exchange_id);
|
|
1322
|
+
END;
|
|
1323
|
+
CREATE TRIGGER trg_session_exchanges_restrict BEFORE DELETE ON session_exchanges
|
|
1324
|
+
BEGIN
|
|
1325
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchange_events.exchange_id')
|
|
1326
|
+
WHERE EXISTS (SELECT 1 FROM session_exchange_events WHERE exchange_id = OLD.id);
|
|
1327
|
+
END;
|
|
1328
|
+
|
|
1329
|
+
-- Foreign keys (delete side): RESTRICT, as for the engine tables.
|
|
1330
|
+
CREATE TRIGGER trg_conversations_exchange_restrict BEFORE DELETE ON conversations
|
|
1331
|
+
BEGIN
|
|
1332
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.conversation')
|
|
1333
|
+
WHERE EXISTS (SELECT 1 FROM session_exchanges WHERE origin_conversation_id = OLD.id OR destination_conversation_id = OLD.id);
|
|
1334
|
+
END;
|
|
1335
|
+
CREATE TRIGGER trg_bots_exchange_restrict BEFORE DELETE ON bots
|
|
1336
|
+
BEGIN
|
|
1337
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.agent')
|
|
1338
|
+
WHERE EXISTS (SELECT 1 FROM session_exchanges WHERE source_agent_id = OLD.id OR destination_agent_id = OLD.id);
|
|
1339
|
+
END;
|
|
1340
|
+
CREATE TRIGGER trg_session_bindings_exchange_restrict BEFORE DELETE ON session_bindings
|
|
1341
|
+
BEGIN
|
|
1342
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.binding')
|
|
1343
|
+
WHERE EXISTS (SELECT 1 FROM session_exchanges WHERE source_binding_id = OLD.id OR destination_binding_id = OLD.id);
|
|
1344
|
+
END;
|
|
1345
|
+
CREATE TRIGGER trg_work_requests_exchange_restrict BEFORE DELETE ON work_requests
|
|
1346
|
+
BEGIN
|
|
1347
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.request')
|
|
1348
|
+
WHERE EXISTS (SELECT 1 FROM session_exchanges WHERE source_request_id = OLD.id OR destination_request_id = OLD.id);
|
|
1349
|
+
END;
|
|
1350
|
+
CREATE TRIGGER trg_messages_exchange_restrict BEFORE DELETE ON messages
|
|
1351
|
+
BEGIN
|
|
1352
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.answer_message_id')
|
|
1353
|
+
WHERE EXISTS (SELECT 1 FROM session_exchanges WHERE answer_message_id = OLD.id);
|
|
1354
|
+
END;
|
|
1355
|
+
CREATE TRIGGER trg_work_attempts_exchange_restrict BEFORE DELETE ON work_attempts
|
|
1356
|
+
BEGIN
|
|
1357
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: session_exchanges.attempt')
|
|
1358
|
+
WHERE EXISTS (SELECT 1 FROM session_exchanges WHERE source_attempt_id = OLD.id OR destination_attempt_id = OLD.id);
|
|
1359
|
+
END;
|
|
1360
|
+
`)}},{version:17,name:"provider_sessions",up:e=>{var t;e.exec(`
|
|
1361
|
+
-- One row per native runtime session Botmancers knows, under a
|
|
1362
|
+
-- stable Botmancers reference (id). provider_session_id is private:
|
|
1363
|
+
-- only the owner-only local debug disclosure ever returns it. A row
|
|
1364
|
+
-- linked to a Session Binding uses the binding's id as its id.
|
|
1365
|
+
-- availability/lifecycle/resumable/busy are independent provider
|
|
1366
|
+
-- facts; resumable NULL means the provider was never asked.
|
|
1367
|
+
CREATE TABLE provider_sessions (
|
|
1368
|
+
id TEXT PRIMARY KEY,
|
|
1369
|
+
agent_id TEXT NOT NULL,
|
|
1370
|
+
runtime_connection_id TEXT NOT NULL,
|
|
1371
|
+
provider_kind TEXT NOT NULL,
|
|
1372
|
+
provider_session_id TEXT NOT NULL,
|
|
1373
|
+
binding_id TEXT UNIQUE,
|
|
1374
|
+
origin TEXT NOT NULL CHECK (origin IN ('binding', 'discovered', 'started')),
|
|
1375
|
+
title TEXT,
|
|
1376
|
+
workspace TEXT,
|
|
1377
|
+
provider_created_at INTEGER,
|
|
1378
|
+
provider_updated_at INTEGER,
|
|
1379
|
+
availability TEXT NOT NULL DEFAULT 'available' CHECK (availability IN ('available', 'missing')),
|
|
1380
|
+
lifecycle TEXT NOT NULL DEFAULT 'open' CHECK (lifecycle IN ('open', 'archived')),
|
|
1381
|
+
resumable INTEGER CHECK (resumable IS NULL OR resumable IN (0, 1)),
|
|
1382
|
+
busy INTEGER NOT NULL DEFAULT 0 CHECK (busy IN (0, 1)),
|
|
1383
|
+
capabilities TEXT,
|
|
1384
|
+
last_synced_at INTEGER,
|
|
1385
|
+
created_at INTEGER NOT NULL,
|
|
1386
|
+
updated_at INTEGER NOT NULL,
|
|
1387
|
+
CHECK (origin <> 'binding' OR binding_id = id),
|
|
1388
|
+
FOREIGN KEY (agent_id) REFERENCES bots(id),
|
|
1389
|
+
FOREIGN KEY (binding_id) REFERENCES session_bindings(id)
|
|
1390
|
+
);
|
|
1391
|
+
-- Repeated discovery is idempotent: at most one unlinked row per
|
|
1392
|
+
-- (Agent, connection, provider session). The same provider id on
|
|
1393
|
+
-- another connection or Agent is another session.
|
|
1394
|
+
CREATE UNIQUE INDEX idx_provider_sessions_native
|
|
1395
|
+
ON provider_sessions(agent_id, runtime_connection_id, provider_session_id) WHERE binding_id IS NULL;
|
|
1396
|
+
CREATE INDEX idx_provider_sessions_lookup
|
|
1397
|
+
ON provider_sessions(agent_id, runtime_connection_id, provider_session_id);
|
|
1398
|
+
|
|
1399
|
+
-- One row per provider turn Botmancers started (start or send),
|
|
1400
|
+
-- keyed by the requester's idempotency key. provider_turn_id is
|
|
1401
|
+
-- private.
|
|
1402
|
+
CREATE TABLE provider_session_turns (
|
|
1403
|
+
id TEXT PRIMARY KEY,
|
|
1404
|
+
session_ref TEXT NOT NULL,
|
|
1405
|
+
agent_id TEXT NOT NULL,
|
|
1406
|
+
kind TEXT NOT NULL CHECK (kind IN ('start', 'send')),
|
|
1407
|
+
authority TEXT NOT NULL CHECK (authority IN ('read_only', 'workspace_write')),
|
|
1408
|
+
requester_kind TEXT NOT NULL,
|
|
1409
|
+
requester_id TEXT NOT NULL,
|
|
1410
|
+
idempotency_key TEXT NOT NULL,
|
|
1411
|
+
request_hash TEXT NOT NULL,
|
|
1412
|
+
provider_turn_id TEXT NOT NULL,
|
|
1413
|
+
state TEXT NOT NULL CHECK (state IN ('running', 'completed', 'failed', 'cancelled')),
|
|
1414
|
+
output TEXT,
|
|
1415
|
+
failure_code TEXT,
|
|
1416
|
+
correlation TEXT NOT NULL,
|
|
1417
|
+
created_at INTEGER NOT NULL,
|
|
1418
|
+
finished_at INTEGER,
|
|
1419
|
+
UNIQUE (agent_id, requester_kind, requester_id, idempotency_key),
|
|
1420
|
+
FOREIGN KEY (session_ref) REFERENCES provider_sessions(id)
|
|
1421
|
+
);
|
|
1422
|
+
CREATE INDEX idx_provider_session_turns_session ON provider_session_turns(session_ref, created_at);
|
|
1423
|
+
|
|
1424
|
+
-- Append-only audit of registry syncs and provider turns. Names
|
|
1425
|
+
-- Botmancers rows only, never a provider id.
|
|
1426
|
+
CREATE TABLE provider_session_events (
|
|
1427
|
+
id TEXT PRIMARY KEY,
|
|
1428
|
+
agent_id TEXT NOT NULL,
|
|
1429
|
+
session_ref TEXT,
|
|
1430
|
+
turn_id TEXT,
|
|
1431
|
+
type TEXT NOT NULL,
|
|
1432
|
+
detail TEXT NOT NULL,
|
|
1433
|
+
created_at INTEGER NOT NULL
|
|
1434
|
+
);
|
|
1435
|
+
CREATE INDEX idx_provider_session_events_agent ON provider_session_events(agent_id, created_at);
|
|
1436
|
+
|
|
1437
|
+
CREATE TRIGGER trg_provider_sessions_fk BEFORE INSERT ON provider_sessions
|
|
1438
|
+
BEGIN
|
|
1439
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: provider_sessions.agent_id')
|
|
1440
|
+
WHERE NOT EXISTS (SELECT 1 FROM bots WHERE id = NEW.agent_id);
|
|
1441
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: provider_sessions.binding_id')
|
|
1442
|
+
WHERE NEW.binding_id IS NOT NULL
|
|
1443
|
+
AND NOT EXISTS (SELECT 1 FROM session_bindings WHERE id = NEW.binding_id AND agent_id = NEW.agent_id);
|
|
1444
|
+
END;
|
|
1445
|
+
CREATE TRIGGER trg_provider_sessions_identity BEFORE UPDATE OF
|
|
1446
|
+
id, agent_id, runtime_connection_id, provider_kind, provider_session_id, origin, created_at
|
|
1447
|
+
ON provider_sessions
|
|
1448
|
+
BEGIN
|
|
1449
|
+
SELECT RAISE(ABORT, 'provider_sessions identity is immutable');
|
|
1450
|
+
END;
|
|
1451
|
+
CREATE TRIGGER trg_provider_session_turns_fk BEFORE INSERT ON provider_session_turns
|
|
1452
|
+
BEGIN
|
|
1453
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: provider_session_turns.session_ref')
|
|
1454
|
+
WHERE NOT EXISTS (SELECT 1 FROM provider_sessions WHERE id = NEW.session_ref AND agent_id = NEW.agent_id);
|
|
1455
|
+
END;
|
|
1456
|
+
CREATE TRIGGER trg_provider_session_events_append_only BEFORE UPDATE ON provider_session_events
|
|
1457
|
+
BEGIN
|
|
1458
|
+
SELECT RAISE(ABORT, 'provider_session_events are append-only');
|
|
1459
|
+
END;
|
|
1460
|
+
-- Delete side: the Agent and binding delete paths
|
|
1461
|
+
-- (deleteEngineRecordsForAgent / deleteEngineRecords) remove or
|
|
1462
|
+
-- unlink registry rows first; the catalog joins bots, so a raw
|
|
1463
|
+
-- delete never surfaces an orphan.
|
|
1464
|
+
CREATE TRIGGER trg_provider_sessions_restrict BEFORE DELETE ON provider_sessions
|
|
1465
|
+
BEGIN
|
|
1466
|
+
SELECT RAISE(ABORT, 'FOREIGN KEY constraint failed: provider_session_turns.session_ref')
|
|
1467
|
+
WHERE EXISTS (SELECT 1 FROM provider_session_turns WHERE session_ref = OLD.id);
|
|
1468
|
+
END;
|
|
1469
|
+
`),(t=e).prepare(`
|
|
1470
|
+
INSERT INTO provider_sessions (
|
|
1471
|
+
id, agent_id, runtime_connection_id, provider_kind, provider_session_id, binding_id, origin,
|
|
1472
|
+
availability, lifecycle, resumable, busy, created_at, updated_at
|
|
1473
|
+
)
|
|
1474
|
+
SELECT b.id, b.agent_id, ${eX(t)}, b.adapter, b.external_session_id, b.id, 'binding',
|
|
1475
|
+
'available', 'open', NULL, 0, b.created_at, COALESCE(b.released_at, b.created_at)
|
|
1476
|
+
FROM session_bindings b
|
|
1477
|
+
JOIN bots bot ON bot.id = b.agent_id
|
|
1478
|
+
WHERE NOT EXISTS (SELECT 1 FROM provider_sessions p WHERE p.binding_id = b.id)
|
|
1479
|
+
ORDER BY b.created_at ASC, b.id ASC
|
|
1480
|
+
`).run()}},{version:18,name:"usage_samples",up:e=>{e.exec(`
|
|
1481
|
+
-- One row per Attempt or provider turn that reached a runtime,
|
|
1482
|
+
-- keyed by sample_key (attempt:<id> or turn:<id>), so a replayed
|
|
1483
|
+
-- terminal result, a reconciled Attempt after a restart, or a late
|
|
1484
|
+
-- result never adds a second row. Each metric is nullable: NULL is
|
|
1485
|
+
-- not reported, 0 is an explicit provider zero. breakdown holds
|
|
1486
|
+
-- whitelisted numeric counters only. Pre-existing Attempts get no
|
|
1487
|
+
-- row: their usage was never reported.
|
|
1488
|
+
CREATE TABLE usage_samples (
|
|
1489
|
+
id TEXT PRIMARY KEY,
|
|
1490
|
+
sample_key TEXT NOT NULL UNIQUE,
|
|
1491
|
+
agent_id TEXT NOT NULL,
|
|
1492
|
+
attempt_id TEXT,
|
|
1493
|
+
session_ref TEXT,
|
|
1494
|
+
turn_id TEXT,
|
|
1495
|
+
provider TEXT NOT NULL,
|
|
1496
|
+
source TEXT NOT NULL CHECK (source IN ('codex.turn_completed', 'result', 'normalized', 'none')),
|
|
1497
|
+
input_tokens INTEGER CHECK (input_tokens IS NULL OR input_tokens >= 0),
|
|
1498
|
+
output_tokens INTEGER CHECK (output_tokens IS NULL OR output_tokens >= 0),
|
|
1499
|
+
cost_usd REAL CHECK (cost_usd IS NULL OR cost_usd >= 0),
|
|
1500
|
+
breakdown TEXT,
|
|
1501
|
+
observed_at INTEGER NOT NULL,
|
|
1502
|
+
created_at INTEGER NOT NULL,
|
|
1503
|
+
updated_at INTEGER NOT NULL,
|
|
1504
|
+
CHECK (attempt_id IS NOT NULL OR turn_id IS NOT NULL)
|
|
1505
|
+
);
|
|
1506
|
+
CREATE INDEX idx_usage_samples_attempt ON usage_samples(attempt_id);
|
|
1507
|
+
CREATE INDEX idx_usage_samples_session ON usage_samples(session_ref);
|
|
1508
|
+
CREATE INDEX idx_usage_samples_agent ON usage_samples(agent_id);
|
|
1509
|
+
`)}},{version:19,name:"provider_turn_usage",up:e=>{e.exec(`
|
|
1510
|
+
ALTER TABLE provider_session_turns ADD COLUMN input_tokens INTEGER;
|
|
1511
|
+
ALTER TABLE provider_session_turns ADD COLUMN output_tokens INTEGER;
|
|
1512
|
+
ALTER TABLE provider_session_turns ADD COLUMN total_cost_usd REAL;
|
|
1513
|
+
`)}},{version:20,name:"session_pins",up:e=>{e.exec(`
|
|
1514
|
+
-- One row per pin. session_ref never changes after insert: a switch
|
|
1515
|
+
-- detaches this pin and creates another. action/authority record
|
|
1516
|
+
-- what the caller asked for (ask = read_only, resume =
|
|
1517
|
+
-- workspace_write after explicit approval); resolution how the
|
|
1518
|
+
-- session was chosen (exact, or for a registered-Agent message the
|
|
1519
|
+
-- home session, the newest eligible one, or a newly started one).
|
|
1520
|
+
CREATE TABLE session_pins (
|
|
1521
|
+
id TEXT PRIMARY KEY,
|
|
1522
|
+
requester_kind TEXT NOT NULL CHECK (requester_kind IN ('person', 'bot', 'service')),
|
|
1523
|
+
requester_id TEXT NOT NULL,
|
|
1524
|
+
idempotency_key TEXT NOT NULL,
|
|
1525
|
+
request_hash TEXT NOT NULL,
|
|
1526
|
+
agent_id TEXT NOT NULL,
|
|
1527
|
+
session_ref TEXT NOT NULL,
|
|
1528
|
+
action TEXT NOT NULL CHECK (action IN ('ask', 'resume')),
|
|
1529
|
+
authority TEXT NOT NULL CHECK (authority IN ('read_only', 'workspace_write')),
|
|
1530
|
+
resolution TEXT NOT NULL CHECK (resolution IN ('exact', 'home', 'newest', 'started')),
|
|
1531
|
+
route TEXT NOT NULL CHECK (route IN ('provider', 'engine')),
|
|
1532
|
+
conversation_id TEXT NOT NULL,
|
|
1533
|
+
approved_at INTEGER,
|
|
1534
|
+
state TEXT NOT NULL CHECK (state IN ('attached', 'detached')),
|
|
1535
|
+
detach_reason TEXT CHECK (detach_reason IS NULL OR detach_reason IN ('detached', 'switched')),
|
|
1536
|
+
replaced_by TEXT,
|
|
1537
|
+
created_at INTEGER NOT NULL,
|
|
1538
|
+
updated_at INTEGER NOT NULL,
|
|
1539
|
+
detached_at INTEGER,
|
|
1540
|
+
CHECK (authority = CASE action WHEN 'ask' THEN 'read_only' ELSE 'workspace_write' END),
|
|
1541
|
+
CHECK (action = 'ask' OR approved_at IS NOT NULL),
|
|
1542
|
+
CHECK ((state = 'attached') = (detached_at IS NULL)),
|
|
1543
|
+
UNIQUE (requester_kind, requester_id, idempotency_key)
|
|
1544
|
+
);
|
|
1545
|
+
CREATE INDEX idx_session_pins_session ON session_pins(session_ref);
|
|
1546
|
+
CREATE INDEX idx_session_pins_agent ON session_pins(agent_id);
|
|
1547
|
+
CREATE TRIGGER trg_session_pins_identity BEFORE UPDATE OF
|
|
1548
|
+
id, requester_kind, requester_id, idempotency_key, request_hash, agent_id, session_ref, action, authority, resolution, route, created_at
|
|
1549
|
+
ON session_pins
|
|
1550
|
+
BEGIN
|
|
1551
|
+
SELECT RAISE(ABORT, 'session_pins identity is immutable');
|
|
1552
|
+
END;
|
|
1553
|
+
|
|
1554
|
+
-- One row per turn sent through a pin, in order. Exactly one of
|
|
1555
|
+
-- exchange_id (engine route: an Ask exchange on the binding) and
|
|
1556
|
+
-- provider_turn_ref (provider route) is set.
|
|
1557
|
+
CREATE TABLE session_pin_turns (
|
|
1558
|
+
id TEXT PRIMARY KEY,
|
|
1559
|
+
pin_id TEXT NOT NULL,
|
|
1560
|
+
seq INTEGER NOT NULL,
|
|
1561
|
+
requester_kind TEXT NOT NULL,
|
|
1562
|
+
requester_id TEXT NOT NULL,
|
|
1563
|
+
idempotency_key TEXT NOT NULL,
|
|
1564
|
+
request_hash TEXT NOT NULL,
|
|
1565
|
+
content TEXT NOT NULL,
|
|
1566
|
+
exchange_id TEXT,
|
|
1567
|
+
provider_turn_ref TEXT,
|
|
1568
|
+
question_message_id TEXT,
|
|
1569
|
+
answer_message_id TEXT,
|
|
1570
|
+
created_at INTEGER NOT NULL,
|
|
1571
|
+
CHECK ((exchange_id IS NULL) <> (provider_turn_ref IS NULL)),
|
|
1572
|
+
UNIQUE (pin_id, seq),
|
|
1573
|
+
UNIQUE (requester_kind, requester_id, idempotency_key),
|
|
1574
|
+
FOREIGN KEY (pin_id) REFERENCES session_pins(id)
|
|
1575
|
+
);
|
|
1576
|
+
|
|
1577
|
+
-- Append-only audit of every pin decision: created (with the
|
|
1578
|
+
-- resolution), turn sent, turn refused (with the stable code; the
|
|
1579
|
+
-- target never changes), detached, switched.
|
|
1580
|
+
CREATE TABLE session_pin_events (
|
|
1581
|
+
id TEXT PRIMARY KEY,
|
|
1582
|
+
pin_id TEXT NOT NULL,
|
|
1583
|
+
sequence INTEGER NOT NULL,
|
|
1584
|
+
type TEXT NOT NULL,
|
|
1585
|
+
data TEXT NOT NULL,
|
|
1586
|
+
created_at INTEGER NOT NULL,
|
|
1587
|
+
UNIQUE (pin_id, sequence)
|
|
1588
|
+
);
|
|
1589
|
+
CREATE TRIGGER trg_session_pin_events_append_only BEFORE UPDATE ON session_pin_events
|
|
1590
|
+
BEGIN
|
|
1591
|
+
SELECT RAISE(ABORT, 'session_pin_events are append-only');
|
|
1592
|
+
END;
|
|
1593
|
+
`)}}];function eX(e){return e.prepare("PRAGMA table_info(bots)").all().some(e=>"runtime_connection_id"===e.name)?"COALESCE(bot.runtime_connection_id, 'rc-local-' || b.adapter)":"'rc-local-' || b.adapter"}let ex=new WeakMap;function eG(e){let t=ex.get(e);if(!t){t=new Set,ex.set(e,t);let n=t;e.function("engine_event_purge_authorized",{deterministic:!1},e=>"string"==typeof e&&n.has(e)?1:0)}return t}function eH(e,t={}){eG(e),e.exec(`
|
|
1120
1594
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1121
1595
|
version INTEGER PRIMARY KEY,
|
|
1122
1596
|
name TEXT NOT NULL,
|
|
1123
1597
|
applied_at INTEGER NOT NULL
|
|
1124
1598
|
);
|
|
1125
|
-
`);let n=e.prepare("SELECT 1 FROM schema_migrations WHERE version = ?"),
|
|
1599
|
+
`);let n=e.prepare("SELECT 1 FROM schema_migrations WHERE version = ?"),i=e.prepare("INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)");for(let r of eW){if(void 0!==t.through&&r.version>t.through)return;e.transaction(()=>{n.get(r.version)||(r.up(e),i.run(r.version,r.name,Date.now()))}).immediate()}}function eB(e){return eJ(JSON.stringify([e.sourceConversationId,e.sourceEventId,e.targetAgentId,e.intent,e.executionKind,e.toolProfile,e.parentRequestId??null,e.wakeEventId??null,e.policy??null]))}eW[eW.length-1].version;let eM="legacy_interrupted",eK="Accepted before NOT-465 by the retired agent_requests dispatcher; it never reached a terminal state.",eY=Object.freeze({kind:"service",id:"botmancers-ui-turns"});function eP(e){let t=en(e?{entryPoint:"wake",executionKind:"conversation",wakeSyntax:"legacy"}:{entryPoint:"ui",executionKind:"conversation"});if(!t.ok)throw new eD("invalid_input",t.reason);return t.policy}let e$="ui_turn_interrupted",ez="The UI turn was interrupted before it finished; it is not run again.";function ej(e){return"string"==typeof e&&e.trim().length>0}function eJ(e){return(0,s.createHash)("sha256").update(e).digest("hex")}function eQ(e){return null==e?null:JSON.stringify(e)}function eV(e){eG(e);let t=e.prepare("SELECT * FROM work_requests WHERE id = ?"),n=e.prepare("SELECT * FROM work_requests WHERE requester_kind = ? AND requester_id = ? AND idempotency_key = ?"),i=e.prepare("SELECT * FROM work_attempts WHERE id = ?"),r=e.prepare(`
|
|
1126
1600
|
INSERT INTO engine_events (id, request_id, sequence, attempt_id, type, data, created_at)
|
|
1127
1601
|
SELECT ?, ?, COALESCE(MAX(sequence), 0) + 1, ?, ?, ?, ? FROM engine_events WHERE request_id = ?
|
|
1128
|
-
`),
|
|
1602
|
+
`),a=e.prepare("SELECT * FROM engine_events WHERE id = ?"),o=e.prepare("SELECT * FROM session_bindings WHERE id = ?");function _(e){let n=t.get(e);if(!n)throw new eD("not_found",`No work request ${e}.`);return n}function d(e){let t=i.get(e);if(!t)throw new eD("not_found",`No attempt ${e}.`);return t}function E(e,t,n,i,o){let _=(0,s.randomUUID)();return r.run(_,e,i,t,eQ(n),o,e),a.get(_)}let u={transaction:t=>e.transaction(t).immediate(),createOrGetWorkRequest(i){if(!ej(i.sourceConversationId))throw new eD("invalid_input","sourceConversationId is required.");if(!ej(i.sourceEventId))throw new eD("invalid_input","sourceEventId is required.");if(!i.requester||!["person","bot","service"].includes(i.requester.kind)||!ej(i.requester.id))throw new eD("invalid_input","A requester principal is required.");if(!ej(i.targetAgentId))throw new eD("invalid_input","targetAgentId is required.");if("string"!=typeof i.intent)throw new eD("invalid_input","intent is required.");if(!ee(i.executionKind))throw new eD("invalid_input","Unknown execution kind.");if(Z[i.executionKind]!==i.toolProfile)throw new eD("invalid_input",`Execution kind ${i.executionKind} requires the ${Z[i.executionKind]} tool profile.`);if(i.policy&&Object.prototype.hasOwnProperty.call(i.policy,"execution_policy"))throw new eD("invalid_input","The execution policy is passed as executionPolicy, never inside policy.");if(void 0!==i.executionPolicy){let e=er(i.executionPolicy);if(!e.ok)throw new eD("invalid_input",e.reason);if(e.policy.execution_kind!==i.executionKind||e.policy.tool_profile!==i.toolProfile)throw new eD("invalid_input","The execution policy does not match the requested execution kind and tool profile.")}if(!ej(i.idempotencyKey))throw new eD("invalid_input","idempotencyKey is required.");if(void 0!==i.executor&&!eb.includes(i.executor))throw new eD("invalid_input","Unknown request executor.");if(i.initialState&&"queued"!==i.initialState&&"blocked"!==i.initialState)throw new eD("invalid_input","A work request starts queued or blocked.");if(void 0!==i.deadlineAt&&null!==i.deadlineAt&&!Number.isSafeInteger(i.deadlineAt))throw new eD("invalid_input","deadlineAt must be an epoch millisecond integer.");if(void 0!==i.retryPolicy){let e=e_(i.retryPolicy);if(!e.ok)throw new eD("invalid_input",e.reason)}let r=i.executionPolicy?{...i.policy??{},execution_policy:i.executionPolicy}:i.policy,a=eB({...i,policy:r});return e.transaction(()=>{let o=n.get(i.requester.kind,i.requester.id,i.idempotencyKey);if(o){if(o.request_hash!==a)throw new eD("idempotency_conflict","The idempotency key was already used with a different request.");return{request:o,created:!1}}let d=i.now??Date.now(),c=(0,s.randomUUID)(),l=c,T=0,p=0,N=i.rootPrincipal??i.requester;if(i.parentRequestId){let e=t.get(i.parentRequestId);if(!e)throw new eD("not_found","Parent work request not found.");l=e.root_request_id,T=e.depth+1,p=i.wakeEventId?e.wake_depth+1:e.wake_depth,N={kind:e.root_principal_kind??"unknown",id:e.root_principal_id??"unknown"}}void 0!==i.wakeDepth&&(p=i.wakeDepth);let R=i.initialState??"queued",m=JSON.stringify({...r??{},...i.safetySnapshot??{},tool_profile:i.toolProfile}),L=eo(),g=i.retryPolicy??L.retryPolicy,O=void 0!==i.deadlineAt?i.deadlineAt:null===L.deadlineMs?null:d+L.deadlineMs;return e.prepare(`
|
|
1129
1603
|
INSERT INTO work_requests (
|
|
1130
1604
|
id, source_conversation_id, source_event_id, requester_kind, requester_id, target_agent_id,
|
|
1131
1605
|
intent, execution_kind, tool_profile, parent_request_id, root_request_id, wake_event_id, depth,
|
|
1132
1606
|
idempotency_key, request_hash, policy_snapshot, state, state_reason, version, created_at, updated_at,
|
|
1133
1607
|
deadline_at, retry_policy, wake_depth, root_principal_kind, root_principal_id, executor
|
|
1134
1608
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1135
|
-
`).run(
|
|
1609
|
+
`).run(c,i.sourceConversationId,i.sourceEventId,i.requester.kind,i.requester.id,i.targetAgentId,i.intent,i.executionKind,i.toolProfile,i.parentRequestId??null,l,i.wakeEventId??null,T,i.idempotencyKey,a,m,R,i.stateReason??null,d,d,O,JSON.stringify(g),p,N.kind,N.id,i.executor??"dispatcher"),E(c,"accepted",{state:R,execution_kind:i.executionKind,tool_profile:i.toolProfile,deadline_at:O,retry_policy:g},null,d),i.executionPolicy&&E(c,"policy_selected",{...i.executionPolicy},null,d),"blocked"===R&&E(c,"state_changed",{from:"queued",to:"blocked",reason:i.stateReason??null},null,d),i.safety&&u.recordSafetyDecision(c,{...i.safety,now:i.safety.now??d}),{request:_(c),created:!0}}).immediate()},getWorkRequest:e=>t.get(e),recordSafetyDecision(t,n){if(!["human_owner","api_principal","agent_principal","engine"].includes(n.principalType))throw new eD("invalid_input","A categorized principal is required.");if(!ej(n.principal?.kind)||!ej(n.principal?.id))throw new eD("invalid_input","A principal is required.");if(!["allowed","blocked","denied"].includes(n.decision))throw new eD("invalid_input","Unknown safety decision.");if("allowed"===n.decision&&!ej(n.grantRule))throw new eD("invalid_input","An allowed decision names its grant rule.");return e.transaction(()=>{let i=_(t),r=(0,s.randomUUID)();return e.prepare(`
|
|
1136
1610
|
INSERT INTO wake_safety_decisions (
|
|
1137
1611
|
id, request_id, sequence, wake_id, principal_type, principal_kind, principal_id, target_agent_id, execution_kind,
|
|
1138
1612
|
decision, reason_code, grant_rule, grant_id, policy_snapshot, created_at
|
|
1139
1613
|
) SELECT ?, ?, COALESCE(MAX(sequence), 0) + 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM wake_safety_decisions WHERE request_id = ?
|
|
1140
|
-
`).run(
|
|
1614
|
+
`).run(r,t,n.wakeId??null,n.principalType,n.principal.kind,n.principal.id,i.target_agent_id,i.execution_kind,n.decision,n.reasonCode??null,n.grantRule??null,n.grantId??null,JSON.stringify(n.snapshot),n.now??Date.now(),t),e.prepare("SELECT * FROM wake_safety_decisions WHERE id = ?").get(r)}).immediate()},listSafetyDecisions:t=>e.prepare("SELECT * FROM wake_safety_decisions WHERE request_id = ? ORDER BY sequence ASC").all(t),latestSafetyDecision:t=>e.prepare("SELECT * FROM wake_safety_decisions WHERE request_id = ? ORDER BY sequence DESC LIMIT 1").get(t),transitionWorkRequest(t,n){if(!ey[n.from]?.includes(n.to))throw new eD("invalid_transition",`Cannot move a work request from ${n.from} to ${n.to}.`);let i=eq.includes(n.to);return e.transaction(()=>{let r=_(t),s=n.now??Date.now();if(1!==e.prepare(`
|
|
1141
1615
|
UPDATE work_requests SET
|
|
1142
1616
|
state = ?, state_reason = ?, version = version + 1, updated_at = ?,
|
|
1143
1617
|
result = ?, error_code = ?, error_message = ?, terminal_at = ?
|
|
1144
1618
|
WHERE id = ? AND state = ? AND (? IS NULL OR version = ?)
|
|
1145
|
-
`).run(n.to,n.reason??null,
|
|
1619
|
+
`).run(n.to,n.reason??null,s,i?eQ(n.result):null,i?n.errorCode??null:null,i?n.errorMessage??null:null,i?s:null,t,n.from,n.expectedVersion??null,n.expectedVersion??null).changes)throw new eD("stale_state",`Work request ${t} is ${r.state} at version ${r.version}, not ${n.from}${void 0===n.expectedVersion?"":` at version ${n.expectedVersion}`}.`);return E(t,"state_changed",{...n.data??{},from:n.from,to:n.to,reason:n.reason??null,...n.errorCode?{error_code:n.errorCode}:{}},null,s),i&&null===r.legacy_agent_request_id&&"dispatcher"===r.executor&&e.prepare("INSERT OR IGNORE INTO terminal_followups (request_id, created_at) VALUES (?, ?)").run(t,s),_(t)}).immediate()},reblockWorkRequest:(t,n)=>e.transaction(()=>{let i=n.now??Date.now();if(1!==e.prepare("UPDATE work_requests SET state_reason = ?, version = version + 1, updated_at = ? WHERE id = ? AND state = 'blocked'").run(n.reason,i,t).changes)throw new eD("stale_state",`Work request ${t} is not blocked.`);return E(t,n.type,n.data??{},null,i),_(t)}).immediate(),appendEvent(t,n){if(!ej(n.type))throw new eD("invalid_input","Event type is required.");return e.transaction(()=>{if(_(t),n.attemptId&&d(n.attemptId).request_id!==t)throw new eD("invalid_input","The attempt belongs to another request.");return E(t,n.type,n.data,n.attemptId??null,n.now??Date.now())}).immediate()},listEvents:t=>e.prepare("SELECT * FROM engine_events WHERE request_id = ? ORDER BY sequence ASC").all(t),createAttempt(t,n){if("launch"!==n.kind&&"resume"!==n.kind)throw new eD("invalid_input","Unknown attempt kind.");if(!ej(n.adapter))throw new eD("invalid_input","adapter is required.");if("resume"===n.kind&&!n.resumedSessionBindingId)throw new eD("invalid_input","A resume attempt names the session binding it resumes.");if("launch"===n.kind&&n.resumedSessionBindingId)throw new eD("invalid_input","A launch attempt does not resume a session binding.");let i="string"==typeof n.launchSnapshot?n.launchSnapshot:JSON.stringify(n.launchSnapshot);if("string"!=typeof i||0===i.length)throw new eD("invalid_input","A launch snapshot is required.");return e.transaction(()=>{let r=_(t);if("running"!==r.state)throw new eD("attempt_conflict",`Attempts start only on running requests (request is ${r.state}).`);if(n.toolProfile!==r.tool_profile)throw new eD("invalid_input",`The attempt tool profile must be ${r.tool_profile}.`);if(e.prepare("SELECT id FROM work_attempts WHERE request_id = ? AND finished_at IS NULL").get(t))throw new eD("attempt_conflict","The request already has an open attempt.");if(n.resumedSessionBindingId){let e=o.get(n.resumedSessionBindingId);if(!e)throw new eD("not_found","Session binding not found.");if(null!==e.released_at)throw new eD("session_mismatch","The session binding was released.");if(e.agent_id!==r.target_agent_id||e.adapter!==n.adapter)throw new eD("session_mismatch","The session binding belongs to another Agent or adapter.");if(null!==e.conversation_id&&e.conversation_id!==r.source_conversation_id)throw new eD("session_mismatch","The session binding belongs to another conversation.");if(null!==e.request_id&&_(e.request_id).root_request_id!==r.root_request_id)throw new eD("session_mismatch","The session binding belongs to an unrelated work request.")}let a=n.now??Date.now(),u=(0,s.randomUUID)(),c=e.prepare("SELECT COALESCE(MAX(attempt_number), 0) + 1 AS n FROM work_attempts WHERE request_id = ?").get(t);return e.prepare(`
|
|
1146
1620
|
INSERT INTO work_attempts (
|
|
1147
1621
|
id, request_id, attempt_number, kind, adapter, tool_profile, launch_snapshot, launch_snapshot_hash,
|
|
1148
1622
|
resumed_session_binding_id, external_run_id, external_session_id, started_at
|
|
1149
1623
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1150
|
-
`).run(
|
|
1624
|
+
`).run(u,t,c.n,n.kind,n.adapter,n.toolProfile,i,eJ(i),n.resumedSessionBindingId??null,n.externalRunId??null,n.externalSessionId??null,a),E(t,"attempt_started",{attempt_number:c.n,kind:n.kind,adapter:n.adapter},u,a),d(u)}).immediate()},recordAttemptExternalIds:(t,n)=>e.transaction(()=>{let i=d(t);if(null!==i.finished_at)throw new eD("attempt_conflict","The attempt is already finished.");return e.prepare("UPDATE work_attempts SET external_run_id = ?, external_session_id = ? WHERE id = ?").run(void 0===n.externalRunId?i.external_run_id:n.externalRunId,void 0===n.externalSessionId?i.external_session_id:n.externalSessionId,t),d(t)}).immediate(),finishAttempt(t,n){if(!["succeeded","failed","cancelled","interrupted","timed_out"].includes(n.outcome))throw new eD("invalid_input","Unknown attempt outcome.");return e.transaction(()=>{let i=d(t);if(null!==i.finished_at)throw new eD("attempt_conflict","The attempt is already finished.");let r=n.now??Date.now();return e.prepare(`
|
|
1151
1625
|
UPDATE work_attempts SET outcome = ?, output = ?, error_category = ?, error_message = ?, artifacts = ?,
|
|
1152
1626
|
external_run_id = ?, external_session_id = ?, finished_at = ?
|
|
1153
1627
|
WHERE id = ? AND finished_at IS NULL
|
|
1154
|
-
`).run(n.outcome,n.output??null,n.errorCategory??null,n.errorMessage??null,JSON.stringify(n.artifacts??[]),void 0===n.externalRunId?
|
|
1628
|
+
`).run(n.outcome,n.output??null,n.errorCategory??null,n.errorMessage??null,JSON.stringify(n.artifacts??[]),void 0===n.externalRunId?i.external_run_id:n.externalRunId,void 0===n.externalSessionId?i.external_session_id:n.externalSessionId,r,t),E(i.request_id,"attempt_finished",{attempt_number:i.attempt_number,outcome:n.outcome,error_category:n.errorCategory??null},t,r),d(t)}).immediate()},recordAttemptUsage(t,n){let i=d(t);eA(e,t,{agentId:_(i.request_id).target_agent_id,provider:i.adapter,usage:n.usage,observedAt:n.observedAt,now:n.now})},getAttempt:e=>i.get(e),listAttempts:t=>e.prepare("SELECT * FROM work_attempts WHERE request_id = ? ORDER BY attempt_number ASC").all(t),bindSession(t){if(!ej(t.agentId))throw new eD("invalid_input","agentId is required.");if(!ej(t.adapter))throw new eD("invalid_input","adapter is required.");if(!ej(t.externalSessionId))throw new eD("invalid_input","externalSessionId is required.");if(!t.conversationId&&!t.requestId)throw new eD("invalid_input","A session binding is scoped to a conversation or work request.");return e.transaction(()=>{let n=t.now??Date.now();if(!e.prepare("SELECT 1 FROM bots WHERE id = ?").get(t.agentId))throw new eD("not_found",`No agent ${t.agentId}.`);if(t.requestId){let e=_(t.requestId);if(e.target_agent_id!==t.agentId)throw new eD("session_mismatch","The work request targets another Agent.");if(t.conversationId&&e.source_conversation_id!==t.conversationId)throw new eD("session_mismatch","The work request belongs to another conversation.")}if(t.sourceAttemptId){let e=d(t.sourceAttemptId),n=_(e.request_id);if(e.adapter!==t.adapter||n.target_agent_id!==t.agentId)throw new eD("session_mismatch","The source attempt ran another Agent or adapter.");if(t.requestId&&e.request_id!==t.requestId)throw new eD("session_mismatch","The source attempt belongs to another work request.");if(t.conversationId&&n.source_conversation_id!==t.conversationId)throw new eD("session_mismatch","The source attempt belongs to another conversation.")}e.prepare(`
|
|
1155
1629
|
UPDATE session_bindings SET released_at = ?
|
|
1156
1630
|
WHERE agent_id = ? AND adapter = ? AND IFNULL(conversation_id, '') = ? AND IFNULL(request_id, '') = ?
|
|
1157
1631
|
AND released_at IS NULL
|
|
1158
|
-
`).run(n,t.agentId,t.adapter,t.conversationId??"",t.requestId??"");let
|
|
1632
|
+
`).run(n,t.agentId,t.adapter,t.conversationId??"",t.requestId??"");let i=(0,s.randomUUID)();return e.prepare(`
|
|
1159
1633
|
INSERT INTO session_bindings (id, agent_id, adapter, conversation_id, request_id, external_session_id, source_attempt_id, created_at)
|
|
1160
1634
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1161
|
-
`).run(
|
|
1635
|
+
`).run(i,t.agentId,t.adapter,t.conversationId??null,t.requestId??null,t.externalSessionId,t.sourceAttemptId??null,n),e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'provider_sessions'").get()&&e.prepare(`
|
|
1636
|
+
INSERT INTO provider_sessions (
|
|
1637
|
+
id, agent_id, runtime_connection_id, provider_kind, provider_session_id, binding_id, origin,
|
|
1638
|
+
availability, lifecycle, resumable, busy, created_at, updated_at
|
|
1639
|
+
)
|
|
1640
|
+
SELECT b.id, b.agent_id, ${eX(e)}, b.adapter, b.external_session_id, b.id, 'binding',
|
|
1641
|
+
'available', 'open', NULL, 0, b.created_at, b.created_at
|
|
1642
|
+
FROM session_bindings b JOIN bots bot ON bot.id = b.agent_id
|
|
1643
|
+
WHERE b.id = ?
|
|
1644
|
+
`).run(i),t.requestId&&E(t.requestId,"session_bound",{binding_id:i,adapter:t.adapter},t.sourceAttemptId??null,n),o.get(i)}).immediate()},getActiveSessionBinding:t=>e.prepare(`
|
|
1162
1645
|
SELECT * FROM session_bindings
|
|
1163
1646
|
WHERE agent_id = ? AND adapter = ? AND IFNULL(conversation_id, '') = ? AND IFNULL(request_id, '') = ?
|
|
1164
1647
|
AND released_at IS NULL
|
|
1165
|
-
`).get(t.agentId,t.adapter,t.conversationId??"",t.requestId??"")};return
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1648
|
+
`).get(t.agentId,t.adapter,t.conversationId??"",t.requestId??"")};return u}function eZ(e,t){let n=(t,...n)=>e.prepare(t).all(...n).map(e=>e.id),i=new Set(n(t.requests,t.arg)),r=new Set,s=new Set(n(t.bindings,t.arg)),a=new Set,o=(e,t)=>{let n=!1;for(let i of t)e.has(i)||(e.add(i),n=!0);return n},_=e=>JSON.stringify([...e]),d="(SELECT value FROM json_each(?))";for(;;){let e=o(r,n(`SELECT id FROM session_exchanges WHERE (${t.exchanges})
|
|
1649
|
+
OR source_request_id IN ${d} OR destination_request_id IN ${d} OR source_attempt_id IN ${d}
|
|
1650
|
+
OR destination_attempt_id IN ${d} OR source_binding_id IN ${d} OR destination_binding_id IN ${d}`,t.arg,t.arg,_(i),_(i),_(a),_(a),_(s),_(s))),E=o(i,n(`SELECT source_request_id AS id FROM session_exchanges WHERE id IN ${d} AND source_request_id IS NOT NULL
|
|
1651
|
+
UNION SELECT destination_request_id AS id FROM session_exchanges WHERE id IN ${d} AND destination_request_id IS NOT NULL`,_(r),_(r))),u=o(i,n(`SELECT id FROM work_requests WHERE parent_request_id IN ${d} OR root_request_id IN ${d}`,_(i),_(i))),c=o(i,n(`SELECT request_id AS id FROM work_attempts WHERE id IN ${d}`,_(a))),l=o(a,n(`SELECT id FROM work_attempts WHERE request_id IN ${d} OR resumed_session_binding_id IN ${d}`,_(i),_(s))),T=o(s,n(`SELECT id FROM session_bindings WHERE request_id IN ${d} OR source_attempt_id IN ${d}`,_(i),_(a)));if(!e&&!E&&!u&&!c&&!l&&!T)break}(function(e,t,...n){let i=e.prepare(`SELECT id FROM session_exchanges WHERE ${t}`).all(...n).map(e=>e.id);if(0===i.length)return;let r=eG(e);for(let e of i)r.add(e);try{e.prepare("DELETE FROM session_exchange_events WHERE exchange_id IN (SELECT value FROM json_each(?))").run(JSON.stringify(i))}finally{r.clear()}e.prepare("DELETE FROM session_exchanges WHERE id IN (SELECT value FROM json_each(?))").run(JSON.stringify(i))})(e,`id IN ${d}`,_(r)),e.prepare(`DELETE FROM conversation_events WHERE request_id IN ${d}`).run(_(i)),e.prepare(`DELETE FROM finalizations WHERE implementation_request_id IN ${d} OR review_request_id IN ${d} OR decision_request_id IN ${d}`).run(_(i),_(i),_(i)),e.prepare(`DELETE FROM candidate_manifests WHERE request_id IN ${d}`).run(_(i)),e.prepare(`DELETE FROM attempt_finalization_baselines WHERE request_id IN ${d}`).run(_(i)),e.prepare(`DELETE FROM conversation_projection_cursors WHERE request_id IN ${d}`).run(_(i)),e.prepare(`DELETE FROM wake_safety_decisions WHERE request_id IN ${d}`).run(_(i)),e.prepare(`DELETE FROM dispatch_leases WHERE request_id IN ${d}`).run(_(i)),e.prepare(`DELETE FROM attempt_launch_intents WHERE request_id IN ${d}`).run(_(i)),e.prepare(`DELETE FROM dispatch_attention WHERE request_id IN ${d}`).run(_(i));let E=eG(e);for(let e of i)E.add(e);try{e.prepare(`DELETE FROM engine_events WHERE request_id IN ${d}`).run(_(i))}finally{E.clear()}for(e0(e,`origin = 'binding' AND binding_id IN ${d}`,_(s)),e.prepare(`UPDATE provider_sessions SET binding_id = NULL WHERE binding_id IN ${d}`).run(_(s)),e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage_samples'").get()&&e.prepare(`DELETE FROM usage_samples WHERE attempt_id IN ${d}`).run(_(a));a.size>0||s.size>0;){let t=n(`SELECT id FROM session_bindings WHERE id IN ${d}
|
|
1652
|
+
AND NOT EXISTS (SELECT 1 FROM work_attempts a WHERE a.resumed_session_binding_id = session_bindings.id)`,_(s));for(let n of t)e.prepare("DELETE FROM session_bindings WHERE id = ?").run(n),s.delete(n);let i=n(`SELECT id FROM work_attempts WHERE id IN ${d}
|
|
1653
|
+
AND NOT EXISTS (SELECT 1 FROM session_bindings b WHERE b.source_attempt_id = work_attempts.id)`,_(a));for(let t of i)e.prepare("DELETE FROM work_attempts WHERE id = ?").run(t),a.delete(t);if(0===t.length&&0===i.length)throw Error("Engine records could not be removed: unexpected attempt/binding reference cycle.")}for(let t of(e.prepare(`DELETE FROM conversation_events WHERE request_id IS NULL AND wake_id IN (SELECT id FROM wakes WHERE work_request_id IN ${d} OR parent_request_id IN ${d} OR root_request_id IN ${d})`).run(_(i),_(i),_(i)),e.prepare(`DELETE FROM wakes WHERE work_request_id IN ${d} OR parent_request_id IN ${d} OR root_request_id IN ${d}`).run(_(i),_(i),_(i)),e.prepare(`DELETE FROM terminal_followups WHERE request_id IN ${d}`).run(_(i)),n(`SELECT id FROM work_requests WHERE id IN ${d} ORDER BY depth DESC`,_(i))))e.prepare("DELETE FROM work_requests WHERE id = ?").run(t)}function e0(e,t,...n){if(!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'provider_sessions'").get())return;let i=JSON.stringify(e.prepare(`SELECT id FROM provider_sessions WHERE ${t}`).all(...n).map(e=>e.id));e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage_samples'").get()&&e.prepare("DELETE FROM usage_samples WHERE session_ref IN (SELECT value FROM json_each(?))").run(i),e.prepare("DELETE FROM provider_session_events WHERE session_ref IN (SELECT value FROM json_each(?))").run(i),e.prepare("DELETE FROM provider_session_turns WHERE session_ref IN (SELECT value FROM json_each(?))").run(i),e.prepare("DELETE FROM provider_sessions WHERE id IN (SELECT value FROM json_each(?))").run(i)}function e1(e,t,...n){if(!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session_pins'").get())return;let i=JSON.stringify(e.prepare(`SELECT id FROM session_pins WHERE ${t}`).all(...n).map(e=>e.id));e.prepare("DELETE FROM session_pin_events WHERE pin_id IN (SELECT value FROM json_each(?))").run(i),e.prepare("DELETE FROM session_pin_turns WHERE pin_id IN (SELECT value FROM json_each(?))").run(i),e.prepare("DELETE FROM session_pins WHERE id IN (SELECT value FROM json_each(?))").run(i)}function e2(e,t){e.prepare("DELETE FROM conversation_intakes WHERE conversation_id = ?").run(t),e.prepare("DELETE FROM delegation_chains WHERE conversation_id = ?").run(t),e.prepare("DELETE FROM conversation_events WHERE conversation_id = ? AND request_id IS NULL").run(t),e.prepare("DELETE FROM wakes WHERE source_conversation_id = ?").run(t),e1(e,"conversation_id = ?",t),eZ(e,{requests:"SELECT id FROM work_requests WHERE source_conversation_id = ?",bindings:"SELECT id FROM session_bindings WHERE conversation_id = ?",exchanges:"origin_conversation_id = ? OR destination_conversation_id = ?",arg:t})}function e6(e,t){e.prepare(`DELETE FROM conversation_events WHERE request_id IS NULL AND wake_id IN (
|
|
1654
|
+
SELECT id FROM wakes WHERE target_agent_id = ? OR (requester_agent_id = ? AND work_request_id IS NULL))`).run(t,t),e.prepare("DELETE FROM wakes WHERE target_agent_id = ? OR (requester_agent_id = ? AND work_request_id IS NULL)").run(t,t),e.prepare("DELETE FROM wake_grants WHERE caller_agent_id = ? OR target_agent_id = ?").run(t,t),e1(e,"agent_id = ?",t),e0(e,"agent_id = ?",t),e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage_samples'").get()&&e.prepare("DELETE FROM usage_samples WHERE agent_id = ?").run(t),e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'provider_session_events'").get()&&e.prepare("DELETE FROM provider_session_events WHERE agent_id = ?").run(t),eZ(e,{requests:"SELECT id FROM work_requests WHERE target_agent_id = ?",bindings:"SELECT id FROM session_bindings WHERE agent_id = ?",exchanges:"source_agent_id = ? OR destination_agent_id = ?",arg:t})}function e4(e){if(!e)return{};try{let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}function e3(e){return"string"==typeof e&&e.length>0?e:null}function e9(e,t){return t?`${e}: ${t}`:e}function e5(e,t,n,i){let r="grant_required"===t,s=r?"needs your approval for edit work":n;return{kind:"wake_blocked",attemptId:null,text:s?`Wake blocked: ${e} — ${s}`:`Wake blocked: ${e}`,data:{...i,target_name:e,reason_code:t,reason:n,actions:r?["allow","deny"]:[]}}}e.s(["EXCHANGE_LIMITS",0,ew,"EXCHANGE_STATES",0,ef,"EXCHANGE_TERMINAL_STATES",0,ev,"EXCHANGE_TRANSITIONS",0,eh,"EngineStoreError",0,eD,"TERMINAL_STATES",0,eq,"UI_TURN_INTERRUPTED",0,e$,"UI_TURN_INTERRUPTED_MESSAGE",0,ez,"UI_TURN_REQUESTER",0,eY,"createEngineStore",0,eV,"deleteEngineRecordsForAgent",0,e6,"deleteEngineRecordsForConversation",0,e2,"migrateEngineSchema",0,eH,"uiTurnExecutionPolicy",0,eP],35613);let e7=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/,e8=/^[a-z][a-z0-9_.:-]{0,63}$/;function te(e){return null==e||""===e?null:e7.test(e)?e:"[invalid]"}function tt(e,t){return e&&e8.test(e)?e:t}let tn="agent_name_conflict";function ti(e){return String(e??"").trim()}function tr(e){return ti(e).normalize("NFC").toLowerCase().normalize("NFC")}function ts(e){return`An Agent named "${ti(e)}" already exists. Agent names must be unique, ignoring case and surrounding spaces.`}class ta extends Error{code=tn;requestedName;conflictingAgentId;constructor(e,t){super(ts(e)),this.name="AgentNameConflictError",this.requestedName=ti(e),this.conflictingAgentId=t}}function to(e){let t=[...e].sort((e,t)=>e.created_at-t.created_at||(e.id<t.id?-1:+(e.id>t.id))),n=new Map,i=[],r=[];for(let e of t){let t=tr(e.name);if(n.has(t)){i.push(e);continue}n.set(t,e.id),e.name_key!==t&&r.push({id:e.id,name:e.name,name_key:t})}let s=[];for(let e of i){let t=tr(e.name),i=ti(e.name)||"Agent",a=2;for(;n.has(tr(`${i}-${a}`));)a++;let o=`${i}-${a}`,_=tr(o);n.set(_,e.id),r.push({id:e.id,name:o,name_key:_}),s.push({bot_id:e.id,previous_name:e.name,new_name:o,name_key:t,kept_bot_id:n.get(t)})}return{updates:r,renames:s}}e.s(["AgentNameConflictError",0,ta,"agentDisplayName",0,ti,"agentNameConflictBody",0,function(e,t="name"){return{error:e.message,code:tn,field:t,name:e.requestedName,conflicting_agent_id:e.conflictingAgentId}},"agentNameConflictMessage",0,ts,"agentNameKey",0,tr,"planNameMigration",0,to],30098);let t_=(0,e.i(52036).dbPath)();":memory:"!==t_&&i.default.mkdirSync(r.default.dirname(r.default.resolve(t_)),{recursive:!0});let td=new n.default(t_);td.pragma("journal_mode = WAL"),td.exec(`
|
|
1169
1655
|
CREATE TABLE IF NOT EXISTS bots (
|
|
1170
1656
|
id TEXT PRIMARY KEY,
|
|
1171
1657
|
name TEXT NOT NULL,
|
|
@@ -1315,7 +1801,16 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1315
1801
|
ON approval_requests(conversation_id, code);
|
|
1316
1802
|
CREATE INDEX IF NOT EXISTS idx_approval_requests_conversation
|
|
1317
1803
|
ON approval_requests(conversation_id, status, created_at);
|
|
1318
|
-
`);let
|
|
1804
|
+
`);let tE=["#C6F54A","#F0A05A","#E85D75","#C9A0FF","#F2E36B"],tu="9e363764-e0d5-4fff-8ebd-ccbc46ba0ba5",tc="5fbe32c2-79cb-452e-9d9b-f8c9eb63b99b",tl=td.prepare("PRAGMA table_info(bots)").all();tl.some(e=>"color"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN color TEXT"),tl.some(e=>"pinned"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0"),tl.some(e=>"last_seen"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN last_seen INTEGER"),tl.some(e=>"unread"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN unread INTEGER NOT NULL DEFAULT 0"),tl.some(e=>"hidden"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0"),tl.some(e=>"source_provider"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN source_provider TEXT"),tl.some(e=>"template_id"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN template_id TEXT"),tl.some(e=>"template_url"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN template_url TEXT"),tl.some(e=>"import_schema_version"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN import_schema_version TEXT"),tl.some(e=>"import_operation_id"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN import_operation_id TEXT"),tl.some(e=>"import_timestamp"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN import_timestamp INTEGER"),tl.some(e=>"hermes_profile"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN hermes_profile TEXT"),tl.some(e=>"persistent_runtime"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN persistent_runtime TEXT NOT NULL DEFAULT 'hermes'"),tl.some(e=>"coding_runtime"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN coding_runtime TEXT"),tl.some(e=>"deck_name"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN deck_name TEXT"),tl.some(e=>"working_directory"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN working_directory TEXT"),tl.some(e=>"runtime"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN runtime TEXT"),tl.some(e=>"agent_client"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN agent_client TEXT"),tl.some(e=>"deck_id"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN deck_id TEXT"),tl.some(e=>"needs_deck_reselection"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN needs_deck_reselection INTEGER NOT NULL DEFAULT 0"),tl.some(e=>"agent"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN agent TEXT"),tl.some(e=>"needs_deck_selection"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN needs_deck_selection INTEGER NOT NULL DEFAULT 0");{let e=td.prepare("SELECT id, agent, runtime, agent_client, persistent_runtime, coding_runtime, deck_id, deck_name, working_directory, needs_deck_reselection, needs_deck_selection FROM bots WHERE agent IS NULL").all(),t=td.prepare("UPDATE bots SET agent = ?, deck_id = ?, deck_name = ?, working_directory = ?, needs_deck_selection = ? WHERE id = ?");td.transaction(e=>{for(let n of e){let e=(0,a.migrateLegacyAgentFields)(n);t.run(e.agent,e.deck_id,e.deck_name,e.working_directory,+!!e.needs_deck_selection,n.id)}})(e)}for(let[e,t]of(tl.some(e=>"avatar_color"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN avatar_color TEXT"),tl.some(e=>"avatar_eyes"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN avatar_eyes TEXT"),tl.some(e=>"avatar_hands"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN avatar_hands TEXT"),tl.some(e=>"avatar_accessory"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN avatar_accessory TEXT"),td.exec(`
|
|
1805
|
+
CREATE TABLE IF NOT EXISTS runtime_connections (
|
|
1806
|
+
id TEXT PRIMARY KEY,
|
|
1807
|
+
provider TEXT NOT NULL,
|
|
1808
|
+
label TEXT NOT NULL,
|
|
1809
|
+
host TEXT NOT NULL,
|
|
1810
|
+
created_at INTEGER NOT NULL
|
|
1811
|
+
);
|
|
1812
|
+
`),[["runtime_connection_id","TEXT"],["launch_profile","TEXT"],["session_scope_kind","TEXT"],["session_scope_items","TEXT"],["default_workspace","TEXT"],["policy_mode","TEXT"],["allow_new_sessions","INTEGER"],["allow_resume_with_edits","INTEGER"],["home_session_id","TEXT"]]))tl.some(t=>t.name===e)||td.exec(`ALTER TABLE bots ADD COLUMN ${e} ${t}`);function tT(e,t=Date.now()){let n=v(e);return td.prepare("INSERT OR IGNORE INTO runtime_connections (id, provider, label, host, created_at) VALUES (?, ?, ?, ?, ?)").run(n,e,h(e),E,t),n}for(let e of a.AGENTS)tT(e,0);td.transaction(()=>{let e=td.prepare("SELECT id, agent, deck_id, working_directory, needs_deck_selection, created_at FROM bots WHERE runtime_connection_id IS NULL").all(),t=td.prepare(`UPDATE bots SET runtime_connection_id = ?, launch_profile = ?, session_scope_kind = ?, session_scope_items = ?,
|
|
1813
|
+
policy_mode = ?, allow_new_sessions = ?, allow_resume_with_edits = ? WHERE id = ?`);for(let n of e){let e=X(n);tT(e.provider,n.created_at),t.run(e.runtime_connection_id,e.launch_profile,e.session_scope_kind,e.session_scope_items,e.policy_mode,e.allow_new_sessions,e.allow_resume_with_edits,n.id)}})(),tl.some(e=>"name_key"===e.name)||td.exec("ALTER TABLE bots ADD COLUMN name_key TEXT"),td.exec(`
|
|
1319
1814
|
CREATE TABLE IF NOT EXISTS agent_name_migrations (
|
|
1320
1815
|
id TEXT PRIMARY KEY,
|
|
1321
1816
|
bot_id TEXT NOT NULL,
|
|
@@ -1326,10 +1821,10 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1326
1821
|
reason TEXT NOT NULL,
|
|
1327
1822
|
created_at INTEGER NOT NULL
|
|
1328
1823
|
);
|
|
1329
|
-
`),
|
|
1824
|
+
`),td.transaction(()=>{let e=to(td.prepare("SELECT id, name, created_at, name_key FROM bots").all());if(0===e.updates.length)return;let t=td.prepare("UPDATE bots SET name_key = NULL WHERE id = ?");for(let n of e.updates)t.run(n.id);let n=td.prepare("UPDATE bots SET name = ?, name_key = ? WHERE id = ?");for(let t of e.updates)n.run(t.name,t.name_key,t.id);let i=td.prepare("INSERT INTO agent_name_migrations (id, bot_id, previous_name, new_name, name_key, kept_bot_id, reason, created_at) VALUES (?, ?, ?, ?, ?, ?, 'duplicate_name', ?)"),r=Date.now();for(let t of e.renames)i.run((0,s.randomUUID)(),t.bot_id,t.previous_name,t.new_name,t.name_key,t.kept_bot_id,r),console.warn(`[botmancers] Agent ${t.bot_id} renamed "${t.previous_name}" -> "${t.new_name}": name already used by Agent ${t.kept_bot_id}.`)})(),td.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_bots_name_key ON bots(name_key)"),td.exec(`
|
|
1330
1825
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_bots_import_operation
|
|
1331
1826
|
ON bots(import_operation_id) WHERE import_operation_id IS NOT NULL
|
|
1332
|
-
`),
|
|
1827
|
+
`),td.prepare("UPDATE bots SET color = ? WHERE id = ?").run(tE[0],tu),td.prepare("UPDATE bots SET color = ? WHERE id = ?").run(tE[1],tc);let tp=td.prepare("SELECT id FROM bots WHERE id NOT IN (?, ?) ORDER BY created_at ASC").all(tu,tc),tN=td.prepare("UPDATE bots SET color = ? WHERE id = ?");function tR(e,t){let n=ti(e),i=tr(n),r=td.prepare("SELECT id FROM bots WHERE name_key = ?").get(i);if(r&&r.id!==t)throw new ta(n,r.id);return{name:n,name_key:i}}function tm(e,t){try{return t()}catch(t){if(t instanceof Error&&/UNIQUE constraint failed: bots\.name_key/.test(t.message)){let t=td.prepare("SELECT id FROM bots WHERE name_key = ?").get(tr(e));throw new ta(e,t?.id??null)}throw t}}function tL(){return tE[td.prepare("SELECT COUNT(*) AS n FROM bots").get().n%tE.length]}tp.forEach((e,t)=>{tN.run(tE[(t+2)%tE.length],e.id)});let tg=td.prepare("PRAGMA table_info(messages)").all();tg.some(e=>"handoff_targets"===e.name)||td.exec("ALTER TABLE messages ADD COLUMN handoff_targets TEXT"),td.prepare("PRAGMA table_info(groups)").all().some(e=>"owner_bot_id"===e.name)||td.exec("ALTER TABLE groups ADD COLUMN owner_bot_id TEXT"),td.prepare("PRAGMA table_info(launch_snapshots)").all().some(e=>"transport"===e.name)||td.exec("ALTER TABLE launch_snapshots ADD COLUMN transport TEXT NOT NULL DEFAULT 'hermes-gateway'");let tO=td.prepare("PRAGMA table_info(conversations)").all();tO.some(e=>"origin_kind"===e.name)||td.exec("ALTER TABLE conversations ADD COLUMN origin_kind TEXT"),tO.some(e=>"origin_id"===e.name)||td.exec("ALTER TABLE conversations ADD COLUMN origin_id TEXT"),tg.some(e=>"sender_kind"===e.name)||td.exec("ALTER TABLE messages ADD COLUMN sender_kind TEXT"),tg.some(e=>"request_id"===e.name)||td.exec("ALTER TABLE messages ADD COLUMN request_id TEXT"),td.exec(`
|
|
1333
1828
|
CREATE TABLE IF NOT EXISTS conversation_participants (
|
|
1334
1829
|
conversation_id TEXT NOT NULL,
|
|
1335
1830
|
participant_kind TEXT NOT NULL,
|
|
@@ -1338,49 +1833,81 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1338
1833
|
PRIMARY KEY (conversation_id, participant_kind, participant_id),
|
|
1339
1834
|
FOREIGN KEY (conversation_id) REFERENCES conversations(id)
|
|
1340
1835
|
);
|
|
1341
|
-
`),
|
|
1836
|
+
`),eH(td);let tI=eV(td),tA=function(e){let t=e.prepare("SELECT * FROM work_requests WHERE id = ?"),n=e.prepare("SELECT * FROM work_attempts WHERE id = ?"),i=e.prepare("SELECT * FROM engine_events WHERE request_id = ? ORDER BY sequence ASC"),r=e.prepare("SELECT sequence FROM conversation_projection_cursors WHERE request_id = ?"),s=e.prepare(`
|
|
1342
1837
|
INSERT INTO conversation_projection_cursors (request_id, sequence) VALUES (?, ?)
|
|
1343
1838
|
ON CONFLICT (request_id) DO UPDATE SET sequence = excluded.sequence WHERE excluded.sequence > sequence
|
|
1344
|
-
`),
|
|
1839
|
+
`),a=e.prepare(`
|
|
1345
1840
|
INSERT OR IGNORE INTO conversation_events (
|
|
1346
1841
|
id, conversation_id, engine_event_id, part, request_id, request_sequence, attempt_id, wake_id,
|
|
1347
1842
|
kind, state, text, data, sort_at, request_created_at, created_at
|
|
1348
1843
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1349
|
-
`);function o(e){return e?n.get(e):void 0}function
|
|
1844
|
+
`);function o(e){return e?n.get(e):void 0}function _(n){return e.transaction(()=>{let e=t.get(n);if(!e)return 0;let _=r.get(n)?.sequence??0,d=i.all(n),E=d.length>0?d[d.length-1].sequence:0;if(E<=_)return 0;let u={state:null,lastFinished:null},c=0,l=0;for(let t of d){c=Math.max(c,t.created_at);let n={...u};!function(e,t){let n=e4(t.data);"accepted"===t.type&&e3(n.state)&&(e.state=n.state),"state_changed"===t.type&&e3(n.to)&&(e.state=n.to),"attempt_finished"===t.type&&t.attempt_id&&(e.lastFinished={attemptId:t.attempt_id,outcome:e3(n.outcome)})}(u,t),t.sequence<=_||null!==e.legacy_agent_request_id||(function(e,t,n){let i=e4(e.data),r=e4(t.policy_snapshot),s=null!==t.wake_event_id,a=e3(r.target_name_snapshot)??t.target_agent_id,_={target_agent_id:t.target_agent_id,execution_kind:t.execution_kind,tool_profile:t.tool_profile};switch(e.type){case"accepted":if("blocked"===i.state)return[];if(s)return[{kind:"wake_accepted",attemptId:null,text:`Wake accepted: ${a} (${t.execution_kind})`,data:{..._,target_name:a,requester_kind:t.requester_kind,requester_id:t.requester_id,parent_request_id:t.parent_request_id,depth:t.depth,wake_depth:t.wake_depth,grant_rule:e3(r.grant_rule),grant_id:e3(r.grant_id)}}];return[{kind:"request_queued",attemptId:null,text:"Queued",data:{..._,requester_kind:t.requester_kind,requester_id:t.requester_id}}];case"state_changed":{let e=e3(i.to),r=e3(i.from),d=e3(i.reason);switch(e){case"blocked":if(s&&"queued"===r&&"blocked"===n.state){let e=function(e){if(!e)return{code:null,reason:null};let t=/^([a-z_]+): ([\s\S]*)$/.exec(e);return t?{code:t[1],reason:t[2]}:{code:null,reason:e}}(d);return[e5(a,e.code,e.reason,_)]}return[{kind:"request_blocked",attemptId:null,text:e9("Blocked",d),data:{from:r,reason:d}}];case"queued":if("retry_scheduled"===d){let e="number"==typeof i.attempt_count?i.attempt_count:null,t="number"==typeof i.max_attempts?i.max_attempts:null;return[{kind:"request_retry_scheduled",attemptId:n.lastFinished?.attemptId??null,text:!0===i.manual?`Retry requested${null!==e&&null!==t?` (Attempt ${e+1} of ${t})`:""}`:`Retry scheduled${null!==e&&null!==t?` (Attempt ${e+1} of ${t})`:""}${"number"==typeof i.delay_ms?` in ${i.delay_ms} ms`:""}`,data:{from:r,reason:d,manual:!0===i.manual,attempt_count:e,max_attempts:t,next_eligible_at:i.next_eligible_at??null,delay_ms:i.delay_ms??null,category:i.category??null,outcome:n.lastFinished?.outcome??null}}]}if(s&&"blocked"===r&&("grant_approved"===d||"target_available"===d))return[{kind:"wake_accepted",attemptId:null,text:`Wake accepted: ${a} (${t.execution_kind})`,data:{..._,target_name:a,requester_kind:t.requester_kind,requester_id:t.requester_id,parent_request_id:t.parent_request_id,depth:t.depth,wake_depth:t.wake_depth,reason:d,grant_rule:i.grant_rule??null,grant_id:i.grant_id??null}}];return[{kind:"request_queued",attemptId:null,text:e9("Queued again",d),data:{from:r,reason:d}}];case"running":return[{kind:"request_running",attemptId:null,text:"Running",data:{phase:"dispatched",from:r}}];case"waiting":return[{kind:"request_waiting",attemptId:null,text:e9("Waiting",d),data:{from:r,reason:d}}];case"completed":{let e=n.lastFinished,i=e?.outcome==="succeeded",r=[{kind:"request_completed",attemptId:e?.attemptId??null,text:i?"Completed":"Completed without a successful Attempt outcome",data:{success:i,outcome:e?.outcome??null}}];if(i&&e){let n=o(e.attemptId),i=e4(t.result);r.push({kind:"result",attemptId:e.attemptId,text:n?.output??"Result recorded",data:{reply_message_id:e3(i.reply_message_id),has_output:"string"==typeof n?.output}})}return r}case"failed":case"cancelled":{let s=n.lastFinished,a=t.error_code??e3(i.error_code),o=t.error_message;if("failed"===e&&"timed_out"===d)return[{kind:"request_timed_out",attemptId:s?.attemptId??null,text:"Timed out: the request passed its deadline",data:{success:!1,error_code:a,reason:d,deadline_at:i.deadline_at??null,from:r,outcome:s?.outcome??null}}];if("failed"===e&&"retries_exhausted"===d)return[{kind:"request_retries_exhausted",attemptId:s?.attemptId??null,text:e9(`Retries exhausted after ${i.attempt_count??"?"} of ${i.max_attempts??"?"} Attempts`,o??a),data:{success:!1,error_code:a,error_message:o,reason:d,attempt_count:i.attempt_count??null,max_attempts:i.max_attempts??null,outcome:s?.outcome??null}}];return[{kind:"failed"===e?"request_failed":"request_cancelled",attemptId:s?.attemptId??null,text:"failed"===e?e9("Failed",o??a):"cancel_requested"===d?e9("Cancelled",t.cancel_reason):"grant_denied"===d?"Cancelled: owner denied edit Wake":e9("Cancelled",d??o),data:{success:!1,error_code:a,error_message:o,reason:d,outcome:s?.outcome??null}}]}default:return[]}}case"runtime_started":{let t=e3(i.adapter);return[{kind:"request_running",attemptId:e.attempt_id,text:t?`Running on ${t}`:"Running",data:{phase:"runtime_started",adapter:t,external_run_id:e3(i.external_run_id),success:!1}}]}case"wake_reblocked":return[e5(a,e3(i.reason_code),e3(i.reason),_)];case"dispatch_deferred":return[{kind:"request_queued",attemptId:null,text:"Queued: waiting for capacity",data:{waiting_for:"capacity",limit:e3(i.reason),active_global:i.active_global??null,active_target:i.active_target??null,max_global:i.max_global??null,max_per_target:i.max_per_target??null}}];case"lineage_stopped":return[{kind:"lineage_stopped",attemptId:null,text:"continuation_budget_exhausted"===i.reason?`Stopped: coordinator continuation limit ${i.limit??"?"} reached`:e9("Stopped",e3(i.reason)),data:i}];case"cancel_requested":{let e=e3(i.reason);return[{kind:"request_cancel_requested",attemptId:null,text:e9("Cancel requested",e),data:{by:e3(i.by),reason:e,state:e3(i.state)}}]}case"question":{let t=e3(i.question)??"";return[{kind:"question",attemptId:e.attempt_id,text:t,data:{question:t}}]}case"attempt_finished":{let t=o(e.attempt_id);if(!t)return[];let n=[];try{let e=JSON.parse(t.artifacts);Array.isArray(e)&&(n=e)}catch{}return n.filter(e=>!(e&&"object"==typeof e&&"candidate_manifest"===e.kind)).map(e=>{let n=e&&"object"==typeof e?e:{ref:String(e)},i=e3(n.kind)??"artifact",r=e3(n.ref)??"";return{kind:"artifact",attemptId:t.id,text:`Artifact (${i}): ${r}`,data:{artifact_kind:i,ref:r,outcome:t.outcome}}})}case"candidate_manifest_recorded":{let t=e3(i.manifest_digest),n="number"==typeof i.file_count?i.file_count:0;return[{kind:"artifact",attemptId:e.attempt_id,text:`Candidate manifest ${t}: ${n} ${1===n?"file":"files"} on base ${e3(i.base_commit)}`,data:{artifact_kind:"candidate_manifest",ref:t,...i}}]}case"candidate_manifest_unavailable":return[{kind:"finalization_blocked",attemptId:e.attempt_id,text:e9("Not finalizable",e3(i.reason_code)),data:{phase:"candidate",...i}}];case"finalization_preparing":return[{kind:"finalization_preparing",attemptId:e.attempt_id,text:`Finalization preparing: manifest ${e3(i.manifest_digest)} (${i.file_count??0} files), review ${e3(i.review_request_id)}`,data:i}];case"finalization_retry_pending":return[{kind:"finalization_preparing",attemptId:e.attempt_id,text:e9("Finalization waiting to retry",e3(i.reason_code)),data:{retry:!0,...i}}];case"finalization_committed":return[{kind:"finalization_committed",attemptId:e.attempt_id,text:`Finalization committed: commit ${e3(i.commit)} (tree ${e3(i.tree)}, manifest ${e3(i.result_manifest_digest)??e3(i.manifest_digest)})`,data:{success:!0,...i}}];case"finalization_blocked":case"finalization_failed":case"finalization_canceled":{let t="finalization_blocked"===e.type?"blocked":"finalization_failed"===e.type?"failed":"canceled";return[{kind:e.type,attemptId:e.attempt_id,text:e9(`Finalization ${t}`,e3(i.reason_code)),data:{success:!1,...i}}]}case"finalization_rejected":return[{kind:"finalization_rejected",attemptId:null,text:e9("Finalization not started",e3(i.reason_code)),data:i}];default:return[]}})(t,e,n).forEach((n,i)=>{l+=a.run(`${t.id}:${i}`,e.source_conversation_id,t.id,i,e.id,t.sequence,n.attemptId,e.wake_event_id,n.kind,u.state,n.text,JSON.stringify(n.data),c,e.created_at,t.created_at).changes})}return s.run(n,E),l}).immediate()}function d(t){return e.transaction(()=>e.prepare("SELECT id FROM work_requests WHERE source_conversation_id = ? ORDER BY created_at ASC, id ASC").all(t).reduce((e,t)=>e+_(t.id),0)+function(t){let n=e.prepare(`
|
|
1350
1845
|
SELECT w.* FROM wakes w
|
|
1351
1846
|
WHERE w.source_conversation_id = ? AND w.status = 'rejected'
|
|
1352
1847
|
AND NOT EXISTS (SELECT 1 FROM conversation_events e WHERE e.id = 'wake:' || w.id || ':0')
|
|
1353
1848
|
ORDER BY w.created_at ASC, w.position ASC
|
|
1354
|
-
`).all(t),
|
|
1849
|
+
`).all(t),i=0;for(let e of n){let t={wake_id:e.id,target_name:e.target_name_snapshot??e.requested_target,target_agent_id:e.target_agent_id,execution_kind:e.execution_kind,requester_agent_id:e.requester_agent_id,parent_request_id:e.parent_request_id,reason_code:e.reason_code,reason:e.reason,limit:e.limit_value,observed:e.observed_value,work_request_id:null};i+=a.run(`wake:${e.id}:0`,e.source_conversation_id,null,0,null,0,null,e.id,"wake_rejected",null,function(e){let t=e.target_name_snapshot??e.requested_target??"an unnamed target";switch(e.reason_code){case"untracked_lineage":return"Wake not started: its source turn is not tracked work";case"depth_exceeded":return`Wake not started: ${t} — depth limit ${e.limit_value??"?"} reached`;case"root_budget_exhausted":return`Wake not started: ${t} — this work already used ${e.observed_value??e.limit_value??"?"} Wakes`;default:return e.reason?`Wake not started: ${t} — ${e.reason}`:`Wake not started: ${t}`}}(e),JSON.stringify(t),e.updated_at,e.created_at,e.updated_at).changes}return i}(t)).immediate()}function E(t){return e.prepare(`
|
|
1355
1850
|
SELECT * FROM conversation_events WHERE conversation_id = ?
|
|
1356
1851
|
ORDER BY sort_at ASC, request_created_at ASC, COALESCE(request_id, wake_id) ASC, request_sequence ASC, part ASC
|
|
1357
|
-
`).all(t)}return{projectRequest:
|
|
1852
|
+
`).all(t)}return{projectRequest:_,projectConversation:d,projectEvent:function(e){return _(e.request_id)},listConversationEventRows:E,listConversationEvents:function(e){return d(e),E(e).map((e,t)=>({eventId:e.id,seq:t+1,kind:e.kind,requestId:e.request_id,requestSequence:e.request_sequence,attemptId:e.attempt_id,wakeId:e.wake_id,engineEventId:e.engine_event_id,state:e.state,text:e.text,data:e4(e.data),createdAt:e.created_at}))}}}(td),tS=(td.exec(`
|
|
1853
|
+
CREATE TABLE IF NOT EXISTS service_audit_events (
|
|
1854
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1855
|
+
at INTEGER NOT NULL,
|
|
1856
|
+
principal TEXT NOT NULL CHECK (length(principal) BETWEEN 1 AND 200),
|
|
1857
|
+
operation TEXT NOT NULL CHECK (length(operation) BETWEEN 1 AND 64),
|
|
1858
|
+
capability TEXT NOT NULL CHECK (length(capability) BETWEEN 1 AND 64),
|
|
1859
|
+
target_kind TEXT NOT NULL CHECK (target_kind IN ('grants', 'agent', 'session', 'conversation', 'exchange', 'request')),
|
|
1860
|
+
target_ref TEXT CHECK (target_ref IS NULL OR length(target_ref) <= 128),
|
|
1861
|
+
agent_id TEXT CHECK (agent_id IS NULL OR length(agent_id) <= 128),
|
|
1862
|
+
outcome TEXT NOT NULL CHECK (outcome IN ('allowed', 'denied', 'rejected', 'error')),
|
|
1863
|
+
code TEXT CHECK (code IS NULL OR length(code) <= 64)
|
|
1864
|
+
);
|
|
1865
|
+
CREATE INDEX IF NOT EXISTS idx_service_audit_principal ON service_audit_events(principal, id);
|
|
1866
|
+
CREATE TRIGGER IF NOT EXISTS trg_service_audit_no_update BEFORE UPDATE ON service_audit_events
|
|
1867
|
+
BEGIN
|
|
1868
|
+
SELECT RAISE(ABORT, 'service_audit_events are append-only');
|
|
1869
|
+
END;
|
|
1870
|
+
CREATE TRIGGER IF NOT EXISTS trg_service_audit_no_delete BEFORE DELETE ON service_audit_events
|
|
1871
|
+
BEGIN
|
|
1872
|
+
SELECT RAISE(ABORT, 'service_audit_events are append-only');
|
|
1873
|
+
END;
|
|
1874
|
+
`),t=td.prepare(`
|
|
1875
|
+
INSERT INTO service_audit_events (at, principal, operation, capability, target_kind, target_ref, agent_id, outcome, code)
|
|
1876
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1877
|
+
`),{append(e){let n=`${e.principal.kind}:${te(e.principal.id)??"[invalid]"}`;t.run(e.at??Date.now(),n.slice(0,200),tt(e.operation,"unknown"),tt(e.capability,"none"),e.targetKind,te(e.targetRef),te(e.agentId),e.outcome,e.code?tt(e.code,"unknown"):null)},list(e={}){let t=Math.min(Math.max(1,e.limit??50),500);return e.principal?td.prepare("SELECT * FROM service_audit_events WHERE principal = ? ORDER BY id DESC LIMIT ?").all(e.principal,t):td.prepare("SELECT * FROM service_audit_events ORDER BY id DESC LIMIT ?").all(t)}}),tk={kind:"person",id:"local-owner"},tf=td.prepare("INSERT OR IGNORE INTO conversation_participants (conversation_id, participant_kind, participant_id, joined_at) VALUES (?, ?, ?, ?)");function tv(e,t,n){for(let i of(td.prepare("UPDATE conversations SET origin_kind = ?, origin_id = ? WHERE id = ? AND origin_kind IS NULL").run(tk.kind,tk.id,e),tf.run(e,tk.kind,tk.id,n),t))tf.run(e,"bot",i,n)}td.transaction(()=>{td.exec("UPDATE messages SET sender_kind = 'person' WHERE sender_kind IS NULL AND sender_type = 'user'"),td.exec("UPDATE messages SET sender_kind = 'bot' WHERE sender_kind IS NULL AND sender_type = 'bot'");let e=td.prepare("SELECT id, type, bot_id, group_id, created_at FROM conversations WHERE origin_kind IS NULL AND type IN ('bot', 'group')").all(),t=td.prepare("SELECT bot_id FROM group_members WHERE group_id = ?");for(let n of e){let e="bot"===n.type?n.bot_id?[n.bot_id]:[]:n.group_id?t.all(n.group_id).map(e=>e.bot_id):[];tv(n.id,e,n.created_at)}})();let th={getAll:()=>td.prepare("SELECT * FROM runtime_connections ORDER BY created_at ASC, id ASC").all(),getById:e=>{let t=td.prepare("SELECT * FROM runtime_connections WHERE id = ?").get(e);return t&&a.AGENTS.includes(t.provider)?t:void 0},create:e=>{let t={id:`rc-${(0,s.randomUUID)()}`,...e,created_at:Date.now()};return td.prepare("INSERT INTO runtime_connections (id, provider, label, host, created_at) VALUES (?, ?, ?, ?, ?)").run(t.id,t.provider,t.label,t.host,t.created_at),t},ensureLocal:e=>tT(e),agentCount:e=>td.prepare("SELECT COUNT(*) AS n FROM bots WHERE runtime_connection_id = ?").get(e).n},tw=["session_scope_kind","session_scope_items","policy_mode","allow_new_sessions","allow_resume_with_edits"],tC={create:(e,t)=>{let n=tR(e.name),i={id:t?.id||(0,s.randomUUID)(),...e,...n,color:tL(),created_at:t?.created_at??Date.now()};i.agent=i.agent||a.DEFAULT_AGENT,i.deck_id=i.deck_id||null,i.needs_deck_selection=!i.deck_id||i.needs_deck_selection?1:0;let r=X({...i,needs_deck_selection:i.needs_deck_selection});i.runtime_connection_id||(i.runtime_connection_id=tT(r.provider,i.created_at)),void 0===i.launch_profile&&(i.launch_profile=r.launch_profile),"direct"===i.launch_profile&&(i.deck_id=null,i.working_directory=null,i.needs_deck_selection=0),i.session_scope_kind||(i.session_scope_kind=r.session_scope_kind,i.session_scope_items=r.session_scope_items),i.policy_mode||(i.policy_mode=r.policy_mode,i.allow_new_sessions=r.allow_new_sessions,i.allow_resume_with_edits=r.allow_resume_with_edits),tm(i.name,()=>td.prepare(`INSERT INTO bots (id, name, name_key, title, description, avatar, color, hermes_profile, agent, deck_id, deck_name, working_directory, needs_deck_selection,
|
|
1878
|
+
runtime_connection_id, launch_profile, session_scope_kind, session_scope_items, default_workspace, policy_mode, allow_new_sessions, allow_resume_with_edits, home_session_id,
|
|
1879
|
+
avatar_color, avatar_eyes, avatar_hands, avatar_accessory, created_at)
|
|
1880
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(i.id,i.name,i.name_key,i.title,i.description,i.avatar||null,i.color,i.hermes_profile||null,i.agent,i.deck_id,i.deck_name||null,i.working_directory||null,i.needs_deck_selection,i.runtime_connection_id,i.launch_profile??null,i.session_scope_kind,i.session_scope_items??"[]",i.default_workspace||null,i.policy_mode,+!!i.allow_new_sessions,+!!i.allow_resume_with_edits,null,i.avatar_color||null,i.avatar_eyes||null,i.avatar_hands||null,i.avatar_accessory||null,i.created_at));let o=(0,s.randomUUID)();return td.prepare("INSERT INTO conversations (id, type, bot_id, created_at) VALUES (?, ?, ?, ?)").run(o,"bot",i.id,i.created_at),tv(o,[i.id],i.created_at),i},createFromImport:(e,t)=>{let n=tR(e.name),i={id:(0,s.randomUUID)(),...e,...n,color:tL(),created_at:Date.now(),agent:a.DEFAULT_AGENT,deck_id:null,deck_name:null,working_directory:null,needs_deck_selection:1,source_provider:t.source_provider,template_id:t.template_id,template_url:t.template_url,import_schema_version:t.import_schema_version,import_operation_id:t.import_operation_id,import_timestamp:t.import_timestamp},r=X(i);Object.assign(i,{runtime_connection_id:tT(r.provider,i.created_at),launch_profile:null,session_scope_kind:r.session_scope_kind,session_scope_items:r.session_scope_items,policy_mode:r.policy_mode,allow_new_sessions:r.allow_new_sessions,allow_resume_with_edits:r.allow_resume_with_edits}),tm(i.name,()=>td.prepare(`INSERT INTO bots (
|
|
1358
1881
|
id, name, name_key, title, description, avatar, color, created_at,
|
|
1359
1882
|
source_provider, template_id, template_url, import_schema_version,
|
|
1360
1883
|
import_operation_id, import_timestamp,
|
|
1361
1884
|
agent, deck_id, deck_name, working_directory,
|
|
1362
|
-
needs_deck_selection
|
|
1363
|
-
|
|
1885
|
+
needs_deck_selection,
|
|
1886
|
+
runtime_connection_id, launch_profile, session_scope_kind, session_scope_items,
|
|
1887
|
+
policy_mode, allow_new_sessions, allow_resume_with_edits
|
|
1888
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(i.id,i.name,i.name_key,i.title,i.description,i.avatar||null,i.color,i.created_at,i.source_provider,i.template_id,i.template_url,i.import_schema_version,i.import_operation_id,i.import_timestamp,i.agent,i.deck_id,i.deck_name,i.working_directory,i.needs_deck_selection,i.runtime_connection_id,i.launch_profile,i.session_scope_kind,i.session_scope_items,i.policy_mode,i.allow_new_sessions,i.allow_resume_with_edits));let o=(0,s.randomUUID)();return td.prepare("INSERT INTO conversations (id, type, bot_id, created_at) VALUES (?, ?, ?, ?)").run(o,"bot",i.id,i.created_at),tv(o,[i.id],i.created_at),i},getByImportOperationId:e=>td.prepare("SELECT * FROM bots WHERE import_operation_id = ?").get(e),getAll:()=>td.prepare("SELECT * FROM bots ORDER BY created_at DESC").all(),getById:e=>td.prepare("SELECT * FROM bots WHERE id = ?").get(e),setAvatar:(e,t)=>{td.prepare("UPDATE bots SET avatar = ? WHERE id = ?").run(t,e)},getByName:e=>{let t=tr(e);if(t)return td.prepare("SELECT * FROM bots WHERE name_key = ?").get(t)},updateIdentity:(e,t,n,i)=>{let r=tR(t,e);tm(r.name,()=>td.prepare("UPDATE bots SET name = ?, name_key = ?, title = ?, description = ? WHERE id = ?").run(r.name,r.name_key,n,i,e))},setPinned:(e,t)=>{td.prepare("UPDATE bots SET pinned = ? WHERE id = ?").run(+!!t,e)},setHidden:(e,t)=>{td.prepare("UPDATE bots SET hidden = ? WHERE id = ?").run(+!!t,e)},setHermesProfile:(e,t)=>{let n=t&&t.trim()?t.trim():null;td.prepare("UPDATE bots SET hermes_profile = ? WHERE id = ?").run(n,e)},updateRegistration:(e,t,n)=>{let i=tC.getById(e);if(!i)return;let r=W(n),s="agent_deck"===n.launch_profile&&n.deck_id?null:i.deck_name??null;td.prepare(`UPDATE bots SET agent = ?, deck_name = ?, runtime_connection_id = ?, launch_profile = ?, deck_id = ?, working_directory = ?,
|
|
1889
|
+
session_scope_kind = ?, session_scope_items = ?, default_workspace = ?, policy_mode = ?, allow_new_sessions = ?,
|
|
1890
|
+
allow_resume_with_edits = ?, home_session_id = ?, needs_deck_selection = ? WHERE id = ?`).run(t,s,r.runtime_connection_id,r.launch_profile,r.deck_id,r.working_directory,r.session_scope_kind,r.session_scope_items,r.default_workspace,r.policy_mode,r.allow_new_sessions,r.allow_resume_with_edits,r.home_session_id,r.needs_deck_selection,e)},updateAgentSelection:(e,t)=>{let n=tC.getById(e);if(!n)return;let i=(0,a.applyAgentUpdate)(n,t),r=void 0!==t.deck_id?"agent_deck":n.launch_profile??null,s=n.runtime_connection_id?th.getById(n.runtime_connection_id):void 0,o=s&&s.provider===i.agent?s.id:tT(i.agent);td.prepare("UPDATE bots SET agent = ?, deck_id = ?, deck_name = ?, working_directory = ?, needs_deck_selection = ?, launch_profile = ?, runtime_connection_id = ? WHERE id = ?").run(i.agent,"direct"===r?null:i.deck_id,i.deck_name,"direct"===r?null:i.working_directory,"direct"===r?0:+!!i.needs_deck_selection,r,o,e)},updateAvatarConfig:(e,t)=>{let n=tC.getById(e);if(!n)return;let i=(e,t)=>void 0===e?t||null:e&&String(e).trim()?String(e).trim():null;td.prepare("UPDATE bots SET avatar_color = ?, avatar_eyes = ?, avatar_hands = ?, avatar_accessory = ? WHERE id = ?").run(i(t.avatar_color,n.avatar_color),i(t.avatar_eyes,n.avatar_eyes),i(t.avatar_hands,n.avatar_hands),i(t.avatar_accessory,n.avatar_accessory),e)},touchSeen:()=>{td.prepare("UPDATE bots SET last_seen = ?").run(Date.now())},markUnread:e=>{td.prepare("UPDATE bots SET unread = 1 WHERE id = ?").run(e)},markRead:e=>{td.prepare("UPDATE bots SET unread = 0 WHERE id = ?").run(e)},remove:e=>{tC.removeMany([e])},deletionPreview:e=>{var t;let n=new Set(e),i=[],r=[],s=[],a=new Set(ty());for(let t of e){let e=tC.getById(t);if(!e){r.push(t);continue}i.push({id:e.id,name:e.name}),(0,J.isChiefOfStaffName)(e.name)?s.push({id:e.id,name:e.name,reason:"chief"}):a.has(e.id)&&s.push({id:e.id,name:e.name,reason:"active"})}return{agents:i,groups:0===(t=n).size?[]:td.prepare(`SELECT DISTINCT g.id, g.name, g.owner_bot_id, g.created_at FROM groups g
|
|
1364
1891
|
JOIN group_members gm ON gm.group_id = g.id
|
|
1365
1892
|
WHERE gm.bot_id IN (${[...t].map(()=>"?").join(", ")})
|
|
1366
|
-
ORDER BY g.created_at ASC, g.id ASC`).all(...t).map(e=>{let n=
|
|
1367
|
-
WHERE gm.group_id = ? ORDER BY b.created_at ASC, b.id ASC`).all(e.id).filter(e=>!t.has(e.id));return n.length<2?{id:e.id,name:e.name,outcome:"removed",remaining:n.length,newOwner:null}:e.owner_bot_id&&t.has(e.owner_bot_id)?{id:e.id,name:e.name,outcome:"reassigned",remaining:n.length,newOwner:n[0]}:{id:e.id,name:e.name,outcome:"shrunk",remaining:n.length,newOwner:null}}),missing:
|
|
1893
|
+
ORDER BY g.created_at ASC, g.id ASC`).all(...t).map(e=>{let n=td.prepare(`SELECT b.id, b.name FROM bots b JOIN group_members gm ON gm.bot_id = b.id
|
|
1894
|
+
WHERE gm.group_id = ? ORDER BY b.created_at ASC, b.id ASC`).all(e.id).filter(e=>!t.has(e.id));return n.length<2?{id:e.id,name:e.name,outcome:"removed",remaining:n.length,newOwner:null}:e.owner_bot_id&&t.has(e.owner_bot_id)?{id:e.id,name:e.name,outcome:"reassigned",remaining:n.length,newOwner:n[0]}:{id:e.id,name:e.name,outcome:"shrunk",remaining:n.length,newOwner:null}}),missing:r,blocked:s}},removeMany:(e,t)=>td.transaction(()=>{let n=tC.deletionPreview(e);if(n.missing.length>0||n.blocked.length>0)throw new tq(n);let i=new Set(e);for(let e of n.groups){if("removed"===e.outcome){var r=e.id;for(let e of td.prepare("SELECT id FROM conversations WHERE group_id = ?").all(r))tU(e.id);td.prepare("DELETE FROM group_members WHERE group_id = ?").run(r),td.prepare("DELETE FROM groups WHERE id = ?").run(r);continue}let t=td.prepare("SELECT id FROM conversations WHERE group_id = ?").all(e.id).map(e=>e.id);for(let n of i)for(let i of(td.prepare("DELETE FROM group_members WHERE group_id = ? AND bot_id = ?").run(e.id,n),t))td.prepare("DELETE FROM conversation_participants WHERE conversation_id = ? AND participant_kind = 'bot' AND participant_id = ?").run(i,n);e.newOwner&&td.prepare("UPDATE groups SET owner_bot_id = ? WHERE id = ?").run(e.newOwner.id,e.id)}for(let n of e){for(let e of td.prepare("SELECT id FROM conversations WHERE bot_id = ?").all(n))tU(e.id);e6(td,n),tD("bot_id",n),td.prepare("DELETE FROM launch_snapshots WHERE bot_id = ?").run(n),td.prepare("DELETE FROM group_members WHERE bot_id = ?").run(n),td.prepare("DELETE FROM conversation_participants WHERE participant_kind = 'bot' AND participant_id = ? AND conversation_id IN (SELECT id FROM conversations WHERE type = 'group')").run(n),td.prepare("DELETE FROM memories WHERE bot_id = ?").run(n),td.prepare("DELETE FROM one_shots WHERE bot_id = ?").run(n),td.prepare("DELETE FROM routines WHERE bot_id = ?").run(n),td.prepare("DELETE FROM pending_questions WHERE bot_id = ?").run(n),td.prepare("DELETE FROM approval_requests WHERE bot_id = ?").run(n),td.prepare("DELETE FROM wake_targets WHERE target_bot_id = ?").run(n),td.prepare("DELETE FROM bots WHERE id = ?").run(n),t?.onAgentDeleted?.(n)}return n})(),managementRows:()=>{let e=td.prepare("SELECT * FROM bots ORDER BY created_at DESC, id ASC").all(),t=new Set(ty()),n=new Map,i=e=>{for(let t of e)t.id&&t.at&&(n.get(t.id)??0)<t.at&&n.set(t.id,t.at)};return i(td.prepare("SELECT c.bot_id AS id, MAX(m.created_at) AS at FROM messages m JOIN conversations c ON c.id = m.conversation_id WHERE c.type = 'bot' GROUP BY c.bot_id").all()),i(td.prepare("SELECT sender_id AS id, MAX(created_at) AS at FROM messages WHERE sender_type = 'bot' AND sender_id IS NOT NULL GROUP BY sender_id").all()),e.map(e=>({bot:e,last_activity:n.get(e.id)??null,blocked:(0,J.isChiefOfStaffName)(e.name)?"chief":t.has(e.id)?"active":null}))}};class tq extends Error{preview;constructor(e){super(e.missing.length>0?"Agent not found":"Some agents cannot be deleted"),this.preview=e}}function ty(){return td.prepare(`
|
|
1368
1895
|
SELECT DISTINCT target_agent_id AS bot_id FROM work_requests
|
|
1369
1896
|
WHERE (executor <> 'dispatcher' AND state IN ('queued', 'running'))
|
|
1370
1897
|
OR (executor = 'dispatcher' AND state = 'running' AND json_extract(policy_snapshot, '$.surface') = 'ui')
|
|
1371
|
-
`).all().map(e=>e.bot_id)}function
|
|
1898
|
+
`).all().map(e=>e.bot_id)}function tb(){return new Set(td.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('legacy_agent_requests_archive', 'legacy_agent_request_events_archive', 'legacy_processing_queue_archive')").all().map(e=>e.name))}function tD(e,t){tb().has("legacy_processing_queue_archive")&&td.prepare(`DELETE FROM legacy_processing_queue_archive WHERE ${e} = ?`).run(t)}function tU(e){let t;e2(td,e),td.prepare("DELETE FROM draft_actions WHERE message_id IN (SELECT id FROM messages WHERE conversation_id = ?)").run(e),t=tb(),tD("conversation_id",e),t.has("legacy_agent_request_events_archive")&&t.has("legacy_agent_requests_archive")&&td.prepare("DELETE FROM legacy_agent_request_events_archive WHERE request_id IN (SELECT id FROM legacy_agent_requests_archive WHERE conversation_id = ?)").run(e),t.has("legacy_agent_requests_archive")&&td.prepare("DELETE FROM legacy_agent_requests_archive WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM messages WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM pending_questions WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM approvals WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM approval_requests WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM one_shots WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM routines WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM wake_targets WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM conversation_participants WHERE conversation_id = ?").run(e),td.prepare("DELETE FROM conversations WHERE id = ?").run(e)}let tF={getByBotId:e=>td.prepare("SELECT * FROM conversations WHERE bot_id = ?").get(e),getByGroupId:e=>td.prepare("SELECT * FROM conversations WHERE group_id = ?").get(e),getById:e=>td.prepare("SELECT * FROM conversations WHERE id = ?").get(e),getUiById:e=>td.prepare("SELECT * FROM conversations WHERE id = ? AND type != 'agent'").get(e)},tW={create:(e,t,n,i,r)=>{let a={id:(0,s.randomUUID)(),conversation_id:e,sender_type:t,sender_id:i,sender_kind:"bot"===t?"bot":tk.kind,content:n,handoff_targets:r&&r.length>0?JSON.stringify(r):null,created_at:Date.now()};if(td.prepare("INSERT INTO messages (id, conversation_id, sender_type, sender_id, sender_kind, content, handoff_targets, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(a.id,a.conversation_id,a.sender_type,a.sender_id||null,a.sender_kind,a.content,a.handoff_targets||null,a.created_at),"bot"===t){i&&tC.markUnread(i);let t=td.prepare("SELECT bot_id FROM conversations WHERE id = ? AND type = ?").get(e,"bot");t?.bot_id&&t.bot_id!==i&&tC.markUnread(t.bot_id)}return a},getById:e=>td.prepare("SELECT * FROM messages WHERE id = ?").get(e),replaceContent:(e,t)=>{td.prepare("UPDATE messages SET content = ? WHERE id = ?").run(t,e)},getByConversation:e=>td.prepare("SELECT * FROM messages WHERE conversation_id = ? ORDER BY created_at ASC").all(e),getBetween:(e,t)=>{let n=tW.getById(e),i=tW.getById(t);if(!n||!i||n.conversation_id!==i.conversation_id)return null;let r=td.prepare("SELECT * FROM messages WHERE conversation_id = ? ORDER BY created_at ASC, rowid ASC").all(n.conversation_id),s=r.findIndex(t=>t.id===e),a=r.findIndex(e=>e.id===t);if(s<0||a<0)return null;let[o,_]=s<a?[s,a]:[a,s];return r.slice(o+1,_)},latestFromBot:e=>{let t=tF.getByBotId(e);for(let n of td.prepare(`SELECT content, conversation_id, created_at FROM messages
|
|
1372
1899
|
WHERE sender_type = 'bot' AND sender_id = ?
|
|
1373
1900
|
ORDER BY created_at DESC, rowid DESC
|
|
1374
|
-
LIMIT 20`).all(e)){if(t&&n.conversation_id!==t.id)continue;let e=
|
|
1901
|
+
LIMIT 20`).all(e)){if(t&&n.conversation_id!==t.id)continue;let e=td.prepare(`SELECT content FROM messages
|
|
1375
1902
|
WHERE conversation_id = ? AND created_at < ?
|
|
1376
1903
|
ORDER BY created_at DESC, rowid DESC
|
|
1377
|
-
LIMIT 1`).get(n.conversation_id,n.created_at);if(!(e&&e.content.startsWith("[From ")))return n.content}return""},priorSentenceForHandoff:e=>{if(!e.handoff_targets)return null;let t=[];try{let n=JSON.parse(e.handoff_targets);if(!Array.isArray(n))return null;t=n.map(e=>String(e))}catch{return null}let n=
|
|
1904
|
+
LIMIT 1`).get(n.conversation_id,n.created_at);if(!(e&&e.content.startsWith("[From ")))return n.content}return""},priorSentenceForHandoff:e=>{if(!e.handoff_targets)return null;let t=[];try{let n=JSON.parse(e.handoff_targets);if(!Array.isArray(n))return null;t=n.map(e=>String(e))}catch{return null}let n=td.prepare(`
|
|
1378
1905
|
SELECT m.conversation_id AS conversation_id, c.type AS type, c.bot_id AS bot_id
|
|
1379
1906
|
FROM messages m
|
|
1380
1907
|
JOIN conversations c ON c.id = m.conversation_id
|
|
1381
1908
|
WHERE m.content = ? AND m.handoff_targets = ?
|
|
1382
1909
|
ORDER BY m.created_at ASC
|
|
1383
|
-
`).all(e.content,e.handoff_targets).find(e=>"group"===e.type||!e.bot_id||!t.includes(e.bot_id)),
|
|
1910
|
+
`).all(e.content,e.handoff_targets).find(e=>"group"===e.type||!e.bot_id||!t.includes(e.bot_id)),i=n?.conversation_id||e.conversation_id,r=tW.getByConversation(i),s=[...r].reverse().find(t=>"user"===t.sender_type&&t.content===e.content&&t.handoff_targets===e.handoff_targets),a=s?s.created_at:e.created_at;for(let e=r.length-1;e>=0;e--){let t=r[e];if(s&&t.id===s.id||t.created_at>a||"bot"!==t.sender_type)continue;let n=(t.content||"").trim();if(n)return n}return null}},tX={get:(e,t)=>td.prepare("SELECT * FROM approvals WHERE conversation_id = ? AND code = ?").get(e,t),recordPending:(e,t,n)=>(td.prepare("INSERT OR IGNORE INTO approvals (conversation_id, code, message_id, status, created_at) VALUES (?, ?, ?, ?, ?)").run(e,t,n||null,"pending",Date.now()),tX.get(e,t)),resolve:(e,t,n)=>Number(td.prepare("UPDATE approvals SET status = ?, resolved_at = ? WHERE conversation_id = ? AND code = ? AND status = 'pending'").run(n,Date.now(),e,t).changes)>0},tx=20;function tG(e){let t=tr(e);if(!t)return{ok:!1,reason:"not_found",requested:String(e??"")};let n=td.prepare("SELECT id, name FROM bots WHERE name_key = ? LIMIT 2").all(t);return 0===n.length?{ok:!1,reason:"not_found",requested:e}:n.length>1?{ok:!1,reason:"ambiguous",requested:e}:{ok:!0,agentId:n[0].id,displayName:n[0].name}}td.exec(`
|
|
1384
1911
|
CREATE TABLE IF NOT EXISTS wake_targets (
|
|
1385
1912
|
id TEXT PRIMARY KEY,
|
|
1386
1913
|
conversation_id TEXT NOT NULL,
|
|
@@ -1398,17 +1925,17 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1398
1925
|
ON wake_targets(conversation_id, created_at);
|
|
1399
1926
|
CREATE INDEX IF NOT EXISTS idx_wake_targets_target
|
|
1400
1927
|
ON wake_targets(target_bot_id, created_at);
|
|
1401
|
-
`),
|
|
1928
|
+
`),td.exec(`
|
|
1402
1929
|
CREATE TABLE IF NOT EXISTS workspace_settings (
|
|
1403
1930
|
key TEXT PRIMARY KEY,
|
|
1404
1931
|
value TEXT NOT NULL,
|
|
1405
1932
|
updated_at INTEGER NOT NULL
|
|
1406
1933
|
);
|
|
1407
|
-
`),e.s(["BotDeletionError",0,
|
|
1934
|
+
`),e.s(["BotDeletionError",0,tq,"UI_OWNER_PRINCIPAL",0,tk,"agentNameMigrations",0,{list:()=>td.prepare("SELECT * FROM agent_name_migrations ORDER BY created_at ASC, rowid ASC").all()},"approvals",0,tX,"bots",0,tC,"conversations",0,tF,"default",0,td,"draftActions",0,{get:e=>td.prepare("SELECT * FROM draft_actions WHERE message_id = ?").get(e),record:(e,t,n)=>Number(td.prepare("INSERT OR IGNORE INTO draft_actions (message_id, status, recipient, acted_at) VALUES (?, ?, ?, ?)").run(e,t,n||null,Date.now()).changes)>0},"engine",0,tI,"groups",0,{create:(e,t,n,i)=>{let r=n&&t.includes(n)?n:t[0],a={id:(0,s.randomUUID)(),name:e,owner_bot_id:r,created_at:i?.created_at??Date.now()},o=td.prepare("INSERT INTO groups (id, name, owner_bot_id, created_at) VALUES (?, ?, ?, ?)"),_=td.prepare("INSERT INTO group_members (group_id, bot_id) VALUES (?, ?)"),d=td.prepare("INSERT INTO conversations (id, type, group_id, created_at) VALUES (?, ?, ?, ?)");return td.transaction(()=>{for(let e of(o.run(a.id,a.name,a.owner_bot_id||null,a.created_at),t))_.run(a.id,e);let e=(0,s.randomUUID)();d.run(e,"group",a.id,a.created_at),tv(e,t,a.created_at)})(),a},getAll:()=>td.prepare("SELECT * FROM groups ORDER BY created_at DESC").all(),getById:e=>td.prepare("SELECT * FROM groups WHERE id = ?").get(e),rename:(e,t)=>{td.prepare("UPDATE groups SET name = ? WHERE id = ?").run(t,e)},getMembers:e=>td.prepare(`
|
|
1408
1935
|
SELECT b.* FROM bots b
|
|
1409
1936
|
JOIN group_members gm ON b.id = gm.bot_id
|
|
1410
1937
|
WHERE gm.group_id = ?
|
|
1411
|
-
`).all(e)},"launchSnapshots",0,{record:(e,t,n,r
|
|
1938
|
+
`).all(e)},"launchSnapshots",0,{record:(e,t,n,i,r="hermes-gateway")=>{td.prepare("INSERT OR IGNORE INTO launch_snapshots (id, bot_id, created_at, hash, snapshot, transport) VALUES (?, ?, ?, ?, ?, ?)").run(e,t,Date.now(),n,i,r)},listByBot:e=>td.prepare("SELECT * FROM launch_snapshots WHERE bot_id = ? ORDER BY created_at DESC, rowid DESC").all(e)},"mcpServers",0,{create:(e,t,n)=>{let i={id:(0,s.randomUUID)(),name:e,command:t,args:JSON.stringify(n),created_at:Date.now()};return td.prepare("INSERT INTO mcp_servers (id, name, command, args, created_at) VALUES (?, ?, ?, ?, ?)").run(i.id,i.name,i.command,i.args,i.created_at),i},list:()=>td.prepare("SELECT * FROM mcp_servers ORDER BY created_at ASC").all()},"memories",0,{rememberStatement:(e,t)=>{var n;let i;if(!e||!(i=t.trim())||/[??]\s*$/.test(i)||/^\[mcp\]/i.test(i)||/^\[tool (?:call|result)\]/i.test(i)||/^\[Handing off to\b/i.test(i)||/^\[From [^\]]+\]/i.test(i)||/^Peer handoff:/i.test(i)||/reply with exactly\b/i.test(i)||(n=i,/^(who|what|when|where|why|how|which|whose|whom)\b/i.test(n)?!/^(what|how|why|where|when|who)\s+i\b/i.test(n):!!(/^(do|does|did|can|could|would|will|should|shall|is|are|am|was|were|have|has)\s+(you|i|we|they|he|she|it|there|the|a|an|my|your|our)\b/i.test(n)||/^(tell me|please tell)\b/i.test(n))))return;let r=t.trim();td.prepare("INSERT INTO memories (id, bot_id, fact, created_at) VALUES (?, ?, ?, ?)").run((0,s.randomUUID)(),e,r,Date.now()),td.prepare(`
|
|
1412
1939
|
DELETE FROM memories
|
|
1413
1940
|
WHERE bot_id = ?
|
|
1414
1941
|
AND id NOT IN (
|
|
@@ -1419,6 +1946,6 @@ module.exports=[85148,(e,t,n)=>{t.exports=e.x("better-sqlite3-90e2652d1716b047",
|
|
|
1419
1946
|
LIMIT ?
|
|
1420
1947
|
)
|
|
1421
1948
|
)
|
|
1422
|
-
`).run(e,e,
|
|
1949
|
+
`).run(e,e,tx)},latestFacts:(e,t=tx)=>{let n=t>0?Math.min(t,tx):tx;return td.prepare("SELECT fact FROM memories WHERE bot_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?").all(e,n).map(e=>e.fact).reverse()}},"messages",0,tW,"oneShots",0,{create:(e,t,n)=>{let i={id:(0,s.randomUUID)(),conversation_id:e,bot_id:t,due_at:n,fired:0,created_at:Date.now()};return td.prepare("INSERT INTO one_shots (id, conversation_id, bot_id, due_at, fired, created_at) VALUES (?, ?, ?, ?, 0, ?)").run(i.id,i.conversation_id,i.bot_id,i.due_at,i.created_at),i},pending:e=>td.prepare("SELECT * FROM one_shots WHERE conversation_id = ? AND fired = 0 ORDER BY due_at ASC LIMIT 1").get(e),unfired:()=>td.prepare("SELECT * FROM one_shots WHERE fired = 0 ORDER BY due_at ASC").all(),claim:e=>1===td.prepare("UPDATE one_shots SET fired = 1 WHERE id = ? AND fired = 0").run(e).changes},"projector",0,tA,"registrationContext",0,{getConnection:e=>th.getById(e),localConnectionFor:e=>tT(e),sessionBelongsTo:function(e,t){return!!e&&(!!td.prepare("SELECT 1 FROM session_bindings WHERE id = ? AND agent_id = ?").get(t,e)||!!td.prepare("SELECT 1 FROM provider_sessions WHERE id = ? AND agent_id = ?").get(t,e))}},"resolveWakeTarget",0,tG,"routines",0,{create:(e,t,n,i,r)=>{let a={id:(0,s.randomUUID)(),conversation_id:e,bot_id:t,word:n,next_due_at:i,every_ms:r,created_at:Date.now()};return td.prepare("INSERT INTO routines (id, conversation_id, bot_id, word, next_due_at, every_ms, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(a.id,a.conversation_id,a.bot_id,a.word,a.next_due_at,a.every_ms,a.created_at),a},forConversation:e=>td.prepare("SELECT * FROM routines WHERE conversation_id = ? ORDER BY created_at ASC LIMIT 1").get(e),all:()=>td.prepare("SELECT * FROM routines ORDER BY next_due_at ASC").all(),postIfDue:(e,t)=>td.transaction(()=>{let n=td.prepare("SELECT * FROM routines WHERE id = ?").get(e);return!!n&&!(n.next_due_at>t)&&1===td.prepare("UPDATE routines SET next_due_at = next_due_at + every_ms WHERE id = ? AND next_due_at = ?").run(e,n.next_due_at).changes&&(tW.create(n.conversation_id,"bot","[routine]\n"+n.word,n.bot_id),!0)})()},"runtimeConnections",0,th,"serializeAgent",0,function(e){let t=(0,a.serializeBot)(e);for(let e of tw)delete t[e];let n=e.runtime_connection_id?th.getById(e.runtime_connection_id):void 0;return{...t,...j(e,n),launch_profile:F(e)}},"serviceAudit",0,tS,"wakeTargets",0,{accept:e=>{let t=tG(e.requestedTarget);if(!t.ok)return t;let n={id:(0,s.randomUUID)(),conversation_id:e.conversationId,source_bot_id:e.sourceBotId??null,source_message_id:e.sourceMessageId??null,requested_target:e.requestedTarget,target_bot_id:t.agentId,target_name_snapshot:t.displayName,created_at:Date.now()};return td.prepare("INSERT INTO wake_targets (id, conversation_id, source_bot_id, source_message_id, requested_target, target_bot_id, target_name_snapshot, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(n.id,n.conversation_id,n.source_bot_id,n.source_message_id,n.requested_target,n.target_bot_id,n.target_name_snapshot,n.created_at),{ok:!0,wake:n}},listByConversation:e=>td.prepare("SELECT * FROM wake_targets WHERE conversation_id = ? ORDER BY created_at ASC, rowid ASC").all(e)},"workspaceSettings",0,{get:e=>{let t=td.prepare("SELECT value FROM workspace_settings WHERE key = ?").get(e);return t?t.value:null},set:(e,t)=>{td.prepare("INSERT INTO workspace_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at").run(e,t,Date.now())},clearForTests:()=>{td.prepare("DELETE FROM workspace_settings").run()}}],62294)}];
|
|
1423
1950
|
|
|
1424
1951
|
//# sourceMappingURL=%5Broot-of-the-server%5D__0izjfmr._.js.map
|