@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.
Files changed (55) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +207 -2
  3. package/account-store.d.ts +78 -0
  4. package/account-store.js +162 -0
  5. package/agent-store.d.ts +79 -0
  6. package/agent-store.js +251 -0
  7. package/agent.d.ts +137 -0
  8. package/agent.js +514 -0
  9. package/api-key.d.ts +53 -0
  10. package/api-key.js +60 -0
  11. package/app-session.d.ts +48 -0
  12. package/app-session.js +105 -0
  13. package/auth-error.d.ts +54 -0
  14. package/auth-error.js +186 -0
  15. package/auth.d.ts +169 -0
  16. package/auth.js +514 -0
  17. package/backend-store.d.ts +134 -0
  18. package/backend-store.js +259 -0
  19. package/env.d.ts +9 -0
  20. package/env.js +10 -0
  21. package/esm/account-store.d.ts +78 -0
  22. package/esm/account-store.js +146 -0
  23. package/esm/agent-store.d.ts +79 -0
  24. package/esm/agent-store.js +201 -0
  25. package/esm/agent.d.ts +137 -0
  26. package/esm/agent.js +503 -0
  27. package/esm/api-key.d.ts +53 -0
  28. package/esm/api-key.js +52 -0
  29. package/esm/app-session.d.ts +48 -0
  30. package/esm/app-session.js +66 -0
  31. package/esm/auth-error.d.ts +54 -0
  32. package/esm/auth-error.js +171 -0
  33. package/esm/auth.d.ts +169 -0
  34. package/esm/auth.js +467 -0
  35. package/esm/backend-store.d.ts +134 -0
  36. package/esm/backend-store.js +239 -0
  37. package/esm/env.d.ts +9 -0
  38. package/esm/env.js +6 -0
  39. package/esm/index.d.ts +12 -0
  40. package/esm/index.js +11 -0
  41. package/esm/operation.d.ts +45 -0
  42. package/esm/operation.js +87 -0
  43. package/esm/session.d.ts +192 -0
  44. package/esm/session.js +297 -0
  45. package/esm/tools-host.d.ts +29 -0
  46. package/esm/tools-host.js +71 -0
  47. package/index.d.ts +12 -0
  48. package/index.js +63 -0
  49. package/operation.d.ts +45 -0
  50. package/operation.js +92 -0
  51. package/package.json +40 -3
  52. package/session.d.ts +192 -0
  53. package/session.js +307 -0
  54. package/tools-host.d.ts +29 -0
  55. package/tools-host.js +74 -0
@@ -0,0 +1,239 @@
1
+ import { deriveSubdomainEndpoint } from '@agentic-kit/db-tools';
2
+ import { checkContextName, ContextNameError, currentContextName, loadSession } from './account-store';
3
+ import { listAgentNames } from './agent-store';
4
+ export const PLANES = ['api', 'auth', 'modules', 'agent', 'compute'];
5
+ const KEY = {
6
+ api: 'apiEndpoint',
7
+ auth: 'authEndpoint',
8
+ modules: 'modulesEndpoint',
9
+ agent: 'agentEndpoint',
10
+ compute: 'computeEndpoint'
11
+ };
12
+ export function planeEndpoint(config, plane) {
13
+ return config[KEY[plane]];
14
+ }
15
+ /** The planes whose endpoints differ, compared exactly (no case or slash folding). */
16
+ export function differingPlanes(a, b) {
17
+ return PLANES.filter((plane) => planeEndpoint(a, plane) !== planeEndpoint(b, plane));
18
+ }
19
+ /**
20
+ * Whether `url` names this machine, where plain http never crosses a network: a host whose last label is localhost,
21
+ * an IPv4 address in 127/8, or ::1.
22
+ */
23
+ export function isLoopback(url) {
24
+ const host = url.hostname;
25
+ return host.split('.').pop() === 'localhost' || /^127(\.\d{1,3}){3}$/.test(host) || host === '[::1]';
26
+ }
27
+ /** An endpoint that cannot name a backend. The message never shows userinfo. */
28
+ export class EndpointError extends Error {
29
+ reason;
30
+ plane;
31
+ constructor(reason, plane, message) {
32
+ super(message);
33
+ this.reason = reason;
34
+ this.plane = plane;
35
+ this.name = 'EndpointError';
36
+ }
37
+ }
38
+ function shown(endpoint) {
39
+ try {
40
+ const url = new URL(endpoint);
41
+ url.username = '';
42
+ url.password = '';
43
+ return url.toString();
44
+ }
45
+ catch {
46
+ return endpoint.replace(/\/\/[^/@]*@/, '//');
47
+ }
48
+ }
49
+ /** `raw` as an endpoint of `plane`, or the `EndpointError` that says why it cannot be one. */
50
+ export function checkedEndpoint(plane, raw) {
51
+ const endpoint = raw.trim();
52
+ let url;
53
+ try {
54
+ url = new URL(endpoint);
55
+ }
56
+ catch {
57
+ throw new EndpointError('not-a-url', plane, `The ${plane} endpoint "${shown(endpoint) || '(empty)'}" is not an absolute URL. Pass one such as https://${plane}.example.com/graphql.`);
58
+ }
59
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
60
+ throw new EndpointError('scheme', plane, `The ${plane} endpoint ${shown(endpoint)} uses ${url.protocol}, but only http and https are supported. Pass an http or https URL.`);
61
+ }
62
+ if (url.protocol === 'http:' && !isLoopback(url)) {
63
+ throw new EndpointError('insecure', plane, `The ${plane} endpoint ${shown(endpoint)} uses plain http on a host that is not this machine, so the password and keys sent to it would cross the network unencrypted. Use its https URL; plain http is accepted only for localhost.`);
64
+ }
65
+ if (url.username || url.password) {
66
+ throw new EndpointError('userinfo', plane, `The ${plane} endpoint ${shown(endpoint)} has a user name or password in it, which would go to every plane. Remove it; sign in with email and password instead.`);
67
+ }
68
+ return endpoint;
69
+ }
70
+ /** Five endpoints of a backend, each checked as given, none derived. Throws `EndpointError`. */
71
+ export function checkedBackend(endpoints) {
72
+ return Object.fromEntries(PLANES.map((plane) => [KEY[plane], checkedEndpoint(plane, endpoints[KEY[plane]] ?? '')]));
73
+ }
74
+ /**
75
+ * The planes share the api endpoint's host scheme only when the host is
76
+ * `api.<rest>` (api.example.com -> auth.example.com). Any other host would send
77
+ * the password to a host the user never named, so it must give every plane.
78
+ */
79
+ function derivedEndpoint(api, plane) {
80
+ const labels = new URL(api).hostname.split('.');
81
+ if (labels[0] !== 'api' || labels.length < 2 || labels.some((label) => label === '')) {
82
+ throw new EndpointError('not-derivable', plane, `Cannot derive the ${plane} endpoint from ${shown(api)}: the other planes are derived only from a host that starts with "api.". Give every plane endpoint explicitly (auth, modules, agent and compute).`);
83
+ }
84
+ return deriveSubdomainEndpoint(api, plane);
85
+ }
86
+ /**
87
+ * The backend that `api` names. A plane given explicitly is used as is; a
88
+ * missing one is derived from an `api.<rest>` host. Throws `EndpointError`.
89
+ */
90
+ export function backendFromEndpoints(endpoints) {
91
+ const api = checkedEndpoint('api', endpoints.api ?? '');
92
+ const config = { apiEndpoint: api };
93
+ for (const plane of PLANES) {
94
+ if (plane === 'api')
95
+ continue;
96
+ const given = endpoints[plane];
97
+ config[KEY[plane]] = given !== undefined ? checkedEndpoint(plane, given) : derivedEndpoint(api, plane);
98
+ }
99
+ return config;
100
+ }
101
+ /**
102
+ * A backend is a named context in the shared store, named after the api
103
+ * endpoint's host without a leading `api.` (https://api.example.com/graphql ->
104
+ * example.com), a port joined by a dash (example.com-8443). Credentials hang
105
+ * off the context, so each backend keeps an independent session.
106
+ */
107
+ export function contextNameFor(config) {
108
+ const { host, hostname } = new URL(config.apiEndpoint);
109
+ const labels = hostname.split('.');
110
+ const raw = labels[0] === 'api' && labels.length >= 2 ? host.slice('api.'.length) : host;
111
+ const name = raw
112
+ .toLowerCase()
113
+ .replace(/[^a-z0-9.-]+/g, '-')
114
+ .replace(/\.{2,}/g, '.')
115
+ .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '')
116
+ .slice(0, 100)
117
+ .replace(/[^a-z0-9]+$/, '');
118
+ return checkContextName(name || 'backend');
119
+ }
120
+ /** A stored context read back: its endpoints pass the same check as new ones, or it is `incomplete` or `invalid`. */
121
+ function fromTargets(name, current, targets) {
122
+ const missing = PLANES.filter((plane) => !targets?.[plane]?.endpoint);
123
+ if (missing.length > 0) {
124
+ const apiEndpoint = targets?.api?.endpoint;
125
+ return { name, current, status: 'incomplete', missing, ...(apiEndpoint ? { apiEndpoint } : {}) };
126
+ }
127
+ try {
128
+ const endpoints = Object.fromEntries(PLANES.map((plane) => [KEY[plane], targets[plane].endpoint]));
129
+ return { name, current, status: 'complete', backend: checkedBackend(endpoints) };
130
+ }
131
+ catch (err) {
132
+ if (!(err instanceof EndpointError))
133
+ throw err;
134
+ return { name, current, status: 'invalid', plane: err.plane, problem: err.message };
135
+ }
136
+ }
137
+ /** One stored context, or null when there is none with that name. */
138
+ export function readBackend(store, name) {
139
+ const ctx = store.loadContext(checkContextName(name));
140
+ return ctx ? fromTargets(name, name === currentContextName(store), ctx.targets) : null;
141
+ }
142
+ /** Every stored context. One with a name that does not pass the check is listed as `invalid-name` and stops nothing. */
143
+ export function listBackends(store) {
144
+ const current = store.loadSettings().currentContext;
145
+ return store.listContexts().map((ctx) => {
146
+ const name = String(ctx.name);
147
+ try {
148
+ checkContextName(name);
149
+ }
150
+ catch (err) {
151
+ if (!(err instanceof ContextNameError))
152
+ throw err;
153
+ return { name, current: name === current, status: 'invalid-name', reason: err.message };
154
+ }
155
+ return fromTargets(name, name === current, ctx.targets);
156
+ });
157
+ }
158
+ /** Storing other endpoints under the context, or removing it, would drop the session filed there while its API key stays valid. */
159
+ export class ContextInUseError extends Error {
160
+ context;
161
+ action;
162
+ agents;
163
+ constructor(context, action, agents = []) {
164
+ super(action === 'store'
165
+ ? `The context "${context}" holds a session that was not issued for these endpoints, or credentials another tool stored, so storing them would drop it while its key stays valid. Sign out of "${context}" first, which revokes that key, or store the backend under another name.`
166
+ : action === 'agents'
167
+ ? `The context "${context}" has agents set up with its endpoints (${agents.join(', ')}), and their keys work only there, so its endpoints cannot change. Delete those agents first (agent delete), or store the backend under another name.`
168
+ : agents.length
169
+ ? `The context "${context}" has agents (${agents.join(', ')}) whose keys stay valid after it is gone, with no entry left to remove them by, so it was not removed. Delete those agents first (agent delete), which ends their keys.`
170
+ : `The context "${context}" holds a session, so removing it would drop the session while its API key stays valid. Sign out of "${context}" first, which revokes that key.`);
171
+ this.context = context;
172
+ this.action = action;
173
+ this.agents = agents;
174
+ this.name = 'ContextInUseError';
175
+ }
176
+ }
177
+ /**
178
+ * Why `config` cannot be stored under `name` now, or null. Credentials filed there must be a session this package
179
+ * wrote, issued for these endpoints; `replacing` takes any session of its own, which a sign-in revokes and replaces.
180
+ * A context whose agents were set up with its endpoints keeps them. The name is checked first, then the agents, then
181
+ * the session: removing an agent needs that sign-in, so the agents must go first.
182
+ */
183
+ export function backendConflict(store, config, name, { replacing = false } = {}) {
184
+ checkContextName(name);
185
+ const stored = readBackend(store, name);
186
+ const agents = stored ? listAgentNames(store, name) : [];
187
+ if (agents.length && (stored.status !== 'complete' || differingPlanes(stored.backend, config).length > 0))
188
+ return new ContextInUseError(name, 'agents', agents);
189
+ if (store.getCredentials(name)) {
190
+ const session = loadSession(store, name);
191
+ if (!session || (!replacing && (!session.issuedFor || differingPlanes(session.issuedFor, config).length > 0)))
192
+ return new ContextInUseError(name, 'store');
193
+ }
194
+ return null;
195
+ }
196
+ /**
197
+ * Store the endpoints as a context (default name: `contextNameFor`), keeping
198
+ * its current choice and the session filed under that name, which must have
199
+ * been issued for exactly these five endpoints. Throws `ContextInUseError`
200
+ * when it was not, or cannot be shown to be (sign out of that context first),
201
+ * and when agents of the context were set up with other endpoints.
202
+ */
203
+ export function addBackend(store, config, name = contextNameFor(config)) {
204
+ const conflict = backendConflict(store, config, name);
205
+ if (conflict)
206
+ throw conflict;
207
+ writeBackend(store, config, name);
208
+ return { name };
209
+ }
210
+ /** Write the endpoints under `name` with no check of what is filed there: for a caller that checked with `backendConflict`. */
211
+ export function writeBackend(store, config, name) {
212
+ const targets = Object.fromEntries(PLANES.map((plane) => [plane, { endpoint: config[KEY[plane]] }]));
213
+ store.createContext(checkContextName(name), { endpoint: config.apiEndpoint, targets });
214
+ }
215
+ /** Put back a context `writeBackend` replaced: its old endpoints, or no context when there was none. */
216
+ export function restoreBackend(store, name, previous) {
217
+ if (previous)
218
+ store.createContext(checkContextName(name), { endpoint: previous.endpoint, targets: previous.targets });
219
+ else
220
+ store.deleteContext(checkContextName(name));
221
+ }
222
+ export function selectBackend(store, name) {
223
+ if (!store.setCurrentContext(checkContextName(name))) {
224
+ const known = store.listContexts().map((ctx) => ctx.name);
225
+ throw new Error(`No backend context named "${name}". Known contexts: ${known.join(', ') || '(none)'}. Add the backend first.`);
226
+ }
227
+ }
228
+ /**
229
+ * Delete a context. Throws `ContextInUseError` while agents are stored under it (`removeAgent` first, which needs the
230
+ * sign-in), then while a session is filed under it (`signOut` first, which revokes its key).
231
+ */
232
+ export function removeBackend(store, name) {
233
+ const agents = listAgentNames(store, checkContextName(name));
234
+ if (agents.length)
235
+ throw new ContextInUseError(name, 'remove', agents);
236
+ if (store.getCredentials(name))
237
+ throw new ContextInUseError(name, 'remove');
238
+ return store.deleteContext(name);
239
+ }
package/esm/env.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The CONSTRUCTIVE_* variables the agentic packages read, and the one place that reads them from the process. Every
3
+ * reader takes this view; a host or a test passes its own environment, and only the default comes from process.env.
4
+ */
5
+ export type ConstructiveEnv = Readonly<Record<string, string | undefined>>;
6
+ /** Base directory of the stash, for tests and isolated runs. Desktop reads the same variable. */
7
+ export declare const STASH_DIR_ENV = "CONSTRUCTIVE_STASH_DIR";
8
+ /** The CONSTRUCTIVE_* variables of `env` (default: the process's), as given: '' stays '', so a reader can refuse it. */
9
+ export declare function getConstructiveEnv(env?: NodeJS.ProcessEnv): ConstructiveEnv;
package/esm/env.js ADDED
@@ -0,0 +1,6 @@
1
+ /** Base directory of the stash, for tests and isolated runs. Desktop reads the same variable. */
2
+ export const STASH_DIR_ENV = 'CONSTRUCTIVE_STASH_DIR';
3
+ /** The CONSTRUCTIVE_* variables of `env` (default: the process's), as given: '' stays '', so a reader can refuse it. */
4
+ export function getConstructiveEnv(env = process.env) {
5
+ return Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith('CONSTRUCTIVE_')));
6
+ }
package/esm/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export { type AccountSession, checkContextName, ContextNameError, openStore, saveSession, STASH_DIR_ENV, STASH_NAME, stashBaseDir, stashDirectories } from './account-store';
2
+ export { type AgentDetails, AgentError, type AgentErrorKind, type AgentInfo, type AgentRemoval, type AgentRenewal, agentSession, createAgent, grantSchemaChanges, listAgents, removeAgent, renewAgentKey, revokeSchemaChanges, SCHEMA_READ_ONLY_MASK } from './agent';
3
+ export { checkAgentName } from './agent-store';
4
+ export { keyEndsSoon, type KeyRevocation, SIGN_IN_AGAIN_WITHIN_MS } from './api-key';
5
+ export { appAuthEndpoint, type AppSession, appSignIn, appSignOut, loadAppSession } from './app-session';
6
+ export { clearSignInChallenge, type CodeMethod, type CredentialCheck, loadSignInChallenge, saveSignInChallenge, SecondFactorRequired, signIn, type SignInChallenge, type SignInProof, type SignInResult, type SignInTarget, signInTarget, signOut, type SignOutResult, verifySession } from './auth';
7
+ export { SignInError, type SignInErrorKind } from './auth-error';
8
+ export { addBackend, type BackendConfig, type BackendContext, type BackendEndpoints, backendFromEndpoints, ContextInUseError, contextNameFor, type Endpoint, EndpointError, type EndpointProblem, listBackends, type Plane, PLANES, readBackend, removeBackend, selectBackend } from './backend-store';
9
+ export { type ConstructiveEnv, getConstructiveEnv } from './env';
10
+ export { type AgentIdentity, type AgentUnusableReason, hostAccount, OVERRIDE_ENV_VARS, type PersonSession, type ResolvedAgentSession, resolveSession, type Session, type SessionAccount, type SessionKey, sessionProblem, type SessionSource } from './session';
11
+ export { sessionToolsHost } from './tools-host';
12
+ export type { ConfigStore } from 'appstash';
package/esm/index.js ADDED
@@ -0,0 +1,11 @@
1
+ export { checkContextName, ContextNameError, openStore, saveSession, STASH_DIR_ENV, STASH_NAME, stashBaseDir, stashDirectories } from './account-store';
2
+ export { AgentError, agentSession, createAgent, grantSchemaChanges, listAgents, removeAgent, renewAgentKey, revokeSchemaChanges, SCHEMA_READ_ONLY_MASK } from './agent';
3
+ export { checkAgentName } from './agent-store';
4
+ export { keyEndsSoon, SIGN_IN_AGAIN_WITHIN_MS } from './api-key';
5
+ export { appAuthEndpoint, appSignIn, appSignOut, loadAppSession } from './app-session';
6
+ export { clearSignInChallenge, loadSignInChallenge, saveSignInChallenge, SecondFactorRequired, signIn, signInTarget, signOut, verifySession } from './auth';
7
+ export { SignInError } from './auth-error';
8
+ export { addBackend, backendFromEndpoints, ContextInUseError, contextNameFor, EndpointError, listBackends, PLANES, readBackend, removeBackend, selectBackend } from './backend-store';
9
+ export { getConstructiveEnv } from './env';
10
+ export { hostAccount, OVERRIDE_ENV_VARS, resolveSession, sessionProblem } from './session';
11
+ export { sessionToolsHost } from './tools-host';
@@ -0,0 +1,45 @@
1
+ /** How to undo a step, and what the person reads when the undo worked or failed. */
2
+ export interface Undo<T> {
3
+ run(value: T): Promise<unknown> | unknown;
4
+ /** Read when the undo worked; empty for an undo the person has nothing to do about. */
5
+ undone: string;
6
+ notUndone(value: T, reason: string): string;
7
+ }
8
+ /** One undo after a failure, as the person reads it. */
9
+ export interface Undone {
10
+ step: string;
11
+ undone: boolean;
12
+ text: string;
13
+ }
14
+ /** A step or the commit failed: `cause` is what it threw, `undone` what the steps before it gave back, last first. */
15
+ export interface StepFailure {
16
+ step: string;
17
+ cause: unknown;
18
+ undone: Undone[];
19
+ }
20
+ /** The undo texts of a failure as one sentence run, for the end of its message. */
21
+ export declare const undoneText: (undone: readonly Undone[]) => string;
22
+ /**
23
+ * An operation that changes the backend and the store, as steps with one commit point:
24
+ *
25
+ * pending --step ok--> pending --commit ok--> committed --settle--> committed
26
+ * | |
27
+ * +--step fails--------+--commit fails--> failed (every done step undone, last first)
28
+ *
29
+ * Before the commit, a failed step or commit undoes the steps done so far and throws what `fail` makes of it. After
30
+ * the commit nothing is undone: what is left runs in `settle`, which cannot fail the operation.
31
+ */
32
+ export declare class Operation {
33
+ private readonly fail;
34
+ private phase;
35
+ private undos;
36
+ constructor(fail: (failure: StepFailure) => Error);
37
+ /** Run a step before the commit. `undo` reverses it when a later step or the commit fails. */
38
+ step<T>(name: string, run: () => Promise<T> | T, undo?: Undo<T>): Promise<T>;
39
+ /** The point after which nothing is undone. A failed commit undoes every step, as a failed step does. */
40
+ commit<T>(name: string, write: () => Promise<T> | T): Promise<T>;
41
+ /** Work after the commit. It cannot fail the operation, so a throw becomes what `onError` makes of it. */
42
+ settle<T>(name: string, run: () => Promise<T> | T, onError: (cause: unknown) => T): Promise<T>;
43
+ private rollBack;
44
+ private expect;
45
+ }
@@ -0,0 +1,87 @@
1
+ import { errorText } from './api-key';
2
+ /** The undo texts of a failure as one sentence run, for the end of its message. */
3
+ export const undoneText = (undone) => undone
4
+ .map(({ text }) => text)
5
+ .filter(Boolean)
6
+ .join(' ');
7
+ /**
8
+ * An operation that changes the backend and the store, as steps with one commit point:
9
+ *
10
+ * pending --step ok--> pending --commit ok--> committed --settle--> committed
11
+ * | |
12
+ * +--step fails--------+--commit fails--> failed (every done step undone, last first)
13
+ *
14
+ * Before the commit, a failed step or commit undoes the steps done so far and throws what `fail` makes of it. After
15
+ * the commit nothing is undone: what is left runs in `settle`, which cannot fail the operation.
16
+ */
17
+ export class Operation {
18
+ fail;
19
+ phase = 'pending';
20
+ undos = [];
21
+ constructor(fail) {
22
+ this.fail = fail;
23
+ }
24
+ /** Run a step before the commit. `undo` reverses it when a later step or the commit fails. */
25
+ async step(name, run, undo) {
26
+ this.expect('pending', name);
27
+ let value;
28
+ try {
29
+ value = await run();
30
+ }
31
+ catch (cause) {
32
+ throw await this.rollBack(name, cause);
33
+ }
34
+ if (undo) {
35
+ this.undos.push({
36
+ step: name,
37
+ run: async () => {
38
+ try {
39
+ await undo.run(value);
40
+ return { step: name, undone: true, text: undo.undone };
41
+ }
42
+ catch (err) {
43
+ return { step: name, undone: false, text: undo.notUndone(value, errorText(err)) };
44
+ }
45
+ }
46
+ });
47
+ }
48
+ return value;
49
+ }
50
+ /** The point after which nothing is undone. A failed commit undoes every step, as a failed step does. */
51
+ async commit(name, write) {
52
+ this.expect('pending', name);
53
+ let value;
54
+ try {
55
+ value = await write();
56
+ }
57
+ catch (cause) {
58
+ throw await this.rollBack(name, cause);
59
+ }
60
+ this.phase = 'committed';
61
+ this.undos = [];
62
+ return value;
63
+ }
64
+ /** Work after the commit. It cannot fail the operation, so a throw becomes what `onError` makes of it. */
65
+ async settle(name, run, onError) {
66
+ this.expect('committed', name);
67
+ try {
68
+ return await run();
69
+ }
70
+ catch (cause) {
71
+ return onError(cause);
72
+ }
73
+ }
74
+ async rollBack(step, cause) {
75
+ this.phase = 'failed';
76
+ const undone = [];
77
+ for (const undo of this.undos.reverse())
78
+ undone.push(await undo.run());
79
+ this.undos = [];
80
+ return this.fail({ step, cause, undone });
81
+ }
82
+ expect(phase, name) {
83
+ if (this.phase !== phase) {
84
+ throw new Error(`"${name}" ran while the operation was ${this.phase}, but it may only run while it is ${phase}. This is a bug in @agentic-kit/session; report it.`);
85
+ }
86
+ }
87
+ }
@@ -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 {};