turnloom 0.7.0__py3-none-any.whl
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.
- turnloom/__init__.py +3 -0
- turnloom/__main__.py +3 -0
- turnloom/acp.py +493 -0
- turnloom/agent.py +938 -0
- turnloom/atif.py +104 -0
- turnloom/cli.py +562 -0
- turnloom/compare.py +87 -0
- turnloom/context.py +99 -0
- turnloom/data/LICENSE.models-dev +21 -0
- turnloom/data/providers.json +189 -0
- turnloom/desktop.py +103 -0
- turnloom/evaluate.py +190 -0
- turnloom/extensions.py +250 -0
- turnloom/gateway.py +144 -0
- turnloom/guard.py +231 -0
- turnloom/meter.py +129 -0
- turnloom/openrouter.py +65 -0
- turnloom/personas/LICENSE +21 -0
- turnloom/personas/academic/academic-anthropologist.md +125 -0
- turnloom/personas/academic/academic-geographer.md +127 -0
- turnloom/personas/academic/academic-historian.md +123 -0
- turnloom/personas/academic/academic-narratologist.md +118 -0
- turnloom/personas/academic/academic-psychologist.md +118 -0
- turnloom/personas/academic/academic-statistician.md +144 -0
- turnloom/personas/catalog.json +2836 -0
- turnloom/personas/design/design-brand-guardian.md +322 -0
- turnloom/personas/design/design-image-prompt-engineer.md +236 -0
- turnloom/personas/design/design-inclusive-visuals-specialist.md +73 -0
- turnloom/personas/design/design-persona-walkthrough.md +272 -0
- turnloom/personas/design/design-ui-designer.md +386 -0
- turnloom/personas/design/design-ui-finish-gate-reviewer.md +217 -0
- turnloom/personas/design/design-ux-architect.md +482 -0
- turnloom/personas/design/design-ux-researcher.md +329 -0
- turnloom/personas/design/design-visual-storyteller.md +149 -0
- turnloom/personas/design/design-whimsy-injector.md +460 -0
- turnloom/personas/engineering/engineering-ai-data-remediation-engineer.md +211 -0
- turnloom/personas/engineering/engineering-ai-engineer.md +146 -0
- turnloom/personas/engineering/engineering-api-platform-engineer.md +181 -0
- turnloom/personas/engineering/engineering-ats-validator-architect.md +383 -0
- turnloom/personas/engineering/engineering-autonomous-optimization-architect.md +121 -0
- turnloom/personas/engineering/engineering-backend-architect.md +255 -0
- turnloom/personas/engineering/engineering-china-network-engineer.md +252 -0
- turnloom/personas/engineering/engineering-cms-developer.md +536 -0
- turnloom/personas/engineering/engineering-code-reviewer.md +76 -0
- turnloom/personas/engineering/engineering-codebase-onboarding-engineer.md +173 -0
- turnloom/personas/engineering/engineering-data-engineer.md +349 -0
- turnloom/personas/engineering/engineering-data-visualization-engineer.md +151 -0
- turnloom/personas/engineering/engineering-database-optimizer.md +188 -0
- turnloom/personas/engineering/engineering-database-reliability-engineer.md +201 -0
- turnloom/personas/engineering/engineering-desktop-app-engineer.md +209 -0
- turnloom/personas/engineering/engineering-developer-tooling-engineer.md +153 -0
- turnloom/personas/engineering/engineering-devops-automator.md +385 -0
- turnloom/personas/engineering/engineering-drupal-performance.md +347 -0
- turnloom/personas/engineering/engineering-drupal-shopping-cart.md +360 -0
- turnloom/personas/engineering/engineering-electrical-engineer.md +575 -0
- turnloom/personas/engineering/engineering-email-intelligence-engineer.md +390 -0
- turnloom/personas/engineering/engineering-embedded-firmware-engineer.md +196 -0
- turnloom/personas/engineering/engineering-feishu-integration-developer.md +606 -0
- turnloom/personas/engineering/engineering-filament-optimization-specialist.md +283 -0
- turnloom/personas/engineering/engineering-finops-engineer.md +164 -0
- turnloom/personas/engineering/engineering-frontend-developer.md +257 -0
- turnloom/personas/engineering/engineering-gaussdb-expert.md +334 -0
- turnloom/personas/engineering/engineering-git-workflow-master.md +98 -0
- turnloom/personas/engineering/engineering-i18n-engineer.md +214 -0
- turnloom/personas/engineering/engineering-identity-access-engineer.md +217 -0
- turnloom/personas/engineering/engineering-incident-response-commander.md +444 -0
- turnloom/personas/engineering/engineering-iot-fleet-engineer.md +148 -0
- turnloom/personas/engineering/engineering-it-service-manager.md +561 -0
- turnloom/personas/engineering/engineering-knowledge-graph-engineer.md +372 -0
- turnloom/personas/engineering/engineering-llm-post-training-engineer.md +166 -0
- turnloom/personas/engineering/engineering-minimal-change-engineer.md +207 -0
- turnloom/personas/engineering/engineering-mobile-app-builder.md +493 -0
- turnloom/personas/engineering/engineering-mobile-release-engineer.md +164 -0
- turnloom/personas/engineering/engineering-multi-agent-systems-architect.md +600 -0
- turnloom/personas/engineering/engineering-network-engineer.md +245 -0
- turnloom/personas/engineering/engineering-orgscript-engineer.md +113 -0
- turnloom/personas/engineering/engineering-payments-billing-engineer.md +228 -0
- turnloom/personas/engineering/engineering-pdf-engine-architect.md +696 -0
- turnloom/personas/engineering/engineering-platform-engineer.md +270 -0
- turnloom/personas/engineering/engineering-privacy-engineer.md +152 -0
- turnloom/personas/engineering/engineering-prompt-engineer.md +209 -0
- turnloom/personas/engineering/engineering-rag-pipeline-engineer.md +450 -0
- turnloom/personas/engineering/engineering-rapid-prototyper.md +466 -0
- turnloom/personas/engineering/engineering-realtime-collaboration-engineer.md +200 -0
- turnloom/personas/engineering/engineering-rust-refactoring-specialist.md +313 -0
- turnloom/personas/engineering/engineering-search-relevance-engineer.md +237 -0
- turnloom/personas/engineering/engineering-section-508-specialist.md +339 -0
- turnloom/personas/engineering/engineering-senior-developer.md +176 -0
- turnloom/personas/engineering/engineering-servicenow-developer-mentor.md +180 -0
- turnloom/personas/engineering/engineering-software-architect.md +112 -0
- turnloom/personas/engineering/engineering-solidity-smart-contract-engineer.md +522 -0
- turnloom/personas/engineering/engineering-sre.md +90 -0
- turnloom/personas/engineering/engineering-technical-writer.md +393 -0
- turnloom/personas/engineering/engineering-universal-document-compiler.md +370 -0
- turnloom/personas/engineering/engineering-uswds-developer.md +340 -0
- turnloom/personas/engineering/engineering-video-streaming-engineer.md +151 -0
- turnloom/personas/engineering/engineering-voice-ai-integration-engineer.md +584 -0
- turnloom/personas/engineering/engineering-webassembly-engineer.md +153 -0
- turnloom/personas/engineering/engineering-wechat-mini-program-developer.md +356 -0
- turnloom/personas/engineering/engineering-wordpress-performance.md +346 -0
- turnloom/personas/engineering/engineering-wordpress-shopping-cart.md +346 -0
- turnloom/personas/finance/finance-bookkeeper-controller.md +260 -0
- turnloom/personas/finance/finance-financial-analyst.md +234 -0
- turnloom/personas/finance/finance-fpa-analyst.md +263 -0
- turnloom/personas/finance/finance-investment-researcher.md +272 -0
- turnloom/personas/finance/finance-tax-strategist.md +239 -0
- turnloom/personas/game-development/blender-addon-engineer.md +243 -0
- turnloom/personas/game-development/economy-designer.md +156 -0
- turnloom/personas/game-development/game-audio-engineer.md +264 -0
- turnloom/personas/game-development/game-designer.md +167 -0
- turnloom/personas/game-development/godot-gameplay-scripter.md +338 -0
- turnloom/personas/game-development/godot-multiplayer-engineer.md +301 -0
- turnloom/personas/game-development/godot-shader-developer.md +267 -0
- turnloom/personas/game-development/level-designer.md +208 -0
- turnloom/personas/game-development/narrative-designer.md +243 -0
- turnloom/personas/game-development/roblox-avatar-creator.md +297 -0
- turnloom/personas/game-development/roblox-experience-designer.md +306 -0
- turnloom/personas/game-development/roblox-systems-scripter.md +332 -0
- turnloom/personas/game-development/technical-artist.md +233 -0
- turnloom/personas/game-development/unity-architect.md +271 -0
- turnloom/personas/game-development/unity-editor-tool-developer.md +310 -0
- turnloom/personas/game-development/unity-multiplayer-engineer.md +323 -0
- turnloom/personas/game-development/unity-shader-graph-artist.md +269 -0
- turnloom/personas/game-development/unreal-multiplayer-architect.md +364 -0
- turnloom/personas/game-development/unreal-systems-engineer.md +322 -0
- turnloom/personas/game-development/unreal-technical-artist.md +256 -0
- turnloom/personas/game-development/unreal-world-builder.md +273 -0
- turnloom/personas/gis/gis-3d-scene-developer.md +111 -0
- turnloom/personas/gis/gis-analyst.md +91 -0
- turnloom/personas/gis/gis-bim-specialist.md +108 -0
- turnloom/personas/gis/gis-cartography-designer.md +150 -0
- turnloom/personas/gis/gis-drone-reality-mapping.md +120 -0
- turnloom/personas/gis/gis-geoai-ml-engineer.md +105 -0
- turnloom/personas/gis/gis-geoprocessing-specialist.md +97 -0
- turnloom/personas/gis/gis-qa-engineer.md +133 -0
- turnloom/personas/gis/gis-solution-engineer.md +101 -0
- turnloom/personas/gis/gis-spatial-data-engineer.md +97 -0
- turnloom/personas/gis/gis-spatial-data-scientist.md +111 -0
- turnloom/personas/gis/gis-technical-consultant.md +86 -0
- turnloom/personas/gis/gis-web-gis-developer.md +108 -0
- turnloom/personas/healthcare/healthcare-clinical-evidence-agent.md +231 -0
- turnloom/personas/healthcare/healthcare-innovation-strategist.md +433 -0
- turnloom/personas/healthcare/healthcare-sovereign-health-systems-agent.md +312 -0
- turnloom/personas/marketing/marketing-aeo-foundations.md +264 -0
- turnloom/personas/marketing/marketing-agentic-search-optimizer.md +279 -0
- turnloom/personas/marketing/marketing-ai-citation-strategist.md +172 -0
- turnloom/personas/marketing/marketing-app-store-optimizer.md +321 -0
- turnloom/personas/marketing/marketing-baidu-seo-specialist.md +226 -0
- turnloom/personas/marketing/marketing-bilibili-content-strategist.md +199 -0
- turnloom/personas/marketing/marketing-book-co-author.md +110 -0
- turnloom/personas/marketing/marketing-carousel-growth-engine.md +204 -0
- turnloom/personas/marketing/marketing-china-ecommerce-operator.md +283 -0
- turnloom/personas/marketing/marketing-china-market-localization-strategist.md +283 -0
- turnloom/personas/marketing/marketing-content-creator.md +54 -0
- turnloom/personas/marketing/marketing-cross-border-ecommerce.md +259 -0
- turnloom/personas/marketing/marketing-developer-community-builder.md +285 -0
- turnloom/personas/marketing/marketing-douyin-strategist.md +149 -0
- turnloom/personas/marketing/marketing-email-strategist.md +249 -0
- turnloom/personas/marketing/marketing-global-podcast-strategist.md +206 -0
- turnloom/personas/marketing/marketing-growth-hacker.md +54 -0
- turnloom/personas/marketing/marketing-instagram-curator.md +113 -0
- turnloom/personas/marketing/marketing-kuaishou-strategist.md +223 -0
- turnloom/personas/marketing/marketing-linkedin-content-creator.md +214 -0
- turnloom/personas/marketing/marketing-livestream-commerce-coach.md +305 -0
- turnloom/personas/marketing/marketing-multi-platform-publisher.md +217 -0
- turnloom/personas/marketing/marketing-podcast-strategist.md +277 -0
- turnloom/personas/marketing/marketing-pr-communications-manager.md +473 -0
- turnloom/personas/marketing/marketing-private-domain-operator.md +308 -0
- turnloom/personas/marketing/marketing-reddit-community-builder.md +123 -0
- turnloom/personas/marketing/marketing-seo-specialist.md +370 -0
- turnloom/personas/marketing/marketing-short-video-editing-coach.md +412 -0
- turnloom/personas/marketing/marketing-social-media-strategist.md +125 -0
- turnloom/personas/marketing/marketing-tiktok-strategist.md +125 -0
- turnloom/personas/marketing/marketing-twitter-engager.md +126 -0
- turnloom/personas/marketing/marketing-video-optimization-specialist.md +119 -0
- turnloom/personas/marketing/marketing-wechat-official-account.md +145 -0
- turnloom/personas/marketing/marketing-weibo-strategist.md +240 -0
- turnloom/personas/marketing/marketing-x-twitter-intelligence-analyst.md +161 -0
- turnloom/personas/marketing/marketing-xiaohongshu-specialist.md +138 -0
- turnloom/personas/marketing/marketing-zhihu-strategist.md +162 -0
- turnloom/personas/paid-media/paid-media-auditor.md +71 -0
- turnloom/personas/paid-media/paid-media-creative-strategist.md +71 -0
- turnloom/personas/paid-media/paid-media-paid-social-strategist.md +71 -0
- turnloom/personas/paid-media/paid-media-ppc-strategist.md +71 -0
- turnloom/personas/paid-media/paid-media-programmatic-buyer.md +71 -0
- turnloom/personas/paid-media/paid-media-search-query-analyst.md +71 -0
- turnloom/personas/paid-media/paid-media-tracking-specialist.md +71 -0
- turnloom/personas/product/product-behavioral-nudge-engine.md +83 -0
- turnloom/personas/product/product-dx-engineer.md +332 -0
- turnloom/personas/product/product-feedback-synthesizer.md +119 -0
- turnloom/personas/product/product-manager.md +469 -0
- turnloom/personas/product/product-sprint-prioritizer.md +154 -0
- turnloom/personas/product/product-trend-researcher.md +159 -0
- turnloom/personas/project-management/project-management-experiment-tracker.md +198 -0
- turnloom/personas/project-management/project-management-jira-workflow-steward.md +233 -0
- turnloom/personas/project-management/project-management-meeting-notes-specialist.md +95 -0
- turnloom/personas/project-management/project-management-project-shepherd.md +194 -0
- turnloom/personas/project-management/project-management-studio-operations.md +200 -0
- turnloom/personas/project-management/project-management-studio-producer.md +203 -0
- turnloom/personas/project-management/project-manager-senior.md +135 -0
- turnloom/personas/research/research-synthesist.md +136 -0
- turnloom/personas/sales/sales-account-strategist.md +227 -0
- turnloom/personas/sales/sales-coach.md +271 -0
- turnloom/personas/sales/sales-deal-strategist.md +180 -0
- turnloom/personas/sales/sales-discovery-coach.md +225 -0
- turnloom/personas/sales/sales-engineer.md +182 -0
- turnloom/personas/sales/sales-offer-lead-gen-strategist.md +257 -0
- turnloom/personas/sales/sales-outbound-strategist.md +201 -0
- turnloom/personas/sales/sales-pipeline-analyst.md +267 -0
- turnloom/personas/sales/sales-proposal-strategist.md +217 -0
- turnloom/personas/security/security-ai-generated-code-auditor.md +207 -0
- turnloom/personas/security/security-appsec-engineer.md +536 -0
- turnloom/personas/security/security-architect.md +307 -0
- turnloom/personas/security/security-blockchain-security-auditor.md +482 -0
- turnloom/personas/security/security-cloud-security-architect.md +576 -0
- turnloom/personas/security/security-compliance-auditor.md +158 -0
- turnloom/personas/security/security-incident-responder.md +450 -0
- turnloom/personas/security/security-penetration-tester.md +399 -0
- turnloom/personas/security/security-secrets-credential-engineer.md +189 -0
- turnloom/personas/security/security-senior-secops.md +771 -0
- turnloom/personas/security/security-threat-detection-engineer.md +553 -0
- turnloom/personas/security/security-threat-intelligence-analyst.md +661 -0
- turnloom/personas/spatial-computing/macos-spatial-metal-engineer.md +337 -0
- turnloom/personas/spatial-computing/terminal-integration-specialist.md +70 -0
- turnloom/personas/spatial-computing/visionos-spatial-engineer.md +54 -0
- turnloom/personas/spatial-computing/xr-cockpit-interaction-specialist.md +32 -0
- turnloom/personas/spatial-computing/xr-immersive-developer.md +32 -0
- turnloom/personas/spatial-computing/xr-interface-architect.md +32 -0
- turnloom/personas/specialized/accounts-payable-agent.md +205 -0
- turnloom/personas/specialized/agentic-identity-trust.md +394 -0
- turnloom/personas/specialized/agents-orchestrator.md +367 -0
- turnloom/personas/specialized/automation-governance-architect.md +216 -0
- turnloom/personas/specialized/business-strategist.md +488 -0
- turnloom/personas/specialized/change-management-consultant.md +497 -0
- turnloom/personas/specialized/chief-financial-officer.md +388 -0
- turnloom/personas/specialized/corporate-training-designer.md +192 -0
- turnloom/personas/specialized/customer-service.md +398 -0
- turnloom/personas/specialized/customer-success-manager.md +460 -0
- turnloom/personas/specialized/data-consolidation-agent.md +60 -0
- turnloom/personas/specialized/data-privacy-officer.md +412 -0
- turnloom/personas/specialized/esg-sustainability-officer.md +396 -0
- turnloom/personas/specialized/government-digital-presales-consultant.md +363 -0
- turnloom/personas/specialized/grant-writer.md +511 -0
- turnloom/personas/specialized/healthcare-aging-parent-care-companion.md +414 -0
- turnloom/personas/specialized/healthcare-customer-service.md +389 -0
- turnloom/personas/specialized/healthcare-marketing-compliance.md +395 -0
- turnloom/personas/specialized/hospitality-guest-services.md +603 -0
- turnloom/personas/specialized/hr-onboarding.md +451 -0
- turnloom/personas/specialized/identity-graph-operator.md +303 -0
- turnloom/personas/specialized/language-translator.md +264 -0
- turnloom/personas/specialized/legal-billing-time-tracking.md +569 -0
- turnloom/personas/specialized/legal-client-intake.md +492 -0
- turnloom/personas/specialized/legal-document-review.md +454 -0
- turnloom/personas/specialized/loan-officer-assistant.md +555 -0
- turnloom/personas/specialized/lsp-index-engineer.md +320 -0
- turnloom/personas/specialized/ma-integration-manager.md +427 -0
- turnloom/personas/specialized/medical-billing-coding-specialist.md +491 -0
- turnloom/personas/specialized/operations-manager.md +399 -0
- turnloom/personas/specialized/organizational-psychologist.md +391 -0
- turnloom/personas/specialized/personal-growth-mentor.md +159 -0
- turnloom/personas/specialized/real-estate-buyer-seller.md +596 -0
- turnloom/personas/specialized/recruitment-specialist.md +515 -0
- turnloom/personas/specialized/report-distribution-agent.md +65 -0
- turnloom/personas/specialized/resume-tailor.md +230 -0
- turnloom/personas/specialized/retail-customer-returns.md +566 -0
- turnloom/personas/specialized/sales-data-extraction-agent.md +67 -0
- turnloom/personas/specialized/sales-outreach.md +425 -0
- turnloom/personas/specialized/specialized-chief-of-staff.md +279 -0
- turnloom/personas/specialized/specialized-civil-engineer.md +356 -0
- turnloom/personas/specialized/specialized-codebase-archaeologist.md +341 -0
- turnloom/personas/specialized/specialized-cultural-intelligence-strategist.md +88 -0
- turnloom/personas/specialized/specialized-developer-advocate.md +317 -0
- turnloom/personas/specialized/specialized-document-generator.md +55 -0
- turnloom/personas/specialized/specialized-fedramp-rmf-compliance.md +378 -0
- turnloom/personas/specialized/specialized-focus-music-architect.md +175 -0
- turnloom/personas/specialized/specialized-french-consulting-market.md +194 -0
- turnloom/personas/specialized/specialized-korean-business-navigator.md +216 -0
- turnloom/personas/specialized/specialized-master-plan-architect.md +157 -0
- turnloom/personas/specialized/specialized-mcp-builder.md +260 -0
- turnloom/personas/specialized/specialized-model-qa.md +528 -0
- turnloom/personas/specialized/specialized-pricing-analyst.md +243 -0
- turnloom/personas/specialized/specialized-salesforce-architect.md +182 -0
- turnloom/personas/specialized/specialized-strategy-duel-agent.md +130 -0
- turnloom/personas/specialized/specialized-workflow-architect.md +597 -0
- turnloom/personas/specialized/study-abroad-advisor.md +282 -0
- turnloom/personas/specialized/supply-chain-strategist.md +591 -0
- turnloom/personas/specialized/zk-steward.md +211 -0
- turnloom/personas/support/support-analytics-reporter.md +387 -0
- turnloom/personas/support/support-executive-summary-generator.md +212 -0
- turnloom/personas/support/support-finance-tracker.md +480 -0
- turnloom/personas/support/support-infrastructure-maintainer.md +628 -0
- turnloom/personas/support/support-legal-compliance-checker.md +591 -0
- turnloom/personas/support/support-support-responder.md +607 -0
- turnloom/personas/testing/testing-accessibility-auditor.md +327 -0
- turnloom/personas/testing/testing-api-tester.md +334 -0
- turnloom/personas/testing/testing-evidence-collector.md +210 -0
- turnloom/personas/testing/testing-performance-benchmarker.md +285 -0
- turnloom/personas/testing/testing-reality-checker.md +249 -0
- turnloom/personas/testing/testing-test-automation-engineer.md +196 -0
- turnloom/personas/testing/testing-test-results-analyzer.md +330 -0
- turnloom/personas/testing/testing-tool-evaluator.md +416 -0
- turnloom/personas/testing/testing-workflow-optimizer.md +488 -0
- turnloom/providers.py +403 -0
- turnloom/proxy.py +252 -0
- turnloom/roster.py +92 -0
- turnloom/server.py +149 -0
- turnloom/studio.py +1342 -0
- turnloom/studio_assets/THIRD-PARTY.txt +1891 -0
- turnloom/studio_assets/icon.ico +0 -0
- turnloom/studio_assets/icon.png +0 -0
- turnloom/studio_assets/icon.svg +1 -0
- turnloom/studio_assets/index.html +2 -0
- turnloom/studio_assets/studio.css +1 -0
- turnloom/studio_assets/studio.js +110 -0
- turnloom/team.py +103 -0
- turnloom/tools.py +479 -0
- turnloom/unwind_stdio.py +44 -0
- turnloom-0.7.0.dist-info/METADATA +209 -0
- turnloom-0.7.0.dist-info/RECORD +326 -0
- turnloom-0.7.0.dist-info/WHEEL +5 -0
- turnloom-0.7.0.dist-info/entry_points.txt +9 -0
- turnloom-0.7.0.dist-info/licenses/LICENSE +21 -0
- turnloom-0.7.0.dist-info/licenses/turnloom/data/LICENSE.models-dev +21 -0
- turnloom-0.7.0.dist-info/licenses/turnloom/personas/LICENSE +21 -0
- turnloom-0.7.0.dist-info/licenses/turnloom/studio_assets/THIRD-PARTY.txt +1891 -0
- turnloom-0.7.0.dist-info/top_level.txt +1 -0
turnloom/__init__.py
ADDED
turnloom/__main__.py
ADDED
turnloom/acp.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"""Serve Turnloom to editors over the Agent Client Protocol: one conversation per session, reported as it runs."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
from collections import defaultdict
|
|
9
|
+
from concurrent.futures import Future
|
|
10
|
+
from contextlib import ExitStack
|
|
11
|
+
from itertools import count
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
from urllib.request import url2pathname
|
|
15
|
+
from uuid import uuid4
|
|
16
|
+
|
|
17
|
+
from turnloom import __version__, guard, providers, roster
|
|
18
|
+
from turnloom.agent import Config, Result, load_history, run_agent
|
|
19
|
+
from turnloom.cli import SESSION, events, instructions
|
|
20
|
+
from turnloom.context import Observations
|
|
21
|
+
from turnloom.extensions import McpTools
|
|
22
|
+
from turnloom.tools import Workspace
|
|
23
|
+
|
|
24
|
+
MODES = {"ask": ("Ask", "Ask before edits and commands"),
|
|
25
|
+
"auto-edit": ("Auto-edit", "Apply edits without asking and ask before commands"),
|
|
26
|
+
"read-only": ("Read-only", "Explore and answer without edits or commands")}
|
|
27
|
+
TOOLS = {"list_files": ("search", "List files {path} {glob}"), "read_file": ("read", "Read {path}"),
|
|
28
|
+
"search_files": ("search", "Search for {query}"), "edit_file": ("edit", "Edit {path}"),
|
|
29
|
+
"write_file": ("edit", "Write {path}"), "shell": ("execute", "{command}"), "recall": ("read", "Recall {reference}"),
|
|
30
|
+
"mcp_search": ("search", "Search {server} tools"), "mcp_call": ("other", "{server}: {name}")}
|
|
31
|
+
GATED = ("edit_file", "write_file", "shell", "mcp_call") # Announced as pending: these wait for approval.
|
|
32
|
+
ALWAYS = {"edit": "Always allow edits in this session", "shell": "Always allow this exact command",
|
|
33
|
+
"mcp": "Always allow this exact tool call"}
|
|
34
|
+
STEPS = 100 # Model calls per turn, as in `turnloom chat`.
|
|
35
|
+
GRACE = 2.0 # Seconds a withdrawn turn gets to stop before its request is given up as cancelled.
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def sdk():
|
|
39
|
+
"""Import the protocol SDK on first use, so Turnloom itself runs without the acp extra."""
|
|
40
|
+
try:
|
|
41
|
+
import acp
|
|
42
|
+
except ImportError as error:
|
|
43
|
+
raise ValueError("Install Turnloom with the acp extra: pip install 'turnloom[acp]'") from error
|
|
44
|
+
return acp
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def said(text, role="agent"):
|
|
48
|
+
return {"sessionUpdate": role + "_message_chunk", "content": {"type": "text", "text": text}}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def block(text):
|
|
52
|
+
"""Tool output inside a code fence longer than any it contains, so Markdown rendering leaves it alone."""
|
|
53
|
+
fence = "`" * max(3, 1 + max(map(len, re.findall("`+", text)), default=0))
|
|
54
|
+
return {"type": "content", "content": {"type": "text", "text": f"{fence}\n{text}\n{fence}"}}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def diff(path, before, after):
|
|
58
|
+
return {"type": "diff", "path": str(path), "oldText": before, "newText": after}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def place(uri, root):
|
|
62
|
+
"""A file URI inside the workspace becomes the relative path the file tools take. Anything else stays as sent."""
|
|
63
|
+
parts = urlsplit(uri)
|
|
64
|
+
if parts.scheme == "file":
|
|
65
|
+
try:
|
|
66
|
+
return Path(url2pathname(parts.path)).resolve().relative_to(root).as_posix()
|
|
67
|
+
except (ValueError, OSError):
|
|
68
|
+
pass
|
|
69
|
+
return uri
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def task_text(blocks, root):
|
|
73
|
+
"""Flatten a prompt into the task: text as written, links by location, attached files in delimited blocks."""
|
|
74
|
+
inline, attached = [], []
|
|
75
|
+
for item in blocks:
|
|
76
|
+
resource = getattr(item, "resource", None)
|
|
77
|
+
if item.type == "text":
|
|
78
|
+
inline.append(item.text)
|
|
79
|
+
elif item.type == "resource_link":
|
|
80
|
+
inline.append(f"[{item.name}]({place(item.uri, root)})")
|
|
81
|
+
elif item.type == "resource" and isinstance(getattr(resource, "text", None), str):
|
|
82
|
+
source = place(resource.uri, root)
|
|
83
|
+
inline.append(source)
|
|
84
|
+
attached.append(f'<attachment source="{source}">\n{resource.text}\n</attachment>')
|
|
85
|
+
else:
|
|
86
|
+
raise sdk().RequestError.invalid_params(
|
|
87
|
+
{"details": "Turnloom reads text and text resources. Images, audio and binary files are not supported."})
|
|
88
|
+
spoken = " ".join(piece.strip() for piece in inline if piece.strip())
|
|
89
|
+
return "\n\n".join(part for part in (spoken, *attached) if part)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def tool_servers(offered):
|
|
93
|
+
"""Sort the editor's MCP servers into those Turnloom's client can launch and the reasons it skips the rest."""
|
|
94
|
+
usable, skipped = {}, []
|
|
95
|
+
for server in offered or []:
|
|
96
|
+
if not getattr(server, "command", None):
|
|
97
|
+
skipped.append(f"{server.name}: only stdio servers are supported")
|
|
98
|
+
else:
|
|
99
|
+
name = re.sub(r"[^A-Za-z0-9_-]", "_", server.name)[:60] or "server"
|
|
100
|
+
while name in usable:
|
|
101
|
+
name += "_"
|
|
102
|
+
usable[name] = {"command": server.command, "args": list(server.args),
|
|
103
|
+
"env": {item.name: item.value for item in server.env or []}}
|
|
104
|
+
return usable, skipped
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def located(files, name):
|
|
108
|
+
"""The absolute path the editor needs for a workspace file, or None when the name does not stay inside the workspace."""
|
|
109
|
+
try:
|
|
110
|
+
return str(files.resolve(name, exists=False))
|
|
111
|
+
except ValueError:
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def opened(call_id, name, arguments, files):
|
|
116
|
+
"""The tool_call fields that announce a tool: a title, a kind, and the file it touches. Also returns its arguments."""
|
|
117
|
+
try:
|
|
118
|
+
params = json.loads(arguments)
|
|
119
|
+
except ValueError:
|
|
120
|
+
params = None
|
|
121
|
+
params = params if isinstance(params, dict) else {}
|
|
122
|
+
kind, title = TOOLS.get(name, ("other", name))
|
|
123
|
+
words = defaultdict(str, {key: str(value) for key, value in params.items() if isinstance(value, (str, int))})
|
|
124
|
+
fields = {"toolCallId": call_id, "name": name, "kind": kind, "status": "pending" if name in GATED else "in_progress",
|
|
125
|
+
"title": " ".join(title.format_map(words).split())[:120] or name}
|
|
126
|
+
path = located(files, params.get("path")) if name in ("read_file", "edit_file", "write_file") else None
|
|
127
|
+
if path:
|
|
128
|
+
line = params.get("line")
|
|
129
|
+
fields["locations"] = [{"path": path, "line": line} if type(line) is int and line > 0 else {"path": path}]
|
|
130
|
+
if name == "shell" and words["command"]:
|
|
131
|
+
fields["content"] = [block(words["command"])]
|
|
132
|
+
return fields, params
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def output(name, outcome):
|
|
136
|
+
"""The part of a tool result worth reading in the editor."""
|
|
137
|
+
if name == "shell" and "stdout" in outcome:
|
|
138
|
+
printed = [part.rstrip() for part in (outcome["stdout"], outcome.get("stderr") or "") if part.strip()]
|
|
139
|
+
return "\n".join([*printed, str(outcome.get("error") or f"exit code {outcome.get('exit_code')}")])
|
|
140
|
+
if "error" in outcome:
|
|
141
|
+
return str(outcome["error"])
|
|
142
|
+
for key in ("text", "entries", "paths", "matches"):
|
|
143
|
+
if key in outcome:
|
|
144
|
+
return outcome[key] if isinstance(outcome[key], str) else "\n".join(map(str, outcome[key]))
|
|
145
|
+
return json.dumps(outcome, indent=2, ensure_ascii=False)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def closed(name, outcome, change, files):
|
|
149
|
+
"""The tool_call fields that report a result: its status, and the diff it applied or the output it produced."""
|
|
150
|
+
outcome = outcome if isinstance(outcome, dict) else {"result": outcome}
|
|
151
|
+
failed = "error" in outcome or outcome.get("exit_code") not in (None, 0) or outcome.get("isError") is True
|
|
152
|
+
path = located(files, change["path"]) if change and not failed else None
|
|
153
|
+
content = diff(path, change["before"], change["after"]) if path else block(output(name, outcome))
|
|
154
|
+
return {"status": "failed" if failed else "completed", "content": [content]}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def guarded(callback, fallback=None):
|
|
158
|
+
"""Wrap an agent callback so a failure while reporting is logged and answered, never raised into the turn."""
|
|
159
|
+
def call(*arguments):
|
|
160
|
+
try:
|
|
161
|
+
return callback(*arguments)
|
|
162
|
+
except Exception as error:
|
|
163
|
+
print(f"turnloom acp: {callback.__name__} failed: {error!r}", file=sys.stderr)
|
|
164
|
+
return fallback
|
|
165
|
+
return call
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class Session:
|
|
169
|
+
"""One Turnloom conversation: its workspace, history and archive, and what the editor has allowed so far."""
|
|
170
|
+
|
|
171
|
+
def __init__(self, session_id, root, persona, told):
|
|
172
|
+
self.id = session_id
|
|
173
|
+
self.files = Workspace(root)
|
|
174
|
+
self.instructions = instructions(persona, None, self.files.root)
|
|
175
|
+
self.transcript = self.files.root / ".turnloom" / (session_id + ".jsonl")
|
|
176
|
+
self.history, self.archive = [], Observations()
|
|
177
|
+
self.mode, self.always = "ask", set()
|
|
178
|
+
self.mcp, self.notes, self.told = None, [], told
|
|
179
|
+
self.calls = count(1)
|
|
180
|
+
self.lock, self.turns = asyncio.Lock(), []
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class Turn:
|
|
184
|
+
"""One prompt. The agent runs on a worker thread; what it does reaches the editor through one ordered queue."""
|
|
185
|
+
|
|
186
|
+
def __init__(self, session, client):
|
|
187
|
+
self.session, self.client = session, client
|
|
188
|
+
self.loop = asyncio.get_running_loop()
|
|
189
|
+
self.outbox = asyncio.Queue()
|
|
190
|
+
self.stop = threading.Event()
|
|
191
|
+
self.asking = None
|
|
192
|
+
self.call = None
|
|
193
|
+
self.streamed = False
|
|
194
|
+
|
|
195
|
+
def post(self, item):
|
|
196
|
+
"""Queue an item for the editor from the worker thread. False once the event loop is gone."""
|
|
197
|
+
try:
|
|
198
|
+
self.loop.call_soon_threadsafe(self.outbox.put_nowait, item)
|
|
199
|
+
except RuntimeError:
|
|
200
|
+
self.stop.set()
|
|
201
|
+
return False
|
|
202
|
+
return True
|
|
203
|
+
|
|
204
|
+
def text(self, delta):
|
|
205
|
+
self.streamed = True
|
|
206
|
+
self.post(said(delta))
|
|
207
|
+
|
|
208
|
+
def thought(self, delta):
|
|
209
|
+
self.post({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": delta}})
|
|
210
|
+
|
|
211
|
+
def started(self, name, arguments):
|
|
212
|
+
session = self.session
|
|
213
|
+
fields, params = opened(f"call-{next(session.calls)}", name, arguments, session.files)
|
|
214
|
+
if fields["kind"] == "edit":
|
|
215
|
+
try:
|
|
216
|
+
fields["content"] = [diff(*session.files.plan(name, params)[:3])]
|
|
217
|
+
except (KeyError, ValueError, TypeError, OSError):
|
|
218
|
+
pass # The tool itself tells the model what is wrong with the request.
|
|
219
|
+
self.streamed = False
|
|
220
|
+
self.call = fields, len(session.files.changes)
|
|
221
|
+
self.post({"sessionUpdate": "tool_call", **fields})
|
|
222
|
+
|
|
223
|
+
def finished(self, name, arguments, result):
|
|
224
|
+
(fields, known), self.call = self.call, None
|
|
225
|
+
changes = self.session.files.changes
|
|
226
|
+
change = changes[-1] if len(changes) > known else None
|
|
227
|
+
self.post({"sessionUpdate": "tool_call_update", "toolCallId": fields["toolCallId"],
|
|
228
|
+
**closed(name, json.loads(result), change, self.session.files)})
|
|
229
|
+
|
|
230
|
+
def approve(self, kind, detail):
|
|
231
|
+
"""Decide an edit, command or MCP call on the worker thread, asking the editor unless the session already allows it."""
|
|
232
|
+
session, fields = self.session, self.call[0]
|
|
233
|
+
if self.stop.is_set() or (session.mode == "read-only" and kind != "mcp"):
|
|
234
|
+
return False
|
|
235
|
+
if not (kind == "edit" and session.mode == "auto-edit") and (kind, detail) not in session.always:
|
|
236
|
+
answer = Future()
|
|
237
|
+
options = [("allow", "Allow", "allow_once"), ("always", ALWAYS[kind], "allow_always"), ("reject", "Reject", "reject_once")]
|
|
238
|
+
request = {"tool_call": {**fields, "content": fields.get("content") or [block(detail)]},
|
|
239
|
+
"options": [{"optionId": key, "name": label, "kind": hint} for key, label, hint in options]}
|
|
240
|
+
if not self.post((request, answer)):
|
|
241
|
+
return False
|
|
242
|
+
choice = answer.result()
|
|
243
|
+
if choice not in ("allow", "always"):
|
|
244
|
+
return False
|
|
245
|
+
if choice == "always" and kind == "edit":
|
|
246
|
+
session.mode = "auto-edit"
|
|
247
|
+
self.post({"sessionUpdate": "current_mode_update", "currentModeId": session.mode})
|
|
248
|
+
elif choice == "always":
|
|
249
|
+
session.always.add((kind, detail))
|
|
250
|
+
self.post({"sessionUpdate": "tool_call_update", "toolCallId": fields["toolCallId"], "status": "in_progress"})
|
|
251
|
+
return True
|
|
252
|
+
|
|
253
|
+
def attempt(self, task):
|
|
254
|
+
"""Run the agent with the operator's connected model. Returns its Result, or the reason there is no model."""
|
|
255
|
+
session = self.session
|
|
256
|
+
try:
|
|
257
|
+
link = providers.resolve()
|
|
258
|
+
except (ValueError, OSError) as error:
|
|
259
|
+
return f"Turnloom has no model to use. {error}\n\nRun `turnloom connect` in a terminal, then send your message again."
|
|
260
|
+
root = session.files.root
|
|
261
|
+
config = Config(link.endpoint, link.model, link.key, root, system_prompt=session.instructions,
|
|
262
|
+
transcript=session.transcript, files=session.files, mcp=session.mcp,
|
|
263
|
+
context_tokens=link.context or 128000, max_reply_tokens=4096, max_steps=STEPS,
|
|
264
|
+
input_rate=link.input_rate, output_rate=link.output_rate, cache_rate=link.cache_rate,
|
|
265
|
+
read_only=session.mode == "read-only",
|
|
266
|
+
stop_requested=self.stop.is_set, approve=guarded(self.approve, False), on_text=guarded(self.text),
|
|
267
|
+
on_thought=guarded(self.thought),
|
|
268
|
+
on_tool_start=guarded(self.started), on_tool_event=guarded(self.finished))
|
|
269
|
+
if not guard.policy_path(root).is_file():
|
|
270
|
+
return run_agent(task, config, session.history, session.archive)
|
|
271
|
+
if not guard.installed():
|
|
272
|
+
return ("This workspace has a provio.yaml but Provio is not installed, so its policy cannot be applied. "
|
|
273
|
+
"Run `pip install \"turnloom[guard]\"` and send your message again.")
|
|
274
|
+
with guard.Gate(root, approve=config.approve, confirm=True, session=session.id) as config.gate:
|
|
275
|
+
return run_agent(task, config, session.history, session.archive)
|
|
276
|
+
|
|
277
|
+
def work(self, task):
|
|
278
|
+
"""The worker thread. Whatever happens it posts how the turn ended, so the turn never waits on a dead thread."""
|
|
279
|
+
try:
|
|
280
|
+
outcome = self.attempt(task)
|
|
281
|
+
except Exception as error:
|
|
282
|
+
outcome = f"Turnloom could not run this turn: {error!r}"
|
|
283
|
+
self.post(outcome)
|
|
284
|
+
|
|
285
|
+
async def send(self, update):
|
|
286
|
+
try:
|
|
287
|
+
await self.client.session_update(session_id=self.session.id, update=update)
|
|
288
|
+
except ConnectionError:
|
|
289
|
+
self.halt()
|
|
290
|
+
except Exception as error:
|
|
291
|
+
print(f"turnloom acp: dropped an update: {error}", file=sys.stderr)
|
|
292
|
+
|
|
293
|
+
async def ask(self, request, answer):
|
|
294
|
+
"""Put a permission question to the editor. Only a chosen option is an answer: a cancelled, failed or
|
|
295
|
+
withdrawn request leaves the worker with None, which it treats as a refusal."""
|
|
296
|
+
choice = None
|
|
297
|
+
try:
|
|
298
|
+
if not self.stop.is_set():
|
|
299
|
+
reply = await self.client.request_permission(session_id=self.session.id, **request)
|
|
300
|
+
choice = getattr(reply.outcome, "option_id", None)
|
|
301
|
+
except Exception as error:
|
|
302
|
+
print(f"turnloom acp: permission request failed: {error}", file=sys.stderr)
|
|
303
|
+
finally:
|
|
304
|
+
if not answer.done():
|
|
305
|
+
answer.set_result(choice)
|
|
306
|
+
|
|
307
|
+
def halt(self):
|
|
308
|
+
"""End the turn: stop the agent and withdraw a question the editor has not answered."""
|
|
309
|
+
self.stop.set()
|
|
310
|
+
if self.asking and not self.asking.done():
|
|
311
|
+
self.asking.cancel()
|
|
312
|
+
|
|
313
|
+
async def run(self, task):
|
|
314
|
+
"""Run the turn to its end and return the protocol's stop reason. Turns in one session run one at a time."""
|
|
315
|
+
session = self.session
|
|
316
|
+
try:
|
|
317
|
+
async with session.lock:
|
|
318
|
+
if self.stop.is_set():
|
|
319
|
+
return "cancelled"
|
|
320
|
+
news = [note for note in session.notes if note not in session.told]
|
|
321
|
+
if news:
|
|
322
|
+
session.told.update(news)
|
|
323
|
+
await self.send(said("Turnloom did not connect these MCP servers from the editor:\n"
|
|
324
|
+
+ "".join(f"- {note}\n" for note in news) + "\n"))
|
|
325
|
+
threading.Thread(target=self.work, args=(task,), daemon=True).start()
|
|
326
|
+
while not isinstance(outcome := await self.outbox.get(), (Result, str)):
|
|
327
|
+
if isinstance(outcome, tuple):
|
|
328
|
+
self.asking = asyncio.ensure_future(self.ask(*outcome))
|
|
329
|
+
else:
|
|
330
|
+
await self.send(outcome)
|
|
331
|
+
if self.call:
|
|
332
|
+
await self.send({"sessionUpdate": "tool_call_update", "toolCallId": self.call[0]["toolCallId"],
|
|
333
|
+
"status": "failed"})
|
|
334
|
+
reason, closing = "end_turn", [outcome]
|
|
335
|
+
if isinstance(outcome, Result):
|
|
336
|
+
if outcome.status == "step_limit" or (outcome.status == "partial" and outcome.steps >= STEPS):
|
|
337
|
+
reason = "max_turn_requests"
|
|
338
|
+
elif outcome.truncated:
|
|
339
|
+
reason = "max_tokens"
|
|
340
|
+
closing = [outcome.answer] if outcome.answer and not self.streamed else []
|
|
341
|
+
if outcome.errors and outcome.status != "completed" and not self.stop.is_set():
|
|
342
|
+
closing.append(outcome.errors[-1] if outcome.answer else "\n".join(outcome.errors))
|
|
343
|
+
if closing:
|
|
344
|
+
await self.send(said(("\n\n" if self.streamed else "") + "\n\n".join(closing)))
|
|
345
|
+
return "cancelled" if self.stop.is_set() else reason
|
|
346
|
+
finally:
|
|
347
|
+
self.halt()
|
|
348
|
+
session.turns.remove(self)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
class Agent:
|
|
352
|
+
"""The protocol surface: each method answers one request or notification from the editor."""
|
|
353
|
+
|
|
354
|
+
def __init__(self, base, persona):
|
|
355
|
+
self.base, self.persona = base, persona
|
|
356
|
+
self.sessions = {}
|
|
357
|
+
self.servers = ExitStack()
|
|
358
|
+
self.told = set()
|
|
359
|
+
self.client = None
|
|
360
|
+
|
|
361
|
+
def on_connect(self, client):
|
|
362
|
+
self.client = client
|
|
363
|
+
|
|
364
|
+
def session(self, session_id):
|
|
365
|
+
if session_id not in self.sessions:
|
|
366
|
+
raise sdk().RequestError(-32002, "Resource not found", {"sessionId": session_id})
|
|
367
|
+
return self.sessions[session_id]
|
|
368
|
+
|
|
369
|
+
def open(self, session_id, cwd, servers):
|
|
370
|
+
"""Create the conversation behind a session ID, rooted at the directory the editor names."""
|
|
371
|
+
root = self.base / cwd
|
|
372
|
+
if not root.is_dir():
|
|
373
|
+
raise sdk().RequestError.invalid_params({"details": f"cwd is not an existing directory: {cwd}"})
|
|
374
|
+
self.halt(session_id)
|
|
375
|
+
session = self.sessions[session_id] = Session(session_id, root, self.persona, self.told)
|
|
376
|
+
usable, session.notes = tool_servers(servers)
|
|
377
|
+
if usable:
|
|
378
|
+
try:
|
|
379
|
+
session.mcp = self.servers.enter_context(McpTools(None, session.files.root, servers=usable))
|
|
380
|
+
except ValueError as error:
|
|
381
|
+
session.notes.append(str(error))
|
|
382
|
+
return session
|
|
383
|
+
|
|
384
|
+
def halt(self, session_id):
|
|
385
|
+
session = self.sessions.get(session_id)
|
|
386
|
+
for turn in list(session.turns) if session else ():
|
|
387
|
+
turn.halt()
|
|
388
|
+
|
|
389
|
+
def close(self):
|
|
390
|
+
"""Stop whatever still runs and shut down the MCP servers the sessions started."""
|
|
391
|
+
for session_id in self.sessions:
|
|
392
|
+
self.halt(session_id)
|
|
393
|
+
self.servers.close()
|
|
394
|
+
|
|
395
|
+
@staticmethod
|
|
396
|
+
def modes(session):
|
|
397
|
+
return {"current_mode_id": session.mode, "available_modes": [
|
|
398
|
+
{"id": key, "name": name, "description": about} for key, (name, about) in MODES.items()]}
|
|
399
|
+
|
|
400
|
+
async def initialize(self, **_):
|
|
401
|
+
"""Advertise what is implemented and nothing more. Turnloom speaks protocol version 1 whatever is proposed."""
|
|
402
|
+
return sdk().InitializeResponse(
|
|
403
|
+
protocol_version=1, agent_info={"name": "Turnloom", "version": __version__}, auth_methods=[],
|
|
404
|
+
agent_capabilities={"load_session": True, "mcp_capabilities": {"http": False, "sse": False},
|
|
405
|
+
"prompt_capabilities": {"image": False, "audio": False, "embedded_context": True}})
|
|
406
|
+
|
|
407
|
+
async def new_session(self, cwd, mcp_servers=None, **_):
|
|
408
|
+
session = self.open(uuid4().hex, cwd, mcp_servers)
|
|
409
|
+
return sdk().NewSessionResponse(session_id=session.id, modes=self.modes(session))
|
|
410
|
+
|
|
411
|
+
async def load_session(self, cwd, session_id, mcp_servers=None, **_):
|
|
412
|
+
"""Continue a saved Turnloom session: rebuild its context, then replay it to the editor before answering."""
|
|
413
|
+
path = self.base / cwd / ".turnloom" / (session_id + ".jsonl")
|
|
414
|
+
if not SESSION.fullmatch(session_id) or path.parent.is_symlink() or not path.is_file():
|
|
415
|
+
raise sdk().RequestError(-32002, "Resource not found", {"sessionId": session_id})
|
|
416
|
+
session = self.open(session_id, cwd, mcp_servers)
|
|
417
|
+
try:
|
|
418
|
+
session.history = load_history(path, session.instructions)
|
|
419
|
+
await self.replay(session, path)
|
|
420
|
+
except (OSError, KeyError, TypeError) as error:
|
|
421
|
+
del self.sessions[session_id]
|
|
422
|
+
raise sdk().RequestError.internal_error({"details": f"The saved session cannot be read: {error!r}"})
|
|
423
|
+
return sdk().LoadSessionResponse(modes=self.modes(session))
|
|
424
|
+
|
|
425
|
+
async def replay(self, session, path):
|
|
426
|
+
"""Show the editor a saved conversation: each message, and each finished tool together with its result."""
|
|
427
|
+
calls, edit, spoken = {}, None, None
|
|
428
|
+
for event in events(path):
|
|
429
|
+
kind, update = event.get("type"), None
|
|
430
|
+
if kind == "start":
|
|
431
|
+
update = said(event["task"], "user")
|
|
432
|
+
elif kind == "assistant":
|
|
433
|
+
spoken = event["message"].get("content")
|
|
434
|
+
calls = {call["id"]: call["function"] for call in event["message"].get("tool_calls") or []}
|
|
435
|
+
update = said(spoken) if spoken else None
|
|
436
|
+
elif kind == "edit":
|
|
437
|
+
edit = event
|
|
438
|
+
elif kind == "tool" and event["id"] in calls:
|
|
439
|
+
function = calls.pop(event["id"])
|
|
440
|
+
fields, _ = opened(f"call-{next(session.calls)}", function["name"], function["arguments"], session.files)
|
|
441
|
+
update = {"sessionUpdate": "tool_call", **fields, **closed(function["name"], event["result"], edit, session.files)}
|
|
442
|
+
edit = None
|
|
443
|
+
elif kind == "end" and event["result"].get("status") in ("partial", "step_limit"):
|
|
444
|
+
# The same closing answer load_history restores to the model's context.
|
|
445
|
+
answer = event["result"].get("answer")
|
|
446
|
+
update = said(answer) if answer and answer != spoken else None
|
|
447
|
+
if update:
|
|
448
|
+
await self.client.session_update(session_id=session.id, update=update)
|
|
449
|
+
|
|
450
|
+
async def set_session_mode(self, session_id, mode_id, **_):
|
|
451
|
+
session = self.session(session_id)
|
|
452
|
+
if mode_id not in MODES:
|
|
453
|
+
raise sdk().RequestError.invalid_params({"details": f"Unknown mode: {mode_id}"})
|
|
454
|
+
session.mode = mode_id
|
|
455
|
+
|
|
456
|
+
async def prompt(self, session_id, prompt, **_):
|
|
457
|
+
session = self.session(session_id)
|
|
458
|
+
task = task_text(prompt, session.files.root)
|
|
459
|
+
if not task:
|
|
460
|
+
raise sdk().RequestError.invalid_params({"details": "The prompt has no text."})
|
|
461
|
+
turn = Turn(session, self.client)
|
|
462
|
+
session.turns.append(turn)
|
|
463
|
+
running = asyncio.ensure_future(turn.run(task))
|
|
464
|
+
try:
|
|
465
|
+
reason = await asyncio.shield(running)
|
|
466
|
+
except asyncio.CancelledError:
|
|
467
|
+
# The editor withdrew the request or went away. Stop the agent and give it a moment to wind down,
|
|
468
|
+
# so the answer can still be a proper cancelled turn. Past that the turn finishes on its own.
|
|
469
|
+
turn.halt()
|
|
470
|
+
await asyncio.wait({running}, timeout=GRACE)
|
|
471
|
+
if not running.done():
|
|
472
|
+
raise
|
|
473
|
+
reason = running.result()
|
|
474
|
+
return sdk().PromptResponse(stop_reason=reason)
|
|
475
|
+
|
|
476
|
+
async def cancel(self, session_id, **_):
|
|
477
|
+
self.halt(session_id)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def serve(default_workspace, persona="builder"):
|
|
481
|
+
"""Run the agent on stdin and stdout until the editor disconnects. Nothing but protocol frames goes to stdout."""
|
|
482
|
+
acp = sdk()
|
|
483
|
+
if not default_workspace.is_dir():
|
|
484
|
+
raise ValueError(f"Workspace does not exist: {default_workspace}")
|
|
485
|
+
roster.find(persona, default_workspace)
|
|
486
|
+
agent = Agent(default_workspace.resolve(), persona)
|
|
487
|
+
try:
|
|
488
|
+
asyncio.run(acp.run_agent(agent))
|
|
489
|
+
except KeyboardInterrupt:
|
|
490
|
+
return 130
|
|
491
|
+
finally:
|
|
492
|
+
agent.close()
|
|
493
|
+
return 0
|