@aislop-inc/opencode-mem 0.0.0-stage → 2.41.1
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/LICENSE +21 -0
- package/README.md +811 -2
- package/dist/config.d.ts +577 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +1141 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1268 -0
- package/dist/plugin.d.ts +10 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +10 -0
- package/dist/services/ai/ai-provider-factory.d.ts +8 -0
- package/dist/services/ai/ai-provider-factory.d.ts.map +1 -0
- package/dist/services/ai/ai-provider-factory.js +61 -0
- package/dist/services/ai/api-key-placeholder.d.ts +2 -0
- package/dist/services/ai/api-key-placeholder.d.ts.map +1 -0
- package/dist/services/ai/api-key-placeholder.js +14 -0
- package/dist/services/ai/internal-capture-sessions.d.ts +7 -0
- package/dist/services/ai/internal-capture-sessions.d.ts.map +1 -0
- package/dist/services/ai/internal-capture-sessions.js +31 -0
- package/dist/services/ai/opencode-diagnostics.d.ts +8 -0
- package/dist/services/ai/opencode-diagnostics.d.ts.map +1 -0
- package/dist/services/ai/opencode-diagnostics.js +36 -0
- package/dist/services/ai/opencode-host-config.d.ts +11 -0
- package/dist/services/ai/opencode-host-config.d.ts.map +1 -0
- package/dist/services/ai/opencode-host-config.js +51 -0
- package/dist/services/ai/opencode-provider-loader.d.ts +4 -0
- package/dist/services/ai/opencode-provider-loader.d.ts.map +1 -0
- package/dist/services/ai/opencode-provider-loader.js +4 -0
- package/dist/services/ai/opencode-provider.d.ts +154 -0
- package/dist/services/ai/opencode-provider.d.ts.map +1 -0
- package/dist/services/ai/opencode-provider.js +731 -0
- package/dist/services/ai/opencode-sdk-client.d.ts +7 -0
- package/dist/services/ai/opencode-sdk-client.d.ts.map +1 -0
- package/dist/services/ai/opencode-sdk-client.js +38 -0
- package/dist/services/ai/profile-llm-client.d.ts +3 -0
- package/dist/services/ai/profile-llm-client.d.ts.map +1 -0
- package/dist/services/ai/profile-llm-client.js +29 -0
- package/dist/services/ai/provider-config.d.ts +19 -0
- package/dist/services/ai/provider-config.d.ts.map +1 -0
- package/dist/services/ai/provider-config.js +36 -0
- package/dist/services/ai/providers/anthropic-messages.d.ts +35 -0
- package/dist/services/ai/providers/anthropic-messages.d.ts.map +1 -0
- package/dist/services/ai/providers/anthropic-messages.js +220 -0
- package/dist/services/ai/providers/api-route.d.ts +49 -0
- package/dist/services/ai/providers/api-route.d.ts.map +1 -0
- package/dist/services/ai/providers/api-route.js +57 -0
- package/dist/services/ai/providers/atlas-cloud.d.ts +51 -0
- package/dist/services/ai/providers/atlas-cloud.d.ts.map +1 -0
- package/dist/services/ai/providers/atlas-cloud.js +59 -0
- package/dist/services/ai/providers/base-provider.d.ts +33 -0
- package/dist/services/ai/providers/base-provider.d.ts.map +1 -0
- package/dist/services/ai/providers/base-provider.js +24 -0
- package/dist/services/ai/providers/cheaper-inference.d.ts +50 -0
- package/dist/services/ai/providers/cheaper-inference.d.ts.map +1 -0
- package/dist/services/ai/providers/cheaper-inference.js +58 -0
- package/dist/services/ai/providers/cloudgpu.d.ts +52 -0
- package/dist/services/ai/providers/cloudgpu.d.ts.map +1 -0
- package/dist/services/ai/providers/cloudgpu.js +60 -0
- package/dist/services/ai/providers/google-gemini.d.ts +16 -0
- package/dist/services/ai/providers/google-gemini.d.ts.map +1 -0
- package/dist/services/ai/providers/google-gemini.js +228 -0
- package/dist/services/ai/providers/minimax.d.ts +38 -0
- package/dist/services/ai/providers/minimax.d.ts.map +1 -0
- package/dist/services/ai/providers/minimax.js +57 -0
- package/dist/services/ai/providers/openai-chat-completion.d.ts +30 -0
- package/dist/services/ai/providers/openai-chat-completion.d.ts.map +1 -0
- package/dist/services/ai/providers/openai-chat-completion.js +532 -0
- package/dist/services/ai/providers/openai-responses.d.ts +14 -0
- package/dist/services/ai/providers/openai-responses.d.ts.map +1 -0
- package/dist/services/ai/providers/openai-responses.js +182 -0
- package/dist/services/ai/providers/orcarouter.d.ts +52 -0
- package/dist/services/ai/providers/orcarouter.d.ts.map +1 -0
- package/dist/services/ai/providers/orcarouter.js +66 -0
- package/dist/services/ai/providers/runcrate.d.ts +49 -0
- package/dist/services/ai/providers/runcrate.d.ts.map +1 -0
- package/dist/services/ai/providers/runcrate.js +57 -0
- package/dist/services/ai/session/ai-session-manager.d.ts +25 -0
- package/dist/services/ai/session/ai-session-manager.d.ts.map +1 -0
- package/dist/services/ai/session/ai-session-manager.js +180 -0
- package/dist/services/ai/session/session-types.d.ts +43 -0
- package/dist/services/ai/session/session-types.d.ts.map +1 -0
- package/dist/services/ai/session/session-types.js +1 -0
- package/dist/services/ai/tools/tool-schema.d.ts +41 -0
- package/dist/services/ai/tools/tool-schema.d.ts.map +1 -0
- package/dist/services/ai/tools/tool-schema.js +24 -0
- package/dist/services/ai/validators/user-profile-validator.d.ts +13 -0
- package/dist/services/ai/validators/user-profile-validator.d.ts.map +1 -0
- package/dist/services/ai/validators/user-profile-validator.js +114 -0
- package/dist/services/api-handlers.d.ts +277 -0
- package/dist/services/api-handlers.d.ts.map +1 -0
- package/dist/services/api-handlers.js +1740 -0
- package/dist/services/auth-token.d.ts +11 -0
- package/dist/services/auth-token.d.ts.map +1 -0
- package/dist/services/auth-token.js +44 -0
- package/dist/services/auto-capture-config-status.d.ts +15 -0
- package/dist/services/auto-capture-config-status.d.ts.map +1 -0
- package/dist/services/auto-capture-config-status.js +31 -0
- package/dist/services/auto-capture.d.ts +33 -0
- package/dist/services/auto-capture.d.ts.map +1 -0
- package/dist/services/auto-capture.js +906 -0
- package/dist/services/auto-update.d.ts +28 -0
- package/dist/services/auto-update.d.ts.map +1 -0
- package/dist/services/auto-update.js +197 -0
- package/dist/services/capture-evidence-events.d.ts +3 -0
- package/dist/services/capture-evidence-events.d.ts.map +1 -0
- package/dist/services/capture-evidence-events.js +15 -0
- package/dist/services/capture-evidence.d.ts +21 -0
- package/dist/services/capture-evidence.d.ts.map +1 -0
- package/dist/services/capture-evidence.js +168 -0
- package/dist/services/capture-tool-evidence.d.ts +21 -0
- package/dist/services/capture-tool-evidence.d.ts.map +1 -0
- package/dist/services/capture-tool-evidence.js +109 -0
- package/dist/services/cleanup-service.d.ts +26 -0
- package/dist/services/cleanup-service.d.ts.map +1 -0
- package/dist/services/cleanup-service.js +199 -0
- package/dist/services/client.d.ts +167 -0
- package/dist/services/client.d.ts.map +1 -0
- package/dist/services/client.js +535 -0
- package/dist/services/context.d.ts +15 -0
- package/dist/services/context.d.ts.map +1 -0
- package/dist/services/context.js +44 -0
- package/dist/services/cors.d.ts +13 -0
- package/dist/services/cors.d.ts.map +1 -0
- package/dist/services/cors.js +52 -0
- package/dist/services/deduplication-service.d.ts +29 -0
- package/dist/services/deduplication-service.d.ts.map +1 -0
- package/dist/services/deduplication-service.js +113 -0
- package/dist/services/dreaming-lock.d.ts +6 -0
- package/dist/services/dreaming-lock.d.ts.map +1 -0
- package/dist/services/dreaming-lock.js +84 -0
- package/dist/services/dreaming-service.d.ts +96 -0
- package/dist/services/dreaming-service.d.ts.map +1 -0
- package/dist/services/dreaming-service.js +626 -0
- package/dist/services/embedding.d.ts +92 -0
- package/dist/services/embedding.d.ts.map +1 -0
- package/dist/services/embedding.js +467 -0
- package/dist/services/injected-prompt-filter.d.ts +49 -0
- package/dist/services/injected-prompt-filter.d.ts.map +1 -0
- package/dist/services/injected-prompt-filter.js +79 -0
- package/dist/services/jsonc.d.ts +7 -0
- package/dist/services/jsonc.d.ts.map +1 -0
- package/dist/services/jsonc.js +110 -0
- package/dist/services/language-detector.d.ts +3 -0
- package/dist/services/language-detector.d.ts.map +1 -0
- package/dist/services/language-detector.js +33 -0
- package/dist/services/logger.d.ts +15 -0
- package/dist/services/logger.d.ts.map +1 -0
- package/dist/services/logger.js +171 -0
- package/dist/services/markdown/backend.d.ts +35 -0
- package/dist/services/markdown/backend.d.ts.map +1 -0
- package/dist/services/markdown/backend.js +111 -0
- package/dist/services/markdown/document.d.ts +44 -0
- package/dist/services/markdown/document.d.ts.map +1 -0
- package/dist/services/markdown/document.js +159 -0
- package/dist/services/markdown/reconcile.d.ts +26 -0
- package/dist/services/markdown/reconcile.d.ts.map +1 -0
- package/dist/services/markdown/reconcile.js +333 -0
- package/dist/services/markdown/vault.d.ts +32 -0
- package/dist/services/markdown/vault.d.ts.map +1 -0
- package/dist/services/markdown/vault.js +142 -0
- package/dist/services/markdown/watcher.d.ts +22 -0
- package/dist/services/markdown/watcher.d.ts.map +1 -0
- package/dist/services/markdown/watcher.js +131 -0
- package/dist/services/memory-portability-service.d.ts +38 -0
- package/dist/services/memory-portability-service.d.ts.map +1 -0
- package/dist/services/memory-portability-service.js +372 -0
- package/dist/services/memory-provenance.d.ts +16 -0
- package/dist/services/memory-provenance.d.ts.map +1 -0
- package/dist/services/memory-provenance.js +115 -0
- package/dist/services/memory-recall.d.ts +49 -0
- package/dist/services/memory-recall.d.ts.map +1 -0
- package/dist/services/memory-recall.js +196 -0
- package/dist/services/memory-scope.d.ts +17 -0
- package/dist/services/memory-scope.d.ts.map +1 -0
- package/dist/services/memory-scope.js +43 -0
- package/dist/services/migration-service.d.ts +43 -0
- package/dist/services/migration-service.d.ts.map +1 -0
- package/dist/services/migration-service.js +333 -0
- package/dist/services/onnxruntime-resolve.d.ts +25 -0
- package/dist/services/onnxruntime-resolve.d.ts.map +1 -0
- package/dist/services/onnxruntime-resolve.js +176 -0
- package/dist/services/privacy.d.ts +38 -0
- package/dist/services/privacy.d.ts.map +1 -0
- package/dist/services/privacy.js +156 -0
- package/dist/services/request-timeouts.d.ts +4 -0
- package/dist/services/request-timeouts.d.ts.map +1 -0
- package/dist/services/request-timeouts.js +5 -0
- package/dist/services/runtime-require.d.ts +18 -0
- package/dist/services/runtime-require.d.ts.map +1 -0
- package/dist/services/runtime-require.js +75 -0
- package/dist/services/secret-resolver.d.ts +2 -0
- package/dist/services/secret-resolver.d.ts.map +1 -0
- package/dist/services/secret-resolver.js +65 -0
- package/dist/services/shard-inventory-service.d.ts +70 -0
- package/dist/services/shard-inventory-service.d.ts.map +1 -0
- package/dist/services/shard-inventory-service.js +315 -0
- package/dist/services/shard-path-migration-service.d.ts +32 -0
- package/dist/services/shard-path-migration-service.d.ts.map +1 -0
- package/dist/services/shard-path-migration-service.js +386 -0
- package/dist/services/skills/skills-manager.d.ts +39 -0
- package/dist/services/skills/skills-manager.d.ts.map +1 -0
- package/dist/services/skills/skills-manager.js +231 -0
- package/dist/services/skills/types.d.ts +32 -0
- package/dist/services/skills/types.d.ts.map +1 -0
- package/dist/services/skills/types.js +5 -0
- package/dist/services/stats-service.d.ts +71 -0
- package/dist/services/stats-service.d.ts.map +1 -0
- package/dist/services/stats-service.js +288 -0
- package/dist/services/tags.d.ts +30 -0
- package/dist/services/tags.d.ts.map +1 -0
- package/dist/services/tags.js +245 -0
- package/dist/services/transformers-resolve.d.ts +17 -0
- package/dist/services/transformers-resolve.d.ts.map +1 -0
- package/dist/services/transformers-resolve.js +142 -0
- package/dist/services/turso/connection-manager.d.ts +66 -0
- package/dist/services/turso/connection-manager.d.ts.map +1 -0
- package/dist/services/turso/connection-manager.js +408 -0
- package/dist/services/turso/encryption-key.d.ts +17 -0
- package/dist/services/turso/encryption-key.d.ts.map +1 -0
- package/dist/services/turso/encryption-key.js +111 -0
- package/dist/services/turso/encryption-migrator.d.ts +6 -0
- package/dist/services/turso/encryption-migrator.d.ts.map +1 -0
- package/dist/services/turso/encryption-migrator.js +234 -0
- package/dist/services/turso/engine-migrator.d.ts +6 -0
- package/dist/services/turso/engine-migrator.d.ts.map +1 -0
- package/dist/services/turso/engine-migrator.js +318 -0
- package/dist/services/turso/error-classifiers.d.ts +4 -0
- package/dist/services/turso/error-classifiers.d.ts.map +1 -0
- package/dist/services/turso/error-classifiers.js +19 -0
- package/dist/services/turso/legacy-migrator.d.ts +2 -0
- package/dist/services/turso/legacy-migrator.d.ts.map +1 -0
- package/dist/services/turso/legacy-migrator.js +535 -0
- package/dist/services/turso/lifecycle.d.ts +11 -0
- package/dist/services/turso/lifecycle.d.ts.map +1 -0
- package/dist/services/turso/lifecycle.js +32 -0
- package/dist/services/turso/operation-lock.d.ts +26 -0
- package/dist/services/turso/operation-lock.d.ts.map +1 -0
- package/dist/services/turso/operation-lock.js +188 -0
- package/dist/services/turso/plugin-refs.d.ts +13 -0
- package/dist/services/turso/plugin-refs.d.ts.map +1 -0
- package/dist/services/turso/plugin-refs.js +43 -0
- package/dist/services/turso/ready.d.ts +3 -0
- package/dist/services/turso/ready.d.ts.map +1 -0
- package/dist/services/turso/ready.js +32 -0
- package/dist/services/turso/schema-migrations.d.ts +24 -0
- package/dist/services/turso/schema-migrations.d.ts.map +1 -0
- package/dist/services/turso/schema-migrations.js +367 -0
- package/dist/services/turso/shard-manager.d.ts +41 -0
- package/dist/services/turso/shard-manager.d.ts.map +1 -0
- package/dist/services/turso/shard-manager.js +419 -0
- package/dist/services/turso/sqlite-handle-release.d.ts +31 -0
- package/dist/services/turso/sqlite-handle-release.d.ts.map +1 -0
- package/dist/services/turso/sqlite-handle-release.js +101 -0
- package/dist/services/turso/turso-db.d.ts +61 -0
- package/dist/services/turso/turso-db.d.ts.map +1 -0
- package/dist/services/turso/turso-db.js +214 -0
- package/dist/services/turso/types.d.ts +52 -0
- package/dist/services/turso/types.d.ts.map +1 -0
- package/dist/services/turso/types.js +1 -0
- package/dist/services/turso/vector-search.d.ts +63 -0
- package/dist/services/turso/vector-search.d.ts.map +1 -0
- package/dist/services/turso/vector-search.js +510 -0
- package/dist/services/turso/vector-utils.d.ts +16 -0
- package/dist/services/turso/vector-utils.d.ts.map +1 -0
- package/dist/services/turso/vector-utils.js +98 -0
- package/dist/services/turso/wal-index-recovery.d.ts +51 -0
- package/dist/services/turso/wal-index-recovery.d.ts.map +1 -0
- package/dist/services/turso/wal-index-recovery.js +248 -0
- package/dist/services/update-on-capture.d.ts +77 -0
- package/dist/services/update-on-capture.d.ts.map +1 -0
- package/dist/services/update-on-capture.js +116 -0
- package/dist/services/user-memory-learning.d.ts +137 -0
- package/dist/services/user-memory-learning.d.ts.map +1 -0
- package/dist/services/user-memory-learning.js +787 -0
- package/dist/services/user-profile/ai-cleanup.d.ts +59 -0
- package/dist/services/user-profile/ai-cleanup.d.ts.map +1 -0
- package/dist/services/user-profile/ai-cleanup.js +488 -0
- package/dist/services/user-profile/learning-lock.d.ts +41 -0
- package/dist/services/user-profile/learning-lock.d.ts.map +1 -0
- package/dist/services/user-profile/learning-lock.js +619 -0
- package/dist/services/user-profile/profile-context.d.ts +2 -0
- package/dist/services/user-profile/profile-context.d.ts.map +1 -0
- package/dist/services/user-profile/profile-context.js +105 -0
- package/dist/services/user-profile/profile-utils.d.ts +17 -0
- package/dist/services/user-profile/profile-utils.d.ts.map +1 -0
- package/dist/services/user-profile/profile-utils.js +77 -0
- package/dist/services/user-profile/types.d.ts +93 -0
- package/dist/services/user-profile/types.d.ts.map +1 -0
- package/dist/services/user-profile/types.js +1 -0
- package/dist/services/user-profile/user-profile-manager.d.ts +106 -0
- package/dist/services/user-profile/user-profile-manager.d.ts.map +1 -0
- package/dist/services/user-profile/user-profile-manager.js +1793 -0
- package/dist/services/user-prompt/user-prompt-manager.d.ts +64 -0
- package/dist/services/user-prompt/user-prompt-manager.d.ts.map +1 -0
- package/dist/services/user-prompt/user-prompt-manager.js +428 -0
- package/dist/services/web-api-auth.d.ts +4 -0
- package/dist/services/web-api-auth.d.ts.map +1 -0
- package/dist/services/web-api-auth.js +24 -0
- package/dist/services/web-auth.d.ts +47 -0
- package/dist/services/web-auth.d.ts.map +1 -0
- package/dist/services/web-auth.js +105 -0
- package/dist/services/web-server.d.ts +58 -0
- package/dist/services/web-server.d.ts.map +1 -0
- package/dist/services/web-server.js +774 -0
- package/dist/shared/api/index.d.ts +5 -0
- package/dist/shared/api/index.d.ts.map +1 -0
- package/dist/shared/api/index.js +2 -0
- package/dist/shared/api/portability-schemas.d.ts +57 -0
- package/dist/shared/api/portability-schemas.d.ts.map +1 -0
- package/dist/shared/api/portability-schemas.js +39 -0
- package/dist/shared/api/schemas.d.ts +296 -0
- package/dist/shared/api/schemas.d.ts.map +1 -0
- package/dist/shared/api/schemas.js +134 -0
- package/dist/shared/api/types.d.ts +29 -0
- package/dist/shared/api/types.d.ts.map +1 -0
- package/dist/shared/api/types.js +1 -0
- package/dist/tui.d.ts +10 -0
- package/dist/tui.d.ts.map +1 -0
- package/dist/tui.js +17 -0
- package/dist/types/index.d.ts +19 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +1 -0
- package/dist/utils/context-limit.d.ts +11 -0
- package/dist/utils/context-limit.d.ts.map +1 -0
- package/dist/utils/context-limit.js +43 -0
- package/dist/utils/math.d.ts +8 -0
- package/dist/utils/math.d.ts.map +1 -0
- package/dist/utils/math.js +48 -0
- package/dist/utils/profile.d.ts +3 -0
- package/dist/utils/profile.d.ts.map +1 -0
- package/dist/utils/profile.js +15 -0
- package/dist/v2/adapter.d.ts +3 -0
- package/dist/v2/adapter.d.ts.map +1 -0
- package/dist/v2/adapter.js +217 -0
- package/dist/v2/legacy-client.d.ts +22 -0
- package/dist/v2/legacy-client.d.ts.map +1 -0
- package/dist/v2/legacy-client.js +410 -0
- package/dist/v2/plugin.d.ts +4 -0
- package/dist/v2/plugin.d.ts.map +1 -0
- package/dist/v2/plugin.js +34 -0
- package/dist/v2/toast-rpc.d.ts +43 -0
- package/dist/v2/toast-rpc.d.ts.map +1 -0
- package/dist/v2/toast-rpc.js +26 -0
- package/dist/web/accent-preview.html +444 -0
- package/dist/web/assets/index-mTgxOb5l.css +2 -0
- package/dist/web/assets/index-ysje17yK.js +109 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/web/favicon.ico +0 -0
- package/dist/web/favicon.svg +11 -0
- package/dist/web/index.html +29 -0
- package/dist/web/opencode-mem-icon.png +0 -0
- package/package.json +122 -4
|
@@ -0,0 +1,731 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured output via the opencode HTTP server.
|
|
3
|
+
*
|
|
4
|
+
* Replaces the older auth.json/OAuth-juggling flow. Instead of forging
|
|
5
|
+
* requests to provider HTTP endpoints ourselves, we delegate to the
|
|
6
|
+
* running opencode server: it already owns the user's auth (any provider,
|
|
7
|
+
* including github-copilot personal/business), token refresh, and provider
|
|
8
|
+
* routing.
|
|
9
|
+
*
|
|
10
|
+
* Per call we create a transient session, prompt it with a JSON schema,
|
|
11
|
+
* then delete the session so it does not pollute the user's TUI session
|
|
12
|
+
* list.
|
|
13
|
+
*
|
|
14
|
+
* Internal capture sessions are least-privilege (issue #189): ordinary
|
|
15
|
+
* agent tools are denied, only StructuredOutput is allowed, a dedicated
|
|
16
|
+
* agent caps steps, and a hard timeout fails closed.
|
|
17
|
+
*
|
|
18
|
+
* The primary transport is the authenticated v2 SDK client initialized from
|
|
19
|
+
* the plugin host's client configuration. A raw fetch fallback remains for
|
|
20
|
+
* older SDK builds that do not expose the v2 session methods.
|
|
21
|
+
*/
|
|
22
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
import { diagnosticUrl, readJson, responseStatus, } from "./opencode-diagnostics.js";
|
|
26
|
+
import { INTERNAL_CAPTURE_SESSION_TITLE, trackInternalCaptureSession, untrackInternalCaptureSession, } from "./internal-capture-sessions.js";
|
|
27
|
+
import { createLazyV2Client } from "./opencode-sdk-client.js";
|
|
28
|
+
/** Dedicated agent registered via the plugin config hook (step-capped). */
|
|
29
|
+
export const STRUCTURED_OUTPUT_AGENT = "opencode-mem-structured";
|
|
30
|
+
/** Hard ceiling for a single internal structured-output prompt. */
|
|
31
|
+
export const STRUCTURED_OUTPUT_TIMEOUT_MS = 90_000;
|
|
32
|
+
/**
|
|
33
|
+
* Soft agent step budget. OpenCode only injects a last-step warning for
|
|
34
|
+
* `format: json_schema` and can keep looping when forced tool calls fail
|
|
35
|
+
* (seen with opencode-claude-auth in #278). We also abort client-side after
|
|
36
|
+
* this many `step-start` parts.
|
|
37
|
+
*/
|
|
38
|
+
export const STRUCTURED_OUTPUT_MAX_STEPS = 2;
|
|
39
|
+
/** Cap OpenCode schema retries so a bad provider cannot spin forever. */
|
|
40
|
+
export const STRUCTURED_OUTPUT_DEFAULT_RETRY_COUNT = 1;
|
|
41
|
+
let _structuredOutputTimeoutOverrideMs;
|
|
42
|
+
// Configured timeout (CONFIG.opencodeTimeoutMs), injected by the plugin init
|
|
43
|
+
// instead of importing config.js here: the provider module is bundled into a
|
|
44
|
+
// single-file lazy loader whose import graph must stay free of config side
|
|
45
|
+
// effects (config creation banner, DATA_DIR mkdir) for subprocess gates.
|
|
46
|
+
let _structuredOutputConfiguredMs;
|
|
47
|
+
/**
|
|
48
|
+
* Test helper: override the structured-output prompt timeout. Pass undefined
|
|
49
|
+
* to reset to the configured value.
|
|
50
|
+
*/
|
|
51
|
+
export function setStructuredOutputTimeoutMsForTests(ms) {
|
|
52
|
+
_structuredOutputTimeoutOverrideMs = ms;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Inject the configured structured-output timeout (CONFIG.opencodeTimeoutMs,
|
|
56
|
+
* already normalized/clamped in config.ts). Called once by the plugin init.
|
|
57
|
+
*/
|
|
58
|
+
export function setStructuredOutputTimeoutConfig(ms) {
|
|
59
|
+
_structuredOutputConfiguredMs = ms;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Effective structured-output prompt timeout: the test override wins, then
|
|
63
|
+
* the configured value, then the hard-coded default.
|
|
64
|
+
*/
|
|
65
|
+
function effectiveStructuredOutputTimeoutMs() {
|
|
66
|
+
return (_structuredOutputTimeoutOverrideMs ??
|
|
67
|
+
_structuredOutputConfiguredMs ??
|
|
68
|
+
STRUCTURED_OUTPUT_TIMEOUT_MS);
|
|
69
|
+
}
|
|
70
|
+
export const STRUCTURED_OUTPUT_PERMISSIONS = [
|
|
71
|
+
{ permission: "*", pattern: "*", action: "deny" },
|
|
72
|
+
{ permission: "StructuredOutput", pattern: "*", action: "allow" },
|
|
73
|
+
];
|
|
74
|
+
export const STRUCTURED_OUTPUT_TOOLS = {
|
|
75
|
+
"*": false,
|
|
76
|
+
StructuredOutput: true,
|
|
77
|
+
};
|
|
78
|
+
export const STRUCTURED_OUTPUT_METADATA = {
|
|
79
|
+
"opencode-mem": {
|
|
80
|
+
internal: true,
|
|
81
|
+
purpose: "structured-output",
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
const _internalSessions = new Set();
|
|
85
|
+
const _structuredStepCounts = new Map();
|
|
86
|
+
const _structuredStepAbortErrors = new Map();
|
|
87
|
+
let _connectedProviders = new Set();
|
|
88
|
+
let _v2Client;
|
|
89
|
+
const _v2Clients = new Set();
|
|
90
|
+
let _v2BaseUrl;
|
|
91
|
+
let _hostFetch;
|
|
92
|
+
let _useSdkTransport = false;
|
|
93
|
+
// Registered by the plugin init so a gate miss can force one provider-directory
|
|
94
|
+
// refresh before failing (late host provider registration).
|
|
95
|
+
let _connectedProvidersRefresher;
|
|
96
|
+
export function setHostFetch(customFetch) {
|
|
97
|
+
_hostFetch = customFetch;
|
|
98
|
+
}
|
|
99
|
+
export function resetHostFetch() {
|
|
100
|
+
_hostFetch = undefined;
|
|
101
|
+
}
|
|
102
|
+
export function setConnectedProviders(providers) {
|
|
103
|
+
_connectedProviders = new Set(providers);
|
|
104
|
+
}
|
|
105
|
+
export function isProviderConnected(providerName) {
|
|
106
|
+
return _connectedProviders.has(providerName);
|
|
107
|
+
}
|
|
108
|
+
/** Register (or clear) the refresh callback used by ensureProviderConnected. */
|
|
109
|
+
export function setConnectedProvidersRefresher(refresher) {
|
|
110
|
+
_connectedProvidersRefresher = refresher;
|
|
111
|
+
}
|
|
112
|
+
/** Clear the refresh callback only if it is still the one being disposed. */
|
|
113
|
+
export function clearConnectedProvidersRefresher(refresher) {
|
|
114
|
+
if (_connectedProvidersRefresher === refresher)
|
|
115
|
+
_connectedProvidersRefresher = undefined;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Refresh-on-miss for the connectivity gate: when a provider id is missing
|
|
119
|
+
* from the snapshot and a refresher is registered, await one refresh and
|
|
120
|
+
* re-check. Returns the re-checked connectivity; never refreshes twice for
|
|
121
|
+
* the same call and never throws (refresh errors are logged by the refresher).
|
|
122
|
+
*/
|
|
123
|
+
export async function ensureProviderConnected(providerName) {
|
|
124
|
+
if (_connectedProviders.has(providerName))
|
|
125
|
+
return true;
|
|
126
|
+
const refresher = _connectedProvidersRefresher;
|
|
127
|
+
if (!refresher)
|
|
128
|
+
return false;
|
|
129
|
+
try {
|
|
130
|
+
await refresher();
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// The refresher logs; a failed refresh keeps the previous set.
|
|
134
|
+
}
|
|
135
|
+
return _connectedProviders.has(providerName);
|
|
136
|
+
}
|
|
137
|
+
export function setV2Client(client) {
|
|
138
|
+
_v2Client = client;
|
|
139
|
+
_v2Clients.add(client);
|
|
140
|
+
// Native v2 adapters pass a session-capable client without a server URL.
|
|
141
|
+
// Enable the SDK transport path so structured output does not require createV2Client.
|
|
142
|
+
if (hasV2SessionClient(client)) {
|
|
143
|
+
_useSdkTransport = true;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
// Each OpenCode location registers a client bound to that location, and this module is shared by all of them.
|
|
147
|
+
// One that closes must hand over to a live client, or later captures run on a closed location.
|
|
148
|
+
export function releaseV2Client(client) {
|
|
149
|
+
_v2Clients.delete(client);
|
|
150
|
+
if (_v2Client === client)
|
|
151
|
+
_v2Client = [..._v2Clients].at(-1);
|
|
152
|
+
}
|
|
153
|
+
export function getV2Client() {
|
|
154
|
+
return _v2Client;
|
|
155
|
+
}
|
|
156
|
+
export function createV2Client(serverUrl, transport) {
|
|
157
|
+
const baseUrl = typeof serverUrl === "string" ? serverUrl : serverUrl.toString();
|
|
158
|
+
const activeTransport = transport ?? (_hostFetch ? { fetch: _hostFetch } : undefined);
|
|
159
|
+
_v2BaseUrl = baseUrl;
|
|
160
|
+
_useSdkTransport = Boolean(activeTransport?.fetch || activeTransport?.headers);
|
|
161
|
+
return createLazyV2Client(baseUrl, activeTransport);
|
|
162
|
+
}
|
|
163
|
+
/** True while an internal structured-output session is live (create → delete). */
|
|
164
|
+
export function isInternalStructuredSession(sessionID) {
|
|
165
|
+
return _internalSessions.has(sessionID);
|
|
166
|
+
}
|
|
167
|
+
/** Test helper: clear tracked internal session IDs. */
|
|
168
|
+
export function resetInternalStructuredSessions() {
|
|
169
|
+
_internalSessions.clear();
|
|
170
|
+
_structuredStepCounts.clear();
|
|
171
|
+
_structuredStepAbortErrors.clear();
|
|
172
|
+
}
|
|
173
|
+
function markInternalSession(sessionID) {
|
|
174
|
+
_internalSessions.add(sessionID);
|
|
175
|
+
_structuredStepCounts.set(sessionID, 0);
|
|
176
|
+
_structuredStepAbortErrors.delete(sessionID);
|
|
177
|
+
}
|
|
178
|
+
function unmarkInternalSession(sessionID) {
|
|
179
|
+
_internalSessions.delete(sessionID);
|
|
180
|
+
_structuredStepCounts.delete(sessionID);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Record a `step-start` on an internal structured-output session.
|
|
184
|
+
* Returns whether the client should abort (step budget exceeded).
|
|
185
|
+
*/
|
|
186
|
+
export function noteStructuredOutputStep(sessionID) {
|
|
187
|
+
if (!_internalSessions.has(sessionID)) {
|
|
188
|
+
return { tracked: false, steps: 0, shouldAbort: false };
|
|
189
|
+
}
|
|
190
|
+
const steps = (_structuredStepCounts.get(sessionID) ?? 0) + 1;
|
|
191
|
+
_structuredStepCounts.set(sessionID, steps);
|
|
192
|
+
if (steps <= STRUCTURED_OUTPUT_MAX_STEPS) {
|
|
193
|
+
return { tracked: true, steps, shouldAbort: false };
|
|
194
|
+
}
|
|
195
|
+
_structuredStepAbortErrors.set(sessionID, new Error(`opencode-mem: structured-output aborted after ${steps} steps ` +
|
|
196
|
+
`(agent maxSteps=${STRUCTURED_OUTPUT_MAX_STEPS} may be ignored while format:json_schema forces tool calls; ` +
|
|
197
|
+
`try a model that supports OpenCode structured output, or configure memoryModel + memoryApiUrl fallback — ` +
|
|
198
|
+
`opencode-claude-auth loops are a common trigger)`));
|
|
199
|
+
return { tracked: true, steps, shouldAbort: true };
|
|
200
|
+
}
|
|
201
|
+
/** Consume a step-budget abort error if the prompt failed after we aborted. */
|
|
202
|
+
export function takeStructuredOutputStepAbortError(sessionID) {
|
|
203
|
+
const error = _structuredStepAbortErrors.get(sessionID);
|
|
204
|
+
_structuredStepAbortErrors.delete(sessionID);
|
|
205
|
+
return error;
|
|
206
|
+
}
|
|
207
|
+
function structuredOutputTimeoutError(timeoutMs) {
|
|
208
|
+
return new Error(`opencode-mem: structured-output timed out after ${timeoutMs}ms ` +
|
|
209
|
+
`(provider may be looping on forced StructuredOutput; ` +
|
|
210
|
+
`try a known json_schema-capable model or memoryModel + memoryApiUrl fallback)`);
|
|
211
|
+
}
|
|
212
|
+
function preferStepAbortError(sessionID, error) {
|
|
213
|
+
const stepError = takeStructuredOutputStepAbortError(sessionID);
|
|
214
|
+
if (stepError)
|
|
215
|
+
throw stepError;
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
function sessionCreateBody() {
|
|
219
|
+
return {
|
|
220
|
+
title: INTERNAL_CAPTURE_SESSION_TITLE,
|
|
221
|
+
permission: STRUCTURED_OUTPUT_PERMISSIONS,
|
|
222
|
+
metadata: STRUCTURED_OUTPUT_METADATA,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function sessionPromptFields(args) {
|
|
226
|
+
return {
|
|
227
|
+
model: { providerID: args.providerID, modelID: args.modelID },
|
|
228
|
+
// The V1 session prompt body carries the reasoning variant as a sibling
|
|
229
|
+
// of `model` (SessionPromptData.body.variant), not inside model.
|
|
230
|
+
...(args.variant ? { variant: args.variant } : {}),
|
|
231
|
+
agent: STRUCTURED_OUTPUT_AGENT,
|
|
232
|
+
system: args.systemPrompt,
|
|
233
|
+
parts: [{ type: "text", text: args.userPrompt }],
|
|
234
|
+
tools: STRUCTURED_OUTPUT_TOOLS,
|
|
235
|
+
// `noReply` suppresses assistant generation in current OpenCode builds,
|
|
236
|
+
// which also suppresses `info.structured_output`; structured capture needs
|
|
237
|
+
// the assistant run even though the temporary session is deleted afterward.
|
|
238
|
+
format: {
|
|
239
|
+
type: "json_schema",
|
|
240
|
+
schema: args.jsonSchema,
|
|
241
|
+
// Bound schema retries so Claude-auth / incompatible providers fail
|
|
242
|
+
// closed instead of spinning until the 90s timeout (#278).
|
|
243
|
+
retryCount: args.retryCount ?? STRUCTURED_OUTPUT_DEFAULT_RETRY_COUNT,
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/** Tools-off prompt body: plain text JSON (no format:json_schema / forced tools). */
|
|
248
|
+
function sessionTextJsonPromptFields(args) {
|
|
249
|
+
const schemaText = JSON.stringify(args.jsonSchema, null, 2);
|
|
250
|
+
return {
|
|
251
|
+
model: { providerID: args.providerID, modelID: args.modelID },
|
|
252
|
+
...(args.variant ? { variant: args.variant } : {}),
|
|
253
|
+
agent: STRUCTURED_OUTPUT_AGENT,
|
|
254
|
+
system: `${args.systemPrompt}\n\n` +
|
|
255
|
+
`Respond with ONLY a single JSON value that validates against this JSON Schema. ` +
|
|
256
|
+
`No markdown fences, no commentary.\n\nJSON Schema:\n${schemaText}`,
|
|
257
|
+
parts: [{ type: "text", text: args.userPrompt }],
|
|
258
|
+
tools: { "*": false },
|
|
259
|
+
noReply: false,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Claude / opencode-claude-auth registers as provider `anthropic`. Forced
|
|
264
|
+
* `format: json_schema` often loops; prefer auth-preserving text JSON (#278).
|
|
265
|
+
*/
|
|
266
|
+
export function shouldUseOpencodeTextJson(providerID) {
|
|
267
|
+
const id = providerID.trim().toLowerCase();
|
|
268
|
+
return id === "anthropic" || id.startsWith("anthropic/");
|
|
269
|
+
}
|
|
270
|
+
function extractAssistantText(parts) {
|
|
271
|
+
return parts
|
|
272
|
+
.filter((part) => typeof part === "object" &&
|
|
273
|
+
part !== null &&
|
|
274
|
+
part.type === "text" &&
|
|
275
|
+
typeof part.text === "string")
|
|
276
|
+
.map((part) => part.text)
|
|
277
|
+
.join("\n")
|
|
278
|
+
.trim();
|
|
279
|
+
}
|
|
280
|
+
function parseJsonFromAssistantText(rawText) {
|
|
281
|
+
const fenced = rawText.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
282
|
+
const candidate = (fenced?.[1] ?? rawText).trim();
|
|
283
|
+
const match = candidate.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
|
|
284
|
+
if (!match) {
|
|
285
|
+
throw new Error("opencode-mem: text-json fallback response did not contain valid JSON " +
|
|
286
|
+
"(opencode-claude-auth / anthropic path)");
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
return JSON.parse(match[0]);
|
|
290
|
+
}
|
|
291
|
+
catch (error) {
|
|
292
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
293
|
+
throw new Error(`opencode-mem: text-json fallback JSON parse failed: ${message}`, {
|
|
294
|
+
cause: error,
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
/** Last host-reported session model from `chat.params` / the V2 context hook. */
|
|
299
|
+
let rememberedSessionModel;
|
|
300
|
+
/**
|
|
301
|
+
* Remember the concrete model the host is using for the current session.
|
|
302
|
+
* OpenCode v2 no longer writes `model.json`, so profile-learning and other
|
|
303
|
+
* non-prompt structured-output paths need this in-process fallback for
|
|
304
|
+
* `opencodeModel: "inherit"` (issue #453).
|
|
305
|
+
*/
|
|
306
|
+
export function rememberSessionModel(providerID, modelID) {
|
|
307
|
+
if (!providerID || !modelID || modelID === "inherit")
|
|
308
|
+
return;
|
|
309
|
+
rememberedSessionModel = { providerID, modelID };
|
|
310
|
+
}
|
|
311
|
+
/** Test helper: drop the in-process session model between cases. */
|
|
312
|
+
export function clearRememberedSessionModelForTests() {
|
|
313
|
+
rememberedSessionModel = undefined;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Resolve `opencodeModel: "inherit"` to a concrete provider/model.
|
|
317
|
+
*
|
|
318
|
+
* Prefer an explicit prompt-recorded model (auto-capture path). Otherwise use
|
|
319
|
+
* the last host-reported session model, then OpenCode's recent `model.json`
|
|
320
|
+
* list (v1 hosts), so profile-learning / conflict / dedup paths don't send the
|
|
321
|
+
* literal model id "inherit" (ProviderModelNotFoundError).
|
|
322
|
+
*/
|
|
323
|
+
export function resolveOpencodeModelRef(opts) {
|
|
324
|
+
if (opts.modelID !== "inherit") {
|
|
325
|
+
return { providerID: opts.providerID, modelID: opts.modelID };
|
|
326
|
+
}
|
|
327
|
+
if (opts.prompt?.providerId && opts.prompt?.modelId) {
|
|
328
|
+
return { providerID: opts.prompt.providerId, modelID: opts.prompt.modelId };
|
|
329
|
+
}
|
|
330
|
+
if (rememberedSessionModel) {
|
|
331
|
+
return rememberedSessionModel;
|
|
332
|
+
}
|
|
333
|
+
const recent = readRecentOpencodeModel(opts.providerID);
|
|
334
|
+
if (recent)
|
|
335
|
+
return recent;
|
|
336
|
+
throw new Error("opencode-mem: opencodeModel is 'inherit' but no session model was recorded and no recent OpenCode model is available");
|
|
337
|
+
}
|
|
338
|
+
function readRecentOpencodeModel(preferredProvider) {
|
|
339
|
+
try {
|
|
340
|
+
// OpenCode state path mirrors `opencode debug paths` → state.
|
|
341
|
+
const stateDir = process.env.XDG_STATE_HOME || join(homedir(), ".local", "state");
|
|
342
|
+
const modelPath = join(stateDir, "opencode", "model.json");
|
|
343
|
+
if (!existsSync(modelPath))
|
|
344
|
+
return undefined;
|
|
345
|
+
const raw = JSON.parse(readFileSync(modelPath, "utf8"));
|
|
346
|
+
const recent = Array.isArray(raw.recent) ? raw.recent : [];
|
|
347
|
+
const match = (preferredProvider
|
|
348
|
+
? recent.find((r) => r.providerID === preferredProvider && r.modelID)
|
|
349
|
+
: undefined) ?? recent.find((r) => r.providerID && r.modelID);
|
|
350
|
+
if (!match?.providerID || !match.modelID)
|
|
351
|
+
return undefined;
|
|
352
|
+
return { providerID: match.providerID, modelID: match.modelID };
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
return undefined;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Generate one structured completion via opencode's HTTP API.
|
|
360
|
+
*
|
|
361
|
+
* Prefer `format: json_schema` (forced StructuredOutput). For Anthropic /
|
|
362
|
+
* opencode-claude-auth (`providerID` anthropic), use auth-preserving text JSON
|
|
363
|
+
* instead — forced tools commonly loop until timeout (#278).
|
|
364
|
+
*
|
|
365
|
+
* Throws on: session.create failure, prompt failure, AssistantMessage.error,
|
|
366
|
+
* missing structured/text JSON, timeout, or final Zod validation failure.
|
|
367
|
+
*/
|
|
368
|
+
export async function generateStructuredOutput(opts) {
|
|
369
|
+
const resolved = resolveOpencodeModelRef({
|
|
370
|
+
providerID: opts.providerID,
|
|
371
|
+
modelID: opts.modelID,
|
|
372
|
+
});
|
|
373
|
+
const { client, systemPrompt, userPrompt, schema, directory, retryCount, variant } = opts;
|
|
374
|
+
const { providerID, modelID } = resolved;
|
|
375
|
+
const jsonSchema = schema.toJSONSchema?.() ?? (await import("zod")).z.toJSONSchema(schema);
|
|
376
|
+
const args = {
|
|
377
|
+
providerID,
|
|
378
|
+
modelID,
|
|
379
|
+
variant,
|
|
380
|
+
systemPrompt,
|
|
381
|
+
userPrompt,
|
|
382
|
+
directory,
|
|
383
|
+
retryCount,
|
|
384
|
+
jsonSchema,
|
|
385
|
+
schema,
|
|
386
|
+
};
|
|
387
|
+
const useTextJson = shouldUseOpencodeTextJson(providerID);
|
|
388
|
+
if (_useSdkTransport && hasV2SessionClient(client)) {
|
|
389
|
+
return useTextJson
|
|
390
|
+
? generateTextJsonViaSdkClient(client, args)
|
|
391
|
+
: generateViaSdkClient(client, args);
|
|
392
|
+
}
|
|
393
|
+
const baseUrl = _v2BaseUrl;
|
|
394
|
+
if (!baseUrl) {
|
|
395
|
+
throw new Error("opencode-mem: v2 server base URL not initialized; call createV2Client(serverUrl) first");
|
|
396
|
+
}
|
|
397
|
+
const base = stripTrailingSlash(baseUrl);
|
|
398
|
+
return useTextJson
|
|
399
|
+
? generateTextJsonViaFetch(base, args)
|
|
400
|
+
: generateJsonSchemaViaFetch(base, args);
|
|
401
|
+
}
|
|
402
|
+
function hasV2SessionClient(client) {
|
|
403
|
+
const session = client.session;
|
|
404
|
+
if (typeof session !== "object" || session === null)
|
|
405
|
+
return false;
|
|
406
|
+
const candidate = session;
|
|
407
|
+
return (typeof candidate.create === "function" &&
|
|
408
|
+
typeof candidate.prompt === "function" &&
|
|
409
|
+
typeof candidate.delete === "function");
|
|
410
|
+
}
|
|
411
|
+
async function generateJsonSchemaViaFetch(base, args) {
|
|
412
|
+
const sessionID = await createSession(base, args.directory);
|
|
413
|
+
markInternalSession(sessionID);
|
|
414
|
+
try {
|
|
415
|
+
const info = await withStructuredOutputTimeout(() => promptSession(base, {
|
|
416
|
+
sessionID,
|
|
417
|
+
directory: args.directory,
|
|
418
|
+
providerID: args.providerID,
|
|
419
|
+
modelID: args.modelID,
|
|
420
|
+
variant: args.variant,
|
|
421
|
+
systemPrompt: args.systemPrompt,
|
|
422
|
+
userPrompt: args.userPrompt,
|
|
423
|
+
jsonSchema: args.jsonSchema,
|
|
424
|
+
retryCount: args.retryCount,
|
|
425
|
+
}), () => abortSession(base, sessionID, args.directory));
|
|
426
|
+
if (info.error) {
|
|
427
|
+
throw new Error(`opencode-mem: opencode reported ${info.error.name}: ${formatAssistantError(info.error)}`);
|
|
428
|
+
}
|
|
429
|
+
const structuredOutput = info.structured_output ?? info.structured;
|
|
430
|
+
if (structuredOutput === undefined || structuredOutput === null) {
|
|
431
|
+
throw new Error("opencode-mem: opencode returned no structured output (info.structured_output/info.structured were empty)");
|
|
432
|
+
}
|
|
433
|
+
return args.schema.parse(structuredOutput);
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
preferStepAbortError(sessionID, error);
|
|
437
|
+
throw error;
|
|
438
|
+
}
|
|
439
|
+
finally {
|
|
440
|
+
unmarkInternalSession(sessionID);
|
|
441
|
+
try {
|
|
442
|
+
await deleteSession(base, sessionID, args.directory);
|
|
443
|
+
}
|
|
444
|
+
catch {
|
|
445
|
+
// intentionally swallowed
|
|
446
|
+
}
|
|
447
|
+
finally {
|
|
448
|
+
untrackInternalCaptureSession(sessionID);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
async function generateTextJsonViaFetch(base, args) {
|
|
453
|
+
const sessionID = await createSession(base, args.directory);
|
|
454
|
+
markInternalSession(sessionID);
|
|
455
|
+
try {
|
|
456
|
+
const data = await withStructuredOutputTimeout(() => promptSessionRaw(base, {
|
|
457
|
+
sessionID,
|
|
458
|
+
directory: args.directory,
|
|
459
|
+
body: sessionTextJsonPromptFields(args),
|
|
460
|
+
}), () => abortSession(base, sessionID, args.directory));
|
|
461
|
+
if (!data.info) {
|
|
462
|
+
throw new Error("opencode-mem: prompt response missing `info`");
|
|
463
|
+
}
|
|
464
|
+
if (data.info.error) {
|
|
465
|
+
throw new Error(`opencode-mem: opencode reported ${data.info.error.name}: ${formatAssistantError(data.info.error)}`);
|
|
466
|
+
}
|
|
467
|
+
const rawText = extractAssistantText(Array.isArray(data.parts) ? data.parts : []);
|
|
468
|
+
return args.schema.parse(parseJsonFromAssistantText(rawText));
|
|
469
|
+
}
|
|
470
|
+
catch (error) {
|
|
471
|
+
preferStepAbortError(sessionID, error);
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
finally {
|
|
475
|
+
unmarkInternalSession(sessionID);
|
|
476
|
+
try {
|
|
477
|
+
await deleteSession(base, sessionID, args.directory);
|
|
478
|
+
}
|
|
479
|
+
catch {
|
|
480
|
+
// intentionally swallowed
|
|
481
|
+
}
|
|
482
|
+
finally {
|
|
483
|
+
untrackInternalCaptureSession(sessionID);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
async function generateViaSdkClient(client, args) {
|
|
488
|
+
const createdResponse = await client.session.create({
|
|
489
|
+
...sessionCreateBody(),
|
|
490
|
+
...(args.directory ? { directory: args.directory } : {}),
|
|
491
|
+
});
|
|
492
|
+
const created = readSdkData(createdResponse, "POST /session");
|
|
493
|
+
if (!created.id) {
|
|
494
|
+
throw new Error("opencode-mem: session.create returned no session id; cannot generate structured output");
|
|
495
|
+
}
|
|
496
|
+
const sessionID = created.id;
|
|
497
|
+
trackInternalCaptureSession(sessionID);
|
|
498
|
+
markInternalSession(sessionID);
|
|
499
|
+
try {
|
|
500
|
+
const promptResponse = await withStructuredOutputTimeout(() => client.session.prompt({
|
|
501
|
+
sessionID,
|
|
502
|
+
...(args.directory ? { directory: args.directory } : {}),
|
|
503
|
+
...sessionPromptFields(args),
|
|
504
|
+
}), () => client.session.abort?.({
|
|
505
|
+
sessionID,
|
|
506
|
+
...(args.directory ? { directory: args.directory } : {}),
|
|
507
|
+
}));
|
|
508
|
+
const data = readSdkData(promptResponse, "POST /session/{id}/message");
|
|
509
|
+
if (!data.info) {
|
|
510
|
+
throw new Error("opencode-mem: prompt response missing `info`");
|
|
511
|
+
}
|
|
512
|
+
if (data.info.error) {
|
|
513
|
+
throw new Error(`opencode-mem: opencode reported ${data.info.error.name}: ${formatAssistantError(data.info.error)}`);
|
|
514
|
+
}
|
|
515
|
+
const structuredOutput = data.info.structured_output ?? data.info.structured;
|
|
516
|
+
if (structuredOutput === undefined || structuredOutput === null) {
|
|
517
|
+
throw new Error("opencode-mem: opencode returned no structured output (info.structured_output/info.structured were empty)");
|
|
518
|
+
}
|
|
519
|
+
return args.schema.parse(structuredOutput);
|
|
520
|
+
}
|
|
521
|
+
catch (error) {
|
|
522
|
+
preferStepAbortError(sessionID, error);
|
|
523
|
+
throw error;
|
|
524
|
+
}
|
|
525
|
+
finally {
|
|
526
|
+
unmarkInternalSession(sessionID);
|
|
527
|
+
try {
|
|
528
|
+
await client.session.delete({
|
|
529
|
+
sessionID,
|
|
530
|
+
...(args.directory ? { directory: args.directory } : {}),
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
catch {
|
|
534
|
+
// Best-effort cleanup for the transient capture session.
|
|
535
|
+
}
|
|
536
|
+
finally {
|
|
537
|
+
untrackInternalCaptureSession(sessionID);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
async function generateTextJsonViaSdkClient(client, args) {
|
|
542
|
+
const createdResponse = await client.session.create({
|
|
543
|
+
...sessionCreateBody(),
|
|
544
|
+
...(args.directory ? { directory: args.directory } : {}),
|
|
545
|
+
});
|
|
546
|
+
const created = readSdkData(createdResponse, "POST /session");
|
|
547
|
+
if (!created.id) {
|
|
548
|
+
throw new Error("opencode-mem: session.create returned no session id; cannot generate structured output");
|
|
549
|
+
}
|
|
550
|
+
const sessionID = created.id;
|
|
551
|
+
trackInternalCaptureSession(sessionID);
|
|
552
|
+
markInternalSession(sessionID);
|
|
553
|
+
try {
|
|
554
|
+
const promptResponse = await withStructuredOutputTimeout(() => client.session.prompt({
|
|
555
|
+
sessionID,
|
|
556
|
+
...(args.directory ? { directory: args.directory } : {}),
|
|
557
|
+
...sessionTextJsonPromptFields(args),
|
|
558
|
+
}), () => client.session.abort?.({
|
|
559
|
+
sessionID,
|
|
560
|
+
...(args.directory ? { directory: args.directory } : {}),
|
|
561
|
+
}));
|
|
562
|
+
const data = readSdkData(promptResponse, "POST /session/{id}/message");
|
|
563
|
+
if (!data.info) {
|
|
564
|
+
throw new Error("opencode-mem: prompt response missing `info`");
|
|
565
|
+
}
|
|
566
|
+
if (data.info.error) {
|
|
567
|
+
throw new Error(`opencode-mem: opencode reported ${data.info.error.name}: ${formatAssistantError(data.info.error)}`);
|
|
568
|
+
}
|
|
569
|
+
const rawText = extractAssistantText(Array.isArray(data.parts) ? data.parts : []);
|
|
570
|
+
return args.schema.parse(parseJsonFromAssistantText(rawText));
|
|
571
|
+
}
|
|
572
|
+
catch (error) {
|
|
573
|
+
preferStepAbortError(sessionID, error);
|
|
574
|
+
throw error;
|
|
575
|
+
}
|
|
576
|
+
finally {
|
|
577
|
+
unmarkInternalSession(sessionID);
|
|
578
|
+
try {
|
|
579
|
+
await client.session.delete({
|
|
580
|
+
sessionID,
|
|
581
|
+
...(args.directory ? { directory: args.directory } : {}),
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
catch {
|
|
585
|
+
// Best-effort cleanup for the transient capture session.
|
|
586
|
+
}
|
|
587
|
+
finally {
|
|
588
|
+
untrackInternalCaptureSession(sessionID);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
async function withStructuredOutputTimeout(run, onTimeout) {
|
|
593
|
+
let timer;
|
|
594
|
+
const timeoutMs = effectiveStructuredOutputTimeoutMs();
|
|
595
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
596
|
+
timer = setTimeout(() => {
|
|
597
|
+
reject(structuredOutputTimeoutError(timeoutMs));
|
|
598
|
+
}, timeoutMs);
|
|
599
|
+
});
|
|
600
|
+
try {
|
|
601
|
+
return await Promise.race([run(), timeoutPromise]);
|
|
602
|
+
}
|
|
603
|
+
catch (error) {
|
|
604
|
+
if (error instanceof Error && error.message.includes("structured-output timed out after")) {
|
|
605
|
+
try {
|
|
606
|
+
await onTimeout();
|
|
607
|
+
}
|
|
608
|
+
catch {
|
|
609
|
+
// best-effort abort
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
throw error;
|
|
613
|
+
}
|
|
614
|
+
finally {
|
|
615
|
+
if (timer !== undefined)
|
|
616
|
+
clearTimeout(timer);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
function readSdkData(response, label) {
|
|
620
|
+
const result = response;
|
|
621
|
+
if (result?.error !== undefined) {
|
|
622
|
+
const status = result.response ? ` (${responseStatus(result.response)})` : "";
|
|
623
|
+
const responseUrl = result.response?.url || result.request?.url;
|
|
624
|
+
const url = responseUrl ? diagnosticUrl(responseUrl) : "the authenticated client";
|
|
625
|
+
throw new Error(`opencode-mem: opencode ${label} failed at ${url}${status}: <redacted response body>`);
|
|
626
|
+
}
|
|
627
|
+
if (result?.data === undefined) {
|
|
628
|
+
throw new Error(`opencode-mem: opencode ${label} returned no response data`);
|
|
629
|
+
}
|
|
630
|
+
return result.data;
|
|
631
|
+
}
|
|
632
|
+
function stripTrailingSlash(url) {
|
|
633
|
+
return url.endsWith("/") ? url.slice(0, -1) : url;
|
|
634
|
+
}
|
|
635
|
+
function buildQuery(directory) {
|
|
636
|
+
if (!directory)
|
|
637
|
+
return "";
|
|
638
|
+
return `?directory=${encodeURIComponent(directory)}`;
|
|
639
|
+
}
|
|
640
|
+
async function fetchJson(endpoint, init) {
|
|
641
|
+
let res;
|
|
642
|
+
try {
|
|
643
|
+
res = await activeFetch()(new Request(endpoint.url, init));
|
|
644
|
+
}
|
|
645
|
+
catch (error) {
|
|
646
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
647
|
+
throw new Error(`opencode-mem: failed to fetch ${endpoint.label} at ${diagnosticUrl(endpoint.url)}: ${message}`, { cause: error });
|
|
648
|
+
}
|
|
649
|
+
return readJson(res, endpoint);
|
|
650
|
+
}
|
|
651
|
+
async function createSession(base, directory) {
|
|
652
|
+
const url = `${base}/session${buildQuery(directory)}`;
|
|
653
|
+
const body = await fetchJson({ label: "POST /session", url }, {
|
|
654
|
+
method: "POST",
|
|
655
|
+
headers: { "Content-Type": "application/json" },
|
|
656
|
+
body: JSON.stringify(sessionCreateBody()),
|
|
657
|
+
});
|
|
658
|
+
if (!body.id) {
|
|
659
|
+
throw new Error("opencode-mem: session.create returned no session id; cannot generate structured output");
|
|
660
|
+
}
|
|
661
|
+
trackInternalCaptureSession(body.id);
|
|
662
|
+
return body.id;
|
|
663
|
+
}
|
|
664
|
+
function formatAssistantError(error) {
|
|
665
|
+
if (!error.data)
|
|
666
|
+
return error.name;
|
|
667
|
+
const details = safeAssistantErrorDetails(error.data);
|
|
668
|
+
if (!error.data.message)
|
|
669
|
+
return details;
|
|
670
|
+
return details ? `${error.data.message}; ${details}` : error.data.message;
|
|
671
|
+
}
|
|
672
|
+
function safeAssistantErrorDetails(data) {
|
|
673
|
+
const safeFields = {};
|
|
674
|
+
for (const key of ["statusCode", "providerID", "modelID"]) {
|
|
675
|
+
const value = data[key];
|
|
676
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
677
|
+
safeFields[key] = value;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
const entries = Object.entries(safeFields);
|
|
681
|
+
if (entries.length === 0)
|
|
682
|
+
return "";
|
|
683
|
+
return `details=${JSON.stringify(Object.fromEntries(entries))}`;
|
|
684
|
+
}
|
|
685
|
+
async function promptSession(base, args) {
|
|
686
|
+
const data = await promptSessionRaw(base, {
|
|
687
|
+
sessionID: args.sessionID,
|
|
688
|
+
directory: args.directory,
|
|
689
|
+
body: sessionPromptFields(args),
|
|
690
|
+
});
|
|
691
|
+
if (!data.info) {
|
|
692
|
+
throw new Error("opencode-mem: prompt response missing `info`");
|
|
693
|
+
}
|
|
694
|
+
return data.info;
|
|
695
|
+
}
|
|
696
|
+
async function promptSessionRaw(base, args) {
|
|
697
|
+
const url = `${base}/session/${encodeURIComponent(args.sessionID)}/message${buildQuery(args.directory)}`;
|
|
698
|
+
return fetchJson({ label: "POST /session/{id}/message", url }, {
|
|
699
|
+
method: "POST",
|
|
700
|
+
headers: { "Content-Type": "application/json" },
|
|
701
|
+
body: JSON.stringify(args.body),
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
async function abortSession(base, sessionID, directory) {
|
|
705
|
+
const url = `${base}/session/${encodeURIComponent(sessionID)}/abort${buildQuery(directory)}`;
|
|
706
|
+
try {
|
|
707
|
+
await activeFetch()(new Request(url, { method: "POST" }));
|
|
708
|
+
}
|
|
709
|
+
catch {
|
|
710
|
+
// best-effort
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
async function deleteSession(base, sessionID, directory) {
|
|
714
|
+
const url = `${base}/session/${encodeURIComponent(sessionID)}${buildQuery(directory)}`;
|
|
715
|
+
let res;
|
|
716
|
+
try {
|
|
717
|
+
res = await activeFetch()(new Request(url, { method: "DELETE" }));
|
|
718
|
+
}
|
|
719
|
+
catch (error) {
|
|
720
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
721
|
+
throw new Error(`opencode-mem: failed to fetch DELETE /session/{id} at ${diagnosticUrl(url)}: ${message}`, { cause: error });
|
|
722
|
+
}
|
|
723
|
+
// DELETE /session/:id returns boolean. We only care that it ran; failures
|
|
724
|
+
// are swallowed at the call site.
|
|
725
|
+
if (!res.ok) {
|
|
726
|
+
throw new Error(`opencode-mem: opencode DELETE /session/{id} failed at ${diagnosticUrl(url)} (${responseStatus(res)})`);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
function activeFetch() {
|
|
730
|
+
return _hostFetch ?? globalThis.fetch;
|
|
731
|
+
}
|