@agentic-kit/session 0.0.0-stage → 0.2.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 +23 -0
- package/README.md +207 -2
- package/account-store.d.ts +78 -0
- package/account-store.js +162 -0
- package/agent-store.d.ts +79 -0
- package/agent-store.js +251 -0
- package/agent.d.ts +137 -0
- package/agent.js +514 -0
- package/api-key.d.ts +53 -0
- package/api-key.js +60 -0
- package/app-session.d.ts +48 -0
- package/app-session.js +105 -0
- package/auth-error.d.ts +54 -0
- package/auth-error.js +186 -0
- package/auth.d.ts +169 -0
- package/auth.js +514 -0
- package/backend-store.d.ts +134 -0
- package/backend-store.js +259 -0
- package/env.d.ts +9 -0
- package/env.js +10 -0
- package/esm/account-store.d.ts +78 -0
- package/esm/account-store.js +146 -0
- package/esm/agent-store.d.ts +79 -0
- package/esm/agent-store.js +201 -0
- package/esm/agent.d.ts +137 -0
- package/esm/agent.js +503 -0
- package/esm/api-key.d.ts +53 -0
- package/esm/api-key.js +52 -0
- package/esm/app-session.d.ts +48 -0
- package/esm/app-session.js +66 -0
- package/esm/auth-error.d.ts +54 -0
- package/esm/auth-error.js +171 -0
- package/esm/auth.d.ts +169 -0
- package/esm/auth.js +467 -0
- package/esm/backend-store.d.ts +134 -0
- package/esm/backend-store.js +239 -0
- package/esm/env.d.ts +9 -0
- package/esm/env.js +6 -0
- package/esm/index.d.ts +12 -0
- package/esm/index.js +11 -0
- package/esm/operation.d.ts +45 -0
- package/esm/operation.js +87 -0
- package/esm/session.d.ts +192 -0
- package/esm/session.js +297 -0
- package/esm/tools-host.d.ts +29 -0
- package/esm/tools-host.js +71 -0
- package/index.d.ts +12 -0
- package/index.js +63 -0
- package/operation.d.ts +45 -0
- package/operation.js +92 -0
- package/package.json +40 -3
- package/session.d.ts +192 -0
- package/session.js +307 -0
- package/tools-host.d.ts +29 -0
- package/tools-host.js +74 -0
package/esm/agent.js
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
import { auth } from '@constructive-io/sdk';
|
|
2
|
+
import { currentContextName, loadSession } from './account-store';
|
|
3
|
+
import { agentEntryExists, AgentNameError, AgentRecordUnreadable, checkAgentName, createAgentEntry, deleteAgent, dropCachedToken, listAgentNames, readAgent, readCachedToken, writeAgent, writeCachedToken } from './agent-store';
|
|
4
|
+
import { errorText, revokeKey } from './api-key';
|
|
5
|
+
import { endSignIn, proofSignIn } from './auth';
|
|
6
|
+
import { describeAuthError, errorCodes, isNetworkError, isUnavailable, publicRefusal, RedirectRefusedError, trackedFetch, withAuthTimeout } from './auth-error';
|
|
7
|
+
import { differingPlanes, readBackend } from './backend-store';
|
|
8
|
+
import { getConstructiveEnv } from './env';
|
|
9
|
+
import { Operation, undoneText } from './operation';
|
|
10
|
+
import { agentBinding, renewFix } from './session';
|
|
11
|
+
/**
|
|
12
|
+
* The org capability mask of an agent that may not change the schema: every
|
|
13
|
+
* capability but `manage_database`. The platform's org capabilities are 64
|
|
14
|
+
* bits wide, `manage_database` is org capability 12, and bit N counts from the
|
|
15
|
+
* right. The backend right-pads a shorter mask with zeros, so the mask must be
|
|
16
|
+
* the full width; a wider backend would read this one as removing more
|
|
17
|
+
* capabilities, never fewer.
|
|
18
|
+
*/
|
|
19
|
+
const ORG_CAPABILITY_WIDTH = 64;
|
|
20
|
+
const MANAGE_DATABASE_BIT = 12;
|
|
21
|
+
export const SCHEMA_READ_ONLY_MASK = Array.from({ length: ORG_CAPABILITY_WIDTH }, (_, i) => (i === ORG_CAPABILITY_WIDTH - MANAGE_DATABASE_BIT ? '0' : '1')).join('');
|
|
22
|
+
/** The org membership type, where the platform's schema capabilities live. */
|
|
23
|
+
const ORG_MEMBERSHIP_TYPE = 2;
|
|
24
|
+
/** How long an agent's key lasts: the cap set on its principal, and what its key asks for. */
|
|
25
|
+
const AGENT_KEY_DAYS = 30;
|
|
26
|
+
/** Mint a new access token once less than this is left of the cached one: covers clock skew and one request. */
|
|
27
|
+
const TOKEN_MARGIN_MS = 30_000;
|
|
28
|
+
/** A failed agent operation. `code` is the server's error code when it gave one. No secret is in it. */
|
|
29
|
+
export class AgentError extends Error {
|
|
30
|
+
kind;
|
|
31
|
+
code;
|
|
32
|
+
constructor(kind, message, code) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.kind = kind;
|
|
35
|
+
this.code = code;
|
|
36
|
+
this.name = 'AgentError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const SIGN_IN_AGAIN = 'Sign in again with your password, then retry.';
|
|
40
|
+
/** Classified by facts only: no answer, the HTTP status, then `extensions.code`. */
|
|
41
|
+
function agentFailure(err, what, endpoint, status) {
|
|
42
|
+
if (isNetworkError(err))
|
|
43
|
+
return new AgentError('backend-unreachable', `${what} failed: ${describeAuthError(err)}`);
|
|
44
|
+
if (err instanceof RedirectRefusedError)
|
|
45
|
+
return new AgentError('server-error', `${what} failed: ${err.message}`, `HTTP_${err.status}`);
|
|
46
|
+
if (status !== undefined && (status < 200 || status >= 300)) {
|
|
47
|
+
return new AgentError('server-error', `${what} failed: the server at ${endpoint} answered HTTP ${status}. Retry later, or check the backend logs.`, `HTTP_${status}`);
|
|
48
|
+
}
|
|
49
|
+
const code = errorCodes(err)[0];
|
|
50
|
+
if (!code)
|
|
51
|
+
return new AgentError('server-error', `${what} failed: ${describeAuthError(err)}. Retry later, or check the backend logs.`);
|
|
52
|
+
if (code.startsWith('STEP_UP_REQUIRED'))
|
|
53
|
+
return new AgentError('step-up-required', `${what} needs a recent sign-in (${code}). ${SIGN_IN_AGAIN}`, code);
|
|
54
|
+
if (code === 'UNAUTHENTICATED' || code === 'NOT_AUTHENTICATED')
|
|
55
|
+
return new AgentError('sign-in-required', `${what} was refused because the sign-in has ended (${code}). ${SIGN_IN_AGAIN}`, code);
|
|
56
|
+
if (code.startsWith('PRINCIPAL_CANNOT_') || code === 'PRINCIPAL_REQUIRED') {
|
|
57
|
+
return new AgentError('not-a-person', `${what} was refused: only the person, not an agent, may do this (${code}). Run it signed in as yourself.`, code);
|
|
58
|
+
}
|
|
59
|
+
if (code === 'PRINCIPAL_NOT_FOUND')
|
|
60
|
+
return new AgentError('not-found', `${what} failed: the backend has no such principal (${code}).`, code);
|
|
61
|
+
const refusal = publicRefusal(err);
|
|
62
|
+
if (!refusal || isUnavailable(refusal))
|
|
63
|
+
return new AgentError('server-error', `${what} failed: ${describeAuthError(err)}. Retry later, or check the backend logs.`, code);
|
|
64
|
+
const kind = refusal.status === 404 ? 'not-found' : refusal.status === 409 ? 'conflict' : 'refused';
|
|
65
|
+
return new AgentError(kind, `${what} was refused. ${refusal.words}`, refusal.code);
|
|
66
|
+
}
|
|
67
|
+
/** One auth-plane call with the sign-in timeout, its failure classified. */
|
|
68
|
+
async function call(endpoint, bearer, what, request) {
|
|
69
|
+
const http = trackedFetch(endpoint);
|
|
70
|
+
const client = auth.createClient({ endpoint, fetch: http.fetch, ...(bearer ? { headers: { Authorization: `Bearer ${bearer}` } } : {}) });
|
|
71
|
+
try {
|
|
72
|
+
return await withAuthTimeout(request(client).unwrap(), endpoint);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
throw agentFailure(err, what, endpoint, http.status());
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function person(session) {
|
|
79
|
+
if (session.kind !== 'signed-in' || session.source !== 'store') {
|
|
80
|
+
const what = session.kind === 'signed-in' && session.source === 'agent'
|
|
81
|
+
? 'an agent, and only the person may manage agents'
|
|
82
|
+
: session.kind === 'signed-in' || session.kind === 'signed-out'
|
|
83
|
+
? 'a credential from the environment, so there is no stored context to file the agent under'
|
|
84
|
+
: 'no sign-in';
|
|
85
|
+
throw new AgentError('not-a-person', `Managing agents needs the person signed in, with a session stored by this computer; this session is ${what}. Unset the CONSTRUCTIVE_* credential variables if they are set, sign in as yourself, then retry.`);
|
|
86
|
+
}
|
|
87
|
+
return session;
|
|
88
|
+
}
|
|
89
|
+
/** The person's stored bearer (the key, else the token another app stored), for the calls that make no credential. */
|
|
90
|
+
function storedBearer(owner) {
|
|
91
|
+
const { key, accessToken, accessTokenExpiresAt } = owner.account;
|
|
92
|
+
const expires = key.kind === 'active' ? key.expiresAt : accessTokenExpiresAt;
|
|
93
|
+
if (expires && Date.parse(expires) <= Date.now())
|
|
94
|
+
throw new AgentError('sign-in-required', `The person's sign-in ended at ${expires}. ${SIGN_IN_AGAIN}`);
|
|
95
|
+
return key.kind === 'active' ? key.apiKey : accessToken;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Run `task` with a new sign-in of the person (`proof`: the password, or the code of the challenge it started), which a
|
|
99
|
+
* key for a principal needs, and end that sign-in on the server when it is done, so no bearer session is left behind.
|
|
100
|
+
* Throws a `SignInError` when the sign-in fails; `SecondFactorRequired` when the password needs a code.
|
|
101
|
+
*/
|
|
102
|
+
async function withFreshSignIn(owner, proof, task) {
|
|
103
|
+
const endpoint = owner.backend.authEndpoint;
|
|
104
|
+
if (!owner.account.email)
|
|
105
|
+
throw new AgentError('sign-in-required', `The stored session records no email to sign in with. ${SIGN_IN_AGAIN}`);
|
|
106
|
+
const fresh = await proofSignIn(endpoint, owner.account.email, proof);
|
|
107
|
+
try {
|
|
108
|
+
if (fresh.userId !== owner.account.userId) {
|
|
109
|
+
throw new AgentError('not-a-person', `The password signed in another account than ${owner.account.email}, which is signed in here. Use the password of ${owner.account.email}.`);
|
|
110
|
+
}
|
|
111
|
+
return await task(fresh.accessToken);
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
await endSignIn(endpoint, fresh.accessToken);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function infoOf(store, record) {
|
|
118
|
+
const stored = readBackend(store, record.context);
|
|
119
|
+
let state = 'ready';
|
|
120
|
+
if (stored?.status !== 'complete' || differingPlanes(record.issuedFor, stored.backend).length > 0)
|
|
121
|
+
state = 'issuer-mismatch';
|
|
122
|
+
else if (Date.parse(record.keyExpiresAt) <= Date.now())
|
|
123
|
+
state = 'set-up-again';
|
|
124
|
+
return {
|
|
125
|
+
name: record.name,
|
|
126
|
+
context: record.context,
|
|
127
|
+
principalId: record.principalId,
|
|
128
|
+
schemaChanges: record.schemaChanges,
|
|
129
|
+
...(record.organization ? { organization: record.organization } : {}),
|
|
130
|
+
createdAt: record.createdAt,
|
|
131
|
+
keyExpiresAt: record.keyExpiresAt,
|
|
132
|
+
state
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** The stored record of an agent the person manages, or the AgentError that says why there is none. */
|
|
136
|
+
function ownedRecord(store, context, name) {
|
|
137
|
+
let record;
|
|
138
|
+
try {
|
|
139
|
+
record = readAgent(store, context, name);
|
|
140
|
+
}
|
|
141
|
+
catch (err) {
|
|
142
|
+
if (err instanceof AgentRecordUnreadable)
|
|
143
|
+
throw new AgentError('unreadable-record', `${err.message} Remove the agent and add it again.`);
|
|
144
|
+
throw err;
|
|
145
|
+
}
|
|
146
|
+
if (!record)
|
|
147
|
+
throw new AgentError('not-found', `There is no agent named "${name}" under the context "${context}".`);
|
|
148
|
+
return record;
|
|
149
|
+
}
|
|
150
|
+
/** The record of an agent the person's backend issued: only that backend can change its principal or its key. */
|
|
151
|
+
function issuedRecord(store, owner, name) {
|
|
152
|
+
const record = ownedRecord(store, owner.context, name);
|
|
153
|
+
if (differingPlanes(record.issuedFor, owner.backend).length > 0) {
|
|
154
|
+
throw new AgentError('issuer-mismatch', `The agent "${name}" was set up with the backend ${record.issuedFor.apiEndpoint}, not the one this context names now, so it was not changed. Remove the agent and add it again under this backend.`);
|
|
155
|
+
}
|
|
156
|
+
return record;
|
|
157
|
+
}
|
|
158
|
+
const nameTaken = (name, context) => new AgentError('name-taken', `There is already an agent named "${name}" under the context "${context}". Pick another name, or remove that agent first.`);
|
|
159
|
+
function checkedName(name) {
|
|
160
|
+
try {
|
|
161
|
+
return checkAgentName(name);
|
|
162
|
+
}
|
|
163
|
+
catch (err) {
|
|
164
|
+
if (err instanceof AgentNameError)
|
|
165
|
+
throw new AgentError('invalid-name', err.message);
|
|
166
|
+
throw err;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* An agent operation (`Operation`): a failure before its commit throws the AgentError it was (or `map` makes of it),
|
|
171
|
+
* with what was undone after its message.
|
|
172
|
+
*/
|
|
173
|
+
function agentOperation(map = () => undefined) {
|
|
174
|
+
return new Operation((failure) => {
|
|
175
|
+
const tail = undoneText(failure.undone);
|
|
176
|
+
const cause = map(failure) ?? failure.cause;
|
|
177
|
+
const message = (text) => (tail ? `${text} ${tail}` : text);
|
|
178
|
+
if (cause instanceof AgentError)
|
|
179
|
+
return new AgentError(cause.kind, message(cause.message), cause.code);
|
|
180
|
+
return new Error(message(errorText(cause)), { cause });
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
async function createPrincipal(endpoint, bearer, name, organization) {
|
|
184
|
+
const principalId = await call(endpoint, bearer, 'Creating the agent', (client) => client.mutation.createPrincipal({ input: { name, useAdminOwner: false, ...(organization ? { entityIds: [organization] } : {}) } }, { select: { result: true } })).then((data) => data?.createPrincipal?.result, (err) => {
|
|
185
|
+
// The backend keeps one principal per name: this store has no record of the one it has.
|
|
186
|
+
if (err instanceof AgentError && err.kind === 'conflict') {
|
|
187
|
+
throw new AgentError('name-taken', `The backend has an agent named "${name}" already, which this computer has no record of. Pick another name.`, err.code);
|
|
188
|
+
}
|
|
189
|
+
throw err;
|
|
190
|
+
});
|
|
191
|
+
if (!principalId)
|
|
192
|
+
throw new AgentError('server-error', 'Creating the agent failed: the backend answered without a principal id. Retry later, or check the backend logs.');
|
|
193
|
+
return principalId;
|
|
194
|
+
}
|
|
195
|
+
async function deletePrincipal(endpoint, bearer, principalId, what) {
|
|
196
|
+
return call(endpoint, bearer, what, (client) => client.mutation.deletePrincipal({ input: { principalId } }, { select: { result: true } }));
|
|
197
|
+
}
|
|
198
|
+
async function revokeAgentKey(endpoint, bearer, keyId, what) {
|
|
199
|
+
const data = await call(endpoint, bearer, what, (client) => client.mutation.revokeApiKey({ input: { keyId } }, { select: { result: true } }));
|
|
200
|
+
if (data?.revokeApiKey?.result !== true) {
|
|
201
|
+
throw new AgentError('server-error', `${what} failed: the server did not confirm that the key was revoked.`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async function setScope(endpoint, bearer, principalId, schemaChanges) {
|
|
205
|
+
const data = await call(endpoint, bearer, 'Setting what the agent may change', (client) => client.mutation.setPrincipalScope({
|
|
206
|
+
input: {
|
|
207
|
+
principalId,
|
|
208
|
+
membershipType: ORG_MEMBERSHIP_TYPE,
|
|
209
|
+
allowedMask: schemaChanges ? null : SCHEMA_READ_ONLY_MASK,
|
|
210
|
+
// The scope's own default is true, which would give the agent the person's admin flag back.
|
|
211
|
+
useAdminOwner: false,
|
|
212
|
+
isActive: true,
|
|
213
|
+
isReadOnly: false
|
|
214
|
+
}
|
|
215
|
+
}, { select: { result: true } }));
|
|
216
|
+
if (data?.setPrincipalScope?.result !== true) {
|
|
217
|
+
throw new AgentError('server-error', 'Setting what the agent may change failed: the server did not confirm the change.');
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
/** Cap every key minted for the principal; the backend applies a cap when it mints a key, so this comes first. */
|
|
221
|
+
async function capKeys(endpoint, bearer, principalId) {
|
|
222
|
+
// The generated SDK types this input as a table patch; the backend's updatePrincipal takes each setting as its own argument.
|
|
223
|
+
const input = { principalId, apiKeyMaxDuration: { days: AGENT_KEY_DAYS } };
|
|
224
|
+
const capped = await call(endpoint, bearer, "Capping the agent's key lifetime", (client) => client.mutation.updatePrincipal({ input }, { select: { result: true } })).then((data) => data?.updatePrincipal?.result);
|
|
225
|
+
if (capped !== true)
|
|
226
|
+
throw new AgentError('server-error', "Capping the agent's key lifetime failed: the backend did not confirm it. Retry later, or check the backend logs.");
|
|
227
|
+
}
|
|
228
|
+
async function createKey(endpoint, bearer, principalId, name) {
|
|
229
|
+
const data = await call(endpoint, bearer, 'Creating the key of the agent', (client) => client.mutation.createApiKey({ input: { keyName: `agent:${name}`, accessLevel: 'full_access', mfaLevel: 'none', expiresIn: { days: AGENT_KEY_DAYS }, principalId } }, { select: { result: { select: { apiKey: true, keyId: true, expiresAt: true } } } }));
|
|
230
|
+
const key = data?.createApiKey?.result;
|
|
231
|
+
const expiresAt = key?.expiresAt ? Date.parse(key.expiresAt) : NaN;
|
|
232
|
+
if (!key?.apiKey || !key.keyId || !key.expiresAt || !(expiresAt > Date.now())) {
|
|
233
|
+
const keyId = key?.keyId;
|
|
234
|
+
const revoked = keyId ? await revokeKey(keyId, (id) => revokeAgentKey(endpoint, bearer, id, 'Revoking a key that cannot be stored')) : undefined;
|
|
235
|
+
const cleanup = revoked?.kind === 'revoked' ? ' That key was revoked.' : keyId ? ` Revoke the key ${keyId} in the app.` : '';
|
|
236
|
+
throw new AgentError('server-error', `Creating the key of the agent failed: the backend did not return a complete key with an end in the future.${cleanup} Retry later, or check the backend logs.`);
|
|
237
|
+
}
|
|
238
|
+
return { apiKey: key.apiKey, keyId: key.keyId, keyExpiresAt: key.expiresAt };
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Create an agent of the signed-in person: a principal that does not share the
|
|
242
|
+
* person's admin flag, held to `organization` when one is given, that may not
|
|
243
|
+
* change the schema unless `allowSchemaChanges`, with every key of it capped at
|
|
244
|
+
* 30 days, and one such key, stored under the person's context. This package
|
|
245
|
+
* uses the key only to mint access tokens, but the backend accepts the key itself
|
|
246
|
+
* on requests too. It signs the person in afresh with the password (or the
|
|
247
|
+
* code of the challenge the password started) and ends that sign-in when done.
|
|
248
|
+
* A failure after the principal exists deletes it again and says so.
|
|
249
|
+
*/
|
|
250
|
+
export async function createAgent({ store, session, name, organization, allowSchemaChanges, ...proof }) {
|
|
251
|
+
const agentName = checkedName(name);
|
|
252
|
+
const owner = person(session);
|
|
253
|
+
const context = owner.context;
|
|
254
|
+
if (agentEntryExists(store, context, agentName))
|
|
255
|
+
throw nameTaken(agentName, context);
|
|
256
|
+
return withFreshSignIn(owner, proof, (bearer) => createWith(store, owner, bearer, agentName, organization, allowSchemaChanges));
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* create the principal [undo: delete it] -> set its scope -> cap its keys -> create its key -> COMMIT: store the agent
|
|
260
|
+
*
|
|
261
|
+
* The steps after the first need no undo of their own: deleting the principal ends its scope and its key.
|
|
262
|
+
*/
|
|
263
|
+
async function createWith(store, owner, bearer, agentName, organization, allowSchemaChanges) {
|
|
264
|
+
const context = owner.context;
|
|
265
|
+
const endpoint = owner.backend.authEndpoint;
|
|
266
|
+
// Another add of this name may have finished since the first check.
|
|
267
|
+
const op = agentOperation(({ cause }) => (cause?.code === 'EEXIST' ? nameTaken(agentName, context) : undefined));
|
|
268
|
+
const principalId = await op.step('create the principal', () => createPrincipal(endpoint, bearer, agentName, organization), {
|
|
269
|
+
run: (id) => deletePrincipal(endpoint, bearer, id, 'Deleting the half-made agent'),
|
|
270
|
+
undone: 'The principal it made was deleted again.',
|
|
271
|
+
notUndone: (id, reason) => `The principal ${id} it made could not be deleted (${reason}); delete it from the app.`
|
|
272
|
+
});
|
|
273
|
+
await op.step('set its scope', () => setScope(endpoint, bearer, principalId, allowSchemaChanges));
|
|
274
|
+
await op.step('cap its keys', () => capKeys(endpoint, bearer, principalId));
|
|
275
|
+
const key = await op.step('create its key', () => createKey(endpoint, bearer, principalId, agentName));
|
|
276
|
+
const record = {
|
|
277
|
+
name: agentName,
|
|
278
|
+
context,
|
|
279
|
+
principalId,
|
|
280
|
+
ownerId: owner.account.userId,
|
|
281
|
+
...(organization ? { organization } : {}),
|
|
282
|
+
schemaChanges: allowSchemaChanges,
|
|
283
|
+
createdAt: new Date().toISOString(),
|
|
284
|
+
issuedFor: owner.backend,
|
|
285
|
+
...key
|
|
286
|
+
};
|
|
287
|
+
return op.commit('store the agent', () => {
|
|
288
|
+
const info = infoOf(store, record);
|
|
289
|
+
createAgentEntry(store, record);
|
|
290
|
+
return info;
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
export function listAgents({ store, context }) {
|
|
294
|
+
const resolved = context ?? currentContextName(store);
|
|
295
|
+
if (!resolved)
|
|
296
|
+
return [];
|
|
297
|
+
return listAgentNames(store, resolved).flatMap((name) => {
|
|
298
|
+
try {
|
|
299
|
+
const record = readAgent(store, resolved, name);
|
|
300
|
+
return record ? [infoOf(store, record)] : [];
|
|
301
|
+
}
|
|
302
|
+
catch (err) {
|
|
303
|
+
if (!(err instanceof AgentRecordUnreadable))
|
|
304
|
+
throw err;
|
|
305
|
+
return [{ name, context: resolved, state: 'unreadable', problem: `${err.message} Remove the agent and add it again.` }];
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Mint an access token with the agent's key, for its principal, at the checked auth endpoint of the context the key
|
|
311
|
+
* was bound to. The refresh token the backend makes is never asked for.
|
|
312
|
+
*/
|
|
313
|
+
async function mint(record, authEndpoint) {
|
|
314
|
+
const unusable = (reason, problem, fix) => ({ kind: 'agent-unusable', context: record.context, agent: record.name, reason, problem, fix });
|
|
315
|
+
let result;
|
|
316
|
+
try {
|
|
317
|
+
const data = await call(authEndpoint, record.apiKey, 'Issuing the agent an access token', (client) => client.mutation.mintAccessToken({ input: { principalId: record.principalId, intent: `agent:${record.name}` } }, { select: { result: { select: { accessToken: true, accessExpiresAt: true } } } }));
|
|
318
|
+
result = data?.mintAccessToken?.result;
|
|
319
|
+
}
|
|
320
|
+
catch (err) {
|
|
321
|
+
if (!(err instanceof AgentError))
|
|
322
|
+
throw err;
|
|
323
|
+
if (err.kind === 'sign-in-required' || err.kind === 'not-found') {
|
|
324
|
+
return unusable('set-up-again', `The backend no longer accepts the key of the agent "${record.name}" (${err.code}): the agent was removed, or its key was revoked or has ended.`, renewFix(record.name));
|
|
325
|
+
}
|
|
326
|
+
return unusable('mint-failed', err.message, 'Retry: the key of the agent is unchanged.');
|
|
327
|
+
}
|
|
328
|
+
if (!result?.accessToken || !result.accessExpiresAt) {
|
|
329
|
+
return unusable('mint-failed', `Issuing the agent "${record.name}" an access token failed: the backend answered without a token.`, 'Retry later, or check the backend logs.');
|
|
330
|
+
}
|
|
331
|
+
const ends = Date.parse(result.accessExpiresAt);
|
|
332
|
+
if (Number.isNaN(ends) || ends <= Date.now()) {
|
|
333
|
+
return unusable('mint-failed', `Issuing the agent "${record.name}" an access token failed: the backend gave it an end that is not a time in the future, so it was not used.`, 'Retry later, or check the backend logs.');
|
|
334
|
+
}
|
|
335
|
+
return { keyId: record.keyId, accessToken: result.accessToken, accessExpiresAt: result.accessExpiresAt };
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* The agent's session for use: the cached access token while more than a
|
|
339
|
+
* short margin of it is left, else a new one minted with the agent's key and
|
|
340
|
+
* cached. Processes need no lock: a token may be used many times, so two that
|
|
341
|
+
* mint at once both work, and the cache keeps one of them.
|
|
342
|
+
*
|
|
343
|
+
* `rejectedToken` is an access token of this agent that the backend just
|
|
344
|
+
* refused as signed out. When it is the cached one, that entry is dropped and
|
|
345
|
+
* one token is minted from the key; when another process already cached a new
|
|
346
|
+
* one, that one is used. It never retries on its own, so a caller passes it
|
|
347
|
+
* once per refusal.
|
|
348
|
+
*/
|
|
349
|
+
export async function agentSession({ store, name, context, env = getConstructiveEnv(), rejectedToken }) {
|
|
350
|
+
const bound = agentBinding({ store, context, env, agent: name });
|
|
351
|
+
if (bound.kind !== 'bound')
|
|
352
|
+
return bound;
|
|
353
|
+
const { record } = bound;
|
|
354
|
+
let cached = readCachedToken(store, bound.context, record.name);
|
|
355
|
+
if (rejectedToken !== undefined && cached?.accessToken === rejectedToken) {
|
|
356
|
+
dropCachedToken(store, bound.context, record.name);
|
|
357
|
+
cached = null;
|
|
358
|
+
}
|
|
359
|
+
let token;
|
|
360
|
+
if (cached && cached.keyId === record.keyId && Date.parse(cached.accessExpiresAt) - Date.now() > TOKEN_MARGIN_MS) {
|
|
361
|
+
token = cached;
|
|
362
|
+
}
|
|
363
|
+
else {
|
|
364
|
+
const minted = await mint(record, bound.backend.authEndpoint);
|
|
365
|
+
if ('kind' in minted)
|
|
366
|
+
return minted;
|
|
367
|
+
writeCachedToken(store, bound.context, record.name, minted);
|
|
368
|
+
token = minted;
|
|
369
|
+
}
|
|
370
|
+
const person = loadSession(store, bound.context);
|
|
371
|
+
const email = person?.userId === record.ownerId && person.email ? person.email : undefined;
|
|
372
|
+
return {
|
|
373
|
+
kind: 'signed-in',
|
|
374
|
+
source: 'agent',
|
|
375
|
+
context: bound.context,
|
|
376
|
+
backend: bound.backend,
|
|
377
|
+
account: { userId: record.ownerId, ...(email ? { email } : {}), accessToken: token.accessToken, accessTokenExpiresAt: token.accessExpiresAt, key: { kind: 'none' } },
|
|
378
|
+
agent: { name: record.name, principalId: record.principalId, schemaChanges: record.schemaChanges, accessExpiresAt: token.accessExpiresAt, keyExpiresAt: record.keyExpiresAt }
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Change what an agent may do with the schema, on the backend and in its record:
|
|
383
|
+
*
|
|
384
|
+
* change the scope [undo: change it back] -> COMMIT: store the record
|
|
385
|
+
*/
|
|
386
|
+
async function setSchemaChanges(store, session, name, schemaChanges) {
|
|
387
|
+
const agentName = checkedName(name);
|
|
388
|
+
const owner = person(session);
|
|
389
|
+
const record = issuedRecord(store, owner, agentName);
|
|
390
|
+
const endpoint = owner.backend.authEndpoint;
|
|
391
|
+
const bearer = storedBearer(owner);
|
|
392
|
+
const op = agentOperation();
|
|
393
|
+
await op.step('change the scope', () => setScope(endpoint, bearer, record.principalId, schemaChanges), {
|
|
394
|
+
run: () => setScope(endpoint, bearer, record.principalId, record.schemaChanges),
|
|
395
|
+
undone: 'The scope was set back on the backend, so nothing changed.',
|
|
396
|
+
notUndone: (_value, reason) => `The backend kept the change, and setting it back failed too (${reason}), so the stored record does not show it. Run the same change again to store it.`
|
|
397
|
+
});
|
|
398
|
+
return op.commit('store the record', () => {
|
|
399
|
+
const current = issuedRecord(store, owner, agentName);
|
|
400
|
+
if (current.principalId !== record.principalId)
|
|
401
|
+
throw new AgentError('conflict', 'The stored agent changed. Retry the scope change.');
|
|
402
|
+
const updated = { ...current, schemaChanges };
|
|
403
|
+
const info = infoOf(store, updated);
|
|
404
|
+
writeAgent(store, updated);
|
|
405
|
+
return info;
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
/** Let an agent change the schema: the scope's mask is removed. */
|
|
409
|
+
export const grantSchemaChanges = ({ store, session, name }) => setSchemaChanges(store, session, name, true);
|
|
410
|
+
/** Stop an agent changing the schema: `manage_database` is masked out again. */
|
|
411
|
+
export const revokeSchemaChanges = ({ store, session, name }) => setSchemaChanges(store, session, name, false);
|
|
412
|
+
/**
|
|
413
|
+
* Give an agent a new 30-day key for the same principal, so it keeps its
|
|
414
|
+
* grants: with a new password sign-in of the person (ended when done), the new
|
|
415
|
+
* key is stored first, the cached token dropped, then the old key revoked,
|
|
416
|
+
* which ends every token minted with it. A failure before the new key is
|
|
417
|
+
* stored keeps the old key and the record as they were.
|
|
418
|
+
*/
|
|
419
|
+
export async function renewAgentKey({ store, session, name, ...proof }) {
|
|
420
|
+
const agentName = checkedName(name);
|
|
421
|
+
const owner = person(session);
|
|
422
|
+
const record = issuedRecord(store, owner, agentName);
|
|
423
|
+
const endpoint = owner.backend.authEndpoint;
|
|
424
|
+
return withFreshSignIn(owner, proof, async (bearer) => {
|
|
425
|
+
// create the new key [undo: revoke it] -> COMMIT: store it -> drop the cached token -> revoke the old key
|
|
426
|
+
const op = agentOperation();
|
|
427
|
+
const key = await op.step('create the new key', () => createKey(endpoint, bearer, record.principalId, agentName), {
|
|
428
|
+
run: (made) => revokeAgentKey(endpoint, bearer, made.keyId, 'Revoking the new key that could not be stored'),
|
|
429
|
+
undone: 'The new key was revoked again; the old key still works.',
|
|
430
|
+
notUndone: (made, reason) => `The new key ${made.keyId} could not be revoked (${reason}); revoke it in the app. The old key still works.`
|
|
431
|
+
});
|
|
432
|
+
const renewed = { ...record, ...key };
|
|
433
|
+
const agent = await op.commit('store the new key', () => {
|
|
434
|
+
const current = issuedRecord(store, owner, agentName);
|
|
435
|
+
if (current.principalId !== record.principalId || current.keyId !== record.keyId) {
|
|
436
|
+
throw new AgentError('conflict', 'The stored agent or its key changed. Retry the renewal.');
|
|
437
|
+
}
|
|
438
|
+
const updated = { ...renewed, schemaChanges: current.schemaChanges };
|
|
439
|
+
const info = infoOf(store, updated);
|
|
440
|
+
writeAgent(store, updated);
|
|
441
|
+
return info;
|
|
442
|
+
});
|
|
443
|
+
dropCachedToken(store, owner.context, agentName);
|
|
444
|
+
const previousKey = await revokeKey(record.keyId, (keyId) => revokeAgentKey(endpoint, bearer, keyId, 'Revoking the old key of the agent'));
|
|
445
|
+
return { agent, previousKey };
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
export async function removeAgent({ store, session, name }) {
|
|
449
|
+
const agentName = checkedName(name);
|
|
450
|
+
const owner = person(session);
|
|
451
|
+
let record;
|
|
452
|
+
try {
|
|
453
|
+
record = ownedRecord(store, owner.context, agentName);
|
|
454
|
+
}
|
|
455
|
+
catch (err) {
|
|
456
|
+
if (!(err instanceof AgentError && err.kind === 'unreadable-record'))
|
|
457
|
+
throw err;
|
|
458
|
+
deleteAgent(store, owner.context, agentName);
|
|
459
|
+
return {
|
|
460
|
+
kind: 'entry-removed',
|
|
461
|
+
name: agentName,
|
|
462
|
+
problem: `The stored record of the agent "${agentName}" could not be read, so its principal is unknown and was not deleted. Delete the principal "${agentName}" in the app; its credential works until then.`
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
// Only the backend that issued the key can delete its principal, and this session belongs to another one: asking it
|
|
466
|
+
// would only hear that the principal is not there.
|
|
467
|
+
if (differingPlanes(record.issuedFor, owner.backend).length > 0) {
|
|
468
|
+
deleteAgent(store, owner.context, agentName);
|
|
469
|
+
return {
|
|
470
|
+
kind: 'entry-removed',
|
|
471
|
+
name: agentName,
|
|
472
|
+
problem: `The agent "${agentName}" was set up with the backend ${record.issuedFor.apiEndpoint}, not the one this context names now, so only its entry here was removed. Its key works on that backend until ${record.keyExpiresAt}: delete the principal "${agentName}" in the app of that backend to end it now.`
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
// COMMIT: delete the principal (no undo: it ends the key and every token) -> remove the entry
|
|
476
|
+
const op = agentOperation();
|
|
477
|
+
const kind = await op.commit('delete the principal', async () => {
|
|
478
|
+
try {
|
|
479
|
+
const data = await deletePrincipal(owner.backend.authEndpoint, storedBearer(owner), record.principalId, 'Removing the agent');
|
|
480
|
+
const payload = data?.deletePrincipal;
|
|
481
|
+
if (!payload)
|
|
482
|
+
return 'already-gone';
|
|
483
|
+
if (payload.result !== true)
|
|
484
|
+
throw new AgentError('server-error', 'Removing the agent failed: the server did not confirm that its principal was deleted.');
|
|
485
|
+
return 'removed';
|
|
486
|
+
}
|
|
487
|
+
catch (err) {
|
|
488
|
+
if (err instanceof AgentError && err.kind === 'not-found')
|
|
489
|
+
return 'already-gone';
|
|
490
|
+
if (err instanceof AgentError)
|
|
491
|
+
throw new AgentError(err.kind, `${err.message} The agent is still stored, and its credential still works.`, err.code);
|
|
492
|
+
throw err;
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
return op.settle('remove the entry', () => {
|
|
496
|
+
deleteAgent(store, owner.context, agentName);
|
|
497
|
+
return { kind, name: agentName };
|
|
498
|
+
}, (cause) => ({
|
|
499
|
+
kind: 'entry-left',
|
|
500
|
+
name: agentName,
|
|
501
|
+
problem: `The principal of the agent "${agentName}" was deleted, which ended its key and its tokens, but its entry here could not be removed (${errorText(cause)}). Remove the agent again to remove the entry.`
|
|
502
|
+
}));
|
|
503
|
+
}
|
package/esm/api-key.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export declare const API_KEY_NAME = "agentic-cli";
|
|
2
|
+
export declare const API_KEY_ACCESS_LEVEL = "full_access";
|
|
3
|
+
export declare const API_KEY_MFA_LEVEL = "none";
|
|
4
|
+
export declare const API_KEY_DAYS = 30;
|
|
5
|
+
/**
|
|
6
|
+
* Ask the person to sign in again once their key is within a week of its end.
|
|
7
|
+
* A new key needs a fresh password sign-in, which mints one, so nothing renews
|
|
8
|
+
* a key on its own.
|
|
9
|
+
*/
|
|
10
|
+
export declare const SIGN_IN_AGAIN_WITHIN_MS: number;
|
|
11
|
+
export interface MintedApiKey {
|
|
12
|
+
apiKey: string;
|
|
13
|
+
keyId: string;
|
|
14
|
+
apiKeyExpiresAt?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface CreateApiKeyInputShape {
|
|
17
|
+
keyName: string;
|
|
18
|
+
accessLevel: string;
|
|
19
|
+
mfaLevel: string;
|
|
20
|
+
expiresIn: {
|
|
21
|
+
days: number;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export declare function buildCreateApiKeyInput({ days }: {
|
|
25
|
+
days: number;
|
|
26
|
+
}): CreateApiKeyInputShape;
|
|
27
|
+
interface RawApiKeyRecord {
|
|
28
|
+
apiKey?: string | null;
|
|
29
|
+
keyId?: string | null;
|
|
30
|
+
expiresAt?: string | null;
|
|
31
|
+
}
|
|
32
|
+
export declare function parseMintedKey(record: RawApiKeyRecord | null | undefined): MintedApiKey;
|
|
33
|
+
/** Whether a key that ends at `expiresAt` has ended or ends within `withinMs`, so the person should sign in again. */
|
|
34
|
+
export declare function keyEndsSoon({ expiresAt, now, withinMs }: {
|
|
35
|
+
expiresAt: string | undefined;
|
|
36
|
+
now?: number;
|
|
37
|
+
withinMs?: number;
|
|
38
|
+
}): boolean;
|
|
39
|
+
/** What happened to the key a new one replaces. */
|
|
40
|
+
export type KeyRevocation = {
|
|
41
|
+
kind: 'absent';
|
|
42
|
+
} | {
|
|
43
|
+
kind: 'revoked';
|
|
44
|
+
keyId: string;
|
|
45
|
+
} | {
|
|
46
|
+
kind: 'failed';
|
|
47
|
+
keyId: string;
|
|
48
|
+
reason: string;
|
|
49
|
+
};
|
|
50
|
+
export declare function errorText(err: unknown): string;
|
|
51
|
+
/** Revoke `keyId`; never throws. */
|
|
52
|
+
export declare function revokeKey(keyId: string | undefined, revoke: (keyId: string) => Promise<void>): Promise<KeyRevocation>;
|
|
53
|
+
export {};
|
package/esm/api-key.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export const API_KEY_NAME = 'agentic-cli';
|
|
2
|
+
export const API_KEY_ACCESS_LEVEL = 'full_access';
|
|
3
|
+
export const API_KEY_MFA_LEVEL = 'none';
|
|
4
|
+
export const API_KEY_DAYS = 30;
|
|
5
|
+
/**
|
|
6
|
+
* Ask the person to sign in again once their key is within a week of its end.
|
|
7
|
+
* A new key needs a fresh password sign-in, which mints one, so nothing renews
|
|
8
|
+
* a key on its own.
|
|
9
|
+
*/
|
|
10
|
+
export const SIGN_IN_AGAIN_WITHIN_MS = 1000 * 60 * 60 * 24 * 7;
|
|
11
|
+
export function buildCreateApiKeyInput({ days }) {
|
|
12
|
+
return {
|
|
13
|
+
keyName: API_KEY_NAME,
|
|
14
|
+
accessLevel: API_KEY_ACCESS_LEVEL,
|
|
15
|
+
mfaLevel: API_KEY_MFA_LEVEL,
|
|
16
|
+
expiresIn: { days }
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function parseMintedKey(record) {
|
|
20
|
+
if (!record?.apiKey || !record.keyId) {
|
|
21
|
+
throw new Error('createApiKey returned no API key.');
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
apiKey: record.apiKey,
|
|
25
|
+
keyId: record.keyId,
|
|
26
|
+
...(record.expiresAt ? { apiKeyExpiresAt: record.expiresAt } : {})
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** Whether a key that ends at `expiresAt` has ended or ends within `withinMs`, so the person should sign in again. */
|
|
30
|
+
export function keyEndsSoon({ expiresAt, now = Date.now(), withinMs = SIGN_IN_AGAIN_WITHIN_MS }) {
|
|
31
|
+
if (!expiresAt)
|
|
32
|
+
return false;
|
|
33
|
+
const expires = Date.parse(expiresAt);
|
|
34
|
+
if (Number.isNaN(expires))
|
|
35
|
+
return false;
|
|
36
|
+
return expires - now <= withinMs;
|
|
37
|
+
}
|
|
38
|
+
export function errorText(err) {
|
|
39
|
+
return err instanceof Error ? err.message : String(err);
|
|
40
|
+
}
|
|
41
|
+
/** Revoke `keyId`; never throws. */
|
|
42
|
+
export async function revokeKey(keyId, revoke) {
|
|
43
|
+
if (!keyId)
|
|
44
|
+
return { kind: 'absent' };
|
|
45
|
+
try {
|
|
46
|
+
await revoke(keyId);
|
|
47
|
+
return { kind: 'revoked', keyId };
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
return { kind: 'failed', keyId, reason: errorText(err) };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ConfigStore } from 'appstash';
|
|
2
|
+
import { type SignInProof } from './auth';
|
|
3
|
+
import { type BackendConfig, type Endpoint } from './backend-store';
|
|
4
|
+
/**
|
|
5
|
+
* A sign-in to an app's own auth plane, as one of the app's users: the record tools act as that user, under the app's
|
|
6
|
+
* own row rules, never as the person's account. One per database of a context, in the store's cache with mode 0600,
|
|
7
|
+
* since its token is short-lived and a new sign-in replaces it.
|
|
8
|
+
*/
|
|
9
|
+
export type AppSession = {
|
|
10
|
+
databaseId: string;
|
|
11
|
+
databaseName: string;
|
|
12
|
+
userId: string;
|
|
13
|
+
email: string;
|
|
14
|
+
accessToken: string;
|
|
15
|
+
accessTokenExpiresAt?: string;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* The auth plane of the database `databaseName` on `backend`: the backend's own auth host with its first label made
|
|
19
|
+
* `auth-<name>`, as the backend serves each database's planes. It passes the same endpoint check as a context's.
|
|
20
|
+
*/
|
|
21
|
+
export declare function appAuthEndpoint(backend: BackendConfig, databaseName: string): Endpoint;
|
|
22
|
+
/** The app sign-in of `databaseId` stored under `context`, or null when there is none that can be read. */
|
|
23
|
+
export declare function loadAppSession(store: ConfigStore, context: string, databaseId: string): AppSession | null;
|
|
24
|
+
/**
|
|
25
|
+
* Sign in to the app of `database` as one of its users, with the app's own email and password (or the code of the
|
|
26
|
+
* challenge the password started), and store the sign-in under `context`, replacing the one there. A failed sign-in
|
|
27
|
+
* stores nothing and throws a `SignInError`; `SecondFactorRequired` when the password needs a code.
|
|
28
|
+
*/
|
|
29
|
+
export declare function appSignIn({ store, context, backend, database, email, ...proof }: {
|
|
30
|
+
store: ConfigStore;
|
|
31
|
+
context: string;
|
|
32
|
+
backend: BackendConfig;
|
|
33
|
+
database: {
|
|
34
|
+
id: string;
|
|
35
|
+
name: string;
|
|
36
|
+
};
|
|
37
|
+
email: string;
|
|
38
|
+
} & SignInProof): Promise<AppSession>;
|
|
39
|
+
/**
|
|
40
|
+
* End the app sign-in of `databaseId` stored under `context` and remove it. The app's server ends its session when it
|
|
41
|
+
* answers; the stored sign-in goes either way. False when there was none.
|
|
42
|
+
*/
|
|
43
|
+
export declare function appSignOut({ store, context, backend, databaseId }: {
|
|
44
|
+
store: ConfigStore;
|
|
45
|
+
context: string;
|
|
46
|
+
backend: BackendConfig;
|
|
47
|
+
databaseId: string;
|
|
48
|
+
}): Promise<boolean>;
|