@jungjaehoon/mama-core 2.4.1 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -239
- package/db/migrations/030-case-first-memory-substrate.sql +13 -98
- package/db/migrations/034-add-connector-event-scope-columns.sql +9 -13
- package/db/migrations/039-add-connector-event-operator-ingest-seq.sql +9 -95
- package/db/migrations/062-refresh-connector-event-sequences.sql +9 -113
- package/db/migrations/063-refresh-legacy-connector-event-updates.sql +9 -32
- package/db/migrations/067-add-connector-event-source-entity-id.sql +9 -13
- package/db/migrations/069-create-registry-nodes.sql +52 -0
- package/db/migrations/070-record-identity.sql +35 -0
- package/db/migrations/071-service-operation-origins.sql +187 -0
- package/db/migrations/072-observation-versions.sql +29 -0
- package/db/migrations/073-registry-corrections.sql +45 -0
- package/db/migrations/074-work-graph-ref-kinds.sql +39 -0
- package/db/migrations/075-agent-judgments.sql +58 -0
- package/db/migrations/076-scoped-checkpoint-bindings.sql +15 -0
- package/db/migrations/077-legacy-record-kind.sql +6 -0
- package/db/migrations/078-source-ingest-commands.sql +18 -0
- package/db/migrations/079-twin-edge-relations.sql +43 -0
- package/db/migrations/080-restore-duration-days.sql +7 -0
- package/db/migrations/081-mailbox.sql +61 -0
- package/db/migrations/082-commitments-row-id.sql +12 -0
- package/db/migrations/083-observation-is-the-evidence.sql +49 -0
- package/db/migrations/084-scope-kind-is-not-the-cores-to-list.sql +34 -0
- package/db/migrations/085-a-migration-has-a-source.sql +37 -0
- package/db/migrations/086-the-mailbox-is-generic.sql +110 -0
- package/db/migrations/087-mailbox-payload.sql +5 -0
- package/db/migrations/088-native-input-journal.sql +14 -0
- package/db/migrations/089-native-turn-receipt-lookup.sql +3 -0
- package/db/migrations/090-model-run-native-inputs.sql +29 -0
- package/db/migrations/091-native-turn-results.sql +11 -0
- package/db/migrations/092-restore-decision-fts.sql +34 -0
- package/db/migrations/093-native-turn-primary-kind.sql +14 -0
- package/db/migrations/094-commitment-run-provenance.sql +9 -0
- package/db/migrations/095-model-run-native-input-identity.sql +39 -0
- package/db/migrations/096-drop-connector-event-index-fts.sql +9 -0
- package/db/migrations/097-native-input-json-validity.sql +37 -0
- package/db/migrations/098-workflow-memory-kind.sql +105 -0
- package/dist/action-contracts.d.ts +212 -0
- package/dist/action-contracts.js +10 -0
- package/dist/api/catalog.d.ts +118 -0
- package/dist/api/catalog.js +1756 -0
- package/dist/api/dispatch.d.ts +76 -0
- package/dist/api/dispatch.js +372 -0
- package/dist/canonicalize.d.ts +2 -2
- package/dist/canonicalize.js +3 -3
- package/dist/client/client.d.ts +33 -0
- package/dist/client/client.js +123 -0
- package/dist/client/ipc.d.ts +81 -0
- package/dist/client/ipc.js +314 -0
- package/dist/db-adapter/base-adapter.d.ts +6 -66
- package/dist/db-adapter/base-adapter.js +6 -6
- package/dist/db-adapter/index.d.ts +5 -5
- package/dist/db-adapter/index.js +2 -5
- package/dist/db-adapter/node-sqlite-adapter.d.ts +85 -15
- package/dist/db-adapter/node-sqlite-adapter.js +1968 -570
- package/dist/db-manager.d.ts +53 -97
- package/dist/db-manager.js +121 -603
- package/dist/embedding/embedder.d.ts +132 -0
- package/dist/embedding/embedder.js +299 -0
- package/dist/identity/principal-repository.d.ts +2 -2
- package/dist/index.d.ts +43 -58
- package/dist/index.js +97 -145
- package/dist/{context-compile/channel-grant.d.ts → knowledge/access.d.ts} +12 -17
- package/dist/knowledge/access.js +663 -0
- package/dist/knowledge/case-errors.d.ts +31 -0
- package/dist/knowledge/case-errors.js +40 -0
- package/dist/{cases/search-rollup.d.ts → knowledge/case-search-rollup.d.ts} +5 -4
- package/dist/{cases/search-rollup.js → knowledge/case-search-rollup.js} +6 -8
- package/dist/{cases/store.d.ts → knowledge/case-store.d.ts} +3 -6
- package/dist/{cases/store.js → knowledge/case-store.js} +7 -42
- package/dist/{cases/timeline-range.d.ts → knowledge/case-timeline-range.d.ts} +3 -3
- package/dist/{cases/timeline-range.js → knowledge/case-timeline-range.js} +47 -25
- package/dist/{cases/types.d.ts → knowledge/case-types.d.ts} +8 -2
- package/dist/{cases/types.js → knowledge/case-types.js} +1 -1
- package/dist/knowledge/commitments.d.ts +188 -0
- package/dist/knowledge/commitments.js +370 -0
- package/dist/knowledge/decision-edges.d.ts +70 -0
- package/dist/knowledge/decision-edges.js +123 -0
- package/dist/{agent-graph/types.d.ts → knowledge/graph-query.d.ts} +80 -70
- package/dist/knowledge/graph-query.js +1585 -0
- package/dist/knowledge/identity.d.ts +16 -0
- package/dist/knowledge/identity.js +22 -0
- package/dist/knowledge/index.d.ts +47 -0
- package/dist/knowledge/index.js +90 -0
- package/dist/knowledge/judgments.d.ts +118 -0
- package/dist/knowledge/judgments.js +808 -0
- package/dist/knowledge/observations.d.ts +160 -0
- package/dist/knowledge/observations.js +449 -0
- package/dist/knowledge/question-type.d.ts +34 -0
- package/dist/knowledge/question-type.js +70 -0
- package/dist/{search → knowledge}/ranker-features.js +1 -1
- package/dist/{search → knowledge}/search-quality.d.ts +0 -1
- package/dist/knowledge/search.d.ts +38 -0
- package/dist/knowledge/search.js +91 -0
- package/dist/knowledge/source-ingest.d.ts +65 -0
- package/dist/knowledge/source-ingest.js +174 -0
- package/dist/{edges/types.d.ts → knowledge/twin-edge-types.d.ts} +31 -4
- package/dist/{edges/types.js → knowledge/twin-edge-types.js} +13 -2
- package/dist/knowledge/work-dates.d.ts +49 -0
- package/dist/knowledge/work-dates.js +120 -0
- package/dist/mama-api.d.ts +114 -778
- package/dist/mama-api.js +313 -2461
- package/dist/memory/api.d.ts +264 -24
- package/dist/memory/api.js +1633 -843
- package/dist/memory/bootstrap-builder.d.ts +2 -1
- package/dist/memory/bootstrap-builder.js +5 -5
- package/dist/memory/channel-summary-state-store.d.ts +3 -2
- package/dist/memory/channel-summary-state-store.js +53 -51
- package/dist/memory/channel-summary-store.d.ts +5 -3
- package/dist/memory/channel-summary-store.js +3 -8
- package/dist/memory/dashboard-read.d.ts +46 -0
- package/dist/memory/dashboard-read.js +94 -0
- package/dist/memory/event-store.d.ts +3 -3
- package/dist/memory/event-store.js +3 -10
- package/dist/memory/finding-store.d.ts +3 -2
- package/dist/memory/finding-store.js +2 -7
- package/dist/memory/graph-read.d.ts +52 -0
- package/dist/memory/graph-read.js +130 -0
- package/dist/memory/judgment-types.d.ts +394 -0
- package/dist/memory/judgment-types.js +16 -0
- package/dist/memory/provenance-audit.d.ts +5 -2
- package/dist/memory/provenance-audit.js +8 -14
- package/dist/memory/provenance-live.d.ts +141 -0
- package/dist/memory/provenance-live.js +409 -0
- package/dist/memory/provenance-query.d.ts +5 -4
- package/dist/memory/provenance-query.js +21 -29
- package/dist/memory/provenance-resolver.d.ts +191 -0
- package/dist/memory/provenance-resolver.js +155 -0
- package/dist/memory/provenance.d.ts +1 -11
- package/dist/memory/provenance.js +2 -33
- package/dist/memory/recall-sanitize.d.ts +55 -0
- package/dist/memory/recall-sanitize.js +144 -0
- package/dist/memory/secret-filter.d.ts +32 -0
- package/dist/memory/secret-filter.js +126 -0
- package/dist/memory/truth-store.d.ts +2 -1
- package/dist/memory/truth-store.js +1 -4
- package/dist/memory/types.d.ts +74 -24
- package/dist/memory/types.js +75 -5
- package/dist/memory/write-adapters.d.ts +98 -0
- package/dist/memory/write-adapters.js +242 -0
- package/dist/operations/owner-action-effects.d.ts +53 -0
- package/dist/operations/owner-action-effects.js +96 -0
- package/dist/provenance/source-ref.d.ts +1 -1
- package/dist/provenance/source-ref.js +0 -2
- package/dist/registry/corrections.d.ts +31 -0
- package/dist/registry/corrections.js +332 -0
- package/dist/registry/record-identity.d.ts +49 -0
- package/dist/registry/record-identity.js +133 -0
- package/dist/registry/store.d.ts +101 -0
- package/dist/registry/store.js +395 -0
- package/dist/registry/types.d.ts +28 -0
- package/dist/registry/types.js +5 -0
- package/dist/relevance-scorer.js +2 -2
- package/dist/runtime/agent-event-bus.d.ts +50 -0
- package/dist/runtime/agent-event-bus.js +101 -0
- package/dist/runtime/drivers/claude-cli-wrapper.d.ts +155 -0
- package/dist/runtime/drivers/claude-cli-wrapper.js +392 -0
- package/dist/runtime/drivers/cli-arg-redaction.d.ts +2 -0
- package/dist/runtime/drivers/cli-arg-redaction.js +18 -0
- package/dist/runtime/drivers/cli-secret-redaction.d.ts +17 -0
- package/dist/runtime/drivers/cli-secret-redaction.js +126 -0
- package/dist/runtime/drivers/codex-app-server-process.d.ts +277 -0
- package/dist/runtime/drivers/codex-app-server-process.js +2342 -0
- package/dist/runtime/drivers/codex-auxiliary-tools.d.ts +17 -0
- package/dist/runtime/drivers/codex-auxiliary-tools.js +267 -0
- package/dist/runtime/drivers/codex-home.d.ts +20 -0
- package/dist/runtime/drivers/codex-home.js +674 -0
- package/dist/runtime/drivers/codex-thread-registry.d.ts +63 -0
- package/dist/runtime/drivers/codex-thread-registry.js +433 -0
- package/dist/runtime/drivers/persistent-cli-adapter.d.ts +160 -0
- package/dist/runtime/drivers/persistent-cli-adapter.js +396 -0
- package/dist/runtime/drivers/persistent-cli-process.d.ts +424 -0
- package/dist/runtime/drivers/persistent-cli-process.js +1543 -0
- package/dist/runtime/drivers/types.d.ts +456 -0
- package/dist/runtime/drivers/types.js +110 -0
- package/dist/runtime/mailbox.d.ts +223 -0
- package/dist/runtime/mailbox.js +582 -0
- package/dist/runtime/model-run-store.d.ts +28 -0
- package/dist/{model-runs/store.js → runtime/model-run-store.js} +81 -41
- package/dist/{model-runs/types.d.ts → runtime/model-run-types.d.ts} +33 -4
- package/dist/{model-runs/types.js → runtime/model-run-types.js} +1 -1
- package/dist/runtime/native-effect-observer.d.ts +22 -0
- package/dist/runtime/native-effect-observer.js +103 -0
- package/dist/runtime/native-input-journal.d.ts +46 -0
- package/dist/runtime/native-input-journal.js +308 -0
- package/dist/runtime/native-prompt.d.ts +118 -0
- package/dist/runtime/native-prompt.js +496 -0
- package/dist/runtime/native-session.d.ts +10 -0
- package/dist/{agent-graph/index.js → runtime/native-session.js} +9 -6
- package/dist/runtime/native-tool-trace-observer.d.ts +5 -0
- package/dist/runtime/native-tool-trace-observer.js +65 -0
- package/dist/runtime/native-turn.d.ts +272 -0
- package/dist/runtime/native-turn.js +1041 -0
- package/dist/runtime/operations.d.ts +236 -0
- package/dist/runtime/operations.js +565 -0
- package/dist/runtime/post-tool-handler.d.ts +74 -0
- package/dist/runtime/post-tool-handler.js +137 -0
- package/dist/runtime/prompt-layers.d.ts +126 -0
- package/dist/runtime/prompt-layers.js +239 -0
- package/dist/runtime/runtime-process.d.ts +102 -0
- package/dist/runtime/runtime-process.js +206 -0
- package/dist/runtime/runtime.d.ts +278 -0
- package/dist/runtime/runtime.js +563 -0
- package/dist/runtime/session-pool.d.ts +176 -0
- package/dist/runtime/session-pool.js +369 -0
- package/dist/runtime/stimulus-payload.d.ts +5 -0
- package/dist/runtime/stimulus-payload.js +50 -0
- package/dist/runtime/subagent-bridge.d.ts +24 -0
- package/dist/{agent-graph/types.js → runtime/subagent-bridge.js} +1 -1
- package/dist/runtime/text-completion.d.ts +22 -0
- package/dist/{agent-situation/types.js → runtime/text-completion.js} +1 -1
- package/dist/runtime/token-estimator.d.ts +25 -0
- package/dist/runtime/token-estimator.js +75 -0
- package/dist/runtime/tool-trace-store.d.ts +22 -0
- package/dist/{model-runs → runtime}/tool-trace-store.js +46 -27
- package/dist/runtime/trace-summary.d.ts +5 -0
- package/dist/runtime/trace-summary.js +74 -0
- package/dist/runtime/turn-text.d.ts +23 -0
- package/dist/runtime/turn-text.js +41 -0
- package/dist/storage/database.d.ts +67 -0
- package/dist/storage/database.js +158 -0
- package/package.json +20 -34
- package/dist/agent-graph/alias-write.d.ts +0 -3
- package/dist/agent-graph/alias-write.js +0 -234
- package/dist/agent-graph/entity-resolve.d.ts +0 -3
- package/dist/agent-graph/entity-resolve.js +0 -271
- package/dist/agent-graph/errors.d.ts +0 -4
- package/dist/agent-graph/errors.js +0 -11
- package/dist/agent-graph/graph-query.d.ts +0 -5
- package/dist/agent-graph/graph-query.js +0 -360
- package/dist/agent-graph/index.d.ts +0 -6
- package/dist/agent-situation/builder.d.ts +0 -8
- package/dist/agent-situation/builder.js +0 -239
- package/dist/agent-situation/cache-key.d.ts +0 -4
- package/dist/agent-situation/cache-key.js +0 -64
- package/dist/agent-situation/index.d.ts +0 -7
- package/dist/agent-situation/index.js +0 -28
- package/dist/agent-situation/packet-store.d.ts +0 -27
- package/dist/agent-situation/packet-store.js +0 -228
- package/dist/agent-situation/ranking-policy.d.ts +0 -18
- package/dist/agent-situation/ranking-policy.js +0 -75
- package/dist/agent-situation/source-readers.d.ts +0 -52
- package/dist/agent-situation/source-readers.js +0 -300
- package/dist/agent-situation/types.d.ts +0 -195
- package/dist/cases/wiki-page-index.d.ts +0 -37
- package/dist/cases/wiki-page-index.js +0 -201
- package/dist/config-loader.d.ts +0 -68
- package/dist/config-loader.js +0 -239
- package/dist/connectors/event-index.d.ts +0 -24
- package/dist/connectors/event-index.js +0 -245
- package/dist/connectors/raw-query.d.ts +0 -40
- package/dist/connectors/raw-query.js +0 -412
- package/dist/connectors/types.d.ts +0 -117
- package/dist/connectors/types.js +0 -3
- package/dist/context-compile/boundary-defaults.d.ts +0 -12
- package/dist/context-compile/boundary-defaults.js +0 -105
- package/dist/context-compile/channel-grant.js +0 -66
- package/dist/context-compile/compiler-policy.d.ts +0 -39
- package/dist/context-compile/compiler-policy.js +0 -147
- package/dist/context-compile/compiler.d.ts +0 -18
- package/dist/context-compile/compiler.js +0 -404
- package/dist/context-compile/index.d.ts +0 -10
- package/dist/context-compile/index.js +0 -26
- package/dist/context-compile/packet-store.d.ts +0 -8
- package/dist/context-compile/packet-store.js +0 -239
- package/dist/context-compile/ref.d.ts +0 -7
- package/dist/context-compile/ref.js +0 -102
- package/dist/context-compile/source-readers.d.ts +0 -70
- package/dist/context-compile/source-readers.js +0 -840
- package/dist/context-compile/types.d.ts +0 -155
- package/dist/context-compile/types.js +0 -11
- package/dist/context-compile/visibility.d.ts +0 -21
- package/dist/context-compile/visibility.js +0 -224
- package/dist/decision-tracker.d.ts +0 -206
- package/dist/decision-tracker.js +0 -481
- package/dist/edges/ref-validation.d.ts +0 -7
- package/dist/edges/ref-validation.js +0 -321
- package/dist/edges/store.d.ts +0 -8
- package/dist/edges/store.js +0 -129
- package/dist/embedding-client.d.ts +0 -28
- package/dist/embedding-client.js +0 -53
- package/dist/embedding-server/index.d.ts +0 -67
- package/dist/embedding-server/index.js +0 -405
- package/dist/embedding-server/mobile/auth.d.ts +0 -44
- package/dist/embedding-server/mobile/auth.js +0 -150
- package/dist/embedding-server/mobile/daemon.d.ts +0 -129
- package/dist/embedding-server/mobile/daemon.js +0 -313
- package/dist/embedding-server/mobile/output-parser.d.ts +0 -115
- package/dist/embedding-server/mobile/output-parser.js +0 -241
- package/dist/embedding-server/mobile/session-api.d.ts +0 -57
- package/dist/embedding-server/mobile/session-api.js +0 -261
- package/dist/embedding-server/mobile/session-manager.d.ts +0 -138
- package/dist/embedding-server/mobile/session-manager.js +0 -378
- package/dist/embedding-server/mobile/websocket-handler.d.ts +0 -137
- package/dist/embedding-server/mobile/websocket-handler.js +0 -486
- package/dist/embeddings.d.ts +0 -68
- package/dist/embeddings.js +0 -244
- package/dist/entities/audit-metrics.d.ts +0 -68
- package/dist/entities/audit-metrics.js +0 -124
- package/dist/entities/candidate-generator.d.ts +0 -8
- package/dist/entities/candidate-generator.js +0 -24
- package/dist/entities/entity-linked-decision-counts.d.ts +0 -2
- package/dist/entities/entity-linked-decision-counts.js +0 -29
- package/dist/entities/entity-list.d.ts +0 -22
- package/dist/entities/entity-list.js +0 -3
- package/dist/entities/entity-orphan-list.d.ts +0 -17
- package/dist/entities/entity-orphan-list.js +0 -3
- package/dist/entities/entity-search.d.ts +0 -20
- package/dist/entities/entity-search.js +0 -3
- package/dist/entities/errors.d.ts +0 -55
- package/dist/entities/errors.js +0 -100
- package/dist/entities/lineage-store.d.ts +0 -28
- package/dist/entities/lineage-store.js +0 -204
- package/dist/entities/normalization.d.ts +0 -14
- package/dist/entities/normalization.js +0 -63
- package/dist/entities/policy-store.d.ts +0 -8
- package/dist/entities/policy-store.js +0 -75
- package/dist/entities/policy-types.d.ts +0 -72
- package/dist/entities/policy-types.js +0 -59
- package/dist/entities/projection.d.ts +0 -8
- package/dist/entities/projection.js +0 -82
- package/dist/entities/provenance-query.d.ts +0 -32
- package/dist/entities/provenance-query.js +0 -3
- package/dist/entities/read-identity.d.ts +0 -31
- package/dist/entities/read-identity.js +0 -264
- package/dist/entities/recall-bridge.d.ts +0 -5
- package/dist/entities/recall-bridge.js +0 -171
- package/dist/entities/resolution-engine.d.ts +0 -8
- package/dist/entities/resolution-engine.js +0 -3
- package/dist/entities/rollback-preview.d.ts +0 -35
- package/dist/entities/rollback-preview.js +0 -3
- package/dist/entities/source-locator.d.ts +0 -3
- package/dist/entities/source-locator.js +0 -32
- package/dist/entities/store.d.ts +0 -69
- package/dist/entities/store.js +0 -544
- package/dist/entities/types.d.ts +0 -166
- package/dist/entities/types.js +0 -30
- package/dist/memory/extraction-prompt.d.ts +0 -4
- package/dist/memory/extraction-prompt.js +0 -89
- package/dist/memory/scope-backfill.d.ts +0 -14
- package/dist/memory/scope-backfill.js +0 -3
- package/dist/memory/scope-store.d.ts +0 -4
- package/dist/memory/scope-store.js +0 -9
- package/dist/memory-store.d.ts +0 -87
- package/dist/memory-store.js +0 -78
- package/dist/model-runs/store.d.ts +0 -13
- package/dist/model-runs/tool-trace-store.d.ts +0 -8
- package/dist/notification-manager.d.ts +0 -7
- package/dist/notification-manager.js +0 -12
- package/dist/outcome-tracker.d.ts +0 -151
- package/dist/outcome-tracker.js +0 -271
- package/dist/query-intent.d.ts +0 -23
- package/dist/query-intent.js +0 -114
- package/dist/runtime/trusted-provenance.d.ts +0 -3
- package/dist/runtime/trusted-provenance.js +0 -6
- package/dist/search/question-type.d.ts +0 -5
- package/dist/search/question-type.js +0 -41
- package/dist/test-utils.d.ts +0 -80
- package/dist/test-utils.js +0 -218
- package/dist/tier-validator.d.ts +0 -43
- package/dist/tier-validator.js +0 -159
- package/dist/time-formatter.d.ts +0 -25
- package/dist/time-formatter.js +0 -93
- /package/dist/{search → knowledge}/feedback-store.d.ts +0 -0
- /package/dist/{search → knowledge}/feedback-store.js +0 -0
- /package/dist/{search → knowledge}/ranker-features.d.ts +0 -0
- /package/dist/{search → knowledge}/ranker-rescore.d.ts +0 -0
- /package/dist/{search → knowledge}/ranker-rescore.js +0 -0
- /package/dist/{search → knowledge}/ranker-trainer.d.ts +0 -0
- /package/dist/{search → knowledge}/ranker-trainer.js +0 -0
- /package/dist/{search → knowledge}/search-quality.js +0 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude CLI Subprocess Wrapper - ToS-Compliant Alternative to Pi Agent
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS EXISTS:
|
|
5
|
+
* - Current Pi Agent uses OAuth token directly via API (ToS violation, ban risk)
|
|
6
|
+
* - Claude CLI is official Anthropic tool (ToS compliant)
|
|
7
|
+
* - Keeps $200/month subscription benefits vs $1000+/month API costs
|
|
8
|
+
*
|
|
9
|
+
* ARCHITECTURE:
|
|
10
|
+
* - Spawns `claude` CLI as subprocess
|
|
11
|
+
* - Communicates via stdin (prompts) / stdout (JSON responses)
|
|
12
|
+
* - Uses --output-format json for structured data
|
|
13
|
+
* - Session continuity via --session-id flag
|
|
14
|
+
*
|
|
15
|
+
* TRADEOFFS:
|
|
16
|
+
* + ✅ ToS compliant (official Claude tool)
|
|
17
|
+
* + ✅ Keeps subscription pricing
|
|
18
|
+
* + ✅ Real usage tracking (cost, tokens)
|
|
19
|
+
* - ⚠️ More complex than direct API
|
|
20
|
+
* - ⚠️ Requires claude CLI installed
|
|
21
|
+
* - ⚠️ Tool integration via MCP (future work)
|
|
22
|
+
*/
|
|
23
|
+
import type { PromptCallbacks, PromptResult } from './types.js';
|
|
24
|
+
export interface ClaudeCLIWrapperOptions {
|
|
25
|
+
/** The isolated workspace this CLI runs in; the product states where. */
|
|
26
|
+
/**
|
|
27
|
+
* Where this run keeps its files. Required: a driver does not know a product's
|
|
28
|
+
* directory name, and the default it used to compute spelled one out.
|
|
29
|
+
*/
|
|
30
|
+
workspaceDir: string;
|
|
31
|
+
model?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Effort level for Claude 4.6 adaptive thinking
|
|
34
|
+
* Applies to claude-opus-4-6 and claude-sonnet-4-6
|
|
35
|
+
* 'max' is only available on Opus 4.6
|
|
36
|
+
*/
|
|
37
|
+
effort?: 'low' | 'medium' | 'high' | 'max';
|
|
38
|
+
sessionId?: string;
|
|
39
|
+
systemPrompt?: string;
|
|
40
|
+
mcpConfigPath?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Skip permission prompts for tool execution
|
|
43
|
+
*
|
|
44
|
+
* @warning SECURITY RISK: Bypasses all permission checks.
|
|
45
|
+
* Only enable in trusted environments where agent actions are pre-approved.
|
|
46
|
+
*/
|
|
47
|
+
dangerouslySkipPermissions?: boolean;
|
|
48
|
+
env?: Record<string, string>;
|
|
49
|
+
/** Complete inherited environment supplied by the consumer; env is applied afterward. */
|
|
50
|
+
processEnv?: NodeJS.ProcessEnv;
|
|
51
|
+
/** Noninteractive consumers use dontAsk with explicit permission rules. */
|
|
52
|
+
permissionMode?: 'default' | 'acceptEdits' | 'dontAsk' | 'plan';
|
|
53
|
+
/** If true, use GatewayToolExecutor instead of MCP (default: false) */
|
|
54
|
+
useGatewayTools?: boolean;
|
|
55
|
+
/** Request timeout in ms (default: 120000). Increase for complex/long tasks. */
|
|
56
|
+
requestTimeout?: number;
|
|
57
|
+
/** Override built-in tool set (--tools CLI flag). Use "" to disable all tools. */
|
|
58
|
+
tools?: string;
|
|
59
|
+
/** Override plugin directory (--plugin-dir CLI flag). Use empty dir to disable plugins. */
|
|
60
|
+
pluginDir?: string;
|
|
61
|
+
/** Structurally disallowed tools (--disallowedTools CLI flag) */
|
|
62
|
+
disallowedTools?: string[];
|
|
63
|
+
/** Structurally allowed tools (--allowedTools CLI flag) */
|
|
64
|
+
allowedTools?: string[];
|
|
65
|
+
}
|
|
66
|
+
export type { PromptCallbacks, PromptResult, ToolUseBlock } from './types.js';
|
|
67
|
+
/**
|
|
68
|
+
* ClaudeCLIWrapper - Wraps Claude CLI for programmatic use
|
|
69
|
+
*
|
|
70
|
+
* Usage:
|
|
71
|
+
* const wrapper = new ClaudeCLIWrapper({ workspaceDir: '/tmp/mama-test-workspace', sessionId: 'my-session' });
|
|
72
|
+
* const result = await wrapper.prompt('Hello, Claude!', {
|
|
73
|
+
* onDelta: (text) => console.log('Delta:', text)
|
|
74
|
+
* });
|
|
75
|
+
*
|
|
76
|
+
* Key Features:
|
|
77
|
+
* - Session continuity (multi-turn conversations)
|
|
78
|
+
* - Real-time streaming (--output-format json streams)
|
|
79
|
+
* - Usage tracking (tokens, cost)
|
|
80
|
+
* - ToS compliant (official CLI)
|
|
81
|
+
*
|
|
82
|
+
* IMPORTANT:
|
|
83
|
+
* - Requires `claude` CLI in PATH
|
|
84
|
+
* - Uses subscription credentials from ~/.claude/.credentials.json
|
|
85
|
+
* - Tools not yet supported (future: via MCP)
|
|
86
|
+
*/
|
|
87
|
+
export declare class ClaudeCLIWrapper {
|
|
88
|
+
private sessionId;
|
|
89
|
+
private options;
|
|
90
|
+
private turnCount;
|
|
91
|
+
constructor(options: ClaudeCLIWrapperOptions);
|
|
92
|
+
/**
|
|
93
|
+
* Send a prompt to Claude CLI
|
|
94
|
+
*
|
|
95
|
+
* Workflow:
|
|
96
|
+
* 1. Spawn `claude -p "<prompt>" --output-format json`
|
|
97
|
+
* 2. Parse JSON output (type: result | error | delta)
|
|
98
|
+
* 3. Aggregate deltas for streaming
|
|
99
|
+
* 4. Return final result with usage stats
|
|
100
|
+
*
|
|
101
|
+
* @param content - Prompt text (images not yet supported)
|
|
102
|
+
* @param callbacks - Streaming callbacks
|
|
103
|
+
* @param options - Optional per-request overrides (model, etc.)
|
|
104
|
+
* @returns PromptResult with response and usage
|
|
105
|
+
*/
|
|
106
|
+
prompt(content: string, callbacks?: PromptCallbacks, options?: {
|
|
107
|
+
model?: string;
|
|
108
|
+
resumeSession?: boolean;
|
|
109
|
+
}): Promise<PromptResult>;
|
|
110
|
+
/**
|
|
111
|
+
* Get current session ID
|
|
112
|
+
*/
|
|
113
|
+
getSessionId(): string;
|
|
114
|
+
/**
|
|
115
|
+
* Create a new session (resets conversation history)
|
|
116
|
+
*/
|
|
117
|
+
resetSession(): void;
|
|
118
|
+
/**
|
|
119
|
+
* Set session ID (for channel-specific conversations)
|
|
120
|
+
*/
|
|
121
|
+
setSessionId(sessionId: string): void;
|
|
122
|
+
/**
|
|
123
|
+
* Set system prompt (updates options for next prompt)
|
|
124
|
+
*/
|
|
125
|
+
setSystemPrompt(prompt: string): void;
|
|
126
|
+
/**
|
|
127
|
+
* Get current options (for debugging)
|
|
128
|
+
*/
|
|
129
|
+
getOptions(): ClaudeCLIWrapperOptions;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Usage Example:
|
|
133
|
+
*
|
|
134
|
+
* const wrapper = new ClaudeCLIWrapper({ workspaceDir: '/tmp/mama-test-workspace', sessionId: 'discord-channel-123' });
|
|
135
|
+
*
|
|
136
|
+
* // First message
|
|
137
|
+
* const result1 = await wrapper.prompt('Hello, what is 2+2?', {
|
|
138
|
+
* onDelta: (text) => console.log('Streaming:', text)
|
|
139
|
+
* });
|
|
140
|
+
*
|
|
141
|
+
* console.log(result1.response); // "4"
|
|
142
|
+
* console.log(result1.usage.input_tokens); // 3
|
|
143
|
+
* console.log(result1.cost_usd); // 0.045
|
|
144
|
+
*
|
|
145
|
+
* // Follow-up (same session)
|
|
146
|
+
* const result2 = await wrapper.prompt('What about 3+3?');
|
|
147
|
+
* console.log(result2.response); // "6"
|
|
148
|
+
*
|
|
149
|
+
* // Cost Tracking Example:
|
|
150
|
+
* let totalCost = 0;
|
|
151
|
+
* const result = await wrapper.prompt('...');
|
|
152
|
+
* totalCost += result.cost_usd || 0;
|
|
153
|
+
* console.log(`Total spent: $${totalCost.toFixed(4)}`);
|
|
154
|
+
*/
|
|
155
|
+
//# sourceMappingURL=claude-cli-wrapper.d.ts.map
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Claude CLI Subprocess Wrapper - ToS-Compliant Alternative to Pi Agent
|
|
4
|
+
*
|
|
5
|
+
* WHY THIS EXISTS:
|
|
6
|
+
* - Current Pi Agent uses OAuth token directly via API (ToS violation, ban risk)
|
|
7
|
+
* - Claude CLI is official Anthropic tool (ToS compliant)
|
|
8
|
+
* - Keeps $200/month subscription benefits vs $1000+/month API costs
|
|
9
|
+
*
|
|
10
|
+
* ARCHITECTURE:
|
|
11
|
+
* - Spawns `claude` CLI as subprocess
|
|
12
|
+
* - Communicates via stdin (prompts) / stdout (JSON responses)
|
|
13
|
+
* - Uses --output-format json for structured data
|
|
14
|
+
* - Session continuity via --session-id flag
|
|
15
|
+
*
|
|
16
|
+
* TRADEOFFS:
|
|
17
|
+
* + ✅ ToS compliant (official Claude tool)
|
|
18
|
+
* + ✅ Keeps subscription pricing
|
|
19
|
+
* + ✅ Real usage tracking (cost, tokens)
|
|
20
|
+
* - ⚠️ More complex than direct API
|
|
21
|
+
* - ⚠️ Requires claude CLI installed
|
|
22
|
+
* - ⚠️ Tool integration via MCP (future work)
|
|
23
|
+
*/
|
|
24
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
25
|
+
if (k2 === undefined) k2 = k;
|
|
26
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
27
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
28
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
29
|
+
}
|
|
30
|
+
Object.defineProperty(o, k2, desc);
|
|
31
|
+
}) : (function(o, m, k, k2) {
|
|
32
|
+
if (k2 === undefined) k2 = k;
|
|
33
|
+
o[k2] = m[k];
|
|
34
|
+
}));
|
|
35
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
36
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
37
|
+
}) : function(o, v) {
|
|
38
|
+
o["default"] = v;
|
|
39
|
+
});
|
|
40
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
41
|
+
var ownKeys = function(o) {
|
|
42
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
43
|
+
var ar = [];
|
|
44
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
45
|
+
return ar;
|
|
46
|
+
};
|
|
47
|
+
return ownKeys(o);
|
|
48
|
+
};
|
|
49
|
+
return function (mod) {
|
|
50
|
+
if (mod && mod.__esModule) return mod;
|
|
51
|
+
var result = {};
|
|
52
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
53
|
+
__setModuleDefault(result, mod);
|
|
54
|
+
return result;
|
|
55
|
+
};
|
|
56
|
+
})();
|
|
57
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
58
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
59
|
+
};
|
|
60
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
61
|
+
exports.ClaudeCLIWrapper = void 0;
|
|
62
|
+
const child_process_1 = require("child_process");
|
|
63
|
+
const crypto_1 = require("crypto");
|
|
64
|
+
const fs_1 = require("fs");
|
|
65
|
+
const path_1 = __importDefault(require("path"));
|
|
66
|
+
const debugLogger = __importStar(require("@jungjaehoon/mama-core/debug-logger"));
|
|
67
|
+
const cli_secret_redaction_js_1 = require("./cli-secret-redaction.js");
|
|
68
|
+
const cli_arg_redaction_js_1 = require("./cli-arg-redaction.js");
|
|
69
|
+
const { DebugLogger } = debugLogger;
|
|
70
|
+
const logger = new DebugLogger('ClaudeCLI');
|
|
71
|
+
function supportsThinkingEffortModel(model) {
|
|
72
|
+
if (!model) {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
// Adaptive thinking effort: Claude 4.6 and every Claude 5 family model accept --effort.
|
|
76
|
+
return /^claude-(opus|sonnet|haiku|fable)-(4-6|5)(\b|-)/.test(model);
|
|
77
|
+
}
|
|
78
|
+
function normalizeThinkingEffort(model, effort) {
|
|
79
|
+
if (effort === 'max' && !(model && /^claude-(opus-4-6|opus-5|fable-5)(\b|-)/.test(model))) {
|
|
80
|
+
return 'high';
|
|
81
|
+
}
|
|
82
|
+
return effort;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* ClaudeCLIWrapper - Wraps Claude CLI for programmatic use
|
|
86
|
+
*
|
|
87
|
+
* Usage:
|
|
88
|
+
* const wrapper = new ClaudeCLIWrapper({ workspaceDir: '/tmp/mama-test-workspace', sessionId: 'my-session' });
|
|
89
|
+
* const result = await wrapper.prompt('Hello, Claude!', {
|
|
90
|
+
* onDelta: (text) => console.log('Delta:', text)
|
|
91
|
+
* });
|
|
92
|
+
*
|
|
93
|
+
* Key Features:
|
|
94
|
+
* - Session continuity (multi-turn conversations)
|
|
95
|
+
* - Real-time streaming (--output-format json streams)
|
|
96
|
+
* - Usage tracking (tokens, cost)
|
|
97
|
+
* - ToS compliant (official CLI)
|
|
98
|
+
*
|
|
99
|
+
* IMPORTANT:
|
|
100
|
+
* - Requires `claude` CLI in PATH
|
|
101
|
+
* - Uses subscription credentials from ~/.claude/.credentials.json
|
|
102
|
+
* - Tools not yet supported (future: via MCP)
|
|
103
|
+
*/
|
|
104
|
+
class ClaudeCLIWrapper {
|
|
105
|
+
sessionId;
|
|
106
|
+
options;
|
|
107
|
+
turnCount = 0;
|
|
108
|
+
constructor(options) {
|
|
109
|
+
this.options = options;
|
|
110
|
+
this.sessionId = options.sessionId || (0, crypto_1.randomUUID)();
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Send a prompt to Claude CLI
|
|
114
|
+
*
|
|
115
|
+
* Workflow:
|
|
116
|
+
* 1. Spawn `claude -p "<prompt>" --output-format json`
|
|
117
|
+
* 2. Parse JSON output (type: result | error | delta)
|
|
118
|
+
* 3. Aggregate deltas for streaming
|
|
119
|
+
* 4. Return final result with usage stats
|
|
120
|
+
*
|
|
121
|
+
* @param content - Prompt text (images not yet supported)
|
|
122
|
+
* @param callbacks - Streaming callbacks
|
|
123
|
+
* @param options - Optional per-request overrides (model, etc.)
|
|
124
|
+
* @returns PromptResult with response and usage
|
|
125
|
+
*/
|
|
126
|
+
async prompt(content, callbacks, options) {
|
|
127
|
+
return new Promise((resolve, reject) => {
|
|
128
|
+
// Use stdin for large content to avoid E2BIG error (ARG_MAX exceeded)
|
|
129
|
+
const useStdin = content.length > 50000; // 50KB threshold
|
|
130
|
+
const args = useStdin
|
|
131
|
+
? ['--output-format', 'json']
|
|
132
|
+
: ['-p', content, '--output-format', 'json'];
|
|
133
|
+
if (useStdin) {
|
|
134
|
+
console.log(`[ClaudeCLI] Using stdin mode (content: ${content.length} chars)`);
|
|
135
|
+
}
|
|
136
|
+
// Session persistence: keeps context across turns, avoids re-injecting system prompt
|
|
137
|
+
args.push('--session-id', this.sessionId);
|
|
138
|
+
// ⚠️ BLOCK GLOBAL SETTINGS — exclude 'user' to prevent loading ~/.claude/settings.json
|
|
139
|
+
// Prevents global plugins from enabledPlugins being injected every turn
|
|
140
|
+
args.push('--setting-sources', 'project,local');
|
|
141
|
+
console.log(`[ClaudeCLI] Session: ${this.sessionId}`);
|
|
142
|
+
// Add model flag - per-request override takes precedence
|
|
143
|
+
const model = options?.model || this.options.model;
|
|
144
|
+
if (model) {
|
|
145
|
+
args.push('--model', model);
|
|
146
|
+
}
|
|
147
|
+
// Add effort level for Claude 4.6 adaptive thinking.
|
|
148
|
+
if (this.options.effort && supportsThinkingEffortModel(model)) {
|
|
149
|
+
const effort = normalizeThinkingEffort(model, this.options.effort);
|
|
150
|
+
args.push('--effort', effort);
|
|
151
|
+
logger.debug('Effort level:', effort);
|
|
152
|
+
}
|
|
153
|
+
// System prompt: first turn only (session persistence keeps it across turns)
|
|
154
|
+
if (this.options.systemPrompt && this.turnCount === 0) {
|
|
155
|
+
args.push('--system-prompt', this.options.systemPrompt);
|
|
156
|
+
console.log(`[ClaudeCLI] System prompt injected (${this.options.systemPrompt.length} chars, first turn)`);
|
|
157
|
+
}
|
|
158
|
+
this.turnCount++;
|
|
159
|
+
// Hybrid mode: MCP + Gateway can both be enabled
|
|
160
|
+
if (this.options.mcpConfigPath) {
|
|
161
|
+
args.push('--mcp-config', this.options.mcpConfigPath);
|
|
162
|
+
args.push('--strict-mcp-config');
|
|
163
|
+
logger.debug('MCP enabled:', this.options.mcpConfigPath);
|
|
164
|
+
}
|
|
165
|
+
if (this.options.useGatewayTools) {
|
|
166
|
+
logger.debug('Gateway Tools mode enabled');
|
|
167
|
+
}
|
|
168
|
+
if (this.options.permissionMode) {
|
|
169
|
+
args.push('--permission-mode', this.options.permissionMode);
|
|
170
|
+
}
|
|
171
|
+
if (this.options.dangerouslySkipPermissions) {
|
|
172
|
+
args.push('--dangerously-skip-permissions');
|
|
173
|
+
}
|
|
174
|
+
if (this.options.allowedTools?.length) {
|
|
175
|
+
args.push('--allowedTools', ...this.options.allowedTools);
|
|
176
|
+
}
|
|
177
|
+
if (this.options.disallowedTools?.length) {
|
|
178
|
+
args.push('--disallowedTools', ...this.options.disallowedTools);
|
|
179
|
+
}
|
|
180
|
+
// ============================================================
|
|
181
|
+
// ⚠️ HOST AGENT ISOLATION — DO NOT MODIFY ⚠️
|
|
182
|
+
// ============================================================
|
|
183
|
+
// Sets cwd to the host's isolated workspace and creates a git boundary to
|
|
184
|
+
// Claude Code from traversing up to ~/CLAUDE.md and other parent configs.
|
|
185
|
+
// File access is controlled separately via --add-dir and --dangerously-skip-permissions.
|
|
186
|
+
// Removing this causes global settings to be re-injected every turn, wasting tokens.
|
|
187
|
+
// ============================================================
|
|
188
|
+
const mamaWorkspace = this.options.workspaceDir;
|
|
189
|
+
if (!(0, fs_1.existsSync)(mamaWorkspace)) {
|
|
190
|
+
(0, fs_1.mkdirSync)(mamaWorkspace, { recursive: true });
|
|
191
|
+
}
|
|
192
|
+
const gitDir = path_1.default.join(mamaWorkspace, '.git');
|
|
193
|
+
if (!(0, fs_1.existsSync)(gitDir)) {
|
|
194
|
+
(0, fs_1.mkdirSync)(gitDir, { recursive: true });
|
|
195
|
+
}
|
|
196
|
+
const headFile = path_1.default.join(gitDir, 'HEAD');
|
|
197
|
+
if (!(0, fs_1.existsSync)(headFile)) {
|
|
198
|
+
(0, fs_1.writeFileSync)(headFile, 'ref: refs/heads/main\n');
|
|
199
|
+
}
|
|
200
|
+
args.push('--add-dir', mamaWorkspace);
|
|
201
|
+
logger.debug(`Spawning: claude ${formatClaudeArgsForLog(args).join(' ')}`);
|
|
202
|
+
logger.debug(`Args count: ${args.length}`);
|
|
203
|
+
let stderr = '';
|
|
204
|
+
const stderrRedactor = new cli_secret_redaction_js_1.SecretRedactingStream((0, cli_secret_redaction_js_1.claudeConfiguredSecrets)(this.options.mcpConfigPath, {
|
|
205
|
+
...(this.options.processEnv ?? process.env),
|
|
206
|
+
...this.options.env,
|
|
207
|
+
}), (safe) => {
|
|
208
|
+
stderr = `${stderr}${safe}`.slice(-16_000);
|
|
209
|
+
if (safe.trim())
|
|
210
|
+
console.error(`[ClaudeCLI:stderr] ${safe.trim()}`);
|
|
211
|
+
});
|
|
212
|
+
const claude = (0, child_process_1.spawn)('claude', args, {
|
|
213
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
214
|
+
// ⚠️ NEVER spawn in the user's home directory — it breaks agent isolation.
|
|
215
|
+
cwd: mamaWorkspace,
|
|
216
|
+
env: { ...(this.options.processEnv ?? process.env), ...this.options.env },
|
|
217
|
+
});
|
|
218
|
+
// Handle stdin: write content if using stdin mode, otherwise close immediately
|
|
219
|
+
if (useStdin) {
|
|
220
|
+
// Write content to stdin with backpressure handling
|
|
221
|
+
// For large content (150KB+), synchronous write can block due to buffer pressure
|
|
222
|
+
// Solution: check write() return value and wait for 'drain' if needed
|
|
223
|
+
const writeContent = () => {
|
|
224
|
+
const canContinue = claude.stdin.write(content);
|
|
225
|
+
if (canContinue) {
|
|
226
|
+
// Buffer had space, content written, close stdin
|
|
227
|
+
claude.stdin.end();
|
|
228
|
+
console.log(`[ClaudeCLI] Content written to stdin (immediate)`);
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
// Buffer was full, wait for drain before closing
|
|
232
|
+
console.log(`[ClaudeCLI] Stdin buffer full, waiting for drain...`);
|
|
233
|
+
claude.stdin.once('drain', () => {
|
|
234
|
+
claude.stdin.end();
|
|
235
|
+
console.log(`[ClaudeCLI] Content written to stdin (after drain)`);
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
// Handle stdin errors to prevent unhandled exceptions
|
|
240
|
+
claude.stdin.on('error', (err) => {
|
|
241
|
+
console.error(`[ClaudeCLI] stdin error:`, err.message);
|
|
242
|
+
// Don't reject here - let the close handler deal with it
|
|
243
|
+
});
|
|
244
|
+
writeContent();
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
// Close stdin immediately - we use -p flag, not stdin input
|
|
248
|
+
// Without this, Claude CLI hangs waiting for stdin input
|
|
249
|
+
claude.stdin.end();
|
|
250
|
+
}
|
|
251
|
+
let stdout = '';
|
|
252
|
+
let lastDelta = '';
|
|
253
|
+
const toolUseBlocks = [];
|
|
254
|
+
claude.stderr.on('data', (chunk) => stderrRedactor.write(chunk));
|
|
255
|
+
claude.stdout.on('data', (chunk) => {
|
|
256
|
+
stdout += chunk.toString();
|
|
257
|
+
const lines = stdout.split('\n');
|
|
258
|
+
for (const line of lines) {
|
|
259
|
+
if (!line.trim())
|
|
260
|
+
continue;
|
|
261
|
+
try {
|
|
262
|
+
const event = JSON.parse(line);
|
|
263
|
+
if (event.type === 'delta' && event.delta) {
|
|
264
|
+
lastDelta += event.delta;
|
|
265
|
+
callbacks?.onDelta?.(lastDelta);
|
|
266
|
+
}
|
|
267
|
+
else if (event.type === 'tool_use') {
|
|
268
|
+
// Collect tool_use blocks for GatewayToolExecutor
|
|
269
|
+
toolUseBlocks.push({
|
|
270
|
+
type: 'tool_use',
|
|
271
|
+
id: event.id || `tool_${(0, crypto_1.randomUUID)()}`,
|
|
272
|
+
name: event.name,
|
|
273
|
+
input: event.input || {},
|
|
274
|
+
});
|
|
275
|
+
callbacks?.onToolUse?.(event.name, event.input);
|
|
276
|
+
console.log(`[ClaudeCLI] Tool use detected: ${event.name}`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
// Not JSON yet, accumulate more
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
claude.on('close', (code) => {
|
|
285
|
+
stderrRedactor.end();
|
|
286
|
+
if (code !== 0) {
|
|
287
|
+
const error = new Error(`Claude CLI exited with code ${code}: ${stderr}`);
|
|
288
|
+
callbacks?.onError?.(error);
|
|
289
|
+
reject(error);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
try {
|
|
293
|
+
// Parse final JSON output
|
|
294
|
+
const result = JSON.parse(stdout.trim());
|
|
295
|
+
if (result.type === 'result' && result.subtype === 'success') {
|
|
296
|
+
const promptResult = {
|
|
297
|
+
response: result.result || '',
|
|
298
|
+
session_id: result.session_id || this.sessionId,
|
|
299
|
+
cost_usd: result.total_cost_usd,
|
|
300
|
+
usage: {
|
|
301
|
+
input_tokens: result.usage?.input_tokens || 0,
|
|
302
|
+
output_tokens: result.usage?.output_tokens || 0,
|
|
303
|
+
cache_creation_input_tokens: result.usage?.cache_creation_input_tokens,
|
|
304
|
+
cache_read_input_tokens: result.usage?.cache_read_input_tokens,
|
|
305
|
+
},
|
|
306
|
+
toolUseBlocks: toolUseBlocks.length > 0 ? toolUseBlocks : undefined,
|
|
307
|
+
hasToolUse: toolUseBlocks.length > 0,
|
|
308
|
+
};
|
|
309
|
+
if (toolUseBlocks.length > 0) {
|
|
310
|
+
console.log(`[ClaudeCLI] Returning ${toolUseBlocks.length} tool_use blocks`);
|
|
311
|
+
}
|
|
312
|
+
callbacks?.onFinal?.({ content: promptResult.response, toolUseBlocks });
|
|
313
|
+
resolve(promptResult);
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
throw new Error(`Unexpected result type: ${result.type}`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
catch (parseError) {
|
|
320
|
+
const error = new Error(`Failed to parse Claude CLI output: ${parseError}`);
|
|
321
|
+
callbacks?.onError?.(error);
|
|
322
|
+
reject(error);
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
claude.on('error', (error) => {
|
|
326
|
+
callbacks?.onError?.(error);
|
|
327
|
+
reject(error);
|
|
328
|
+
});
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Get current session ID
|
|
333
|
+
*/
|
|
334
|
+
getSessionId() {
|
|
335
|
+
return this.sessionId;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Create a new session (resets conversation history)
|
|
339
|
+
*/
|
|
340
|
+
resetSession() {
|
|
341
|
+
this.sessionId = (0, crypto_1.randomUUID)();
|
|
342
|
+
this.turnCount = 0; // Reset so system prompt is injected on next turn
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Set session ID (for channel-specific conversations)
|
|
346
|
+
*/
|
|
347
|
+
setSessionId(sessionId) {
|
|
348
|
+
this.sessionId = sessionId;
|
|
349
|
+
this.turnCount = 0; // Reset so system prompt is injected on next turn
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Set system prompt (updates options for next prompt)
|
|
353
|
+
*/
|
|
354
|
+
setSystemPrompt(prompt) {
|
|
355
|
+
this.options.systemPrompt = prompt;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Get current options (for debugging)
|
|
359
|
+
*/
|
|
360
|
+
getOptions() {
|
|
361
|
+
return { ...this.options };
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
exports.ClaudeCLIWrapper = ClaudeCLIWrapper;
|
|
365
|
+
function formatClaudeArgsForLog(args) {
|
|
366
|
+
return (0, cli_arg_redaction_js_1.formatCliArgsForLog)(args);
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Usage Example:
|
|
370
|
+
*
|
|
371
|
+
* const wrapper = new ClaudeCLIWrapper({ workspaceDir: '/tmp/mama-test-workspace', sessionId: 'discord-channel-123' });
|
|
372
|
+
*
|
|
373
|
+
* // First message
|
|
374
|
+
* const result1 = await wrapper.prompt('Hello, what is 2+2?', {
|
|
375
|
+
* onDelta: (text) => console.log('Streaming:', text)
|
|
376
|
+
* });
|
|
377
|
+
*
|
|
378
|
+
* console.log(result1.response); // "4"
|
|
379
|
+
* console.log(result1.usage.input_tokens); // 3
|
|
380
|
+
* console.log(result1.cost_usd); // 0.045
|
|
381
|
+
*
|
|
382
|
+
* // Follow-up (same session)
|
|
383
|
+
* const result2 = await wrapper.prompt('What about 3+3?');
|
|
384
|
+
* console.log(result2.response); // "6"
|
|
385
|
+
*
|
|
386
|
+
* // Cost Tracking Example:
|
|
387
|
+
* let totalCost = 0;
|
|
388
|
+
* const result = await wrapper.prompt('...');
|
|
389
|
+
* totalCost += result.cost_usd || 0;
|
|
390
|
+
* console.log(`Total spent: $${totalCost.toFixed(4)}`);
|
|
391
|
+
*/
|
|
392
|
+
//# sourceMappingURL=claude-cli-wrapper.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.formatCliArgsForLog = formatCliArgsForLog;
|
|
4
|
+
const SENSITIVE_PROMPT_ARGS = new Set(['--system-prompt', '--append-system-prompt']);
|
|
5
|
+
function formatCliArgsForLog(args) {
|
|
6
|
+
const redacted = [];
|
|
7
|
+
for (let i = 0; i < args.length; i++) {
|
|
8
|
+
const arg = args[i];
|
|
9
|
+
redacted.push(arg);
|
|
10
|
+
if (SENSITIVE_PROMPT_ARGS.has(arg) && i + 1 < args.length) {
|
|
11
|
+
const value = args[i + 1] ?? '';
|
|
12
|
+
redacted.push(`[redacted ${value.length} chars]`);
|
|
13
|
+
i++;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return redacted;
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=cli-arg-redaction.js.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { CodexAppServerLaunchConfig } from './codex-home.js';
|
|
2
|
+
export declare function configuredSecretValues(launch: CodexAppServerLaunchConfig): Set<string>;
|
|
3
|
+
/** Exact configured values, never an entropy/token-length guess. */
|
|
4
|
+
export declare function redactConfiguredSecrets(value: string, secrets: ReadonlySet<string>): string;
|
|
5
|
+
export declare function claudeConfiguredSecrets(configPath: string | undefined, env: NodeJS.ProcessEnv): Set<string>;
|
|
6
|
+
/** Keep the possible credential suffix until the next chunk (including UTF-8 boundaries). */
|
|
7
|
+
export declare class SecretRedactingStream {
|
|
8
|
+
private readonly secrets;
|
|
9
|
+
private readonly emit;
|
|
10
|
+
private pending;
|
|
11
|
+
private readonly decoder;
|
|
12
|
+
private readonly overlap;
|
|
13
|
+
constructor(secrets: ReadonlySet<string>, emit: (safe: string) => void);
|
|
14
|
+
write(chunk: Buffer): void;
|
|
15
|
+
end(): void;
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=cli-secret-redaction.d.ts.map
|