@orchestraai/agent-tools 0.8.2 → 0.10.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.
Files changed (40) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.codex-plugin/plugin.json +1 -1
  5. package/.cursor-plugin/plugin.json +1 -1
  6. package/.devin/adapter.json +1 -1
  7. package/.hermes/adapter.json +1 -1
  8. package/.opencode/adapter.json +1 -1
  9. package/README.md +20 -0
  10. package/dist/bin.js +13 -1
  11. package/dist/bin.js.map +1 -1
  12. package/dist/claude-accounting.d.ts +75 -0
  13. package/dist/claude-accounting.js +155 -0
  14. package/dist/claude-accounting.js.map +1 -0
  15. package/dist/claude-native.d.ts +47 -0
  16. package/dist/claude-native.js +210 -0
  17. package/dist/claude-native.js.map +1 -0
  18. package/dist/claude-reconciliation.d.ts +28 -0
  19. package/dist/claude-reconciliation.js +112 -0
  20. package/dist/claude-reconciliation.js.map +1 -0
  21. package/dist/commands/claude-session.d.ts +30 -0
  22. package/dist/commands/claude-session.js +136 -0
  23. package/dist/commands/claude-session.js.map +1 -0
  24. package/dist/commands/claude-setup.d.ts +12 -0
  25. package/dist/commands/claude-setup.js +97 -0
  26. package/dist/commands/claude-setup.js.map +1 -0
  27. package/dist/commands/claude.d.ts +28 -0
  28. package/dist/commands/claude.js +129 -0
  29. package/dist/commands/claude.js.map +1 -0
  30. package/dist/commands/onboarding.js +66 -2
  31. package/dist/commands/onboarding.js.map +1 -1
  32. package/dist/index.js +6 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/internal/reporting-contracts.d.ts +2 -2
  35. package/dist/onboarding/init.d.ts +1 -1
  36. package/dist/onboarding/init.js +3 -1
  37. package/dist/onboarding/init.js.map +1 -1
  38. package/docs/claude-gateway.md +126 -0
  39. package/docs/release-checklist.md +6 -1
  40. package/package.json +1 -1
@@ -2,7 +2,7 @@
2
2
  "name": "orchestra-skills",
3
3
  "metadata": {
4
4
  "description": "Orchestra skills for improving LLM apps with local-first evidence, evals, optimization, local models, and routing.",
5
- "version": "0.8.2"
5
+ "version": "0.10.0"
6
6
  },
7
7
  "plugins": [
8
8
  {
@@ -5,7 +5,7 @@
5
5
  },
6
6
  "metadata": {
7
7
  "description": "Claude Code skills for improving LLM apps with Orchestra — trace, evaluate, optimize, compare, deploy.",
8
- "version": "0.8.2"
8
+ "version": "0.10.0"
9
9
  },
10
10
  "plugins": [
11
11
  {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "orchestra",
3
3
  "description": "Improve LLM apps and agents from real traces — reduce cost/latency, raise quality/reliability, capture traces, build evals, run local optimization (GEPA), compare models/providers, and route through Orchestra.",
4
- "version": "0.8.2",
4
+ "version": "0.10.0",
5
5
  "author": {
6
6
  "name": "Orchestra"
7
7
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orchestra",
3
- "version": "0.8.2",
3
+ "version": "0.10.0",
4
4
  "description": "Improve LLM apps and agents from real traces: capture evidence, build evals, optimize prompts/routes, compare models, run local models, and hand off to Orchestra.",
5
5
  "skills": "./skills/"
6
6
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "orchestra",
3
3
  "description": "Improve LLM apps and agents from real traces: capture evidence, build evals, optimize prompts/routes, compare models, run local models, and hand off to Orchestra.",
4
- "version": "0.8.2",
4
+ "version": "0.10.0",
5
5
  "author": {
6
6
  "name": "Orchestra"
7
7
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "understudy-devin-adapter",
3
- "version": "0.8.2",
3
+ "version": "0.10.0",
4
4
  "skills": "./skills",
5
5
  "discovery": "AGENTS.md rule injection + knowledge notes"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "understudy-hermes-adapter",
3
- "version": "0.8.2",
3
+ "version": "0.10.0",
4
4
  "skills": "./skills",
5
5
  "register": "skills.external_dirs in ~/.hermes/config.yaml"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "understudy-opencode-adapter",
3
- "version": "0.8.2",
3
+ "version": "0.10.0",
4
4
  "skills": "./skills",
5
5
  "commands": "./commands"
6
6
  }
package/README.md CHANGED
@@ -487,3 +487,23 @@ command outputs that do not contain private payloads.
487
487
  ## License
488
488
 
489
489
  MIT.
490
+
491
+ ### Claude Code gateway attribution
492
+
493
+ Run Claude Code with persistent session and Git attribution using
494
+ `orchestra claude`. See [setup, resume, capture/cost reconciliation and PR linking](docs/claude-gateway.md).
495
+
496
+ ### Use Claude Code through Orchestra by default
497
+
498
+ Run `orchestra claude-setup` once to choose an organization, project, workload,
499
+ traffic environment, and Claude model. The wizard explains gateway traffic and
500
+ capture before you enable it. Then use `claude` and `claude --resume` normally;
501
+ repository configuration is not required. Requires Claude Code 2.1.312 or later.
502
+
503
+ `orchestra start` offers optional launch, resume, setup status, and session
504
+ reports. `orchestra claude-setup remove` restores the settings Orchestra changed
505
+ and preserves later user edits. Restart Claude after removal. This is a local
506
+ terminal integration; managed policies, disabled mods, and explicit settings or
507
+ shell overrides can prevent it. Setup does not change those policies. Repository
508
+ or branch changes within a session require a new session to keep attribution
509
+ consistent. Captures and prices can arrive later; reports expose those gaps.
package/dist/bin.js CHANGED
@@ -23,7 +23,19 @@ process.emitWarning = ((warning, ...rest) => {
23
23
  return;
24
24
  emitWarning(warning, ...rest);
25
25
  });
26
- if (process.argv[2] === INTERNAL_CONVERSATION_SIDECAR_ARG) {
26
+ if (process.argv[2] === "claude-native-env") {
27
+ try {
28
+ const { nativeClaudeEnvironment } = await import("./claude-native.js");
29
+ const { readFileSync } = await import("node:fs");
30
+ const input = JSON.parse(readFileSync(0, "utf8"));
31
+ process.stdout.write(JSON.stringify(nativeClaudeEnvironment(input.session_id)));
32
+ }
33
+ catch {
34
+ process.stderr.write("Orchestra Claude initialization failed. Run orchestra claude-setup status.\n");
35
+ process.exitCode = 1;
36
+ }
37
+ }
38
+ else if (process.argv[2] === INTERNAL_CONVERSATION_SIDECAR_ARG) {
27
39
  const { runConversationSidecarMain } = await import("./runtime/conversation/sidecar.js");
28
40
  await runConversationSidecarMain();
29
41
  }
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AAEA,oEAAoE;AACpE,OAAO,iBAAiB,CAAC;AACzB,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD,MAAM,iCAAiC,GAAG,qCAAqC,CAAC;AAEhF,wEAAwE;AACxE,qEAAqE;AACrE,MAAM,IAAI,GAAG,iBAAiB,EAAE,CAAC;AACjC,IAAI,IAAI,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;IAC/B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,qFAAqF,CAAC,CAAC;AAC9G,CAAC;KAAM,IAAI,IAAI,CAAC,MAAM,KAAK,OAAO,EAAE,CAAC;IACnC,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,oHAAoH;QAClH,qEAAqE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAChI,CAAC;AACJ,CAAC;AAED,wEAAwE;AACxE,6EAA6E;AAC7E,+EAA+E;AAC/E,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAiC,CAAC;AACtF,OAAO,CAAC,WAAW,GAAG,CAAC,CAAC,OAAuB,EAAE,GAAG,IAAe,EAAE,EAAE;IACrE,MAAM,IAAI,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;IACrE,IAAI,IAAI,CAAC,UAAU,CAAC,mCAAmC,CAAC;QAAE,OAAO;IACjE,WAAW,CAAC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AAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AAC3B,CAAC"}
@@ -0,0 +1,75 @@
1
+ import { z } from "zod";
2
+ import { ClaudeSessionSchema } from "./commands/claude.js";
3
+ type Session = z.infer<typeof ClaudeSessionSchema>;
4
+ interface Scope {
5
+ org: string;
6
+ projectId: string;
7
+ workloadId: string;
8
+ traceId: string;
9
+ environment: string;
10
+ }
11
+ export declare function collectSessionRequests(scope: Scope, pageRequest: (cursor: string | null) => Promise<unknown>): Promise<{
12
+ calls: {
13
+ request_id: string;
14
+ ts: string;
15
+ project_id: string;
16
+ workload_id: string;
17
+ request_environment: "test" | "production";
18
+ trace_id: string;
19
+ status_code: number;
20
+ outcome: string;
21
+ tokens: {
22
+ [x: string]: unknown;
23
+ input_tokens: number;
24
+ cache_creation_input_tokens: number;
25
+ cache_read_input_tokens: number;
26
+ output_tokens: number;
27
+ reasoning_output_tokens: number;
28
+ };
29
+ capture_state: "unknown" | "expected" | "disabled";
30
+ }[];
31
+ snapshot: {
32
+ snapshot_watermark: string;
33
+ };
34
+ known_gaps: string[];
35
+ }>;
36
+ export declare function accountClaudeSession(session: Session, captureDirectory?: string): Promise<{
37
+ session_id: string;
38
+ trace_id: string;
39
+ snapshot: {
40
+ snapshot_watermark: string;
41
+ };
42
+ requests: number;
43
+ failed_requests: number;
44
+ priced_cost_usd: number;
45
+ customer_cost_usd: number | null;
46
+ unpriced_request_ids: string[];
47
+ uncaptured_request_ids: string[];
48
+ known_gaps: string[];
49
+ unmatched_requests: null;
50
+ ambiguous_requests: null;
51
+ attribution_note: string;
52
+ records: {
53
+ pricing_status: string;
54
+ customer_cost_usd: number | null;
55
+ capture_verification: string;
56
+ request_id: string;
57
+ ts: string;
58
+ project_id: string;
59
+ workload_id: string;
60
+ request_environment: "test" | "production";
61
+ trace_id: string;
62
+ status_code: number;
63
+ outcome: string;
64
+ tokens: {
65
+ [x: string]: unknown;
66
+ input_tokens: number;
67
+ cache_creation_input_tokens: number;
68
+ cache_read_input_tokens: number;
69
+ output_tokens: number;
70
+ reasoning_output_tokens: number;
71
+ };
72
+ capture_state: "unknown" | "expected" | "disabled";
73
+ }[];
74
+ }>;
75
+ export {};
@@ -0,0 +1,155 @@
1
+ import { z } from "zod";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { request, UnderstudyApiError } from "./internal/http.js";
5
+ import { resolveProject } from "./internal/projects.js";
6
+ import { resolveWorkload } from "./internal/workloads.js";
7
+ import { CallCostResponseSchema, CoverageSchema, TokenCountsSchema } from "./internal/reporting-contracts.js";
8
+ import { exportCapturesByRequestIds } from "./commands/captures.js";
9
+ import { verifySessionCapture } from "./claude-reconciliation.js";
10
+ // Customer request-log wire subset; unknown fields never enter the report.
11
+ const SessionRequestSchema = z.object({
12
+ request_id: z.string().uuid(), ts: z.string(), project_id: z.string(), workload_id: z.string(),
13
+ request_environment: z.enum(["test", "production"]), trace_id: z.string(), status_code: z.number().int(),
14
+ outcome: z.string(), tokens: TokenCountsSchema,
15
+ capture_state: z.enum(["expected", "disabled", "unknown"]),
16
+ });
17
+ const SessionPageSchema = z.object({
18
+ org_id: z.string(), trace_id: z.string(), snapshot_watermark: z.string(),
19
+ groups: z.array(z.object({ project_id: z.string(), total_count: z.number().int().nonnegative(), calls: z.array(SessionRequestSchema) })),
20
+ next_cursor: z.string().nullable(), coverage: CoverageSchema,
21
+ });
22
+ export async function collectSessionRequests(scope, pageRequest) {
23
+ const calls = [];
24
+ const seenRequests = new Set();
25
+ const seenCursors = new Set();
26
+ const gaps = new Set();
27
+ let cursor = null;
28
+ let snapshot;
29
+ let total;
30
+ let previous;
31
+ do {
32
+ const page = SessionPageSchema.parse(await pageRequest(cursor));
33
+ if (page.org_id !== scope.org || page.trace_id !== scope.traceId)
34
+ throw new Error("Session inventory scope mismatch.");
35
+ if (!Number.isFinite(Date.parse(page.snapshot_watermark)))
36
+ throw new Error("Invalid inventory timeline.");
37
+ if (snapshot && snapshot !== page.snapshot_watermark)
38
+ throw new Error("Inventory snapshot changed during pagination.");
39
+ snapshot ??= page.snapshot_watermark;
40
+ for (const gap of page.coverage.known_gaps)
41
+ gaps.add(gap);
42
+ if (page.coverage.data_completeness < 1)
43
+ gaps.add("Some gateway request metadata is incomplete.");
44
+ let pageCount = 0;
45
+ for (const group of page.groups) {
46
+ if (group.project_id !== scope.projectId)
47
+ throw new Error("Trace spans another project; attribution is ambiguous.");
48
+ if (total !== undefined && total !== group.total_count)
49
+ throw new Error("Inventory total changed during pagination.");
50
+ total ??= group.total_count;
51
+ for (const call of group.calls) {
52
+ if (call.project_id !== scope.projectId || call.workload_id !== scope.workloadId || call.request_environment !== scope.environment || call.trace_id !== scope.traceId)
53
+ throw new Error("Request scope mismatch.");
54
+ const at = Date.parse(call.ts);
55
+ if (!Number.isFinite(at))
56
+ throw new Error("Invalid request timestamp.");
57
+ if (seenRequests.has(call.request_id) || (previous && (at < Date.parse(previous.ts) || (at === Date.parse(previous.ts) && call.request_id <= previous.request_id))))
58
+ throw new Error("Repeated or unordered request in inventory.");
59
+ previous = call;
60
+ seenRequests.add(call.request_id);
61
+ calls.push(call);
62
+ pageCount++;
63
+ if (calls.length > 100_000)
64
+ throw new Error("Session exceeds 100000 requests; no partial report was returned.");
65
+ }
66
+ }
67
+ cursor = page.next_cursor;
68
+ if (cursor !== null) {
69
+ if (!cursor || seenCursors.has(cursor) || pageCount === 0)
70
+ throw new Error("Invalid inventory continuation cursor.");
71
+ seenCursors.add(cursor);
72
+ }
73
+ } while (cursor !== null);
74
+ if (calls.length !== (total ?? 0))
75
+ throw new Error("Inventory count does not match the trace total.");
76
+ return { calls, snapshot: { snapshot_watermark: snapshot }, known_gaps: [...gaps] };
77
+ }
78
+ export async function accountClaudeSession(session, captureDirectory) {
79
+ if (!session.traceparent)
80
+ throw new Error("This session predates trace attribution. Start a new session for transcript-free accounting; use reconcile for older sessions.");
81
+ const traceId = session.traceparent.split("-")[1];
82
+ const project = await resolveProject({ org: session.org, project: session.project });
83
+ if (project.auth.gatewayUrl !== session.gateway_url)
84
+ throw new Error("Gateway changed since session launch.");
85
+ const workload = await resolveWorkload(project, session.workload);
86
+ const inventory = await collectSessionRequests({ org: session.org, projectId: project.projectId, workloadId: workload.id, traceId, environment: session.environment }, async (cursor) => {
87
+ const params = new URLSearchParams({ request_environment: session.environment, limit: "100", include_rejection_details: "true" });
88
+ if (cursor)
89
+ params.set("cursor", cursor);
90
+ return (await request({ orgId: session.org, url: `/admin/v1/orgs/${encodeURIComponent(session.org)}/request-logs/traces/${traceId}?${params}` }, SessionPageSchema)).data;
91
+ });
92
+ const records = [];
93
+ for (const call of inventory.calls) {
94
+ let customerCost = null;
95
+ let pricingStatus = "missing";
96
+ try {
97
+ const cost = (await request({ orgId: session.org, url: `/admin/v1/orgs/${encodeURIComponent(session.org)}/calls/${encodeURIComponent(call.request_id)}/cost` }, CallCostResponseSchema)).data;
98
+ if (cost.org_id !== session.org || cost.project_id !== project.projectId || cost.workload_id !== workload.id || cost.request_id !== call.request_id)
99
+ throw new Error("Cost record scope mismatch.");
100
+ pricingStatus = cost.pricing_status;
101
+ if (cost.pricing_status === "priced") {
102
+ if (!Number.isFinite(cost.customer_cost_usd) || cost.customer_cost_usd < 0)
103
+ throw new Error("Invalid customer cost.");
104
+ customerCost = cost.customer_cost_usd;
105
+ }
106
+ if (cost.coverage.data_completeness < 1)
107
+ inventory.known_gaps.push("Some cost metadata is incomplete.");
108
+ for (const gap of cost.coverage.known_gaps)
109
+ inventory.known_gaps.push(gap);
110
+ }
111
+ catch (error) {
112
+ if (!(error instanceof UnderstudyApiError) || error.status !== 404)
113
+ throw error;
114
+ }
115
+ records.push({ ...call, pricing_status: pricingStatus, customer_cost_usd: customerCost, capture_verification: captureDirectory && call.capture_state !== "expected" ? "not_captured" : "not_requested" });
116
+ }
117
+ if (captureDirectory && records.length) {
118
+ const expected = records.filter(row => row.capture_state === "expected").map(row => row.request_id);
119
+ if (expected.length) {
120
+ const batch = await exportCapturesByRequestIds({ requestIds: expected, outputDirectory: captureDirectory, includePayload: true, concurrency: 4, retries: 2, resume: false, orgId: session.org, projectId: project.projectId, workloadId: workload.id });
121
+ for (const row of records) {
122
+ if (row.capture_state !== "expected") {
123
+ row.capture_verification = "not_captured";
124
+ continue;
125
+ }
126
+ if (batch.failed_request_ids.includes(row.request_id)) {
127
+ row.capture_verification = "missing";
128
+ continue;
129
+ }
130
+ let capture;
131
+ try {
132
+ capture = JSON.parse(readFileSync(join(captureDirectory, `${encodeURIComponent(row.request_id)}.payload.json`), "utf8"));
133
+ }
134
+ catch {
135
+ throw new Error("Invalid capture JSON; raw content omitted.");
136
+ }
137
+ verifySessionCapture(capture, session, row.request_id);
138
+ row.capture_verification = "verified";
139
+ }
140
+ }
141
+ }
142
+ const unpriced = records.filter(row => row.customer_cost_usd === null).map(row => row.request_id);
143
+ const pricedCost = records.reduce((sum, row) => sum + (row.customer_cost_usd ?? 0), 0);
144
+ return {
145
+ session_id: session.session_id, trace_id: traceId, snapshot: inventory.snapshot, requests: records.length,
146
+ failed_requests: records.filter(row => row.status_code >= 400 || row.outcome === "error").length,
147
+ priced_cost_usd: pricedCost, customer_cost_usd: unpriced.length || !records.length ? null : pricedCost,
148
+ unpriced_request_ids: unpriced, uncaptured_request_ids: records.filter(row => row.capture_state !== "expected").map(row => row.request_id),
149
+ known_gaps: [...new Set([...inventory.known_gaps, "Snapshot covers ingested requests carrying this session trace ID, including background calls; later arrivals and traffic without the ID require a fresh inventory or separate investigation."])],
150
+ unmatched_requests: null, ambiguous_requests: null,
151
+ attribution_note: "Session membership is explicit. Requests missing this session trace ID and shared/reused IDs cannot be quantified from this filtered inventory alone.",
152
+ records,
153
+ };
154
+ }
155
+ //# sourceMappingURL=claude-accounting.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-accounting.js","sourceRoot":"","sources":["../src/claude-accounting.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,YAA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AChG,eAAe,EAAE,UAAU,EAAE,iBAAiB,EAAE,QAAQ,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU;QACtG,oBAAoB,EAAE,QAAQ,EAAE,sBAAsB,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,aAAa,KAAK,UAAU,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC;QAC1I,UAAU,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,SAAS,CAAC,UAAU,EAAE,8LAA8L,CAAC,CAAC,CAAC;QACnP,kBAAkB,EAAE,IAAI,EAAE,kBAAkB,EAAE,IAAI;QAClD,gBAAgB,EAAE,uJAAuJ;QACzK,OAAO;KACR,CAAC;AACJ,CAAC"}
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ export declare const BLOCKED_GATEWAY = "http://127.0.0.1:1";
3
+ export declare const ClaudeNativeConfigSchema: z.ZodObject<{
4
+ version: z.ZodLiteral<1>;
5
+ org: z.ZodString;
6
+ project: z.ZodString;
7
+ workload: z.ZodString;
8
+ environment: z.ZodEnum<{
9
+ test: "test";
10
+ production: "production";
11
+ }>;
12
+ gateway_url: z.ZodString;
13
+ model: z.ZodString;
14
+ harness_version: z.ZodOptional<z.ZodString>;
15
+ }, z.core.$strip>;
16
+ export type ClaudeNativeConfig = z.infer<typeof ClaudeNativeConfigSchema>;
17
+ export declare const claudeSettingsPath: () => string;
18
+ export declare function writeNativeJson(path: string, value: unknown): void;
19
+ export declare function readNativeState(): {
20
+ config: {
21
+ version: 1;
22
+ org: string;
23
+ project: string;
24
+ workload: string;
25
+ environment: "test" | "production";
26
+ gateway_url: string;
27
+ model: string;
28
+ harness_version?: string | undefined;
29
+ };
30
+ settings_path: string;
31
+ before: Record<string, unknown>;
32
+ installed: Record<string, unknown>;
33
+ };
34
+ export declare function storedNativeCredential(config: ClaudeNativeConfig): string;
35
+ export declare function checkClaudeVersion(): string;
36
+ export declare function nativeModSource(command: string[]): string;
37
+ export declare function enableNativeClaude(value: ClaudeNativeConfig, cli: string, node?: string): {
38
+ enabled: boolean;
39
+ settings_path: string;
40
+ next: string;
41
+ };
42
+ export declare function removeNativeClaude(): {
43
+ enabled: boolean;
44
+ preserved_user_edits: string[];
45
+ next: string;
46
+ };
47
+ export declare function nativeClaudeEnvironment(id: string, cwd?: string): NodeJS.ProcessEnv;
@@ -0,0 +1,210 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { randomBytes, randomUUID } from "node:crypto";
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, mkdtempSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { z } from "zod";
7
+ import { globalConfigDir, samePath } from "./config/paths.js";
8
+ import { readCredentials } from "./config/credentials.js";
9
+ import { ClaudeSessionSchema, claudeEnvironment, repositoryFromRemote } from "./commands/claude.js";
10
+ export const BLOCKED_GATEWAY = "http://127.0.0.1:1";
11
+ const Header = z.string().min(1).max(256).regex(/^[\x20-\x7e]+$/);
12
+ export const ClaudeNativeConfigSchema = z.object({
13
+ version: z.literal(1), org: Header, project: Header, workload: Header,
14
+ environment: z.enum(["test", "production"]), gateway_url: z.string().url(), model: Header, harness_version: z.string().optional(),
15
+ });
16
+ const object = (value) => z.record(z.string(), z.unknown()).parse(value);
17
+ const statePath = () => join(globalConfigDir(), "claude-native.json");
18
+ export const claudeSettingsPath = () => join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "settings.json");
19
+ const readJson = (path) => existsSync(path) ? object(JSON.parse(readFileSync(path, "utf8"))) : {};
20
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
21
+ export function writeNativeJson(path, value) {
22
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
23
+ const temp = mkdtempSync(join(dirname(path), ".orchestra-write-"));
24
+ try {
25
+ writeFileSync(join(temp, "data"), JSON.stringify(value, null, 2) + "\n", { mode: 0o600 });
26
+ renameSync(join(temp, "data"), path);
27
+ }
28
+ finally {
29
+ rmSync(temp, { recursive: true, force: true });
30
+ }
31
+ }
32
+ const StateSchema = z.object({
33
+ config: ClaudeNativeConfigSchema, settings_path: z.string(),
34
+ before: z.record(z.string(), z.unknown()), installed: z.record(z.string(), z.unknown()),
35
+ });
36
+ export function readNativeState() {
37
+ if (!existsSync(statePath()))
38
+ throw new Error("Claude integration is not enabled. Run orchestra claude-setup.");
39
+ return StateSchema.parse(readJson(statePath()));
40
+ }
41
+ export function storedNativeCredential(config) {
42
+ // Persistent setup is bound to a stored org credential, never an ambient shell API key.
43
+ const entry = readCredentials()?.orgs[config.org];
44
+ if (!entry || entry.gateway_url !== config.gateway_url)
45
+ throw new Error("Claude credential is missing or its gateway changed. Sign in and run orchestra claude-setup again.");
46
+ return entry.api_key;
47
+ }
48
+ export function checkClaudeVersion() {
49
+ const version = execFileSync("claude", ["--version"], { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "pipe"] }).trim();
50
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
51
+ if (!match || Number(match[1]) < 2 || (Number(match[1]) === 2 && (Number(match[2]) < 1 || (Number(match[2]) === 1 && Number(match[3]) < 312)))) {
52
+ throw new Error("Persistent Orchestra setup requires Claude Code 2.1.312 or later. Update Claude and retry.");
53
+ }
54
+ return version;
55
+ }
56
+ export function nativeModSource(command) {
57
+ return `const command = ${JSON.stringify(command)};
58
+ async function apply($) {
59
+ // Refuse network inference until both credentials and attribution are initialized.
60
+ await $.env.set('ANTHROPIC_BASE_URL', '${BLOCKED_GATEWAY}');
61
+ await $.env.set('ANTHROPIC_API_KEY', 'orchestra-initialization-required');
62
+ const result = await $.process.run(command, {
63
+ stdin: JSON.stringify({ session_id: await $.session.id() }), timeoutMs: 10000,
64
+ });
65
+ if (result.exitCode !== 0) throw new Error('Run orchestra claude-setup status to diagnose or orchestra claude-setup remove to restore your settings.');
66
+ const env = JSON.parse(result.stdout);
67
+ await $.env.set('ANTHROPIC_CUSTOM_HEADERS', env.ANTHROPIC_CUSTOM_HEADERS);
68
+ await $.env.set('ANTHROPIC_AUTH_TOKEN', '');
69
+ await $.env.set('ANTHROPIC_API_KEY', env.ANTHROPIC_API_KEY);
70
+ await $.env.set('ANTHROPIC_BASE_URL', env.ANTHROPIC_BASE_URL);
71
+ }
72
+ export function register(on) {
73
+ on('session.start', async ($, e, next) => {
74
+ try { await apply($); } catch { $.ui.log('Orchestra setup needs attention. Run orchestra claude-setup status. Inference is blocked until setup succeeds.'); }
75
+ return next(e);
76
+ });
77
+ on('turn.step', async function* ($, e, next) {
78
+ try { await apply($); } catch { $.ui.log('Orchestra could not initialize this session. Run orchestra claude-setup status.'); return; }
79
+ return yield* next(e);
80
+ });
81
+ }
82
+ `;
83
+ }
84
+ export function enableNativeClaude(value, cli, node = process.execPath) {
85
+ const config = ClaudeNativeConfigSchema.parse(value);
86
+ const url = new URL(config.gateway_url);
87
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash)
88
+ throw new Error("Persistent gateway must be HTTPS without embedded credentials, query, or fragment.");
89
+ storedNativeCredential(config);
90
+ if (existsSync(statePath()))
91
+ throw new Error("Claude integration is already enabled. Remove it before changing the default scope.");
92
+ const settingsPath = claudeSettingsPath();
93
+ if (existsSync(settingsPath) && lstatSync(settingsPath).isSymbolicLink())
94
+ throw new Error("Claude settings is a symlink. Configure its owner directly before enabling Orchestra.");
95
+ const before = readJson(settingsPath);
96
+ if (before.disableAllHooks === true)
97
+ throw new Error("Claude hooks/mods are disabled. Enable them before configuring Orchestra.");
98
+ const env = object(before.env ?? {});
99
+ const conflicts = Object.keys(process.env).filter(key => /^(ANTHROPIC_|CLAUDE_CODE_USE_|CLAUDE_CODE_PLUGIN_DIRS$)/.test(key) && process.env[key]);
100
+ if (conflicts.length)
101
+ throw new Error(`Unset conflicting shell variables before setup: ${conflicts.join(", ")}`);
102
+ for (const key of Object.keys(env))
103
+ if (key.startsWith("CLAUDE_CODE_USE_") && env[key] && env[key] !== "0")
104
+ throw new Error(`Remove conflicting provider setting env.${key} before setup.`);
105
+ const plugin = join(globalConfigDir(), "claude-native-mod");
106
+ const plugins = typeof env.CLAUDE_CODE_PLUGIN_DIRS === "string" && env.CLAUDE_CODE_PLUGIN_DIRS ? env.CLAUDE_CODE_PLUGIN_DIRS + (process.platform === "win32" ? ";" : ":") : "";
107
+ const installed = {
108
+ env: {
109
+ ANTHROPIC_BASE_URL: BLOCKED_GATEWAY,
110
+ ANTHROPIC_API_KEY: "orchestra-initialization-required",
111
+ ANTHROPIC_AUTH_TOKEN: "",
112
+ ANTHROPIC_CUSTOM_HEADERS: "",
113
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
114
+ CLAUDE_CODE_PLUGIN_DIRS: plugins + plugin,
115
+ ANTHROPIC_MODEL: config.model,
116
+ ANTHROPIC_DEFAULT_OPUS_MODEL: config.model,
117
+ ANTHROPIC_DEFAULT_SONNET_MODEL: config.model,
118
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: config.model,
119
+ },
120
+ model: config.model,
121
+ };
122
+ writeNativeJson(join(plugin, ".claude-plugin", "plugin.json"), { name: "orchestra-gateway", version: "0.1.0", author: { name: "Orchestra" }, license: "MIT", description: "Persistent Orchestra gateway and session attribution" });
123
+ writeNativeJson(join(plugin, "hooks", "hooks.json"), { modules: ["./register.js"] });
124
+ writeFileSync(join(plugin, "hooks", "register.js"), nativeModSource([node, resolve(cli), "claude-native-env"]), { mode: 0o600 });
125
+ // Save recovery state first: interruption before settings write remains safely removable.
126
+ writeNativeJson(statePath(), { config, settings_path: settingsPath, before, installed });
127
+ writeNativeJson(settingsPath, { ...before, ...installed, env: { ...env, ...installed.env } });
128
+ return { enabled: true, settings_path: settingsPath, next: "Run claude normally. To restore previous settings: orchestra claude-setup remove" };
129
+ }
130
+ export function removeNativeClaude() {
131
+ const state = readNativeState();
132
+ const current = readJson(state.settings_path);
133
+ const preserved = [];
134
+ for (const [key, installed] of Object.entries(state.installed)) {
135
+ if (key === "env") {
136
+ const env = object(current.env ?? {});
137
+ const original = object(state.before.env ?? {});
138
+ for (const [name, value] of Object.entries(object(installed))) {
139
+ if (same(env[name], value)) {
140
+ if (Object.hasOwn(original, name))
141
+ env[name] = original[name];
142
+ else
143
+ delete env[name];
144
+ }
145
+ else if (name === "CLAUDE_CODE_PLUGIN_DIRS" && typeof env[name] === "string") {
146
+ const separator = process.platform === "win32" ? ";" : ":";
147
+ env[name] = env[name].split(separator).filter(path => !samePath(path, join(globalConfigDir(), "claude-native-mod"))).join(separator);
148
+ }
149
+ else
150
+ preserved.push(`env.${name}`);
151
+ }
152
+ if (Object.keys(env).length || Object.hasOwn(state.before, "env"))
153
+ current.env = env;
154
+ else
155
+ delete current.env;
156
+ }
157
+ else if (same(current[key], installed)) {
158
+ if (Object.hasOwn(state.before, key))
159
+ current[key] = state.before[key];
160
+ else
161
+ delete current[key];
162
+ }
163
+ else
164
+ preserved.push(key);
165
+ }
166
+ writeNativeJson(state.settings_path, current);
167
+ rmSync(statePath());
168
+ // Keep the inert mod files for running sessions; new sessions no longer load them.
169
+ return { enabled: false, preserved_user_edits: preserved, next: "Restart Claude to use your restored settings." };
170
+ }
171
+ export function nativeClaudeEnvironment(id, cwd = process.cwd()) {
172
+ z.string().uuid().parse(id);
173
+ const { config } = readNativeState();
174
+ const token = storedNativeCredential(config);
175
+ const git = (...args) => execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 5000 }).trim();
176
+ let root = resolve(cwd), repository = null, branch = null, base_commit = null;
177
+ try {
178
+ root = git("rev-parse", "--show-toplevel");
179
+ }
180
+ catch { /* Non-repository sessions still have request accounting. */ }
181
+ try {
182
+ repository = repositoryFromRemote(git("remote", "get-url", "origin"));
183
+ }
184
+ catch { /* Unsupported remotes are not uploaded. */ }
185
+ try {
186
+ branch = git("symbolic-ref", "--short", "HEAD");
187
+ }
188
+ catch { /* Detached HEAD has no branch attribution. */ }
189
+ try {
190
+ base_commit = git("rev-parse", "HEAD");
191
+ }
192
+ catch { /* Empty repositories have no base commit. */ }
193
+ const path = join(globalConfigDir(), "claude-sessions", `${id}.json`);
194
+ let session;
195
+ if (existsSync(path)) {
196
+ session = ClaudeSessionSchema.parse(readJson(path));
197
+ if (!samePath(session.root, root) || session.repository !== repository || session.branch !== branch)
198
+ throw new Error("Session repository or branch changed. Start a new Claude session to preserve attribution.");
199
+ for (const field of ["org", "project", "workload", "environment", "gateway_url"])
200
+ if (session[field] !== config[field])
201
+ throw new Error("Session scope changed. Start a new Claude session.");
202
+ }
203
+ else {
204
+ session = ClaudeSessionSchema.parse({ ...config, version: 1, session_id: id, traceparent: `00-${randomUUID().replaceAll("-", "")}-${randomBytes(8).toString("hex")}-01`, created_at: new Date().toISOString(), root, repository, branch, base_commit });
205
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
206
+ writeFileSync(path, JSON.stringify(session, null, 2) + "\n", { mode: 0o600, flag: "wx" });
207
+ }
208
+ return claudeEnvironment({}, session, token);
209
+ }
210
+ //# sourceMappingURL=claude-native.js.map