@agentropy/core 0.0.0-bootstrap.0 → 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/dist/store.js ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Driver-neutral Store port (ADR-0017): named collections of JSON documents with revision CAS, a small set of
3
+ * indexed fields per collection, and an async unit of work. Adapters must make one `transaction` atomic and
4
+ * serialize transactions that touch the same store. No SQL-specific semantics leak through this interface.
5
+ *
6
+ * An adapter may re-run a transaction callback after a serialization conflict (ADR-0028), so callbacks must only
7
+ * read and write through `tx` and have no other effects.
8
+ */
9
+ import { AgentropyError } from './errors.js';
10
+ export const STORE_COLLECTIONS = {
11
+ /** `callerId`, `ownerId` and `createdAt` let listings and quotas read what concerns them (FEAT-039.3). */
12
+ tasks: [
13
+ 'tenantId',
14
+ 'status',
15
+ 'instanceId',
16
+ 'parentTaskId',
17
+ 'callerId',
18
+ 'ownerId',
19
+ 'createdAt',
20
+ /** Null until compaction has removed the standing state of an ended task (TASK-066). */
21
+ 'compactedAt',
22
+ ],
23
+ /** `runAt` and `tenantId` let a worker read what is due, and a tenant's running count, without scanning (FEAT-039.3). */
24
+ executions: ['taskId', 'state', 'runAt', 'tenantId'],
25
+ checkpoints: ['taskId'],
26
+ wakeups: ['taskId', 'status', 'dueAt', 'checkAt'],
27
+ subscriptions: ['taskId', 'source', 'status'],
28
+ mailbox: ['taskId', 'subscriptionId', 'consumed'],
29
+ /** `at` lets compaction read only the dedupe records that fell out of the window (TASK-066). */
30
+ inboundEvents: ['source', 'at'],
31
+ effects: ['taskId'],
32
+ outbox: ['published', 'aggregateId'],
33
+ /** `pending` (1 while an entry is unacknowledged and unpresented at its revision) lets the briefing read only those (FEAT-039.3). */
34
+ inbox: ['tenantId', 'ownerId', 'status', 'pending'],
35
+ /** `dueAt` and `claimExpiresAt` let the expiry sweep read only what lapsed (FEAT-039.3). */
36
+ humanActions: ['taskId', 'status', 'dueAt', 'claimExpiresAt'],
37
+ /** `taskId` lets compaction find a task's record (instance records have none) (FEAT-040.1). */
38
+ idempotency: ['tenantId', 'taskId'],
39
+ /** `forwarded` (0/1) lets the forwarder read only rows still to send instead of the whole log (FEAT-039.1). */
40
+ audit: ['tenantId', 'type', 'forwarded'],
41
+ gates: ['taskId', 'nextCheckAt'],
42
+ instances: ['tenantId', 'ownerId'],
43
+ sessions: ['tenantId'],
44
+ leases: ['kind'],
45
+ usage: ['taskId'],
46
+ /** `taskId` finds one projection without scanning them all (FEAT-039.2). */
47
+ remoteTasks: [
48
+ 'tenantId',
49
+ 'status',
50
+ 'parentTaskId',
51
+ 'taskId',
52
+ /** Lets compaction read only the terminal projections that fell out of the window (TASK-066). */
53
+ 'observedAt',
54
+ ],
55
+ auditPolicies: ['tenantId'],
56
+ auditHolds: ['tenantId', 'status'],
57
+ auditReceipts: ['tenantId'],
58
+ /** Per-tenant audit chain head (`id` = tenant ID): the last link's hash, so appends need no chain scan. */
59
+ auditHeads: ['tenantId'],
60
+ /** Policy decision cache invalidations shared by every worker on the store (FEAT-033.1); pruned after 10 min. */
61
+ policyInvalidations: ['tenantId'],
62
+ /** A2A push notification configs (FEAT-034.3); webhook secrets are stored only sealed. */
63
+ pushConfigs: ['tenantId', 'taskId'],
64
+ /** A2A message history (FEAT-044.2): user messages kept per sending principal when the endpoint enables it. */
65
+ a2aHistory: ['tenantId', 'taskId'],
66
+ /** Agent memory (FEAT-045): entries per tenant and acting principal (`ownerId`), with an optional expiry. */
67
+ memories: ['tenantId', 'ownerId', 'expiresAt'],
68
+ /** Status an operator set on a tool or skill version (FEAT-074), so it survives a restart and reaches every worker. */
69
+ lifecycle: ['kind'],
70
+ };
71
+ /** Extracts the indexed fields of a document value; missing fields index as null. */
72
+ export function indexValues(collection, value) {
73
+ const out = {};
74
+ const v = (value ?? {});
75
+ for (const field of STORE_COLLECTIONS[collection]) {
76
+ const raw = v[field];
77
+ if (raw === undefined || raw === null)
78
+ out[field] = null;
79
+ else if (typeof raw === 'string' || typeof raw === 'number')
80
+ out[field] = raw;
81
+ else if (typeof raw === 'boolean')
82
+ out[field] = raw ? 1 : 0;
83
+ else
84
+ throw new AgentropyError('Internal', `Indexed field ${collection}.${field} must be a scalar`);
85
+ }
86
+ return out;
87
+ }
88
+ export const staleRevision = (collection, id, reason, expected, actual) => new AgentropyError('StaleRevision', `${collection}/${id}: ${reason}`, {
89
+ details: {
90
+ collection,
91
+ reason,
92
+ ...(expected !== undefined ? { expectedRevision: expected } : {}),
93
+ ...(actual !== undefined ? { actualRevision: actual } : {}),
94
+ },
95
+ });
96
+ /** A FIFO async mutex: transactions on one store never interleave. */
97
+ export class AsyncMutex {
98
+ tail = Promise.resolve();
99
+ run(fn) {
100
+ const result = this.tail.then(fn);
101
+ this.tail = result.then(() => undefined, () => undefined);
102
+ return result;
103
+ }
104
+ }
105
+ function compare(a, b) {
106
+ if (a === b)
107
+ return 0;
108
+ if (a === null)
109
+ return -1;
110
+ if (b === null)
111
+ return 1;
112
+ return a < b ? -1 : 1;
113
+ }
114
+ /** Reference adapter (durability "none"): everything is lost when the process exits. */
115
+ export class MemoryStore {
116
+ durability = 'none';
117
+ data = new Map();
118
+ seq = 0;
119
+ closed = false;
120
+ mutex = new AsyncMutex();
121
+ transaction(fn) {
122
+ return this.mutex.run(async () => {
123
+ if (this.closed)
124
+ throw new AgentropyError('ProviderUnavailable', 'Store is closed');
125
+ // Rolling back replays an undo log of what this transaction changed, newest first, instead of copying the
126
+ // whole store before every transaction: the cost follows the documents touched. Stored documents are never
127
+ // modified in place (a write replaces the object), so keeping the previous object is enough.
128
+ const undo = [];
129
+ const seq = this.seq;
130
+ try {
131
+ return await fn(this.tx(undo));
132
+ }
133
+ catch (err) {
134
+ for (let i = undo.length - 1; i >= 0; i--)
135
+ undo[i]();
136
+ this.seq = seq;
137
+ throw err;
138
+ }
139
+ });
140
+ }
141
+ async close() {
142
+ this.closed = true;
143
+ }
144
+ col(c) {
145
+ let m = this.data.get(c);
146
+ if (!m)
147
+ this.data.set(c, (m = new Map()));
148
+ return m;
149
+ }
150
+ tx(undo) {
151
+ return {
152
+ get: async (c, id) => structuredClone(this.col(c).get(id)),
153
+ insert: async (c, id, value) => {
154
+ if (this.col(c).has(id))
155
+ throw staleRevision(c, id, 'exists');
156
+ indexValues(c, value);
157
+ const doc = {
158
+ id,
159
+ revision: 1,
160
+ seq: ++this.seq,
161
+ value: structuredClone(value),
162
+ };
163
+ this.col(c).set(id, doc);
164
+ undo.push(() => void this.col(c).delete(id));
165
+ return structuredClone(doc);
166
+ },
167
+ update: async (c, id, expected, value) => {
168
+ const cur = this.col(c).get(id);
169
+ if (!cur)
170
+ throw staleRevision(c, id, 'missing', expected);
171
+ if (cur.revision !== expected)
172
+ throw staleRevision(c, id, 'revision', expected, cur.revision);
173
+ indexValues(c, value);
174
+ const doc = {
175
+ id,
176
+ revision: cur.revision + 1,
177
+ seq: cur.seq,
178
+ value: structuredClone(value),
179
+ };
180
+ this.col(c).set(id, doc);
181
+ undo.push(() => void this.col(c).set(id, cur));
182
+ return structuredClone(doc);
183
+ },
184
+ remove: async (c, id, expected) => {
185
+ const cur = this.col(c).get(id);
186
+ if (!cur)
187
+ throw staleRevision(c, id, 'missing', expected);
188
+ if (cur.revision !== expected)
189
+ throw staleRevision(c, id, 'revision', expected, cur.revision);
190
+ this.col(c).delete(id);
191
+ undo.push(() => void this.col(c).set(id, cur));
192
+ },
193
+ find: async (c, o = {}) => {
194
+ let docs = [...this.col(c).values()].map((d) => ({
195
+ d,
196
+ idx: indexValues(c, d.value),
197
+ }));
198
+ for (const [field, v] of Object.entries(o.where ?? {}))
199
+ docs = docs.filter((x) => x.idx[field] === v);
200
+ if (o.range) {
201
+ const { field, gte, lte } = o.range;
202
+ docs = docs.filter((x) => x.idx[field] !== null &&
203
+ (gte === undefined || compare(x.idx[field], gte) >= 0) &&
204
+ (lte === undefined || compare(x.idx[field], lte) <= 0));
205
+ }
206
+ if (o.afterSeq !== undefined)
207
+ docs = docs.filter((x) => x.d.seq > o.afterSeq);
208
+ if (o.beforeSeq !== undefined)
209
+ docs = docs.filter((x) => x.d.seq < o.beforeSeq);
210
+ const by = o.orderBy ?? 'seq';
211
+ docs.sort((a, b) => by === 'seq'
212
+ ? a.d.seq - b.d.seq
213
+ : compare(a.idx[by], b.idx[by]) || a.d.seq - b.d.seq);
214
+ if (o.descending)
215
+ docs.reverse();
216
+ return structuredClone(docs.slice(0, o.limit ?? docs.length).map((x) => x.d));
217
+ },
218
+ };
219
+ }
220
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Observability port (docs/contracts/observability-v1.md, D-12/D-13/D-14, M2-10).
3
+ *
4
+ * A vendor-neutral surface the runtime calls for spans and metrics; the OpenTelemetry adapter in
5
+ * `@agentropy/runtime` maps it onto `@opentelemetry/api`. Context crosses boundaries only as a W3C `traceparent`
6
+ * string, which is validated before use and is never an authorization input. Attributes carry identifiers and
7
+ * outcomes only — never inputs, outputs, payloads, prompts or credentials.
8
+ */
9
+ export type AttributeValue = string | number | boolean;
10
+ export type Attributes = Record<string, AttributeValue>;
11
+ export interface TelemetrySpan {
12
+ /** W3C traceparent of this span, for propagation to children; undefined when tracing is off. */
13
+ readonly traceparent: string | undefined;
14
+ setAttributes(attributes: Attributes): void;
15
+ /** Marks the span failed with an Errors v1 code (no message, which may carry data). */
16
+ fail(code: string): void;
17
+ end(): void;
18
+ }
19
+ export interface SpanOptions {
20
+ /** Parent context as a traceparent (already sanitized by the caller). */
21
+ parent?: string;
22
+ /** Causal links, e.g. the inbound event that woke a task. */
23
+ links?: string[];
24
+ kind?: 'internal' | 'server' | 'client' | 'producer' | 'consumer';
25
+ attributes?: Attributes;
26
+ }
27
+ export interface Telemetry {
28
+ startSpan(name: string, options?: SpanOptions): TelemetrySpan;
29
+ /** Monotonic counter. */
30
+ count(name: string, value: number, attributes?: Attributes): void;
31
+ /** Histogram sample (durations in milliseconds). */
32
+ record(name: string, value: number, attributes?: Attributes): void;
33
+ }
34
+ export declare const NOOP_TELEMETRY: Telemetry;
35
+ /** Baseline metric names (D-12). Attribute keys are listed in the observability contract. */
36
+ export declare const METRICS: {
37
+ readonly tasksAccepted: "agentropy.tasks.accepted";
38
+ readonly tasksFinished: "agentropy.tasks.finished";
39
+ readonly executionDuration: "agentropy.execution.duration";
40
+ readonly capabilityCalls: "agentropy.capability.calls";
41
+ readonly dispatchGated: "agentropy.dispatch.gated";
42
+ readonly mailboxDropped: "agentropy.mailbox.dropped";
43
+ readonly outboxLag: "agentropy.outbox.delivery_lag";
44
+ readonly traceRejected: "agentropy.trace.rejected";
45
+ /** Store transactions that hit a serialization conflict or deadlock (FEAT-032.1). */
46
+ readonly storeConflicts: "agentropy.store.conflicts";
47
+ /** Scheduler ticks (wake-up poll plus dispatch) that threw; the loop goes on (FEAT-037.1). */
48
+ readonly schedulerErrors: "agentropy.scheduler.errors";
49
+ /** Outbox deliveries that a consumer failed (the row is retried and blocks later rows until it succeeds). */
50
+ readonly outboxFailures: "agentropy.outbox.failures";
51
+ /** Outbox rows given up on after `poisonAfter` failed deliveries (FEAT-039.4). */
52
+ readonly outboxPoisoned: "agentropy.outbox.poisoned";
53
+ /** Audit rows the sink refused: counted per attempt; the row is retried and blocks later rows (FEAT-075). */
54
+ readonly auditForwardFailures: "agentropy.audit.forward_failures";
55
+ };
56
+ /** Span names (D-13). */
57
+ export declare const SPANS: {
58
+ readonly accept: "agentropy.task.accept";
59
+ readonly execute: "agentropy.task.execute";
60
+ readonly capability: "agentropy.capability.invoke";
61
+ };
62
+ /**
63
+ * D-14: accept only a well-formed version-00 W3C traceparent (lowercase hex, non-zero IDs). Anything else is
64
+ * dropped, so malformed or oversized carriers cannot reach exporters or logs.
65
+ */
66
+ export declare function sanitizeTraceparent(value: unknown): string | undefined;
67
+ export declare function parseTraceparent(value: string): {
68
+ traceId: string;
69
+ spanId: string;
70
+ sampled: boolean;
71
+ } | undefined;
72
+ export declare const formatTraceparent: (traceId: string, spanId: string, sampled: boolean) => string;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Observability port (docs/contracts/observability-v1.md, D-12/D-13/D-14, M2-10).
3
+ *
4
+ * A vendor-neutral surface the runtime calls for spans and metrics; the OpenTelemetry adapter in
5
+ * `@agentropy/runtime` maps it onto `@opentelemetry/api`. Context crosses boundaries only as a W3C `traceparent`
6
+ * string, which is validated before use and is never an authorization input. Attributes carry identifiers and
7
+ * outcomes only — never inputs, outputs, payloads, prompts or credentials.
8
+ */
9
+ const NOOP_SPAN = {
10
+ traceparent: undefined,
11
+ setAttributes() { },
12
+ fail() { },
13
+ end() { },
14
+ };
15
+ export const NOOP_TELEMETRY = {
16
+ startSpan: () => NOOP_SPAN,
17
+ count() { },
18
+ record() { },
19
+ };
20
+ /** Baseline metric names (D-12). Attribute keys are listed in the observability contract. */
21
+ export const METRICS = {
22
+ tasksAccepted: 'agentropy.tasks.accepted',
23
+ tasksFinished: 'agentropy.tasks.finished',
24
+ executionDuration: 'agentropy.execution.duration',
25
+ capabilityCalls: 'agentropy.capability.calls',
26
+ dispatchGated: 'agentropy.dispatch.gated',
27
+ mailboxDropped: 'agentropy.mailbox.dropped',
28
+ outboxLag: 'agentropy.outbox.delivery_lag',
29
+ traceRejected: 'agentropy.trace.rejected',
30
+ /** Store transactions that hit a serialization conflict or deadlock (FEAT-032.1). */
31
+ storeConflicts: 'agentropy.store.conflicts',
32
+ /** Scheduler ticks (wake-up poll plus dispatch) that threw; the loop goes on (FEAT-037.1). */
33
+ schedulerErrors: 'agentropy.scheduler.errors',
34
+ /** Outbox deliveries that a consumer failed (the row is retried and blocks later rows until it succeeds). */
35
+ outboxFailures: 'agentropy.outbox.failures',
36
+ /** Outbox rows given up on after `poisonAfter` failed deliveries (FEAT-039.4). */
37
+ outboxPoisoned: 'agentropy.outbox.poisoned',
38
+ /** Audit rows the sink refused: counted per attempt; the row is retried and blocks later rows (FEAT-075). */
39
+ auditForwardFailures: 'agentropy.audit.forward_failures',
40
+ };
41
+ /** Span names (D-13). */
42
+ export const SPANS = {
43
+ accept: 'agentropy.task.accept',
44
+ execute: 'agentropy.task.execute',
45
+ capability: 'agentropy.capability.invoke',
46
+ };
47
+ const TRACEPARENT = /^00-(?!0{32})([0-9a-f]{32})-(?!0{16})([0-9a-f]{16})-([0-9a-f]{2})$/;
48
+ /**
49
+ * D-14: accept only a well-formed version-00 W3C traceparent (lowercase hex, non-zero IDs). Anything else is
50
+ * dropped, so malformed or oversized carriers cannot reach exporters or logs.
51
+ */
52
+ export function sanitizeTraceparent(value) {
53
+ return typeof value === 'string' &&
54
+ value.length === 55 &&
55
+ TRACEPARENT.test(value)
56
+ ? value
57
+ : undefined;
58
+ }
59
+ export function parseTraceparent(value) {
60
+ const m = TRACEPARENT.exec(value);
61
+ if (!m)
62
+ return undefined;
63
+ return {
64
+ traceId: m[1],
65
+ spanId: m[2],
66
+ sampled: (parseInt(m[3], 16) & 1) === 1,
67
+ };
68
+ }
69
+ export const formatTraceparent = (traceId, spanId, sampled) => `00-${traceId}-${spanId}-${sampled ? '01' : '00'}`;
package/dist/tool.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ /** Tool v1 (docs/contracts/tool-v1.md). */
2
+ import type { JsonSchema, TrustedPrincipal, Version, VersionedRef } from './agent.js';
3
+ import type { OperationEffect } from './capability.js';
4
+ export type ToolId = string;
5
+ export type ToolStatus = 'registered' | 'active' | 'suspended' | 'revoked';
6
+ export interface ToolProvenance {
7
+ publisher: string;
8
+ source: string;
9
+ digest: string;
10
+ verified: boolean;
11
+ }
12
+ export interface ToolDescriptor {
13
+ id: ToolId;
14
+ version: Version;
15
+ description: string;
16
+ inputSchema: JsonSchema;
17
+ outputSchema?: JsonSchema;
18
+ effect: OperationEffect;
19
+ idempotency: 'idempotent' | 'keyed' | 'at-least-once';
20
+ permission: string;
21
+ }
22
+ export interface ToolBinding {
23
+ bindingId: string;
24
+ toolId: ToolId;
25
+ toolVersion: Version;
26
+ providerId: string;
27
+ providerVersion: Version;
28
+ config: Record<string, unknown>;
29
+ credentialRef?: string;
30
+ default?: boolean;
31
+ }
32
+ export interface ToolRecord {
33
+ descriptor: ToolDescriptor;
34
+ provenance: ToolProvenance;
35
+ bindings: ToolBinding[];
36
+ status: ToolStatus;
37
+ revision: number;
38
+ }
39
+ export interface ToolPin {
40
+ toolId: ToolId;
41
+ toolVersion: Version;
42
+ bindingId: string;
43
+ providerId: string;
44
+ providerVersion: Version;
45
+ digest: string;
46
+ }
47
+ export interface ToolProviderFeatures {
48
+ protocol: string;
49
+ protocolVersion: string;
50
+ cancellation: boolean;
51
+ idempotencyKeys: boolean;
52
+ streaming: boolean;
53
+ }
54
+ export interface ToolInvocationContext {
55
+ tenantId: string;
56
+ taskId: string;
57
+ executionId: string;
58
+ principal: TrustedPrincipal;
59
+ idempotencyKey?: string;
60
+ credential?: unknown;
61
+ deadline?: string;
62
+ signal: AbortSignal;
63
+ }
64
+ export interface ToolProvider {
65
+ readonly id: string;
66
+ readonly version: Version;
67
+ readonly features: ToolProviderFeatures;
68
+ invoke(binding: ToolBinding, descriptor: ToolDescriptor, input: unknown, ctx: ToolInvocationContext): Promise<unknown>;
69
+ }
70
+ export interface ToolRegistry {
71
+ register(descriptor: ToolDescriptor, bindings: ToolBinding[], provenance: Omit<ToolProvenance, 'digest' | 'verified'>, admin: TrustedPrincipal): Promise<ToolRecord>;
72
+ activate(ref: VersionedRef, admin: TrustedPrincipal): Promise<ToolRecord>;
73
+ suspend(ref: VersionedRef, admin: TrustedPrincipal): Promise<ToolRecord>;
74
+ revoke(ref: VersionedRef, admin: TrustedPrincipal): Promise<ToolRecord>;
75
+ get(ref: VersionedRef): ToolRecord | undefined;
76
+ /**
77
+ * The record with the status as the shared store has it (FEAT-074): what an invocation must act on, since a revoke or
78
+ * a suspend can come from another worker. A registry without a store answers as `get` does.
79
+ */
80
+ refreshed?(ref: VersionedRef): Promise<ToolRecord | undefined>;
81
+ discover(query: {
82
+ text?: string;
83
+ }, caller: TrustedPrincipal): Promise<ToolDescriptor[]>;
84
+ }
85
+ export interface ToolExecutor {
86
+ invoke(pin: ToolPin, input: unknown, ctx: ToolInvocationContext & {
87
+ stepKey?: string;
88
+ }): Promise<unknown>;
89
+ }
package/dist/tool.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@agentropy/core",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "Placeholder that reserves the package name; install @agentropy/* at version 0.1.0 or later.",
3
+ "version": "0.1.0",
4
+ "description": "Agentropy contracts: types, JSON Schemas, the error catalog, lifecycle tables and pure resolvers (no I/O).",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -9,7 +9,40 @@
9
9
  "directory": "packages/core"
10
10
  },
11
11
  "homepage": "https://github.com/bassemZohdy/agentropy/tree/main/packages/core#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/bassemZohdy/agentropy/issues"
14
+ },
15
+ "keywords": [
16
+ "agents",
17
+ "multi-agent",
18
+ "contracts",
19
+ "typescript",
20
+ "agentropy"
21
+ ],
22
+ "engines": {
23
+ "node": ">=24"
24
+ },
25
+ "type": "module",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
12
32
  "files": [
13
- "README.md"
14
- ]
15
- }
33
+ "dist",
34
+ "LICENSE"
35
+ ],
36
+ "dependencies": {
37
+ "ajv": "^8.20.0",
38
+ "ajv-formats": "^3.0.1",
39
+ "semver": "^7.8.6"
40
+ },
41
+ "devDependencies": {
42
+ "@types/semver": "^7.8.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsc -b",
46
+ "typecheck": "tsc --noEmit"
47
+ }
48
+ }