@hivemagnus/ardent-studio 0.0.0-stage → 0.1.1
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 +202 -0
- package/NOTICE +12 -0
- package/README.md +133 -2
- package/dist/agents/config-edit.d.ts +20 -0
- package/dist/agents/config-edit.js +75 -0
- package/dist/agents/directory.d.ts +27 -0
- package/dist/agents/directory.js +97 -0
- package/dist/agents/operations.d.ts +47 -0
- package/dist/agents/operations.js +93 -0
- package/dist/auth/links.d.ts +27 -0
- package/dist/auth/links.js +46 -0
- package/dist/auth/oathweave.d.ts +46 -0
- package/dist/auth/oathweave.js +123 -0
- package/dist/blobs/store.d.ts +45 -0
- package/dist/blobs/store.js +159 -0
- package/dist/clients/chattermost.d.ts +16 -0
- package/dist/clients/chattermost.js +36 -0
- package/dist/clients/hivemem.d.ts +85 -0
- package/dist/clients/hivemem.js +89 -0
- package/dist/clients/magnus.d.ts +417 -0
- package/dist/clients/magnus.js +343 -0
- package/dist/clients/service-token.d.ts +24 -0
- package/dist/clients/service-token.js +87 -0
- package/dist/clients/sse.d.ts +8 -0
- package/dist/clients/sse.js +42 -0
- package/dist/conductor/activity.d.ts +38 -0
- package/dist/conductor/activity.js +101 -0
- package/dist/conductor/addressing.d.ts +24 -0
- package/dist/conductor/addressing.js +42 -0
- package/dist/conductor/conductor.d.ts +225 -0
- package/dist/conductor/conductor.js +939 -0
- package/dist/conductor/follower.d.ts +48 -0
- package/dist/conductor/follower.js +154 -0
- package/dist/conductor/live.d.ts +23 -0
- package/dist/conductor/live.js +32 -0
- package/dist/conductor/prompting.d.ts +74 -0
- package/dist/conductor/prompting.js +177 -0
- package/dist/config.d.ts +52 -0
- package/dist/config.js +163 -0
- package/dist/db/database.d.ts +12 -0
- package/dist/db/database.js +62 -0
- package/dist/db/json.d.ts +8 -0
- package/dist/db/json.js +13 -0
- package/dist/db/migrations.d.ts +6 -0
- package/dist/db/migrations.js +571 -0
- package/dist/db/repos/agents.d.ts +86 -0
- package/dist/db/repos/agents.js +92 -0
- package/dist/db/repos/audit.d.ts +37 -0
- package/dist/db/repos/audit.js +20 -0
- package/dist/db/repos/events.d.ts +29 -0
- package/dist/db/repos/events.js +55 -0
- package/dist/db/repos/files.d.ts +41 -0
- package/dist/db/repos/files.js +72 -0
- package/dist/db/repos/idempotency.d.ts +27 -0
- package/dist/db/repos/idempotency.js +46 -0
- package/dist/db/repos/links.d.ts +47 -0
- package/dist/db/repos/links.js +99 -0
- package/dist/db/repos/projects.d.ts +44 -0
- package/dist/db/repos/projects.js +107 -0
- package/dist/db/repos/proposals.d.ts +46 -0
- package/dist/db/repos/proposals.js +65 -0
- package/dist/db/repos/review.d.ts +191 -0
- package/dist/db/repos/review.js +195 -0
- package/dist/db/repos/room.d.ts +163 -0
- package/dist/db/repos/room.js +151 -0
- package/dist/db/repos/sessions.d.ts +36 -0
- package/dist/db/repos/sessions.js +30 -0
- package/dist/db/repos/summaries.d.ts +22 -0
- package/dist/db/repos/summaries.js +105 -0
- package/dist/db/repos/tasks.d.ts +103 -0
- package/dist/db/repos/tasks.js +112 -0
- package/dist/db/repos/team.d.ts +49 -0
- package/dist/db/repos/team.js +95 -0
- package/dist/db/repos/templates.d.ts +55 -0
- package/dist/db/repos/templates.js +120 -0
- package/dist/db/store.d.ts +57 -0
- package/dist/db/store.js +108 -0
- package/dist/events/bus.d.ts +21 -0
- package/dist/events/bus.js +31 -0
- package/dist/events/types.d.ts +3 -0
- package/dist/events/types.js +1 -0
- package/dist/ids.d.ts +28 -0
- package/dist/ids.js +81 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +17 -0
- package/dist/knowledge/extract.d.ts +17 -0
- package/dist/knowledge/extract.js +82 -0
- package/dist/knowledge/sync.d.ts +40 -0
- package/dist/knowledge/sync.js +172 -0
- package/dist/logger.d.ts +5 -0
- package/dist/logger.js +11 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +42 -0
- package/dist/review/anchors.d.ts +16 -0
- package/dist/review/anchors.js +67 -0
- package/dist/review/context.d.ts +4 -0
- package/dist/review/context.js +29 -0
- package/dist/review/docx.d.ts +29 -0
- package/dist/review/docx.js +21 -0
- package/dist/review/export.d.ts +16 -0
- package/dist/review/export.js +84 -0
- package/dist/review/importer.d.ts +68 -0
- package/dist/review/importer.js +215 -0
- package/dist/review/index.d.ts +13 -0
- package/dist/review/index.js +7 -0
- package/dist/server/app.d.ts +5 -0
- package/dist/server/app.js +44 -0
- package/dist/server/deps.d.ts +43 -0
- package/dist/server/deps.js +17 -0
- package/dist/server/env.d.ts +6 -0
- package/dist/server/env.js +1 -0
- package/dist/server/errors.d.ts +12 -0
- package/dist/server/errors.js +25 -0
- package/dist/server/routes/agent-studio.d.ts +5 -0
- package/dist/server/routes/agent-studio.js +441 -0
- package/dist/server/routes/agents.d.ts +3 -0
- package/dist/server/routes/agents.js +4 -0
- package/dist/server/routes/files.d.ts +3 -0
- package/dist/server/routes/files.js +88 -0
- package/dist/server/routes/health.d.ts +3 -0
- package/dist/server/routes/health.js +31 -0
- package/dist/server/routes/links.d.ts +3 -0
- package/dist/server/routes/links.js +79 -0
- package/dist/server/routes/projects.d.ts +3 -0
- package/dist/server/routes/projects.js +119 -0
- package/dist/server/routes/review.d.ts +3 -0
- package/dist/server/routes/review.js +198 -0
- package/dist/server/routes/room.d.ts +9 -0
- package/dist/server/routes/room.js +224 -0
- package/dist/server/routes/stream.d.ts +4 -0
- package/dist/server/routes/stream.js +104 -0
- package/dist/server/routes/team.d.ts +3 -0
- package/dist/server/routes/team.js +183 -0
- package/dist/server/routes/templates.d.ts +11 -0
- package/dist/server/routes/templates.js +103 -0
- package/dist/server/routes/work.d.ts +3 -0
- package/dist/server/routes/work.js +139 -0
- package/dist/server/routing.d.ts +31 -0
- package/dist/server/routing.js +132 -0
- package/dist/service.d.ts +34 -0
- package/dist/service.js +93 -0
- package/dist/shared/browser.d.ts +5824 -0
- package/dist/shared/browser.js +1318 -0
- package/dist/team/proposals.d.ts +129 -0
- package/dist/team/proposals.js +349 -0
- package/dist/team/service.d.ts +12 -0
- package/dist/team/service.js +13 -0
- package/dist/team/validation.d.ts +37 -0
- package/dist/team/validation.js +157 -0
- package/dist/templates/secrets.d.ts +2 -0
- package/dist/templates/secrets.js +23 -0
- package/dist/templates/seeds.d.ts +34 -0
- package/dist/templates/seeds.js +277 -0
- package/dist/url.d.ts +2 -0
- package/dist/url.js +7 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +11 -0
- package/docs/openapi-browser.json +12658 -0
- package/package.json +95 -4
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// Magnus is the only way ArdentStudio reaches an agent. It calls the Magnus control API
|
|
2
|
+
// with its own Oathweave service identity (audience `magnus`) and, for work a person asked
|
|
3
|
+
// for, forwards that person's Oathweave subject in x-acting-subject so Magnus can check
|
|
4
|
+
// and audit both. ArdentStudio never talks to nodes or Ardent directly and holds no Ardent token.
|
|
5
|
+
//
|
|
6
|
+
// The routes, action bodies and answers come from @hivemagnus/magnus-contracts/ardent-service
|
|
7
|
+
// (`ardentServiceRoutes`, the routes a linked service identity may call), pinned to the Magnus
|
|
8
|
+
// release Studio is built against. Only shapes that contract leaves open are typed here: the
|
|
9
|
+
// installation (which it answers as a record) and the Ardent management resources it relays as-is.
|
|
10
|
+
// The agent changes (identity-save, skill-set, config-save, skill-install and reading config) need an
|
|
11
|
+
// acting Magnus ADMIN in x-acting-subject (ARDENT_SERVICE_ADMIN_ACTIONS).
|
|
12
|
+
// A node agent reports `capabilities.studio` (ARDENT_STUDIO_CAPABILITY): 1 for sessions, streams and
|
|
13
|
+
// artifacts, 2 for missions, pause and resume, previews and development, 3 for skill-install; below
|
|
14
|
+
// that Magnus answers 409 AGENT_UPGRADE_REQUIRED.
|
|
15
|
+
import { ARDENT_ACTING_SUBJECT_HEADER, ardentAgentDeployRequestSchema, ardentAgentOperationSchema, ardentConfigEditSchema, ardentConfigFileSchema, ardentConfigSavedSchema, ardentDevelopmentNoteSchema, ardentDevelopmentPageSchema, ardentDevelopmentRecordSchema, ardentIdentityEditSchema, ardentIdentityFileSchema, ardentMissionSubmitSchema, ardentPreviewSubmitSchema, ardentServiceProfileSchema, ardentServiceSessionSchema, ardentServiceSkillSetRequestSchema, ardentServiceTaskSubmitRequestSchema, ardentSessionOpenSchema, ardentSkillEditSchema, ardentSkillInstallResultSchema, ardentSkillInstallSchema, ardentTaskAdmissionSchema, ardentTaskArtifactsSchema, ardentArtifactRecordSchema, ardentTaskJournalEventSchema, ardentTaskPauseStateSchema, } from '@hivemagnus/magnus-contracts/ardent-service';
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
import { parseSse } from './sse.js';
|
|
18
|
+
import { trimTrailingSlashes } from '../url.js';
|
|
19
|
+
export { ARDENT_SERVICE_ADMIN_ACTIONS, ARDENT_SERVICE_CONFIG_PATHS, ARDENT_STUDIO_CAPABILITY, ARDENT_STUDIO_EVENT_KINDS, ardentAgentOperationSchema, ardentTaskDoneEventSchema, ardentTaskJournalEventSchema, ardentTaskTextEventSchema, ardentTeamMissionSchema, } from '@hivemagnus/magnus-contracts/ardent-service';
|
|
20
|
+
export { ARDENT_CONTEXT_ITEMS_MAX_BYTES } from '@hivemagnus/magnus-contracts/browser';
|
|
21
|
+
export const ACTING_SUBJECT_HEADER = ARDENT_ACTING_SUBJECT_HEADER;
|
|
22
|
+
export class MagnusError extends Error {
|
|
23
|
+
status;
|
|
24
|
+
code;
|
|
25
|
+
name = 'MagnusError';
|
|
26
|
+
constructor(message, status, code) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.status = status;
|
|
29
|
+
this.code = code;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const REF_PART = /^[A-Za-z0-9._-]{1,128}$/;
|
|
33
|
+
export function parseAgentRef(ref) {
|
|
34
|
+
const [nodeId, profile, extra] = ref.split('~');
|
|
35
|
+
if (extra !== undefined || !nodeId || !profile || !REF_PART.test(nodeId) || !REF_PART.test(profile))
|
|
36
|
+
throw new MagnusError('Invalid agent reference', 400, 'INVALID_AGENT_REF');
|
|
37
|
+
return { nodeId, profile };
|
|
38
|
+
}
|
|
39
|
+
export function agentRef(nodeId, profile) {
|
|
40
|
+
return `${nodeId}~${profile}`;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* GET /ardent/installations and /ardent/installations/{nodeId}. The service contract answers these
|
|
44
|
+
* as records, so Studio reads only the fields it uses (Magnus ArdentFleetInstallationSchema).
|
|
45
|
+
*/
|
|
46
|
+
export const magnusArdentInstallationSchema = z.object({
|
|
47
|
+
installed: z.boolean(),
|
|
48
|
+
version: z.string().nullable(),
|
|
49
|
+
owner: z.string(),
|
|
50
|
+
profiles: z.array(ardentServiceProfileSchema.pick({ id: true, name: true, backend: true, apiPort: true, running: true, a2aEnabled: true, channels: true, error: true })),
|
|
51
|
+
checkedAt: z.string(),
|
|
52
|
+
nodeId: z.string(),
|
|
53
|
+
nodeName: z.string(),
|
|
54
|
+
hostname: z.string(),
|
|
55
|
+
reachable: z.boolean(),
|
|
56
|
+
error: z.string().nullable(),
|
|
57
|
+
/** The node agent's Studio level (ARDENT_STUDIO_CAPABILITY). Absent on agents that predate it. */
|
|
58
|
+
capabilities: z.object({ studio: z.number().int().min(0).optional() }).loose().optional(),
|
|
59
|
+
});
|
|
60
|
+
// Ardent management shapes, as Ardent's OpenAPI document defines them. Magnus relays these resources unchanged.
|
|
61
|
+
export const ardentTaskStateSchema = z.enum(['queued', 'running', 'input_required', 'completed', 'partial', 'failed', 'cancelled', 'unknown']);
|
|
62
|
+
export const ardentTaskSchema = z.object({
|
|
63
|
+
id: z.string(), caller: z.string(), context: z.string(), session_id: z.string().nullable(), prompt: z.string(), content_hash: z.string(),
|
|
64
|
+
idempotency_key: z.string().nullable(), backend: z.string(), state: ardentTaskStateSchema, result: z.string().nullable(), error: z.string().nullable(),
|
|
65
|
+
deadline_ms: z.number(), created_ms: z.number(), updated_ms: z.number(),
|
|
66
|
+
});
|
|
67
|
+
export const ardentStatusSchema = z.object({ version: z.string(), profile: z.string(), backend: z.string(), tasks: z.number().int() });
|
|
68
|
+
export const ardentMemoryStatusSchema = z.object({
|
|
69
|
+
status: z.enum(['ready', 'degraded']), agent_id: z.string(), workspace_id: z.string(),
|
|
70
|
+
retrieval: z.string().nullable(), storage: z.string().nullable(), reason: z.string().nullable(),
|
|
71
|
+
});
|
|
72
|
+
export const ardentSkillSchema = z.object({ name: z.string(), enabled: z.boolean() }).loose();
|
|
73
|
+
/** Actions released Magnus accepts on POST …/action (an ADMIN person; a service identity gets the Studio subset below). */
|
|
74
|
+
export const RELEASED_ACTIONS = ['profile-create', 'config-validate', 'config-save', 'peer-validate', 'peer-save', 'identity-save', 'identity-restore',
|
|
75
|
+
'provider-test', 'channel-test', 'peer-test', 'memory-search', 'task-submit', 'task-cancel', 'skill-set', 'service-start', 'service-stop',
|
|
76
|
+
'service-restart', 'package-install', 'context-stage', 'context-adopt', 'context-rollback'];
|
|
77
|
+
/**
|
|
78
|
+
* Actions added for Ardent Project Studio. session-open needs studio >= 1, skill-install studio >= 3 and a
|
|
79
|
+
* Magnus with a HiveSkills registry, the others studio >= 2 and Ardent 2.2.0.
|
|
80
|
+
*/
|
|
81
|
+
export const STUDIO_ACTIONS = ['session-open', 'mission-submit', 'task-pause', 'task-resume', 'preview-submit', 'development-note', 'skill-install'];
|
|
82
|
+
/**
|
|
83
|
+
* Whether Magnus lets the Studio service identity run service-restart. It does not: a service may run
|
|
84
|
+
* only the session, task, mission, preview, development and ARDENT_SERVICE_ADMIN_ACTIONS actions, so a
|
|
85
|
+
* profile restart stays a person's act in the Magnus console.
|
|
86
|
+
*/
|
|
87
|
+
export const ARDENT_SERVICE_CAN_RESTART = false;
|
|
88
|
+
/** action task-submit: the prompt is at most 16000 characters and the idempotency key a UUID. */
|
|
89
|
+
const ardentTaskSubmitSchema = ardentServiceTaskSubmitRequestSchema.shape.body;
|
|
90
|
+
/** action skill-set: the skill name is the target. */
|
|
91
|
+
const ardentSkillTargetSchema = ardentServiceSkillSetRequestSchema.shape.target;
|
|
92
|
+
/** The New Agent and resume answers. */
|
|
93
|
+
const operationAcceptedSchema = z.object({ operationId: z.string() });
|
|
94
|
+
const envelope = z.object({ success: z.literal(true), data: z.unknown() });
|
|
95
|
+
const failure = z.object({ success: z.literal(false), error: z.object({ code: z.string(), message: z.string() }) });
|
|
96
|
+
export class MagnusClient {
|
|
97
|
+
options;
|
|
98
|
+
request;
|
|
99
|
+
baseUrl;
|
|
100
|
+
constructor(options) {
|
|
101
|
+
this.options = options;
|
|
102
|
+
this.request = options.fetch ?? ((input, init) => fetch(input, init));
|
|
103
|
+
this.baseUrl = trimTrailingSlashes(options.baseUrl);
|
|
104
|
+
}
|
|
105
|
+
// ── Released routes ──
|
|
106
|
+
/** Every Magnus-managed Ardent profile across the fleet. */
|
|
107
|
+
async listProfiles(context = {}) {
|
|
108
|
+
return z.array(ardentServiceProfileSchema).parse(await this.json('GET', '/api/v1/ardent/profiles', context));
|
|
109
|
+
}
|
|
110
|
+
async listInstallations(context = {}) {
|
|
111
|
+
return z.array(magnusArdentInstallationSchema).parse(await this.json('GET', '/api/v1/ardent/installations', context));
|
|
112
|
+
}
|
|
113
|
+
async getInstallation(nodeId, context = {}) {
|
|
114
|
+
if (!REF_PART.test(nodeId))
|
|
115
|
+
throw new MagnusError('Invalid node ID', 400, 'INVALID_AGENT_REF');
|
|
116
|
+
return magnusArdentInstallationSchema.parse(await this.json('GET', `/api/v1/ardent/installations/${nodeId}`, context));
|
|
117
|
+
}
|
|
118
|
+
/** Read an allow-listed Ardent management resource through Magnus. */
|
|
119
|
+
async resource(ref, resource, context = {}) {
|
|
120
|
+
const { nodeId, profile } = parseAgentRef(ref);
|
|
121
|
+
const query = new URLSearchParams();
|
|
122
|
+
for (const [key, value] of Object.entries(context.query ?? {}))
|
|
123
|
+
if (value !== undefined)
|
|
124
|
+
query.set(key, String(value));
|
|
125
|
+
const suffix = query.size ? `?${query}` : '';
|
|
126
|
+
return this.json('GET', `/api/v1/ardent/installations/${nodeId}/profiles/${profile}/${resource}${suffix}`, context);
|
|
127
|
+
}
|
|
128
|
+
async status(ref, context = {}) { return ardentStatusSchema.parse(await this.resource(ref, 'status', context)); }
|
|
129
|
+
async memoryStatus(ref, context = {}) { return ardentMemoryStatusSchema.parse(await this.resource(ref, 'memory/status', context)); }
|
|
130
|
+
async task(ref, taskId, context = {}) { return ardentTaskSchema.parse(await this.resource(ref, `tasks/${uuid(taskId)}`, context)); }
|
|
131
|
+
async skills(ref, context = {}) {
|
|
132
|
+
const data = await this.resource(ref, 'skills', context);
|
|
133
|
+
const list = z.union([z.array(ardentSkillSchema), z.object({ skills: z.array(ardentSkillSchema) }).loose()]).parse(data);
|
|
134
|
+
return Array.isArray(list) ? list : list.skills;
|
|
135
|
+
}
|
|
136
|
+
async taskEvents(ref, taskId, after = 0, context = {}) {
|
|
137
|
+
return z.object({ events: z.array(ardentTaskJournalEventSchema) }).parse(await this.resource(ref, `tasks/${uuid(taskId)}/events`, { ...context, query: { after } })).events;
|
|
138
|
+
}
|
|
139
|
+
async identity(ref, kind, context = {}) {
|
|
140
|
+
return ardentIdentityFileSchema.parse(await this.resource(ref, `identity/${kind}`, context));
|
|
141
|
+
}
|
|
142
|
+
/** The profile's config.yaml and its revision. Needs an acting Magnus ADMIN. */
|
|
143
|
+
async config(ref, context = {}) {
|
|
144
|
+
return ardentConfigFileSchema.parse(await this.resource(ref, 'config', context));
|
|
145
|
+
}
|
|
146
|
+
/** Artifact bytes, buffered (Magnus caps them; see MAGNUS_AGENT_ARDENT_ARTIFACT_MAX_BYTES). Prefer artifactStream for large files. */
|
|
147
|
+
async artifact(ref, sha256, context = {}) {
|
|
148
|
+
const response = await this.artifactStream(ref, sha256, context);
|
|
149
|
+
return new Uint8Array(await new Response(response.body).arrayBuffer());
|
|
150
|
+
}
|
|
151
|
+
/** Artifact bytes as Magnus streams them, never buffered here. The caller verifies the digest. */
|
|
152
|
+
async artifactStream(ref, sha256, context = {}) {
|
|
153
|
+
const { nodeId, profile } = parseAgentRef(ref);
|
|
154
|
+
if (!/^[a-f0-9]{64}$/.test(sha256))
|
|
155
|
+
throw new MagnusError('Invalid artifact ID', 400, 'VALIDATION_ERROR');
|
|
156
|
+
const response = await this.send('GET', `/api/v1/ardent/installations/${nodeId}/profiles/${profile}/artifacts/${sha256}`, context, undefined, { accept: 'application/octet-stream' }, 0);
|
|
157
|
+
if (!response.ok || !response.body)
|
|
158
|
+
await this.fail(response);
|
|
159
|
+
const length = Number(response.headers.get('content-length') ?? '');
|
|
160
|
+
return { body: response.body, size: Number.isSafeInteger(length) && length >= 0 && response.headers.has('content-length') ? length : undefined };
|
|
161
|
+
}
|
|
162
|
+
/** Run a management action through Magnus's audited action route. */
|
|
163
|
+
async action(ref, action, input = {}, context = {}) {
|
|
164
|
+
const { nodeId, profile } = parseAgentRef(ref);
|
|
165
|
+
const payload = { action };
|
|
166
|
+
if (input.target !== undefined)
|
|
167
|
+
payload.target = input.target;
|
|
168
|
+
if (input.body !== undefined)
|
|
169
|
+
payload.body = input.body;
|
|
170
|
+
return this.json('POST', `/api/v1/ardent/installations/${nodeId}/profiles/${profile}/action`, context, payload);
|
|
171
|
+
}
|
|
172
|
+
/** A direct task. The prompt is at most 16000 characters; the idempotency key is a UUID; a session (studio >= 1) carries the conversation. */
|
|
173
|
+
async submitTask(ref, body, context = {}) {
|
|
174
|
+
const parsed = ardentTaskSubmitSchema.safeParse(body);
|
|
175
|
+
if (!parsed.success)
|
|
176
|
+
throw new MagnusError(`Task submission is invalid: ${parsed.error.issues[0]?.message ?? 'invalid'}`, 400, 'VALIDATION_ERROR');
|
|
177
|
+
return ardentTaskAdmissionSchema.parse(await this.action(ref, 'task-submit', { body: parsed.data }, context));
|
|
178
|
+
}
|
|
179
|
+
async cancelTask(ref, taskId, context = {}) {
|
|
180
|
+
return this.action(ref, 'task-cancel', { target: uuid(taskId) }, context);
|
|
181
|
+
}
|
|
182
|
+
/** Ardent rejects a stale revision with 409, so concurrent edits never overwrite each other. */
|
|
183
|
+
async saveIdentity(ref, kind, body, context = {}) {
|
|
184
|
+
return ardentIdentityFileSchema.parse(await this.action(ref, 'identity-save', { target: kind, body: validated(ardentIdentityEditSchema, body, 'identity-save') }, context));
|
|
185
|
+
}
|
|
186
|
+
/** Each change answers the next configuration revision: chain it into the next skill-set or config-save. */
|
|
187
|
+
async setSkill(ref, name, body, context = {}) {
|
|
188
|
+
const target = validated(ardentSkillTargetSchema, name, 'skill-set');
|
|
189
|
+
return ardentConfigSavedSchema.parse(await this.action(ref, 'skill-set', { target, body: validated(ardentSkillEditSchema, body, 'skill-set') }, context));
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Install a HiveSkills catalog release (studio >= 3). Magnus answers 503 HIVESKILLS_UNCONFIGURED without a registry,
|
|
193
|
+
* 409 SKILL_VERSION_UNAVAILABLE or SKILL_CONFLICT, and 422 SKILL_ARCHIVE_INVALID; a Magnus that predates the action
|
|
194
|
+
* answers 400 "Invalid Ardent action".
|
|
195
|
+
*/
|
|
196
|
+
async installSkill(ref, body, context = {}) {
|
|
197
|
+
return ardentSkillInstallResultSchema.parse(await this.action(ref, 'skill-install', { body: validated(ardentSkillInstallSchema, body, 'skill-install') }, context));
|
|
198
|
+
}
|
|
199
|
+
/** Magnus refuses (403 CONFIG_PATH_FORBIDDEN) a text that changes anything outside ARDENT_SERVICE_CONFIG_PATHS. */
|
|
200
|
+
async saveConfig(ref, body, context = {}) {
|
|
201
|
+
return ardentConfigSavedSchema.parse(await this.action(ref, 'config-save', { body: validated(ardentConfigEditSchema, body, 'config-save') }, context));
|
|
202
|
+
}
|
|
203
|
+
// ── Studio routes ──
|
|
204
|
+
/** The node agent's Studio level for a node: 0 when it reports none. */
|
|
205
|
+
async studioLevel(nodeId, context = {}) {
|
|
206
|
+
return (await this.getInstallation(nodeId, context)).capabilities?.studio ?? 0;
|
|
207
|
+
}
|
|
208
|
+
/** Open (or reopen: the same key answers the same session) an Ardent session. studio >= 1; a context needs studio >= 2. */
|
|
209
|
+
async openSession(ref, body, context = {}) {
|
|
210
|
+
return ardentServiceSessionSchema.parse(await this.action(ref, 'session-open', { body: ardentSessionOpenSchema.parse(body) }, context));
|
|
211
|
+
}
|
|
212
|
+
/** Submit a team mission in a session opened with context mission. studio >= 2. */
|
|
213
|
+
async submitMission(ref, body, context = {}) {
|
|
214
|
+
const parsed = ardentMissionSubmitSchema.safeParse(body);
|
|
215
|
+
if (!parsed.success)
|
|
216
|
+
throw new MagnusError(`Mission is invalid: ${parsed.error.issues[0]?.message ?? 'invalid'}`, 400, 'VALIDATION_ERROR');
|
|
217
|
+
return ardentTaskAdmissionSchema.parse(await this.action(ref, 'mission-submit', { body: parsed.data }, context));
|
|
218
|
+
}
|
|
219
|
+
/** Pause at the next step boundary. studio >= 2; a finished task answers 409. */
|
|
220
|
+
async pauseTask(ref, taskId, context = {}) {
|
|
221
|
+
return ardentTaskPauseStateSchema.parse(await this.action(ref, 'task-pause', { target: uuid(taskId) }, context));
|
|
222
|
+
}
|
|
223
|
+
async resumeTask(ref, taskId, context = {}) {
|
|
224
|
+
return ardentTaskPauseStateSchema.parse(await this.action(ref, 'task-resume', { target: uuid(taskId) }, context));
|
|
225
|
+
}
|
|
226
|
+
/** A side-effect-free preview task with draft overrides. studio >= 2; needs the acting person. */
|
|
227
|
+
async submitPreview(ref, body, context) {
|
|
228
|
+
if (!context.actingSubject)
|
|
229
|
+
throw new MagnusError('A preview needs the acting person', 400, 'ACTING_SUBJECT_REQUIRED');
|
|
230
|
+
return ardentTaskAdmissionSchema.parse(await this.action(ref, 'preview-submit', { body: ardentPreviewSubmitSchema.parse(body) }, context));
|
|
231
|
+
}
|
|
232
|
+
/** Record a development note. studio >= 2; needs the acting person. */
|
|
233
|
+
async addDevelopmentNote(ref, body, context) {
|
|
234
|
+
if (!context.actingSubject)
|
|
235
|
+
throw new MagnusError('A development note needs the acting person', 400, 'ACTING_SUBJECT_REQUIRED');
|
|
236
|
+
return ardentDevelopmentRecordSchema.parse(await this.action(ref, 'development-note', { body: ardentDevelopmentNoteSchema.parse(body) }, context));
|
|
237
|
+
}
|
|
238
|
+
/** Artifact manifests a task registered, oldest first. studio >= 2. */
|
|
239
|
+
async taskArtifacts(ref, taskId, context = {}) {
|
|
240
|
+
return ardentTaskArtifactsSchema.parse(await this.resource(ref, `tasks/${uuid(taskId)}/artifacts`, context)).artifacts;
|
|
241
|
+
}
|
|
242
|
+
/** One artifact manifest. studio >= 2. */
|
|
243
|
+
async artifactManifest(ref, sha256, context = {}) {
|
|
244
|
+
if (!/^[a-f0-9]{64}$/.test(sha256))
|
|
245
|
+
throw new MagnusError('Invalid artifact ID', 400, 'VALIDATION_ERROR');
|
|
246
|
+
return ardentArtifactRecordSchema.parse(await this.resource(ref, `artifacts/${sha256}/manifest`, context));
|
|
247
|
+
}
|
|
248
|
+
/** Portable development records, cursor-paginated. studio >= 2. */
|
|
249
|
+
async development(ref, query = {}, context = {}) {
|
|
250
|
+
if (query.after !== undefined && !/^[A-Za-z0-9_-]{1,400}$/.test(query.after))
|
|
251
|
+
throw new MagnusError('Invalid development cursor', 400, 'VALIDATION_ERROR');
|
|
252
|
+
return ardentDevelopmentPageSchema.parse(await this.resource(ref, 'development', { ...context, query }));
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Follow a task's journal and live reply text (GET …/tasks/:id/stream, piped unbuffered by
|
|
256
|
+
* Magnus). Yields task.event (resumable, id = journal sequence), task.text, task.delta and
|
|
257
|
+
* task.done. Ardent ends a stream after 60 seconds; reconnect with `after`.
|
|
258
|
+
*/
|
|
259
|
+
async *streamTask(ref, taskId, options = {}) {
|
|
260
|
+
const { nodeId, profile } = parseAgentRef(ref);
|
|
261
|
+
const query = options.after !== undefined ? `?after=${options.after}` : '';
|
|
262
|
+
const response = await this.send('GET', `/api/v1/ardent/installations/${nodeId}/profiles/${profile}/tasks/${uuid(taskId)}/stream${query}`, options, undefined, { accept: 'text/event-stream' }, 0);
|
|
263
|
+
if (!response.ok || !response.body)
|
|
264
|
+
await this.fail(response);
|
|
265
|
+
yield* parseSse(response.body);
|
|
266
|
+
}
|
|
267
|
+
/** Magnus New Agent deploy operation. Magnus runs it only when the acting person is a Magnus ADMIN. */
|
|
268
|
+
async createAgent(body, context) {
|
|
269
|
+
if (!context.actingSubject)
|
|
270
|
+
throw new MagnusError('New Agent needs the acting person', 400, 'ACTING_SUBJECT_REQUIRED');
|
|
271
|
+
return operationAcceptedSchema.parse(await this.json('POST', '/api/v1/ardent/agents', context, ardentAgentDeployRequestSchema.parse(body)));
|
|
272
|
+
}
|
|
273
|
+
/** Step receipts of a New Agent or Enable HiveMem operation. */
|
|
274
|
+
async agentOperation(operationId, context = {}) {
|
|
275
|
+
return ardentAgentOperationSchema.parse(await this.json('GET', `/api/v1/ardent/agents/operations/${operationIdOf(operationId)}`, context));
|
|
276
|
+
}
|
|
277
|
+
/** Live operation updates: `operation` events, then one `done`. */
|
|
278
|
+
async *streamAgentOperation(operationId, options = {}) {
|
|
279
|
+
const response = await this.send('GET', `/api/v1/ardent/agents/operations/${operationIdOf(operationId)}/stream`, options, undefined, { accept: 'text/event-stream' }, 0);
|
|
280
|
+
if (!response.ok || !response.body)
|
|
281
|
+
await this.fail(response);
|
|
282
|
+
yield* parseSse(response.body);
|
|
283
|
+
}
|
|
284
|
+
/** Resume a failed operation from its first unfinished step. Needs an acting ADMIN. */
|
|
285
|
+
async resumeAgentOperation(operationId, context) {
|
|
286
|
+
if (!context.actingSubject)
|
|
287
|
+
throw new MagnusError('Resuming an operation needs the acting person', 400, 'ACTING_SUBJECT_REQUIRED');
|
|
288
|
+
return operationAcceptedSchema.parse(await this.json('POST', `/api/v1/ardent/agents/operations/${operationIdOf(operationId)}/resume`, context));
|
|
289
|
+
}
|
|
290
|
+
// ── Transport ──
|
|
291
|
+
async json(method, path, context, body) {
|
|
292
|
+
const response = await this.send(method, path, context, body);
|
|
293
|
+
if (!response.ok)
|
|
294
|
+
await this.fail(response);
|
|
295
|
+
const parsed = envelope.safeParse(await response.json().catch(() => null));
|
|
296
|
+
if (!parsed.success)
|
|
297
|
+
throw new MagnusError('Magnus answered with an unexpected body', 502, 'BAD_GATEWAY');
|
|
298
|
+
return parsed.data.data;
|
|
299
|
+
}
|
|
300
|
+
async send(method, path, context, body, extraHeaders = {}, timeoutMs = this.options.timeoutMs ?? 20_000) {
|
|
301
|
+
const attempt = async () => {
|
|
302
|
+
const headers = { authorization: `Bearer ${await this.options.tokens.token()}`, accept: 'application/json', ...extraHeaders };
|
|
303
|
+
if (context.actingSubject)
|
|
304
|
+
headers[ACTING_SUBJECT_HEADER] = context.actingSubject;
|
|
305
|
+
if (body !== undefined)
|
|
306
|
+
headers['content-type'] = 'application/json';
|
|
307
|
+
const signals = [context.signal, timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined].filter((signal) => Boolean(signal));
|
|
308
|
+
return this.request(`${this.baseUrl}${path}`, {
|
|
309
|
+
method, headers, redirect: 'error', ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
310
|
+
...(signals.length ? { signal: AbortSignal.any(signals) } : {}),
|
|
311
|
+
});
|
|
312
|
+
};
|
|
313
|
+
let response = await attempt();
|
|
314
|
+
if (response.status === 401) {
|
|
315
|
+
// A revoked or rotated service token: fetch a new one once.
|
|
316
|
+
await response.body?.cancel();
|
|
317
|
+
this.options.tokens.invalidate();
|
|
318
|
+
response = await attempt();
|
|
319
|
+
}
|
|
320
|
+
return response;
|
|
321
|
+
}
|
|
322
|
+
async fail(response) {
|
|
323
|
+
const parsed = failure.safeParse(await response.json().catch(() => null));
|
|
324
|
+
const message = parsed.success ? parsed.data.error.message.slice(0, 300) : `Magnus answered HTTP ${response.status}`;
|
|
325
|
+
throw new MagnusError(message, response.status, parsed.success ? parsed.data.error.code : `HTTP_${response.status}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function validated(schema, value, action) {
|
|
329
|
+
const parsed = schema.safeParse(value);
|
|
330
|
+
if (!parsed.success)
|
|
331
|
+
throw new MagnusError(`The ${action} request is invalid: ${parsed.error.issues[0]?.message ?? 'invalid'}`, 400, 'VALIDATION_ERROR');
|
|
332
|
+
return parsed.data;
|
|
333
|
+
}
|
|
334
|
+
function operationIdOf(value) {
|
|
335
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(value))
|
|
336
|
+
throw new MagnusError('Invalid operation ID', 400, 'VALIDATION_ERROR');
|
|
337
|
+
return value;
|
|
338
|
+
}
|
|
339
|
+
function uuid(value) {
|
|
340
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value))
|
|
341
|
+
throw new MagnusError('Invalid Ardent task ID', 400, 'VALIDATION_ERROR');
|
|
342
|
+
return value;
|
|
343
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface ServiceTokenOptions {
|
|
2
|
+
tokenUrl: string;
|
|
3
|
+
clientId: string;
|
|
4
|
+
clientSecret: string;
|
|
5
|
+
scope?: string | undefined;
|
|
6
|
+
fetch?: typeof fetch;
|
|
7
|
+
now?: () => number;
|
|
8
|
+
}
|
|
9
|
+
export declare class ServiceTokenError extends Error {
|
|
10
|
+
name: string;
|
|
11
|
+
}
|
|
12
|
+
export declare class ServiceTokenProvider {
|
|
13
|
+
private readonly options;
|
|
14
|
+
private cached;
|
|
15
|
+
private inFlight;
|
|
16
|
+
private retryAfter;
|
|
17
|
+
private readonly request;
|
|
18
|
+
private readonly now;
|
|
19
|
+
constructor(options: ServiceTokenOptions);
|
|
20
|
+
token(): Promise<string>;
|
|
21
|
+
/** Forget the cached token, for example after the resource answered 401. */
|
|
22
|
+
invalidate(): void;
|
|
23
|
+
private fetchToken;
|
|
24
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// ArdentStudio's own service identity: short-lived Oathweave client_credentials tokens,
|
|
2
|
+
// one machine client per audience (Oathweave binds a client to one audience). A token is
|
|
3
|
+
// fetched on first use and replaced before it expires; nothing has to renew it by hand.
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
export class ServiceTokenError extends Error {
|
|
6
|
+
name = 'ServiceTokenError';
|
|
7
|
+
}
|
|
8
|
+
const tokenResponse = z.object({ access_token: z.string().min(1), expires_in: z.number().positive().optional(), token_type: z.string().optional() });
|
|
9
|
+
const MIN_LIFETIME_MS = 10_000;
|
|
10
|
+
const MAX_LIFETIME_MS = 3600_000;
|
|
11
|
+
const FAILURE_BACKOFF_MS = 5_000;
|
|
12
|
+
function unverifiedExpiry(token) {
|
|
13
|
+
try {
|
|
14
|
+
const claims = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf8'));
|
|
15
|
+
return claims && typeof claims === 'object' && 'exp' in claims && typeof claims.exp === 'number' ? claims.exp * 1000 : undefined;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class ServiceTokenProvider {
|
|
22
|
+
options;
|
|
23
|
+
cached;
|
|
24
|
+
inFlight;
|
|
25
|
+
retryAfter = 0;
|
|
26
|
+
request;
|
|
27
|
+
now;
|
|
28
|
+
constructor(options) {
|
|
29
|
+
this.options = options;
|
|
30
|
+
this.request = options.fetch ?? ((input, init) => fetch(input, init));
|
|
31
|
+
this.now = options.now ?? Date.now;
|
|
32
|
+
}
|
|
33
|
+
async token() {
|
|
34
|
+
const at = this.now();
|
|
35
|
+
const usable = this.cached && this.cached.expiresAt - 5_000 > at ? this.cached : undefined;
|
|
36
|
+
if (usable && usable.refreshAt > at)
|
|
37
|
+
return usable.token;
|
|
38
|
+
if (this.inFlight)
|
|
39
|
+
return usable ? usable.token : this.inFlight;
|
|
40
|
+
if (at < this.retryAfter) {
|
|
41
|
+
if (usable)
|
|
42
|
+
return usable.token;
|
|
43
|
+
throw new ServiceTokenError('Oathweave token request is backing off after a failure');
|
|
44
|
+
}
|
|
45
|
+
const refresh = this.fetchToken().finally(() => { this.inFlight = undefined; });
|
|
46
|
+
this.inFlight = refresh;
|
|
47
|
+
if (usable) {
|
|
48
|
+
refresh.catch(() => undefined);
|
|
49
|
+
return usable.token;
|
|
50
|
+
}
|
|
51
|
+
return refresh;
|
|
52
|
+
}
|
|
53
|
+
/** Forget the cached token, for example after the resource answered 401. */
|
|
54
|
+
invalidate() {
|
|
55
|
+
this.cached = undefined;
|
|
56
|
+
}
|
|
57
|
+
async fetchToken() {
|
|
58
|
+
const startedAt = this.now();
|
|
59
|
+
const form = new URLSearchParams({ grant_type: 'client_credentials', client_id: this.options.clientId, client_secret: this.options.clientSecret });
|
|
60
|
+
if (this.options.scope)
|
|
61
|
+
form.set('scope', this.options.scope);
|
|
62
|
+
try {
|
|
63
|
+
const response = await this.request(this.options.tokenUrl, {
|
|
64
|
+
method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
65
|
+
body: form.toString(), redirect: 'error', signal: AbortSignal.timeout(10_000),
|
|
66
|
+
});
|
|
67
|
+
// Never include the response body: it may echo the request.
|
|
68
|
+
if (!response.ok)
|
|
69
|
+
throw new ServiceTokenError(`Oathweave token request failed (HTTP ${response.status})`);
|
|
70
|
+
const parsed = tokenResponse.safeParse(await response.json().catch(() => null));
|
|
71
|
+
if (!parsed.success)
|
|
72
|
+
throw new ServiceTokenError('Oathweave token response is malformed');
|
|
73
|
+
const lifetime = Math.min(MAX_LIFETIME_MS, Math.max(MIN_LIFETIME_MS, (parsed.data.expires_in ?? 300) * 1000));
|
|
74
|
+
const expiresAt = Math.min(startedAt + lifetime, unverifiedExpiry(parsed.data.access_token) ?? Number.POSITIVE_INFINITY);
|
|
75
|
+
if (expiresAt - 5_000 <= this.now())
|
|
76
|
+
throw new ServiceTokenError('Oathweave issued an expired token');
|
|
77
|
+
const span = expiresAt - startedAt;
|
|
78
|
+
this.cached = { token: parsed.data.access_token, expiresAt, refreshAt: startedAt + Math.max(0, Math.min(span * 0.8, span - 30_000)) };
|
|
79
|
+
this.retryAfter = 0;
|
|
80
|
+
return parsed.data.access_token;
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
this.retryAfter = this.now() + FAILURE_BACKOFF_MS;
|
|
84
|
+
throw error instanceof ServiceTokenError ? error : new ServiceTokenError(`Oathweave token request failed (${error instanceof Error ? error.name : 'error'})`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** One server-sent event. `id` is absent for events that are not resumable. */
|
|
2
|
+
export interface SseMessage {
|
|
3
|
+
event: string;
|
|
4
|
+
data: string;
|
|
5
|
+
id?: string;
|
|
6
|
+
}
|
|
7
|
+
/** Parse a text/event-stream body. Comments are skipped; a final unterminated event is dropped, as the spec says. */
|
|
8
|
+
export declare function parseSse(body: ReadableStream<Uint8Array>, maxEventBytes?: number): AsyncGenerator<SseMessage>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Parse a text/event-stream body. Comments are skipped; a final unterminated event is dropped, as the spec says. */
|
|
2
|
+
export async function* parseSse(body, maxEventBytes = 4 * 1024 * 1024) {
|
|
3
|
+
const decoder = new TextDecoder();
|
|
4
|
+
let buffer = '';
|
|
5
|
+
let event = '';
|
|
6
|
+
let data = [];
|
|
7
|
+
let id;
|
|
8
|
+
let size = 0;
|
|
9
|
+
for await (const chunk of body) {
|
|
10
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
11
|
+
let newline;
|
|
12
|
+
while ((newline = buffer.search(/\r\n|\r|\n/)) >= 0) {
|
|
13
|
+
const line = buffer.slice(0, newline);
|
|
14
|
+
buffer = buffer.slice(newline + (buffer.startsWith('\r\n', newline) ? 2 : 1));
|
|
15
|
+
if (line === '') {
|
|
16
|
+
if (data.length)
|
|
17
|
+
yield { event: event || 'message', data: data.join('\n'), ...(id !== undefined ? { id } : {}) };
|
|
18
|
+
event = '';
|
|
19
|
+
data = [];
|
|
20
|
+
id = undefined;
|
|
21
|
+
size = 0;
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (line.startsWith(':'))
|
|
25
|
+
continue;
|
|
26
|
+
const colon = line.indexOf(':');
|
|
27
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
28
|
+
const value = colon < 0 ? '' : line.slice(colon + 1).replace(/^ /, '');
|
|
29
|
+
size += value.length;
|
|
30
|
+
if (size > maxEventBytes)
|
|
31
|
+
throw new Error('Server-sent event exceeds the size limit');
|
|
32
|
+
if (field === 'event')
|
|
33
|
+
event = value;
|
|
34
|
+
else if (field === 'data')
|
|
35
|
+
data.push(value);
|
|
36
|
+
else if (field === 'id' && !value.includes('\0'))
|
|
37
|
+
id = value;
|
|
38
|
+
}
|
|
39
|
+
if (buffer.length > maxEventBytes)
|
|
40
|
+
throw new Error('Server-sent event exceeds the size limit');
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import type { DeliverableRevision } from '../db/repos/review.js';
|
|
3
|
+
import type { Message } from '../db/repos/room.js';
|
|
4
|
+
import { type StudioTask } from '../db/repos/tasks.js';
|
|
5
|
+
import type { activityStateSchema } from '../shared/browser.js';
|
|
6
|
+
export type ActivityState = z.infer<typeof activityStateSchema>;
|
|
7
|
+
/** Highest first: when an agent has several tasks, the first state in this list wins. */
|
|
8
|
+
export declare const ACTIVITY_PRECEDENCE: readonly ActivityState[];
|
|
9
|
+
export interface ActivityCandidate {
|
|
10
|
+
state: ActivityState;
|
|
11
|
+
label: string;
|
|
12
|
+
source: Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
/** The last status probe of an agent: running and reachable, not, or Magnus could not be asked. Absent until probed. */
|
|
15
|
+
export type ProbeResult = 'available' | 'offline' | 'unreachable';
|
|
16
|
+
export interface ActivityInput {
|
|
17
|
+
probe: ProbeResult | undefined;
|
|
18
|
+
/** Every task of this binding in the project, oldest first. */
|
|
19
|
+
tasks: readonly StudioTask[];
|
|
20
|
+
/** The first unfinished task ahead of a queued task in its ordering group. */
|
|
21
|
+
blockerOf: (task: StudioTask) => StudioTask | undefined;
|
|
22
|
+
/** Active tasks started by a hand-off from one of this binding's tasks. */
|
|
23
|
+
handedOff: readonly StudioTask[];
|
|
24
|
+
message: (id: string) => Pick<Message, 'body_md' | 'links'> | undefined;
|
|
25
|
+
roleName: (task: StudioTask) => string;
|
|
26
|
+
/** The newest revision this binding delivered in the project. */
|
|
27
|
+
delivered: (DeliverableRevision & {
|
|
28
|
+
deliverable_name: string;
|
|
29
|
+
}) | undefined;
|
|
30
|
+
now: Date;
|
|
31
|
+
deliveringMs: number;
|
|
32
|
+
}
|
|
33
|
+
export declare const excerpt: (text: string, max?: number) => string;
|
|
34
|
+
/** Every state the records show for one agent binding in one project. */
|
|
35
|
+
export declare function activityCandidates(input: ActivityInput): ActivityCandidate[];
|
|
36
|
+
/** The candidate with the highest precedence; among equals, the oldest task's. */
|
|
37
|
+
export declare function pickActivity(candidates: readonly ActivityCandidate[]): ActivityCandidate;
|
|
38
|
+
export declare function deriveActivity(input: ActivityInput): ActivityCandidate;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { TERMINAL_TASK_STATES } from '../db/repos/tasks.js';
|
|
2
|
+
/** Highest first: when an agent has several tasks, the first state in this list wins. */
|
|
3
|
+
export const ACTIVITY_PRECEDENCE = [
|
|
4
|
+
'offline', 'paused', 'blocked', 'asking', 'reviewing', 'working', 'queued', 'waiting', 'delivering', 'available', 'unknown',
|
|
5
|
+
];
|
|
6
|
+
export const excerpt = (text, max = 80) => { const line = text.replace(/\s+/g, ' ').trim(); return line.length > max ? `${line.slice(0, max - 1)}…` : line; };
|
|
7
|
+
const outcomeOf = (task) => (task.outcome && typeof task.outcome === 'object' ? task.outcome : {});
|
|
8
|
+
/** The clarification a task posted that nobody has answered yet. */
|
|
9
|
+
function openQuestion(task, input) {
|
|
10
|
+
const id = outcomeOf(task).clarification_message_id;
|
|
11
|
+
const message = typeof id === 'string' ? input.message(id) : undefined;
|
|
12
|
+
if (!message || message.links.answer_message_id)
|
|
13
|
+
return undefined;
|
|
14
|
+
return message.body_md;
|
|
15
|
+
}
|
|
16
|
+
/** Why the binding's newest task needs a person: it failed, Ardent lost track of it, or the agent reported itself blocked. */
|
|
17
|
+
function blockedBy(task, input) {
|
|
18
|
+
if (!TERMINAL_TASK_STATES.includes(task.state))
|
|
19
|
+
return undefined;
|
|
20
|
+
const outcome = outcomeOf(task);
|
|
21
|
+
const error = typeof outcome.error === 'string' && outcome.error ? outcome.error : undefined;
|
|
22
|
+
if (task.state === 'failed')
|
|
23
|
+
return error ?? `${task.title} failed`;
|
|
24
|
+
if (task.state === 'unknown')
|
|
25
|
+
return error ?? `Ardent does not know how ${task.title} ended`;
|
|
26
|
+
const result = outcome.team_result;
|
|
27
|
+
if (result?.outcome === 'blocked') {
|
|
28
|
+
const reply = typeof outcome.reply_message_id === 'string' ? input.message(outcome.reply_message_id)?.body_md : undefined;
|
|
29
|
+
return reply?.trim() ? reply : task.title;
|
|
30
|
+
}
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
function taskCandidate(task, input) {
|
|
34
|
+
const source = { task_id: task.id, kind: 'task' };
|
|
35
|
+
switch (task.state) {
|
|
36
|
+
case 'pausing': return { state: 'paused', label: `Pause requested: ${task.title}`, source };
|
|
37
|
+
case 'paused': return { state: 'paused', label: `Paused: ${task.title}`, source };
|
|
38
|
+
case 'input_required': return { state: 'asking', label: `Asking: ${excerpt(openQuestion(task, input) ?? task.title)}`, source: { ...source, kind: 'clarification' } };
|
|
39
|
+
case 'running':
|
|
40
|
+
case 'queued': {
|
|
41
|
+
const question = openQuestion(task, input);
|
|
42
|
+
if (question)
|
|
43
|
+
return { state: 'asking', label: `Asking: ${excerpt(question)}`, source: { ...source, kind: 'clarification' } };
|
|
44
|
+
const accepted = Boolean(task.ardent.task_id);
|
|
45
|
+
if (task.mode === 'review' && (task.state === 'running' || task.progress.model_started))
|
|
46
|
+
return { state: 'reviewing', label: `Reviewing: ${task.title}`, source };
|
|
47
|
+
// Working only once the journal shows the model started or a tool was tried.
|
|
48
|
+
if (accepted && task.progress.model_started) {
|
|
49
|
+
return { state: 'working', label: `Working: ${task.title}${task.progress.tool ? ` · ${task.progress.tool}` : ''}`, source: { ...source, kind: 'journal' } };
|
|
50
|
+
}
|
|
51
|
+
if (task.state === 'running')
|
|
52
|
+
return { state: 'queued', label: `Starting: ${task.title}`, source };
|
|
53
|
+
const blocker = accepted ? undefined : input.blockerOf(task);
|
|
54
|
+
if (blocker)
|
|
55
|
+
return { state: 'waiting', label: `Waiting for ${input.roleName(blocker)}`, source: { ...source, kind: 'group', waiting_for: blocker.id } };
|
|
56
|
+
return { state: 'queued', label: `Queued: ${task.title}`, source };
|
|
57
|
+
}
|
|
58
|
+
default: return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Every state the records show for one agent binding in one project. */
|
|
62
|
+
export function activityCandidates(input) {
|
|
63
|
+
const candidates = [];
|
|
64
|
+
if (input.probe === 'offline')
|
|
65
|
+
candidates.push({ state: 'offline', label: 'Offline', source: { kind: 'presence' } });
|
|
66
|
+
if (input.probe === 'unreachable')
|
|
67
|
+
candidates.push({ state: 'offline', label: 'Offline: Magnus is unreachable', source: { kind: 'presence' } });
|
|
68
|
+
for (const task of input.tasks) {
|
|
69
|
+
const candidate = taskCandidate(task, input);
|
|
70
|
+
if (candidate)
|
|
71
|
+
candidates.push(candidate);
|
|
72
|
+
}
|
|
73
|
+
const newest = input.tasks.at(-1);
|
|
74
|
+
const reason = newest ? blockedBy(newest, input) : undefined;
|
|
75
|
+
if (newest && reason)
|
|
76
|
+
candidates.push({ state: 'blocked', label: `Blocked: ${excerpt(reason, 120)}`, source: { task_id: newest.id, kind: 'outcome' } });
|
|
77
|
+
for (const task of input.handedOff) {
|
|
78
|
+
candidates.push({ state: 'waiting', label: `Waiting for ${input.roleName(task)}`, source: { task_id: task.id, kind: 'handoff', from_task: task.source.from_task } });
|
|
79
|
+
}
|
|
80
|
+
const delivered = input.delivered;
|
|
81
|
+
if (delivered && input.now.getTime() - Date.parse(delivered.received_at) < input.deliveringMs) {
|
|
82
|
+
candidates.push({ state: 'delivering', label: `Delivered ${delivered.deliverable_name} r${delivered.revision}`,
|
|
83
|
+
source: { kind: 'artifact_registered', revision_id: delivered.id, task_id: delivered.source_task_id } });
|
|
84
|
+
}
|
|
85
|
+
if (input.probe === 'available')
|
|
86
|
+
candidates.push({ state: 'available', label: 'Available', source: { kind: 'presence' } });
|
|
87
|
+
candidates.push({ state: 'unknown', label: 'Status not checked yet', source: { kind: 'presence' } });
|
|
88
|
+
return candidates;
|
|
89
|
+
}
|
|
90
|
+
/** The candidate with the highest precedence; among equals, the oldest task's. */
|
|
91
|
+
export function pickActivity(candidates) {
|
|
92
|
+
let best;
|
|
93
|
+
for (const candidate of candidates) {
|
|
94
|
+
if (!best || ACTIVITY_PRECEDENCE.indexOf(candidate.state) < ACTIVITY_PRECEDENCE.indexOf(best.state))
|
|
95
|
+
best = candidate;
|
|
96
|
+
}
|
|
97
|
+
return best;
|
|
98
|
+
}
|
|
99
|
+
export function deriveActivity(input) {
|
|
100
|
+
return pickActivity(activityCandidates(input));
|
|
101
|
+
}
|