@teamlearners/clawops 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ClawOps
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,313 @@
1
+ # ClawOps Node.js SDK
2
+
3
+ [ClawOps Voice API](https://api.claw-ops.com/docs)의 공식 Node.js/TypeScript 라이브러리입니다.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@teamlearners/clawops.svg)](https://www.npmjs.com/package/@teamlearners/clawops)
6
+ [![Node.js 18+](https://img.shields.io/node/v/@teamlearners/clawops.svg)](https://www.npmjs.com/package/@teamlearners/clawops)
7
+
8
+ ## 설치
9
+
10
+ ```bash
11
+ # REST API SDK만 사용
12
+ npm install @teamlearners/clawops
13
+
14
+ # AI Agent 포함 (필요한 프로바이더를 함께 설치)
15
+ npm install @teamlearners/clawops ws openai # OpenAI Realtime 모드
16
+ npm install @teamlearners/clawops ws @google/genai # Gemini Realtime 모드
17
+ npm install @teamlearners/clawops ws @deepgram/sdk openai elevenlabs # Pipeline 모드 (OpenAI LLM)
18
+ npm install @teamlearners/clawops ws @deepgram/sdk @anthropic-ai/sdk elevenlabs # Pipeline 모드 (Anthropic LLM)
19
+ ```
20
+
21
+ ## AI Agent (음성 에이전트)
22
+
23
+ `ClawOpsAgent`를 사용하면 한 줄로 인바운드 전화를 AI로 처리할 수 있습니다. ngrok 없이 WebSocket 역방향 연결로 동작합니다.
24
+
25
+ ```typescript
26
+ import { ClawOpsAgent, OpenAIRealtime } from '@teamlearners/clawops/agent';
27
+
28
+ const agent = new ClawOpsAgent({
29
+ from: '07012341234',
30
+ session: new OpenAIRealtime({
31
+ systemPrompt: '친절한 상담원입니다. 고객의 질문에 답변해주세요.',
32
+ voice: 'marin',
33
+ language: 'ko',
34
+ }),
35
+ });
36
+
37
+ agent.tool('check_order', '주문 상태를 확인합니다.', { orderId: { type: 'string' } }, async ({ orderId }) => {
38
+ return '배송 완료';
39
+ });
40
+
41
+ agent.on('call_start', async (call) => {
42
+ console.log(`통화 시작: ${call.fromNumber} -> ${call.toNumber}`);
43
+ });
44
+
45
+ await agent.serve(); // Ctrl+C로 종료
46
+ ```
47
+
48
+ ### MCP 서버 연동
49
+
50
+ MCP 서버를 연결하여 AI에게 외부 도구를 제공할 수 있습니다.
51
+
52
+ ```bash
53
+ npm install @teamlearners/clawops ws @modelcontextprotocol/sdk
54
+ ```
55
+
56
+ ```typescript
57
+ import { ClawOpsAgent, OpenAIRealtime, mcpServerStdio, mcpServerHTTP } from '@teamlearners/clawops/agent';
58
+
59
+ const agent = new ClawOpsAgent({
60
+ from: '07012341234',
61
+ session: new OpenAIRealtime({
62
+ systemPrompt: '상담원입니다.',
63
+ }),
64
+ mcpServers: [
65
+ mcpServerStdio('npx', { args: ['@modelcontextprotocol/server-google'], env: { GOOGLE_API_KEY: '...' } }),
66
+ mcpServerHTTP('https://my-mcp-server.com', { headers: { Authorization: 'Bearer token' } }),
67
+ ],
68
+ });
69
+
70
+ await agent.serve(); // Ctrl+C로 종료
71
+ ```
72
+
73
+ MCP 서버는 전화가 올 때마다 자동으로 시작되고, 통화 종료 시 정리됩니다. MCP 서버가 제공하는 도구는 `agent.tool()`로 등록한 도구와 함께 세션에 자동 등록됩니다.
74
+
75
+ ### OpenTelemetry Tracing
76
+
77
+ 통화 흐름, MCP 도구 호출, LLM 세션을 OpenTelemetry로 추적할 수 있습니다.
78
+
79
+ ```bash
80
+ npm install @teamlearners/clawops ws @opentelemetry/api @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-grpc
81
+ ```
82
+
83
+ ```typescript
84
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
85
+ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
86
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
87
+
88
+ const provider = new NodeTracerProvider();
89
+ provider.addSpanProcessor(new BatchSpanProcessor(new OTLPTraceExporter()));
90
+ provider.register();
91
+
92
+ import { ClawOpsAgent, OpenAIRealtime, setTracingConfig } from '@teamlearners/clawops/agent';
93
+
94
+ setTracingConfig({ enabled: true, serviceName: 'my-call-center' });
95
+
96
+ const agent = new ClawOpsAgent({
97
+ from: '07012341234',
98
+ session: new OpenAIRealtime({ systemPrompt: '상담원입니다.' }),
99
+ });
100
+ ```
101
+
102
+ **Span 계층:**
103
+ - `call` → `mcp.connect` → `llm.session` → `tool.call` → `mcp.call_tool`
104
+
105
+ > 자세한 사용법은 **[Agent 문서](docs/agent/)** 를 참고하세요. (Tool, 이벤트, 통화 녹음, 파이프라인 모드, 커스텀 제공자, MCP 연동, Tracing 등)
106
+
107
+ ## REST API 사용법
108
+
109
+ ```typescript
110
+ import ClawOps from '@teamlearners/clawops';
111
+
112
+ const client = new ClawOps({
113
+ apiKey: 'sk_...', // 또는 CLAWOPS_API_KEY 환경변수 사용
114
+ accountId: 'AC1a2b3c4d', // 또는 CLAWOPS_ACCOUNT_ID 환경변수 사용
115
+ });
116
+ ```
117
+
118
+ ### 통화 (Calls)
119
+
120
+ ```typescript
121
+ // 발신 전화 생성
122
+ const call = await client.calls.create({
123
+ to: '01012345678',
124
+ from: '07052358010',
125
+ url: 'https://my-app.com/twiml',
126
+ statusCallback: 'https://my-app.com/status',
127
+ statusCallbackEvent: 'initiated ringing answered completed',
128
+ });
129
+ console.log(call.callId);
130
+
131
+ // 통화 목록 조회 (페이지네이션)
132
+ const page = await client.calls.list({ status: 'completed', page: 0, pageSize: 20 });
133
+ for (const call of page) {
134
+ console.log(call.callId, call.status);
135
+ }
136
+
137
+ // 모든 통화를 자동으로 순회
138
+ for await (const call of (await client.calls.list()).autoPagingIter()) {
139
+ console.log(call.callId);
140
+ }
141
+
142
+ // 특정 통화 조회
143
+ const detail = await client.calls.get('CAabcdef1234567890');
144
+
145
+ // 통화 종료
146
+ await client.calls.update('CAabcdef1234567890', { status: 'completed' });
147
+ ```
148
+
149
+ ### 전화번호 (Numbers)
150
+
151
+ ```typescript
152
+ // 번호 구매
153
+ const number = await client.numbers.create({ source: 'pool' });
154
+ console.log(number.phoneNumber);
155
+
156
+ // 번호 목록 조회
157
+ const numbers = await client.numbers.list();
158
+
159
+ // 웹훅 URL 변경
160
+ await client.numbers.update('07012340001', { webhookUrl: 'https://my-app.com/webhook' });
161
+
162
+ // 번호 해제
163
+ await client.numbers.delete('07012340001');
164
+ ```
165
+
166
+ ### 메시지 (Messages)
167
+
168
+ ```typescript
169
+ // SMS 발송
170
+ const msg = await client.messages.create({
171
+ to: '01012345678',
172
+ from: '07052358010',
173
+ body: '안녕하세요',
174
+ });
175
+ console.log(msg.messageId);
176
+
177
+ // MMS 발송
178
+ const mms = await client.messages.create({
179
+ to: '01012345678',
180
+ from: '07052358010',
181
+ body: '사진 첨부',
182
+ type: 'mms',
183
+ subject: '제목',
184
+ });
185
+
186
+ // 메시지 목록 조회 (필터링)
187
+ const msgPage = await client.messages.list({ type: 'sms', status: 'sent', page: 0, pageSize: 20 });
188
+ for (const m of msgPage) {
189
+ console.log(m.messageId, m.status);
190
+ }
191
+
192
+ // 모든 메시지를 자동으로 순회
193
+ for await (const m of (await client.messages.list()).autoPagingIter()) {
194
+ console.log(m.messageId);
195
+ }
196
+
197
+ // 특정 메시지 조회
198
+ const detail = await client.messages.get('MG0123456789abcdef');
199
+ ```
200
+
201
+ ### 멀티 계정 접근
202
+
203
+ ```typescript
204
+ // 다른 계정의 리소스에 접근
205
+ const other = client.accounts('AC_other_account_id');
206
+ await other.calls.list();
207
+ await other.numbers.list();
208
+ await other.messages.list();
209
+ ```
210
+
211
+ ## 웹훅 서명 검증
212
+
213
+ ```typescript
214
+ client.webhooks.verify({
215
+ url: 'https://my-app.com/webhook',
216
+ params: { CallId: 'CA...', CallStatus: 'completed' },
217
+ signature: request.headers['x-signature'],
218
+ signingKey: 'your_account_signing_key',
219
+ });
220
+ ```
221
+
222
+ 서명이 유효하지 않으면 `WebhookVerificationError`가 발생합니다.
223
+
224
+ ## 에러 처리
225
+
226
+ ```typescript
227
+ import ClawOps, { BadRequestError, AuthenticationError, NotFoundError } from '@teamlearners/clawops';
228
+
229
+ const client = new ClawOps();
230
+
231
+ try {
232
+ const call = await client.calls.create({ to: '01012345678', from: '07052358010', url: 'https://...' });
233
+ } catch (e) {
234
+ if (e instanceof BadRequestError) {
235
+ console.log(`잘못된 요청: ${e.statusCode} - ${JSON.stringify(e.body)}`);
236
+ } else if (e instanceof AuthenticationError) {
237
+ console.log(`유효하지 않은 API 키: ${e.statusCode}`);
238
+ } else if (e instanceof NotFoundError) {
239
+ console.log(`리소스를 찾을 수 없음: ${e.statusCode}`);
240
+ }
241
+ }
242
+ ```
243
+
244
+ 모든 에러는 `ClawOpsError`를 상속합니다. HTTP 에러는 `statusCode`, `body` 속성을 제공합니다.
245
+
246
+ | 에러 | 상태 코드 |
247
+ | -------------------------- | --------- |
248
+ | `BadRequestError` | 400 |
249
+ | `AuthenticationError` | 401 |
250
+ | `PermissionDeniedError` | 403 |
251
+ | `NotFoundError` | 404 |
252
+ | `ConflictError` | 409 |
253
+ | `UnprocessableEntityError` | 422 |
254
+ | `InternalServerError` | 500+ |
255
+ | `ServiceUnavailableError` | 503 |
256
+
257
+ ## 설정
258
+
259
+ ### 재시도
260
+
261
+ 기본적으로 `408`, `409`, `429`, `500+` 에러 시 지수 백오프로 최대 2회 재시도합니다.
262
+
263
+ ```typescript
264
+ const client = new ClawOps({ maxRetries: 5 });
265
+
266
+ // 재시도 비활성화
267
+ const client = new ClawOps({ maxRetries: 0 });
268
+ ```
269
+
270
+ ### 타임아웃
271
+
272
+ 기본 타임아웃은 600초입니다. 클라이언트 단위로 변경할 수 있습니다:
273
+
274
+ ```typescript
275
+ const client = new ClawOps({ timeout: 30_000 }); // 30초 (밀리초)
276
+ ```
277
+
278
+ ### 커스텀 fetch
279
+
280
+ 프록시 등 고급 설정이 필요한 경우 커스텀 `fetch` 함수를 주입할 수 있습니다:
281
+
282
+ ```typescript
283
+ import { ProxyAgent } from 'undici';
284
+
285
+ const dispatcher = new ProxyAgent('http://proxy.example.com:8080');
286
+ const client = new ClawOps({
287
+ fetch: (url, init) => fetch(url, { ...init, dispatcher }),
288
+ });
289
+ ```
290
+
291
+ ## 환경변수
292
+
293
+ | 변수 | 설명 | 필수 여부 |
294
+ | -------------------- | ---------------------- | ------------------------------------------- |
295
+ | `CLAWOPS_API_KEY` | API 키 (`sk_...`) | 예 (생성자에 전달하지 않은 경우) |
296
+ | `CLAWOPS_ACCOUNT_ID` | 기본 계정 ID (`AC...`) | 예 (생성자에 전달하지 않은 경우) |
297
+ | `CLAWOPS_BASE_URL` | API 기본 URL | 아니오 (기본값: `https://api.claw-ops.com`) |
298
+ | `OPENAI_API_KEY` | OpenAI API 키 | OpenAI Realtime 사용 시 |
299
+ | `GOOGLE_API_KEY` | Google API 키 | Gemini Realtime 사용 시 |
300
+
301
+ ## 문서
302
+
303
+ - **[AI Agent 가이드](docs/agent/)** — 음성 에이전트 상세 사용법, 파이프라인 모드, 커스텀 제공자, MCP 연동
304
+
305
+ ## 요구사항
306
+
307
+ - Node.js 18+
308
+ - `zod` >= 3.23
309
+ - `ws` >= 8.0 (Agent 사용 시)
310
+
311
+ ## 라이선스
312
+
313
+ Apache-2.0