@devries-cameron20 / composio-1 / commits / 05ef2f414
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(cli): resolve the agent session a command runs in (#5314)

## Summary This PR: - adds `resolveAgentSession` (`ts/packages/cli/src/services/agent-session.ts`), which answers "which Claude Code or Codex chat is this command part of?", or "none" - derives the agent session ID as the UUID v5 of `<host>:<host session ID>` under a fixed namespace, so the host's own session ID stays inside the resolver - declares the five variables it reads as `HOST_CONFIG.AGENT_SESSION`; `HOST_CONFIG.AGENT_HOST` and `agent_host_env` are unchanged - exports `telemetryDisabled` next to `TELEMETRY_CONFIG` and makes the analytics dispatcher use it in place of its private copy - adds `uniku@^0.7.0` to the CLI for `uniku/uuid/v5` **This PR sends nothing new.** Nothing calls `resolveAgentSession` yet: no analytics property, request header or log line changes. It is the base of a four-PR stack. The next three attach the agent session to analytics events, to first-party requests, and add a compaction count; each of those sends data and waits for the disclosure decision before merge. ## Changes - **Resolution order.** A pair exported by a Composio plugin hook (`COMPOSIO_AGENT_HOST` + `COMPOSIO_AGENT_SESSION_ID`, host `claude` or `codex`) wins, because child processes inherit it and a nested host should report its parent's chat. Otherwise the host's own variable is used: `CLAUDE_CODE_SESSION_ID` for `claude`; `CODEX_SESSION_ID`, then `CODEX_THREAD_ID`, for `codex`. An export with an unknown host or only one of its two variables is ignored. Variables from both hosts with no export resolve none. - **The telemetry gate lives in the resolver.** `resolveAgentSession` returns none when `TELEMETRY_CONFIG.DISABLED` is true (`COMPOSIO_CLI_TELEMETRY_DISABLED`, `COMPOSIO_DISABLE_TELEMETRY`, `TELEMETRY_DISABLED`, `CI`, `NODE_ENV=test`), before it reads any session variable, so later consumers are suppressed by construction. It does not require a PostHog key, which source builds lack. - **`uniku@0.7.0` needs a temporary `minimumReleaseAgeExclude` entry.** It was published on 2026-11-11, inside the three-day `minimumReleaseAge`, and is the first release with `uuid/v5`. The exclusion is for that exact version. Checked by hand: published by GitHub Actions with npm provenance, no install scripts. Without the entry, `pnpm install --frozen-lockfile` fails with `ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`. It can be removed after 2026-11-14. - **Lockfile.** Updated with `pnpm --filter @composio/cli add`. Besides `uniku` and its `@noble/hashes` dependency, pnpm rewrote the peer suffix of the `@openai/agents` and `@openai/agents-core` 0.21.0 entries (it now lists `supports-color`); no version changed. - **README.** The two hook variables are listed in the table of coordination variables. ## Type of change - [ ] Bug fix - [x] New feature - [x] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? All run locally from the repository root on the pushed tree: | Check | Command | Result | | --- | --- | --- | | Focused tests | `pnpm --filter @composio/cli exec vitest run test/src/services/agent-session.test.ts test/src/config/host.test.ts test/src/analytics.dispatch.test.ts` | pass, 3 files, 74 tests | | Full CLI suite | `pnpm --filter @composio/cli test` | pass, 225 files, 2977 tests passed, 1 skipped | | CLI typecheck | `pnpm --filter @composio/cli run typecheck` | pass | | Workspace typecheck | `pnpm typecheck` | pass, 14 of 14 tasks | | Effect diagnostics | `pnpm --filter @composio/cli run lint:effect` | pass, 0 errors, 0 warnings | | Lint | `pnpm lint:packages` | pass, 0 errors (38 existing warnings, none in touched files) | | Lint boundaries | `pnpm --filter @composio/cli run validate:boundaries` | pass, 5 registered disables, none added | | Clean install | `pnpm install --frozen-lockfile` | pass | The new suite gives the resolver an isolated `ConfigProvider.fromEnvRecord`, so its results do not depend on the shell that runs it (an agent host's own session variables, `CI`, or `NODE_ENV=test`). The gate tests run each of the five switches against both a host variable and a hook export. Removing the gate makes all ten fail, and skipping it only for the hook export makes the five hook cases fail. The derivation tests use fixed vectors with made-up session IDs. ## Checklist - [ ] I have read the Code of Conduct and this PR adheres to it - [ ] I have read and understand every line of this diff, including any LLM-generated code - [x] Any third-party docs links or promotional content follow the [third-party links policy](https://github.com/ComposioHQ/composio/blob/next/CONTRIBUTING.md#third-party-links-in-docs) - [x] I ran linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests or explain why not applicable - [ ] I added a changeset if this change affects published packages No changeset: `@composio/cli` is ignored by Changesets. No `CHANGELOG.md` note either, because nothing user-visible changes until the next PR in the stack. ## Additional context - Both hook values and the host variables are read through `optionalString`, so surrounding whitespace is dropped and a blank value reads as unset. Nothing else is normalized: the same session ID in a different case derives a different ID. - `selectHostSession` and `deriveAgentSessionId` are exported as pure functions so they can be tested directly. Neither reads a telemetry switch; consumers go through `resolveAgentSession`.

Alberto Schiabel committed Nov 13, 2026 at 11:44 UTC 05ef2f414a6aed181f82d1fbe849758679066d4a
11 files changed +429 -20
pnpm-lock.yaml
+25 -8
@@ -987,7 +987,7 @@ importers:
987 version: 1.32.1(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.6.7)
988 '@openai/agents':
989 specifier: ^0.21.0
990 - version: 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
990 + version: 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
991 dotenv:
992 specifier: 'catalog:'
993 version: 18.0.8
@@ -1067,7 +1067,7 @@ importers:
1067 version: 1.6.2(@aws-sdk/credential-provider-node@3.972.87)(@langchain/core@1.2.19(@opentelemetry/api@1.10.0)(openai@7.39.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7))(ws@8.22.0))(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)
1068 '@openai/agents':
1069 specifier: ^0.21.0
1070 - version: 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
1070 + version: 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
1071 ai:
1072 specifier: 'catalog:'
1073 version: 7.0.146(zod@4.6.7)
@@ -1318,6 +1318,9 @@ importers:
1318 superjson:
1319 specifier: ^2.2.6
1320 version: 2.2.6
1321 + uniku:
1322 + specifier: ^0.7.0
1323 + version: 0.7.0
1324 zod:
1325 specifier: 'catalog:'
1326 version: 4.6.7
@@ -1723,7 +1726,7 @@ importers:
1726 version: link:../../core
1727 '@openai/agents':
1728 specifier: ^0.21.0
1726 - version: 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
1729 + version: 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
1730 tsdown:
1731 specifier: 'catalog:'
1732 version: 0.23.1(@arethetypeswrong/core@0.18.5)(publint@0.3.25)(tsx@4.23.15)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3))
@@ -3419,6 +3422,10 @@ packages:
3422 '@emnapi/core': ^1.7.1 || ^2.0.0-alpha.4
3423 '@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.4
3424
3425 + '@noble/hashes@2.4.0':
3426 + resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}
3427 + engines: {node: '>= 20.19.0'}
3428 +
3429 '@openai/agents-core@0.21.0':
3430 resolution: {integrity: sha512-P2jJhc85xrKpe9GUOHAVfPHqK52my49fD1CI0LnfYEvBUwZxJXQI6lgSwby9nWhvQECveM9OvBUglAXuArsHXw==}
3431 peerDependencies:
@@ -6558,6 +6565,10 @@ packages:
6565 unified@11.0.5:
6566 resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
6567
6568 + uniku@0.7.0:
6569 + resolution: {integrity: sha512-ev83Ax6TSFt8FcCzFYZz84UPorZ78iyZ8xoYxf09g/Z2Rs/ckuljrV7E76zPbwWUy3wcr28avA7Jue2vTyd2Cw==}
6570 + engines: {node: '>=20.19.0'}
6571 +
6572 unique-string@3.0.0:
6573 resolution: {integrity: sha512-VGXBUVwxKMBUznyffQweQABPRRW1vHZAbadFZud4pLFAqRGvv/96vafgjWFqzourzr8YonlQiPgH0YCJfawoGQ==}
6574 engines: {node: '>=12'}
@@ -8712,7 +8723,9 @@ snapshots:
8723 '@tybys/wasm-util': 0.10.4
8724 optional: true
8725
8715 - '@openai/agents-core@0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)':
8726 + '@noble/hashes@2.4.0': {}
8727 +
8728 + '@openai/agents-core@0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)':
8729 dependencies:
8730 '@standard-schema/spec': 1.1.0
8731 debug: 4.4.3(supports-color@10.2.2)
@@ -8730,7 +8743,7 @@ snapshots:
8743
8744 '@openai/agents-openai@0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)':
8745 dependencies:
8733 - '@openai/agents-core': 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
8746 + '@openai/agents-core': 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
8747 openai: 7.39.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
8748 zod: 4.6.7
8749 transitivePeerDependencies:
@@ -8743,7 +8756,7 @@ snapshots:
8756
8757 '@openai/agents-realtime@0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(zod@4.6.7)':
8758 dependencies:
8746 - '@openai/agents-core': 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
8759 + '@openai/agents-core': 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
8760 '@types/ws': 8.18.2
8761 ws: 8.22.0
8762 zod: 4.6.7
@@ -8756,9 +8769,9 @@ snapshots:
8769 - undici
8770 - utf-8-validate
8771
8759 - '@openai/agents@0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)':
8772 + '@openai/agents@0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)':
8773 dependencies:
8761 - '@openai/agents-core': 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
8774 + '@openai/agents-core': 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
8775 '@openai/agents-openai': 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
8776 '@openai/agents-realtime': 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(zod@4.6.7)
8777 openai: 7.39.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(undici@6.29.1)(ws@8.22.0)(zod@4.6.7)
@@ -11832,6 +11845,10 @@ snapshots:
11845 trough: 2.2.0
11846 vfile: 6.0.3
11847
11848 + uniku@0.7.0:
11849 + dependencies:
11850 + '@noble/hashes': 2.4.0
11851 +
11852 unique-string@3.0.0:
11853 dependencies:
11854 crypto-random-string: 4.0.0
pnpm-workspace.yaml
+6
@@ -100,6 +100,12 @@ minimumReleaseAgeExclude:
100 # scripts were checked by hand for this exact version only, so later releases
101 # still wait out the cooldown. Remove once 0.6.0 is older than the cutoff.
102 - '@typesafe-ai/sdk@0.6.0'
103 + # temporary: 0.7.0 (2026-11-11) is the first release with `uniku/uuid/v5`,
104 + # which the CLI uses to derive agent session IDs. Publisher (GitHub Actions),
105 + # npm provenance, and the absence of install scripts were checked by hand for
106 + # this exact version only, so later releases still wait out the cooldown.
107 + # Remove once 0.7.0 is older than the cutoff (after 2026-11-14).
108 + - uniku@0.7.0
109
110 peerDependencyRules:
111 allowedVersions:
ts/packages/cli/README.md
+3 -1
@@ -112,7 +112,7 @@ By default, both files are stored in `~/.composio`, but you can specify a custom
112
113 `composio login` records the backend it logged in to as `base_url` and `web_url` in `user_data.json`, and later commands keep using it. Setting `COMPOSIO_BASE_URL` or `COMPOSIO_ENVIRONMENT` overrides it; when that sends the stored API key to a different backend, the CLI prints a warning on stderr. A key from `COMPOSIO_USER_API_KEY` always uses the backend the environment selects. `composio logout` forgets the recorded backend.
114
115 -The CLI and its installer use these variables to coordinate nested commands. They aren't intended for manual configuration.
115 +The CLI, its installer, and the Composio agent plugins use these variables to coordinate nested commands. They aren't intended for manual configuration.
116
117 | Environment Variable | Description | Default |
118 | ------------------------------ | ---------------------------------------------------------------------------------------------------- | ------- |
@@ -120,6 +120,8 @@ The CLI and its installer use these variables to coordinate nested commands. The
120 | COMPOSIO_CLI_PARENT_RUN_ID | Reuses the parent run ID for nested command telemetry | None |
121 | COMPOSIO_RUN_OUTPUT_DIR | Shares one artifact directory across nested `composio run` commands | None |
122 | COMPOSIO_RUN_STAGED_FILES_FILE | Points to the temporary JSON file containing upload names and types for the child `composio execute` | None |
123 +| COMPOSIO_AGENT_HOST | Names the agent host (`claude` or `codex`) whose chat the command runs in; set by the plugin's hook | None |
124 +| COMPOSIO_AGENT_SESSION_ID | Carries that host's ID for the chat; read only together with `COMPOSIO_AGENT_HOST` | None |
125
126 Additionally, `composio upgrade` supports the following environment variables:
127
ts/packages/cli/package.json
+1
@@ -87,6 +87,7 @@
87 "semver": "^7.8.5",
88 "source-map-js": "^1.2.2",
89 "superjson": "^2.2.6",
90 + "uniku": "^0.7.0",
91 "zod": "catalog:"
92 },
93 "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
ts/packages/cli/src/analytics/dispatch.ts
+6 -8
@@ -15,7 +15,7 @@ import {
15 import { Base64Url } from 'effect/encoding';
16 import { HttpClient, HttpClientRequest } from 'effect/http';
17 import * as constants from 'src/constants';
18 -import { APP_CONFIG, TELEMETRY_CONFIG } from 'src/config';
18 +import { APP_CONFIG, TELEMETRY_CONFIG, telemetryDisabled } from 'src/config';
19 import { resolveBackend, withoutTrailingSlashes } from 'src/config/backend';
20 import { getDetachedWorkerSpawnArgs, spawnDetached } from 'src/services/detached-process';
21 import { atomicWriteFileString } from 'src/utils/atomic-write';
@@ -75,8 +75,6 @@ type ConsumerShortTermCacheState = Record<
75 }
76 >;
77
78 -const analyticsDisabled = Effect.orDie(TELEMETRY_CONFIG.DISABLED);
79 -
78 const getPostHogConfig = Effect.orDie(
79 Effect.all({
80 ingestUrl: TELEMETRY_CONFIG.POSTHOG_INGEST_URL,
@@ -85,7 +83,7 @@ const getPostHogConfig = Effect.orDie(
83 );
84
85 const postHogEnabled = Effect.gen(function* () {
88 - if (yield* analyticsDisabled) {
86 + if (yield* telemetryDisabled) {
87 return false;
88 }
89 const { projectKey } = yield* getPostHogConfig;
@@ -536,7 +534,7 @@ const buildPostHogBody = (envelope: AnalyticsEnvelope, projectKey: string) => ({
534
535 const captureToPostHog = (envelope: AnalyticsEnvelope) =>
536 Effect.gen(function* () {
539 - const disabled = yield* analyticsDisabled;
537 + const disabled = yield* telemetryDisabled;
538 const { ingestUrl, projectKey } = yield* getPostHogConfig;
539 if (disabled || projectKey.length === 0) {
540 yield* telemetryDebugLog('posthog_delivery_skipped', {
@@ -617,7 +615,7 @@ export const createCliCodactFailureBody = (
615 const captureToComposioCodactFailures = (failure: CliCodactFailure) =>
616 Effect.gen(function* () {
617 const endpoint = yield* getCliCodactFailuresEndpoint;
620 - const disabled = yield* analyticsDisabled;
618 + const disabled = yield* telemetryDisabled;
619 if (disabled) {
620 yield* telemetryDebugLog('codact_delivery_skipped', {
621 reason: 'disabled',
@@ -689,7 +687,7 @@ export const trackCliEventEffect = (event: TrackEvent) =>
687
688 if (!(yield* postHogEnabled)) {
689 yield* telemetryDebugLog('skip', {
692 - reason: (yield* analyticsDisabled) ? 'disabled' : 'missing_project_key',
690 + reason: (yield* telemetryDisabled) ? 'disabled' : 'missing_project_key',
691 eventName: event.name,
692 });
693 return;
@@ -861,7 +859,7 @@ export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
859 Effect.gen(function* () {
860 const endpoint = yield* getCliCodactFailuresEndpoint;
861 const userApiKey = yield* getUserApiKey;
864 - const disabled = yield* analyticsDisabled;
862 + const disabled = yield* telemetryDisabled;
863 if (disabled || !userApiKey) {
864 yield* telemetryDebugLog('codact_skip', {
865 reason: disabled ? 'disabled' : 'missing_user_api_key',
ts/packages/cli/src/config/host.ts
+12
@@ -48,6 +48,17 @@ export const HOST_CONFIG = {
48 codexHome: optionalString('CODEX_HOME'),
49 }),
50
51 + // The agent chat this process runs in. The Composio plugin hook exports the first two as a
52 + // pair; the other three are the hosts' own session variables, read when the hook exported
53 + // nothing. `CODEX_THREAD_ID` is the same variable `AGENT_HOST` reads as a host marker.
54 + AGENT_SESSION: Config.all({
55 + hookHost: optionalString('COMPOSIO_AGENT_HOST'),
56 + hookSessionId: optionalString('COMPOSIO_AGENT_SESSION_ID'),
57 + claudeCodeSessionId: optionalString('CLAUDE_CODE_SESSION_ID'),
58 + codexSessionId: optionalString('CODEX_SESSION_ID'),
59 + codexThreadId: optionalString('CODEX_THREAD_ID'),
60 + }),
61 +
62 // Which agent, if any, drives this process: any `CODEX*` / `CLAUDE*` variable counts
63 MASTER_SIGNALS: agentPrefixSignals.pipe(Config.map(({ codex, claude }) => ({ codex, claude }))),
64
@@ -62,4 +73,5 @@ export const HOST_CONFIG = {
73 };
74
75 export type AgentHostEnvironment = Config.Success<typeof HOST_CONFIG.AGENT_HOST>;
76 +export type AgentSessionEnvironment = Config.Success<typeof HOST_CONFIG.AGENT_SESSION>;
77 export type CallerAgentSignals = Config.Success<typeof HOST_CONFIG.CALLER_AGENT_SIGNALS>;
ts/packages/cli/src/config/index.ts
+7 -2
@@ -13,6 +13,11 @@
13 */
14 export { APP_CONFIG } from './app';
15 export { DEBUG_CONFIG } from './debug';
16 -export { TELEMETRY_CONFIG } from './telemetry';
17 -export { HOST_CONFIG, type AgentHostEnvironment, type CallerAgentSignals } from './host';
16 +export { TELEMETRY_CONFIG, telemetryDisabled } from './telemetry';
17 +export {
18 + HOST_CONFIG,
19 + type AgentHostEnvironment,
20 + type AgentSessionEnvironment,
21 + type CallerAgentSignals,
22 +} from './host';
23 export { GITHUB_CONFIG, GITHUB_REPAIR_CONFIG, type GitHubConfig } from './github';
ts/packages/cli/src/config/telemetry.ts
+4 -1
@@ -1,4 +1,4 @@
1 -import { Config } from 'effect';
1 +import { Config, Effect } from 'effect';
2 import * as constants from 'src/constants';
3 import { flag, optionalString, stringWithDefault } from './env';
4
@@ -28,3 +28,6 @@ export const TELEMETRY_CONFIG = {
28 constants.COMPOSIO_POSTHOG_PROJECT_API_KEY
29 ),
30 };
31 +
32 +/** Whether any opt-out spelling, a test run, or CI turns telemetry off. */
33 +export const telemetryDisabled: Effect.Effect<boolean> = Effect.orDie(TELEMETRY_CONFIG.DISABLED);
ts/packages/cli/src/services/agent-session.ts new
+96
@@ -0,0 +1,96 @@
1 +import { Effect, Option } from 'effect';
2 +import { uuidv5 } from 'uniku/uuid/v5';
3 +import { HOST_CONFIG, telemetryDisabled, type AgentSessionEnvironment } from 'src/config';
4 +import { AGENT_HOSTS, type AgentHost } from './agent-host';
5 +
6 +/** A chat as its agent host identifies it. The host's ID stays on this device. */
7 +export type HostSession = {
8 + readonly host: AgentHost;
9 + readonly hostSessionId: string;
10 +};
11 +
12 +/** The agent session a command is part of: the host, and the ID derived for its chat. */
13 +export type AgentSession = {
14 + readonly host: AgentHost;
15 + readonly id: string;
16 +};
17 +
18 +/** The pair a plugin hook exported, when it names a known host and carries a session ID. */
19 +const exportedSession = (env: AgentSessionEnvironment): Option.Option<HostSession> =>
20 + Option.all({
21 + host: Option.fromUndefinedOr(AGENT_HOSTS.find(host => host === env.hookHost)),
22 + hostSessionId: Option.fromUndefinedOr(env.hookSessionId),
23 + });
24 +
25 +/** Each host's own session ID. Codex versions without `CODEX_SESSION_ID` set only a thread ID. */
26 +const ownSessionIds = (env: AgentSessionEnvironment): Record<AgentHost, string | undefined> => ({
27 + claude: env.claudeCodeSessionId,
28 + codex: env.codexSessionId ?? env.codexThreadId,
29 +});
30 +
31 +/** The one host whose own variable is set. Two hosts cannot be ordered, so they give none. */
32 +const soleOwnSession = (env: AgentSessionEnvironment): Option.Option<HostSession> => {
33 + const ids = ownSessionIds(env);
34 + const [session, ...others] = AGENT_HOSTS.flatMap((host): ReadonlyArray<HostSession> => {
35 + const hostSessionId = ids[host];
36 + return hostSessionId === undefined ? [] : [{ host, hostSessionId }];
37 + });
38 + return session !== undefined && others.length === 0 ? Option.some(session) : Option.none();
39 +};
40 +
41 +/**
42 + * Picks the chat this process runs in from the agent session variables.
43 + *
44 + * The pair a plugin hook exported wins, because child processes inherit it: a host started
45 + * inside another host's chat still reports the parent chat. Without a usable export, the one
46 + * host whose own variable is set is used. Blank variables already read as `undefined` (see
47 + * `HOST_CONFIG`).
48 + *
49 + * This reads no telemetry switch. Callers go through `resolveAgentSession`.
50 + */
51 +export const selectHostSession = (env: AgentSessionEnvironment): Option.Option<HostSession> =>
52 + Option.orElse(exportedSession(env), () => soleOwnSession(env));
53 +
54 +/**
55 + * The namespace every agent session ID is derived under. A UUID v5 needs one, and this one is
56 + * itself the UUID v5 of the name below under the RFC 9562 URL namespace, so nothing here is
57 + * an arbitrary number. The name labels the scheme and does not have to resolve. `uuidv5.NIL`
58 + * or `uuidv5.MAX` would be accepted too, but they belong to no one: any other system hashing
59 + * the same `<host>:<id>` name under them would produce our IDs.
60 + *
61 + * Frozen. Another name changes every derived ID and splits each chat in two. Any system that
62 + * holds a host and its session ID derives the same ID from this value.
63 + */
64 +export const AGENT_SESSION_NAMESPACE = uuidv5(
65 + 'https://composio.dev/ns/agent-session/v1',
66 + uuidv5.URL
67 +);
68 +
69 +const deriveInAgentSessionNamespace = uuidv5.namespace(AGENT_SESSION_NAMESPACE);
70 +
71 +/**
72 + * The UUID v5 of `<host>:<host session ID>`. Surrounding whitespace was dropped when the
73 + * variables were read (see `HOST_CONFIG`); nothing else is changed, letter case included.
74 + */
75 +export const deriveAgentSessionId = ({ host, hostSessionId }: HostSession): string =>
76 + deriveInAgentSessionNamespace(`${host}:${hostSessionId}`);
77 +
78 +/**
79 + * The agent session this command is part of, or none outside a known agent host.
80 + *
81 + * Telemetry is checked here, before any session variable is read, so every consumer resolves
82 + * none while an opt-out, a test run, or CI disables it. The result never carries the host's
83 + * own session ID.
84 + */
85 +export const resolveAgentSession: Effect.Effect<Option.Option<AgentSession>> = Effect.gen(
86 + function* () {
87 + if (yield* telemetryDisabled) {
88 + return Option.none();
89 + }
90 + const hostSession = selectHostSession(yield* Effect.orDie(HOST_CONFIG.AGENT_SESSION));
91 + return Option.map(hostSession, session => ({
92 + host: session.host,
93 + id: deriveAgentSessionId(session),
94 + }));
95 + }
96 +);
ts/packages/cli/test/src/config/host.test.ts
+32
@@ -20,6 +20,10 @@ describe('HOST_CONFIG', () => {
20 CLAUDE_CONFIG_DIR: ' ',
21 COMPOSIO_CALLER_AGENT: 'Open-Claw',
22 VITEST: 'off',
23 + COMPOSIO_AGENT_HOST: 'claude',
24 + COMPOSIO_AGENT_SESSION_ID: 'hook_session_test',
25 + CLAUDE_CODE_SESSION_ID: 'claude_session_test',
26 + CODEX_SESSION_ID: 'codex_session_test',
27 });
28 deepStrictEqual(actual, {
29 SHELL: '/bin/zsh',
@@ -35,12 +39,40 @@ describe('HOST_CONFIG', () => {
39 claudeConfigDir: undefined,
40 codexHome: undefined,
41 },
42 + AGENT_SESSION: {
43 + hookHost: 'claude',
44 + hookSessionId: 'hook_session_test',
45 + claudeCodeSessionId: 'claude_session_test',
46 + codexSessionId: 'codex_session_test',
47 + codexThreadId: 'thread_test',
48 + },
49 MASTER_SIGNALS: { codex: true, claude: true },
50 CALLER_AGENT_SIGNALS: { explicit: 'Open-Claw', codex: true, claude: true, openclaw: false },
51 });
52 })
53 );
54
55 + it.effect('[Given] blank agent session variables [Then] each one reads as unset', () =>
56 + Effect.gen(function* () {
57 + deepStrictEqual(
58 + yield* read(HOST_CONFIG.AGENT_SESSION, {
59 + COMPOSIO_AGENT_HOST: '',
60 + COMPOSIO_AGENT_SESSION_ID: ' ',
61 + CLAUDE_CODE_SESSION_ID: '',
62 + CODEX_SESSION_ID: ' ',
63 + CODEX_THREAD_ID: '',
64 + }),
65 + {
66 + hookHost: undefined,
67 + hookSessionId: undefined,
68 + claudeCodeSessionId: undefined,
69 + codexSessionId: undefined,
70 + codexThreadId: undefined,
71 + }
72 + );
73 + })
74 + );
75 +
76 it.effect('[Then] CI redaction keys off the exact `CI=true` convention only', () =>
77 Effect.gen(function* () {
78 deepStrictEqual(yield* read(HOST_CONFIG.CI_REDACTION_ENABLED, { CI: '1' }), false);
ts/packages/cli/test/src/services/agent-session.test.ts new
+237
@@ -0,0 +1,237 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Array as Arr, ConfigProvider, Effect, Option, pipe } from 'effect';
3 +import { TELEMETRY_CONFIG, type AgentSessionEnvironment } from 'src/config';
4 +import {
5 + AGENT_SESSION_NAMESPACE,
6 + deriveAgentSessionId,
7 + resolveAgentSession,
8 + selectHostSession,
9 + type HostSession,
10 +} from 'src/services/agent-session';
11 +
12 +// Made-up host session IDs and the UUID v5 each one derives to.
13 +const CLAUDE_SESSION = '00000000-0000-4000-8000-000000000001';
14 +const CLAUDE_AGENT_SESSION_ID = 'df095fd9-410b-5ec9-b678-4ed04b5ab2dd';
15 +const CODEX_SESSION = '00000000-0000-7000-8000-000000000002';
16 +const CODEX_AGENT_SESSION_ID = '9d27e7e4-b2ed-522c-bed8-595444e853a7';
17 +
18 +describe('deriveAgentSessionId', () => {
19 + it('[Given] the namespace name [Then] it is the namespace other systems derive under', () => {
20 + expect(AGENT_SESSION_NAMESPACE).toBe('377a1a01-b6e5-5f6e-ae1c-a874a3316d89');
21 + });
22 +
23 + it.each([
24 + { host: 'claude', hostSessionId: CLAUDE_SESSION, expected: CLAUDE_AGENT_SESSION_ID },
25 + { host: 'codex', hostSessionId: CODEX_SESSION, expected: CODEX_AGENT_SESSION_ID },
26 + ] as const)(
27 + '[Given] host $host and session $hostSessionId [Then] the ID is $expected',
28 + ({ host, hostSessionId, expected }) => {
29 + expect(deriveAgentSessionId({ host, hostSessionId })).toBe(expected);
30 + }
31 + );
32 +
33 + it('[Given] the same session ID in upper case [Then] the ID differs', () => {
34 + const hostSessionId = 'abcdef00-0000-4000-8000-000000000001';
35 + expect(
36 + deriveAgentSessionId({ host: 'claude', hostSessionId: hostSessionId.toUpperCase() })
37 + ).not.toBe(deriveAgentSessionId({ host: 'claude', hostSessionId }));
38 + });
39 +});
40 +
41 +const NO_VARIABLES: AgentSessionEnvironment = {
42 + hookHost: undefined,
43 + hookSessionId: undefined,
44 + claudeCodeSessionId: undefined,
45 + codexSessionId: undefined,
46 + codexThreadId: undefined,
47 +};
48 +
49 +type SelectionCase = {
50 + readonly name: string;
51 + readonly variables: Partial<AgentSessionEnvironment>;
52 + readonly expected: HostSession | undefined;
53 +};
54 +
55 +const SELECTION_CASES: ReadonlyArray<SelectionCase> = [
56 + {
57 + name: 'a hook export for claude and a different CLAUDE_CODE_SESSION_ID: the export wins',
58 + variables: { hookHost: 'claude', hookSessionId: 'hook-chat', claudeCodeSessionId: 'own-chat' },
59 + expected: { host: 'claude', hostSessionId: 'hook-chat' },
60 + },
61 + {
62 + name: 'a hook export for codex and a different CLAUDE_CODE_SESSION_ID: the export wins',
63 + variables: { hookHost: 'codex', hookSessionId: 'hook-chat', claudeCodeSessionId: 'own-chat' },
64 + expected: { host: 'codex', hostSessionId: 'hook-chat' },
65 + },
66 + {
67 + name: 'a hook export for claude inside Codex: the parent chat is reported',
68 + variables: { hookHost: 'claude', hookSessionId: 'hook-chat', codexSessionId: 'codex-chat' },
69 + expected: { host: 'claude', hostSessionId: 'hook-chat' },
70 + },
71 + {
72 + name: 'a hook export for an unknown host: the export is ignored',
73 + variables: { hookHost: 'pi', hookSessionId: 'hook-chat', claudeCodeSessionId: 'own-chat' },
74 + expected: { host: 'claude', hostSessionId: 'own-chat' },
75 + },
76 + {
77 + name: 'a hook host without a hook session ID: treated as no export',
78 + variables: { hookHost: 'codex', claudeCodeSessionId: 'own-chat' },
79 + expected: { host: 'claude', hostSessionId: 'own-chat' },
80 + },
81 + {
82 + name: 'a hook session ID without a hook host: treated as no export',
83 + variables: { hookSessionId: 'hook-chat', codexSessionId: 'codex-chat' },
84 + expected: { host: 'codex', hostSessionId: 'codex-chat' },
85 + },
86 + {
87 + name: 'only CLAUDE_CODE_SESSION_ID: host claude',
88 + variables: { claudeCodeSessionId: 'own-chat' },
89 + expected: { host: 'claude', hostSessionId: 'own-chat' },
90 + },
91 + {
92 + name: 'only CODEX_SESSION_ID: host codex',
93 + variables: { codexSessionId: 'codex-chat' },
94 + expected: { host: 'codex', hostSessionId: 'codex-chat' },
95 + },
96 + {
97 + name: 'CODEX_SESSION_ID and a different CODEX_THREAD_ID: the session ID is used',
98 + variables: { codexSessionId: 'codex-chat', codexThreadId: 'codex-thread' },
99 + expected: { host: 'codex', hostSessionId: 'codex-chat' },
100 + },
101 + {
102 + name: 'only CODEX_THREAD_ID: host codex with the thread ID',
103 + variables: { codexThreadId: 'codex-thread' },
104 + expected: { host: 'codex', hostSessionId: 'codex-thread' },
105 + },
106 + {
107 + name: 'CLAUDE_CODE_SESSION_ID and CODEX_SESSION_ID with no export: none',
108 + variables: { claudeCodeSessionId: 'own-chat', codexSessionId: 'codex-chat' },
109 + expected: undefined,
110 + },
111 + {
112 + name: 'CLAUDE_CODE_SESSION_ID and CODEX_THREAD_ID with no export: none',
113 + variables: { claudeCodeSessionId: 'own-chat', codexThreadId: 'codex-thread' },
114 + expected: undefined,
115 + },
116 + { name: 'no variable: none', variables: {}, expected: undefined },
117 +];
118 +
119 +describe('selectHostSession', () => {
120 + it.each(SELECTION_CASES)('[Given] $name', ({ variables, expected }) => {
121 + expect(
122 + Option.getOrUndefined(selectHostSession({ ...NO_VARIABLES, ...variables }))
123 + ).toStrictEqual(expected);
124 + });
125 +});
126 +
127 +// Each record is the whole environment the resolver sees, so the shell that runs the suite
128 +// (its `NODE_ENV=test`, `CI`, and agent-host session variables) cannot change a result.
129 +const isolatedEnvironment = (env: Record<string, string>) => ConfigProvider.fromEnvRecord(env);
130 +
131 +const resolveWith = (env: Record<string, string>) =>
132 + resolveAgentSession.pipe(
133 + Effect.provideService(ConfigProvider.ConfigProvider, isolatedEnvironment(env)),
134 + Effect.map(Option.getOrUndefined)
135 + );
136 +
137 +const TELEMETRY_ON = { CI: 'false', NODE_ENV: 'production' };
138 +
139 +type SessionSource = {
140 + readonly source: string;
141 + readonly variables: Record<string, string>;
142 +};
143 +
144 +// Both ways a session resolves. Each resolves one in the tests below while telemetry is on.
145 +const SESSION_SOURCES: ReadonlyArray<SessionSource> = [
146 + { source: 'a host variable', variables: { CLAUDE_CODE_SESSION_ID: CLAUDE_SESSION } },
147 + {
148 + source: 'a hook export',
149 + variables: { COMPOSIO_AGENT_HOST: 'claude', COMPOSIO_AGENT_SESSION_ID: CLAUDE_SESSION },
150 + },
151 +];
152 +
153 +const TELEMETRY_DISABLED_CASES = pipe(
154 + [
155 + { name: 'COMPOSIO_CLI_TELEMETRY_DISABLED', value: '1' },
156 + { name: 'COMPOSIO_DISABLE_TELEMETRY', value: 'true' },
157 + { name: 'TELEMETRY_DISABLED', value: '1' },
158 + { name: 'CI', value: 'true' },
159 + { name: 'NODE_ENV', value: 'test' },
160 + ],
161 + Arr.flatMap(telemetrySwitch =>
162 + pipe(
163 + SESSION_SOURCES,
164 + Arr.map(sessionSource => ({ ...telemetrySwitch, ...sessionSource }))
165 + )
166 + )
167 +);
168 +
169 +describe('resolveAgentSession', () => {
170 + it.effect('[Given] CLAUDE_CODE_SESSION_ID [Then] it resolves claude and the derived ID', () =>
171 + Effect.gen(function* () {
172 + const actual = yield* resolveWith({
173 + ...TELEMETRY_ON,
174 + CLAUDE_CODE_SESSION_ID: CLAUDE_SESSION,
175 + });
176 + expect(actual).toStrictEqual({ host: 'claude', id: CLAUDE_AGENT_SESSION_ID });
177 + })
178 + );
179 +
180 + it.effect('[Given] CODEX_THREAD_ID alone [Then] it resolves codex and the derived ID', () =>
181 + Effect.gen(function* () {
182 + const actual = yield* resolveWith({ ...TELEMETRY_ON, CODEX_THREAD_ID: CODEX_SESSION });
183 + expect(actual).toStrictEqual({ host: 'codex', id: CODEX_AGENT_SESSION_ID });
184 + })
185 + );
186 +
187 + it.effect('[Given] a hook export inside another host [Then] it resolves the exported chat', () =>
188 + Effect.gen(function* () {
189 + const actual = yield* resolveWith({
190 + ...TELEMETRY_ON,
191 + COMPOSIO_AGENT_HOST: 'claude',
192 + COMPOSIO_AGENT_SESSION_ID: CLAUDE_SESSION,
193 + CODEX_SESSION_ID: CODEX_SESSION,
194 + });
195 + expect(actual).toStrictEqual({ host: 'claude', id: CLAUDE_AGENT_SESSION_ID });
196 + })
197 + );
198 +
199 + it.effect('[Given] variables from both hosts and no export [Then] it resolves none', () =>
200 + Effect.gen(function* () {
201 + const actual = yield* resolveWith({
202 + ...TELEMETRY_ON,
203 + CLAUDE_CODE_SESSION_ID: CLAUDE_SESSION,
204 + CODEX_SESSION_ID: CODEX_SESSION,
205 + });
206 + expect(actual).toBeUndefined();
207 + })
208 + );
209 +
210 + it.effect('[Given] no agent session variable [Then] it resolves none', () =>
211 + Effect.gen(function* () {
212 + expect(yield* resolveWith(TELEMETRY_ON)).toBeUndefined();
213 + })
214 + );
215 +
216 + it.effect.each(TELEMETRY_DISABLED_CASES)(
217 + '[Given] $source and telemetry disabled by $name=$value [Then] it resolves none',
218 + ({ name, value, variables }) =>
219 + Effect.gen(function* () {
220 + const actual = yield* resolveWith({ ...TELEMETRY_ON, ...variables, [name]: value });
221 + expect(actual).toBeUndefined();
222 + })
223 + );
224 +
225 + it.effect('[Given] telemetry enabled and no PostHog key [Then] it still resolves', () =>
226 + Effect.gen(function* () {
227 + const env = { ...TELEMETRY_ON, CLAUDE_CODE_SESSION_ID: CLAUDE_SESSION };
228 + expect(yield* TELEMETRY_CONFIG.POSTHOG_PROJECT_API_KEY.parse(isolatedEnvironment(env))).toBe(
229 + ''
230 + );
231 + expect(yield* resolveWith(env)).toStrictEqual({
232 + host: 'claude',
233 + id: CLAUDE_AGENT_SESSION_ID,
234 + });
235 + })
236 + );
237 +});