@lawrenceliang-btc/atel-sdk 0.9.2 → 0.9.6

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
@@ -1,74 +1,75 @@
1
1
  # ATEL SDK
2
2
 
3
- **Agent Trust & Economics Layer** — a TypeScript protocol SDK for building trustworthy, auditable multi-agent systems.
4
-
5
- ATEL provides the cryptographic primitives and protocol building blocks that let AI agents collaborate safely: identity verification, scoped consent, policy enforcement, tamper-evident execution traces, Merkle-tree proofs, and reputation scoring.
6
-
7
- ## What's New in v0.9.0
8
-
9
- - **🔍 System Status Command** — Check agent health with `atel status`
10
- - **🤖 Ollama Auto-Init** — Automatic Ollama service startup and model download
11
- - **📊 Visual Health Indicators** — Clear ✅/❌/⚠️ status display
12
- - **🔐 Enhanced Security** — Improved audit verification with local LLM fallback
13
-
14
- See [docs/STATUS_AND_OLLAMA_FEATURE.md](docs/STATUS_AND_OLLAMA_FEATURE.md) for details.
3
+ **Agent Trust & Exchange Layer** — A TypeScript protocol SDK for building trustworthy, auditable multi-agent systems.
4
+
5
+ ## Core Capabilities
6
+
7
+ ATEL provides the cryptographic primitives and protocol building blocks that enable secure AI agent collaboration:
8
+
9
+ - **🔐 Identity & Verification** — Ed25519 keypairs, DID creation, signing & verification
10
+ - **📋 Policy Enforcement** — Scoped consent tokens, call tracking, deterministic hashing
11
+ - **🔍 Execution Tracing** — Tamper-evident, hash-chained audit logs with auto-checkpoints
12
+ - **✅ Proof Generation** — Merkle-tree proof bundles with multi-check verification
13
+ - **⚓ On-Chain Anchoring** — Multi-chain proof anchoring (Solana/Base/BSC)
14
+ - **📊 Trust Scoring** — Local trust computation based on execution history
15
+ - **🤖 CoT Audit** — Chain-of-thought reasoning verification with local LLM
16
+ - **👥 P2P Access Control** — Relationship-based friend system with temporary sessions
17
+
18
+ ## Key Features
19
+
20
+ ### Zero-Config Deployment
21
+ - No external dependencies (no Ollama, no Docker)
22
+ - Auto-downloads audit model on first run (~400MB)
23
+ - Pure Node.js with node-llama-cpp
24
+ - Cross-platform (Linux/macOS/Windows)
25
+
26
+ ### P2P Friend System
27
+ - Relationship-based access control (friends-only mode)
28
+ - Friend request workflow with approval
29
+ - Temporary sessions for non-friends (time & task limits)
30
+ - DID alias system (@alias syntax)
31
+ - Rate limiting and security validation
32
+
33
+ ### Trust & Verification
34
+ - Tamper-evident execution traces
35
+ - Merkle-tree proof generation
36
+ - On-chain anchoring (Solana/Base/BSC)
37
+ - Local trust score computation
38
+ - CoT reasoning audit with local LLM
39
+
40
+ ### Developer Experience
41
+ - Comprehensive CLI with detailed help
42
+ - Unified output format (human/json/quiet)
43
+ - Status commands for system overview
44
+ - Confirmation prompts for destructive operations
45
+ - 13 composable modules
15
46
 
16
47
  ## Quick Start
17
48
 
18
- ### For End Users (CLI)
19
-
20
- Install the ATEL CLI globally:
49
+ ### Installation
21
50
 
22
51
  ```bash
23
52
  npm install -g @lawrenceliang-btc/atel-sdk
24
- atel init my-agent
25
- atel register "My Agent" "assistant,research"
26
- atel start 3100
27
- ```
28
-
29
- **Check system status:**
30
- ```bash
31
- atel status
32
- # Shows: Identity, Agent, Executor, Gateway, Ollama, Audit, Network
33
53
  ```
34
54
 
35
- See [skill/references/quickstart.md](skill/references/quickstart.md) for detailed setup and upgrade instructions.
36
-
37
- ### For Developers (SDK)
38
-
39
- Clone and build from source:
55
+ ### Initialize Your Agent
40
56
 
41
57
  ```bash
42
- git clone https://github.com/LawrenceLiang-BTC/atel-sdk.git
43
- cd atel-sdk
44
- npm install
45
- npm run build
46
-
47
- # Run the end-to-end demo
48
- npx tsx demo/full-demo.ts
58
+ atel init my-agent
59
+ atel register "My Agent" "assistant,research"
60
+ atel start 3100
49
61
  ```
50
62
 
51
- Phase 0.5 commands:
63
+ ### First Run (Auto-Downloads Model)
52
64
 
53
65
  ```bash
54
- # Real external API e2e demo
55
- npm run demo:real
56
-
57
- # Testnet anchoring smoke (requires chain env vars)
58
- npm run smoke:anchor
59
-
60
- # Performance baseline
61
- npm run test:perf
62
-
63
- # 5-10 agent continuous run (Phase 0.5)
64
- npm run run:cluster
65
-
66
- # deploy acceptance (service + sync + proof + anchor)
67
- npm run acceptance:deploy
66
+ atel start 3100
67
+ # 📦 Downloading model (first time only, ~400MB)...
68
+ # Progress: 100% (408.9/408.9 MB)
69
+ # Model ready
70
+ # 🚀 Agent started on port 3100
68
71
  ```
69
72
 
70
- The demo simulates two agents collaborating on a flight search task, exercising the end-to-end trust workflow.
71
-
72
73
  ## Architecture
73
74
 
74
75
  ATEL is organized into 13 composable modules:
@@ -87,165 +88,98 @@ ATEL is organized into 13 composable modules:
87
88
 
88
89
  | Module | Description |
89
90
  |--------|-------------|
90
- | **Identity** | Ed25519 key pairs, DID creation (`did:atel:*`), signing & verification |
91
- | **Schema** | Task and Capability JSON schemas, validation, factory functions, matching |
92
- | **Policy** | Consent tokens (scoped, time-limited), policy engine with call tracking |
93
- | **Gateway** | Central tool invocation gateway with policy enforcement and deterministic hashing |
94
- | **Trace** | Append-only, hash-chained execution log with auto-checkpoints |
95
- | **Proof** | Merkle-tree proof bundles with multi-check verification |
96
- | **Score** | Local trust-score computation based on execution history |
97
- | **Graph** | Multi-dimensional trust graph, direct/indirect/composite trust |
98
- | **TrustManager** | Unified score + graph submission and trust query API |
99
- | **Rollback** | Compensation and rollback execution manager |
100
- | **Anchor** | Multi-chain proof anchoring (Base/BSC/Solana/Mock) |
101
- | **Orchestrator** | High-level API wiring task delegation/execution/verify |
102
- | **Service** | HTTP API for score + graph queries with JSON persistence |
103
- | **Audit** | Thinking verification with tiered strategy (Gateway → Ollama → Rule) |
104
-
105
- ## Audit System
106
-
107
- ATEL includes a comprehensive audit system for verifying agent thinking processes:
108
-
109
- ### Tiered Verification Strategy
110
-
111
- ```
112
- ┌─────────────────────────────────────────────┐
113
- │ Audit Verification │
114
- ├─────────────────────────────────────────────┤
115
- │ 1. Gateway (OpenClaw) ← Primary │
116
- │ 2. Ollama (Local LLM) ← Fallback │
117
- │ 3. Rule-Based ← Last Resort │
118
- └─────────────────────────────────────────────┘
119
- ```
120
-
121
- **Features:**
122
- - **Auto-initialization**: Ollama service starts automatically on agent startup
123
- - **Model management**: Automatic download of `qwen2.5:0.5b` (397MB) if missing
124
- - **Non-blocking**: Audit runs asynchronously, never blocks task completion
125
- - **Graceful degradation**: Falls back to simpler verification if advanced methods fail
126
-
127
- **Verification Levels:**
128
- 1. **Gateway**: Uses OpenClaw Gateway to call large language models
129
- 2. **Ollama**: Local LLM inference for offline verification
130
- 3. **Rule**: Keyword-based pattern matching (always available)
131
-
132
- See [docs/AUDIT_SERVICE.md](docs/AUDIT_SERVICE.md) for implementation details.
133
-
134
- ## Trust Modes
135
-
136
- ATEL supports two deployment modes that can coexist:
137
-
138
- - `Local Mode` (default): execute, prove, verify, and score locally with no network dependency.
139
- - `Network Mode` (optional): keep local trust updates, and additionally sync summaries to a shared trust service.
140
-
141
- This means local capability is never removed when network trust is enabled.
142
-
143
- ## API Reference
144
-
145
- Detailed API guide: `docs/API.md`
146
- Start here (one-page onboarding): `docs/START-HERE.md`
147
- 5-minute quickstart: `docs/QUICKSTART-5MIN.md`
148
- Phase 0.5 runbook: `docs/PHASE-0.5.md`
149
- Service deployment: `docs/SERVICE-DEPLOY.md`
150
- Status & Ollama features: `docs/STATUS_AND_OLLAMA_FEATURE.md`
151
-
152
- ATEL skill package: `skills/atel/SKILL.md`
153
-
154
- ### CLI Commands
155
-
156
- **System Management:**
91
+ | **Identity** | Ed25519 keypairs, DID creation, signing & verification |
92
+ | **Schema** | Task and capability schemas, validation, matching |
93
+ | **Policy** | Consent tokens, policy engine with call tracking |
94
+ | **Gateway** | Tool invocation gateway with policy enforcement |
95
+ | **Trace** | Append-only, hash-chained execution log |
96
+ | **Proof** | Merkle-tree proof bundles with verification |
97
+ | **Score** | Local trust-score computation |
98
+ | **Graph** | Multi-dimensional trust graph |
99
+ | **TrustManager** | Unified score + graph API |
100
+ | **Rollback** | Compensation and rollback execution |
101
+ | **Anchor** | Multi-chain proof anchoring |
102
+ | **Orchestrator** | High-level task delegation API |
103
+ | **Service** | HTTP API for trust queries |
104
+
105
+ ## CLI Commands
106
+
107
+ ### System Management
157
108
  ```bash
158
109
  atel init [name] # Create agent identity
159
110
  atel info # Show identity and configuration
160
- atel status # Check system health (NEW in v0.9.0)
161
- atel status --json # JSON output for monitoring
162
- ```
163
-
164
- **Network Setup:**
165
- ```bash
166
- atel setup [port] # Configure network (IP, UPnP, verify)
167
- atel verify # Verify port reachability
168
- atel start [port] # Start agent endpoint (auto-init Ollama)
111
+ atel status # Check system health
112
+ atel start [port] # Start agent endpoint
169
113
  ```
170
114
 
171
- **Registry:**
115
+ ### Friend System
172
116
  ```bash
173
- atel register [name] [caps] # Register on public registry
174
- atel search <capability> # Search for agents
117
+ # Friend Management
118
+ atel friend add <did> [--alias "name"] [--notes "text"]
119
+ atel friend remove <did> [--yes]
120
+ atel friend list [--json]
121
+ atel friend status
122
+ atel friend request <did> [--message "text"]
123
+ atel friend accept <requestId>
124
+ atel friend reject <requestId> [--reason "text"]
125
+ atel friend pending
126
+
127
+ # Temporary Sessions
128
+ atel temp-session allow <did> [--duration 60] [--max-tasks 10]
129
+ atel temp-session revoke <sessionId>
130
+ atel temp-session list [--all]
131
+ atel temp-session status
132
+
133
+ # DID Aliases
134
+ atel alias set <alias> <did>
135
+ atel alias list
136
+ atel alias remove <alias>
137
+
138
+ # Using aliases in commands
139
+ atel friend add @alice --notes "Met at conference"
140
+ atel temp-session allow @bob --duration 120
175
141
  ```
176
142
 
177
- **Task Execution:**
143
+ ### Task Execution
178
144
  ```bash
179
145
  atel task <target> <json> # Delegate task to agent
180
146
  atel result <taskId> <json> # Submit execution result
181
147
  ```
182
148
 
183
- **Trust & Verification:**
149
+ ### Trust & Verification
184
150
  ```bash
185
151
  atel check <did> [risk] # Check agent trust score
186
152
  atel audit <did> <taskId> # Deep audit with trace verification
187
153
  atel verify-proof <tx> <root> # Verify on-chain proof
188
154
  ```
189
155
 
190
- **Account & Trading:**
156
+ ### Registry & Trading
191
157
  ```bash
192
- atel balance # Show account balance
158
+ atel register [name] [caps] # Register on public registry
159
+ atel search <capability> # Search for agents
193
160
  atel order <did> <cap> <price> # Create trade order
194
161
  atel accept <orderId> # Accept order
195
162
  atel complete <orderId> # Mark complete
196
163
  atel confirm <orderId> # Confirm and settle
197
164
  ```
198
165
 
199
- ### Status Command Output
200
-
201
- ```
202
- === ATEL Agent Status ===
203
-
204
- Identity: ✅ did:atel:ed25519:Huqt3hpi...
205
- Agent: ✅ Running (port 14002)
206
- Executor: ✅ Available (http://127.0.0.1:14004)
207
- Gateway: ✅ Connected (http://localhost:18789)
208
- Ollama: ✅ Running (1 models)
209
- Models: qwen2.5:0.5b
210
- Audit: ✅ Enabled (Gateway → Ollama → Rule)
211
- Registry: http://47.251.8.19:8200
212
- Network: ✅ http://43.160.230.129:14002
213
- ```
166
+ ## API Examples
214
167
 
215
- ### Module 1: Identity
168
+ ### Identity & Signing
216
169
 
217
170
  ```typescript
218
- import { AgentIdentity, generateKeyPair, createDID, sign, verify } from '@lawrenceliang-btc/atel-sdk';
171
+ import { AgentIdentity } from '@lawrenceliang-btc/atel-sdk';
219
172
 
220
173
  const agent = new AgentIdentity();
221
- console.log(agent.did); // "did:atel:..."
174
+ console.log(agent.did); // "did:atel:ed25519:..."
222
175
  const sig = agent.sign(payload);
223
176
  const ok = agent.verify(payload, sig);
224
177
  ```
225
178
 
226
- ### Module 2: Schema
179
+ ### Policy Enforcement
227
180
 
228
181
  ```typescript
229
- import { createTask, createCapability, matchTaskToCapability } from '@lawrenceliang-btc/atel-sdk';
230
-
231
- const task = createTask({
232
- issuer: agent.did,
233
- intent: { type: 'flight_search', goal: 'Find flights SIN→HND' },
234
- risk: { level: 'medium' },
235
- });
236
-
237
- const cap = createCapability({
238
- provider: executor.did,
239
- capabilities: [{ type: 'flight_search', description: '...' }],
240
- });
241
-
242
- const match = matchTaskToCapability(task, cap);
243
- ```
244
-
245
- ### Module 3: Policy
246
-
247
- ```typescript
248
- import { mintConsentToken, verifyConsentToken, PolicyEngine } from '@lawrenceliang-btc/atel-sdk';
182
+ import { mintConsentToken, PolicyEngine } from '@lawrenceliang-btc/atel-sdk';
249
183
 
250
184
  const token = mintConsentToken(
251
185
  issuer.did, executor.did,
@@ -255,29 +189,11 @@ const token = mintConsentToken(
255
189
  issuer.secretKey,
256
190
  );
257
191
 
258
- verifyConsentToken(token, issuer.publicKey);
259
-
260
192
  const engine = new PolicyEngine(token);
261
193
  const decision = engine.evaluate(action); // 'allow' | 'deny' | 'needs_confirm'
262
194
  ```
263
195
 
264
- ### Module 4: Gateway
265
-
266
- ```typescript
267
- import { ToolGateway } from '@lawrenceliang-btc/atel-sdk';
268
-
269
- const gateway = new ToolGateway(policyEngine);
270
- gateway.registerTool('http.get', async (input) => { /* ... */ });
271
-
272
- const result = await gateway.callTool({
273
- tool: 'http.get',
274
- input: { url: '...' },
275
- consentToken: '...',
276
- });
277
- // result.output, result.input_hash, result.output_hash
278
- ```
279
-
280
- ### Module 5: Trace
196
+ ### Execution Tracing
281
197
 
282
198
  ```typescript
283
199
  import { ExecutionTrace } from '@lawrenceliang-btc/atel-sdk';
@@ -290,7 +206,7 @@ trace.finalize(result);
290
206
  const { valid, errors } = trace.verify();
291
207
  ```
292
208
 
293
- ### Module 6: Proof
209
+ ### Proof Generation
294
210
 
295
211
  ```typescript
296
212
  import { ProofGenerator, ProofVerifier } from '@lawrenceliang-btc/atel-sdk';
@@ -302,16 +218,16 @@ const report = ProofVerifier.verify(bundle, { trace });
302
218
  // report.valid, report.checks, report.summary
303
219
  ```
304
220
 
305
- ### Module 7: On-Chain Anchoring
221
+ ### On-Chain Anchoring
306
222
 
307
223
  ```typescript
308
- import { SolanaAnchorProvider, BaseAnchorProvider, BSCAnchorProvider } from '@lawrenceliang-btc/atel-sdk';
224
+ import { SolanaAnchorProvider } from '@lawrenceliang-btc/atel-sdk';
309
225
 
310
- // Anchor proof to Solana
311
226
  const solana = new SolanaAnchorProvider({
312
227
  rpcUrl: 'https://api.mainnet-beta.solana.com',
313
228
  privateKey: process.env.ATEL_SOLANA_PRIVATE_KEY
314
229
  });
230
+
315
231
  const result = await solana.anchor(traceRoot, {
316
232
  executorDid: 'did:atel:ed25519:...',
317
233
  requesterDid: 'did:atel:ed25519:...',
@@ -319,83 +235,77 @@ const result = await solana.anchor(traceRoot, {
319
235
  });
320
236
  // result.txHash, result.blockNumber
321
237
 
322
- // Verify on-chain anchor
323
238
  const verified = await solana.verify(traceRoot, txHash);
324
239
  // verified.valid, verified.detail
325
240
  ```
326
241
 
327
- **Supported Chains:**
328
- - Solana (Memo Program)
329
- - Base (L2)
330
- - BSC (Binance Smart Chain)
242
+ ## Trust Score Formula
331
243
 
332
- **On-Chain Format (v2):**
333
244
  ```
334
- ATEL:1:executorDID:requesterDID:taskId:traceRoot
245
+ base = success_rate × 60
246
+ volume = min(total_tasks / 100, 1) × 15
247
+ risk_bonus = (high_risk_successes / total) × 15
248
+ consistency = (1 − violation_rate) × 10
249
+ ─────────────────────────────────────────
250
+ score = base + volume + risk_bonus + consistency (clamped 0–100)
335
251
  ```
336
252
 
337
- Example:
338
- ```
339
- ATEL:1:did:atel:ed25519:ABC...:did:atel:ed25519:XYZ...:task-123:6776dd40b1aa3e1cc8d4f713c83d13ecb6b92aade817c9ef073a7607c6fe63d0
340
- ```
253
+ ## P2P Friend System
341
254
 
342
- **Environment Variables:**
343
- - `ATEL_SOLANA_PRIVATE_KEY` - Solana wallet private key (base58)
344
- - `ATEL_SOLANA_RPC_URL` - Solana RPC endpoint (default: mainnet-beta)
345
- - `ATEL_BASE_PRIVATE_KEY` - Base chain private key (hex)
346
- - `ATEL_BASE_RPC_URL` - Base RPC endpoint (default: https://mainnet.base.org)
347
- - `ATEL_BSC_PRIVATE_KEY` - BSC private key (hex)
348
- - `ATEL_BSC_RPC_URL` - BSC RPC endpoint (default: https://bsc-dataseed.binance.org)
255
+ ### Access Control Modes
349
256
 
350
- ### Module 8: Score
257
+ - **friends_only** (default): Only friends can send tasks
258
+ - **open**: Anyone can send tasks (legacy behavior)
259
+ - **blacklist**: Blocked DIDs cannot send tasks
351
260
 
352
- ```typescript
353
- import { TrustScoreClient } from '@lawrenceliang-btc/atel-sdk';
261
+ ### Temporary Sessions
354
262
 
355
- const client = new TrustScoreClient();
356
- client.submitExecutionSummary({ executor: did, task_id, success: true, ... });
263
+ Grant temporary access to non-friends:
264
+ - Duration limits: 1-1440 minutes
265
+ - Task count limits: 1-100 tasks
266
+ - Automatic expiration and cleanup
357
267
 
358
- const report = client.getAgentScore(did);
359
- // report.trust_score (0-100), report.risk_flags, etc.
360
- ```
268
+ ### Security Features
361
269
 
362
- ## Trust Score Formula
270
+ - DID format validation
271
+ - Secure random ID generation (crypto.randomBytes)
272
+ - Rate limiting (10 friend requests per hour per DID)
273
+ - In-memory cache with TTL (friends: 60s, temp sessions: 30s)
363
274
 
364
- ```
365
- base = success_rate × 60
366
- volume = min(total_tasks / 100, 1) × 15
367
- risk_bonus = (high_risk_successes / total) × 15
368
- consistency = (1 violation_rate) × 10
369
- ─────────────────────────────────────────
370
- score = base + volume + risk_bonus + consistency (clamped 0–100)
371
- ```
275
+ ### Data Files
276
+
277
+ Friend system data is stored in `.atel/`:
278
+ - `friends.json` - Friend list with metadata
279
+ - `friend-requests.json` - Pending friend requests
280
+ - `temp-sessions.json` - Temporary session grants
281
+ - `aliases.json` - DID aliases
282
+
283
+ ## Documentation
284
+
285
+ - [docs/START-HERE.md](docs/START-HERE.md) — One-page onboarding
286
+ - [docs/QUICKSTART-5MIN.md](docs/QUICKSTART-5MIN.md) — 5-minute quickstart
287
+ - [docs/API.md](docs/API.md) — Detailed API guide
288
+ - [docs/AUDIT_SERVICE.md](docs/AUDIT_SERVICE.md) — Audit system guide
289
+ - [docs/builtin-executor-guide.md](docs/builtin-executor-guide.md) — Built-in executor guide
290
+ - [docs/protocol-specification.md](docs/protocol-specification.md) — Protocol specification
291
+
292
+ ## Environment Variables
293
+
294
+ **On-Chain Anchoring:**
295
+ - `ATEL_SOLANA_PRIVATE_KEY` - Solana wallet private key (base58)
296
+ - `ATEL_SOLANA_RPC_URL` - Solana RPC endpoint
297
+ - `ATEL_BASE_PRIVATE_KEY` - Base chain private key (hex)
298
+ - `ATEL_BASE_RPC_URL` - Base RPC endpoint
299
+ - `ATEL_BSC_PRIVATE_KEY` - BSC private key (hex)
300
+ - `ATEL_BSC_RPC_URL` - BSC RPC endpoint
372
301
 
373
- ## Current Status (2026-03-13)
302
+ ## Current Status
374
303
 
375
304
  - [x] **Phase 0 MVP complete** — 13 modules implemented, core trust workflow end-to-end
376
- - [x] **241 tests in suite** — unit/integration coverage across modules
377
- - [x] **Demo coverage** — success path + failure scenarios
378
- - [x] **Audit system** — Thinking verification with tiered strategy (Gateway → Ollama → Rule)
379
- - [x] **v0.9.0 released** — Status command, Ollama auto-init, enhanced monitoring
305
+ - [x] **241 tests in suite** — Unit/integration coverage across modules
306
+ - [x] **P2P friend system** — Relationship-based access control with temporary sessions
307
+ - [x] **Audit system** — CoT reasoning verification with local LLM
380
308
  - [x] **Production deployment** — Platform + SDK deployed and tested
381
- - [ ] **Phase 0.5 validation** — real agents + real external tools + real testnet anchoring
382
-
383
- ## Recent Updates
384
-
385
- ### v0.9.0 (2026-03-13)
386
- - ✅ Added `atel status` command for system health monitoring
387
- - ✅ Automatic Ollama service initialization on agent startup
388
- - ✅ Auto-download of `qwen2.5:0.5b` model (397MB)
389
- - ✅ Visual status indicators (✅/❌/⚠️)
390
- - ✅ JSON output support for programmatic monitoring
391
- - ✅ Repository cleanup (removed sensitive data and internal reports)
392
-
393
- ### v0.8.x (2026-03-12)
394
- - ✅ Implemented comprehensive audit system
395
- - ✅ Tiered verification strategy (Gateway → Ollama → Rule)
396
- - ✅ Async audit queue with retry mechanism
397
- - ✅ Security fixes (shell injection, promise rejection handling)
398
- - ✅ Platform integration with thinking verification
399
309
 
400
310
  ## Roadmap
401
311
 
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Attachment CLI Helpers - Platform API Version
4
+ *
5
+ * Helper functions for processing attachments in CLI commands.
6
+ */
7
+
8
+ import { processImage, uploadAttachment } from '../dist/attachment/index.js';
9
+
10
+ /**
11
+ * Parse attachment flags from command line arguments
12
+ */
13
+ export function parseAttachmentFlags(args) {
14
+ const images = [];
15
+ const files = [];
16
+ const audios = [];
17
+ const videos = [];
18
+
19
+ for (let i = 0; i < args.length; i++) {
20
+ if (args[i] === '--image' && args[i + 1]) {
21
+ images.push(args[i + 1]);
22
+ i++;
23
+ } else if (args[i] === '--file' && args[i + 1]) {
24
+ files.push(args[i + 1]);
25
+ i++;
26
+ } else if (args[i] === '--audio' && args[i + 1]) {
27
+ audios.push(args[i + 1]);
28
+ i++;
29
+ } else if (args[i] === '--video' && args[i + 1]) {
30
+ videos.push(args[i + 1]);
31
+ i++;
32
+ }
33
+ }
34
+
35
+ return { images, files, audios, videos };
36
+ }
37
+
38
+ /**
39
+ * Process attachments for a task
40
+ */
41
+ export async function processAttachments(attachmentFlags, uploadedBy, taskId) {
42
+ const images = [];
43
+ const attachments = [];
44
+
45
+ // Process images
46
+ for (const imagePath of attachmentFlags.images) {
47
+ try {
48
+ console.log(`Processing image: ${imagePath}...`);
49
+ const result = await processImage(imagePath, {
50
+ kind: 'image',
51
+ uploadedBy,
52
+ taskId,
53
+ });
54
+ images.push(result);
55
+
56
+ if (result.kind === 'inline') {
57
+ console.log(` ✓ Inlined (${result.size} bytes)`);
58
+ } else {
59
+ console.log(` ✓ Uploaded (${result.attachmentId})`);
60
+ }
61
+ } catch (error) {
62
+ console.error(` ✗ Failed: ${error.message}`);
63
+ throw error;
64
+ }
65
+ }
66
+
67
+ // Process files
68
+ for (const filePath of attachmentFlags.files) {
69
+ try {
70
+ console.log(`Uploading file: ${filePath}...`);
71
+ const result = await uploadAttachment(filePath, {
72
+ kind: 'file',
73
+ uploadedBy,
74
+ taskId,
75
+ });
76
+ attachments.push(result);
77
+ console.log(` ✓ Uploaded (${result.attachmentId})`);
78
+ } catch (error) {
79
+ console.error(` ✗ Failed: ${error.message}`);
80
+ throw error;
81
+ }
82
+ }
83
+
84
+ // Process audio
85
+ for (const audioPath of attachmentFlags.audios) {
86
+ try {
87
+ console.log(`Uploading audio: ${audioPath}...`);
88
+ const result = await uploadAttachment(audioPath, {
89
+ kind: 'audio',
90
+ uploadedBy,
91
+ taskId,
92
+ });
93
+ attachments.push(result);
94
+ console.log(` ✓ Uploaded (${result.attachmentId})`);
95
+ } catch (error) {
96
+ console.error(` ✗ Failed: ${error.message}`);
97
+ throw error;
98
+ }
99
+ }
100
+
101
+ // Process video
102
+ for (const videoPath of attachmentFlags.videos) {
103
+ try {
104
+ console.log(`Uploading video: ${videoPath}...`);
105
+ const result = await uploadAttachment(videoPath, {
106
+ kind: 'video',
107
+ uploadedBy,
108
+ taskId,
109
+ });
110
+ attachments.push(result);
111
+ console.log(` ✓ Uploaded (${result.attachmentId})`);
112
+ } catch (error) {
113
+ console.error(` ✗ Failed: ${error.message}`);
114
+ throw error;
115
+ }
116
+ }
117
+
118
+ return { images, attachments };
119
+ }
120
+
121
+ export { processImage, uploadAttachment };