@orangecheck/agent-openai 0.1.1 → 0.2.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 +1 -1
- package/dist/index.d.mts +14 -5
- package/dist/index.d.ts +14 -5
- package/dist/index.js +39 -8
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +39 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -2
- package/src/index.ts +71 -19
package/README.md
CHANGED
|
@@ -72,4 +72,4 @@ MIT.
|
|
|
72
72
|
- [@orangecheck/agent-core](https://www.npmjs.com/package/@orangecheck/agent-core) — verifier library.
|
|
73
73
|
- [@orangecheck/agent-mcp](https://www.npmjs.com/package/@orangecheck/agent-mcp) — same pattern, for MCP.
|
|
74
74
|
- [@orangecheck/agent-anthropic](https://www.npmjs.com/package/@orangecheck/agent-anthropic) — same pattern, for Claude Tool Use.
|
|
75
|
-
- [
|
|
75
|
+
- [fleet.ochk.io/integrations/openai](https://fleet.ochk.io/integrations/openai) — managed-tier story.
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import { DelegationEnvelope } from '@orangecheck/agent-core';
|
|
2
2
|
import { SignerRef, ActionEnvelope } from '@orangecheck/agent-signer';
|
|
3
|
-
import { ConsoleClient, PostActionResult } from '@orangecheck/agent-console-client';
|
|
4
|
-
export { ConsoleClient, PostActionResult, postActionToConsole } from '@orangecheck/agent-console-client';
|
|
5
3
|
|
|
6
4
|
interface OpenAiFunctionCall {
|
|
7
5
|
id: string;
|
|
@@ -29,13 +27,24 @@ interface InvokeWithStampResult<T> {
|
|
|
29
27
|
call: OpenAiFunctionCall;
|
|
30
28
|
}
|
|
31
29
|
declare function invokeWithStamp<T>(input: InvokeWithStampInput<T>): Promise<InvokeWithStampResult<T>>;
|
|
32
|
-
|
|
30
|
+
interface FleetClient {
|
|
31
|
+
baseUrl?: string;
|
|
32
|
+
apiToken: string;
|
|
33
|
+
projectId: string;
|
|
34
|
+
fetch?: typeof fetch;
|
|
35
|
+
}
|
|
36
|
+
interface PostActionResult {
|
|
37
|
+
id: string;
|
|
38
|
+
project_id: string;
|
|
39
|
+
delegation_id: string;
|
|
40
|
+
}
|
|
41
|
+
declare function postActionToFleet(action: ActionEnvelope, client: FleetClient): Promise<PostActionResult>;
|
|
33
42
|
interface InvokeWithStampAndPostInput<T> extends InvokeWithStampInput<T> {
|
|
34
|
-
|
|
43
|
+
fleet?: FleetClient;
|
|
35
44
|
}
|
|
36
45
|
interface InvokeWithStampAndPostResult<T> extends InvokeWithStampResult<T> {
|
|
37
46
|
posted: PostActionResult | null;
|
|
38
47
|
}
|
|
39
48
|
declare function invokeWithStampAndPost<T>(input: InvokeWithStampAndPostInput<T>): Promise<InvokeWithStampAndPostResult<T>>;
|
|
40
49
|
|
|
41
|
-
export { type InvokeWithStampAndPostInput, type InvokeWithStampAndPostResult, type InvokeWithStampInput, type InvokeWithStampResult, type OpenAiFunctionCall, type StampFunctionCallInput, canonicalizeFunctionCall, functionCallActionId, functionCallHash, invokeWithStamp, invokeWithStampAndPost, parseFunctionCall, stampFunctionCall };
|
|
50
|
+
export { type FleetClient, type InvokeWithStampAndPostInput, type InvokeWithStampAndPostResult, type InvokeWithStampInput, type InvokeWithStampResult, type OpenAiFunctionCall, type PostActionResult, type StampFunctionCallInput, canonicalizeFunctionCall, functionCallActionId, functionCallHash, invokeWithStamp, invokeWithStampAndPost, parseFunctionCall, postActionToFleet, stampFunctionCall };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import { DelegationEnvelope } from '@orangecheck/agent-core';
|
|
2
2
|
import { SignerRef, ActionEnvelope } from '@orangecheck/agent-signer';
|
|
3
|
-
import { ConsoleClient, PostActionResult } from '@orangecheck/agent-console-client';
|
|
4
|
-
export { ConsoleClient, PostActionResult, postActionToConsole } from '@orangecheck/agent-console-client';
|
|
5
3
|
|
|
6
4
|
interface OpenAiFunctionCall {
|
|
7
5
|
id: string;
|
|
@@ -29,13 +27,24 @@ interface InvokeWithStampResult<T> {
|
|
|
29
27
|
call: OpenAiFunctionCall;
|
|
30
28
|
}
|
|
31
29
|
declare function invokeWithStamp<T>(input: InvokeWithStampInput<T>): Promise<InvokeWithStampResult<T>>;
|
|
32
|
-
|
|
30
|
+
interface FleetClient {
|
|
31
|
+
baseUrl?: string;
|
|
32
|
+
apiToken: string;
|
|
33
|
+
projectId: string;
|
|
34
|
+
fetch?: typeof fetch;
|
|
35
|
+
}
|
|
36
|
+
interface PostActionResult {
|
|
37
|
+
id: string;
|
|
38
|
+
project_id: string;
|
|
39
|
+
delegation_id: string;
|
|
40
|
+
}
|
|
41
|
+
declare function postActionToFleet(action: ActionEnvelope, client: FleetClient): Promise<PostActionResult>;
|
|
33
42
|
interface InvokeWithStampAndPostInput<T> extends InvokeWithStampInput<T> {
|
|
34
|
-
|
|
43
|
+
fleet?: FleetClient;
|
|
35
44
|
}
|
|
36
45
|
interface InvokeWithStampAndPostResult<T> extends InvokeWithStampResult<T> {
|
|
37
46
|
posted: PostActionResult | null;
|
|
38
47
|
}
|
|
39
48
|
declare function invokeWithStampAndPost<T>(input: InvokeWithStampAndPostInput<T>): Promise<InvokeWithStampAndPostResult<T>>;
|
|
40
49
|
|
|
41
|
-
export { type InvokeWithStampAndPostInput, type InvokeWithStampAndPostResult, type InvokeWithStampInput, type InvokeWithStampResult, type OpenAiFunctionCall, type StampFunctionCallInput, canonicalizeFunctionCall, functionCallActionId, functionCallHash, invokeWithStamp, invokeWithStampAndPost, parseFunctionCall, stampFunctionCall };
|
|
50
|
+
export { type FleetClient, type InvokeWithStampAndPostInput, type InvokeWithStampAndPostResult, type InvokeWithStampInput, type InvokeWithStampResult, type OpenAiFunctionCall, type PostActionResult, type StampFunctionCallInput, canonicalizeFunctionCall, functionCallActionId, functionCallHash, invokeWithStamp, invokeWithStampAndPost, parseFunctionCall, postActionToFleet, stampFunctionCall };
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
var sha256 = require('@noble/hashes/sha256');
|
|
4
4
|
var agentCore = require('@orangecheck/agent-core');
|
|
5
5
|
var agentSigner = require('@orangecheck/agent-signer');
|
|
6
|
-
var agentConsoleClient = require('@orangecheck/agent-console-client');
|
|
7
6
|
|
|
8
7
|
// src/index.ts
|
|
9
8
|
function parseFunctionCall(raw) {
|
|
@@ -88,29 +87,61 @@ async function invokeWithStamp(input) {
|
|
|
88
87
|
const result = await input.execute(fc);
|
|
89
88
|
return { result, action, call: fc };
|
|
90
89
|
}
|
|
90
|
+
async function postActionToFleet(action, client) {
|
|
91
|
+
const baseUrl = client.baseUrl ?? "https://fleet.ochk.io";
|
|
92
|
+
const f = client.fetch ?? fetch;
|
|
93
|
+
const body = {
|
|
94
|
+
project_id: client.projectId,
|
|
95
|
+
delegation_id: action.delegation_id,
|
|
96
|
+
agent_address: action.signer.address,
|
|
97
|
+
scope_exercised: action.scope_exercised,
|
|
98
|
+
content_hash: action.content.hash,
|
|
99
|
+
content_length: action.content.length,
|
|
100
|
+
content_mime: action.content.mime,
|
|
101
|
+
signed_at: action.signed_at,
|
|
102
|
+
signature: action.sig.value,
|
|
103
|
+
id: action.id
|
|
104
|
+
};
|
|
105
|
+
const r = await f(`${baseUrl}/api/actions`, {
|
|
106
|
+
method: "POST",
|
|
107
|
+
headers: {
|
|
108
|
+
"Content-Type": "application/json",
|
|
109
|
+
Authorization: `Bearer ${client.apiToken}`
|
|
110
|
+
},
|
|
111
|
+
body: JSON.stringify(body)
|
|
112
|
+
});
|
|
113
|
+
if (!r.ok) {
|
|
114
|
+
let reason = `http_${r.status}`;
|
|
115
|
+
try {
|
|
116
|
+
const j2 = await r.json();
|
|
117
|
+
if (j2.reason) reason = j2.reason;
|
|
118
|
+
} catch {
|
|
119
|
+
}
|
|
120
|
+
throw new Error(`postActionToFleet failed: ${reason}`);
|
|
121
|
+
}
|
|
122
|
+
const j = await r.json();
|
|
123
|
+
return j.action;
|
|
124
|
+
}
|
|
91
125
|
async function invokeWithStampAndPost(input) {
|
|
92
126
|
const { result, action, call } = await invokeWithStamp(input);
|
|
93
127
|
let posted = null;
|
|
94
|
-
if (input.
|
|
128
|
+
if (input.fleet) {
|
|
95
129
|
try {
|
|
96
|
-
posted = await
|
|
130
|
+
posted = await postActionToFleet(action, input.fleet);
|
|
97
131
|
} catch (err) {
|
|
98
|
-
console.error("[oc-agent-openai]
|
|
132
|
+
console.error("[oc-agent-openai] postActionToFleet failed:", err);
|
|
99
133
|
}
|
|
100
134
|
}
|
|
101
135
|
return { result, action, call, posted };
|
|
102
136
|
}
|
|
103
137
|
|
|
104
|
-
Object.defineProperty(exports, "postActionToConsole", {
|
|
105
|
-
enumerable: true,
|
|
106
|
-
get: function () { return agentConsoleClient.postActionToConsole; }
|
|
107
|
-
});
|
|
108
138
|
exports.canonicalizeFunctionCall = canonicalizeFunctionCall;
|
|
109
139
|
exports.functionCallActionId = functionCallActionId;
|
|
110
140
|
exports.functionCallHash = functionCallHash;
|
|
111
141
|
exports.invokeWithStamp = invokeWithStamp;
|
|
112
142
|
exports.invokeWithStampAndPost = invokeWithStampAndPost;
|
|
113
143
|
exports.parseFunctionCall = parseFunctionCall;
|
|
144
|
+
exports.postActionToFleet = postActionToFleet;
|
|
114
145
|
exports.stampFunctionCall = stampFunctionCall;
|
|
115
146
|
//# sourceMappingURL=index.js.map
|
|
116
147
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["canonicalize","hexEncode","sha256","computeActionId","parseScope","isSubScope","signAsAgent","_post"],"mappings":";;;;;;;;AAqDO,SAAS,kBAAkB,GAAA,EAAkC;AAChE,EAAA,IAAI,GAAA,IAAO,IAAA,IAAQ,OAAO,GAAA,KAAQ,QAAA,EAAU;AACxC,IAAA,MAAM,IAAI,UAAU,2CAA2C,CAAA;AAAA,EACnE;AACA,EAAA,MAAM,CAAA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,GAAA,EAAK;AAEV,MAAA,OAAA,CAAQ,KAAA,CAAM,iDAAiD,GAAG,CAAA;AAAA,IACtE;AAAA,EACJ;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,MAAA,EAAQ,IAAA,EAAM,MAAA,EAAO;AAC1C","file":"index.js","sourcesContent":["// @orangecheck/agent-openai — wrap OpenAI function calls in OC Agent\n// action envelopes.\n//\n// Covers both surfaces:\n// - Responses API: response.output → tool_call items with\n// { type: 'function_call', name, arguments, call_id }\n// (`arguments` is a JSON string)\n// - Chat Completions: message.tool_calls[i] = { id, function: { name, arguments } }\n// (`arguments` is also a JSON string)\n//\n// Both shapes normalize through `parseFunctionCall()` to the canonical\n// {id, name, arguments} form before hashing.\n\nimport { sha256 } from '@noble/hashes/sha256';\nimport {\n canonicalize,\n computeActionId,\n hexEncode,\n isSubScope,\n parseScope,\n type DelegationEnvelope,\n} from '@orangecheck/agent-core';\nimport {\n signAsAgent,\n type ActionEnvelope,\n type SignerRef,\n} from '@orangecheck/agent-signer';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shape normalization\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface OpenAiFunctionCall {\n /** OpenAI's `id` for this call (Chat Completions: `tool_call.id`; Responses: `call_id`). */\n id: string;\n /** The function name. */\n name: string;\n /** The (already-parsed) function arguments. */\n arguments: Record<string, unknown>;\n}\n\n/**\n * Normalize either a Chat Completions `tool_call` or a Responses\n * `function_call` item into our canonical {id, name, arguments} shape.\n *\n * Accepts:\n * - { id, function: { name, arguments } } (Chat Completions)\n * - { call_id, name, arguments } (Responses, function_call)\n * - { id, name, arguments } (already normalized)\n *\n * `arguments` may be either a JSON string (OpenAI's wire shape) or an\n * already-parsed object (your post-processing). Both work.\n */\nexport function parseFunctionCall(raw: unknown): OpenAiFunctionCall {\n if (raw == null || typeof raw !== 'object') {\n throw new TypeError('parseFunctionCall: input is not an object');\n }\n const r = raw as Record<string, unknown>;\n\n // Chat Completions shape\n if (r.function && typeof r.function === 'object') {\n const f = r.function as Record<string, unknown>;\n return {\n id: String(r.id ?? ''),\n name: String(f.name ?? ''),\n arguments: parseArgs(f.arguments),\n };\n }\n\n // Responses API or already-normalized\n return {\n id: String(r.id ?? r.call_id ?? ''),\n name: String(r.name ?? ''),\n arguments: parseArgs(r.arguments),\n };\n}\n\nfunction parseArgs(args: unknown): Record<string, unknown> {\n if (args == null) return {};\n if (typeof args === 'object') return args as Record<string, unknown>;\n if (typeof args === 'string') {\n try {\n const v = JSON.parse(args);\n if (v && typeof v === 'object') return v as Record<string, unknown>;\n return { _raw: args };\n } catch {\n return { _raw: args };\n }\n }\n return { _raw: String(args) };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonicalization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Produce the canonical bytes for an OpenAI function call. The bytes are\n * what the agent-action envelope's `content.hash` is a SHA-256 of.\n *\n * Shape (RFC 8785 canonical JSON, then trailing LF):\n * {\n * \"arguments\": <canonical JSON of arguments>,\n * \"id\": <call id>,\n * \"name\": <function name>\n * }\n */\nexport function canonicalizeFunctionCall(c: OpenAiFunctionCall): Uint8Array {\n const canon = {\n arguments: c.arguments,\n id: c.id,\n name: c.name,\n };\n const str = canonicalize(canon as unknown as Parameters<typeof canonicalize>[0]);\n return new TextEncoder().encode(str + '\\n');\n}\n\nexport function functionCallHash(c: OpenAiFunctionCall): string {\n return 'sha256:' + hexEncode(sha256(canonicalizeFunctionCall(c)));\n}\n\nexport function functionCallActionId(\n agentAddress: string,\n signedAt: string,\n delegationId: string,\n scopeExercised: string,\n c: OpenAiFunctionCall\n): string {\n return computeActionId({\n address: agentAddress,\n content_hash: functionCallHash(c),\n content_length: canonicalizeFunctionCall(c).byteLength,\n content_mime: 'application/vnd.oc-agent.openai-function-call+json',\n signed_at: signedAt,\n delegation_id: delegationId,\n scope_exercised: scopeExercised,\n });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Stamping + invocation\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface StampFunctionCallInput {\n agent: SignerRef;\n delegation: DelegationEnvelope;\n /** Either a normalized `OpenAiFunctionCall` or a raw OpenAI tool_call / function_call object. */\n call: OpenAiFunctionCall | unknown;\n /** Defaults to `openai:function(name=<name>)` — the tightest admissible sub-scope. */\n scopeExercised?: string;\n signedAt?: Date;\n}\n\nexport async function stampFunctionCall(\n input: StampFunctionCallInput\n): Promise<ActionEnvelope> {\n const fc =\n typeof input.call === 'object' &&\n input.call !== null &&\n 'arguments' in (input.call as Record<string, unknown>) &&\n typeof (input.call as Record<string, unknown>).arguments !== 'string'\n ? (input.call as OpenAiFunctionCall)\n : parseFunctionCall(input.call);\n\n const scopeExercised =\n input.scopeExercised ?? `openai:function(name=${fc.name})`;\n\n const granted = (input.delegation.scopes ?? []).map(parseScope);\n const exercisedParsed = parseScope(scopeExercised);\n if (!granted.some((g) => isSubScope(exercisedParsed, g))) {\n throw new Error(\n `stampFunctionCall: scope_exercised (${scopeExercised}) is not a sub-scope of any granted scope`\n );\n }\n\n const bytes = canonicalizeFunctionCall(fc);\n return signAsAgent({\n agent: input.agent,\n delegation: input.delegation as never,\n content: { hash: functionCallHash(fc), length: bytes.byteLength },\n mime: 'application/vnd.oc-agent.openai-function-call+json',\n scopeExercised,\n signedAt: input.signedAt,\n });\n}\n\nexport interface InvokeWithStampInput<T> extends StampFunctionCallInput {\n /** Your handler. Receives the normalized OpenAiFunctionCall. */\n execute: (call: OpenAiFunctionCall) => Promise<T>;\n}\n\nexport interface InvokeWithStampResult<T> {\n result: T;\n action: ActionEnvelope;\n call: OpenAiFunctionCall;\n}\n\nexport async function invokeWithStamp<T>(\n input: InvokeWithStampInput<T>\n): Promise<InvokeWithStampResult<T>> {\n const action = await stampFunctionCall(input);\n const fc = parseFunctionCall(input.call);\n const result = await input.execute(fc);\n return { result, action, call: fc };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Console integration — re-export from the shared client\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport {\n postActionToConsole,\n type ConsoleClient,\n type PostActionResult,\n} from '@orangecheck/agent-console-client';\n\nimport {\n postActionToConsole as _post,\n type ConsoleClient as _ConsoleClient,\n type PostActionResult as _PostActionResult,\n} from '@orangecheck/agent-console-client';\n\nexport interface InvokeWithStampAndPostInput<T> extends InvokeWithStampInput<T> {\n /** Console credentials. If absent, behaves like invokeWithStamp + posted: null. */\n console?: _ConsoleClient;\n}\n\nexport interface InvokeWithStampAndPostResult<T> extends InvokeWithStampResult<T> {\n /** Set when console is configured AND the POST succeeded. */\n posted: _PostActionResult | null;\n}\n\nexport async function invokeWithStampAndPost<T>(\n input: InvokeWithStampAndPostInput<T>\n): Promise<InvokeWithStampAndPostResult<T>> {\n const { result, action, call } = await invokeWithStamp(input);\n let posted: _PostActionResult | null = null;\n if (input.console) {\n try {\n posted = await _post(action, input.console);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[oc-agent-openai] postActionToConsole failed:', err);\n }\n }\n return { result, action, call, posted };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["canonicalize","hexEncode","sha256","computeActionId","parseScope","isSubScope","signAsAgent","j"],"mappings":";;;;;;;AAqDO,SAAS,kBAAkB,GAAA,EAAkC;AAChE,EAAA,IAAI,GAAA,IAAO,IAAA,IAAQ,OAAO,GAAA,KAAQ,QAAA,EAAU;AACxC,IAAA,MAAM,IAAI,UAAU,2CAA2C,CAAA;AAAA,EACnE;AACA,EAAA,MAAM,CAAA,GAAI,GAAA;AAGV,EAAA,IAAI,CAAA,CAAE,QAAA,IAAY,OAAO,CAAA,CAAE,aAAa,QAAA,EAAU;AAC9C,IAAA,MAAM,IAAI,CAAA,CAAE,QAAA;AACZ,IAAA,OAAO;AAAA,MACH,EAAA,EAAI,MAAA,CAAO,CAAA,CAAE,EAAA,IAAM,EAAE,CAAA;AAAA,MACrB,IAAA,EAAM,MAAA,CAAO,CAAA,CAAE,IAAA,IAAQ,EAAE,CAAA;AAAA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A,IACpE;AAAA,EACJ;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,MAAA,EAAQ,IAAA,EAAM,MAAA,EAAO;AAC1C","file":"index.js","sourcesContent":["// @orangecheck/agent-openai — wrap OpenAI function calls in OC Agent\n// action envelopes.\n//\n// Covers both surfaces:\n// - Responses API: response.output → tool_call items with\n// { type: 'function_call', name, arguments, call_id }\n// (`arguments` is a JSON string)\n// - Chat Completions: message.tool_calls[i] = { id, function: { name, arguments } }\n// (`arguments` is also a JSON string)\n//\n// Both shapes normalize through `parseFunctionCall()` to the canonical\n// {id, name, arguments} form before hashing.\n\nimport { sha256 } from '@noble/hashes/sha256';\nimport {\n canonicalize,\n computeActionId,\n hexEncode,\n isSubScope,\n parseScope,\n type DelegationEnvelope,\n} from '@orangecheck/agent-core';\nimport {\n signAsAgent,\n type ActionEnvelope,\n type SignerRef,\n} from '@orangecheck/agent-signer';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shape normalization\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface OpenAiFunctionCall {\n /** OpenAI's `id` for this call (Chat Completions: `tool_call.id`; Responses: `call_id`). */\n id: string;\n /** The function name. */\n name: string;\n /** The (already-parsed) function arguments. */\n arguments: Record<string, unknown>;\n}\n\n/**\n * Normalize either a Chat Completions `tool_call` or a Responses\n * `function_call` item into our canonical {id, name, arguments} shape.\n *\n * Accepts:\n * - { id, function: { name, arguments } } (Chat Completions)\n * - { call_id, name, arguments } (Responses, function_call)\n * - { id, name, arguments } (already normalized)\n *\n * `arguments` may be either a JSON string (OpenAI's wire shape) or an\n * already-parsed object (your post-processing). Both work.\n */\nexport function parseFunctionCall(raw: unknown): OpenAiFunctionCall {\n if (raw == null || typeof raw !== 'object') {\n throw new TypeError('parseFunctionCall: input is not an object');\n }\n const r = raw as Record<string, unknown>;\n\n // Chat Completions shape\n if (r.function && typeof r.function === 'object') {\n const f = r.function as Record<string, unknown>;\n return {\n id: String(r.id ?? ''),\n name: String(f.name ?? ''),\n arguments: parseArgs(f.arguments),\n };\n }\n\n // Responses API or already-normalized\n return {\n id: String(r.id ?? r.call_id ?? ''),\n name: String(r.name ?? ''),\n arguments: parseArgs(r.arguments),\n };\n}\n\nfunction parseArgs(args: unknown): Record<string, unknown> {\n if (args == null) return {};\n if (typeof args === 'object') return args as Record<string, unknown>;\n if (typeof args === 'string') {\n try {\n const v = JSON.parse(args);\n if (v && typeof v === 'object') return v as Record<string, unknown>;\n return { _raw: args };\n } catch {\n return { _raw: args };\n }\n }\n return { _raw: String(args) };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonicalization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Produce the canonical bytes for an OpenAI function call. The bytes are\n * what the agent-action envelope's `content.hash` is a SHA-256 of.\n *\n * Shape (RFC 8785 canonical JSON, then trailing LF):\n * {\n * \"arguments\": <canonical JSON of arguments>,\n * \"id\": <call id>,\n * \"name\": <function name>\n * }\n */\nexport function canonicalizeFunctionCall(c: OpenAiFunctionCall): Uint8Array {\n const canon = {\n arguments: c.arguments,\n id: c.id,\n name: c.name,\n };\n const str = canonicalize(canon as unknown as Parameters<typeof canonicalize>[0]);\n return new TextEncoder().encode(str + '\\n');\n}\n\nexport function functionCallHash(c: OpenAiFunctionCall): string {\n return 'sha256:' + hexEncode(sha256(canonicalizeFunctionCall(c)));\n}\n\nexport function functionCallActionId(\n agentAddress: string,\n signedAt: string,\n delegationId: string,\n scopeExercised: string,\n c: OpenAiFunctionCall\n): string {\n return computeActionId({\n address: agentAddress,\n content_hash: functionCallHash(c),\n content_length: canonicalizeFunctionCall(c).byteLength,\n content_mime: 'application/vnd.oc-agent.openai-function-call+json',\n signed_at: signedAt,\n delegation_id: delegationId,\n scope_exercised: scopeExercised,\n });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Stamping + invocation\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface StampFunctionCallInput {\n agent: SignerRef;\n delegation: DelegationEnvelope;\n /** Either a normalized `OpenAiFunctionCall` or a raw OpenAI tool_call / function_call object. */\n call: OpenAiFunctionCall | unknown;\n /** Defaults to `openai:function(name=<name>)` — the tightest admissible sub-scope. */\n scopeExercised?: string;\n signedAt?: Date;\n}\n\nexport async function stampFunctionCall(\n input: StampFunctionCallInput\n): Promise<ActionEnvelope> {\n const fc =\n typeof input.call === 'object' &&\n input.call !== null &&\n 'arguments' in (input.call as Record<string, unknown>) &&\n typeof (input.call as Record<string, unknown>).arguments !== 'string'\n ? (input.call as OpenAiFunctionCall)\n : parseFunctionCall(input.call);\n\n const scopeExercised =\n input.scopeExercised ?? `openai:function(name=${fc.name})`;\n\n const granted = (input.delegation.scopes ?? []).map(parseScope);\n const exercisedParsed = parseScope(scopeExercised);\n if (!granted.some((g) => isSubScope(exercisedParsed, g))) {\n throw new Error(\n `stampFunctionCall: scope_exercised (${scopeExercised}) is not a sub-scope of any granted scope`\n );\n }\n\n const bytes = canonicalizeFunctionCall(fc);\n return signAsAgent({\n agent: input.agent,\n delegation: input.delegation as never,\n content: { hash: functionCallHash(fc), length: bytes.byteLength },\n mime: 'application/vnd.oc-agent.openai-function-call+json',\n scopeExercised,\n signedAt: input.signedAt,\n });\n}\n\nexport interface InvokeWithStampInput<T> extends StampFunctionCallInput {\n /** Your handler. Receives the normalized OpenAiFunctionCall. */\n execute: (call: OpenAiFunctionCall) => Promise<T>;\n}\n\nexport interface InvokeWithStampResult<T> {\n result: T;\n action: ActionEnvelope;\n call: OpenAiFunctionCall;\n}\n\nexport async function invokeWithStamp<T>(\n input: InvokeWithStampInput<T>\n): Promise<InvokeWithStampResult<T>> {\n const action = await stampFunctionCall(input);\n const fc = parseFunctionCall(input.call);\n const result = await input.execute(fc);\n return { result, action, call: fc };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fleet integration: POST stamped actions to fleet.ochk.io/api/actions\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface FleetClient {\n /** Defaults to https://fleet.ochk.io. */\n baseUrl?: string;\n /** Bearer token from /settings § 03 (`ock_<hex>`). */\n apiToken: string;\n /** Project the action belongs to (proj_*). */\n projectId: string;\n /** Optional fetch override for runtimes that need it. */\n fetch?: typeof fetch;\n}\n\nexport interface PostActionResult {\n id: string;\n project_id: string;\n delegation_id: string;\n}\n\n/**\n * POST a stamped action envelope to fleet.ochk.io/api/actions. The\n * fleet re-derives the action id, validates agent-must-match-\n * delegation, persists, fans out to Nostr (kind 30084), submits to\n * OC Stamp, and triggers any subscribed webhooks. Throws on non-2xx\n * with the server's reason string.\n */\nexport async function postActionToFleet(\n action: ActionEnvelope,\n client: FleetClient\n): Promise<PostActionResult> {\n const baseUrl = client.baseUrl ?? 'https://fleet.ochk.io';\n const f = client.fetch ?? fetch;\n const body = {\n project_id: client.projectId,\n delegation_id: action.delegation_id,\n agent_address: action.signer.address,\n scope_exercised: action.scope_exercised,\n content_hash: action.content.hash,\n content_length: action.content.length,\n content_mime: action.content.mime,\n signed_at: action.signed_at,\n signature: action.sig.value,\n id: action.id,\n };\n const r = await f(`${baseUrl}/api/actions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${client.apiToken}`,\n },\n body: JSON.stringify(body),\n });\n if (!r.ok) {\n let reason = `http_${r.status}`;\n try {\n const j = (await r.json()) as { reason?: string };\n if (j.reason) reason = j.reason;\n } catch {\n // body wasn't json\n }\n throw new Error(`postActionToFleet failed: ${reason}`);\n }\n const j = (await r.json()) as { ok: true; action: PostActionResult };\n return j.action;\n}\n\nexport interface InvokeWithStampAndPostInput<T> extends InvokeWithStampInput<T> {\n /** Fleet credentials. If absent, behaves like invokeWithStamp. */\n fleet?: FleetClient;\n}\n\nexport interface InvokeWithStampAndPostResult<T> extends InvokeWithStampResult<T> {\n /** Set when fleet is configured AND the POST succeeded. */\n posted: PostActionResult | null;\n}\n\nexport async function invokeWithStampAndPost<T>(\n input: InvokeWithStampAndPostInput<T>\n): Promise<InvokeWithStampAndPostResult<T>> {\n const { result, action, call } = await invokeWithStamp(input);\n let posted: PostActionResult | null = null;\n if (input.fleet) {\n try {\n posted = await postActionToFleet(action, input.fleet);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[oc-agent-openai] postActionToFleet failed:', err);\n }\n }\n return { result, action, call, posted };\n}\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { sha256 } from '@noble/hashes/sha256';
|
|
2
2
|
import { canonicalize, hexEncode, computeActionId, parseScope, isSubScope } from '@orangecheck/agent-core';
|
|
3
3
|
import { signAsAgent } from '@orangecheck/agent-signer';
|
|
4
|
-
import { postActionToConsole } from '@orangecheck/agent-console-client';
|
|
5
|
-
export { postActionToConsole } from '@orangecheck/agent-console-client';
|
|
6
4
|
|
|
7
5
|
// src/index.ts
|
|
8
6
|
function parseFunctionCall(raw) {
|
|
@@ -87,19 +85,54 @@ async function invokeWithStamp(input) {
|
|
|
87
85
|
const result = await input.execute(fc);
|
|
88
86
|
return { result, action, call: fc };
|
|
89
87
|
}
|
|
88
|
+
async function postActionToFleet(action, client) {
|
|
89
|
+
const baseUrl = client.baseUrl ?? "https://fleet.ochk.io";
|
|
90
|
+
const f = client.fetch ?? fetch;
|
|
91
|
+
const body = {
|
|
92
|
+
project_id: client.projectId,
|
|
93
|
+
delegation_id: action.delegation_id,
|
|
94
|
+
agent_address: action.signer.address,
|
|
95
|
+
scope_exercised: action.scope_exercised,
|
|
96
|
+
content_hash: action.content.hash,
|
|
97
|
+
content_length: action.content.length,
|
|
98
|
+
content_mime: action.content.mime,
|
|
99
|
+
signed_at: action.signed_at,
|
|
100
|
+
signature: action.sig.value,
|
|
101
|
+
id: action.id
|
|
102
|
+
};
|
|
103
|
+
const r = await f(`${baseUrl}/api/actions`, {
|
|
104
|
+
method: "POST",
|
|
105
|
+
headers: {
|
|
106
|
+
"Content-Type": "application/json",
|
|
107
|
+
Authorization: `Bearer ${client.apiToken}`
|
|
108
|
+
},
|
|
109
|
+
body: JSON.stringify(body)
|
|
110
|
+
});
|
|
111
|
+
if (!r.ok) {
|
|
112
|
+
let reason = `http_${r.status}`;
|
|
113
|
+
try {
|
|
114
|
+
const j2 = await r.json();
|
|
115
|
+
if (j2.reason) reason = j2.reason;
|
|
116
|
+
} catch {
|
|
117
|
+
}
|
|
118
|
+
throw new Error(`postActionToFleet failed: ${reason}`);
|
|
119
|
+
}
|
|
120
|
+
const j = await r.json();
|
|
121
|
+
return j.action;
|
|
122
|
+
}
|
|
90
123
|
async function invokeWithStampAndPost(input) {
|
|
91
124
|
const { result, action, call } = await invokeWithStamp(input);
|
|
92
125
|
let posted = null;
|
|
93
|
-
if (input.
|
|
126
|
+
if (input.fleet) {
|
|
94
127
|
try {
|
|
95
|
-
posted = await
|
|
128
|
+
posted = await postActionToFleet(action, input.fleet);
|
|
96
129
|
} catch (err) {
|
|
97
|
-
console.error("[oc-agent-openai]
|
|
130
|
+
console.error("[oc-agent-openai] postActionToFleet failed:", err);
|
|
98
131
|
}
|
|
99
132
|
}
|
|
100
133
|
return { result, action, call, posted };
|
|
101
134
|
}
|
|
102
135
|
|
|
103
|
-
export { canonicalizeFunctionCall, functionCallActionId, functionCallHash, invokeWithStamp, invokeWithStampAndPost, parseFunctionCall, stampFunctionCall };
|
|
136
|
+
export { canonicalizeFunctionCall, functionCallActionId, functionCallHash, invokeWithStamp, invokeWithStampAndPost, parseFunctionCall, postActionToFleet, stampFunctionCall };
|
|
104
137
|
//# sourceMappingURL=index.mjs.map
|
|
105
138
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["_post"],"mappings":";;;;;;;AAqDO,SAAS,kBAAkB,GAAA,EAAkC;AAChE,EAAA,IAAI,GAAA,IAAO,IAAA,IAAQ,OAAO,GAAA,KAAQ,QAAA,EAAU;AACxC,IAAA,MAAM,IAAI,UAAU,2CAA2C,CAAA;AAAA,EACnE;AACA,EAA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A,EAAK;AAEV,MAAA,OAAA,CAAQ,KAAA,CAAM,iDAAiD,GAAG,CAAA;AAAA,IACtE;AAAA,EACJ;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,MAAA,EAAQ,IAAA,EAAM,MAAA,EAAO;AAC1C","file":"index.mjs","sourcesContent":["// @orangecheck/agent-openai — wrap OpenAI function calls in OC Agent\n// action envelopes.\n//\n// Covers both surfaces:\n// - Responses API: response.output → tool_call items with\n// { type: 'function_call', name, arguments, call_id }\n// (`arguments` is a JSON string)\n// - Chat Completions: message.tool_calls[i] = { id, function: { name, arguments } }\n// (`arguments` is also a JSON string)\n//\n// Both shapes normalize through `parseFunctionCall()` to the canonical\n// {id, name, arguments} form before hashing.\n\nimport { sha256 } from '@noble/hashes/sha256';\nimport {\n canonicalize,\n computeActionId,\n hexEncode,\n isSubScope,\n parseScope,\n type DelegationEnvelope,\n} from '@orangecheck/agent-core';\nimport {\n signAsAgent,\n type ActionEnvelope,\n type SignerRef,\n} from '@orangecheck/agent-signer';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shape normalization\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface OpenAiFunctionCall {\n /** OpenAI's `id` for this call (Chat Completions: `tool_call.id`; Responses: `call_id`). */\n id: string;\n /** The function name. */\n name: string;\n /** The (already-parsed) function arguments. */\n arguments: Record<string, unknown>;\n}\n\n/**\n * Normalize either a Chat Completions `tool_call` or a Responses\n * `function_call` item into our canonical {id, name, arguments} shape.\n *\n * Accepts:\n * - { id, function: { name, arguments } } (Chat Completions)\n * - { call_id, name, arguments } (Responses, function_call)\n * - { id, name, arguments } (already normalized)\n *\n * `arguments` may be either a JSON string (OpenAI's wire shape) or an\n * already-parsed object (your post-processing). Both work.\n */\nexport function parseFunctionCall(raw: unknown): OpenAiFunctionCall {\n if (raw == null || typeof raw !== 'object') {\n throw new TypeError('parseFunctionCall: input is not an object');\n }\n const r = raw as Record<string, unknown>;\n\n // Chat Completions shape\n if (r.function && typeof r.function === 'object') {\n const f = r.function as Record<string, unknown>;\n return {\n id: String(r.id ?? ''),\n name: String(f.name ?? ''),\n arguments: parseArgs(f.arguments),\n };\n }\n\n // Responses API or already-normalized\n return {\n id: String(r.id ?? r.call_id ?? ''),\n name: String(r.name ?? ''),\n arguments: parseArgs(r.arguments),\n };\n}\n\nfunction parseArgs(args: unknown): Record<string, unknown> {\n if (args == null) return {};\n if (typeof args === 'object') return args as Record<string, unknown>;\n if (typeof args === 'string') {\n try {\n const v = JSON.parse(args);\n if (v && typeof v === 'object') return v as Record<string, unknown>;\n return { _raw: args };\n } catch {\n return { _raw: args };\n }\n }\n return { _raw: String(args) };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonicalization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Produce the canonical bytes for an OpenAI function call. The bytes are\n * what the agent-action envelope's `content.hash` is a SHA-256 of.\n *\n * Shape (RFC 8785 canonical JSON, then trailing LF):\n * {\n * \"arguments\": <canonical JSON of arguments>,\n * \"id\": <call id>,\n * \"name\": <function name>\n * }\n */\nexport function canonicalizeFunctionCall(c: OpenAiFunctionCall): Uint8Array {\n const canon = {\n arguments: c.arguments,\n id: c.id,\n name: c.name,\n };\n const str = canonicalize(canon as unknown as Parameters<typeof canonicalize>[0]);\n return new TextEncoder().encode(str + '\\n');\n}\n\nexport function functionCallHash(c: OpenAiFunctionCall): string {\n return 'sha256:' + hexEncode(sha256(canonicalizeFunctionCall(c)));\n}\n\nexport function functionCallActionId(\n agentAddress: string,\n signedAt: string,\n delegationId: string,\n scopeExercised: string,\n c: OpenAiFunctionCall\n): string {\n return computeActionId({\n address: agentAddress,\n content_hash: functionCallHash(c),\n content_length: canonicalizeFunctionCall(c).byteLength,\n content_mime: 'application/vnd.oc-agent.openai-function-call+json',\n signed_at: signedAt,\n delegation_id: delegationId,\n scope_exercised: scopeExercised,\n });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Stamping + invocation\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface StampFunctionCallInput {\n agent: SignerRef;\n delegation: DelegationEnvelope;\n /** Either a normalized `OpenAiFunctionCall` or a raw OpenAI tool_call / function_call object. */\n call: OpenAiFunctionCall | unknown;\n /** Defaults to `openai:function(name=<name>)` — the tightest admissible sub-scope. */\n scopeExercised?: string;\n signedAt?: Date;\n}\n\nexport async function stampFunctionCall(\n input: StampFunctionCallInput\n): Promise<ActionEnvelope> {\n const fc =\n typeof input.call === 'object' &&\n input.call !== null &&\n 'arguments' in (input.call as Record<string, unknown>) &&\n typeof (input.call as Record<string, unknown>).arguments !== 'string'\n ? (input.call as OpenAiFunctionCall)\n : parseFunctionCall(input.call);\n\n const scopeExercised =\n input.scopeExercised ?? `openai:function(name=${fc.name})`;\n\n const granted = (input.delegation.scopes ?? []).map(parseScope);\n const exercisedParsed = parseScope(scopeExercised);\n if (!granted.some((g) => isSubScope(exercisedParsed, g))) {\n throw new Error(\n `stampFunctionCall: scope_exercised (${scopeExercised}) is not a sub-scope of any granted scope`\n );\n }\n\n const bytes = canonicalizeFunctionCall(fc);\n return signAsAgent({\n agent: input.agent,\n delegation: input.delegation as never,\n content: { hash: functionCallHash(fc), length: bytes.byteLength },\n mime: 'application/vnd.oc-agent.openai-function-call+json',\n scopeExercised,\n signedAt: input.signedAt,\n });\n}\n\nexport interface InvokeWithStampInput<T> extends StampFunctionCallInput {\n /** Your handler. Receives the normalized OpenAiFunctionCall. */\n execute: (call: OpenAiFunctionCall) => Promise<T>;\n}\n\nexport interface InvokeWithStampResult<T> {\n result: T;\n action: ActionEnvelope;\n call: OpenAiFunctionCall;\n}\n\nexport async function invokeWithStamp<T>(\n input: InvokeWithStampInput<T>\n): Promise<InvokeWithStampResult<T>> {\n const action = await stampFunctionCall(input);\n const fc = parseFunctionCall(input.call);\n const result = await input.execute(fc);\n return { result, action, call: fc };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Console integration — re-export from the shared client\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport {\n postActionToConsole,\n type ConsoleClient,\n type PostActionResult,\n} from '@orangecheck/agent-console-client';\n\nimport {\n postActionToConsole as _post,\n type ConsoleClient as _ConsoleClient,\n type PostActionResult as _PostActionResult,\n} from '@orangecheck/agent-console-client';\n\nexport interface InvokeWithStampAndPostInput<T> extends InvokeWithStampInput<T> {\n /** Console credentials. If absent, behaves like invokeWithStamp + posted: null. */\n console?: _ConsoleClient;\n}\n\nexport interface InvokeWithStampAndPostResult<T> extends InvokeWithStampResult<T> {\n /** Set when console is configured AND the POST succeeded. */\n posted: _PostActionResult | null;\n}\n\nexport async function invokeWithStampAndPost<T>(\n input: InvokeWithStampAndPostInput<T>\n): Promise<InvokeWithStampAndPostResult<T>> {\n const { result, action, call } = await invokeWithStamp(input);\n let posted: _PostActionResult | null = null;\n if (input.console) {\n try {\n posted = await _post(action, input.console);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[oc-agent-openai] postActionToConsole failed:', err);\n }\n }\n return { result, action, call, posted };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["j"],"mappings":";;;;;AAqDO,SAAS,kBAAkB,GAAA,EAAkC;AAChE,EAAA,IAAI,GAAA,IAAO,IAAA,IAAQ,OAAO,GAAA,KAAQ,QAAA,EAAU;AACxC,IAAA,MAAM,IAAI,UAAU,2CAA2C,CAAA;AAAA,EACnE;AACA,EAAA,MAAM,CAAA,GAAI,GAAA;AAGV,EAAA,IAAI,CAAA,CAAE,QAAA,IAAY,OAAO,CAAA,CAAE,aAAa,QAAA,EAAU;AAC9C,IAAA,MAAM,IAAI,CAAA,CAAE,QAAA;AACZ,IAAA,OAAO;AAAA,MACH,EAAA,EAAI,MAAA,CAAO,CAAA,CAAE,EAAA,IAAM,EAAE,CAAA;AAAA,MACrB,IAAA,EAAM,MAAA,CAAO,CAAA,CAAE,IAAA,IAAQ,EAAE,CAAA;AAAA,MACzB,SAAA,EAAW,SAAA,CAAU,CAAA,CAAE,SAAS;AAA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AAA,EAAM,MAAA,EAAO;AAC1C","file":"index.mjs","sourcesContent":["// @orangecheck/agent-openai — wrap OpenAI function calls in OC Agent\n// action envelopes.\n//\n// Covers both surfaces:\n// - Responses API: response.output → tool_call items with\n// { type: 'function_call', name, arguments, call_id }\n// (`arguments` is a JSON string)\n// - Chat Completions: message.tool_calls[i] = { id, function: { name, arguments } }\n// (`arguments` is also a JSON string)\n//\n// Both shapes normalize through `parseFunctionCall()` to the canonical\n// {id, name, arguments} form before hashing.\n\nimport { sha256 } from '@noble/hashes/sha256';\nimport {\n canonicalize,\n computeActionId,\n hexEncode,\n isSubScope,\n parseScope,\n type DelegationEnvelope,\n} from '@orangecheck/agent-core';\nimport {\n signAsAgent,\n type ActionEnvelope,\n type SignerRef,\n} from '@orangecheck/agent-signer';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Shape normalization\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface OpenAiFunctionCall {\n /** OpenAI's `id` for this call (Chat Completions: `tool_call.id`; Responses: `call_id`). */\n id: string;\n /** The function name. */\n name: string;\n /** The (already-parsed) function arguments. */\n arguments: Record<string, unknown>;\n}\n\n/**\n * Normalize either a Chat Completions `tool_call` or a Responses\n * `function_call` item into our canonical {id, name, arguments} shape.\n *\n * Accepts:\n * - { id, function: { name, arguments } } (Chat Completions)\n * - { call_id, name, arguments } (Responses, function_call)\n * - { id, name, arguments } (already normalized)\n *\n * `arguments` may be either a JSON string (OpenAI's wire shape) or an\n * already-parsed object (your post-processing). Both work.\n */\nexport function parseFunctionCall(raw: unknown): OpenAiFunctionCall {\n if (raw == null || typeof raw !== 'object') {\n throw new TypeError('parseFunctionCall: input is not an object');\n }\n const r = raw as Record<string, unknown>;\n\n // Chat Completions shape\n if (r.function && typeof r.function === 'object') {\n const f = r.function as Record<string, unknown>;\n return {\n id: String(r.id ?? ''),\n name: String(f.name ?? ''),\n arguments: parseArgs(f.arguments),\n };\n }\n\n // Responses API or already-normalized\n return {\n id: String(r.id ?? r.call_id ?? ''),\n name: String(r.name ?? ''),\n arguments: parseArgs(r.arguments),\n };\n}\n\nfunction parseArgs(args: unknown): Record<string, unknown> {\n if (args == null) return {};\n if (typeof args === 'object') return args as Record<string, unknown>;\n if (typeof args === 'string') {\n try {\n const v = JSON.parse(args);\n if (v && typeof v === 'object') return v as Record<string, unknown>;\n return { _raw: args };\n } catch {\n return { _raw: args };\n }\n }\n return { _raw: String(args) };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Canonicalization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Produce the canonical bytes for an OpenAI function call. The bytes are\n * what the agent-action envelope's `content.hash` is a SHA-256 of.\n *\n * Shape (RFC 8785 canonical JSON, then trailing LF):\n * {\n * \"arguments\": <canonical JSON of arguments>,\n * \"id\": <call id>,\n * \"name\": <function name>\n * }\n */\nexport function canonicalizeFunctionCall(c: OpenAiFunctionCall): Uint8Array {\n const canon = {\n arguments: c.arguments,\n id: c.id,\n name: c.name,\n };\n const str = canonicalize(canon as unknown as Parameters<typeof canonicalize>[0]);\n return new TextEncoder().encode(str + '\\n');\n}\n\nexport function functionCallHash(c: OpenAiFunctionCall): string {\n return 'sha256:' + hexEncode(sha256(canonicalizeFunctionCall(c)));\n}\n\nexport function functionCallActionId(\n agentAddress: string,\n signedAt: string,\n delegationId: string,\n scopeExercised: string,\n c: OpenAiFunctionCall\n): string {\n return computeActionId({\n address: agentAddress,\n content_hash: functionCallHash(c),\n content_length: canonicalizeFunctionCall(c).byteLength,\n content_mime: 'application/vnd.oc-agent.openai-function-call+json',\n signed_at: signedAt,\n delegation_id: delegationId,\n scope_exercised: scopeExercised,\n });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Stamping + invocation\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface StampFunctionCallInput {\n agent: SignerRef;\n delegation: DelegationEnvelope;\n /** Either a normalized `OpenAiFunctionCall` or a raw OpenAI tool_call / function_call object. */\n call: OpenAiFunctionCall | unknown;\n /** Defaults to `openai:function(name=<name>)` — the tightest admissible sub-scope. */\n scopeExercised?: string;\n signedAt?: Date;\n}\n\nexport async function stampFunctionCall(\n input: StampFunctionCallInput\n): Promise<ActionEnvelope> {\n const fc =\n typeof input.call === 'object' &&\n input.call !== null &&\n 'arguments' in (input.call as Record<string, unknown>) &&\n typeof (input.call as Record<string, unknown>).arguments !== 'string'\n ? (input.call as OpenAiFunctionCall)\n : parseFunctionCall(input.call);\n\n const scopeExercised =\n input.scopeExercised ?? `openai:function(name=${fc.name})`;\n\n const granted = (input.delegation.scopes ?? []).map(parseScope);\n const exercisedParsed = parseScope(scopeExercised);\n if (!granted.some((g) => isSubScope(exercisedParsed, g))) {\n throw new Error(\n `stampFunctionCall: scope_exercised (${scopeExercised}) is not a sub-scope of any granted scope`\n );\n }\n\n const bytes = canonicalizeFunctionCall(fc);\n return signAsAgent({\n agent: input.agent,\n delegation: input.delegation as never,\n content: { hash: functionCallHash(fc), length: bytes.byteLength },\n mime: 'application/vnd.oc-agent.openai-function-call+json',\n scopeExercised,\n signedAt: input.signedAt,\n });\n}\n\nexport interface InvokeWithStampInput<T> extends StampFunctionCallInput {\n /** Your handler. Receives the normalized OpenAiFunctionCall. */\n execute: (call: OpenAiFunctionCall) => Promise<T>;\n}\n\nexport interface InvokeWithStampResult<T> {\n result: T;\n action: ActionEnvelope;\n call: OpenAiFunctionCall;\n}\n\nexport async function invokeWithStamp<T>(\n input: InvokeWithStampInput<T>\n): Promise<InvokeWithStampResult<T>> {\n const action = await stampFunctionCall(input);\n const fc = parseFunctionCall(input.call);\n const result = await input.execute(fc);\n return { result, action, call: fc };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fleet integration: POST stamped actions to fleet.ochk.io/api/actions\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface FleetClient {\n /** Defaults to https://fleet.ochk.io. */\n baseUrl?: string;\n /** Bearer token from /settings § 03 (`ock_<hex>`). */\n apiToken: string;\n /** Project the action belongs to (proj_*). */\n projectId: string;\n /** Optional fetch override for runtimes that need it. */\n fetch?: typeof fetch;\n}\n\nexport interface PostActionResult {\n id: string;\n project_id: string;\n delegation_id: string;\n}\n\n/**\n * POST a stamped action envelope to fleet.ochk.io/api/actions. The\n * fleet re-derives the action id, validates agent-must-match-\n * delegation, persists, fans out to Nostr (kind 30084), submits to\n * OC Stamp, and triggers any subscribed webhooks. Throws on non-2xx\n * with the server's reason string.\n */\nexport async function postActionToFleet(\n action: ActionEnvelope,\n client: FleetClient\n): Promise<PostActionResult> {\n const baseUrl = client.baseUrl ?? 'https://fleet.ochk.io';\n const f = client.fetch ?? fetch;\n const body = {\n project_id: client.projectId,\n delegation_id: action.delegation_id,\n agent_address: action.signer.address,\n scope_exercised: action.scope_exercised,\n content_hash: action.content.hash,\n content_length: action.content.length,\n content_mime: action.content.mime,\n signed_at: action.signed_at,\n signature: action.sig.value,\n id: action.id,\n };\n const r = await f(`${baseUrl}/api/actions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${client.apiToken}`,\n },\n body: JSON.stringify(body),\n });\n if (!r.ok) {\n let reason = `http_${r.status}`;\n try {\n const j = (await r.json()) as { reason?: string };\n if (j.reason) reason = j.reason;\n } catch {\n // body wasn't json\n }\n throw new Error(`postActionToFleet failed: ${reason}`);\n }\n const j = (await r.json()) as { ok: true; action: PostActionResult };\n return j.action;\n}\n\nexport interface InvokeWithStampAndPostInput<T> extends InvokeWithStampInput<T> {\n /** Fleet credentials. If absent, behaves like invokeWithStamp. */\n fleet?: FleetClient;\n}\n\nexport interface InvokeWithStampAndPostResult<T> extends InvokeWithStampResult<T> {\n /** Set when fleet is configured AND the POST succeeded. */\n posted: PostActionResult | null;\n}\n\nexport async function invokeWithStampAndPost<T>(\n input: InvokeWithStampAndPostInput<T>\n): Promise<InvokeWithStampAndPostResult<T>> {\n const { result, action, call } = await invokeWithStamp(input);\n let posted: PostActionResult | null = null;\n if (input.fleet) {\n try {\n posted = await postActionToFleet(action, input.fleet);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[oc-agent-openai] postActionToFleet failed:', err);\n }\n }\n return { result, action, call, posted };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orangecheck/agent-openai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Wrap OpenAI function-calling (Responses API + Chat Completions tool path) with OC Agent scope enforcement and emit a signed agent-action envelope per function invocation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"bitcoin",
|
|
@@ -52,7 +52,6 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@noble/hashes": "^1.5.0",
|
|
55
|
-
"@orangecheck/agent-console-client": "0.1.0",
|
|
56
55
|
"@orangecheck/agent-core": "^0.3.0",
|
|
57
56
|
"@orangecheck/agent-signer": "^0.1.0"
|
|
58
57
|
},
|
package/src/index.ts
CHANGED
|
@@ -205,42 +205,94 @@ export async function invokeWithStamp<T>(
|
|
|
205
205
|
}
|
|
206
206
|
|
|
207
207
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
208
|
-
//
|
|
208
|
+
// Fleet integration: POST stamped actions to fleet.ochk.io/api/actions
|
|
209
209
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
210
210
|
|
|
211
|
-
export {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
211
|
+
export interface FleetClient {
|
|
212
|
+
/** Defaults to https://fleet.ochk.io. */
|
|
213
|
+
baseUrl?: string;
|
|
214
|
+
/** Bearer token from /settings § 03 (`ock_<hex>`). */
|
|
215
|
+
apiToken: string;
|
|
216
|
+
/** Project the action belongs to (proj_*). */
|
|
217
|
+
projectId: string;
|
|
218
|
+
/** Optional fetch override for runtimes that need it. */
|
|
219
|
+
fetch?: typeof fetch;
|
|
220
|
+
}
|
|
216
221
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
}
|
|
222
|
+
export interface PostActionResult {
|
|
223
|
+
id: string;
|
|
224
|
+
project_id: string;
|
|
225
|
+
delegation_id: string;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* POST a stamped action envelope to fleet.ochk.io/api/actions. The
|
|
230
|
+
* fleet re-derives the action id, validates agent-must-match-
|
|
231
|
+
* delegation, persists, fans out to Nostr (kind 30084), submits to
|
|
232
|
+
* OC Stamp, and triggers any subscribed webhooks. Throws on non-2xx
|
|
233
|
+
* with the server's reason string.
|
|
234
|
+
*/
|
|
235
|
+
export async function postActionToFleet(
|
|
236
|
+
action: ActionEnvelope,
|
|
237
|
+
client: FleetClient
|
|
238
|
+
): Promise<PostActionResult> {
|
|
239
|
+
const baseUrl = client.baseUrl ?? 'https://fleet.ochk.io';
|
|
240
|
+
const f = client.fetch ?? fetch;
|
|
241
|
+
const body = {
|
|
242
|
+
project_id: client.projectId,
|
|
243
|
+
delegation_id: action.delegation_id,
|
|
244
|
+
agent_address: action.signer.address,
|
|
245
|
+
scope_exercised: action.scope_exercised,
|
|
246
|
+
content_hash: action.content.hash,
|
|
247
|
+
content_length: action.content.length,
|
|
248
|
+
content_mime: action.content.mime,
|
|
249
|
+
signed_at: action.signed_at,
|
|
250
|
+
signature: action.sig.value,
|
|
251
|
+
id: action.id,
|
|
252
|
+
};
|
|
253
|
+
const r = await f(`${baseUrl}/api/actions`, {
|
|
254
|
+
method: 'POST',
|
|
255
|
+
headers: {
|
|
256
|
+
'Content-Type': 'application/json',
|
|
257
|
+
Authorization: `Bearer ${client.apiToken}`,
|
|
258
|
+
},
|
|
259
|
+
body: JSON.stringify(body),
|
|
260
|
+
});
|
|
261
|
+
if (!r.ok) {
|
|
262
|
+
let reason = `http_${r.status}`;
|
|
263
|
+
try {
|
|
264
|
+
const j = (await r.json()) as { reason?: string };
|
|
265
|
+
if (j.reason) reason = j.reason;
|
|
266
|
+
} catch {
|
|
267
|
+
// body wasn't json
|
|
268
|
+
}
|
|
269
|
+
throw new Error(`postActionToFleet failed: ${reason}`);
|
|
270
|
+
}
|
|
271
|
+
const j = (await r.json()) as { ok: true; action: PostActionResult };
|
|
272
|
+
return j.action;
|
|
273
|
+
}
|
|
222
274
|
|
|
223
275
|
export interface InvokeWithStampAndPostInput<T> extends InvokeWithStampInput<T> {
|
|
224
|
-
/**
|
|
225
|
-
|
|
276
|
+
/** Fleet credentials. If absent, behaves like invokeWithStamp. */
|
|
277
|
+
fleet?: FleetClient;
|
|
226
278
|
}
|
|
227
279
|
|
|
228
280
|
export interface InvokeWithStampAndPostResult<T> extends InvokeWithStampResult<T> {
|
|
229
|
-
/** Set when
|
|
230
|
-
posted:
|
|
281
|
+
/** Set when fleet is configured AND the POST succeeded. */
|
|
282
|
+
posted: PostActionResult | null;
|
|
231
283
|
}
|
|
232
284
|
|
|
233
285
|
export async function invokeWithStampAndPost<T>(
|
|
234
286
|
input: InvokeWithStampAndPostInput<T>
|
|
235
287
|
): Promise<InvokeWithStampAndPostResult<T>> {
|
|
236
288
|
const { result, action, call } = await invokeWithStamp(input);
|
|
237
|
-
let posted:
|
|
238
|
-
if (input.
|
|
289
|
+
let posted: PostActionResult | null = null;
|
|
290
|
+
if (input.fleet) {
|
|
239
291
|
try {
|
|
240
|
-
posted = await
|
|
292
|
+
posted = await postActionToFleet(action, input.fleet);
|
|
241
293
|
} catch (err) {
|
|
242
294
|
// eslint-disable-next-line no-console
|
|
243
|
-
console.error('[oc-agent-openai]
|
|
295
|
+
console.error('[oc-agent-openai] postActionToFleet failed:', err);
|
|
244
296
|
}
|
|
245
297
|
}
|
|
246
298
|
return { result, action, call, posted };
|