@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/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentic-kit/session",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"author": "Constructive <developers@constructive.io>",
|
|
5
|
+
"description": "the shared Constructive sign-in: backend contexts, email and password sign-in, the stored session, agent credentials and the CONSTRUCTIVE_* environment overrides, for every binary",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"module": "esm/index.js",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"homepage": "https://github.com/constructive-io/constructive",
|
|
10
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public",
|
|
13
|
+
"directory": "dist"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/constructive-io/constructive"
|
|
18
|
+
},
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/constructive-io/constructive/issues"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@constructive-io/fetch": "^1.2.0",
|
|
24
|
+
"appstash": "^0.9.0",
|
|
25
|
+
"@constructive-io/errors": "^0.27.2",
|
|
26
|
+
"@agentic-kit/db-tools": "^0.16.1",
|
|
27
|
+
"@constructive-io/sdk": "^1.22.4"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"agentic-kit",
|
|
31
|
+
"constructive",
|
|
32
|
+
"auth",
|
|
33
|
+
"session"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"clean": "makage clean",
|
|
37
|
+
"build": "makage build",
|
|
38
|
+
"build:dev": "makage build --dev",
|
|
39
|
+
"lint": "eslint . --fix",
|
|
40
|
+
"test": "jest",
|
|
41
|
+
"test:watch": "jest --watch"
|
|
42
|
+
}
|
|
6
43
|
}
|
package/session.d.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import type { HostAccount, HostBackendConfig } from '@agentic-kit/db-tools';
|
|
2
|
+
import { ConfigStore } from 'appstash';
|
|
3
|
+
import { type AgentRecord } from './agent-store';
|
|
4
|
+
import { BackendConfig, BackendEndpoints, Plane } from './backend-store';
|
|
5
|
+
import { type ConstructiveEnv } from './env';
|
|
6
|
+
export type SessionSource = 'env' | 'store';
|
|
7
|
+
export type SessionKey = {
|
|
8
|
+
kind: 'none';
|
|
9
|
+
} | {
|
|
10
|
+
kind: 'active';
|
|
11
|
+
apiKey: string;
|
|
12
|
+
keyId?: string;
|
|
13
|
+
expiresAt?: string;
|
|
14
|
+
};
|
|
15
|
+
export interface SessionAccount {
|
|
16
|
+
userId: string;
|
|
17
|
+
/** Known for a stored session only. */
|
|
18
|
+
email?: string;
|
|
19
|
+
accessToken: string;
|
|
20
|
+
accessTokenExpiresAt?: string;
|
|
21
|
+
key: SessionKey;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The one answer to "who talks to which backend". A credential is only ever
|
|
25
|
+
* paired with the backend of its own source: a stored session with the
|
|
26
|
+
* endpoints of the context it is filed under, an environment credential with
|
|
27
|
+
* the endpoints the environment names.
|
|
28
|
+
*/
|
|
29
|
+
/** The states every resolution can answer: no backend, a stored one that cannot be used, or a wrong environment. */
|
|
30
|
+
type CommonState =
|
|
31
|
+
/** No context is chosen (`context: null`), or the named one does not exist. */
|
|
32
|
+
{
|
|
33
|
+
kind: 'no-backend';
|
|
34
|
+
context: string | null;
|
|
35
|
+
}
|
|
36
|
+
/** A stored context lacks planes, for example one another app wrote. */
|
|
37
|
+
| {
|
|
38
|
+
kind: 'incomplete-backend';
|
|
39
|
+
context: string;
|
|
40
|
+
missing: Plane[];
|
|
41
|
+
apiEndpoint?: string;
|
|
42
|
+
}
|
|
43
|
+
/** A stored context holds an endpoint that fails the endpoint check (`plane`); `problem` says why. Nothing is sent to it. */
|
|
44
|
+
| {
|
|
45
|
+
kind: 'invalid-backend';
|
|
46
|
+
context: string;
|
|
47
|
+
plane: Plane;
|
|
48
|
+
problem: string;
|
|
49
|
+
}
|
|
50
|
+
/** An environment variable is missing, empty or wrong; `fix` says what to set. */
|
|
51
|
+
| {
|
|
52
|
+
kind: 'invalid-override';
|
|
53
|
+
variable: string;
|
|
54
|
+
problem: string;
|
|
55
|
+
fix: string;
|
|
56
|
+
}
|
|
57
|
+
/** A context or an agent was named, but the environment variable `variable` decides the session; one of the two must go. */
|
|
58
|
+
| {
|
|
59
|
+
kind: 'conflict';
|
|
60
|
+
context: string;
|
|
61
|
+
variable: string;
|
|
62
|
+
problem: string;
|
|
63
|
+
fix: string;
|
|
64
|
+
};
|
|
65
|
+
/** A person's session: what `resolveSession` answers without `agent`. */
|
|
66
|
+
export type PersonSession = CommonState
|
|
67
|
+
/**
|
|
68
|
+
* A session is stored under the context, but it was issued for another
|
|
69
|
+
* backend: `differs` names the planes whose endpoints are not the ones it
|
|
70
|
+
* was issued for (`issuedFor`), or the session does not record the backend
|
|
71
|
+
* it was issued for (`issuedFor: null`, `differs: []`). It is never used or
|
|
72
|
+
* sent; a new sign-in replaces it.
|
|
73
|
+
*/
|
|
74
|
+
| {
|
|
75
|
+
kind: 'issuer-mismatch';
|
|
76
|
+
source: 'store';
|
|
77
|
+
context: string;
|
|
78
|
+
backend: BackendConfig;
|
|
79
|
+
issuedFor: BackendEndpoints | null;
|
|
80
|
+
differs: Plane[];
|
|
81
|
+
} | {
|
|
82
|
+
kind: 'signed-out';
|
|
83
|
+
source: SessionSource;
|
|
84
|
+
context: string | null;
|
|
85
|
+
backend: BackendConfig;
|
|
86
|
+
} | {
|
|
87
|
+
kind: 'signed-in';
|
|
88
|
+
source: SessionSource;
|
|
89
|
+
context: string | null;
|
|
90
|
+
backend: BackendConfig;
|
|
91
|
+
account: SessionAccount;
|
|
92
|
+
};
|
|
93
|
+
/** The named agent cannot act; `fix` says how to recover. */
|
|
94
|
+
type AgentUnusable = {
|
|
95
|
+
kind: 'agent-unusable';
|
|
96
|
+
context: string | null;
|
|
97
|
+
agent: string;
|
|
98
|
+
reason: AgentUnusableReason;
|
|
99
|
+
problem: string;
|
|
100
|
+
fix: string;
|
|
101
|
+
};
|
|
102
|
+
/** An agent's session that can be used or says why not: what `agentSession` answers. */
|
|
103
|
+
export type ResolvedAgentSession = CommonState
|
|
104
|
+
/**
|
|
105
|
+
* An agent of the person acts: an access token minted with the agent's key,
|
|
106
|
+
* filed under the person's context and bound to the endpoints it was issued
|
|
107
|
+
* for. `account.userId` is the person's id, which the backend requires.
|
|
108
|
+
*/
|
|
109
|
+
| {
|
|
110
|
+
kind: 'signed-in';
|
|
111
|
+
source: 'agent';
|
|
112
|
+
context: string;
|
|
113
|
+
backend: BackendConfig;
|
|
114
|
+
account: SessionAccount;
|
|
115
|
+
agent: AgentIdentity;
|
|
116
|
+
} | AgentUnusable;
|
|
117
|
+
/** Any resolution, for a caller that handles both (`sessionProblem`, the tools host). */
|
|
118
|
+
export type Session = PersonSession | ResolvedAgentSession;
|
|
119
|
+
export interface AgentIdentity {
|
|
120
|
+
name: string;
|
|
121
|
+
principalId: string;
|
|
122
|
+
schemaChanges: boolean;
|
|
123
|
+
/** When the access token in this session ends. */
|
|
124
|
+
accessExpiresAt: string;
|
|
125
|
+
/** When the agent's key ends; after that the agent must be set up again. */
|
|
126
|
+
keyExpiresAt: string;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* `set-up-again`: the agent's key has ended or the backend refused it; the
|
|
130
|
+
* person renews the key. `unreadable`: its record cannot be read, so only
|
|
131
|
+
* removing the agent and adding it again helps.
|
|
132
|
+
* `mint-failed`: no token could be minted (no answer, or a server error); the
|
|
133
|
+
* key is unchanged, so a retry is safe.
|
|
134
|
+
*/
|
|
135
|
+
export type AgentUnusableReason = 'not-found' | 'issuer-mismatch' | 'set-up-again' | 'unreadable' | 'mint-failed';
|
|
136
|
+
/** Every environment variable `resolveSession` reads, besides `CONSTRUCTIVE_STASH_DIR`. */
|
|
137
|
+
export declare const OVERRIDE_ENV_VARS: readonly string[];
|
|
138
|
+
interface ResolveOptions {
|
|
139
|
+
context?: string;
|
|
140
|
+
/** The environment to read the CONSTRUCTIVE_* variables from. Default: the process's (getConstructiveEnv). */
|
|
141
|
+
env?: ConstructiveEnv;
|
|
142
|
+
store?: ConfigStore;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* The person's session, resolved once from the environment and the store together.
|
|
146
|
+
*
|
|
147
|
+
* - Any credential variable selects the environment as the credential source;
|
|
148
|
+
* it needs CONSTRUCTIVE_USER_ID, CONSTRUCTIVE_ACCESS_TOKEN and the backend
|
|
149
|
+
* from CONSTRUCTIVE_API_ENDPOINT.
|
|
150
|
+
* - An endpoint override alone gives that backend `signed-out`, unless it names
|
|
151
|
+
* exactly the backend of the stored context, whose session then applies.
|
|
152
|
+
* - Otherwise the stored context `context` (default: the active one) and the
|
|
153
|
+
* session filed under it, used only when the context's auth endpoint issued it.
|
|
154
|
+
* - A `context` named while the environment decides the session is `conflict`.
|
|
155
|
+
*
|
|
156
|
+
* Returns `invalid-override` or `conflict` rather than throwing for a wrong
|
|
157
|
+
* environment. Throws `ContextNameError` for a `context` that is not a valid name.
|
|
158
|
+
*/
|
|
159
|
+
export declare function resolveSession({ context, env, store }?: ResolveOptions): PersonSession;
|
|
160
|
+
export declare const agentFix: (agent: string) => string;
|
|
161
|
+
/** The fix for an agent whose key has ended or was refused: a new key keeps its principal and grants. */
|
|
162
|
+
export declare const renewFix: (agent: string) => string;
|
|
163
|
+
/** An agent whose record and key can be used, bound to the context's backend; it carries no access token yet. */
|
|
164
|
+
export type AgentBinding = Exclude<ResolvedAgentSession, {
|
|
165
|
+
kind: 'signed-in';
|
|
166
|
+
}> | {
|
|
167
|
+
kind: 'bound';
|
|
168
|
+
context: string;
|
|
169
|
+
backend: BackendConfig;
|
|
170
|
+
record: AgentRecord;
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* The stored agent `agent` under the context `context` (default: the active
|
|
174
|
+
* one), checked against the context's endpoints and its key's end, with no
|
|
175
|
+
* request. With any CONSTRUCTIVE_* credential or endpoint variable set, it is
|
|
176
|
+
* `conflict`: the environment would decide the session, not the agent.
|
|
177
|
+
*/
|
|
178
|
+
export declare function agentBinding({ agent, context: named, env, store }: ResolveOptions & {
|
|
179
|
+
agent: string;
|
|
180
|
+
}): AgentBinding;
|
|
181
|
+
/** The tools' account for a signed-in session: an agent's names the agent, so a plan says who makes the change. */
|
|
182
|
+
export declare function hostAccount(session: Extract<Session, {
|
|
183
|
+
kind: 'signed-in';
|
|
184
|
+
}>): HostAccount;
|
|
185
|
+
export declare function hostBackendConfig(backend: BackendConfig): HostBackendConfig;
|
|
186
|
+
/**
|
|
187
|
+
* Why a session cannot be used, in one or two sentences with the fix, or null
|
|
188
|
+
* for a session that is only absent or signed out. `repairHint` names the
|
|
189
|
+
* command of the binary that stores a complete context. No secret is in it.
|
|
190
|
+
*/
|
|
191
|
+
export declare function sessionProblem(session: Session, repairHint?: string): string | null;
|
|
192
|
+
export {};
|
package/session.js
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.renewFix = exports.agentFix = exports.OVERRIDE_ENV_VARS = void 0;
|
|
4
|
+
exports.resolveSession = resolveSession;
|
|
5
|
+
exports.agentBinding = agentBinding;
|
|
6
|
+
exports.hostAccount = hostAccount;
|
|
7
|
+
exports.hostBackendConfig = hostBackendConfig;
|
|
8
|
+
exports.sessionProblem = sessionProblem;
|
|
9
|
+
const account_store_1 = require("./account-store");
|
|
10
|
+
const agent_store_1 = require("./agent-store");
|
|
11
|
+
const backend_store_1 = require("./backend-store");
|
|
12
|
+
const env_1 = require("./env");
|
|
13
|
+
const CREDENTIAL_VARS = ['CONSTRUCTIVE_USER_ID', 'CONSTRUCTIVE_ACCESS_TOKEN', 'CONSTRUCTIVE_API_KEY'];
|
|
14
|
+
const REQUIRED_CREDENTIAL_VARS = ['CONSTRUCTIVE_USER_ID', 'CONSTRUCTIVE_ACCESS_TOKEN'];
|
|
15
|
+
const endpointVar = (plane) => `CONSTRUCTIVE_${plane.toUpperCase()}_ENDPOINT`;
|
|
16
|
+
const ENDPOINT_VARS = backend_store_1.PLANES.map(endpointVar);
|
|
17
|
+
/** Every environment variable `resolveSession` reads, besides `CONSTRUCTIVE_STASH_DIR`. */
|
|
18
|
+
exports.OVERRIDE_ENV_VARS = [...CREDENTIAL_VARS, ...ENDPOINT_VARS];
|
|
19
|
+
const isSet = (env, name) => env[name] !== undefined;
|
|
20
|
+
function envBackend(env) {
|
|
21
|
+
const empty = ENDPOINT_VARS.find((name) => env[name] === '');
|
|
22
|
+
if (empty)
|
|
23
|
+
return { kind: 'invalid-override', variable: empty, problem: `${empty} is set but empty.`, fix: `Set ${empty} to an https URL, or unset it.` };
|
|
24
|
+
const api = env.CONSTRUCTIVE_API_ENDPOINT;
|
|
25
|
+
if (api === undefined) {
|
|
26
|
+
const stray = ENDPOINT_VARS.find((name) => isSet(env, name));
|
|
27
|
+
if (!stray)
|
|
28
|
+
return { kind: 'none' };
|
|
29
|
+
return {
|
|
30
|
+
kind: 'invalid-override',
|
|
31
|
+
variable: 'CONSTRUCTIVE_API_ENDPOINT',
|
|
32
|
+
problem: `${stray} is set, but CONSTRUCTIVE_API_ENDPOINT is not, so the environment names no backend.`,
|
|
33
|
+
fix: `Set CONSTRUCTIVE_API_ENDPOINT to the api endpoint of the backend ${stray} belongs to, or unset ${stray}.`
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const given = Object.fromEntries(backend_store_1.PLANES.filter((plane) => plane !== 'api' && isSet(env, endpointVar(plane))).map((plane) => [plane, env[endpointVar(plane)]]));
|
|
37
|
+
try {
|
|
38
|
+
return { kind: 'backend', backend: (0, backend_store_1.backendFromEndpoints)({ api, ...given }) };
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
if (!(err instanceof backend_store_1.EndpointError))
|
|
42
|
+
throw err;
|
|
43
|
+
const variable = err.reason === 'not-derivable' ? 'CONSTRUCTIVE_API_ENDPOINT' : endpointVar(err.plane);
|
|
44
|
+
return { kind: 'invalid-override', variable, problem: err.message, fix: ENDPOINT_FIX[err.reason](endpointVar(err.plane), env) };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** What to set for each reason an endpoint variable is refused. */
|
|
48
|
+
const ENDPOINT_FIX = {
|
|
49
|
+
'not-a-url': (variable) => `Set ${variable} to an absolute https URL, or unset it.`,
|
|
50
|
+
scheme: (variable) => `Set ${variable} to an https URL, or unset it.`,
|
|
51
|
+
insecure: (variable) => `Set ${variable} to its https URL, or unset it; plain http is accepted only for this machine.`,
|
|
52
|
+
userinfo: (variable) => `Set ${variable} to the URL with no user name or password in it, or unset it.`,
|
|
53
|
+
'not-derivable': (_variable, env) => `Set every plane explicitly: ${ENDPOINT_VARS.filter((name) => !isSet(env, name)).join(', ')}.`
|
|
54
|
+
};
|
|
55
|
+
function envAccount(env) {
|
|
56
|
+
const set = CREDENTIAL_VARS.filter((name) => isSet(env, name));
|
|
57
|
+
if (set.length === 0)
|
|
58
|
+
return { kind: 'none' };
|
|
59
|
+
const missing = REQUIRED_CREDENTIAL_VARS.find((name) => !env[name]);
|
|
60
|
+
if (missing || env.CONSTRUCTIVE_API_KEY === '') {
|
|
61
|
+
const variable = missing ?? 'CONSTRUCTIVE_API_KEY';
|
|
62
|
+
return {
|
|
63
|
+
kind: 'invalid-override',
|
|
64
|
+
variable,
|
|
65
|
+
problem: `${set.join(' and ')} ${set.length > 1 ? 'are' : 'is'} set, so the credential comes from the environment, but ${variable} is ${isSet(env, variable) ? 'empty' : 'not set'}.`,
|
|
66
|
+
fix: `Set CONSTRUCTIVE_USER_ID and CONSTRUCTIVE_ACCESS_TOKEN (and optionally CONSTRUCTIVE_API_KEY), or unset all three to use the stored session.`
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
const apiKey = env.CONSTRUCTIVE_API_KEY;
|
|
70
|
+
return {
|
|
71
|
+
kind: 'account',
|
|
72
|
+
account: {
|
|
73
|
+
userId: env.CONSTRUCTIVE_USER_ID,
|
|
74
|
+
accessToken: env.CONSTRUCTIVE_ACCESS_TOKEN,
|
|
75
|
+
key: apiKey ? { kind: 'active', apiKey } : { kind: 'none' }
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
const sameBackend = (a, b) => (0, backend_store_1.differingPlanes)(a, b).length === 0;
|
|
80
|
+
/** The stored side: the context `named` (default: the active one), with the session filed under it. */
|
|
81
|
+
function storedSession(store, named) {
|
|
82
|
+
const context = named ?? (0, account_store_1.currentContextName)(store);
|
|
83
|
+
const stored = context ? (0, backend_store_1.readBackend)(store, context) : null;
|
|
84
|
+
if (!stored)
|
|
85
|
+
return { kind: 'no-backend', context: context ?? null };
|
|
86
|
+
if (stored.status === 'incomplete') {
|
|
87
|
+
return { kind: 'incomplete-backend', context, missing: stored.missing, ...(stored.apiEndpoint ? { apiEndpoint: stored.apiEndpoint } : {}) };
|
|
88
|
+
}
|
|
89
|
+
if (stored.status === 'invalid')
|
|
90
|
+
return { kind: 'invalid-backend', context, plane: stored.plane, problem: stored.problem };
|
|
91
|
+
const session = (0, account_store_1.loadSession)(store, context);
|
|
92
|
+
if (!session)
|
|
93
|
+
return { kind: 'signed-out', source: 'store', context, backend: stored.backend };
|
|
94
|
+
const differs = session.issuedFor ? (0, backend_store_1.differingPlanes)(session.issuedFor, stored.backend) : [];
|
|
95
|
+
if (!session.issuedFor || differs.length > 0) {
|
|
96
|
+
return { kind: 'issuer-mismatch', source: 'store', context, backend: stored.backend, issuedFor: session.issuedFor ?? null, differs };
|
|
97
|
+
}
|
|
98
|
+
const key = session.apiKey
|
|
99
|
+
? { kind: 'active', apiKey: session.apiKey, ...(session.keyId ? { keyId: session.keyId } : {}), ...(session.apiKeyExpiresAt ? { expiresAt: session.apiKeyExpiresAt } : {}) }
|
|
100
|
+
: { kind: 'none' };
|
|
101
|
+
return {
|
|
102
|
+
kind: 'signed-in',
|
|
103
|
+
source: 'store',
|
|
104
|
+
context,
|
|
105
|
+
backend: stored.backend,
|
|
106
|
+
account: {
|
|
107
|
+
userId: session.userId,
|
|
108
|
+
...(session.email ? { email: session.email } : {}),
|
|
109
|
+
accessToken: session.accessToken,
|
|
110
|
+
...(session.accessTokenExpiresAt ? { accessTokenExpiresAt: session.accessTokenExpiresAt } : {}),
|
|
111
|
+
key
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/** The store to read and the environment's backend and credential, or the environment variable that is wrong. */
|
|
116
|
+
function prepare({ context, env, store }) {
|
|
117
|
+
if (context !== undefined)
|
|
118
|
+
(0, account_store_1.checkContextName)(context);
|
|
119
|
+
let opened = store;
|
|
120
|
+
if (!opened) {
|
|
121
|
+
try {
|
|
122
|
+
opened = (0, account_store_1.openStore)((0, account_store_1.stashBaseDir)(env));
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
if (env[env_1.STASH_DIR_ENV] !== '')
|
|
126
|
+
throw err;
|
|
127
|
+
return { kind: 'invalid-override', variable: env_1.STASH_DIR_ENV, problem: err.message, fix: `Set ${env_1.STASH_DIR_ENV} to a directory, or unset it.` };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const backend = envBackend(env);
|
|
131
|
+
if (backend.kind === 'invalid-override')
|
|
132
|
+
return backend;
|
|
133
|
+
const account = envAccount(env);
|
|
134
|
+
if (account.kind === 'invalid-override')
|
|
135
|
+
return account;
|
|
136
|
+
return { store: opened, backend, account };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The person's session, resolved once from the environment and the store together.
|
|
140
|
+
*
|
|
141
|
+
* - Any credential variable selects the environment as the credential source;
|
|
142
|
+
* it needs CONSTRUCTIVE_USER_ID, CONSTRUCTIVE_ACCESS_TOKEN and the backend
|
|
143
|
+
* from CONSTRUCTIVE_API_ENDPOINT.
|
|
144
|
+
* - An endpoint override alone gives that backend `signed-out`, unless it names
|
|
145
|
+
* exactly the backend of the stored context, whose session then applies.
|
|
146
|
+
* - Otherwise the stored context `context` (default: the active one) and the
|
|
147
|
+
* session filed under it, used only when the context's auth endpoint issued it.
|
|
148
|
+
* - A `context` named while the environment decides the session is `conflict`.
|
|
149
|
+
*
|
|
150
|
+
* Returns `invalid-override` or `conflict` rather than throwing for a wrong
|
|
151
|
+
* environment. Throws `ContextNameError` for a `context` that is not a valid name.
|
|
152
|
+
*/
|
|
153
|
+
function resolveSession({ context, env = (0, env_1.getConstructiveEnv)(), store } = {}) {
|
|
154
|
+
const prepared = prepare({ context, env, store });
|
|
155
|
+
if ('kind' in prepared)
|
|
156
|
+
return prepared;
|
|
157
|
+
const { store: opened, backend, account } = prepared;
|
|
158
|
+
if (account.kind === 'account') {
|
|
159
|
+
if (backend.kind === 'none') {
|
|
160
|
+
return {
|
|
161
|
+
kind: 'invalid-override',
|
|
162
|
+
variable: 'CONSTRUCTIVE_API_ENDPOINT',
|
|
163
|
+
problem: 'The credential comes from the environment, but CONSTRUCTIVE_API_ENDPOINT is not set, so it names no backend to send it to.',
|
|
164
|
+
fix: 'Set CONSTRUCTIVE_API_ENDPOINT to the api endpoint the credential belongs to.'
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
if (context !== undefined)
|
|
168
|
+
return conflict(context, CREDENTIAL_VARS.find((name) => isSet(env, name)), backend.backend, 'credential');
|
|
169
|
+
return { kind: 'signed-in', source: 'env', context: null, backend: backend.backend, account: account.account };
|
|
170
|
+
}
|
|
171
|
+
const stored = storedSession(opened, context);
|
|
172
|
+
if (backend.kind === 'none')
|
|
173
|
+
return stored;
|
|
174
|
+
const storedBackend = stored.kind === 'signed-in' || stored.kind === 'signed-out' || stored.kind === 'issuer-mismatch' ? stored.backend : null;
|
|
175
|
+
if (storedBackend && sameBackend(storedBackend, backend.backend))
|
|
176
|
+
return stored;
|
|
177
|
+
if (context !== undefined)
|
|
178
|
+
return conflict(context, 'CONSTRUCTIVE_API_ENDPOINT', backend.backend, 'backend');
|
|
179
|
+
return { kind: 'signed-out', source: 'env', context: null, backend: backend.backend };
|
|
180
|
+
}
|
|
181
|
+
function agentConflict(context, agent, variable) {
|
|
182
|
+
return {
|
|
183
|
+
kind: 'conflict',
|
|
184
|
+
context,
|
|
185
|
+
variable,
|
|
186
|
+
problem: `The agent "${agent}" was named, but ${variable} is set, so the environment would decide the session, not the agent.`,
|
|
187
|
+
fix: `Name no agent to use the environment, or unset ${variable} and the other CONSTRUCTIVE_* credential and endpoint variables to act as the agent.`
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const agentFix = (agent) => `Remove the agent "${agent}" and add it again, which needs the person signed in.`;
|
|
191
|
+
exports.agentFix = agentFix;
|
|
192
|
+
/** The fix for an agent whose key has ended or was refused: a new key keeps its principal and grants. */
|
|
193
|
+
const renewFix = (agent) => `Renew the key of the agent "${agent}", which needs the person's password; if the agent was removed in the app, add it again.`;
|
|
194
|
+
exports.renewFix = renewFix;
|
|
195
|
+
/**
|
|
196
|
+
* The stored agent `agent` under the context `context` (default: the active
|
|
197
|
+
* one), checked against the context's endpoints and its key's end, with no
|
|
198
|
+
* request. With any CONSTRUCTIVE_* credential or endpoint variable set, it is
|
|
199
|
+
* `conflict`: the environment would decide the session, not the agent.
|
|
200
|
+
*/
|
|
201
|
+
function agentBinding({ agent, context: named, env = (0, env_1.getConstructiveEnv)(), store }) {
|
|
202
|
+
(0, agent_store_1.checkAgentName)(agent);
|
|
203
|
+
const prepared = prepare({ context: named, env, store });
|
|
204
|
+
if ('kind' in prepared)
|
|
205
|
+
return prepared;
|
|
206
|
+
const opened = prepared.store;
|
|
207
|
+
const variable = exports.OVERRIDE_ENV_VARS.find((name) => isSet(env, name));
|
|
208
|
+
if (variable)
|
|
209
|
+
return agentConflict(named ?? (0, account_store_1.currentContextName)(opened) ?? '', agent, variable);
|
|
210
|
+
const context = named ?? (0, account_store_1.currentContextName)(opened);
|
|
211
|
+
const stored = context ? (0, backend_store_1.readBackend)(opened, context) : null;
|
|
212
|
+
if (!stored)
|
|
213
|
+
return { kind: 'no-backend', context: context ?? null };
|
|
214
|
+
if (stored.status === 'incomplete') {
|
|
215
|
+
return { kind: 'incomplete-backend', context, missing: stored.missing, ...(stored.apiEndpoint ? { apiEndpoint: stored.apiEndpoint } : {}) };
|
|
216
|
+
}
|
|
217
|
+
if (stored.status === 'invalid')
|
|
218
|
+
return { kind: 'invalid-backend', context, plane: stored.plane, problem: stored.problem };
|
|
219
|
+
const unusable = (reason, problem, fix = (0, exports.agentFix)(agent)) => ({ kind: 'agent-unusable', context, agent, reason, problem, fix });
|
|
220
|
+
let record;
|
|
221
|
+
try {
|
|
222
|
+
record = (0, agent_store_1.readAgent)(opened, context, agent);
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
if (err instanceof agent_store_1.AgentRecordUnreadable)
|
|
226
|
+
return unusable('unreadable', err.message.replace('of the agent', `of the agent "${agent}"`));
|
|
227
|
+
throw err;
|
|
228
|
+
}
|
|
229
|
+
if (!record) {
|
|
230
|
+
return unusable('not-found', `There is no agent named "${agent}" under the context "${context}".`, `Add the agent first, or name one that exists.`);
|
|
231
|
+
}
|
|
232
|
+
const differs = (0, backend_store_1.differingPlanes)(record.issuedFor, stored.backend);
|
|
233
|
+
if (differs.length > 0) {
|
|
234
|
+
const changes = differs.map((plane) => `the ${plane} endpoint is ${(0, backend_store_1.planeEndpoint)(stored.backend, plane)}, but the agent was set up for ${(0, backend_store_1.planeEndpoint)(record.issuedFor, plane)}`);
|
|
235
|
+
return unusable('issuer-mismatch', `The agent "${agent}" was set up for another backend: ${changes.join('; ')}. Its credential is not used or sent anywhere.`);
|
|
236
|
+
}
|
|
237
|
+
if (Date.parse(record.keyExpiresAt) <= Date.now()) {
|
|
238
|
+
return unusable('set-up-again', `The key of the agent "${agent}" ended at ${record.keyExpiresAt}.`, (0, exports.renewFix)(agent));
|
|
239
|
+
}
|
|
240
|
+
return { kind: 'bound', context, backend: stored.backend, record };
|
|
241
|
+
}
|
|
242
|
+
function conflict(context, variable, backend, what) {
|
|
243
|
+
const unset = what === 'credential' ? 'CONSTRUCTIVE_USER_ID, CONSTRUCTIVE_ACCESS_TOKEN and CONSTRUCTIVE_API_KEY' : 'CONSTRUCTIVE_API_ENDPOINT and the other CONSTRUCTIVE_*_ENDPOINT variables';
|
|
244
|
+
return {
|
|
245
|
+
kind: 'conflict',
|
|
246
|
+
context,
|
|
247
|
+
variable,
|
|
248
|
+
problem: `The context "${context}" was named, but ${variable} is set, so the environment decides the session: the ${what} for ${backend.apiEndpoint}, not the context.`,
|
|
249
|
+
fix: `Name no context to use the environment, or unset ${unset} to use the context.`
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
/** The tools' account for a signed-in session: an agent's names the agent, so a plan says who makes the change. */
|
|
253
|
+
function hostAccount(session) {
|
|
254
|
+
const { account } = session;
|
|
255
|
+
return {
|
|
256
|
+
userId: account.userId,
|
|
257
|
+
...(account.email ? { email: account.email } : {}),
|
|
258
|
+
...(session.source === 'agent' ? { agent: { name: session.agent.name, principalId: session.agent.principalId } } : {}),
|
|
259
|
+
accessToken: account.accessToken,
|
|
260
|
+
backend: hostBackendConfig(session.backend),
|
|
261
|
+
...(account.key.kind === 'active' ? { apiKey: account.key.apiKey } : {})
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
function hostBackendConfig(backend) {
|
|
265
|
+
return {
|
|
266
|
+
apiEndpoint: backend.apiEndpoint,
|
|
267
|
+
authEndpoint: backend.authEndpoint,
|
|
268
|
+
modulesEndpoint: backend.modulesEndpoint,
|
|
269
|
+
agentEndpoint: backend.agentEndpoint,
|
|
270
|
+
computeEndpoint: backend.computeEndpoint
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
const planeList = (missing) => `${missing.join(', ')} endpoint${missing.length > 1 ? 's' : ''}`;
|
|
274
|
+
/**
|
|
275
|
+
* Why a session cannot be used, in one or two sentences with the fix, or null
|
|
276
|
+
* for a session that is only absent or signed out. `repairHint` names the
|
|
277
|
+
* command of the binary that stores a complete context. No secret is in it.
|
|
278
|
+
*/
|
|
279
|
+
function sessionProblem(session, repairHint = 'Store the context again with every endpoint.') {
|
|
280
|
+
switch (session.kind) {
|
|
281
|
+
case 'incomplete-backend':
|
|
282
|
+
return `The backend context "${session.context}" lacks the ${planeList(session.missing)}, so it cannot be used; no endpoint is filled in on its own. ${repairHint}`;
|
|
283
|
+
case 'invalid-backend':
|
|
284
|
+
return `The backend context "${session.context}" cannot be used, and nothing is sent to it: ${session.problem} ${repairHint}`;
|
|
285
|
+
case 'invalid-override':
|
|
286
|
+
case 'conflict':
|
|
287
|
+
case 'agent-unusable':
|
|
288
|
+
return `${session.problem} ${session.fix}`;
|
|
289
|
+
case 'issuer-mismatch': {
|
|
290
|
+
const where = `The session stored under "${session.context}"`;
|
|
291
|
+
if (!session.issuedFor) {
|
|
292
|
+
return `${where} does not record the backend it was issued for, so it is not used or sent anywhere: it may not come from ${session.backend.authEndpoint}. A new sign-in replaces it.`;
|
|
293
|
+
}
|
|
294
|
+
const { issuedFor } = session;
|
|
295
|
+
const changes = session.differs.map((plane) => `the ${plane} endpoint is ${(0, backend_store_1.planeEndpoint)(session.backend, plane)}, but the session was issued for ${(0, backend_store_1.planeEndpoint)(issuedFor, plane)}`);
|
|
296
|
+
return `${where} was issued for another backend: ${changes.join('; ')}. It is not used or sent anywhere. A new sign-in replaces it.`;
|
|
297
|
+
}
|
|
298
|
+
case 'no-backend':
|
|
299
|
+
case 'signed-out':
|
|
300
|
+
case 'signed-in':
|
|
301
|
+
return null;
|
|
302
|
+
default: {
|
|
303
|
+
const unknown = session;
|
|
304
|
+
throw new Error(`Unknown session state ${JSON.stringify(unknown)}.`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
package/tools-host.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ToolsHost } from '@agentic-kit/db-tools';
|
|
2
|
+
import { type ConstructiveEnv } from './env';
|
|
3
|
+
/**
|
|
4
|
+
* The `configureHost` input of `@agentic-kit/db-tools`. Each call resolves the
|
|
5
|
+
* session again, so a sign-in mid-session, or an agent token another process
|
|
6
|
+
* minted, is picked up without a restart, and each answer comes from one
|
|
7
|
+
* resolution. Absence is null (no account) or undefined (no backend). A
|
|
8
|
+
* session that cannot be used, and a store that cannot be read, throw their
|
|
9
|
+
* cause from both getters, so the tools report it whichever they read first.
|
|
10
|
+
* A stored session another backend issued throws from `account()` only, since
|
|
11
|
+
* the backend itself is usable.
|
|
12
|
+
*
|
|
13
|
+
* With `agent`, the host acts as that agent of the person: `account()` is
|
|
14
|
+
* asynchronous, and gives an access token minted with the agent's key when the
|
|
15
|
+
* cached one is near its end.
|
|
16
|
+
*
|
|
17
|
+
* `previewToken` gives the app sign-in the store keeps for a database under the
|
|
18
|
+
* person's context (`appSignIn`), which the record tools act as.
|
|
19
|
+
*/
|
|
20
|
+
export declare function sessionToolsHost({ signInHint, appSignInHint, repairHint, context, env, agent }: {
|
|
21
|
+
signInHint: string;
|
|
22
|
+
/** The step that signs in to an app, for a record tool that finds no one signed in to it. */
|
|
23
|
+
appSignInHint?: string;
|
|
24
|
+
/** The command that stores a complete context, for the `incomplete-backend` message. */
|
|
25
|
+
repairHint?: string;
|
|
26
|
+
context?: string;
|
|
27
|
+
env?: ConstructiveEnv;
|
|
28
|
+
agent?: string;
|
|
29
|
+
}): ToolsHost;
|
package/tools-host.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sessionToolsHost = sessionToolsHost;
|
|
4
|
+
const account_store_1 = require("./account-store");
|
|
5
|
+
const agent_1 = require("./agent");
|
|
6
|
+
const app_session_1 = require("./app-session");
|
|
7
|
+
const env_1 = require("./env");
|
|
8
|
+
const session_1 = require("./session");
|
|
9
|
+
/**
|
|
10
|
+
* The `configureHost` input of `@agentic-kit/db-tools`. Each call resolves the
|
|
11
|
+
* session again, so a sign-in mid-session, or an agent token another process
|
|
12
|
+
* minted, is picked up without a restart, and each answer comes from one
|
|
13
|
+
* resolution. Absence is null (no account) or undefined (no backend). A
|
|
14
|
+
* session that cannot be used, and a store that cannot be read, throw their
|
|
15
|
+
* cause from both getters, so the tools report it whichever they read first.
|
|
16
|
+
* A stored session another backend issued throws from `account()` only, since
|
|
17
|
+
* the backend itself is usable.
|
|
18
|
+
*
|
|
19
|
+
* With `agent`, the host acts as that agent of the person: `account()` is
|
|
20
|
+
* asynchronous, and gives an access token minted with the agent's key when the
|
|
21
|
+
* cached one is near its end.
|
|
22
|
+
*
|
|
23
|
+
* `previewToken` gives the app sign-in the store keeps for a database under the
|
|
24
|
+
* person's context (`appSignIn`), which the record tools act as.
|
|
25
|
+
*/
|
|
26
|
+
function sessionToolsHost({ signInHint, appSignInHint, repairHint, context, env, agent }) {
|
|
27
|
+
const person = () => {
|
|
28
|
+
const session = (0, session_1.resolveSession)({ context, env });
|
|
29
|
+
const problem = session.kind === 'issuer-mismatch' ? null : (0, session_1.sessionProblem)(session, repairHint);
|
|
30
|
+
if (problem)
|
|
31
|
+
throw new Error(problem);
|
|
32
|
+
return session;
|
|
33
|
+
};
|
|
34
|
+
const agentAccount = async () => {
|
|
35
|
+
const stash = env ?? (0, env_1.getConstructiveEnv)();
|
|
36
|
+
const session = await (0, agent_1.agentSession)({ store: (0, account_store_1.openStore)((0, account_store_1.stashBaseDir)(stash)), name: agent, context, env: stash });
|
|
37
|
+
const problem = (0, session_1.sessionProblem)(session, repairHint);
|
|
38
|
+
if (problem)
|
|
39
|
+
throw new Error(problem);
|
|
40
|
+
return session.kind === 'signed-in' ? (0, session_1.hostAccount)(session) : null;
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
account() {
|
|
44
|
+
if (agent !== undefined)
|
|
45
|
+
return agentAccount();
|
|
46
|
+
const session = person();
|
|
47
|
+
if (session.kind === 'issuer-mismatch')
|
|
48
|
+
throw new Error((0, session_1.sessionProblem)(session));
|
|
49
|
+
return session.kind === 'signed-in' ? (0, session_1.hostAccount)(session) : null;
|
|
50
|
+
},
|
|
51
|
+
backendConfig() {
|
|
52
|
+
if (agent !== undefined) {
|
|
53
|
+
const bound = (0, session_1.agentBinding)({ context, env, agent });
|
|
54
|
+
if (bound.kind === 'bound')
|
|
55
|
+
return (0, session_1.hostBackendConfig)(bound.backend);
|
|
56
|
+
const problem = (0, session_1.sessionProblem)(bound, repairHint);
|
|
57
|
+
if (problem)
|
|
58
|
+
throw new Error(problem);
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
const session = person();
|
|
62
|
+
return session.kind === 'signed-in' || session.kind === 'signed-out' || session.kind === 'issuer-mismatch' ? (0, session_1.hostBackendConfig)(session.backend) : undefined;
|
|
63
|
+
},
|
|
64
|
+
async previewToken({ databaseId }) {
|
|
65
|
+
const stash = env ?? (0, env_1.getConstructiveEnv)();
|
|
66
|
+
const session = (0, session_1.resolveSession)({ context, env: stash });
|
|
67
|
+
const name = 'context' in session ? session.context : null;
|
|
68
|
+
const app = name ? (0, app_session_1.loadAppSession)((0, account_store_1.openStore)((0, account_store_1.stashBaseDir)(stash)), name, databaseId) : null;
|
|
69
|
+
return app ? { accessToken: app.accessToken, userId: app.userId, email: app.email, ...(app.accessTokenExpiresAt ? { accessTokenExpiresAt: app.accessTokenExpiresAt } : {}) } : null;
|
|
70
|
+
},
|
|
71
|
+
signInHint,
|
|
72
|
+
...(appSignInHint ? { appSignInHint } : {})
|
|
73
|
+
};
|
|
74
|
+
}
|