@agentic-kit/session 0.0.0-stage → 0.2.0

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 +43 -4
  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,201 @@
1
+ import { randomBytes } from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { checkContextName, ContextNameError, issuedForOf, storeDirs } from './account-store';
5
+ export class AgentNameError extends Error {
6
+ value;
7
+ constructor(value, reason = 'An agent name has 1 to 100 characters: lower-case letters, digits, ".", "-" and "_", starting with a letter or a digit, with no "..".') {
8
+ super(`"${value.length > 120 ? `${value.slice(0, 120)}…` : value}" is not a valid agent name. ${reason}`);
9
+ this.value = value;
10
+ this.name = 'AgentNameError';
11
+ }
12
+ }
13
+ /**
14
+ * An agent name is the stem of a file in the store, so it follows the
15
+ * context-name rule, and it may not end like the store's own files.
16
+ */
17
+ export function checkAgentName(name) {
18
+ try {
19
+ checkContextName(name);
20
+ }
21
+ catch (err) {
22
+ if (err instanceof ContextNameError)
23
+ throw new AgentNameError(err.value);
24
+ throw err;
25
+ }
26
+ if (name.endsWith('.json')) {
27
+ throw new AgentNameError(name, 'It ends in ".json", so it reads like a file of the store (an agent record). Leave out the ending.');
28
+ }
29
+ return name;
30
+ }
31
+ const agentDir = (store, context) => path.join(storeDirs(store).config, 'agents', checkContextName(context));
32
+ const tokenDir = (store, context) => path.join(storeDirs(store).cache, 'agents', checkContextName(context));
33
+ export const agentFile = (store, context, name) => path.join(agentDir(store, context), `${checkAgentName(name)}.json`);
34
+ const tokenFile = (store, context, name) => path.join(tokenDir(store, context), `${checkAgentName(name)}.json`);
35
+ function ensureDir(dir) {
36
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
37
+ fs.chmodSync(dir, 0o700);
38
+ fs.chmodSync(path.dirname(dir), 0o700);
39
+ }
40
+ /**
41
+ * Write `content` with mode 0600 through a temporary file, so a reader sees the
42
+ * old file or the new one, never half of one. `create` fails with EEXIST when
43
+ * the file exists (a hard link never replaces), so of two creates one wins.
44
+ */
45
+ export function writeAtomic(file, content, mode) {
46
+ ensureDir(path.dirname(file));
47
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
48
+ const fd = fs.openSync(tmp, 'wx', 0o600);
49
+ // The temporary file holds the key too, so it goes on every path once it exists.
50
+ try {
51
+ try {
52
+ fs.writeFileSync(fd, content);
53
+ fs.fsyncSync(fd);
54
+ }
55
+ finally {
56
+ fs.closeSync(fd);
57
+ }
58
+ if (mode === 'create')
59
+ fs.linkSync(tmp, file);
60
+ else
61
+ fs.renameSync(tmp, file);
62
+ }
63
+ catch (err) {
64
+ fs.rmSync(tmp, { force: true });
65
+ throw err;
66
+ }
67
+ // Published: a copy left behind holds the same record, with the same mode and in the same directory as the
68
+ // record, so a failed removal exposes nothing new and must not read as a failed write.
69
+ try {
70
+ fs.rmSync(tmp, { force: true });
71
+ }
72
+ catch {
73
+ // The record is written; see above.
74
+ }
75
+ }
76
+ /** Whether a record file exists under the name, readable or not. */
77
+ export function agentEntryExists(store, context, name) {
78
+ return fs.existsSync(agentFile(store, context, name));
79
+ }
80
+ /** A record file that does not parse, or lacks what an agent record holds: an edit by hand, since the store writes it atomically. */
81
+ export class AgentRecordUnreadable extends Error {
82
+ file;
83
+ constructor(file, problem) {
84
+ super(`The stored record of the agent (${file}) ${problem}, so its credential cannot be used.`);
85
+ this.file = file;
86
+ this.name = 'AgentRecordUnreadable';
87
+ }
88
+ }
89
+ const RECORD_TEXT = ['name', 'context', 'principalId', 'ownerId', 'createdAt', 'apiKey', 'keyId', 'keyExpiresAt'];
90
+ function isRecord(value) {
91
+ const r = value;
92
+ return (!!r &&
93
+ typeof r === 'object' &&
94
+ RECORD_TEXT.every((key) => typeof r[key] === 'string' && r[key] !== '') &&
95
+ !Number.isNaN(Date.parse(r.keyExpiresAt)) &&
96
+ typeof r.schemaChanges === 'boolean' &&
97
+ !!issuedForOf(r.issuedFor));
98
+ }
99
+ export function readAgent(store, context, name) {
100
+ const file = agentFile(store, context, name);
101
+ let raw;
102
+ try {
103
+ raw = fs.readFileSync(file, 'utf8');
104
+ }
105
+ catch (err) {
106
+ if (err.code === 'ENOENT')
107
+ return null;
108
+ throw err;
109
+ }
110
+ let value;
111
+ try {
112
+ value = JSON.parse(raw);
113
+ }
114
+ catch {
115
+ // The parser's message can quote the text around the error, which may be the key.
116
+ throw new AgentRecordUnreadable(file, 'is not valid JSON');
117
+ }
118
+ if (!isRecord(value))
119
+ throw new AgentRecordUnreadable(file, 'lacks the principal, the key, a valid key end date or the backend of an agent');
120
+ // A record copied under another name would make an operation on this name act on that agent's principal.
121
+ if (value.name !== name || value.context !== context)
122
+ throw new AgentRecordUnreadable(file, `is the record of the agent "${value.name}" under "${value.context}", not of this name and context`);
123
+ return value;
124
+ }
125
+ /** Store a new agent; throws an error with code EEXIST when an agent of that name is stored already. */
126
+ export function createAgentEntry(store, record) {
127
+ writeAtomic(agentFile(store, record.context, record.name), JSON.stringify(record, null, 2), 'create');
128
+ }
129
+ export function writeAgent(store, record) {
130
+ writeAtomic(agentFile(store, record.context, record.name), JSON.stringify(record, null, 2), 'replace');
131
+ }
132
+ /**
133
+ * Delete the agent's cached token, best effort (see `readCachedToken`): a session takes a cached token only for the
134
+ * key that minted it, so a token left behind is never used again.
135
+ */
136
+ export function dropCachedToken(store, context, name) {
137
+ try {
138
+ fs.rmSync(tokenFile(store, context, name), { force: true });
139
+ }
140
+ catch {
141
+ // See readCachedToken.
142
+ }
143
+ }
144
+ /** Delete the agent's record, then its cached token. Throws when the record cannot be deleted. */
145
+ export function deleteAgent(store, context, name) {
146
+ fs.rmSync(agentFile(store, context, name), { force: true });
147
+ dropCachedToken(store, context, name);
148
+ }
149
+ /** The names of the agents stored under `context`, valid names only, sorted. */
150
+ export function listAgentNames(store, context) {
151
+ let files;
152
+ try {
153
+ files = fs.readdirSync(agentDir(store, context));
154
+ }
155
+ catch (err) {
156
+ if (err.code === 'ENOENT')
157
+ return [];
158
+ throw err;
159
+ }
160
+ return files
161
+ .filter((file) => file.endsWith('.json'))
162
+ .map((file) => file.slice(0, -'.json'.length))
163
+ .filter((name) => {
164
+ try {
165
+ checkAgentName(name);
166
+ return true;
167
+ }
168
+ catch {
169
+ return false;
170
+ }
171
+ })
172
+ .sort();
173
+ }
174
+ /** The cached token, or null when there is none or it does not parse: a missing cache only costs one more mint. */
175
+ /**
176
+ * The cached token, or null when there is none that can be read. The cache only saves a mint, so reading, writing
177
+ * and deleting it never fail an operation: a token that cannot be cached is minted again next time.
178
+ */
179
+ export function readCachedToken(store, context, name) {
180
+ let value;
181
+ try {
182
+ value = JSON.parse(fs.readFileSync(tokenFile(store, context, name), 'utf8'));
183
+ }
184
+ catch {
185
+ return null;
186
+ }
187
+ return typeof value?.keyId === 'string' && typeof value.accessToken === 'string' && typeof value.accessExpiresAt === 'string' ? value : null;
188
+ }
189
+ /**
190
+ * Cache a minted token, best effort (see `readCachedToken`). Processes write it without a lock: a token may be used
191
+ * many times, so when two write at once, the one renamed last stays, and the other process's token still works
192
+ * until it ends.
193
+ */
194
+ export function writeCachedToken(store, context, name, token) {
195
+ try {
196
+ writeAtomic(tokenFile(store, context, name), JSON.stringify(token), 'replace');
197
+ }
198
+ catch {
199
+ // See readCachedToken.
200
+ }
201
+ }
package/esm/agent.d.ts ADDED
@@ -0,0 +1,137 @@
1
+ import { ConfigStore } from 'appstash';
2
+ import { type KeyRevocation } from './api-key';
3
+ import { type SignInProof } from './auth';
4
+ import { type ConstructiveEnv } from './env';
5
+ import { type ResolvedAgentSession, type Session } from './session';
6
+ export declare const SCHEMA_READ_ONLY_MASK: string;
7
+ export type AgentErrorKind = 'invalid-name' | 'not-a-person' | 'sign-in-required' | 'step-up-required' | 'name-taken' | 'not-found' | 'unreadable-record'
8
+ /** Another backend than the person's session issued the agent's key, and only that backend can change it. */
9
+ | 'issuer-mismatch'
10
+ /** The backend holds something the operation would make again. */
11
+ | 'conflict' | 'refused' | 'backend-unreachable' | 'server-error';
12
+ /** A failed agent operation. `code` is the server's error code when it gave one. No secret is in it. */
13
+ export declare class AgentError extends Error {
14
+ readonly kind: AgentErrorKind;
15
+ readonly code?: string;
16
+ constructor(kind: AgentErrorKind, message: string, code?: string);
17
+ }
18
+ /**
19
+ * An agent as listed, in one of four states: `ready`, `set-up-again` (its key has ended), `issuer-mismatch` (the
20
+ * context now names other endpoints), or `unreadable` (its record cannot be read; `problem` says why). An agent that
21
+ * is `ready` keeps working until its key ends (`keyExpiresAt`) or it is removed, also after the person signs out.
22
+ */
23
+ export type AgentInfo = AgentDetails | {
24
+ name: string;
25
+ context: string;
26
+ state: 'unreadable';
27
+ problem: string;
28
+ };
29
+ export interface AgentDetails {
30
+ name: string;
31
+ context: string;
32
+ principalId: string;
33
+ schemaChanges: boolean;
34
+ organization?: string;
35
+ createdAt: string;
36
+ keyExpiresAt: string;
37
+ /** `set-up-again`: the key has ended. `issuer-mismatch`: the context now names other endpoints. */
38
+ state: 'ready' | 'set-up-again' | 'issuer-mismatch';
39
+ }
40
+ /**
41
+ * Create an agent of the signed-in person: a principal that does not share the
42
+ * person's admin flag, held to `organization` when one is given, that may not
43
+ * change the schema unless `allowSchemaChanges`, with every key of it capped at
44
+ * 30 days, and one such key, stored under the person's context. This package
45
+ * uses the key only to mint access tokens, but the backend accepts the key itself
46
+ * on requests too. It signs the person in afresh with the password (or the
47
+ * code of the challenge the password started) and ends that sign-in when done.
48
+ * A failure after the principal exists deletes it again and says so.
49
+ */
50
+ export declare function createAgent({ store, session, name, organization, allowSchemaChanges, ...proof }: {
51
+ store: ConfigStore;
52
+ session: Session;
53
+ name: string;
54
+ organization?: string;
55
+ allowSchemaChanges: boolean;
56
+ } & SignInProof): Promise<AgentInfo>;
57
+ export declare function listAgents({ store, context }: {
58
+ store: ConfigStore;
59
+ context?: string;
60
+ }): AgentInfo[];
61
+ /**
62
+ * The agent's session for use: the cached access token while more than a
63
+ * short margin of it is left, else a new one minted with the agent's key and
64
+ * cached. Processes need no lock: a token may be used many times, so two that
65
+ * mint at once both work, and the cache keeps one of them.
66
+ *
67
+ * `rejectedToken` is an access token of this agent that the backend just
68
+ * refused as signed out. When it is the cached one, that entry is dropped and
69
+ * one token is minted from the key; when another process already cached a new
70
+ * one, that one is used. It never retries on its own, so a caller passes it
71
+ * once per refusal.
72
+ */
73
+ export declare function agentSession({ store, name, context, env, rejectedToken }: {
74
+ store: ConfigStore;
75
+ name: string;
76
+ context?: string;
77
+ env?: ConstructiveEnv;
78
+ rejectedToken?: string;
79
+ }): Promise<ResolvedAgentSession>;
80
+ /** Let an agent change the schema: the scope's mask is removed. */
81
+ export declare const grantSchemaChanges: ({ store, session, name }: {
82
+ store: ConfigStore;
83
+ session: Session;
84
+ name: string;
85
+ }) => Promise<AgentInfo>;
86
+ /** Stop an agent changing the schema: `manage_database` is masked out again. */
87
+ export declare const revokeSchemaChanges: ({ store, session, name }: {
88
+ store: ConfigStore;
89
+ session: Session;
90
+ name: string;
91
+ }) => Promise<AgentInfo>;
92
+ /** A renewed agent, and what happened to its old key. */
93
+ export interface AgentRenewal {
94
+ agent: AgentInfo;
95
+ previousKey: KeyRevocation;
96
+ }
97
+ /**
98
+ * Give an agent a new 30-day key for the same principal, so it keeps its
99
+ * grants: with a new password sign-in of the person (ended when done), the new
100
+ * key is stored first, the cached token dropped, then the old key revoked,
101
+ * which ends every token minted with it. A failure before the new key is
102
+ * stored keeps the old key and the record as they were.
103
+ */
104
+ export declare function renewAgentKey({ store, session, name, ...proof }: {
105
+ store: ConfigStore;
106
+ session: Session;
107
+ name: string;
108
+ } & SignInProof): Promise<AgentRenewal>;
109
+ /**
110
+ * Delete the agent's principal on the backend, which ends its key and every
111
+ * token minted with it at once, then its stored entry and cached token. A
112
+ * failed delete keeps the entry and throws; a principal the backend no longer
113
+ * has is `already-gone`, and its entry is removed. An agent that another
114
+ * backend issued is `entry-removed`, with nothing sent: its problem names where
115
+ * its key still works.
116
+ */
117
+ export type AgentRemoval = {
118
+ kind: 'removed' | 'already-gone';
119
+ name: string;
120
+ }
121
+ /** The record could not be read, or another backend issued it: only the entry was removed, and `problem` says what is left. */
122
+ | {
123
+ kind: 'entry-removed';
124
+ name: string;
125
+ problem: string;
126
+ }
127
+ /** The principal was deleted, so its key and tokens are ended, but its entry could not be removed: `problem` says how to finish. */
128
+ | {
129
+ kind: 'entry-left';
130
+ name: string;
131
+ problem: string;
132
+ };
133
+ export declare function removeAgent({ store, session, name }: {
134
+ store: ConfigStore;
135
+ session: Session;
136
+ name: string;
137
+ }): Promise<AgentRemoval>;