@caracalai/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Garudex Labs]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ export * from "./envelope.js";
2
+ export * from "./context.js";
3
+ export * from "./coordinator.js";
4
+ export * from "./primitives.js";
5
+ export * from "./http.js";
6
+ export { Caracal } from "./client.js";
7
+ export type { CaracalConfig, SpawnOptions, DelegateOptions, LifecycleHook } from "./client.js";
8
+ //# sourceMappingURL=advanced.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"advanced.d.ts","sourceRoot":"","sources":["../src/advanced.ts"],"names":[],"mappings":"AAUA,cAAc,eAAe,CAAC;AAC9B,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAC1B,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,16 @@
1
+ /*
2
+ * Copyright (C) 2026 Garudex Labs. All Rights Reserved.
3
+ * Caracal, a product of Garudex Labs
4
+ *
5
+ * Advanced surface: low-level primitives, codec, ambient context plumbing,
6
+ * and the raw coordinator client. Most integrators only need the default
7
+ * "@caracalai/sdk" entrypoint; reach for these when building a transport
8
+ * adapter or a framework shim.
9
+ */
10
+ export * from "./envelope.js";
11
+ export * from "./context.js";
12
+ export * from "./coordinator.js";
13
+ export * from "./primitives.js";
14
+ export * from "./http.js";
15
+ export { Caracal } from "./client.js";
16
+ //# sourceMappingURL=advanced.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"advanced.js","sourceRoot":"","sources":["../src/advanced.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,cAAc,eAAe,CAAC;AAC9B,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAC1B,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,61 @@
1
+ import { type CaracalContext } from "./context.js";
2
+ import { type HeaderGetter } from "./envelope.js";
3
+ import { type CoordinatorClient } from "./coordinator.js";
4
+ import { AgentKind, type DelegationConstraints } from "./coordinator.js";
5
+ export interface ResourceBinding {
6
+ resourceId: string;
7
+ upstreamPrefix: string;
8
+ }
9
+ export interface CaracalConfig {
10
+ coordinator: CoordinatorClient;
11
+ zoneId: string;
12
+ applicationId: string;
13
+ subjectToken: string;
14
+ gatewayUrl?: string;
15
+ resources?: ResourceBinding[];
16
+ defaultKind?: AgentKind;
17
+ defaultTtlSeconds?: number;
18
+ }
19
+ export interface SpawnOptions {
20
+ kind?: AgentKind;
21
+ ttlSeconds?: number;
22
+ sessionSid?: string;
23
+ parentId?: string;
24
+ metadata?: Record<string, unknown>;
25
+ traceId?: string;
26
+ }
27
+ export interface DelegateOptions {
28
+ to: string;
29
+ toApplicationId: string;
30
+ scopes: string[];
31
+ constraints?: DelegationConstraints;
32
+ ttlSeconds?: number;
33
+ }
34
+ export type LifecycleHook = (ctx: CaracalContext) => void | Promise<void>;
35
+ export declare class Caracal {
36
+ readonly config: CaracalConfig;
37
+ private agentStartHooks;
38
+ private agentEndHooks;
39
+ constructor(config: CaracalConfig);
40
+ static fromEnv(env?: NodeJS.ProcessEnv): Caracal;
41
+ spawn<T>(fn: () => Promise<T>, opts?: SpawnOptions): Promise<T>;
42
+ delegate<T>(opts: DelegateOptions, fn: () => Promise<T>): Promise<T>;
43
+ onAgentStart(cb: LifecycleHook): void;
44
+ onAgentEnd(cb: LifecycleHook): void;
45
+ private fire;
46
+ current(): CaracalContext | undefined;
47
+ headers(): Record<string, string>;
48
+ bindFromHeaders<T>(headers: Record<string, string | string[] | undefined> | HeaderGetter, fn: () => Promise<T>): Promise<T>;
49
+ /**
50
+ * Returns a fetch-shaped function that injects the Caracal envelope (traceparent
51
+ * + baggage) onto outbound requests and, for gateway-routed calls, replaces the
52
+ * `Authorization` header with the current subject token. Pass to any provider
53
+ * SDK that accepts a custom fetch.
54
+ */
55
+ transport(): typeof fetch;
56
+ private routeThroughGateway;
57
+ middleware(): (req: {
58
+ headers: Record<string, string | string[] | undefined>;
59
+ }, _res: unknown, next: (err?: unknown) => void) => void;
60
+ }
61
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAOA,OAAO,EAA2C,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAC5F,OAAO,EAIL,KAAK,YAAY,EAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,KAAK,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAO1D,OAAO,EAAE,SAAS,EAAE,KAAK,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzE,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,aAAa;IAC5B,WAAW,EAAE,iBAAiB,CAAC;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,eAAe,EAAE,CAAC;IAC9B,WAAW,CAAC,EAAE,SAAS,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CA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C,GAAG,YAAY,EACrE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC;IAqBb;;;;;OAKG;IACH,SAAS,IAAI,OAAO,KAAK;IAyBzB,OAAO,CAAC,mBAAmB;IAsC3B,UAAU,KAEN,KAAK;QAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAA;KAAE,EAC/D,MAAM,OAAO,EACb,MAAM,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,IAAI,KAC5B,IAAI;CAMV"}
package/dist/client.js ADDED
@@ -0,0 +1,233 @@
1
+ /*
2
+ * Copyright (C) 2026 Garudex Labs. All Rights Reserved.
3
+ * Caracal, a product of Garudex Labs
4
+ *
5
+ * Caracal: drop-in bound client wrapping zone, application, subject token, and coordinator.
6
+ */
7
+ import { bind, fromEnvelope, toEnvelope, current } from "./context.js";
8
+ import { decodeEnvelope, toHeaders, } from "./envelope.js";
9
+ import { spawn as spawnPrimitive, delegate as delegatePrimitive, } from "./primitives.js";
10
+ import { AgentKind } from "./coordinator.js";
11
+ export class Caracal {
12
+ config;
13
+ agentStartHooks = [];
14
+ agentEndHooks = [];
15
+ constructor(config) {
16
+ this.config = config;
17
+ }
18
+ static fromEnv(env = process.env) {
19
+ const url = env.CARACAL_COORDINATOR_URL;
20
+ const zoneId = env.CARACAL_ZONE_ID;
21
+ const applicationId = env.CARACAL_APPLICATION_ID;
22
+ const subjectToken = env.CARACAL_SUBJECT_TOKEN;
23
+ const gatewayUrl = env.CARACAL_GATEWAY_URL;
24
+ const missing = [
25
+ ["CARACAL_COORDINATOR_URL", url],
26
+ ["CARACAL_ZONE_ID", zoneId],
27
+ ["CARACAL_APPLICATION_ID", applicationId],
28
+ ["CARACAL_SUBJECT_TOKEN", subjectToken],
29
+ ].filter(([, v]) => !v).map(([k]) => k);
30
+ if (missing.length) {
31
+ throw new Error(`Caracal.fromEnv: missing ${missing.join(", ")}`);
32
+ }
33
+ return new Caracal({
34
+ coordinator: { baseUrl: url },
35
+ zoneId: zoneId,
36
+ applicationId: applicationId,
37
+ subjectToken: subjectToken,
38
+ gatewayUrl,
39
+ resources: parseResourceBindings(env.CARACAL_RESOURCES),
40
+ });
41
+ }
42
+ spawn(fn, opts = {}) {
43
+ const input = {
44
+ coordinator: this.config.coordinator,
45
+ zoneId: this.config.zoneId,
46
+ applicationId: this.config.applicationId,
47
+ subjectToken: this.config.subjectToken,
48
+ kind: opts.kind ?? this.config.defaultKind ?? AgentKind.Instance,
49
+ ttlSeconds: opts.ttlSeconds ?? this.config.defaultTtlSeconds,
50
+ sessionSid: opts.sessionSid,
51
+ parentId: opts.parentId,
52
+ metadata: opts.metadata,
53
+ traceId: opts.traceId,
54
+ onAgentStart: this.agentStartHooks.length ? (c) => this.fire(this.agentStartHooks, c) : undefined,
55
+ onAgentEnd: this.agentEndHooks.length ? (c) => this.fire(this.agentEndHooks, c) : undefined,
56
+ };
57
+ return spawnPrimitive(input, fn);
58
+ }
59
+ delegate(opts, fn) {
60
+ const input = {
61
+ coordinator: this.config.coordinator,
62
+ toAgentSessionId: opts.to,
63
+ toApplicationId: opts.toApplicationId,
64
+ scopes: opts.scopes,
65
+ constraints: opts.constraints,
66
+ ttlSeconds: opts.ttlSeconds,
67
+ };
68
+ return delegatePrimitive(input, fn);
69
+ }
70
+ onAgentStart(cb) {
71
+ this.agentStartHooks.push(cb);
72
+ }
73
+ onAgentEnd(cb) {
74
+ this.agentEndHooks.push(cb);
75
+ }
76
+ async fire(hooks, ctx) {
77
+ for (const h of hooks)
78
+ await h(ctx);
79
+ }
80
+ current() {
81
+ return current();
82
+ }
83
+ headers() {
84
+ const ctx = current();
85
+ if (!ctx) {
86
+ return toHeaders({
87
+ subjectToken: this.config.subjectToken,
88
+ hop: 0,
89
+ });
90
+ }
91
+ return toHeaders(toEnvelope(ctx));
92
+ }
93
+ bindFromHeaders(headers, fn) {
94
+ const env = typeof headers === "function"
95
+ ? decodeEnvelope(headers)
96
+ : decodeEnvelope((n) => {
97
+ const lower = n.toLowerCase();
98
+ for (const k of Object.keys(headers)) {
99
+ if (k.toLowerCase() === lower) {
100
+ const v = headers[k];
101
+ return Array.isArray(v) ? v[0] : v;
102
+ }
103
+ }
104
+ return undefined;
105
+ });
106
+ if (!env.subjectToken)
107
+ env.subjectToken = this.config.subjectToken;
108
+ const ctx = fromEnvelope(env, {
109
+ zoneId: this.config.zoneId,
110
+ clientId: this.config.applicationId,
111
+ });
112
+ return bind(ctx, fn);
113
+ }
114
+ /**
115
+ * Returns a fetch-shaped function that injects the Caracal envelope (traceparent
116
+ * + baggage) onto outbound requests and, for gateway-routed calls, replaces the
117
+ * `Authorization` header with the current subject token. Pass to any provider
118
+ * SDK that accepts a custom fetch.
119
+ */
120
+ transport() {
121
+ const outer = this;
122
+ const fn = (async (input, init) => {
123
+ const ctx = current();
124
+ const env = ctx
125
+ ? toEnvelope(ctx)
126
+ : { subjectToken: outer.config.subjectToken, hop: 0 };
127
+ const merged = new Headers(init?.headers ?? {});
128
+ for (const [k, v] of Object.entries(toHeaders(env))) {
129
+ if (!merged.has(k))
130
+ merged.set(k, v);
131
+ }
132
+ const fetchImpl = outer.config.coordinator.fetchImpl ?? fetch;
133
+ const explicitResource = merged.get("X-Caracal-Resource") ?? undefined;
134
+ const rewritten = outer.routeThroughGateway(input, explicitResource);
135
+ if (rewritten) {
136
+ merged.set("X-Caracal-Resource", rewritten.resourceId);
137
+ merged.set("Authorization", `Bearer ${env.subjectToken ?? outer.config.subjectToken}`);
138
+ return fetchImpl(rewritten.url, { ...init, headers: merged });
139
+ }
140
+ return fetchImpl(input, { ...init, headers: merged });
141
+ });
142
+ return fn;
143
+ }
144
+ routeThroughGateway(input, explicitResource) {
145
+ const gw = this.config.gatewayUrl;
146
+ if (!gw)
147
+ return null;
148
+ const raw = typeof input === "string"
149
+ ? input
150
+ : input instanceof URL
151
+ ? input.toString()
152
+ : input.url;
153
+ let parsed;
154
+ try {
155
+ parsed = new URL(raw);
156
+ }
157
+ catch {
158
+ return null;
159
+ }
160
+ if (sameOrigin(parsed, gw))
161
+ return null;
162
+ const binding = explicitResource
163
+ ? this.config.resources?.find((b) => b.resourceId === explicitResource)
164
+ : this.config.resources?.find((b) => urlMatchesPrefix(parsed, b.upstreamPrefix));
165
+ if (!binding && !explicitResource)
166
+ return null;
167
+ const gateway = new URL(gw);
168
+ let suffix = parsed.pathname + parsed.search;
169
+ if (binding) {
170
+ const prefix = new URL(binding.upstreamPrefix);
171
+ if (parsed.pathname.startsWith(prefix.pathname) && prefix.pathname !== "/") {
172
+ suffix = parsed.pathname.slice(prefix.pathname.length) + parsed.search;
173
+ if (!suffix.startsWith("/"))
174
+ suffix = "/" + suffix;
175
+ }
176
+ }
177
+ const base = gateway.origin + gateway.pathname.replace(/\/$/, "");
178
+ const target = base + suffix;
179
+ return { url: target, resourceId: binding?.resourceId ?? explicitResource };
180
+ }
181
+ middleware() {
182
+ return (req, _res, next) => {
183
+ this.bindFromHeaders(req.headers, async () => {
184
+ next();
185
+ }).catch(next);
186
+ };
187
+ }
188
+ }
189
+ function sameOrigin(a, b) {
190
+ try {
191
+ const o = new URL(b);
192
+ return a.protocol === o.protocol && a.host === o.host;
193
+ }
194
+ catch {
195
+ return false;
196
+ }
197
+ }
198
+ function urlMatchesPrefix(target, prefix) {
199
+ let p;
200
+ try {
201
+ p = new URL(prefix);
202
+ }
203
+ catch {
204
+ return false;
205
+ }
206
+ if (p.protocol !== target.protocol)
207
+ return false;
208
+ if (p.host !== target.host)
209
+ return false;
210
+ if (p.pathname === "/" || p.pathname === "")
211
+ return true;
212
+ return target.pathname === p.pathname || target.pathname.startsWith(p.pathname.endsWith("/") ? p.pathname : p.pathname + "/");
213
+ }
214
+ function parseResourceBindings(raw) {
215
+ if (!raw)
216
+ return undefined;
217
+ const out = [];
218
+ for (const entry of raw.split(",")) {
219
+ const trimmed = entry.trim();
220
+ if (!trimmed)
221
+ continue;
222
+ const idx = trimmed.indexOf("=");
223
+ if (idx <= 0)
224
+ continue;
225
+ const resourceId = trimmed.slice(0, idx).trim();
226
+ const upstreamPrefix = trimmed.slice(idx + 1).trim();
227
+ if (resourceId && upstreamPrefix) {
228
+ out.push({ resourceId, upstreamPrefix });
229
+ }
230
+ }
231
+ return out.length ? out : undefined;
232
+ }
233
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,UAAU,EAAE,OAAO,EAAuB,MAAM,cAAc,CAAC;AAC5F,OAAO,EACL,cAAc,EACd,SAAS,GAGV,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,KAAK,IAAI,cAAc,EACvB,QAAQ,IAAI,iBAAiB,GAG9B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,EAA8B,MAAM,kBAAkB,CAAC;AAqCzE,MAAM,OAAO,OAAO;IAIU;IAHpB,eAAe,GAAoB,EAAE,CAAC;IACtC,aAAa,GAAoB,EAAE,CAAC;IAE5C,YAA4B,MAAqB;QAArB,WAAM,GAAN,MAAM,CAAe;IAAG,CAAC;IAErD,MAAM,CAAC,OAAO,CAAC,MAAyB,OAAO,CAAC,GAAG;QACjD,MAAM,GAAG,GAAG,GAAG,CAAC,uBAAuB,CAAC;QACxC,MAAM,MAAM,GAAG,GAAG,CAAC,eAAe,CAAC;QACnC,MAAM,aAAa,GAAG,GAAG,CAAC,sBAAsB,CAAC;QACjD,MAAM,YAAY,GAAG,GAAG,CAAC,qBAAqB,CAAC;QAC/C,MAAM,UAAU,GAAG,GAAG,CAAC,mBAAmB,CAAC;QAC3C,MAAM,OAAO,GAAG;YACd,CAAC,yBAAyB,EAAE,GAAG,CAAC;YAChC,CAAC,iBAAiB,EAAE,MAAM,CAAC;YAC3B,CAAC,wBAAwB,EAAE,aAAa,CAA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AE,SAAS;QACvB,MAAM,UAAU,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;QAChD,MAAM,cAAc,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACrD,IAAI,UAAU,IAAI,cAAc,EAAE,CAAC;YACjC,GAAG,CAAC,IAAI,CAAC,EAAE,UAAU,EAAE,cAAc,EAAE,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;AACtC,CAAC"}
@@ -0,0 +1,21 @@
1
+ import { Envelope } from "./envelope.js";
2
+ export interface CaracalContext {
3
+ subjectToken: string;
4
+ zoneId: string;
5
+ clientId: string;
6
+ agentSessionId?: string;
7
+ delegationEdgeId?: string;
8
+ parentEdgeId?: string;
9
+ sessionId?: string;
10
+ traceId?: string;
11
+ hop: number;
12
+ }
13
+ export declare function current(): CaracalContext | undefined;
14
+ export declare function bind<T>(ctx: CaracalContext, fn: () => T | Promise<T>): T | Promise<T>;
15
+ export declare function withOverrides<T>(patch: Partial<CaracalContext>, fn: () => T | Promise<T>): T | Promise<T>;
16
+ export declare function toEnvelope(ctx: CaracalContext): Envelope;
17
+ export declare function fromEnvelope(env: Envelope, base: {
18
+ zoneId: string;
19
+ clientId: string;
20
+ }): CaracalContext;
21
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,MAAM,WAAW,cAAc;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;CACb;AAID,wBAAgB,OAAO,IAAI,cAAc,GAAG,SAAS,CAEpD;AAED,wBAAgB,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,cAAc,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAErF;AAED,wBAAgB,aAAa,CAAC,CAAC,EAC7B,KAAK,EAAE,OAAO,CAAC,cAAc,CAAC,EAC9B,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GACvB,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAIhB;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,cAAc,GAAG,QAAQ,CASxD;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAAG,cAAc,CAYtG"}
@@ -0,0 +1,45 @@
1
+ /*
2
+ * Copyright (C) 2026 Garudex Labs. All Rights Reserved.
3
+ * Caracal, a product of Garudex Labs
4
+ *
5
+ * CaracalContext: ambient identity and delegation context propagated across async boundaries.
6
+ */
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ const storage = new AsyncLocalStorage();
9
+ export function current() {
10
+ return storage.getStore();
11
+ }
12
+ export function bind(ctx, fn) {
13
+ return storage.run(ctx, fn);
14
+ }
15
+ export function withOverrides(patch, fn) {
16
+ const base = current();
17
+ if (!base)
18
+ throw new Error("withOverrides requires an existing Caracal context");
19
+ return storage.run({ ...base, ...patch }, fn);
20
+ }
21
+ export function toEnvelope(ctx) {
22
+ return {
23
+ subjectToken: ctx.subjectToken,
24
+ agentSessionId: ctx.agentSessionId,
25
+ delegationEdgeId: ctx.delegationEdgeId,
26
+ parentEdgeId: ctx.parentEdgeId,
27
+ traceId: ctx.traceId,
28
+ hop: ctx.hop,
29
+ };
30
+ }
31
+ export function fromEnvelope(env, base) {
32
+ if (!env.subjectToken)
33
+ throw new Error("envelope missing subject token");
34
+ return {
35
+ subjectToken: env.subjectToken,
36
+ zoneId: base.zoneId,
37
+ clientId: base.clientId,
38
+ agentSessionId: env.agentSessionId,
39
+ delegationEdgeId: env.delegationEdgeId,
40
+ parentEdgeId: env.parentEdgeId,
41
+ traceId: env.traceId,
42
+ hop: env.hop,
43
+ };
44
+ }
45
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAerD,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAkB,CAAC;AAExD,MAAM,UAAU,OAAO;IACrB,OAAO,OAAO,CAAC,QAAQ,EAAE,CAAC;AAC5B,CAAC;AAED,MAAM,UAAU,IAAI,CAAI,GAAmB,EAAE,EAAwB;IACnE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;AAC9B,CAAC;AAED,MAAM,UAAU,aAAa,CAC3B,KAA8B,EAC9B,EAAwB;IAExB,MAAM,IAAI,GAAG,OAAO,EAAE,CAAC;IACvB,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACjF,OAAO,OAAO,CAAC,GAAG,CAAC,EAAE,GAAG,IAAI,EAAE,GAAG,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,GAAmB;IAC5C,OAAO;QACL,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,cAAc,EAAE,GAAG,CAAC,cAAc;QAClC,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;QACtC,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,GAAG,EAAE,GAAG,CAAC,GAAG;KACb,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAa,EAAE,IAA0C;IACpF,IAAI,CAAC,GAAG,CAAC,YAAY;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACzE,OAAO;QACL,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,cAAc,EAAE,GAAG,CAAC,cAAc;QAClC,gBAAgB,EAAE,GAAG,CAAC,gBAAgB;QACtC,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,GAAG,EAAE,GAAG,CAAC,GAAG;KACb,CAAC;AACJ,CAAC"}
@@ -0,0 +1,47 @@
1
+ export interface CoordinatorClient {
2
+ baseUrl: string;
3
+ fetchImpl?: typeof fetch;
4
+ }
5
+ export declare const AgentKind: {
6
+ readonly Service: "service";
7
+ readonly Instance: "instance";
8
+ readonly Ephemeral: "ephemeral";
9
+ };
10
+ export type AgentKind = typeof AgentKind[keyof typeof AgentKind];
11
+ export interface DelegationConstraints {
12
+ resources?: string[];
13
+ actions?: string[];
14
+ maxDepth?: number;
15
+ expiresAt?: string;
16
+ }
17
+ export interface SpawnRequest {
18
+ zoneId: string;
19
+ applicationId: string;
20
+ sessionSid?: string;
21
+ parentId?: string;
22
+ kind?: AgentKind;
23
+ ttlSeconds?: number;
24
+ metadata?: Record<string, unknown>;
25
+ }
26
+ export interface SpawnResponse {
27
+ id?: string;
28
+ agent_session_id: string;
29
+ }
30
+ export interface DelegationRequest {
31
+ zoneId: string;
32
+ issuerApplicationId: string;
33
+ sourceSessionId: string;
34
+ targetSessionId: string;
35
+ receiverApplicationId: string;
36
+ scopes: string[];
37
+ constraints?: DelegationConstraints;
38
+ ttlSeconds?: number;
39
+ }
40
+ export interface DelegationResponse {
41
+ id?: string;
42
+ delegation_edge_id: string;
43
+ }
44
+ export declare function spawnAgent(client: CoordinatorClient, bearer: string, req: SpawnRequest): Promise<SpawnResponse>;
45
+ export declare function terminateAgent(client: CoordinatorClient, bearer: string, zoneId: string, agentSessionId: string): Promise<void>;
46
+ export declare function createDelegation(client: CoordinatorClient, bearer: string, req: DelegationRequest): Promise<DelegationResponse>;
47
+ //# sourceMappingURL=coordinator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coordinator.d.ts","sourceRoot":"","sources":["../src/coordinator.ts"],"names":[],"mappings":"AAOA,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAC1B;AAED,eAAO,MAAM,SAAS;;;;CAIZ,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,OAAO,SAAS,CAAC,MAAM,OAAO,SAAS,CAAC,CAAC;AAEjE,MAAM,WAAW,qBAAqB;IACpC,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,MAAM,WAAW,aAAa;IAC5B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,mBAAmB,EAAE,MAAM,CAAC;IAC5B,eAAe,EAAE,MAAM,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,qBAAqB,EAAE,MAAM,CAAC;IAC9B,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,WAAW,CAAC,EAAE,qBAAqB,CAAC;IACpC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,kBAAkB;IACjC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAyBD,wBAAsB,UAAU,CAC9B,MAAM,EAAE,iBAAiB,EACzB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,YAAY,GAChB,OAAO,CAAC,aAAa,CAAC,CAWxB;AAED,wBAAsB,cAAc,CAClC,MAAM,EAAE,iBAAiB,EACzB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,IAAI,CAAC,CASf;AAED,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,iBAAiB,EACzB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,iBAAiB,GACrB,OAAO,CAAC,kBAAkB,CAAC,CAoB7B"}
@@ -0,0 +1,70 @@
1
+ /*
2
+ * Copyright (C) 2026 Garudex Labs. All Rights Reserved.
3
+ * Caracal, a product of Garudex Labs
4
+ *
5
+ * Coordinator REST client used by SDK primitives.
6
+ */
7
+ export const AgentKind = {
8
+ Service: "service",
9
+ Instance: "instance",
10
+ Ephemeral: "ephemeral",
11
+ };
12
+ async function call(client, method, path, bearer, body) {
13
+ const fetchFn = client.fetchImpl ?? fetch;
14
+ const res = await fetchFn(`${client.baseUrl}${path}`, {
15
+ method,
16
+ headers: {
17
+ "content-type": "application/json",
18
+ authorization: `Bearer ${bearer}`,
19
+ },
20
+ body: body ? JSON.stringify(body) : undefined,
21
+ });
22
+ if (!res.ok) {
23
+ const text = await res.text().catch(() => "");
24
+ throw new Error(`coordinator ${method} ${path} failed: ${res.status} ${text}`);
25
+ }
26
+ return (await res.json());
27
+ }
28
+ export async function spawnAgent(client, bearer, req) {
29
+ const res = await call(client, "POST", `/zones/${encodeURIComponent(req.zoneId)}/agents`, bearer, {
30
+ application_id: req.applicationId,
31
+ session_sid: req.sessionSid,
32
+ parent_id: req.parentId,
33
+ kind: req.kind ?? AgentKind.Instance,
34
+ ttl_seconds: req.ttlSeconds,
35
+ metadata: req.metadata,
36
+ });
37
+ if (!res.agent_session_id && res.id)
38
+ res.agent_session_id = res.id;
39
+ return res;
40
+ }
41
+ export async function terminateAgent(client, bearer, zoneId, agentSessionId) {
42
+ const fetchFn = client.fetchImpl ?? fetch;
43
+ await fetchFn(`${client.baseUrl}/zones/${encodeURIComponent(zoneId)}/agents/${encodeURIComponent(agentSessionId)}`, {
44
+ method: "DELETE",
45
+ headers: { authorization: `Bearer ${bearer}` },
46
+ }).catch(() => undefined);
47
+ }
48
+ export async function createDelegation(client, bearer, req) {
49
+ const constraints = req.constraints
50
+ ? {
51
+ resources: req.constraints.resources,
52
+ actions: req.constraints.actions,
53
+ max_depth: req.constraints.maxDepth,
54
+ expires_at: req.constraints.expiresAt,
55
+ }
56
+ : undefined;
57
+ const res = await call(client, "POST", `/zones/${encodeURIComponent(req.zoneId)}/delegations`, bearer, {
58
+ issuer_application_id: req.issuerApplicationId,
59
+ source_session_id: req.sourceSessionId,
60
+ target_session_id: req.targetSessionId,
61
+ receiver_application_id: req.receiverApplicationId,
62
+ scopes: req.scopes,
63
+ constraints,
64
+ ttl_seconds: req.ttlSeconds,
65
+ });
66
+ if (!res.delegation_edge_id && res.id)
67
+ res.delegation_edge_id = res.id;
68
+ return res;
69
+ }
70
+ //#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,CAAC;IACd,MAAM,GAAG,GAAG,MAAM,IAAI,CAAqB,MAAM,EAAE,MAAM,EAAE,UAAU,kBAAkB,CAAC,GAAG,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,EAAE;QACzH,qBAAqB,EAAE,GAAG,CAAC,mBAAmB;QAC9C,iBAAiB,EAAE,GAAG,CAAC,eAAe;QACtC,iBAAiB,EAAE,GAAG,CAAC,eAAe;QACtC,uBAAuB,EAAE,GAAG,CAAC,qBAAqB;QAClD,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,WAAW;QACX,WAAW,EAAE,GAAG,CAAC,UAAU;KAC5B,CAAC,CAAC;IACH,IAAI,CAAC,GAAG,CAAC,kBAAkB,IAAI,GAAG,CAAC,EAAE;QAAE,GAAG,CAAC,kBAAkB,GAAG,GAAG,CAAC,EAAE,CAAC;IACvE,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,31 @@
1
+ export declare const HeaderAuthorization = "authorization";
2
+ export declare const HeaderTraceparent = "traceparent";
3
+ export declare const HeaderBaggage = "baggage";
4
+ export declare const BaggageAgentSession = "caracal.agent_session";
5
+ export declare const BaggageDelegationEdge = "caracal.delegation_edge";
6
+ export declare const BaggageParentEdge = "caracal.parent_edge";
7
+ export declare const BaggageHop = "caracal.hop";
8
+ export declare const MaxHop = 32;
9
+ export interface Envelope {
10
+ subjectToken?: string;
11
+ agentSessionId?: string;
12
+ delegationEdgeId?: string;
13
+ parentEdgeId?: string;
14
+ traceId?: string;
15
+ hop: number;
16
+ }
17
+ export type HeaderGetter = (name: string) => string | undefined;
18
+ export type HeaderSetter = (name: string, value: string) => void;
19
+ export declare function formatTraceparent(traceId: string): string;
20
+ export declare function parseTraceparent(value: string): {
21
+ traceId: string;
22
+ } | undefined;
23
+ export declare function encodeBaggage(entries: Record<string, string | undefined>): string;
24
+ export declare function parseBaggage(value: string | undefined): Record<string, string>;
25
+ export declare function fromHeaders(headers: Record<string, string | string[] | undefined>): Envelope;
26
+ export declare function decodeEnvelope(get: HeaderGetter): Envelope;
27
+ export declare function encodeEnvelope(env: Envelope, set: HeaderSetter): void;
28
+ export declare function toHeaders(env: Envelope): Record<string, string>;
29
+ export declare function inject(env: Envelope, carrier: Record<string, string>): void;
30
+ export declare function extract(carrier: Record<string, string | string[] | undefined>): Envelope;
31
+ //# sourceMappingURL=envelope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAYA,eAAO,MAAM,mBAAmB,kBAAkB,CAAC;AACnD,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAC/C,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC,eAAO,MAAM,mBAAmB,0BAA0B,CAAC;AAC3D,eAAO,MAAM,qBAAqB,4BAA4B,CAAC;AAC/D,eAAO,MAAM,iBAAiB,wBAAwB,CAAC;AACvD,eAAO,MAAM,UAAU,gBAAgB,CAAC;AAExC,eAAO,MAAM,MAAM,KAAK,CAAC;AAEzB,MAAM,WAAW,QAAQ;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;AAChE,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;AAyBjE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAK/E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM,CAOjF;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAgB9E;AAaD,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,GAAG,QAAQ,CAE5F;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,GAAG,QAAQ,CAiB1D;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,YAAY,GAAG,IAAI,CAWrE;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAM/D;AAED,wBAAgB,MAAM,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAI3E;AAED,wBAAgB,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,GAAG,QAAQ,CAExF"}
@@ -0,0 +1,140 @@
1
+ /*
2
+ * Copyright (C) 2026 Garudex Labs. All Rights Reserved.
3
+ * Caracal, a product of Garudex Labs
4
+ *
5
+ * Wire envelope using W3C Trace Context (traceparent) and W3C Baggage.
6
+ *
7
+ * Subject token rides in Authorization. Caracal-specific cross-cutting fields
8
+ * (agent_session, delegation_edge, parent_edge, hop) ride in Baggage under the
9
+ * caracal.* namespace. Trace identifiers ride in traceparent so any
10
+ * OpenTelemetry-aware client/server propagates them transparently.
11
+ */
12
+ export const HeaderAuthorization = "authorization";
13
+ export const HeaderTraceparent = "traceparent";
14
+ export const HeaderBaggage = "baggage";
15
+ export const BaggageAgentSession = "caracal.agent_session";
16
+ export const BaggageDelegationEdge = "caracal.delegation_edge";
17
+ export const BaggageParentEdge = "caracal.parent_edge";
18
+ export const BaggageHop = "caracal.hop";
19
+ export const MaxHop = 32;
20
+ const TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
21
+ function randomHex(byteLen) {
22
+ const bytes = new Uint8Array(byteLen);
23
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
24
+ crypto.getRandomValues(bytes);
25
+ }
26
+ else {
27
+ for (let i = 0; i < byteLen; i++)
28
+ bytes[i] = Math.floor(Math.random() * 256);
29
+ }
30
+ let s = "";
31
+ for (const b of bytes)
32
+ s += b.toString(16).padStart(2, "0");
33
+ return s;
34
+ }
35
+ function genTraceId() {
36
+ return randomHex(16);
37
+ }
38
+ function genSpanId() {
39
+ return randomHex(8);
40
+ }
41
+ export function formatTraceparent(traceId) {
42
+ return `00-${traceId}-${genSpanId()}-01`;
43
+ }
44
+ export function parseTraceparent(value) {
45
+ const m = TRACEPARENT_RE.exec(value.trim());
46
+ if (!m)
47
+ return undefined;
48
+ if (m[2] === "00000000000000000000000000000000")
49
+ return undefined;
50
+ return { traceId: m[2] };
51
+ }
52
+ export function encodeBaggage(entries) {
53
+ const parts = [];
54
+ for (const [k, v] of Object.entries(entries)) {
55
+ if (v === undefined || v === "")
56
+ continue;
57
+ parts.push(`${k}=${encodeURIComponent(v)}`);
58
+ }
59
+ return parts.join(",");
60
+ }
61
+ export function parseBaggage(value) {
62
+ const out = {};
63
+ if (!value)
64
+ return out;
65
+ for (const piece of value.split(",")) {
66
+ const eq = piece.indexOf("=");
67
+ if (eq <= 0)
68
+ continue;
69
+ const k = piece.slice(0, eq).trim();
70
+ const semi = piece.indexOf(";", eq + 1);
71
+ const rawV = (semi === -1 ? piece.slice(eq + 1) : piece.slice(eq + 1, semi)).trim();
72
+ try {
73
+ out[k] = decodeURIComponent(rawV);
74
+ }
75
+ catch {
76
+ out[k] = rawV;
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+ const headerKey = (h, name) => {
82
+ const lower = name.toLowerCase();
83
+ for (const k of Object.keys(h)) {
84
+ if (k.toLowerCase() === lower) {
85
+ const v = h[k];
86
+ return Array.isArray(v) ? v[0] : v;
87
+ }
88
+ }
89
+ return undefined;
90
+ };
91
+ export function fromHeaders(headers) {
92
+ return decodeEnvelope((n) => headerKey(headers, n));
93
+ }
94
+ export function decodeEnvelope(get) {
95
+ const auth = get(HeaderAuthorization);
96
+ const subjectToken = auth && /^Bearer\s+/i.test(auth) ? auth.replace(/^Bearer\s+/i, "").trim() : undefined;
97
+ const tp = get(HeaderTraceparent);
98
+ const traceId = tp ? parseTraceparent(tp)?.traceId : undefined;
99
+ const bag = parseBaggage(get(HeaderBaggage));
100
+ const hopRaw = bag[BaggageHop];
101
+ const hop = hopRaw ? Math.max(0, Math.min(MaxHop, parseInt(hopRaw, 10) || 0)) : 0;
102
+ return {
103
+ subjectToken,
104
+ agentSessionId: bag[BaggageAgentSession] || undefined,
105
+ delegationEdgeId: bag[BaggageDelegationEdge] || undefined,
106
+ parentEdgeId: bag[BaggageParentEdge] || undefined,
107
+ traceId,
108
+ hop,
109
+ };
110
+ }
111
+ export function encodeEnvelope(env, set) {
112
+ if (env.subjectToken)
113
+ set(HeaderAuthorization, `Bearer ${env.subjectToken}`);
114
+ const traceId = env.traceId && /^[0-9a-f]{32}$/.test(env.traceId) ? env.traceId : genTraceId();
115
+ set(HeaderTraceparent, formatTraceparent(traceId));
116
+ const baggage = encodeBaggage({
117
+ [BaggageAgentSession]: env.agentSessionId,
118
+ [BaggageDelegationEdge]: env.delegationEdgeId,
119
+ [BaggageParentEdge]: env.parentEdgeId,
120
+ [BaggageHop]: String(env.hop),
121
+ });
122
+ if (baggage)
123
+ set(HeaderBaggage, baggage);
124
+ }
125
+ export function toHeaders(env) {
126
+ const out = {};
127
+ encodeEnvelope(env, (n, v) => {
128
+ out[n] = v;
129
+ });
130
+ return out;
131
+ }
132
+ export function inject(env, carrier) {
133
+ encodeEnvelope(env, (n, v) => {
134
+ carrier[n] = v;
135
+ });
136
+ }
137
+ export function extract(carrier) {
138
+ return fromHeaders(carrier);
139
+ }
140
+ //# sourceMappingURL=envelope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,MAAM,CAAC,MAAM,mBAAmB,GAAG,eAAe,CAAC;AACnD,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAC;AAC/C,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AAEvC,MAAM,CAAC,MAAM,mBAAmB,GAAG,uBAAuB,CAAC;AAC3D,MAAM,CAAC,MAAM,qBAAqB,GAAG,yBAAyB,CAAC;AAC/D,MAAM,CAAC,MAAM,iBAAiB,GAAG,qBAAqB,CAAC;AACvD,MAAM,CAAC,MAAM,UAAU,GAAG,aAAa,CAAC;AAExC,MAAM,CAAC,MAAM,MAAM,GAAG,EAAE,CAAC;AAczB,MAAM,cAAc,GAClB,6DAA6D,CAAC;AAEhE,SAAS,SAAS,CAAC,OAAe;IAChC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;IACtC,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;QAC5D,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAChC,CAAC;SAAM,CAAC;QACN,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE;YAAE,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,CAAC;IAC/E,CAAC;IACD,IAAI,CAAC,GAAG,EAAE,CAAC;IACX,KAAK,MAAM,CAAC,IAAI,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CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,OAAsD;IAC5E,OAAO,WAAW,CAAC,OAAO,CAAC,CAAC;AAC9B,CAAC"}
package/dist/http.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { Caracal } from "./client.js";
2
+ export interface IncomingLike {
3
+ headers: Record<string, string | string[] | undefined>;
4
+ }
5
+ export type ConnectMiddleware = (req: IncomingLike, res: unknown, next: (err?: unknown) => void) => void;
6
+ export declare function caracalHttpMiddleware(caracal: Caracal): ConnectMiddleware;
7
+ export interface FastifyRequestLike {
8
+ headers: Record<string, string | string[] | undefined>;
9
+ }
10
+ export declare function caracalFastifyHook(caracal: Caracal): (req: FastifyRequestLike) => Promise<void>;
11
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;CACxD;AAED,MAAM,MAAM,iBAAiB,GAAG,CAC9B,GAAG,EAAE,YAAY,EACjB,GAAG,EAAE,OAAO,EACZ,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,IAAI,KAC1B,IAAI,CAAC;AAEV,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,iBAAiB,CAQzE;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;CACxD;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,IACnC,KAAK,kBAAkB,mBAGtC"}
package/dist/http.js ADDED
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright (C) 2026 Garudex Labs. All Rights Reserved.
3
+ * Caracal, a product of Garudex Labs
4
+ *
5
+ * Generic HTTP server middleware: extracts the wire envelope from incoming requests
6
+ * and binds a CaracalContext for the handler scope. Works with Express, Connect,
7
+ * Fastify (via preHandler), and any framework exposing (req, res, next).
8
+ */
9
+ export function caracalHttpMiddleware(caracal) {
10
+ return (req, _res, next) => {
11
+ caracal
12
+ .bindFromHeaders(req.headers, async () => {
13
+ next();
14
+ })
15
+ .catch(next);
16
+ };
17
+ }
18
+ export function caracalFastifyHook(caracal) {
19
+ return async (req) => {
20
+ await caracal.bindFromHeaders(req.headers, async () => undefined);
21
+ };
22
+ }
23
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAcH,MAAM,UAAU,qBAAqB,CAAC,OAAgB;IACpD,OAAO,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QACzB,OAAO;aACJ,eAAe,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,IAAI,EAAE;YACvC,IAAI,EAAE,CAAC;QACT,CAAC,CAAC;aACD,KAAK,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC;AAMD,MAAM,UAAU,kBAAkB,CAAC,OAAgB;IACjD,OAAO,KAAK,EAAE,GAAuB,EAAE,EAAE;QACvC,MAAM,OAAO,CAAC,eAAe,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC;IACpE,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,8 @@
1
+ export { Caracal } from "./client.js";
2
+ export type { CaracalConfig, SpawnOptions, DelegateOptions, ResourceBinding, LifecycleHook } from "./client.js";
3
+ export type { CaracalContext } from "./context.js";
4
+ export type { CoordinatorClient } from "./coordinator.js";
5
+ export { AgentKind } from "./coordinator.js";
6
+ export type { DelegationConstraints } from "./coordinator.js";
7
+ export type { Envelope } from "./envelope.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAChH,YAAY,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,YAAY,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAC9D,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /*
2
+ * Copyright (C) 2026 Garudex Labs. All Rights Reserved.
3
+ * Caracal, a product of Garudex Labs
4
+ *
5
+ * Public surface of the Caracal SDK.
6
+ */
7
+ export { Caracal } from "./client.js";
8
+ export { AgentKind } from "./coordinator.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAItC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { CaracalContext } from "./context.js";
2
+ import { CoordinatorClient, AgentKind, DelegationConstraints } from "./coordinator.js";
3
+ export interface SpawnInput {
4
+ coordinator: CoordinatorClient;
5
+ zoneId: string;
6
+ applicationId: string;
7
+ subjectToken: string;
8
+ sessionSid?: string;
9
+ parentId?: string;
10
+ kind?: AgentKind;
11
+ ttlSeconds?: number;
12
+ metadata?: Record<string, unknown>;
13
+ traceId?: string;
14
+ onAgentStart?: (ctx: CaracalContext) => void | Promise<void>;
15
+ onAgentEnd?: (ctx: CaracalContext) => void | Promise<void>;
16
+ }
17
+ export declare function spawn<T>(input: SpawnInput, fn: () => Promise<T>): Promise<T>;
18
+ export interface DelegateInput {
19
+ coordinator: CoordinatorClient;
20
+ toAgentSessionId: string;
21
+ toApplicationId: string;
22
+ scopes: string[];
23
+ constraints?: DelegationConstraints;
24
+ ttlSeconds?: number;
25
+ }
26
+ export declare function delegate<T>(input: DelegateInput, fn: () => Promise<T>): Promise<T>;
27
+ //# sourceMappingURL=primitives.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"primitives.d.ts","sourceRoot":"","sources":["../src/primitives.ts"],"names":[],"mappings":"AAOA,OAAO,EAAiB,cAAc,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EACL,iBAAiB,EAIjB,SAAS,EACT,qBAAqB,EACtB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,UAAU;IACzB,WAAW,EAAE,iBAAiB,CAAC;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7D,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5D;AAED,wBAAsB,KAAK,CAAC,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAiClF;AAED,MAAM,WAAW,aAAa;IAC5B,WAAW,EAAE,iBAAiB,CAAC;IAC/B,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,WAAW,CAAC,EAAE,qBAAqB,CAAC;IACpC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,wBAAsB,QAAQ,CAAC,CAAC,EAC9B,KAAK,EAAE,aAAa,EACpB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CAuBZ"}
@@ -0,0 +1,71 @@
1
+ /*
2
+ * Copyright (C) 2026 Garudex Labs. All Rights Reserved.
3
+ * Caracal, a product of Garudex Labs
4
+ *
5
+ * SDK primitives: spawn an agent session and delegate authority.
6
+ */
7
+ import { bind, current } from "./context.js";
8
+ import { spawnAgent, terminateAgent, createDelegation, AgentKind, } from "./coordinator.js";
9
+ export async function spawn(input, fn) {
10
+ const parent = current();
11
+ const parentId = input.parentId ?? parent?.agentSessionId;
12
+ const bearer = input.subjectToken;
13
+ const kind = input.kind ?? AgentKind.Instance;
14
+ const res = await spawnAgent(input.coordinator, bearer, {
15
+ zoneId: input.zoneId,
16
+ applicationId: input.applicationId,
17
+ sessionSid: input.sessionSid,
18
+ parentId,
19
+ kind,
20
+ ttlSeconds: input.ttlSeconds,
21
+ metadata: input.metadata,
22
+ });
23
+ const ctx = {
24
+ subjectToken: bearer,
25
+ zoneId: input.zoneId,
26
+ clientId: input.applicationId,
27
+ agentSessionId: res.agent_session_id,
28
+ parentEdgeId: parent?.delegationEdgeId,
29
+ sessionId: input.sessionSid ?? parent?.sessionId,
30
+ traceId: input.traceId ?? parent?.traceId,
31
+ hop: parent?.hop ?? 0,
32
+ };
33
+ if (input.onAgentStart)
34
+ await input.onAgentStart(ctx);
35
+ try {
36
+ return await bind(ctx, fn);
37
+ }
38
+ finally {
39
+ if (input.onAgentEnd)
40
+ await input.onAgentEnd(ctx);
41
+ if (kind !== AgentKind.Service) {
42
+ await terminateAgent(input.coordinator, bearer, input.zoneId, res.agent_session_id);
43
+ }
44
+ }
45
+ }
46
+ export async function delegate(input, fn) {
47
+ const ctx = current();
48
+ if (!ctx)
49
+ throw new Error("delegate requires a Caracal context bound on this path");
50
+ if (!ctx.agentSessionId) {
51
+ throw new Error("delegate requires an active agent session in context");
52
+ }
53
+ const res = await createDelegation(input.coordinator, ctx.subjectToken, {
54
+ zoneId: ctx.zoneId,
55
+ issuerApplicationId: ctx.clientId,
56
+ sourceSessionId: ctx.agentSessionId,
57
+ targetSessionId: input.toAgentSessionId,
58
+ receiverApplicationId: input.toApplicationId,
59
+ scopes: input.scopes,
60
+ constraints: input.constraints,
61
+ ttlSeconds: input.ttlSeconds,
62
+ });
63
+ const child = {
64
+ ...ctx,
65
+ parentEdgeId: ctx.delegationEdgeId,
66
+ delegationEdgeId: res.delegation_edge_id,
67
+ hop: ctx.hop + 1,
68
+ };
69
+ return bind(child, fn);
70
+ }
71
+ //# sourceMappingURL=primitives.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"primitives.js","sourceRoot":"","sources":["../src/primitives.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAkB,MAAM,cAAc,CAAC;AAC7D,OAAO,EAEL,UAAU,EACV,cAAc,EACd,gBAAgB,EAChB,SAAS,GAEV,MAAM,kBAAkB,CAAC;AAiB1B,MAAM,CAAC,KAAK,UAAU,KAAK,CAAI,KAAiB,EAAE,EAAoB;IACpE,MAAM,MAAM,GAAG,OAAO,EAAE,CAAC;IACzB,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,IAAI,MAAM,EAAE,cAAc,CAAC;IAC1D,MA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AAC,CAAC;QACtF,CAAC;IACH,CAAC;AACH,CAAC;AAWD,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,KAAoB,EACpB,EAAoB;IAEpB,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;IACtB,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IACpF,IAAI,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,KAAK,CAAC,WAAW,EAAE,GAAG,CAAC,YAAY,EAAE;QACtE,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,mBAAmB,EAAE,GAAG,CAAC,QAAQ;QACjC,eAAe,EAAE,GAAG,CAAC,cAAc;QACnC,eAAe,EAAE,KAAK,CAAC,gBAAgB;QACvC,qBAAqB,EAAE,KAAK,CAAC,eAAe;QAC5C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,UAAU,EAAE,KAAK,CAAC,UAAU;KAC7B,CAAC,CAAC;IACH,MAAM,KAAK,GAAmB;QAC5B,GAAG,GAAG;QACN,YAAY,EAAE,GAAG,CAAC,gBAAgB;QAClC,gBAAgB,EAAE,GAAG,CAAC,kBAAkB;QACxC,GAAG,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC;KACjB,CAAC;IACF,OAAQ,IAAI,CAAC,KAAK,EAAE,EAAE,CAAgB,CAAC;AACzC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@caracalai/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Caracal agent identity and delegation SDK.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://github.com/Garudex-Labs/caracal",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Garudex-Labs/caracal.git",
10
+ "directory": "packages/sdk/ts"
11
+ },
12
+ "keywords": ["caracal", "agent", "identity", "delegation", "sdk"],
13
+ "type": "module",
14
+ "main": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.js",
19
+ "types": "./dist/index.d.ts"
20
+ },
21
+ "./advanced": {
22
+ "import": "./dist/advanced.js",
23
+ "types": "./dist/advanced.d.ts"
24
+ }
25
+ },
26
+ "files": ["dist", "README.md", "LICENSE"],
27
+ "publishConfig": { "access": "public" },
28
+ "scripts": {
29
+ "build": "tsc",
30
+ "typecheck": "tsc --noEmit",
31
+ "test": "vitest run --root ../../.. tests/typescript/unit/sdk/client.test.ts",
32
+ "prepublishOnly": "tsc"
33
+ },
34
+ "dependencies": {
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^20.0.0",
38
+ "typescript": "^5.8.0",
39
+ "vitest": "^3.0.0"
40
+ }
41
+ }