Repository navigation
Expand file tree
/
Copy pathProteinCommandChannel.ts
More file actions
187 lines (170 loc) · 5.94 KB
/
Copy pathProteinCommandChannel.ts
File metadata and controls
187 lines (170 loc) · 5.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/**
* Protein command bus — `/commands/*` API via shared HTTPClient (auth, X-Project-ID, retries).
* Complements Rules Engine `AgentCommand` (`/command`) and high-level `AgentProtein` (`/protein/execute`).
*/
import { HTTPClient } from '../client/http-client';
import {
buildProteinDeltaExecuteBody,
type ProteinCommitMode,
type ProteinDraftDomain,
} from '../protocol/proteinDraft';
/** Request body for POST /commands/execute */
export interface ProteinCommandExecuteRequest {
command_type: string;
command_name: string;
payload: Record<string, unknown>;
priority?: number;
timeout_ms?: number;
retry_count?: number;
}
export interface ProteinBatchCommandRequest {
commands: ProteinCommandExecuteRequest[];
execute_parallel?: boolean;
fail_fast?: boolean;
}
/** R32/R35 — HTTP 200 with ``success: false`` or dirty unflushed must not ACK. */
export function assertProteinCommandResponseOk(data: unknown): void {
if (data == null || typeof data !== 'object') return;
const d = data as Record<string, unknown>;
if (d.success === false) {
throw new Error(String(d.error ?? 'protein_command_failed'));
}
const payload =
d.result != null && typeof d.result === 'object'
? (d.result as Record<string, unknown>)
: d;
const mode = String(payload.commit_mode ?? '');
if (payload.flushed === false && (mode === 'dirty' || payload.dirty === true)) {
throw new Error('protein_delta_not_flushed');
}
}
export class ProteinCommandChannel {
private readonly sessionId: string;
constructor(private readonly http: HTTPClient) {
this.sessionId = `sdk_session_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
}
private supplementalHeaders(): Record<string, string> {
const h: Record<string, string> = {
'X-Session-ID': this.sessionId,
'X-Request-ID': `req_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
};
const tok = this.http.getAuthToken();
if (tok) {
h['X-User-Token'] = tok;
}
return h;
}
async executeCommand<T = unknown>(request: ProteinCommandExecuteRequest): Promise<T> {
const res = await this.http.post<T>('/commands/execute', request, {
headers: this.supplementalHeaders(),
});
assertProteinCommandResponseOk(res.data);
return res.data;
}
/**
* DNA DELTA via protein bus — supports ``commit_mode`` immediate|dirty|working_set.
* Genetic: shared.organelles.protein_commit.gen1
*/
async deltaUpdate<T = unknown>(args: {
targetEntity: string;
updates: Record<string, unknown>;
domain?: ProteinDraftDomain | string;
commitMode?: ProteinCommitMode;
opId?: string;
entityUuid?: string;
entityId?: string | number;
projectId?: number;
userId?: number;
}): Promise<T> {
const body = buildProteinDeltaExecuteBody({
targetEntity: args.targetEntity,
updates: args.updates,
domain: (args.domain || 'config') as ProteinDraftDomain,
commitMode: args.commitMode,
opId: args.opId,
entityUuid: args.entityUuid,
entityId: args.entityId,
projectId: args.projectId,
userId: args.userId,
});
return this.executeCommand<T>(body as ProteinCommandExecuteRequest);
}
/**
* DNA GET with optional ``If-Epoch-Match`` (N8-04 RYW after DELTA flush).
* ``entityKey`` should be ``uuid:<uuid>`` when fencing dual protein entries.
*/
async getEntity<T = unknown>(args: {
entityType?: string;
entityUuid: string;
projectId?: number;
ifEpochMatch?: number;
}): Promise<T> {
const headers = this.supplementalHeaders();
const epoch = args.ifEpochMatch;
if (epoch != null && Number.isFinite(epoch) && epoch > 0) {
headers['If-Epoch-Match'] = String(Math.floor(epoch));
}
const et = encodeURIComponent(args.entityType || 'entity');
const id = encodeURIComponent(args.entityUuid);
const qs =
args.projectId != null && Number(args.projectId) > 0
? `?project_id=${encodeURIComponent(String(args.projectId))}`
: '';
const res = await this.http.get<T>(`/commands/dna/${et}/get/${id}${qs}`, {
headers,
});
return res.data;
}
async executeDNAOperation<T = unknown>(
entityType: string,
operation: string,
data: Record<string, unknown>
): Promise<T> {
const res = await this.http.post<T>(`/commands/dna/${entityType}/${operation}`, data, {
headers: this.supplementalHeaders(),
});
assertProteinCommandResponseOk(res.data);
return res.data;
}
async executeBatchCommands<T = unknown>(request: ProteinBatchCommandRequest): Promise<T> {
const res = await this.http.post<T>('/commands/batch', request, {
headers: this.supplementalHeaders(),
});
assertProteinCommandResponseOk(res.data);
return res.data;
}
async getEntities<T = unknown>(
entityType: string,
filters?: Record<string, unknown>
): Promise<T> {
const res = await this.http.get<T>(`/commands/entities/${entityType}`, filters, {
headers: this.supplementalHeaders(),
});
return res.data;
}
async createEntity<T = unknown>(entityType: string, data: Record<string, unknown>): Promise<T> {
const res = await this.http.post<T>(`/commands/entities/${entityType}`, data, {
headers: this.supplementalHeaders(),
});
assertProteinCommandResponseOk(res.data);
return res.data;
}
async getCommandStatus<T = unknown>(commandUuid: string): Promise<T> {
const res = await this.http.get<T>(`/commands/status/${commandUuid}`, undefined, {
headers: this.supplementalHeaders(),
});
return res.data;
}
async getCommandHistory<T = unknown>(limit = 100, offset = 0): Promise<T> {
const res = await this.http.get<T>('/commands/history', { limit, offset }, {
headers: this.supplementalHeaders(),
});
return res.data;
}
async healthCheck<T = unknown>(): Promise<T> {
const res = await this.http.get<T>('/commands/health', undefined, {
headers: this.supplementalHeaders(),
});
return res.data;
}
}