raysurfer 0.4.2 → 0.5.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 CHANGED
@@ -20,107 +20,117 @@ Get your key from the [dashboard](https://raysurfer.com/dashboard/api-keys).
20
20
 
21
21
  ## Usage
22
22
 
23
- Swap your client class and method names. Options come directly from `@anthropic-ai/claude-agent-sdk`:
23
+ Swap your import everything else stays the same:
24
24
 
25
25
  ```typescript
26
26
  // Before
27
- import { ClaudeSDKClient, ClaudeAgentOptions } from "@anthropic-ai/claude-agent-sdk";
27
+ import { query } from "@anthropic-ai/claude-agent-sdk";
28
28
 
29
29
  // After
30
- import { RaysurferClient } from "raysurfer";
31
- import { ClaudeAgentOptions } from "@anthropic-ai/claude-agent-sdk";
32
-
33
- const options: ClaudeAgentOptions = {
34
- allowedTools: ["Read", "Write", "Bash"],
35
- systemPrompt: "You are a helpful assistant.",
36
- };
37
-
38
- const client = new RaysurferClient(options);
39
-
40
- for await (const msg of client.raysurferQuery("Generate quarterly report")) {
41
- console.log(msg);
30
+ import { query } from "raysurfer";
31
+
32
+ for await (const message of query({
33
+ prompt: "Fetch data from GitHub API",
34
+ options: {
35
+ model: "claude-opus-4-5-20250514",
36
+ systemPrompt: "You are a helpful assistant.",
37
+ },
38
+ })) {
39
+ console.log(message);
42
40
  }
43
41
  ```
44
42
 
45
- ## Method Mapping
43
+ All Claude SDK types are re-exported from `raysurfer`, so you don't need a separate import:
46
44
 
47
- | Claude SDK | Raysurfer |
48
- |------------|-----------|
49
- | `new ClaudeSDKClient(options)` | `new RaysurferClient(options)` |
50
- | `client.query(prompt)` | `client.raysurferQuery(prompt)` |
45
+ ```typescript
46
+ import { query, type Options, type SDKMessage, type Query } from "raysurfer";
47
+ ```
51
48
 
52
49
  ## How It Works
53
50
 
54
- 1. **On `raysurferQuery()`**: Retrieves cached code blocks matching your task
55
- 2. **Downloads to sandbox**: Files ready for the agent to execute
56
- 3. **Injects into prompt**: Agent sees proven code snippets
57
- 4. **After success**: New code is cached for next time
58
-
59
- Caching is enabled automatically when `RAYSURFER_API_KEY` is set.
51
+ 1. **On query**: Retrieves cached code blocks matching your task
52
+ 2. **Injects into prompt**: Agent sees proven code snippets
53
+ 3. **After success**: New code is cached for next time
60
54
 
61
- ## Snippet Retrieval Scope
55
+ Caching is enabled automatically when `RAYSURFER_API_KEY` is set. Without it, behaves exactly like the original SDK.
62
56
 
63
- Control which cached snippets are retrieved using `publicSnips` and `snipsDesired`:
57
+ ## Class-based API
64
58
 
65
59
  ```typescript
66
- import { RaysurferClient } from "raysurfer";
67
- import { ClaudeAgentOptions } from "@anthropic-ai/claude-agent-sdk";
60
+ import { ClaudeSDKClient } from "raysurfer";
68
61
 
69
- const options: ClaudeAgentOptions = {
70
- allowedTools: ["Read", "Write", "Bash"],
71
- };
72
-
73
- // Include both public and company snippets
74
- const client = new RaysurferClient(options, {
75
- publicSnips: true, // Include public/shared snippets
76
- snipsDesired: "company", // Also include company-level snippets
62
+ const client = new ClaudeSDKClient({
63
+ model: "claude-opus-4-5-20250514",
64
+ systemPrompt: "You are a helpful assistant.",
77
65
  });
78
66
 
79
- // Enterprise: Retrieve client-specific snippets only
80
- const enterpriseClient = new RaysurferClient(options, {
81
- snipsDesired: "client", // Client workspace snippets (Enterprise only)
82
- });
67
+ for await (const msg of client.query("Fetch data from GitHub API")) {
68
+ console.log(msg);
69
+ }
83
70
  ```
84
71
 
85
- | Configuration | Required Tier |
86
- |--------------|---------------|
87
- | `publicSnips: true` only | FREE (default) |
88
- | `snipsDesired: "company"` | TEAM or ENTERPRISE |
89
- | `snipsDesired: "client"` | ENTERPRISE only |
72
+ ## System Prompt Preset
90
73
 
91
- ## Full Example
74
+ Use the Claude Code preset system prompt with appended instructions:
92
75
 
93
76
  ```typescript
94
- import { RaysurferClient } from "raysurfer";
95
- import { ClaudeAgentOptions } from "@anthropic-ai/claude-agent-sdk";
77
+ for await (const message of query({
78
+ prompt: "Refactor the auth module",
79
+ options: {
80
+ systemPrompt: {
81
+ type: "preset",
82
+ preset: "claude_code",
83
+ append: "Always explain your reasoning.",
84
+ },
85
+ },
86
+ })) {
87
+ console.log(message);
88
+ }
89
+ ```
96
90
 
97
- process.env.RAYSURFER_API_KEY = "your_api_key";
91
+ ## Query Control Methods
98
92
 
99
- const options: ClaudeAgentOptions = {
100
- allowedTools: ["Read", "Write", "Bash"],
101
- systemPrompt: "You are a helpful assistant.",
102
- };
93
+ The `query()` function returns a `Query` object with full control methods:
103
94
 
104
- const client = new RaysurferClient(options);
95
+ ```typescript
96
+ const q = query({ prompt: "Build a REST API" });
97
+
98
+ await q.interrupt();
99
+ await q.setPermissionMode("acceptEdits");
100
+ await q.setModel("claude-sonnet-4-5-20250929");
101
+ await q.setMaxThinkingTokens(4096);
102
+ const models = await q.supportedModels();
103
+ const info = await q.accountInfo();
104
+ q.close();
105
+ ```
105
106
 
106
- // First run: generates and caches code
107
- for await (const msg of client.raysurferQuery("Fetch GitHub trending repos")) {
108
- console.log(msg);
109
- }
107
+ ## Snippet Retrieval Scope
110
108
 
111
- // Second run: retrieves from cache (instant)
112
- for await (const msg of client.raysurferQuery("Fetch GitHub trending repos")) {
113
- console.log(msg);
114
- }
115
- ```
109
+ Control which cached snippets are retrieved:
110
+
111
+ ```typescript
112
+ import { ClaudeSDKClient } from "raysurfer";
116
113
 
117
- ## Without Caching
114
+ // Include company-level snippets (Team/Enterprise)
115
+ const client = new ClaudeSDKClient({
116
+ snipsDesired: "company",
117
+ });
118
118
 
119
- If `RAYSURFER_API_KEY` is not set, `RaysurferClient` behaves exactly like `ClaudeSDKClient` — no caching, just a pass-through wrapper.
119
+ // Enterprise: client-specific snippets only
120
+ const enterpriseClient = new ClaudeSDKClient({
121
+ snipsDesired: "client",
122
+ });
123
+ ```
124
+
125
+ | Configuration | Required Tier |
126
+ |--------------|---------------|
127
+ | Default (public only) | FREE |
128
+ | `snipsDesired: "company"` | TEAM or ENTERPRISE |
129
+ | `snipsDesired: "client"` | ENTERPRISE only |
120
130
 
121
131
  ## Low-Level API
122
132
 
123
- For custom integrations, use the `RaySurfer` client directly with three core methods:
133
+ For custom integrations, use the `RaySurfer` client directly:
124
134
 
125
135
  ```typescript
126
136
  import { RaySurfer } from "raysurfer";
@@ -150,14 +160,6 @@ await client.voteCodeSnip({
150
160
  });
151
161
  ```
152
162
 
153
- ### Method Reference
154
-
155
- | Method | Description |
156
- |--------|-------------|
157
- | `getCodeSnips({ task, topK?, minVerdictScore? })` | Retrieve cached code snippets by semantic search |
158
- | `uploadNewCodeSnips(task, filesWritten, succeeded)` | Store new code files for future reuse |
159
- | `voteCodeSnip({ task, codeBlockId, codeBlockName, codeBlockDescription, succeeded })` | Vote on snippet usefulness |
160
-
161
163
  ## License
162
164
 
163
165
  MIT
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * RaySurfer SDK client
3
3
  */
4
- export declare const VERSION = "0.4.2";
4
+ export declare const VERSION = "0.5.0";
5
5
  import type { AgentReview, AgentVerdict, AutoReviewParams, AutoReviewResponse, ExecutionState, FewShotExample, FileWritten, GetCodeFilesResponse, GetExecutionsParams, RetrieveBestResponse, RetrieveCodeBlockResponse, RetrieveExecutionsResponse, SnipsDesired, StoreCodeBlockResponse, StoreExecutionResponse, SubmitExecutionResultResponse, TaskPattern } from "./types";
6
6
  export interface RaySurferOptions {
7
7
  /** RaySurfer API key */
package/dist/index.d.ts CHANGED
@@ -14,8 +14,10 @@
14
14
  export type { GetCodeFilesParams, GetTaskPatternsParams, RaySurferOptions, RetrieveParams, StoreCodeBlockParams, StoreExecutionParams, } from "./client";
15
15
  export { default as RaySurferDefault, RaySurfer, VERSION } from "./client";
16
16
  export { APIError, AuthenticationError, CacheUnavailableError, RateLimitError, RaySurferError, ValidationError, } from "./errors";
17
- export type { QueryOptions, QueryParams, RaysurferAgentOptions, } from "./sdk-client";
17
+ export type { QueryOptions, QueryParams, RaysurferAgentOptions, RaysurferExtras, RaysurferQueryOptions, } from "./sdk-client";
18
18
  export { ClaudeSDKClient, default as queryDefault, query, RaysurferClient, } from "./sdk-client";
19
19
  export type { AgentReview, AlternativeCandidate, BestMatch, CodeBlock, CodeBlockMatch, CodeFile, ExecutionIO, ExecutionRecord, FewShotExample, FileWritten, GetCodeFilesResponse, RetrieveBestResponse, RetrieveCodeBlockResponse, RetrieveExecutionsResponse, StoreCodeBlockResponse, StoreExecutionResponse, SubmitExecutionResultRequest, SubmitExecutionResultResponse, TaskPattern, VoteCodeSnipParams, VoteCodeSnipResponse, } from "./types";
20
20
  export { AgentVerdict, ExecutionState } from "./types";
21
+ export type { AccountInfo, AgentDefinition, AgentMcpServerSpec, AnyZodRawShape, ApiKeySource, AsyncHookJSONOutput, BaseHookInput, BaseOutputFormat, CanUseTool, ConfigScope, ExitReason, HookCallback, HookCallbackMatcher, HookEvent, HookInput, HookJSONOutput, InferShape, JsonSchemaOutputFormat, McpHttpServerConfig, McpSdkServerConfig, McpSdkServerConfigWithInstance, McpServerConfig, McpServerConfigForProcessTransport, McpServerStatus, McpSetServersResult, McpSSEServerConfig, McpStdioServerConfig, ModelInfo, ModelUsage, NonNullableUsage, NotificationHookInput, NotificationHookSpecificOutput, Options, OutputFormat, OutputFormatType, PermissionBehavior, PermissionMode, PermissionRequestHookInput, PermissionRequestHookSpecificOutput, PermissionResult, PermissionRuleValue, PermissionUpdate, PermissionUpdateDestination, PostToolUseFailureHookInput, PostToolUseFailureHookSpecificOutput, PostToolUseHookInput, PostToolUseHookSpecificOutput, PreCompactHookInput, PreToolUseHookInput, PreToolUseHookSpecificOutput, Query, RewindFilesResult, SandboxIgnoreViolations, SandboxNetworkConfig, SandboxSettings, SDKAssistantMessage, SDKAssistantMessageError, SDKAuthStatusMessage, SDKCompactBoundaryMessage, SDKHookProgressMessage, SDKHookResponseMessage, SDKHookStartedMessage, SDKMessage, SDKPartialAssistantMessage, SDKPermissionDenial, SDKResultError, SDKResultMessage, SDKResultSuccess, SDKStatus, SDKStatusMessage, SDKSystemMessage, SDKTaskNotificationMessage, SDKToolProgressMessage, SDKToolUseSummaryMessage, SDKUserMessage, SDKUserMessageReplay, SdkBeta, SdkMcpToolDefinition, SdkPluginConfig, SessionEndHookInput, SessionStartHookInput, SessionStartHookSpecificOutput, SettingSource, SetupHookInput, SetupHookSpecificOutput, SlashCommand, SpawnedProcess, SpawnOptions, StopHookInput, SubagentStartHookInput, SubagentStartHookSpecificOutput, SubagentStopHookInput, SyncHookJSONOutput, UserPromptSubmitHookInput, UserPromptSubmitHookSpecificOutput, } from "@anthropic-ai/claude-agent-sdk";
22
+ export { AbortError, createSdkMcpServer, EXIT_REASONS, HOOK_EVENTS, tool, } from "@anthropic-ai/claude-agent-sdk";
21
23
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,YAAY,EACV,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,EAChB,cAAc,EACd,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAE3E,OAAO,EACL,QAAQ,EACR,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,EACd,cAAc,EACd,eAAe,GAChB,MAAM,UAAU,CAAC;AAClB,YAAY,EACV,YAAY,EACZ,WAAW,EACX,qBAAqB,GACtB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,eAAe,EACf,OAAO,IAAI,YAAY,EACvB,KAAK,EACL,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,YAAY,EACV,WAAW,EACX,oBAAoB,EACpB,SAAS,EACT,SAAS,EACT,cAAc,EACd,QAAQ,EACR,WAAW,EACX,eAAe,EACf,cAAc,EACd,WAAW,EACX,oBAAoB,EACpB,oBAAoB,EACpB,yBAAyB,EACzB,0BAA0B,EAC1B,sBAAsB,EACtB,sBAAsB,EACtB,4BAA4B,EAC5B,6BAA6B,EAC7B,WAAW,EACX,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"}
package/dist/index.js CHANGED
@@ -69,7 +69,7 @@ class ValidationError extends RaySurferError {
69
69
  }
70
70
 
71
71
  // src/client.ts
72
- var VERSION = "0.4.2";
72
+ var VERSION = "0.5.0";
73
73
  var DEFAULT_BASE_URL = "https://api.raysurfer.com";
74
74
  var MAX_RETRIES = 3;
75
75
  var RETRY_BASE_DELAY = 500;
@@ -552,31 +552,152 @@ var createDebugLogger = (enabled) => ({
552
552
  group: (label) => enabled && console.group(`[raysurfer] ${label}`),
553
553
  groupEnd: () => enabled && console.groupEnd()
554
554
  });
555
- async function* query(params) {
556
- const { prompt, options = {} } = params;
557
- const debugEnabled = options.debug || process.env.RAYSURFER_DEBUG === "true";
558
- const debug = createDebugLogger(debugEnabled);
559
- debug.group("Raysurfer Query Started");
560
- debug.log("Prompt:", prompt);
561
- debug.log("Options:", {
562
- ...options,
563
- systemPrompt: options.systemPrompt || undefined
564
- });
565
- const apiKey = process.env.RAYSURFER_API_KEY;
566
- const baseUrl = process.env.RAYSURFER_BASE_URL || DEFAULT_RAYSURFER_URL;
567
- const cacheEnabled = !!apiKey;
568
- if (!cacheEnabled) {
569
- console.warn("[raysurfer] RAYSURFER_API_KEY not set - caching disabled");
570
- }
571
- debug.log("Cache enabled:", cacheEnabled);
572
- debug.log("Base URL:", baseUrl);
573
- let raysurfer = null;
574
- let cachedFiles = [];
575
- const modifiedFilePaths = new Set;
576
- const bashGeneratedFiles = new Set;
577
- const executionLogs = [];
578
- let taskSucceeded = false;
579
- const extractBashOutputFiles = (command) => {
555
+ function augmentSystemPrompt(systemPrompt, addition) {
556
+ if (!addition)
557
+ return systemPrompt;
558
+ if (typeof systemPrompt === "string")
559
+ return systemPrompt + addition;
560
+ if (systemPrompt?.type === "preset") {
561
+ return { ...systemPrompt, append: (systemPrompt.append ?? "") + addition };
562
+ }
563
+ return addition;
564
+ }
565
+ function splitOptions(options) {
566
+ const { snipsDesired, namespace, debug, workingDirectory, ...sdkOptions } = options;
567
+ return {
568
+ sdkOptions,
569
+ extras: { snipsDesired, namespace, debug, workingDirectory }
570
+ };
571
+ }
572
+
573
+ class RaysurferQuery {
574
+ _inner = null;
575
+ _initPromise = null;
576
+ _raysurfer = null;
577
+ _cachedFiles = [];
578
+ _modifiedFilePaths = new Set;
579
+ _bashGeneratedFiles = new Set;
580
+ _executionLogs = [];
581
+ _taskSucceeded = false;
582
+ _generatedCodeBlocks = [];
583
+ _cacheUploadDone = false;
584
+ _messageCount = 0;
585
+ _startTime = 0;
586
+ _promptText;
587
+ _params;
588
+ _debug;
589
+ _cacheEnabled;
590
+ _workDir;
591
+ _apiKey;
592
+ _baseUrl;
593
+ _extras;
594
+ _sdkOptions;
595
+ constructor(params) {
596
+ this._params = params;
597
+ const options = params.options ?? {};
598
+ const { sdkOptions, extras } = splitOptions(options);
599
+ this._sdkOptions = sdkOptions;
600
+ this._extras = extras;
601
+ this._promptText = typeof params.prompt === "string" ? params.prompt : null;
602
+ const debugEnabled = extras.debug || process.env.RAYSURFER_DEBUG === "true";
603
+ this._debug = createDebugLogger(debugEnabled);
604
+ this._apiKey = process.env.RAYSURFER_API_KEY;
605
+ this._baseUrl = process.env.RAYSURFER_BASE_URL || DEFAULT_RAYSURFER_URL;
606
+ this._cacheEnabled = !!this._apiKey;
607
+ if (extras.workingDirectory && !sdkOptions.cwd) {
608
+ console.warn("[raysurfer] workingDirectory is deprecated, use cwd instead");
609
+ this._sdkOptions.cwd = extras.workingDirectory;
610
+ }
611
+ this._workDir = this._sdkOptions.cwd || process.cwd();
612
+ }
613
+ async _initialize() {
614
+ this._debug.group("Raysurfer Query Started");
615
+ this._debug.log("Prompt:", this._promptText ?? "<stream>");
616
+ this._debug.log("Cache enabled:", this._cacheEnabled);
617
+ this._debug.log("Base URL:", this._baseUrl);
618
+ if (!this._cacheEnabled) {
619
+ console.warn("[raysurfer] RAYSURFER_API_KEY not set - caching disabled");
620
+ }
621
+ let addToLlmPrompt = "";
622
+ if (this._cacheEnabled && this._promptText) {
623
+ this._raysurfer = new RaySurfer({
624
+ apiKey: this._apiKey,
625
+ baseUrl: this._baseUrl,
626
+ snipsDesired: this._extras.snipsDesired,
627
+ namespace: this._extras.namespace
628
+ });
629
+ try {
630
+ this._debug.time("Cache lookup");
631
+ const cacheDir = join(this._workDir, CACHE_DIR);
632
+ const response = await this._raysurfer.getCodeFiles({
633
+ task: this._promptText,
634
+ topK: 5,
635
+ minVerdictScore: 0.3,
636
+ preferComplete: true,
637
+ cacheDir
638
+ });
639
+ this._debug.timeEnd("Cache lookup");
640
+ this._cachedFiles = response.files;
641
+ addToLlmPrompt = response.addToLlmPrompt;
642
+ this._debug.log(`Found ${this._cachedFiles.length} cached files:`);
643
+ console.log("[raysurfer] Cache hit:", this._cachedFiles.length, "snippets retrieved");
644
+ if (this._cachedFiles.length > 0) {
645
+ this._debug.table(this._cachedFiles.map((f) => ({
646
+ filename: f.filename,
647
+ similarity: `${Math.round(f.similarityScore * 100)}%`,
648
+ verdict: `${Math.round(f.verdictScore * 100)}%`,
649
+ combined: `${Math.round(f.combinedScore * 100)}%`,
650
+ thumbs: `${f.thumbsUp}/${f.thumbsDown}`,
651
+ sourceLength: `${f.source.length} chars`
652
+ })));
653
+ try {
654
+ mkdirSync(cacheDir, { recursive: true });
655
+ for (const file of this._cachedFiles) {
656
+ const filePath = join(cacheDir, file.filename);
657
+ writeFileSync(filePath, file.source, "utf-8");
658
+ this._debug.log(` → Wrote cached file: ${filePath}`);
659
+ this._modifiedFilePaths.add(filePath);
660
+ }
661
+ } catch (writeErr) {
662
+ this._debug.log("Failed to write cached files:", writeErr);
663
+ }
664
+ }
665
+ } catch (error) {
666
+ this._debug.log("Cache lookup failed:", error);
667
+ console.warn("[raysurfer] Cache unavailable:", error instanceof Error ? error.message : error);
668
+ }
669
+ }
670
+ const augmented = augmentSystemPrompt(this._sdkOptions.systemPrompt, addToLlmPrompt);
671
+ const augmentedOptions = {
672
+ ...this._sdkOptions,
673
+ systemPrompt: augmented
674
+ };
675
+ this._debug.log("Augmented prompt addition:", addToLlmPrompt.length, "chars");
676
+ let sdkQueryFn;
677
+ try {
678
+ const sdk = await import("@anthropic-ai/claude-agent-sdk");
679
+ sdkQueryFn = sdk.query;
680
+ } catch {
681
+ throw new Error("Could not import @anthropic-ai/claude-agent-sdk. Install it with: npm install @anthropic-ai/claude-agent-sdk");
682
+ }
683
+ this._debug.time("Claude API call");
684
+ this._debug.log("Calling Claude Agent SDK...");
685
+ this._startTime = Date.now();
686
+ this._inner = sdkQueryFn({
687
+ prompt: this._params.prompt,
688
+ options: augmentedOptions
689
+ });
690
+ }
691
+ async _ensureInit() {
692
+ if (!this._inner) {
693
+ if (!this._initPromise) {
694
+ this._initPromise = this._initialize();
695
+ }
696
+ await this._initPromise;
697
+ }
698
+ return this._inner;
699
+ }
700
+ _extractBashOutputFiles(command) {
580
701
  for (const pattern of BASH_OUTPUT_PATTERNS) {
581
702
  pattern.lastIndex = 0;
582
703
  let match = pattern.exec(command);
@@ -585,103 +706,23 @@ async function* query(params) {
585
706
  if (filePath && filePath.length > 0) {
586
707
  const ext = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
587
708
  if (TRACKABLE_EXTENSIONS.has(ext)) {
588
- bashGeneratedFiles.add(filePath);
589
- debug.log(` → Bash output file detected: ${filePath}`);
709
+ this._bashGeneratedFiles.add(filePath);
710
+ this._debug.log(` → Bash output file detected: ${filePath}`);
590
711
  }
591
712
  }
592
713
  match = pattern.exec(command);
593
714
  }
594
715
  }
595
- };
596
- const workDir = options.workingDirectory || process.cwd();
597
- let addToLlmPrompt = "";
598
- if (cacheEnabled) {
599
- raysurfer = new RaySurfer({
600
- apiKey,
601
- baseUrl,
602
- snipsDesired: options.snipsDesired,
603
- namespace: options.namespace
604
- });
605
- try {
606
- debug.time("Cache lookup");
607
- const cacheDir = join(workDir, CACHE_DIR);
608
- const response2 = await raysurfer.getCodeFiles({
609
- task: prompt,
610
- topK: 5,
611
- minVerdictScore: 0.3,
612
- preferComplete: true,
613
- cacheDir
614
- });
615
- debug.timeEnd("Cache lookup");
616
- cachedFiles = response2.files;
617
- addToLlmPrompt = response2.addToLlmPrompt;
618
- debug.log(`Found ${cachedFiles.length} cached files:`);
619
- console.log("[raysurfer] Cache hit:", cachedFiles.length, "snippets retrieved");
620
- if (cachedFiles.length > 0) {
621
- debug.table(cachedFiles.map((f) => ({
622
- filename: f.filename,
623
- similarity: `${Math.round(f.similarityScore * 100)}%`,
624
- verdict: `${Math.round(f.verdictScore * 100)}%`,
625
- combined: `${Math.round(f.combinedScore * 100)}%`,
626
- thumbs: `${f.thumbsUp}/${f.thumbsDown}`,
627
- sourceLength: `${f.source.length} chars`
628
- })));
629
- try {
630
- mkdirSync(cacheDir, { recursive: true });
631
- for (const file of cachedFiles) {
632
- const filePath = join(cacheDir, file.filename);
633
- writeFileSync(filePath, file.source, "utf-8");
634
- debug.log(` → Wrote cached file: ${filePath}`);
635
- modifiedFilePaths.add(filePath);
636
- }
637
- } catch (writeErr) {
638
- debug.log("Failed to write cached files:", writeErr);
639
- }
640
- }
641
- } catch (error) {
642
- debug.log("Cache lookup failed:", error);
643
- console.warn("[raysurfer] Cache unavailable:", error instanceof Error ? error.message : error);
644
- }
645
- }
646
- const augmentedPrompt = (options.systemPrompt ?? "") + addToLlmPrompt;
647
- debug.log("System prompt length:", options.systemPrompt?.length ?? 0, "chars");
648
- debug.log("Augmented prompt length:", augmentedPrompt.length, "chars");
649
- debug.log("Added from cache:", addToLlmPrompt.length, "chars");
650
- if (addToLlmPrompt) {
651
- debug.log(`
652
- --- AUGMENTED PROMPT ADDITION ---`);
653
- debug.log(addToLlmPrompt);
654
- debug.log(`--- END AUGMENTED PROMPT ---
655
- `);
656
716
  }
657
- let sdkQuery;
658
- try {
659
- const sdk = await import("@anthropic-ai/claude-agent-sdk");
660
- sdkQuery = sdk.query;
661
- } catch {
662
- throw new Error("Could not import @anthropic-ai/claude-agent-sdk. Install it with: npm install @anthropic-ai/claude-agent-sdk");
663
- }
664
- debug.time("Claude API call");
665
- debug.log("Calling Claude Agent SDK...");
666
- const response = sdkQuery({
667
- prompt,
668
- options: {
669
- ...options,
670
- systemPrompt: augmentedPrompt
671
- }
672
- });
673
- let messageCount = 0;
674
- const startTime = Date.now();
675
- const generatedCodeBlocks = [];
676
- for await (const message of response) {
677
- messageCount++;
717
+ _trackMessage(message) {
718
+ this._messageCount++;
678
719
  const msg = message;
679
- const elapsed = Date.now() - startTime;
680
- debug.log(`
720
+ const elapsed = Date.now() - this._startTime;
721
+ this._debug.log(`
681
722
  ═══════════════════════════════════════════════════`);
682
- debug.log(`Message #${messageCount} [${elapsed}ms] type=${msg.type} subtype=${msg.subtype || "none"}`);
683
- debug.log(`═══════════════════════════════════════════════════`);
684
- debug.log(JSON.stringify(msg, null, 2));
723
+ this._debug.log(`Message #${this._messageCount} [${elapsed}ms] type=${msg.type} subtype=${msg.subtype || "none"}`);
724
+ this._debug.log(`═══════════════════════════════════════════════════`);
725
+ this._debug.log(JSON.stringify(msg, null, 2));
685
726
  if (msg.type === "assistant") {
686
727
  const content = msg.message;
687
728
  const contentBlocks = content?.content;
@@ -691,21 +732,21 @@ async function* query(params) {
691
732
  const input = block.input;
692
733
  const filePath = input?.file_path ?? input?.notebook_path;
693
734
  if (filePath) {
694
- debug.log(` → ${block.name} tool detected:`, filePath);
695
- modifiedFilePaths.add(filePath);
735
+ this._debug.log(` → ${block.name} tool detected:`, filePath);
736
+ this._modifiedFilePaths.add(filePath);
696
737
  }
697
738
  }
698
739
  if (block.type === "tool_use" && block.name === "Bash") {
699
740
  const input = block.input;
700
741
  const command = input?.command;
701
742
  if (command) {
702
- extractBashOutputFiles(command);
743
+ this._extractBashOutputFiles(command);
703
744
  }
704
745
  }
705
746
  if (block.type === "tool_result") {
706
- const content2 = block.content;
707
- if (content2) {
708
- executionLogs.push(content2.slice(0, 5000));
747
+ const resultContent = block.content;
748
+ if (resultContent) {
749
+ this._executionLogs.push(resultContent.slice(0, 5000));
709
750
  }
710
751
  }
711
752
  if (block.type === "text") {
@@ -715,8 +756,8 @@ async function* query(params) {
715
756
  for (const match of codeMatches) {
716
757
  const code = match.replace(/```(?:typescript|javascript|ts|js)?\n?/, "").replace(/\n?```$/, "");
717
758
  if (code.trim().length > 50) {
718
- generatedCodeBlocks.push(code.trim());
719
- debug.log(` → Extracted code block (${code.length} chars)`);
759
+ this._generatedCodeBlocks.push(code.trim());
760
+ this._debug.log(` → Extracted code block (${code.length} chars)`);
720
761
  }
721
762
  }
722
763
  }
@@ -725,93 +766,165 @@ async function* query(params) {
725
766
  }
726
767
  }
727
768
  if (msg.type === "result" && msg.subtype === "success") {
728
- taskSucceeded = true;
729
- debug.timeEnd("Claude API call");
730
- debug.log("Task succeeded!");
769
+ this._taskSucceeded = true;
770
+ this._debug.timeEnd("Claude API call");
771
+ this._debug.log("Task succeeded!");
731
772
  const result = msg;
732
- debug.log(" Duration:", result.duration_ms, "ms");
733
- debug.log(" Total cost:", result.total_cost_usd, "USD");
734
- debug.log(" Turns:", result.num_turns);
773
+ this._debug.log(" Duration:", result.duration_ms, "ms");
774
+ this._debug.log(" Total cost:", result.total_cost_usd, "USD");
775
+ this._debug.log(" Turns:", result.num_turns);
735
776
  }
736
777
  if (msg.type === "result" && msg.subtype !== "success") {
737
- debug.timeEnd("Claude API call");
738
- debug.log("Task failed:", msg.subtype);
739
- }
740
- yield message;
741
- }
742
- debug.log("Total messages streamed:", messageCount);
743
- debug.log("Modified files tracked:", modifiedFilePaths.size);
744
- debug.log("Code blocks extracted:", generatedCodeBlocks.length);
745
- const filesToCache = [];
746
- for (const filePath of modifiedFilePaths) {
747
- if (filePath.includes(CACHE_DIR)) {
748
- debug.log(" → Skipping cached file:", filePath);
749
- continue;
750
- }
751
- try {
752
- if (existsSync(filePath)) {
753
- const content = readFileSync(filePath, "utf-8");
754
- if (content.includes("\x00")) {
755
- debug.log(" → Skipping binary file:", filePath);
756
- continue;
757
- }
758
- filesToCache.push({ path: filePath, content });
759
- debug.log(" → Will cache file:", filePath, `(${content.length} chars)`);
760
- } else {
761
- debug.log(" → File not found:", filePath);
762
- }
763
- } catch (err) {
764
- debug.log(" → Failed to read file:", filePath, err);
778
+ this._debug.timeEnd("Claude API call");
779
+ this._debug.log("Task failed:", msg.subtype);
765
780
  }
766
781
  }
767
- for (const filePath of bashGeneratedFiles) {
768
- if (modifiedFilePaths.has(filePath))
769
- continue;
770
- try {
771
- if (existsSync(filePath)) {
772
- const content = readFileSync(filePath, "utf-8");
773
- if (!content.includes("\x00")) {
782
+ async _uploadCache() {
783
+ if (this._cacheUploadDone)
784
+ return;
785
+ this._cacheUploadDone = true;
786
+ this._debug.log("Total messages streamed:", this._messageCount);
787
+ this._debug.log("Modified files tracked:", this._modifiedFilePaths.size);
788
+ this._debug.log("Code blocks extracted:", this._generatedCodeBlocks.length);
789
+ const filesToCache = [];
790
+ for (const filePath of this._modifiedFilePaths) {
791
+ if (filePath.includes(CACHE_DIR)) {
792
+ this._debug.log(" → Skipping cached file:", filePath);
793
+ continue;
794
+ }
795
+ try {
796
+ if (existsSync(filePath)) {
797
+ const content = readFileSync(filePath, "utf-8");
798
+ if (content.includes("\x00")) {
799
+ this._debug.log(" → Skipping binary file:", filePath);
800
+ continue;
801
+ }
774
802
  filesToCache.push({ path: filePath, content });
775
- debug.log(" → Will cache Bash-generated file:", filePath, `(${content.length} chars)`);
803
+ this._debug.log(" → Will cache file:", filePath, `(${content.length} chars)`);
804
+ } else {
805
+ this._debug.log(" → File not found:", filePath);
776
806
  }
807
+ } catch (err) {
808
+ this._debug.log(" → Failed to read file:", filePath, err);
777
809
  }
778
- } catch {
779
- debug.log(" → Failed to read Bash-generated file:", filePath);
780
810
  }
781
- }
782
- if (generatedCodeBlocks.length > 0) {
783
- const largestBlock = generatedCodeBlocks.reduce((a, b) => a.length > b.length ? a : b);
784
- filesToCache.push({
785
- path: "generated-code.ts",
786
- content: largestBlock
787
- });
788
- debug.log(" → Will cache generated code block:", `(${largestBlock.length} chars)`);
789
- }
790
- debug.log("Total items to cache:", filesToCache.length);
791
- if (cacheEnabled && raysurfer && taskSucceeded) {
792
- const cachedBlocksForVoting = cachedFiles.map((f) => ({
793
- codeBlockId: f.codeBlockId,
794
- filename: f.filename,
795
- description: f.description
796
- }));
797
- if (filesToCache.length > 0 || cachedBlocksForVoting.length > 0) {
811
+ for (const filePath of this._bashGeneratedFiles) {
812
+ if (this._modifiedFilePaths.has(filePath))
813
+ continue;
798
814
  try {
799
- debug.time("Cache upload + voting");
800
- const joinedLogs = executionLogs.length > 0 ? executionLogs.join(`
815
+ if (existsSync(filePath)) {
816
+ const content = readFileSync(filePath, "utf-8");
817
+ if (!content.includes("\x00")) {
818
+ filesToCache.push({ path: filePath, content });
819
+ this._debug.log(" → Will cache Bash-generated file:", filePath, `(${content.length} chars)`);
820
+ }
821
+ }
822
+ } catch {
823
+ this._debug.log(" → Failed to read Bash-generated file:", filePath);
824
+ }
825
+ }
826
+ if (this._generatedCodeBlocks.length > 0) {
827
+ const largestBlock = this._generatedCodeBlocks.reduce((a, b) => a.length > b.length ? a : b);
828
+ filesToCache.push({
829
+ path: "generated-code.ts",
830
+ content: largestBlock
831
+ });
832
+ this._debug.log(" → Will cache generated code block:", `(${largestBlock.length} chars)`);
833
+ }
834
+ this._debug.log("Total items to cache:", filesToCache.length);
835
+ if (this._cacheEnabled && this._raysurfer && this._taskSucceeded && this._promptText) {
836
+ const cachedBlocksForVoting = this._cachedFiles.map((f) => ({
837
+ codeBlockId: f.codeBlockId,
838
+ filename: f.filename,
839
+ description: f.description
840
+ }));
841
+ if (filesToCache.length > 0 || cachedBlocksForVoting.length > 0) {
842
+ try {
843
+ this._debug.time("Cache upload + voting");
844
+ const joinedLogs = this._executionLogs.length > 0 ? this._executionLogs.join(`
801
845
  ---
802
846
  `) : undefined;
803
- debug.log("Uploading", filesToCache.length, "files, voting for", cachedBlocksForVoting.length, "cached blocks,", executionLogs.length, "log entries...");
804
- await raysurfer.uploadNewCodeSnips(prompt, filesToCache, true, cachedBlocksForVoting.length > 0 ? cachedBlocksForVoting : undefined, true, joinedLogs);
805
- debug.timeEnd("Cache upload + voting");
806
- debug.log("Cache upload successful, voting queued on backend");
807
- console.log("[raysurfer] Cache upload successful:", filesToCache.length, "files stored");
808
- } catch (error) {
809
- debug.log("Cache upload failed:", error);
810
- console.warn("[raysurfer] Cache upload failed:", error instanceof Error ? error.message : error);
847
+ this._debug.log("Uploading", filesToCache.length, "files, voting for", cachedBlocksForVoting.length, "cached blocks,", this._executionLogs.length, "log entries...");
848
+ await this._raysurfer.uploadNewCodeSnips(this._promptText, filesToCache, true, cachedBlocksForVoting.length > 0 ? cachedBlocksForVoting : undefined, true, joinedLogs);
849
+ this._debug.timeEnd("Cache upload + voting");
850
+ this._debug.log("Cache upload successful, voting queued on backend");
851
+ console.log("[raysurfer] Cache upload successful:", filesToCache.length, "files stored");
852
+ } catch (error) {
853
+ this._debug.log("Cache upload failed:", error);
854
+ console.warn("[raysurfer] Cache upload failed:", error instanceof Error ? error.message : error);
855
+ }
811
856
  }
812
857
  }
858
+ this._debug.groupEnd();
859
+ }
860
+ async next(...args) {
861
+ const inner = await this._ensureInit();
862
+ const result = await inner.next(...args);
863
+ if (!result.done) {
864
+ this._trackMessage(result.value);
865
+ } else {
866
+ await this._uploadCache();
867
+ }
868
+ return result;
869
+ }
870
+ async return(value) {
871
+ if (this._inner) {
872
+ await this._uploadCache();
873
+ return this._inner.return(value);
874
+ }
875
+ return { done: true, value: undefined };
876
+ }
877
+ async throw(e) {
878
+ if (this._inner)
879
+ return this._inner.throw(e);
880
+ throw e;
881
+ }
882
+ [Symbol.asyncIterator]() {
883
+ return this;
884
+ }
885
+ async[Symbol.asyncDispose]() {
886
+ this.close();
887
+ }
888
+ async interrupt() {
889
+ return (await this._ensureInit()).interrupt();
890
+ }
891
+ async setPermissionMode(mode) {
892
+ return (await this._ensureInit()).setPermissionMode(mode);
893
+ }
894
+ async setModel(model) {
895
+ return (await this._ensureInit()).setModel(model);
896
+ }
897
+ async setMaxThinkingTokens(maxThinkingTokens) {
898
+ return (await this._ensureInit()).setMaxThinkingTokens(maxThinkingTokens);
899
+ }
900
+ async supportedCommands() {
901
+ return (await this._ensureInit()).supportedCommands();
902
+ }
903
+ async supportedModels() {
904
+ return (await this._ensureInit()).supportedModels();
905
+ }
906
+ async mcpServerStatus() {
907
+ return (await this._ensureInit()).mcpServerStatus();
908
+ }
909
+ async accountInfo() {
910
+ return (await this._ensureInit()).accountInfo();
911
+ }
912
+ async rewindFiles(userMessageId, options) {
913
+ return (await this._ensureInit()).rewindFiles(userMessageId, options);
914
+ }
915
+ async setMcpServers(servers) {
916
+ return (await this._ensureInit()).setMcpServers(servers);
917
+ }
918
+ async streamInput(stream) {
919
+ return (await this._ensureInit()).streamInput(stream);
920
+ }
921
+ close() {
922
+ if (this._inner)
923
+ this._inner.close();
813
924
  }
814
- debug.groupEnd();
925
+ }
926
+ function query(params) {
927
+ return new RaysurferQuery(params);
815
928
  }
816
929
 
817
930
  class ClaudeSDKClient {
@@ -819,8 +932,8 @@ class ClaudeSDKClient {
819
932
  constructor(options = {}) {
820
933
  this.options = options;
821
934
  }
822
- async* query(prompt) {
823
- yield* query({ prompt, options: this.options });
935
+ query(prompt) {
936
+ return query({ prompt, options: this.options });
824
937
  }
825
938
  }
826
939
  var sdk_client_default = query;
@@ -838,9 +951,20 @@ var AgentVerdict;
838
951
  AgentVerdict2["THUMBS_DOWN"] = "thumbs_down";
839
952
  AgentVerdict2["PENDING"] = "pending";
840
953
  })(AgentVerdict ||= {});
954
+
955
+ // src/index.ts
956
+ import {
957
+ AbortError,
958
+ createSdkMcpServer,
959
+ EXIT_REASONS,
960
+ HOOK_EVENTS,
961
+ tool
962
+ } from "@anthropic-ai/claude-agent-sdk";
841
963
  export {
964
+ tool,
842
965
  sdk_client_default as queryDefault,
843
966
  query,
967
+ createSdkMcpServer,
844
968
  ValidationError,
845
969
  VERSION,
846
970
  ClaudeSDKClient as RaysurferClient,
@@ -848,10 +972,13 @@ export {
848
972
  client_default as RaySurferDefault,
849
973
  RaySurfer,
850
974
  RateLimitError,
975
+ HOOK_EVENTS,
851
976
  ExecutionState,
977
+ EXIT_REASONS,
852
978
  ClaudeSDKClient,
853
979
  CacheUnavailableError,
854
980
  AuthenticationError,
855
981
  AgentVerdict,
982
+ AbortError,
856
983
  APIError
857
984
  };
@@ -11,33 +11,29 @@
11
11
  *
12
12
  * Everything else works exactly the same. Set RAYSURFER_API_KEY to enable caching.
13
13
  */
14
+ import type { Options, Query, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
14
15
  import type { SnipsDesired } from "./types";
15
- /** Options for the query function - matches Claude Agent SDK */
16
- export interface QueryOptions {
17
- model?: string;
18
- workingDirectory?: string;
19
- systemPrompt?: string;
20
- permissionMode?: "default" | "acceptEdits" | "plan" | "bypassPermissions";
21
- maxBudgetUsd?: number;
22
- allowedTools?: string[];
23
- disallowedTools?: string[];
24
- maxTurns?: number;
25
- env?: Record<string, string>;
16
+ /** Raysurfer-specific options beyond Claude SDK Options */
17
+ export interface RaysurferExtras {
26
18
  /** Scope of private snippets - "company" (Team/Enterprise) or "client" (Enterprise only) */
27
19
  snipsDesired?: SnipsDesired;
28
20
  /** Custom namespace for code storage/retrieval */
29
21
  namespace?: string;
30
22
  /** Enable debug logging - also enabled via RAYSURFER_DEBUG=true env var */
31
23
  debug?: boolean;
32
- /** Path to Claude Code executable (required for SDK) */
33
- pathToClaudeCodeExecutable?: string;
34
- /** Allow dangerous permissions bypass */
35
- allowDangerouslySkipPermissions?: boolean;
24
+ /** @deprecated Use `cwd` instead */
25
+ workingDirectory?: string;
36
26
  }
27
+ /** Full query options: Claude SDK Options extended with Raysurfer extras */
28
+ export type RaysurferQueryOptions = Options & RaysurferExtras;
29
+ /**
30
+ * @deprecated Use RaysurferQueryOptions instead
31
+ */
32
+ export type QueryOptions = RaysurferQueryOptions;
37
33
  /** Query parameters - matches Claude Agent SDK */
38
34
  export interface QueryParams {
39
- prompt: string;
40
- options?: QueryOptions;
35
+ prompt: string | AsyncIterable<SDKUserMessage>;
36
+ options?: RaysurferQueryOptions;
41
37
  }
42
38
  /**
43
39
  * Drop-in replacement for Claude Agent SDK's query function with automatic caching.
@@ -52,7 +48,7 @@ export interface QueryParams {
52
48
  *
53
49
  * Set RAYSURFER_API_KEY environment variable to enable caching.
54
50
  */
55
- export declare function query(params: QueryParams): AsyncGenerator<unknown>;
51
+ export declare function query(params: QueryParams): Query;
56
52
  /**
57
53
  * ClaudeSDKClient - Class-based drop-in replacement.
58
54
  *
@@ -65,10 +61,10 @@ export declare function query(params: QueryParams): AsyncGenerator<unknown>;
65
61
  */
66
62
  export declare class ClaudeSDKClient {
67
63
  private options;
68
- constructor(options?: QueryOptions);
69
- query(prompt: string): AsyncGenerator<unknown>;
64
+ constructor(options?: RaysurferQueryOptions);
65
+ query(prompt: string | AsyncIterable<SDKUserMessage>): Query;
70
66
  }
71
67
  export { ClaudeSDKClient as RaysurferClient };
72
- export type { QueryOptions as RaysurferAgentOptions };
68
+ export type { RaysurferQueryOptions as RaysurferAgentOptions };
73
69
  export default query;
74
70
  //# sourceMappingURL=sdk-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sdk-client.d.ts","sourceRoot":"","sources":["../src/sdk-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAKH,OAAO,KAAK,EAAyB,YAAY,EAAE,MAAM,SAAS,CAAC;AA2DnE,gEAAgE;AAChE,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,SAAS,GAAG,aAAa,GAAG,MAAM,GAAG,mBAAmB,CAAC;IAC1E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,4FAA4F;IAC5F,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2EAA2E;IAC3E,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,wDAAwD;IACxD,0BAA0B,CAAC,EAAE,MAAM,CAAC;IACpC,yCAAyC;IACzC,+BAA+B,CAAC,EAAE,OAAO,CAAC;CAC3C;AAED,kDAAkD;AAClD,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,YAAY,CAAC;CACxB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAuB,KAAK,CAAC,MAAM,EAAE,WAAW,GAAG,cAAc,CAAC,OAAO,CAAC,CAqYzE;AAED;;;;;;;;;GASG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,OAAO,CAAe;gBAElB,OAAO,GAAE,YAAiB;IAI/B,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,cAAc,CAAC,OAAO,CAAC;CAGtD;AAGD,OAAO,EAAE,eAAe,IAAI,eAAe,EAAE,CAAC;AAC9C,YAAY,EAAE,YAAY,IAAI,qBAAqB,EAAE,CAAC;AAEtD,eAAe,KAAK,CAAC"}
1
+ {"version":3,"file":"sdk-client.d.ts","sourceRoot":"","sources":["../src/sdk-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,KAAK,EAMV,OAAO,EAEP,KAAK,EAGL,cAAc,EAEf,MAAM,gCAAgC,CAAC;AAExC,OAAO,KAAK,EAAyB,YAAY,EAAE,MAAM,SAAS,CAAC;AA2DnE,2DAA2D;AAC3D,MAAM,WAAW,eAAe;IAC9B,4FAA4F;IAC5F,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2EAA2E;IAC3E,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,oCAAoC;IACpC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,4EAA4E;AAC5E,MAAM,MAAM,qBAAqB,GAAG,OAAO,GAAG,eAAe,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,qBAAqB,CAAC;AAEjD,kDAAkD;AAClD,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,GAAG,aAAa,CAAC,cAAc,CAAC,CAAC;IAC/C,OAAO,CAAC,EAAE,qBAAqB,CAAC;CACjC;AAmjBD;;;;;;;;;;;;GAYG;AACH,wBAAgB,KAAK,CAAC,MAAM,EAAE,WAAW,GAAG,KAAK,CAEhD;AAED;;;;;;;;;GASG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,OAAO,CAAwB;gBAE3B,OAAO,GAAE,qBAA0B;IAI/C,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,CAAC,cAAc,CAAC,GAAG,KAAK;CAG7D;AAGD,OAAO,EAAE,eAAe,IAAI,eAAe,EAAE,CAAC;AAC9C,YAAY,EAAE,qBAAqB,IAAI,qBAAqB,EAAE,CAAC;AAE/D,eAAe,KAAK,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "raysurfer",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "Drop-in replacement for Claude Agent SDK with automatic code caching - just swap your import",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",