sootradhaar-agent-sdk 0.0.0-stage → 1.0.2
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 +70 -2
- package/lib/auth.js +81 -0
- package/lib/dispatcher.js +129 -0
- package/lib/envelope.js +139 -0
- package/lib/index.js +333 -0
- package/lib/llm-client.js +127 -0
- package/lib/schemas/communication.json +173 -0
- package/lib/validator.js +145 -0
- package/package.json +7 -4
package/README.md
CHANGED
|
@@ -1,3 +1,71 @@
|
|
|
1
|
-
#
|
|
1
|
+
# sootradhaar-agent-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official Agent SDK for the Sootradhaar multi-agent orchestration system.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install sootradhaar-agent-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires Node.js >= 18.
|
|
12
|
+
|
|
13
|
+
## Quick Start
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
const { createAgent, registerTool, SDK_SCHEMA_VERSION } = require('sootradhaar-agent-sdk')
|
|
17
|
+
|
|
18
|
+
createAgent({
|
|
19
|
+
name: 'my-agent',
|
|
20
|
+
version: '1.0.0',
|
|
21
|
+
schemaVersion: SDK_SCHEMA_VERSION,
|
|
22
|
+
description: 'What this agent does',
|
|
23
|
+
capabilities: {
|
|
24
|
+
inputs: [{ field: 'input_field', type: 'string', required: true }],
|
|
25
|
+
outputs: [{ field: 'output_field', type: 'string' }]
|
|
26
|
+
},
|
|
27
|
+
async handler({ objective, inputs }) {
|
|
28
|
+
return { output_field: 'result' }
|
|
29
|
+
}
|
|
30
|
+
}).listen(process.env.PORT || 3001)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Public API
|
|
34
|
+
|
|
35
|
+
- `createAgent(config)` — starts the Express server, wires POST /auth, GET /, POST /task. Returns the Express app (call `.listen(port)` to start).
|
|
36
|
+
- `registerTool(name, description, handlerFn)` — registers a named tool handler. Must be called before `createAgent`.
|
|
37
|
+
- `SDK_SCHEMA_VERSION` — string constant matching the bundled communication schema version.
|
|
38
|
+
|
|
39
|
+
## Semver Contract
|
|
40
|
+
|
|
41
|
+
| Bump | Meaning |
|
|
42
|
+
|------|---------|
|
|
43
|
+
| **major** | Breaking change to the auth flow or communication schema. Requires agent re-deployment and potentially re-onboarding. |
|
|
44
|
+
| **minor** | New developer-facing helpers or optional features. Backward-compatible. |
|
|
45
|
+
| **patch** | Bug fixes with no API change. |
|
|
46
|
+
|
|
47
|
+
A major version bump signals that existing agents must update and re-deploy. If the communication schema changes at a major version, agents may need to re-onboard through the Sootradhaar dashboard.
|
|
48
|
+
|
|
49
|
+
## Environment Variables
|
|
50
|
+
|
|
51
|
+
| Variable | Required | Default | Description |
|
|
52
|
+
|---|---|---|---|
|
|
53
|
+
| `AGENT_CLIENT_ID` | Yes | — | Agent client ID provisioned at onboarding |
|
|
54
|
+
| `AGENT_CLIENT_SECRET` | Yes | — | HMAC signing key provisioned at onboarding |
|
|
55
|
+
| `ORCHESTRATOR_HOST` | Yes | — | Base URL of the Sootradhaar orchestrator |
|
|
56
|
+
| `SDK_HANDLER_TIMEOUT_MS` | No | 25000 | Handler timeout in milliseconds |
|
|
57
|
+
| `SDK_RESPONSE_MAX_RETRIES` | No | 4 | Max retry attempts for response delivery |
|
|
58
|
+
| `PORT` | No | 3001 | HTTP port the agent server listens on |
|
|
59
|
+
| `AGENT_SDK_LLM_PROVIDER` | No | — | LLM provider for tool-matching (not yet implemented) |
|
|
60
|
+
|
|
61
|
+
## Routes
|
|
62
|
+
|
|
63
|
+
The SDK exposes three routes on the Express server:
|
|
64
|
+
|
|
65
|
+
- `POST /auth` — authenticates the orchestrator via client_id/client_secret, returns a dispatch token.
|
|
66
|
+
- `GET /` — returns agent metadata (token-gated).
|
|
67
|
+
- `POST /task` — receives task dispatches from the orchestrator (token-gated, fires handler async, acks immediately).
|
|
68
|
+
|
|
69
|
+
## License
|
|
70
|
+
|
|
71
|
+
MIT
|
package/lib/auth.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// @capability CAP-010 | Agent SDK Package
|
|
2
|
+
// @intent HMAC token minting, verification, and constant-time comparison for agent dispatch tokens
|
|
3
|
+
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
const crypto = require('crypto');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* timingSafeCompare — constant-time string comparison.
|
|
10
|
+
* Returns false immediately if lengths differ (does NOT throw).
|
|
11
|
+
* @param {string} a
|
|
12
|
+
* @param {string} b
|
|
13
|
+
* @returns {boolean}
|
|
14
|
+
*/
|
|
15
|
+
function timingSafeCompare(a, b) {
|
|
16
|
+
const bufA = Buffer.from(a);
|
|
17
|
+
const bufB = Buffer.from(b);
|
|
18
|
+
if (bufA.length !== bufB.length) return false;
|
|
19
|
+
return crypto.timingSafeEqual(bufA, bufB);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* mintToken — mint an HMAC-signed dispatch token.
|
|
24
|
+
* Token format: base64url(headerJSON).base64url(HMAC_SHA256(base64url(headerJSON), signingKeyHex))
|
|
25
|
+
* @contract input: { scope: string, signingKeyHex: string, ttlSeconds?: number } → output: string token
|
|
26
|
+
* @param {string} scope
|
|
27
|
+
* @param {string} signingKeyHex — hex-encoded HMAC signing key
|
|
28
|
+
* @param {number} [ttlSeconds=600] — token lifetime in seconds (default 10 minutes, hardcoded per spec)
|
|
29
|
+
* @returns {string}
|
|
30
|
+
*/
|
|
31
|
+
function mintToken(scope, signingKeyHex, ttlSeconds = 600) {
|
|
32
|
+
const iat = Math.floor(Date.now() / 1000);
|
|
33
|
+
const headerPart = Buffer.from(JSON.stringify({ scope, iat, exp: iat + ttlSeconds })).toString('base64url');
|
|
34
|
+
const sig = crypto
|
|
35
|
+
.createHmac('sha256', Buffer.from(signingKeyHex, 'hex'))
|
|
36
|
+
.update(headerPart)
|
|
37
|
+
.digest('base64url');
|
|
38
|
+
return headerPart + '.' + sig;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* verifyToken — verify an HMAC-signed dispatch token.
|
|
43
|
+
* @contract input: { tokenStr: string, signingKeyHex: string } → output: { valid: boolean, payload?, reason? }
|
|
44
|
+
* @param {string} tokenStr
|
|
45
|
+
* @param {string} signingKeyHex
|
|
46
|
+
* @returns {{ valid: boolean, payload?: { scope: string, iat: number, exp: number }, reason?: string }}
|
|
47
|
+
*/
|
|
48
|
+
function verifyToken(tokenStr, signingKeyHex) {
|
|
49
|
+
if (typeof tokenStr !== 'string') return { valid: false, reason: 'malformed' };
|
|
50
|
+
|
|
51
|
+
const parts = tokenStr.split('.');
|
|
52
|
+
if (parts.length !== 2) return { valid: false, reason: 'malformed' };
|
|
53
|
+
|
|
54
|
+
const [headerPart, receivedSig] = parts;
|
|
55
|
+
|
|
56
|
+
const expectedSig = crypto
|
|
57
|
+
.createHmac('sha256', Buffer.from(signingKeyHex, 'hex'))
|
|
58
|
+
.update(headerPart)
|
|
59
|
+
.digest('base64url');
|
|
60
|
+
|
|
61
|
+
if (!timingSafeCompare(expectedSig, receivedSig)) {
|
|
62
|
+
return { valid: false, reason: 'signature_mismatch' };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let payload;
|
|
66
|
+
try {
|
|
67
|
+
payload = JSON.parse(Buffer.from(headerPart, 'base64url').toString('utf8'));
|
|
68
|
+
} catch {
|
|
69
|
+
return { valid: false, reason: 'malformed' };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const { scope, iat, exp } = payload;
|
|
73
|
+
|
|
74
|
+
if (typeof exp !== 'number' || exp <= Math.floor(Date.now() / 1000)) {
|
|
75
|
+
return { valid: false, reason: 'expired' };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return { valid: true, payload: { scope, iat, exp } };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = { mintToken, verifyToken, timingSafeCompare };
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// @capability CAP-010 | Agent SDK Package
|
|
2
|
+
// @intent Tool dispatch algorithm — exact match, substring match, LLM match, default handler, no-match
|
|
3
|
+
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* dispatch — route an objective to the best-matching tool handler.
|
|
8
|
+
*
|
|
9
|
+
* Algorithm (in order):
|
|
10
|
+
* 1. Exact match: tool.name.toLowerCase() === objective.toLowerCase()
|
|
11
|
+
* 2. Longest-substring match: collect tools whose name appears as substring in objective (case-insensitive);
|
|
12
|
+
* pick the one with the longest name.
|
|
13
|
+
* 3. LLM match: if AGENT_SDK_LLM_PROVIDER is set, log warning and skip (not yet implemented).
|
|
14
|
+
* 4. Default handler: if defaultHandler provided, call it with { objective, inputs }.
|
|
15
|
+
* 5. No match: return { failed: true, reason: `no_tool_matched: ${objective}` }.
|
|
16
|
+
*
|
|
17
|
+
* @contract input: { objective, inputs, toolRegistry, defaultHandler } → output: Promise<{ outputs }|{ failed, reason }>
|
|
18
|
+
* @param {string} objective
|
|
19
|
+
* @param {object} inputs
|
|
20
|
+
* @param {Map<string, { description: string, handler: Function }>} toolRegistry
|
|
21
|
+
* @param {Function|null} defaultHandler
|
|
22
|
+
* @returns {Promise<{ outputs: object }|{ failed: true, reason: string }>}
|
|
23
|
+
*/
|
|
24
|
+
async function dispatch(objective, inputs, toolRegistry, defaultHandler) {
|
|
25
|
+
const objLower = objective.toLowerCase();
|
|
26
|
+
|
|
27
|
+
// --- Step 1: Exact match ---
|
|
28
|
+
for (const [name, entry] of toolRegistry) {
|
|
29
|
+
if (name.toLowerCase() === objLower) {
|
|
30
|
+
try {
|
|
31
|
+
const result = await entry.handler({ objective, inputs });
|
|
32
|
+
return { outputs: result };
|
|
33
|
+
} catch (err) {
|
|
34
|
+
return { failed: true, reason: err.message, handlerException: true, toolName: name };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// --- Step 2: Longest-substring match ---
|
|
40
|
+
let bestMatch = null;
|
|
41
|
+
let bestMatchLen = -1;
|
|
42
|
+
for (const [name, entry] of toolRegistry) {
|
|
43
|
+
if (objLower.includes(name.toLowerCase())) {
|
|
44
|
+
if (name.length > bestMatchLen) {
|
|
45
|
+
bestMatchLen = name.length;
|
|
46
|
+
bestMatch = { name, entry };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (bestMatch !== null) {
|
|
51
|
+
try {
|
|
52
|
+
const result = await bestMatch.entry.handler({ objective, inputs });
|
|
53
|
+
return { outputs: result };
|
|
54
|
+
} catch (err) {
|
|
55
|
+
return { failed: true, reason: err.message, handlerException: true, toolName: bestMatch.name };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// --- Step 3: LLM match ---
|
|
60
|
+
if (process.env.AGENT_SDK_LLM_PROVIDER) {
|
|
61
|
+
try {
|
|
62
|
+
let llmUrl;
|
|
63
|
+
try {
|
|
64
|
+
llmUrl = new URL(process.env.AGENT_SDK_LLM_PROVIDER);
|
|
65
|
+
} catch (_) {
|
|
66
|
+
console.warn('sdk: LLM tool-match failed: invalid URL — falling through to default');
|
|
67
|
+
llmUrl = null;
|
|
68
|
+
}
|
|
69
|
+
if (llmUrl) {
|
|
70
|
+
const toolList = Array.from(toolRegistry.entries()).map(([name, t]) => ({ name, description: t.description }));
|
|
71
|
+
const reqBody = JSON.stringify({ objective, tools: toolList });
|
|
72
|
+
const llmResult = await new Promise((resolve, reject) => {
|
|
73
|
+
const lib = llmUrl.protocol === 'https:' ? require('https') : require('http');
|
|
74
|
+
const opts = {
|
|
75
|
+
hostname: llmUrl.hostname,
|
|
76
|
+
port: llmUrl.port || (llmUrl.protocol === 'https:' ? 443 : 80),
|
|
77
|
+
path: llmUrl.pathname + (llmUrl.search || ''),
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(reqBody) },
|
|
80
|
+
};
|
|
81
|
+
const req = lib.request(opts, (res) => {
|
|
82
|
+
let data = '';
|
|
83
|
+
res.on('data', (chunk) => { data += chunk; });
|
|
84
|
+
res.on('end', () => {
|
|
85
|
+
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
86
|
+
try { resolve(JSON.parse(data)); } catch (e) { reject(new Error('invalid JSON response')); }
|
|
87
|
+
} else {
|
|
88
|
+
reject(new Error('HTTP ' + res.statusCode));
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
req.setTimeout(5000, () => { req.destroy(new Error('LLM request timeout')); });
|
|
93
|
+
req.on('error', reject);
|
|
94
|
+
req.write(reqBody);
|
|
95
|
+
req.end();
|
|
96
|
+
});
|
|
97
|
+
const matchedName = llmResult && llmResult.tool_name;
|
|
98
|
+
const llmTool = matchedName && toolRegistry.get(matchedName);
|
|
99
|
+
if (llmTool) {
|
|
100
|
+
try {
|
|
101
|
+
const result = await llmTool.handler({ objective, inputs });
|
|
102
|
+
return { outputs: result };
|
|
103
|
+
} catch (err) {
|
|
104
|
+
return { failed: true, reason: err.message, handlerException: true, toolName: matchedName };
|
|
105
|
+
}
|
|
106
|
+
} else {
|
|
107
|
+
console.warn('sdk: LLM tool-match failed: tool not found in registry — falling through to default');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
} catch (err) {
|
|
111
|
+
console.warn('sdk: LLM tool-match failed: ' + err.message + ' — falling through to default');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// --- Step 4: Default handler ---
|
|
116
|
+
if (typeof defaultHandler === 'function') {
|
|
117
|
+
try {
|
|
118
|
+
const result = await defaultHandler({ objective, inputs });
|
|
119
|
+
return { outputs: result };
|
|
120
|
+
} catch (err) {
|
|
121
|
+
return { failed: true, reason: err.message, handlerException: true, toolName: 'default' };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// --- Step 5: No match ---
|
|
126
|
+
return { failed: true, reason: `no_tool_matched: ${objective}` };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
module.exports = { dispatch };
|
package/lib/envelope.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// @capability CAP-010 | Agent SDK Package
|
|
2
|
+
// @intent Builds agent response envelopes and POSTs them to the orchestrator with retry/backoff
|
|
3
|
+
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
const https = require('https');
|
|
7
|
+
const http = require('http');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* buildResponse — construct an agent response object.
|
|
11
|
+
* @contract input: { taskId, sessionId, status, outputs, failureReason, entities } → output: plain response object
|
|
12
|
+
* @param {string} taskId
|
|
13
|
+
* @param {string} sessionId
|
|
14
|
+
* @param {'completed'|'failed'} status
|
|
15
|
+
* @param {object} outputs
|
|
16
|
+
* @param {string|null} failureReason
|
|
17
|
+
* @param {string[]} entities
|
|
18
|
+
* @returns {object}
|
|
19
|
+
*/
|
|
20
|
+
function buildResponse(taskId, sessionId, status, outputs, failureReason, entities) {
|
|
21
|
+
return {
|
|
22
|
+
task_id: taskId,
|
|
23
|
+
session_id: sessionId,
|
|
24
|
+
status: status,
|
|
25
|
+
outputs: outputs || {},
|
|
26
|
+
failure_reason: failureReason || null,
|
|
27
|
+
entities: entities || [],
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* _sleep — returns a Promise that resolves after ms milliseconds.
|
|
33
|
+
* @param {number} ms
|
|
34
|
+
* @returns {Promise<void>}
|
|
35
|
+
*/
|
|
36
|
+
function _sleep(ms) {
|
|
37
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* _httpPost — perform a single HTTP/HTTPS POST using Node built-ins.
|
|
42
|
+
* @param {string} url
|
|
43
|
+
* @param {string} bearerToken
|
|
44
|
+
* @param {object} body
|
|
45
|
+
* @returns {Promise<{ statusCode: number }>}
|
|
46
|
+
*/
|
|
47
|
+
function _httpPost(url, bearerToken, body) {
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const parsed = new URL(url);
|
|
50
|
+
const isHttps = parsed.protocol === 'https:';
|
|
51
|
+
const transport = isHttps ? https : http;
|
|
52
|
+
|
|
53
|
+
const bodyStr = JSON.stringify(body);
|
|
54
|
+
const options = {
|
|
55
|
+
hostname: parsed.hostname,
|
|
56
|
+
port: parsed.port || (isHttps ? 443 : 80),
|
|
57
|
+
path: parsed.pathname + (parsed.search || ''),
|
|
58
|
+
method: 'POST',
|
|
59
|
+
headers: {
|
|
60
|
+
'Content-Type': 'application/json',
|
|
61
|
+
'Content-Length': Buffer.byteLength(bodyStr),
|
|
62
|
+
'Authorization': `Bearer ${bearerToken}`,
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const req = transport.request(options, (res) => {
|
|
67
|
+
// Drain the response body to allow connection reuse
|
|
68
|
+
res.resume();
|
|
69
|
+
res.on('end', () => {
|
|
70
|
+
resolve({ statusCode: res.statusCode });
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
req.on('error', reject);
|
|
75
|
+
req.write(bodyStr);
|
|
76
|
+
req.end();
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* postResponse — POST agent response to the orchestrator with exponential-backoff retry.
|
|
82
|
+
* Retry policy:
|
|
83
|
+
* - attempt 1: immediate
|
|
84
|
+
* - before attempt 2: 1000ms delay
|
|
85
|
+
* - before attempt 3: 2000ms delay
|
|
86
|
+
* - before attempt 4: 4000ms delay
|
|
87
|
+
* Non-retryable: HTTP 401 (auth failed), HTTP 400 (validation error).
|
|
88
|
+
* Retryable: network errors, HTTP 5xx, HTTP 503.
|
|
89
|
+
*
|
|
90
|
+
* @contract input: { url, responseToken, body, maxRetries? } → output: Promise<void>
|
|
91
|
+
* @param {string} url
|
|
92
|
+
* @param {string} responseToken
|
|
93
|
+
* @param {object} body
|
|
94
|
+
* @param {number} [maxRetries=4]
|
|
95
|
+
* @returns {Promise<void>}
|
|
96
|
+
*/
|
|
97
|
+
async function postResponse(url, responseToken, body, maxRetries = 4) {
|
|
98
|
+
const taskId = (body && body.task_id) || 'unknown';
|
|
99
|
+
const delays = [0, 1000, 2000, 4000, 8000]; // delays[i] = delay before attempt i+1
|
|
100
|
+
|
|
101
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
102
|
+
// Apply delay before each attempt after the first
|
|
103
|
+
if (attempt > 1) {
|
|
104
|
+
const delayMs = delays[attempt - 1] || delays[delays.length - 1];
|
|
105
|
+
await _sleep(delayMs);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
try {
|
|
109
|
+
const { statusCode } = await _httpPost(url, responseToken, body);
|
|
110
|
+
|
|
111
|
+
if (statusCode >= 200 && statusCode < 300) {
|
|
112
|
+
// Success
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (statusCode === 401) {
|
|
117
|
+
console.error(`sdk: response delivery auth failed: ${taskId}`);
|
|
118
|
+
return; // non-retryable
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (statusCode === 400) {
|
|
122
|
+
console.error(`sdk: response delivery validation_error: ${taskId}`);
|
|
123
|
+
return; // non-retryable
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// 5xx or other — retryable; fall through to next attempt
|
|
127
|
+
if (attempt === maxRetries) {
|
|
128
|
+
console.error(`sdk: response delivery failed permanently after ${maxRetries} attempts: ${taskId}`);
|
|
129
|
+
}
|
|
130
|
+
} catch (err) {
|
|
131
|
+
// Network error — retryable
|
|
132
|
+
if (attempt === maxRetries) {
|
|
133
|
+
console.error(`sdk: response delivery failed permanently after ${maxRetries} attempts: ${taskId}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
module.exports = { buildResponse, postResponse };
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// @capability CAP-010 | Agent SDK Package
|
|
2
|
+
// @intent Public API: createAgent(), registerTool(), SDK_SCHEMA_VERSION — wires Express server with auth, metadata, and task dispatch routes
|
|
3
|
+
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const express = require('express');
|
|
8
|
+
|
|
9
|
+
const { mintToken, verifyToken, timingSafeCompare } = require('./auth');
|
|
10
|
+
const { validateInboundTask } = require('./validator');
|
|
11
|
+
const { buildResponse, postResponse } = require('./envelope');
|
|
12
|
+
const { dispatch } = require('./dispatcher');
|
|
13
|
+
const { callLLM } = require('./llm-client');
|
|
14
|
+
|
|
15
|
+
// --- Schema loading ---
|
|
16
|
+
const _schemaPath = path.join(__dirname, 'schemas', 'communication.json');
|
|
17
|
+
let _schema;
|
|
18
|
+
try {
|
|
19
|
+
_schema = require(_schemaPath);
|
|
20
|
+
} catch (err) {
|
|
21
|
+
throw new Error(`sdk: cannot load communication schema at ${_schemaPath}: ${err.message}`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// --- SDK_SCHEMA_VERSION: extracted from $comment field ---
|
|
25
|
+
// $comment format: "schema_version: 1.0"
|
|
26
|
+
let SDK_SCHEMA_VERSION = '1.0';
|
|
27
|
+
if (_schema && typeof _schema.$comment === 'string') {
|
|
28
|
+
const match = _schema.$comment.match(/schema_version:\s*([\d.]+)/);
|
|
29
|
+
if (match) {
|
|
30
|
+
SDK_SCHEMA_VERSION = match[1];
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// --- Module-level tool registry ---
|
|
35
|
+
// @entry registerTool — module-level tool registration
|
|
36
|
+
const _tools = new Map();
|
|
37
|
+
let _defaultHandler = null;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* registerTool — register a named tool handler.
|
|
41
|
+
* Must be called before createAgent.
|
|
42
|
+
* @contract input: { name: string, description: string, handlerFn: Function } → output: void | throws
|
|
43
|
+
* @param {string} name
|
|
44
|
+
* @param {string} description
|
|
45
|
+
* @param {Function} handlerFn
|
|
46
|
+
*/
|
|
47
|
+
function registerTool(name, description, handlerFn) {
|
|
48
|
+
if (!name) throw new Error("registerTool: missing argument 'name'");
|
|
49
|
+
if (!description) throw new Error("registerTool: missing argument 'description'");
|
|
50
|
+
if (!handlerFn) throw new Error("registerTool: missing argument 'handlerFn'");
|
|
51
|
+
if (_tools.has(name)) throw new Error(`registerTool: tool '${name}' already registered`);
|
|
52
|
+
_tools.set(name, { description, handler: handlerFn });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// @entry createAgent — builds and returns the Express server
|
|
56
|
+
/**
|
|
57
|
+
* createAgent — validates config, reads env vars, wires Express routes, returns the app (not started).
|
|
58
|
+
* Caller does app.listen(PORT).
|
|
59
|
+
* @contract input: { config } → output: Express app | throws synchronously on config/env errors
|
|
60
|
+
* @param {object} config
|
|
61
|
+
* @returns {import('express').Application}
|
|
62
|
+
*/
|
|
63
|
+
function createAgent(config) {
|
|
64
|
+
// Guard: detect the common mistake of passing the result of createAgent() back into createAgent()
|
|
65
|
+
if (config && typeof config.listen === 'function' && typeof config.use === 'function') {
|
|
66
|
+
throw new Error(
|
|
67
|
+
"createAgent: received an Express app instead of a config object. " +
|
|
68
|
+
"src/agent.js should export a plain config object (module.exports = { name, version, ... }) " +
|
|
69
|
+
"and src/index.js should call createAgent(require('./agent')). " +
|
|
70
|
+
"Do not call createAgent() inside agent.js."
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// --- 1. Validate required config fields ---
|
|
75
|
+
const requiredFields = ['name', 'version', 'schemaVersion', 'description', 'capabilities'];
|
|
76
|
+
for (const field of requiredFields) {
|
|
77
|
+
if (config[field] === undefined || config[field] === null) {
|
|
78
|
+
throw new Error(`createAgent: missing required field '${field}'`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// capabilities must have inputs and outputs arrays
|
|
83
|
+
if (!config.capabilities || !Array.isArray(config.capabilities.inputs) || !Array.isArray(config.capabilities.outputs)) {
|
|
84
|
+
throw new Error("createAgent: missing required field 'capabilities.inputs' or 'capabilities.outputs'");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// --- 2. Check schemaVersion matches bundled schema ---
|
|
88
|
+
if (config.schemaVersion !== SDK_SCHEMA_VERSION) {
|
|
89
|
+
throw new Error(
|
|
90
|
+
`createAgent: schemaVersion mismatch — config declares '${config.schemaVersion}' but SDK bundles '${SDK_SCHEMA_VERSION}'`
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// --- 3. Read required env vars ---
|
|
95
|
+
const clientId = process.env.AGENT_CLIENT_ID;
|
|
96
|
+
if (!clientId) throw new Error("createAgent: missing required env var 'AGENT_CLIENT_ID'");
|
|
97
|
+
|
|
98
|
+
const clientSecret = process.env.AGENT_CLIENT_SECRET;
|
|
99
|
+
if (!clientSecret) throw new Error("createAgent: missing required env var 'AGENT_CLIENT_SECRET'");
|
|
100
|
+
|
|
101
|
+
const orchestratorHost = process.env.ORCHESTRATOR_HOST;
|
|
102
|
+
if (!orchestratorHost) throw new Error("createAgent: missing required env var 'ORCHESTRATOR_HOST'");
|
|
103
|
+
|
|
104
|
+
// Optional env vars
|
|
105
|
+
const handlerTimeoutMs = parseInt(process.env.SDK_HANDLER_TIMEOUT_MS, 10) || 25000;
|
|
106
|
+
const responseMaxRetries = parseInt(process.env.SDK_RESPONSE_MAX_RETRIES, 10) || 4;
|
|
107
|
+
|
|
108
|
+
// Store default handler if provided in config
|
|
109
|
+
if (typeof config.handler === 'function') {
|
|
110
|
+
_defaultHandler = config.handler;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// --- 4. In-memory session state ---
|
|
114
|
+
// Map: session_id → { response_token, dispatch_token }
|
|
115
|
+
const _sessions = new Map();
|
|
116
|
+
|
|
117
|
+
// --- 5. Startup timestamp ---
|
|
118
|
+
const startupTimestamp = new Date().toISOString();
|
|
119
|
+
|
|
120
|
+
// --- 6. Create Express app ---
|
|
121
|
+
const app = express();
|
|
122
|
+
app.use(express.json());
|
|
123
|
+
|
|
124
|
+
// Helper: set CORS header on all responses
|
|
125
|
+
const setCors = (res) => {
|
|
126
|
+
res.setHeader('Access-Control-Allow-Origin', orchestratorHost);
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// =========================================================================
|
|
130
|
+
// POST /auth — orchestrator authenticates and receives a dispatch token
|
|
131
|
+
// @entry POST /auth | authenticates orchestrator and mints dispatch token
|
|
132
|
+
// @contract input: { client_id, client_secret, session_id?, response_token? } → output: { ok, token, expires_in } | errors: [400, 401]
|
|
133
|
+
// =========================================================================
|
|
134
|
+
app.post('/auth', (req, res) => {
|
|
135
|
+
setCors(res);
|
|
136
|
+
const { client_id, client_secret, session_id, response_token } = req.body || {};
|
|
137
|
+
|
|
138
|
+
// Validate presence of credentials
|
|
139
|
+
if (!client_id || !client_secret) {
|
|
140
|
+
return res.status(400).json({ ok: false, error: 'invalid_request' });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Constant-time compare both credentials
|
|
144
|
+
const idMatch = timingSafeCompare(Buffer.from(client_id).toString(), Buffer.from(clientId).toString());
|
|
145
|
+
const secretMatch = timingSafeCompare(Buffer.from(client_secret).toString(), Buffer.from(clientSecret).toString());
|
|
146
|
+
|
|
147
|
+
if (!idMatch || !secretMatch) {
|
|
148
|
+
return res.status(401).json({ ok: false, error: 'invalid_client' });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Determine scope: session_id from body if present, else 'onboarding'
|
|
152
|
+
const scope = session_id || 'onboarding';
|
|
153
|
+
|
|
154
|
+
// Mint a dispatch token (600s hardcoded per spec)
|
|
155
|
+
const dispatchToken = mintToken(scope, clientSecret, 600);
|
|
156
|
+
|
|
157
|
+
// Store response_token if provided
|
|
158
|
+
if (session_id && response_token) {
|
|
159
|
+
_sessions.set(session_id, { response_token, dispatch_token: dispatchToken });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return res.status(200).json({
|
|
163
|
+
ok: true,
|
|
164
|
+
token: dispatchToken,
|
|
165
|
+
expires_in: 600,
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
// =========================================================================
|
|
170
|
+
// GET / — agent metadata endpoint (token-gated)
|
|
171
|
+
// @entry GET / | returns agent metadata; requires valid dispatch token
|
|
172
|
+
// @contract input: { Authorization: Bearer <token> } → output: agent metadata | errors: [401]
|
|
173
|
+
// =========================================================================
|
|
174
|
+
app.get('/', (req, res) => {
|
|
175
|
+
setCors(res);
|
|
176
|
+
const authHeader = req.headers['authorization'] || '';
|
|
177
|
+
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
|
|
178
|
+
|
|
179
|
+
if (!token) {
|
|
180
|
+
return res.status(401).json({ ok: false, error: 'unauthorized' });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const result = verifyToken(token, clientSecret);
|
|
184
|
+
if (!result.valid) {
|
|
185
|
+
return res.status(401).json({ ok: false, error: 'unauthorized' });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Normalize capabilities: add required:false to inputs where not set; strip required from outputs
|
|
189
|
+
const inputs = (config.capabilities.inputs || []).map(f => ({
|
|
190
|
+
field: f.field,
|
|
191
|
+
type: f.type,
|
|
192
|
+
required: typeof f.required === 'boolean' ? f.required : false,
|
|
193
|
+
}));
|
|
194
|
+
const outputs = (config.capabilities.outputs || []).map(f => ({
|
|
195
|
+
field: f.field,
|
|
196
|
+
type: f.type,
|
|
197
|
+
}));
|
|
198
|
+
|
|
199
|
+
return res.status(200).json({
|
|
200
|
+
name: config.name,
|
|
201
|
+
version: config.version,
|
|
202
|
+
description: config.description,
|
|
203
|
+
schemaVersion: SDK_SCHEMA_VERSION,
|
|
204
|
+
capabilities: { inputs, outputs },
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// =========================================================================
|
|
209
|
+
// POST /task — receives a task dispatch from the orchestrator
|
|
210
|
+
// @entry POST /task | authenticates, validates, acks, runs handler async
|
|
211
|
+
// @contract input: { Authorization: Bearer <dispatch_token>, body: CAP-006 envelope } → output: { ok: true } ack | errors: [401, 400]
|
|
212
|
+
// =========================================================================
|
|
213
|
+
app.post('/task', async (req, res) => {
|
|
214
|
+
setCors(res);
|
|
215
|
+
|
|
216
|
+
// --- Step 1: Extract and verify token (FIRST action) ---
|
|
217
|
+
const authHeader = req.headers['authorization'] || '';
|
|
218
|
+
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
|
|
219
|
+
|
|
220
|
+
if (!token) {
|
|
221
|
+
return res.status(401).json({ ok: false, error: 'unauthorized' });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const tokenResult = verifyToken(token, clientSecret);
|
|
225
|
+
if (!tokenResult.valid) {
|
|
226
|
+
return res.status(401).json({ ok: false, error: 'unauthorized', reason: tokenResult.reason });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// --- Step 2: Check scope matches session_id from body ---
|
|
230
|
+
const body = req.body || {};
|
|
231
|
+
const sessionId = body.payload && body.payload.session_id;
|
|
232
|
+
if (tokenResult.payload.scope !== sessionId) {
|
|
233
|
+
return res.status(401).json({ ok: false, error: 'unauthorized', reason: 'scope_mismatch' });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// --- Step 3: Validate inbound message schema ---
|
|
237
|
+
const validation = validateInboundTask(body);
|
|
238
|
+
if (!validation.valid) {
|
|
239
|
+
// Ack with 200 and auto-POST failure response if we can parse task_id/session_id
|
|
240
|
+
const taskId = body.payload && body.payload.task_id;
|
|
241
|
+
const sessId = body.payload && body.payload.session_id;
|
|
242
|
+
|
|
243
|
+
// Send 200 ack first
|
|
244
|
+
res.status(200).json({ ok: true });
|
|
245
|
+
|
|
246
|
+
// Auto-POST failure response
|
|
247
|
+
if (taskId && sessId) {
|
|
248
|
+
const responseToken = _sessions.get(sessId) && _sessions.get(sessId).response_token;
|
|
249
|
+
if (responseToken) {
|
|
250
|
+
const responseUrl = `${orchestratorHost}/api/v1/sessions/${sessId}/tasks/${taskId}/response`;
|
|
251
|
+
const failBody = buildResponse(taskId, sessId, 'failed', {}, `schema_validation_failed: ${validation.errors.join('; ')}`, []);
|
|
252
|
+
postResponse(responseUrl, responseToken, failBody, responseMaxRetries).catch(err => {
|
|
253
|
+
console.error(`sdk: postResponse error for schema failure: ${err.message}`);
|
|
254
|
+
});
|
|
255
|
+
} else {
|
|
256
|
+
console.error(`sdk: missing response_token for session ${sessId} — cannot post schema_validation_failed response`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// --- Step 4: Send 200 ack immediately ---
|
|
263
|
+
res.status(200).json({ ok: true });
|
|
264
|
+
|
|
265
|
+
// --- Step 5: Run handler asynchronously (fire and forget) ---
|
|
266
|
+
setImmediate(async () => {
|
|
267
|
+
const payload = body.payload;
|
|
268
|
+
const taskId = payload.task_id;
|
|
269
|
+
const sessId = payload.session_id;
|
|
270
|
+
const objective = payload.objective;
|
|
271
|
+
const inputs = payload.inputs || {};
|
|
272
|
+
|
|
273
|
+
// Retrieve response_token from sessions map
|
|
274
|
+
const sessionEntry = _sessions.get(sessId);
|
|
275
|
+
if (!sessionEntry || !sessionEntry.response_token) {
|
|
276
|
+
console.error(`sdk: missing response_token for session ${sessId} — cannot post response`);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const responseToken = sessionEntry.response_token;
|
|
280
|
+
const responseUrl = `${orchestratorHost}/api/v1/sessions/${sessId}/tasks/${taskId}/response`;
|
|
281
|
+
|
|
282
|
+
// Build timeout promise
|
|
283
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
284
|
+
setTimeout(() => reject(new Error('handler_timeout')), handlerTimeoutMs);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
let result;
|
|
288
|
+
try {
|
|
289
|
+
result = await Promise.race([
|
|
290
|
+
dispatch(objective, inputs, _tools, _defaultHandler),
|
|
291
|
+
timeoutPromise,
|
|
292
|
+
]);
|
|
293
|
+
} catch (err) {
|
|
294
|
+
// Timeout or unhandled error
|
|
295
|
+
const reason = err.message === 'handler_timeout' ? 'handler_timeout' : `handler_exception: ${err.message}`;
|
|
296
|
+
const toolName = 'default';
|
|
297
|
+
console.error(`handler error: ${toolName}: ${err.message}`, err);
|
|
298
|
+
const failBody = buildResponse(taskId, sessId, 'failed', {}, reason, []);
|
|
299
|
+
await postResponse(responseUrl, responseToken, failBody, responseMaxRetries);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
if (result && result.failed) {
|
|
304
|
+
if (result.handlerException) {
|
|
305
|
+
console.error('handler error: ' + result.toolName + ': ' + result.reason);
|
|
306
|
+
}
|
|
307
|
+
const failureReason = result.handlerException
|
|
308
|
+
? 'handler_exception: ' + result.reason
|
|
309
|
+
: result.reason;
|
|
310
|
+
const failBody = buildResponse(taskId, sessId, 'failed', {}, failureReason, []);
|
|
311
|
+
await postResponse(responseUrl, responseToken, failBody, responseMaxRetries);
|
|
312
|
+
} else {
|
|
313
|
+
const successBody = buildResponse(taskId, sessId, 'completed', result.outputs || {}, null, []);
|
|
314
|
+
await postResponse(responseUrl, responseToken, successBody, responseMaxRetries);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
// Log startup message
|
|
320
|
+
const port = process.env.PORT || 3001;
|
|
321
|
+
// Note: actual listen is called by the caller; we log when the app object is returned
|
|
322
|
+
// The caller does app.listen(PORT, () => ...) — we emit the log on the returned app's listen call
|
|
323
|
+
const originalListen = app.listen.bind(app);
|
|
324
|
+
app.listen = function (...args) {
|
|
325
|
+
const server = originalListen(...args);
|
|
326
|
+
console.log(`Agent ${config.name} listening on port ${port}`);
|
|
327
|
+
return server;
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
return app;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
module.exports = { createAgent, registerTool, SDK_SCHEMA_VERSION, callLLM };
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// @capability CAP-010 | Agent SDK Package
|
|
2
|
+
// @intent Built-in LLM client for agent handlers — reads AGENT_LLM_PROVIDER, AGENT_LLM_MODEL, AGENT_LLM_KEY; supports anthropic, openai, google
|
|
3
|
+
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
const https = require('https');
|
|
7
|
+
|
|
8
|
+
// @contract input: { prompt: string, timeoutMs: number } → output: string | errors: ["timeout", "provider_error", "missing_env"]
|
|
9
|
+
async function callLLM(prompt, timeoutMs = 15000) {
|
|
10
|
+
const provider = process.env.AGENT_LLM_PROVIDER;
|
|
11
|
+
const model = process.env.AGENT_LLM_MODEL;
|
|
12
|
+
const apiKey = process.env.AGENT_LLM_KEY;
|
|
13
|
+
|
|
14
|
+
if (!provider || !model || !apiKey) {
|
|
15
|
+
throw new Error('AGENT_LLM_PROVIDER, AGENT_LLM_MODEL, and AGENT_LLM_KEY must be set');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
19
|
+
setTimeout(() => reject(new Error(`LLM call timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
return Promise.race([_callProvider(provider, model, prompt, apiKey), timeoutPromise]);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function _callProvider(provider, model, prompt, apiKey) {
|
|
26
|
+
if (provider === 'anthropic') return _callAnthropic(model, prompt, apiKey);
|
|
27
|
+
if (provider === 'openai') return _callOpenAI(model, prompt, apiKey);
|
|
28
|
+
if (provider === 'google') return _callGoogle(model, prompt, apiKey);
|
|
29
|
+
throw new Error(`Unsupported AGENT_LLM_PROVIDER: ${provider}. Valid values: anthropic, openai, google`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function _callAnthropic(model, prompt, apiKey) {
|
|
33
|
+
const body = JSON.stringify({
|
|
34
|
+
model,
|
|
35
|
+
max_tokens: 4096,
|
|
36
|
+
messages: [{ role: 'user', content: prompt }],
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
return _httpsPost({
|
|
40
|
+
hostname: 'api.anthropic.com',
|
|
41
|
+
path: '/v1/messages',
|
|
42
|
+
headers: {
|
|
43
|
+
'x-api-key': apiKey,
|
|
44
|
+
'anthropic-version': '2023-06-01',
|
|
45
|
+
},
|
|
46
|
+
}, body, res => {
|
|
47
|
+
if (res.error) throw new Error(res.error.message);
|
|
48
|
+
const content = res.content?.[0]?.text;
|
|
49
|
+
if (!content) throw new Error('Empty response from Anthropic');
|
|
50
|
+
return content;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function _callOpenAI(model, prompt, apiKey) {
|
|
55
|
+
const body = JSON.stringify({
|
|
56
|
+
model,
|
|
57
|
+
messages: [{ role: 'user', content: prompt }],
|
|
58
|
+
temperature: 0,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
return _httpsPost({
|
|
62
|
+
hostname: 'api.openai.com',
|
|
63
|
+
path: '/v1/chat/completions',
|
|
64
|
+
headers: {
|
|
65
|
+
'Authorization': `Bearer ${apiKey}`,
|
|
66
|
+
},
|
|
67
|
+
}, body, res => {
|
|
68
|
+
if (res.error) throw new Error(res.error.message);
|
|
69
|
+
const content = res.choices?.[0]?.message?.content;
|
|
70
|
+
if (!content) throw new Error('Empty response from OpenAI');
|
|
71
|
+
return content;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function _callGoogle(model, prompt, apiKey) {
|
|
76
|
+
const body = JSON.stringify({
|
|
77
|
+
contents: [{ parts: [{ text: prompt }] }],
|
|
78
|
+
generationConfig: { temperature: 0 },
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Gemini REST endpoint: POST /v1beta/models/{model}:generateContent?key={apiKey}
|
|
82
|
+
return _httpsPost({
|
|
83
|
+
hostname: 'generativelanguage.googleapis.com',
|
|
84
|
+
path: `/v1beta/models/${model}:generateContent?key=${apiKey}`,
|
|
85
|
+
headers: {},
|
|
86
|
+
}, body, res => {
|
|
87
|
+
if (res.error) throw new Error(res.error.message);
|
|
88
|
+
const content = res.candidates?.[0]?.content?.parts?.[0]?.text;
|
|
89
|
+
if (!content) throw new Error('Empty response from Google');
|
|
90
|
+
return content;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Shared HTTPS POST helper — avoids repeating the streaming boilerplate
|
|
95
|
+
function _httpsPost(opts, body, extractFn) {
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
const req = https.request(
|
|
98
|
+
{
|
|
99
|
+
hostname: opts.hostname,
|
|
100
|
+
path: opts.path,
|
|
101
|
+
method: 'POST',
|
|
102
|
+
headers: {
|
|
103
|
+
'Content-Type': 'application/json',
|
|
104
|
+
'Content-Length': Buffer.byteLength(body),
|
|
105
|
+
...opts.headers,
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
(res) => {
|
|
109
|
+
let data = '';
|
|
110
|
+
res.on('data', chunk => { data += chunk; });
|
|
111
|
+
res.on('end', () => {
|
|
112
|
+
try {
|
|
113
|
+
const parsed = JSON.parse(data);
|
|
114
|
+
resolve(extractFn(parsed));
|
|
115
|
+
} catch (e) {
|
|
116
|
+
reject(new Error(`${opts.hostname} response error: ${e.message}`));
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
);
|
|
121
|
+
req.on('error', reject);
|
|
122
|
+
req.write(body);
|
|
123
|
+
req.end();
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = { callLLM };
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
|
+
"title": "Sootradhaar Communication Schema v1.0",
|
|
4
|
+
"$comment": "schema_version: 1.0",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"additionalProperties": false,
|
|
7
|
+
"required": ["version", "message_id", "message_type", "sent_at", "payload"],
|
|
8
|
+
"properties": {
|
|
9
|
+
"version": {
|
|
10
|
+
"type": "string",
|
|
11
|
+
"description": "Schema semver string, e.g. '1.0'"
|
|
12
|
+
},
|
|
13
|
+
"message_id": {
|
|
14
|
+
"type": "string",
|
|
15
|
+
"format": "uuid",
|
|
16
|
+
"description": "UUID generated by sender"
|
|
17
|
+
},
|
|
18
|
+
"message_type": {
|
|
19
|
+
"type": "string",
|
|
20
|
+
"enum": ["task_dispatch", "agent_response", "event"]
|
|
21
|
+
},
|
|
22
|
+
"sent_at": {
|
|
23
|
+
"type": "string",
|
|
24
|
+
"format": "date-time",
|
|
25
|
+
"description": "ISO 8601 timestamp"
|
|
26
|
+
},
|
|
27
|
+
"payload": {
|
|
28
|
+
"type": "object",
|
|
29
|
+
"description": "Payload shape determined by message_type"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"definitions": {
|
|
33
|
+
"task_dispatch_payload": {
|
|
34
|
+
"type": "object",
|
|
35
|
+
"additionalProperties": false,
|
|
36
|
+
"required": [
|
|
37
|
+
"task_id",
|
|
38
|
+
"session_id",
|
|
39
|
+
"objective",
|
|
40
|
+
"session_intent",
|
|
41
|
+
"inputs",
|
|
42
|
+
"step_number",
|
|
43
|
+
"total_steps"
|
|
44
|
+
],
|
|
45
|
+
"properties": {
|
|
46
|
+
"task_id": {
|
|
47
|
+
"type": "string",
|
|
48
|
+
"description": "session_task_id, e.g. 'sess-abc-step_1'"
|
|
49
|
+
},
|
|
50
|
+
"session_id": {
|
|
51
|
+
"type": "string"
|
|
52
|
+
},
|
|
53
|
+
"objective": {
|
|
54
|
+
"type": "string",
|
|
55
|
+
"description": "Specific task instruction for this step"
|
|
56
|
+
},
|
|
57
|
+
"session_intent": {
|
|
58
|
+
"type": "string",
|
|
59
|
+
"description": "Top-level workflow intent for context"
|
|
60
|
+
},
|
|
61
|
+
"inputs": {
|
|
62
|
+
"type": "object",
|
|
63
|
+
"description": "Resolved from context-data.json; free-form keys"
|
|
64
|
+
},
|
|
65
|
+
"step_number": {
|
|
66
|
+
"type": "integer",
|
|
67
|
+
"description": "1-based position in plan"
|
|
68
|
+
},
|
|
69
|
+
"total_steps": {
|
|
70
|
+
"type": "integer"
|
|
71
|
+
},
|
|
72
|
+
"rules_constraints": {
|
|
73
|
+
"type": "array",
|
|
74
|
+
"items": {
|
|
75
|
+
"type": "string"
|
|
76
|
+
},
|
|
77
|
+
"description": "Human-readable rule_text strings from RulesMemory"
|
|
78
|
+
},
|
|
79
|
+
"agent_metadata": {
|
|
80
|
+
"type": "object",
|
|
81
|
+
"additionalProperties": false,
|
|
82
|
+
"properties": {
|
|
83
|
+
"agent_id": {
|
|
84
|
+
"type": "string"
|
|
85
|
+
},
|
|
86
|
+
"agent_name": {
|
|
87
|
+
"type": "string"
|
|
88
|
+
},
|
|
89
|
+
"schemaVersion": {
|
|
90
|
+
"type": "string"
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
"agent_response_payload": {
|
|
97
|
+
"type": "object",
|
|
98
|
+
"additionalProperties": false,
|
|
99
|
+
"required": ["task_id", "session_id", "status", "outputs"],
|
|
100
|
+
"properties": {
|
|
101
|
+
"task_id": {
|
|
102
|
+
"type": "string",
|
|
103
|
+
"description": "Must match the task_id from the dispatched task"
|
|
104
|
+
},
|
|
105
|
+
"session_id": {
|
|
106
|
+
"type": "string"
|
|
107
|
+
},
|
|
108
|
+
"status": {
|
|
109
|
+
"type": "string",
|
|
110
|
+
"enum": ["completed", "failed"]
|
|
111
|
+
},
|
|
112
|
+
"outputs": {
|
|
113
|
+
"type": "object",
|
|
114
|
+
"description": "Keys defined by agent's declared capability; free-form"
|
|
115
|
+
},
|
|
116
|
+
"entities": {
|
|
117
|
+
"type": "array",
|
|
118
|
+
"items": {
|
|
119
|
+
"type": "string"
|
|
120
|
+
},
|
|
121
|
+
"description": "Named entities extracted by agent"
|
|
122
|
+
},
|
|
123
|
+
"failure_reason": {
|
|
124
|
+
"type": ["string", "null"],
|
|
125
|
+
"description": "Required when status is 'failed', null otherwise"
|
|
126
|
+
},
|
|
127
|
+
"metadata": {
|
|
128
|
+
"type": "object",
|
|
129
|
+
"description": "Free-form agent-supplied data, stored but not acted on in v1"
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
"event_payload": {
|
|
134
|
+
"type": "object",
|
|
135
|
+
"additionalProperties": false,
|
|
136
|
+
"required": ["event_type", "session_id", "detail", "timestamp"],
|
|
137
|
+
"properties": {
|
|
138
|
+
"event_type": {
|
|
139
|
+
"type": "string",
|
|
140
|
+
"enum": [
|
|
141
|
+
"agent-started",
|
|
142
|
+
"agent-completed",
|
|
143
|
+
"agent-failed",
|
|
144
|
+
"session-planned",
|
|
145
|
+
"session-replanned",
|
|
146
|
+
"session-completed",
|
|
147
|
+
"session-failed"
|
|
148
|
+
]
|
|
149
|
+
},
|
|
150
|
+
"session_id": {
|
|
151
|
+
"type": "string"
|
|
152
|
+
},
|
|
153
|
+
"detail": {
|
|
154
|
+
"type": "string",
|
|
155
|
+
"description": "Human-readable description"
|
|
156
|
+
},
|
|
157
|
+
"timestamp": {
|
|
158
|
+
"type": "string",
|
|
159
|
+
"format": "date-time",
|
|
160
|
+
"description": "ISO 8601 timestamp"
|
|
161
|
+
},
|
|
162
|
+
"task_id": {
|
|
163
|
+
"type": ["string", "null"],
|
|
164
|
+
"description": "Present for agent-scoped events, null for session-scoped"
|
|
165
|
+
},
|
|
166
|
+
"agent_id": {
|
|
167
|
+
"type": ["string", "null"],
|
|
168
|
+
"description": "Present for agent-scoped events, null for session-scoped"
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
package/lib/validator.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// @capability CAP-010 | Agent SDK Package
|
|
2
|
+
// @intent Validates inbound task_dispatch messages against the communication schema — no AJV, custom validator
|
|
3
|
+
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
// Allowed top-level envelope keys (additionalProperties: false)
|
|
7
|
+
const ALLOWED_ENVELOPE_KEYS = new Set(['version', 'message_id', 'message_type', 'sent_at', 'payload']);
|
|
8
|
+
|
|
9
|
+
// Allowed task_dispatch payload keys (additionalProperties: false)
|
|
10
|
+
const ALLOWED_PAYLOAD_KEYS = new Set([
|
|
11
|
+
'task_id', 'session_id', 'objective', 'session_intent', 'inputs',
|
|
12
|
+
'step_number', 'total_steps', 'rules_constraints', 'agent_metadata',
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
// Allowed agent_metadata keys
|
|
16
|
+
const ALLOWED_METADATA_KEYS = new Set(['agent_id', 'agent_name', 'schemaVersion']);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* validateInboundTask — validates that req.body conforms to the task_dispatch envelope.
|
|
20
|
+
* Collects ALL errors (not fail-fast). Error strings are human-readable.
|
|
21
|
+
* @contract input: { body: any } → output: { valid: boolean, errors: string[] }
|
|
22
|
+
* @param {any} body
|
|
23
|
+
* @returns {{ valid: boolean, errors: string[] }}
|
|
24
|
+
*/
|
|
25
|
+
function validateInboundTask(body) {
|
|
26
|
+
const errors = [];
|
|
27
|
+
|
|
28
|
+
// Must be a non-null object
|
|
29
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
30
|
+
errors.push('request body must be a non-null object');
|
|
31
|
+
return { valid: false, errors };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// --- Envelope required fields ---
|
|
35
|
+
if (body.version === undefined || body.version === null) {
|
|
36
|
+
errors.push('version: required field missing');
|
|
37
|
+
} else if (typeof body.version !== 'string') {
|
|
38
|
+
errors.push('version: must be a string');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (body.message_id === undefined || body.message_id === null) {
|
|
42
|
+
errors.push('message_id: required field missing');
|
|
43
|
+
} else if (typeof body.message_id !== 'string') {
|
|
44
|
+
errors.push('message_id: must be a string');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (body.message_type === undefined || body.message_type === null) {
|
|
48
|
+
errors.push('message_type: required field missing');
|
|
49
|
+
} else if (body.message_type !== 'task_dispatch') {
|
|
50
|
+
errors.push(`message_type: must be 'task_dispatch'; received '${body.message_type}'`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (body.sent_at === undefined || body.sent_at === null) {
|
|
54
|
+
errors.push('sent_at: required field missing');
|
|
55
|
+
} else if (typeof body.sent_at !== 'string') {
|
|
56
|
+
errors.push('sent_at: must be a string (ISO 8601)');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (body.payload === undefined || body.payload === null) {
|
|
60
|
+
errors.push('payload: required field missing');
|
|
61
|
+
} else if (typeof body.payload !== 'object' || Array.isArray(body.payload)) {
|
|
62
|
+
errors.push('payload: must be a non-null object');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// --- additionalProperties: false on envelope ---
|
|
66
|
+
for (const key of Object.keys(body)) {
|
|
67
|
+
if (!ALLOWED_ENVELOPE_KEYS.has(key)) {
|
|
68
|
+
errors.push(`additionalProperty not allowed in envelope: '${key}'`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// --- Payload validation (only if payload is an object) ---
|
|
73
|
+
const payload = body.payload;
|
|
74
|
+
if (typeof payload === 'object' && payload !== null && !Array.isArray(payload)) {
|
|
75
|
+
// Required payload fields
|
|
76
|
+
const requiredPayloadFields = ['task_id', 'session_id', 'objective', 'session_intent', 'inputs', 'step_number', 'total_steps'];
|
|
77
|
+
for (const field of requiredPayloadFields) {
|
|
78
|
+
if (payload[field] === undefined || payload[field] === null) {
|
|
79
|
+
errors.push(`payload.${field}: required field missing`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Type checks for required fields
|
|
84
|
+
if (payload.task_id !== undefined && payload.task_id !== null && typeof payload.task_id !== 'string') {
|
|
85
|
+
errors.push('payload.task_id: must be a string');
|
|
86
|
+
}
|
|
87
|
+
if (payload.session_id !== undefined && payload.session_id !== null && typeof payload.session_id !== 'string') {
|
|
88
|
+
errors.push('payload.session_id: must be a string');
|
|
89
|
+
}
|
|
90
|
+
if (payload.objective !== undefined && payload.objective !== null && typeof payload.objective !== 'string') {
|
|
91
|
+
errors.push('payload.objective: must be a string');
|
|
92
|
+
}
|
|
93
|
+
if (payload.session_intent !== undefined && payload.session_intent !== null && typeof payload.session_intent !== 'string') {
|
|
94
|
+
errors.push('payload.session_intent: must be a string');
|
|
95
|
+
}
|
|
96
|
+
if (payload.inputs !== undefined && payload.inputs !== null) {
|
|
97
|
+
if (typeof payload.inputs !== 'object' || Array.isArray(payload.inputs)) {
|
|
98
|
+
errors.push('payload.inputs: must be an object');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (payload.step_number !== undefined && payload.step_number !== null && !Number.isInteger(payload.step_number)) {
|
|
102
|
+
errors.push('payload.step_number: must be a number (integer)');
|
|
103
|
+
}
|
|
104
|
+
if (payload.total_steps !== undefined && payload.total_steps !== null && !Number.isInteger(payload.total_steps)) {
|
|
105
|
+
errors.push('payload.total_steps: must be a number (integer)');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Optional field: rules_constraints (array of strings)
|
|
109
|
+
if (payload.rules_constraints !== undefined && payload.rules_constraints !== null) {
|
|
110
|
+
if (!Array.isArray(payload.rules_constraints)) {
|
|
111
|
+
errors.push('payload.rules_constraints: must be an array');
|
|
112
|
+
} else {
|
|
113
|
+
for (let i = 0; i < payload.rules_constraints.length; i++) {
|
|
114
|
+
if (typeof payload.rules_constraints[i] !== 'string') {
|
|
115
|
+
errors.push(`payload.rules_constraints[${i}]: must be a string`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Optional field: agent_metadata (object)
|
|
122
|
+
if (payload.agent_metadata !== undefined && payload.agent_metadata !== null) {
|
|
123
|
+
if (typeof payload.agent_metadata !== 'object' || Array.isArray(payload.agent_metadata)) {
|
|
124
|
+
errors.push('payload.agent_metadata: must be an object');
|
|
125
|
+
} else {
|
|
126
|
+
for (const key of Object.keys(payload.agent_metadata)) {
|
|
127
|
+
if (!ALLOWED_METADATA_KEYS.has(key)) {
|
|
128
|
+
errors.push(`payload.agent_metadata: additionalProperty not allowed: '${key}'`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// additionalProperties: false on payload
|
|
135
|
+
for (const key of Object.keys(payload)) {
|
|
136
|
+
if (!ALLOWED_PAYLOAD_KEYS.has(key)) {
|
|
137
|
+
errors.push(`payload: additionalProperty not allowed: '${key}'`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return { valid: errors.length === 0, errors };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
module.exports = { validateInboundTask };
|
package/package.json
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sootradhaar-agent-sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "Agent SDK for Sootradhaar multi-agent orchestration system",
|
|
5
|
+
"main": "lib/index.js",
|
|
6
|
+
"files": ["lib/"],
|
|
7
|
+
"engines": { "node": ">=18" },
|
|
8
|
+
"dependencies": { "express": "^4.18.2" }
|
|
9
|
+
}
|