@useorgx/openclaw-plugin 0.4.6 → 0.4.8

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.
@@ -0,0 +1,271 @@
1
+ import { randomUUID } from "node:crypto";
2
+ const MAX_PREVIEW_MARKDOWN = 25_000;
3
+ function normalizeText(value) {
4
+ return typeof value === "string" ? value.trim() : "";
5
+ }
6
+ function isUuid(value) {
7
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
8
+ }
9
+ function resolveCreatedById(client, input) {
10
+ const explicit = normalizeText(input.created_by_id);
11
+ if (explicit && isUuid(explicit))
12
+ return explicit;
13
+ const fromClient = typeof client?.getUserId === "function"
14
+ ? normalizeText(client.getUserId())
15
+ : "";
16
+ if (fromClient && isUuid(fromClient))
17
+ return fromClient;
18
+ const fromEnv = normalizeText(process.env.ORGX_CREATED_BY_ID);
19
+ if (fromEnv && isUuid(fromEnv))
20
+ return fromEnv;
21
+ return null;
22
+ }
23
+ export function validateRegisterArtifactInput(input) {
24
+ const errors = [];
25
+ if (!input || typeof input !== "object") {
26
+ return ["input must be an object"];
27
+ }
28
+ const entityType = normalizeText(input.entity_type);
29
+ if (!entityType)
30
+ errors.push("entity_type is required");
31
+ const entityId = normalizeText(input.entity_id);
32
+ if (!entityId)
33
+ errors.push("entity_id is required");
34
+ // In production OrgX uses UUIDs, but tests/mocks sometimes use short ids like "init-1".
35
+ // Keep this as a soft constraint (persistence validation will catch mismatches upstream).
36
+ const name = normalizeText(input.name);
37
+ if (!name)
38
+ errors.push("name is required");
39
+ const artifactType = normalizeText(input.artifact_type);
40
+ if (!artifactType)
41
+ errors.push("artifact_type is required");
42
+ const createdByType = normalizeText(input.created_by_type);
43
+ if (createdByType && createdByType !== "human" && createdByType !== "agent") {
44
+ errors.push("created_by_type must be 'human' or 'agent' when provided");
45
+ }
46
+ const externalUrl = normalizeText(input.external_url);
47
+ const preview = normalizeText(input.preview_markdown);
48
+ if (!externalUrl && !preview) {
49
+ errors.push("at least one of external_url or preview_markdown is required");
50
+ }
51
+ return errors;
52
+ }
53
+ function safeErrorMessage(err) {
54
+ if (err instanceof Error)
55
+ return err.message;
56
+ return String(err);
57
+ }
58
+ function isArtifactTypeConstraintError(err) {
59
+ const msg = safeErrorMessage(err).toLowerCase();
60
+ return (msg.includes("artifact_type") &&
61
+ (msg.includes("constraint") || msg.includes("foreign") || msg.includes("violat")));
62
+ }
63
+ function normalizeBaseUrl(baseUrl) {
64
+ return baseUrl.replace(/\/+$/, "");
65
+ }
66
+ async function sleep(ms) {
67
+ await new Promise((r) => setTimeout(r, ms));
68
+ }
69
+ async function validateArtifactPersistence(client, input) {
70
+ // Use API-key compatible entity CRUD endpoints for validation.
71
+ // The web UI endpoints (/api/artifacts/*, /api/work-artifacts/*) are session-authenticated (401 for API keys).
72
+ const detail = await client.rawRequest("GET", `/api/entities?type=artifact&id=${encodeURIComponent(input.artifactId)}`);
73
+ const rows = detail && typeof detail === "object" ? detail.data : null;
74
+ const artifact = Array.isArray(rows) ? rows.find((r) => r && typeof r === "object" && r.id === input.artifactId) : null;
75
+ const artifactOk = artifact && typeof artifact === "object" && typeof artifact.id === "string" && artifact.id === input.artifactId;
76
+ const linkedOk = artifactOk &&
77
+ typeof artifact.entity_type === "string" &&
78
+ typeof artifact.entity_id === "string" &&
79
+ artifact.entity_type === input.entity_type &&
80
+ artifact.entity_id === input.entity_id;
81
+ return { artifact_detail_ok: Boolean(artifactOk), linked_ok: Boolean(linkedOk) };
82
+ }
83
+ export async function registerArtifact(client, baseUrl, input) {
84
+ const warnings = [];
85
+ const errors = validateRegisterArtifactInput(input);
86
+ if (errors.length > 0) {
87
+ return {
88
+ ok: false,
89
+ artifact_id: null,
90
+ artifact_url: null,
91
+ created: false,
92
+ persistence: {
93
+ checked: false,
94
+ artifact_detail_ok: false,
95
+ linked_ok: false,
96
+ attempts: 0,
97
+ last_error: errors.join("; "),
98
+ },
99
+ warnings: [],
100
+ };
101
+ }
102
+ const requestedId = normalizeText(input.artifact_id);
103
+ const desiredId = requestedId && isUuid(requestedId) ? requestedId : randomUUID();
104
+ const artifactUrl = `${normalizeBaseUrl(baseUrl)}/artifacts/${desiredId}`;
105
+ const status = normalizeText(input.status) || "draft";
106
+ const createdByType = normalizeText(input.created_by_type) || "human";
107
+ const createdById = resolveCreatedById(client, input);
108
+ const createdBy = createdById ? { created_by_type: createdByType, created_by_id: createdById } : { created_by_type: createdByType };
109
+ const metadata = {
110
+ ...(input.metadata && typeof input.metadata === "object" && !Array.isArray(input.metadata)
111
+ ? input.metadata
112
+ : {}),
113
+ };
114
+ if (input.external_url)
115
+ metadata.external_url = String(input.external_url);
116
+ if (input.preview_markdown) {
117
+ const preview = String(input.preview_markdown);
118
+ metadata.preview_markdown =
119
+ preview.length > MAX_PREVIEW_MARKDOWN
120
+ ? preview.slice(0, MAX_PREVIEW_MARKDOWN)
121
+ : preview;
122
+ if (preview.length > MAX_PREVIEW_MARKDOWN)
123
+ metadata.preview_truncated = true;
124
+ }
125
+ const metadataInitiativeId = typeof metadata.initiative_id === "string" && metadata.initiative_id.trim().length > 0
126
+ ? metadata.initiative_id.trim()
127
+ : null;
128
+ const initiativeIdHint = input.entity_type === "initiative" ? input.entity_id : metadataInitiativeId;
129
+ let entity = null;
130
+ let created = false;
131
+ // Attempt idempotent create using a client-provided UUID id (preferred).
132
+ try {
133
+ try {
134
+ entity = await client.createEntity("artifact", {
135
+ id: desiredId,
136
+ name: input.name,
137
+ description: input.description ?? undefined,
138
+ artifact_type: input.artifact_type,
139
+ entity_type: input.entity_type,
140
+ entity_id: input.entity_id,
141
+ ...(initiativeIdHint ? { initiative_id: initiativeIdHint } : {}),
142
+ artifact_url: artifactUrl,
143
+ status,
144
+ metadata,
145
+ ...createdBy,
146
+ });
147
+ created = true;
148
+ }
149
+ catch (err) {
150
+ if (!isArtifactTypeConstraintError(err)) {
151
+ throw err;
152
+ }
153
+ warnings.push(`artifact_type rejected; retrying with shared.project_handbook`);
154
+ metadata.requested_artifact_type = input.artifact_type;
155
+ entity = await client.createEntity("artifact", {
156
+ id: desiredId,
157
+ name: input.name,
158
+ description: input.description ?? undefined,
159
+ artifact_type: "shared.project_handbook",
160
+ entity_type: input.entity_type,
161
+ entity_id: input.entity_id,
162
+ ...(initiativeIdHint ? { initiative_id: initiativeIdHint } : {}),
163
+ artifact_url: artifactUrl,
164
+ status,
165
+ metadata,
166
+ ...createdBy,
167
+ });
168
+ created = true;
169
+ }
170
+ }
171
+ catch (err) {
172
+ warnings.push(`artifact create with explicit id failed: ${safeErrorMessage(err)}`);
173
+ // Fallback: create without id, then patch artifact_url once we know the server id.
174
+ try {
175
+ entity = await client.createEntity("artifact", {
176
+ name: input.name,
177
+ description: input.description ?? undefined,
178
+ artifact_type: input.artifact_type,
179
+ entity_type: input.entity_type,
180
+ entity_id: input.entity_id,
181
+ ...(initiativeIdHint ? { initiative_id: initiativeIdHint } : {}),
182
+ artifact_url: input.external_url ?? `${normalizeBaseUrl(baseUrl)}/artifacts/pending`,
183
+ status,
184
+ metadata,
185
+ ...createdBy,
186
+ });
187
+ created = true;
188
+ }
189
+ catch (inner) {
190
+ if (!isArtifactTypeConstraintError(inner)) {
191
+ throw inner;
192
+ }
193
+ warnings.push(`artifact_type rejected; retrying with shared.project_handbook`);
194
+ metadata.requested_artifact_type = input.artifact_type;
195
+ entity = await client.createEntity("artifact", {
196
+ name: input.name,
197
+ description: input.description ?? undefined,
198
+ artifact_type: "shared.project_handbook",
199
+ entity_type: input.entity_type,
200
+ entity_id: input.entity_id,
201
+ ...(initiativeIdHint ? { initiative_id: initiativeIdHint } : {}),
202
+ artifact_url: input.external_url ?? `${normalizeBaseUrl(baseUrl)}/artifacts/pending`,
203
+ status,
204
+ metadata,
205
+ ...createdBy,
206
+ });
207
+ created = true;
208
+ }
209
+ }
210
+ const artifactId = entity && typeof entity === "object" && typeof entity.id === "string"
211
+ ? String(entity.id)
212
+ : null;
213
+ let finalArtifactUrl = artifactId
214
+ ? `${normalizeBaseUrl(baseUrl)}/artifacts/${artifactId}`
215
+ : null;
216
+ if (artifactId) {
217
+ try {
218
+ await client.updateEntity("artifact", artifactId, {
219
+ artifact_url: finalArtifactUrl,
220
+ });
221
+ }
222
+ catch (err) {
223
+ warnings.push(`artifact_url patch failed: ${safeErrorMessage(err)}`);
224
+ // Keep whatever we sent originally.
225
+ finalArtifactUrl = typeof entity?.artifact_url === "string" ? entity.artifact_url : finalArtifactUrl;
226
+ }
227
+ }
228
+ const shouldValidate = input.validate_persistence === true;
229
+ const persistence = {
230
+ checked: false,
231
+ artifact_detail_ok: false,
232
+ linked_ok: false,
233
+ attempts: 0,
234
+ last_error: null,
235
+ };
236
+ if (shouldValidate && artifactId) {
237
+ persistence.checked = true;
238
+ const maxAttempts = 4;
239
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
240
+ persistence.attempts = attempt;
241
+ try {
242
+ const result = await validateArtifactPersistence(client, {
243
+ artifactId,
244
+ entity_type: input.entity_type,
245
+ entity_id: input.entity_id,
246
+ });
247
+ persistence.artifact_detail_ok = result.artifact_detail_ok;
248
+ persistence.linked_ok = result.linked_ok;
249
+ if (result.artifact_detail_ok && result.linked_ok) {
250
+ break;
251
+ }
252
+ }
253
+ catch (err) {
254
+ persistence.last_error = safeErrorMessage(err);
255
+ }
256
+ // quick backoff for eventual consistency
257
+ await sleep(250 * attempt);
258
+ }
259
+ if (!persistence.artifact_detail_ok || !persistence.linked_ok) {
260
+ warnings.push(`artifact persistence check failed (detail_ok=${persistence.artifact_detail_ok}, linked_ok=${persistence.linked_ok})`);
261
+ }
262
+ }
263
+ return {
264
+ ok: Boolean(artifactId),
265
+ artifact_id: artifactId,
266
+ artifact_url: finalArtifactUrl,
267
+ created,
268
+ persistence,
269
+ warnings,
270
+ };
271
+ }
@@ -14,6 +14,9 @@ function installationFile() {
14
14
  function isUserScopedApiKey(apiKey) {
15
15
  return apiKey.trim().toLowerCase().startsWith('oxk_');
16
16
  }
17
+ function isUuid(value) {
18
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
19
+ }
17
20
  function ensureAuthDir() {
18
21
  const dir = authDir();
19
22
  mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -49,17 +52,6 @@ export function readPersistedAuth() {
49
52
  if (!parsed || typeof parsed.apiKey !== 'string' || parsed.apiKey.trim().length === 0) {
50
53
  return null;
51
54
  }
52
- if (isUserScopedApiKey(parsed.apiKey) &&
53
- typeof parsed.userId === 'string' &&
54
- parsed.userId.trim().length > 0) {
55
- const sanitized = {
56
- ...parsed,
57
- userId: null,
58
- updatedAt: new Date().toISOString(),
59
- };
60
- writeJsonFileAtomicSync(file, sanitized, 0o600);
61
- return sanitized;
62
- }
63
55
  return parsed;
64
56
  }
65
57
  catch {
@@ -70,9 +62,12 @@ export function writePersistedAuth(input) {
70
62
  ensureAuthDir();
71
63
  const now = new Date().toISOString();
72
64
  const existing = readPersistedAuth();
73
- const normalizedUserId = isUserScopedApiKey(input.apiKey)
65
+ const rawUserId = typeof input.userId === 'string' ? input.userId.trim() : '';
66
+ const normalizedUserId = rawUserId.length === 0
74
67
  ? null
75
- : input.userId ?? null;
68
+ : isUserScopedApiKey(input.apiKey)
69
+ ? (isUuid(rawUserId) ? rawUserId : null)
70
+ : rawUserId;
76
71
  const next = {
77
72
  apiKey: input.apiKey,
78
73
  source: input.source,
@@ -26,6 +26,7 @@ export declare class OrgXClient {
26
26
  baseUrl?: string;
27
27
  }): void;
28
28
  getBaseUrl(): string;
29
+ getUserId(): string;
29
30
  /**
30
31
  * Low-level authenticated request helper.
31
32
  *
@@ -80,17 +80,16 @@ export class OrgXClient {
80
80
  constructor(apiKey, baseUrl, userId) {
81
81
  this.apiKey = apiKey;
82
82
  this.baseUrl = normalizeClientBaseUrl(baseUrl, DEFAULT_CLIENT_BASE_URL);
83
- this.userId = isUserScopedApiKey(apiKey) ? "" : userId || "";
83
+ // Keep userId available even for oxk_ keys (it can be used as created_by_id for certain writes),
84
+ // but only send it as a header for non-user-scoped keys.
85
+ this.userId = userId || "";
84
86
  }
85
87
  setCredentials(input) {
86
88
  if (typeof input.apiKey === "string") {
87
89
  this.apiKey = input.apiKey;
88
- if (isUserScopedApiKey(this.apiKey)) {
89
- this.userId = "";
90
- }
91
90
  }
92
91
  if (typeof input.userId === "string") {
93
- this.userId = isUserScopedApiKey(this.apiKey) ? "" : input.userId;
92
+ this.userId = input.userId;
94
93
  }
95
94
  if (typeof input.baseUrl === "string" && input.baseUrl.trim().length > 0) {
96
95
  this.baseUrl = normalizeClientBaseUrl(input.baseUrl, this.baseUrl);
@@ -99,6 +98,9 @@ export class OrgXClient {
99
98
  getBaseUrl() {
100
99
  return this.baseUrl;
101
100
  }
101
+ getUserId() {
102
+ return this.userId;
103
+ }
102
104
  // ===========================================================================
103
105
  // HTTP helpers
104
106
  // ===========================================================================
@@ -568,6 +568,10 @@ export interface LiveActivityItem {
568
568
  description: string | null;
569
569
  agentId: string | null;
570
570
  agentName: string | null;
571
+ requesterAgentId: string | null;
572
+ requesterAgentName: string | null;
573
+ executorAgentId: string | null;
574
+ executorAgentName: string | null;
571
575
  runId: string | null;
572
576
  initiativeId: string | null;
573
577
  timestamp: string;