@0gfoundation/0g-agentdna 0.2.3 → 0.5.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.
- package/GUIDE.md +190 -40
- package/OPERATORS.md +164 -0
- package/OPERATORS.zh.md +141 -0
- package/PROVIDERS.md +6 -0
- package/PROVIDERS.zh.md +3 -1
- package/README.md +84 -11
- package/dist/AgentClient.d.ts +374 -26
- package/dist/AgentClient.d.ts.map +1 -1
- package/dist/AgentClient.js +323 -40
- package/dist/AgentClient.js.map +1 -1
- package/dist/AgenticID.d.ts +170 -80
- package/dist/AgenticID.d.ts.map +1 -1
- package/dist/AgenticID.js +300 -42
- package/dist/AgenticID.js.map +1 -1
- package/dist/AttestorClient.d.ts +115 -31
- package/dist/AttestorClient.d.ts.map +1 -1
- package/dist/AttestorClient.js +276 -56
- package/dist/AttestorClient.js.map +1 -1
- package/dist/Credentials.d.ts +574 -0
- package/dist/Credentials.d.ts.map +1 -0
- package/dist/Credentials.js +838 -0
- package/dist/Credentials.js.map +1 -0
- package/dist/Operators.d.ts +60 -0
- package/dist/Operators.d.ts.map +1 -0
- package/dist/Operators.js +38 -0
- package/dist/Operators.js.map +1 -0
- package/dist/Providers.d.ts +13 -0
- package/dist/Providers.d.ts.map +1 -1
- package/dist/Providers.js +20 -1
- package/dist/Providers.js.map +1 -1
- package/dist/Releases.d.ts +51 -0
- package/dist/Releases.d.ts.map +1 -0
- package/dist/Releases.js +72 -0
- package/dist/Releases.js.map +1 -0
- package/dist/ReputationClient.d.ts +47 -3
- package/dist/ReputationClient.d.ts.map +1 -1
- package/dist/ReputationClient.js +204 -78
- package/dist/ReputationClient.js.map +1 -1
- package/dist/ServeProof.d.ts +70 -23
- package/dist/ServeProof.d.ts.map +1 -1
- package/dist/ServeProof.js +94 -35
- package/dist/ServeProof.js.map +1 -1
- package/dist/ServeSession.d.ts +17 -2
- package/dist/ServeSession.d.ts.map +1 -1
- package/dist/ServeSession.js +77 -9
- package/dist/ServeSession.js.map +1 -1
- package/dist/Settings.d.ts +25 -1
- package/dist/Settings.d.ts.map +1 -1
- package/dist/Settings.js +53 -1
- package/dist/Settings.js.map +1 -1
- package/dist/TrustRegistry.d.ts +28 -0
- package/dist/TrustRegistry.d.ts.map +1 -0
- package/dist/TrustRegistry.js +67 -0
- package/dist/TrustRegistry.js.map +1 -0
- package/dist/abi.d.ts +346 -34
- package/dist/abi.d.ts.map +1 -1
- package/dist/abi.js +150 -30
- package/dist/abi.js.map +1 -1
- package/dist/cli/attach.d.ts +79 -0
- package/dist/cli/attach.d.ts.map +1 -0
- package/dist/cli/attach.js +253 -0
- package/dist/cli/attach.js.map +1 -0
- package/dist/cli/commands/cells.d.ts +45 -0
- package/dist/cli/commands/cells.d.ts.map +1 -1
- package/dist/cli/commands/cells.js +77 -0
- package/dist/cli/commands/cells.js.map +1 -1
- package/dist/cli/commands/cred.d.ts +12 -0
- package/dist/cli/commands/cred.d.ts.map +1 -0
- package/dist/cli/commands/cred.js +43 -0
- package/dist/cli/commands/cred.js.map +1 -0
- package/dist/cli/commands/doctor.d.ts.map +1 -1
- package/dist/cli/commands/doctor.js +44 -35
- package/dist/cli/commands/doctor.js.map +1 -1
- package/dist/cli/commands/interactive.d.ts +597 -21
- package/dist/cli/commands/interactive.d.ts.map +1 -1
- package/dist/cli/commands/interactive.js +5082 -1323
- package/dist/cli/commands/interactive.js.map +1 -1
- package/dist/cli/commands/list.d.ts +5 -5
- package/dist/cli/commands/list.d.ts.map +1 -1
- package/dist/cli/commands/list.js +21 -26
- package/dist/cli/commands/list.js.map +1 -1
- package/dist/cli/commands/providers.d.ts +4 -0
- package/dist/cli/commands/providers.d.ts.map +1 -1
- package/dist/cli/commands/providers.js +19 -5
- package/dist/cli/commands/providers.js.map +1 -1
- package/dist/cli/commands/releases.d.ts +13 -0
- package/dist/cli/commands/releases.d.ts.map +1 -0
- package/dist/cli/commands/releases.js +65 -0
- package/dist/cli/commands/releases.js.map +1 -0
- package/dist/cli/commands/settings.d.ts +5 -0
- package/dist/cli/commands/settings.d.ts.map +1 -1
- package/dist/cli/commands/settings.js +70 -24
- package/dist/cli/commands/settings.js.map +1 -1
- package/dist/cli/commands/status.d.ts +2 -1
- package/dist/cli/commands/status.d.ts.map +1 -1
- package/dist/cli/commands/status.js +22 -19
- package/dist/cli/commands/status.js.map +1 -1
- package/dist/cli/config.d.ts +48 -1
- package/dist/cli/config.d.ts.map +1 -1
- package/dist/cli/config.js +114 -5
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/credentials.d.ts +179 -0
- package/dist/cli/credentials.d.ts.map +1 -0
- package/dist/cli/credentials.js +1443 -0
- package/dist/cli/credentials.js.map +1 -0
- package/dist/cli/download.d.ts +21 -0
- package/dist/cli/download.d.ts.map +1 -0
- package/dist/cli/download.js +89 -0
- package/dist/cli/download.js.map +1 -0
- package/dist/cli/env.d.ts +6 -0
- package/dist/cli/env.d.ts.map +1 -1
- package/dist/cli/env.js +18 -6
- package/dist/cli/env.js.map +1 -1
- package/dist/cli/envelope.d.ts +4 -2
- package/dist/cli/envelope.d.ts.map +1 -1
- package/dist/cli/envelope.js +10 -6
- package/dist/cli/envelope.js.map +1 -1
- package/dist/cli/errors.d.ts +45 -1
- package/dist/cli/errors.d.ts.map +1 -1
- package/dist/cli/errors.js +77 -0
- package/dist/cli/errors.js.map +1 -1
- package/dist/cli/inference.d.ts.map +1 -1
- package/dist/cli/inference.js +7 -0
- package/dist/cli/inference.js.map +1 -1
- package/dist/cli/inkView.d.ts +341 -0
- package/dist/cli/inkView.d.ts.map +1 -0
- package/dist/cli/inkView.js +1019 -0
- package/dist/cli/inkView.js.map +1 -0
- package/dist/cli/legacy/modelKey.d.ts +24 -0
- package/dist/cli/legacy/modelKey.d.ts.map +1 -0
- package/dist/cli/legacy/modelKey.js +32 -0
- package/dist/cli/legacy/modelKey.js.map +1 -0
- package/dist/cli/livePrompt.d.ts +212 -0
- package/dist/cli/livePrompt.d.ts.map +1 -0
- package/dist/cli/livePrompt.js +576 -0
- package/dist/cli/livePrompt.js.map +1 -0
- package/dist/cli/main.js +206 -72
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/modelkey.d.ts +64 -0
- package/dist/cli/modelkey.d.ts.map +1 -0
- package/dist/cli/modelkey.js +113 -0
- package/dist/cli/modelkey.js.map +1 -0
- package/dist/cli/outboxSync.d.ts +51 -0
- package/dist/cli/outboxSync.d.ts.map +1 -0
- package/dist/cli/outboxSync.js +210 -0
- package/dist/cli/outboxSync.js.map +1 -0
- package/dist/cli/plain.d.ts +46 -0
- package/dist/cli/plain.d.ts.map +1 -0
- package/dist/cli/plain.js +260 -0
- package/dist/cli/plain.js.map +1 -0
- package/dist/cli/proofs.d.ts +5 -0
- package/dist/cli/proofs.d.ts.map +1 -1
- package/dist/cli/proofs.js +20 -0
- package/dist/cli/proofs.js.map +1 -1
- package/dist/cli/ref.d.ts.map +1 -1
- package/dist/cli/ref.js +3 -2
- package/dist/cli/ref.js.map +1 -1
- package/dist/cli/releaseNotice.d.ts +64 -0
- package/dist/cli/releaseNotice.d.ts.map +1 -0
- package/dist/cli/releaseNotice.js +194 -0
- package/dist/cli/releaseNotice.js.map +1 -0
- package/dist/cli/sdk.d.ts +18 -0
- package/dist/cli/sdk.d.ts.map +1 -1
- package/dist/cli/sdk.js +99 -1
- package/dist/cli/sdk.js.map +1 -1
- package/dist/cli/settings.d.ts +90 -9
- package/dist/cli/settings.d.ts.map +1 -1
- package/dist/cli/settings.js +273 -21
- package/dist/cli/settings.js.map +1 -1
- package/dist/cli/textfit.d.ts +28 -0
- package/dist/cli/textfit.d.ts.map +1 -0
- package/dist/cli/textfit.js +111 -0
- package/dist/cli/textfit.js.map +1 -0
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/context.d.ts +26 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +1 -0
- package/dist/context.js.map +1 -1
- package/dist/index.d.ts +19 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +35 -2
- package/dist/index.js.map +1 -1
- package/dist/legacy/modelKey.d.ts +67 -0
- package/dist/legacy/modelKey.d.ts.map +1 -0
- package/dist/legacy/modelKey.js +80 -0
- package/dist/legacy/modelKey.js.map +1 -0
- package/dist/legacy/serveProofV1.d.ts +56 -0
- package/dist/legacy/serveProofV1.d.ts.map +1 -0
- package/dist/legacy/serveProofV1.js +91 -0
- package/dist/legacy/serveProofV1.js.map +1 -0
- package/dist/provider-catalog.json +3 -2
- package/dist/secretEnv.d.ts +18 -3
- package/dist/secretEnv.d.ts.map +1 -1
- package/dist/secretEnv.js +16 -2
- package/dist/secretEnv.js.map +1 -1
- package/dist/types.d.ts +63 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/viemErrors.d.ts +30 -0
- package/dist/viemErrors.d.ts.map +1 -0
- package/dist/viemErrors.js +36 -0
- package/dist/viemErrors.js.map +1 -0
- package/package.json +5 -1
- package/src/AgentClient.ts +622 -68
- package/src/AgenticID.ts +345 -56
- package/src/AttestorClient.ts +330 -83
- package/src/Credentials.ts +1027 -0
- package/src/Operators.ts +71 -0
- package/src/Providers.ts +20 -0
- package/src/Releases.ts +95 -0
- package/src/ReputationClient.ts +231 -79
- package/src/ServeProof.ts +123 -39
- package/src/ServeSession.ts +91 -9
- package/src/Settings.ts +61 -1
- package/src/TrustRegistry.ts +75 -0
- package/src/abi.ts +153 -30
- package/src/cli/attach.ts +257 -0
- package/src/cli/commands/cells.ts +104 -0
- package/src/cli/commands/cred.ts +44 -0
- package/src/cli/commands/doctor.ts +45 -37
- package/src/cli/commands/interactive.ts +4120 -664
- package/src/cli/commands/list.ts +21 -30
- package/src/cli/commands/providers.ts +17 -4
- package/src/cli/commands/releases.ts +60 -0
- package/src/cli/commands/settings.ts +75 -28
- package/src/cli/commands/status.ts +24 -21
- package/src/cli/config.ts +119 -4
- package/src/cli/credentials.ts +1379 -0
- package/src/cli/download.ts +80 -0
- package/src/cli/env.ts +22 -7
- package/src/cli/envelope.ts +10 -6
- package/src/cli/errors.ts +92 -0
- package/src/cli/inference.ts +8 -1
- package/src/cli/inkView.ts +969 -0
- package/src/cli/legacy/modelKey.ts +35 -0
- package/src/cli/livePrompt.ts +615 -0
- package/src/cli/main.ts +206 -76
- package/src/cli/modelkey.ts +124 -0
- package/src/cli/outboxSync.ts +231 -0
- package/src/cli/plain.ts +260 -0
- package/src/cli/proofs.ts +27 -0
- package/src/cli/ref.ts +5 -4
- package/src/cli/releaseNotice.ts +200 -0
- package/src/cli/sdk.ts +87 -7
- package/src/cli/settings.ts +275 -25
- package/src/cli/textfit.ts +95 -0
- package/src/constants.ts +1 -1
- package/src/context.ts +28 -0
- package/src/index.ts +50 -7
- package/src/legacy/modelKey.ts +80 -0
- package/src/legacy/serveProofV1.ts +124 -0
- package/src/provider-catalog.json +3 -2
- package/src/secretEnv.ts +18 -3
- package/src/types.ts +60 -1
- package/src/viemErrors.ts +39 -0
|
@@ -0,0 +1,1443 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @file credentials.ts
|
|
4
|
+
* @description The owner's credentials for one agent, as the CLI speaks them:
|
|
5
|
+
* the `key=value` grammar of `cred <agent> set`, the rendering of a stored
|
|
6
|
+
* set, of pending requests and of the audit log, and {@link credOp}, the one
|
|
7
|
+
* operation `0g-agentdna cred`, the REPL's `cred <id>` and the session's
|
|
8
|
+
* `/cred` all run — so the three can never drift.
|
|
9
|
+
*
|
|
10
|
+
* A value is never an argument: it is read from stdin (piped) or typed at a
|
|
11
|
+
* prompt that does not echo it, so it stays out of shell history and process
|
|
12
|
+
* listings. The SDK seals it to the agent before anything leaves the machine.
|
|
13
|
+
*/
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.CRED_PRESETS = exports.CRED_USAGE = exports.CRED_KEYS = void 0;
|
|
16
|
+
exports.renderPresets = renderPresets;
|
|
17
|
+
exports.parseCredArgs = parseCredArgs;
|
|
18
|
+
exports.checkCredName = checkCredName;
|
|
19
|
+
exports.applyCredPatch = applyCredPatch;
|
|
20
|
+
exports.renderCredentials = renderCredentials;
|
|
21
|
+
exports.ensureModelKey = ensureModelKey;
|
|
22
|
+
exports.renderPending = renderPending;
|
|
23
|
+
exports.printable = printable;
|
|
24
|
+
exports.renderAudit = renderAudit;
|
|
25
|
+
exports.cachedCredNames = cachedCredNames;
|
|
26
|
+
exports.readConfirm = readConfirm;
|
|
27
|
+
exports.commandKeyPrompt = commandKeyPrompt;
|
|
28
|
+
exports.credOp = credOp;
|
|
29
|
+
exports.answerPending = answerPending;
|
|
30
|
+
exports.credOwnerOp = credOwnerOp;
|
|
31
|
+
exports.readSecret = readSecret;
|
|
32
|
+
const viem_1 = require("viem");
|
|
33
|
+
const Credentials_1 = require("../Credentials");
|
|
34
|
+
const errors_1 = require("./errors");
|
|
35
|
+
const modelkey_1 = require("./modelkey");
|
|
36
|
+
const node_readline_1 = require("node:readline");
|
|
37
|
+
const envelope_1 = require("./envelope");
|
|
38
|
+
const config_1 = require("./config");
|
|
39
|
+
/** The keys `cred <agent> set <name>` takes. */
|
|
40
|
+
exports.CRED_KEYS = [
|
|
41
|
+
'preset', 'host', 'header', 'basic', 'query', 'body', 'path', 'use', 'signer', 'token', 'writeback', 'reveal', 'expires', 'desc',
|
|
42
|
+
'token_url', 'client_id', 'client_secret', 'scope', 'api_host',
|
|
43
|
+
];
|
|
44
|
+
const SET_USAGE = "cred <agent> set <name> [preset=<name>] [host=a.example,b.example] [header='Authorization: Bearer {v}'] [basic=<user>] [query=<param>] [body=<field>] [path=yes] [use=inject|token_only|sign] [signer=<json>] [token=<json>] [writeback=yes|no] [reveal=yes|no] [expires=<YYYY-MM-DD|unix>] [desc=…]";
|
|
45
|
+
/** The token-request presets: OAuth 2.0 refresh (RFC 6749 §6) and client credentials (§4.4). */
|
|
46
|
+
const OAUTH2_PRESETS = ['oauth2-refresh', 'oauth2-client'];
|
|
47
|
+
const OAUTH2_USAGE = 'cred <agent> set <name> preset=oauth2-refresh|oauth2-client token_url=https://… client_id=… api_host=api.example [client_secret=<entry>] [scope=…]';
|
|
48
|
+
const MODEL_USAGE = 'cred <agent> set model [provider=<id>]';
|
|
49
|
+
exports.CRED_USAGE = `usage:
|
|
50
|
+
cred <agent> list the agent's credentials (never values)
|
|
51
|
+
${SET_USAGE}
|
|
52
|
+
add or change one; the value is read from stdin or a prompt that does not echo
|
|
53
|
+
${OAUTH2_USAGE}
|
|
54
|
+
a refresh token (oauth2-refresh) or a client secret (oauth2-client) that sealed
|
|
55
|
+
trades for access tokens; the agent uses [[credential:derived:<name>]] on api_host
|
|
56
|
+
cred presets the presets, and where to create each key
|
|
57
|
+
cred <agent> rm <name> remove one (revoke it at its provider as well)
|
|
58
|
+
${MODEL_USAGE}
|
|
59
|
+
the agent's model key for a provider (default: the one its settings use);
|
|
60
|
+
the settings choose which provider's key is used, so keys for several may be kept
|
|
61
|
+
cred <agent> rm model [provider=<id>]
|
|
62
|
+
remove a model key
|
|
63
|
+
cred <agent> connect <name> [<mcp-url>] [client_id=… client_secret_entry=… scope=a,b]
|
|
64
|
+
connect an MCP server to the agent (you log in through a link); sealed keeps the tokens
|
|
65
|
+
cred <agent> disconnect <name> revoke that connection at the server (when it offers that) and remove it
|
|
66
|
+
cred <agent> reveal <name> on|off let the agent read the value itself without asking each time
|
|
67
|
+
cred <agent> pending requests waiting for you
|
|
68
|
+
cred <agent> approve [<id>] approve one request once (an id prefix; none when only one waits)
|
|
69
|
+
cred <agent> deny [<id>] refuse one request
|
|
70
|
+
cred <agent> log [n] what the agent did with its credentials (last n, default 50)
|
|
71
|
+
cred pending pending counts across every agent you own
|
|
72
|
+
cred notify [<email>|off] where you are emailed when an agent waits for you`;
|
|
73
|
+
const BEARER = { kind: 'header', name: 'Authorization', template: 'Bearer {v}' };
|
|
74
|
+
/**
|
|
75
|
+
* Where common providers take their key: each provider's documented hosts
|
|
76
|
+
* and headers (checked 2026-11), and for git hosts the Basic username that
|
|
77
|
+
* goes with a token as the password.
|
|
78
|
+
*/
|
|
79
|
+
exports.CRED_PRESETS = {
|
|
80
|
+
github: {
|
|
81
|
+
hosts: ['api.github.com', 'uploads.github.com', 'github.com'],
|
|
82
|
+
// GitHub does not use the Basic username to authenticate a token, but it must not be empty.
|
|
83
|
+
positions: [BEARER, { kind: 'basic', username: 'x-access-token' }],
|
|
84
|
+
description: 'GitHub token (REST API and git over HTTPS)',
|
|
85
|
+
create: 'https://github.com/settings/personal-access-tokens/new',
|
|
86
|
+
tip: 'a fine-grained token, limited to the repositories and permissions the agent needs; git uses it with no setup',
|
|
87
|
+
},
|
|
88
|
+
gitlab: {
|
|
89
|
+
hosts: ['gitlab.com'],
|
|
90
|
+
positions: [{ kind: 'header', name: 'PRIVATE-TOKEN', template: '{v}' }, BEARER, { kind: 'basic', username: 'oauth2' }],
|
|
91
|
+
description: 'GitLab token (REST API and git over HTTPS)',
|
|
92
|
+
create: 'https://gitlab.com/-/user_settings/personal_access_tokens',
|
|
93
|
+
tip: 'a fine-grained token, or the narrowest scopes (read_api, read_repository, write_repository); for one project, a project access token',
|
|
94
|
+
},
|
|
95
|
+
huggingface: {
|
|
96
|
+
hosts: ['huggingface.co', 'router.huggingface.co'],
|
|
97
|
+
positions: [BEARER],
|
|
98
|
+
description: 'Hugging Face token',
|
|
99
|
+
create: 'https://huggingface.co/settings/tokens',
|
|
100
|
+
tip: 'a fine-grained token; the read role if the agent only reads',
|
|
101
|
+
},
|
|
102
|
+
slack: {
|
|
103
|
+
hosts: ['slack.com'],
|
|
104
|
+
positions: [BEARER],
|
|
105
|
+
description: 'Slack bot token',
|
|
106
|
+
create: 'https://api.slack.com/apps',
|
|
107
|
+
tip: 'an app with only the bot scopes it needs, installed to the workspace; the bot token (xoxb-) is under OAuth & Permissions',
|
|
108
|
+
},
|
|
109
|
+
stripe: {
|
|
110
|
+
hosts: ['api.stripe.com'],
|
|
111
|
+
positions: [BEARER],
|
|
112
|
+
description: 'Stripe API key',
|
|
113
|
+
create: 'https://dashboard.stripe.com/apikeys',
|
|
114
|
+
tip: 'a restricted key (rk_) allowing only the resources it needs',
|
|
115
|
+
},
|
|
116
|
+
gemini: {
|
|
117
|
+
hosts: ['generativelanguage.googleapis.com'],
|
|
118
|
+
positions: [{ kind: 'header', name: 'x-goog-api-key', template: '{v}' }, BEARER],
|
|
119
|
+
description: 'Google Gemini API key',
|
|
120
|
+
create: 'https://aistudio.google.com/apikey',
|
|
121
|
+
tip: 'AI Studio keys are restricted to the Gemini API by default',
|
|
122
|
+
},
|
|
123
|
+
openai: {
|
|
124
|
+
hosts: ['api.openai.com'],
|
|
125
|
+
positions: [BEARER],
|
|
126
|
+
description: 'OpenAI API key',
|
|
127
|
+
create: 'https://platform.openai.com/settings/organization/api-keys',
|
|
128
|
+
tip: 'a key for a project of its own, with only the permissions it needs',
|
|
129
|
+
},
|
|
130
|
+
anthropic: {
|
|
131
|
+
hosts: ['api.anthropic.com'],
|
|
132
|
+
positions: [BEARER, { kind: 'header', name: 'x-api-key', template: '{v}' }],
|
|
133
|
+
description: 'Anthropic API key',
|
|
134
|
+
create: 'https://platform.claude.com/settings/keys',
|
|
135
|
+
tip: 'a key scoped to one workspace, with an expiry; requests also need anthropic-version, which the agent adds',
|
|
136
|
+
},
|
|
137
|
+
openrouter: {
|
|
138
|
+
hosts: ['openrouter.ai'],
|
|
139
|
+
positions: [BEARER],
|
|
140
|
+
description: 'OpenRouter API key',
|
|
141
|
+
create: 'https://openrouter.ai/settings/keys',
|
|
142
|
+
tip: 'set a credit limit on the key',
|
|
143
|
+
},
|
|
144
|
+
deepseek: {
|
|
145
|
+
hosts: ['api.deepseek.com'],
|
|
146
|
+
positions: [BEARER, { kind: 'header', name: 'x-api-key', template: '{v}' }],
|
|
147
|
+
description: 'DeepSeek API key',
|
|
148
|
+
create: 'https://platform.deepseek.com/api_keys',
|
|
149
|
+
tip: 'a key for the agent alone, so you can revoke it on its own',
|
|
150
|
+
},
|
|
151
|
+
npm: {
|
|
152
|
+
hosts: ['registry.npmjs.org'],
|
|
153
|
+
positions: [BEARER],
|
|
154
|
+
description: 'npm registry token',
|
|
155
|
+
create: 'npmjs.com → your avatar → Access Tokens',
|
|
156
|
+
tip: 'a granular token: read-only unless it publishes, limited to its packages, with an expiry',
|
|
157
|
+
},
|
|
158
|
+
notion: {
|
|
159
|
+
hosts: ['api.notion.com'],
|
|
160
|
+
positions: [BEARER],
|
|
161
|
+
description: 'Notion integration token',
|
|
162
|
+
create: 'https://app.notion.com/developers/connections',
|
|
163
|
+
tip: 'share only the pages it needs (child pages inherit access); requests also need Notion-Version, which the agent adds',
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
/** `cred presets`: every preset, where to create its key, and the OAuth 2.0 ones. */
|
|
167
|
+
function renderPresets() {
|
|
168
|
+
const lines = [];
|
|
169
|
+
for (const [name, p] of Object.entries(exports.CRED_PRESETS)) {
|
|
170
|
+
lines.push(`${name.padEnd(12)} ${p.description}`);
|
|
171
|
+
lines.push(`${''.padEnd(12)} ${p.hosts.join(', ')} — ${p.positions.map(positionText).join(' · ')}`);
|
|
172
|
+
lines.push(`${''.padEnd(12)} create: ${p.create}`);
|
|
173
|
+
lines.push(`${''.padEnd(12)} ${p.tip}`);
|
|
174
|
+
}
|
|
175
|
+
lines.push(`oauth2-refresh a refresh token sealed trades for access tokens (it rotates and is written back)`);
|
|
176
|
+
lines.push(`oauth2-client a client secret sealed trades for access tokens (client credentials)`);
|
|
177
|
+
lines.push(` ${OAUTH2_USAGE}`);
|
|
178
|
+
return lines;
|
|
179
|
+
}
|
|
180
|
+
const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
|
|
181
|
+
const FORBIDDEN_HEADERS = new Set(['host', 'content-length', 'transfer-encoding', 'cookie']);
|
|
182
|
+
function usage(message, remedy = SET_USAGE) {
|
|
183
|
+
return new errors_1.CliError('BAD_FLAG', message, { remedy });
|
|
184
|
+
}
|
|
185
|
+
const CONNECT_USAGE = 'cred <agent> connect <name> [<mcp-url>] [client_id=… client_secret_entry=… scope=a,b] (a connection already defined: just its name)';
|
|
186
|
+
function yesNo(key, raw) {
|
|
187
|
+
if (/^(yes|on|true|1)$/i.test(raw))
|
|
188
|
+
return true;
|
|
189
|
+
if (/^(no|off|false|0)$/i.test(raw))
|
|
190
|
+
return false;
|
|
191
|
+
throw usage(`${key}= takes yes or no, not "${raw}"`);
|
|
192
|
+
}
|
|
193
|
+
/** `YYYY-MM-DD` (UTC midnight) or Unix seconds → Unix seconds. */
|
|
194
|
+
function parseExpiry(raw) {
|
|
195
|
+
if (/^\d+$/.test(raw))
|
|
196
|
+
return Number(raw);
|
|
197
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) {
|
|
198
|
+
const ms = Date.parse(`${raw}T00:00:00Z`);
|
|
199
|
+
if (!Number.isNaN(ms))
|
|
200
|
+
return Math.floor(ms / 1000);
|
|
201
|
+
}
|
|
202
|
+
throw usage(`expires= takes YYYY-MM-DD or Unix seconds, not "${raw}"`);
|
|
203
|
+
}
|
|
204
|
+
/** Parse the assignments of `set <name> k=v …`. Usage errors only; no I/O. */
|
|
205
|
+
function parseCredArgs(args) {
|
|
206
|
+
const out = {};
|
|
207
|
+
const add = (k, v) => {
|
|
208
|
+
out[k] = [...(out[k] ?? []), ...v];
|
|
209
|
+
};
|
|
210
|
+
for (const arg of args) {
|
|
211
|
+
const eq = arg.indexOf('=');
|
|
212
|
+
const key = eq > 0 ? arg.slice(0, eq) : arg;
|
|
213
|
+
const raw = eq > 0 ? arg.slice(eq + 1) : '';
|
|
214
|
+
switch (key) {
|
|
215
|
+
case 'preset': {
|
|
216
|
+
if (OAUTH2_PRESETS.includes(raw)) {
|
|
217
|
+
out.oauth2 = { ...out.oauth2, preset: raw };
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
const p = exports.CRED_PRESETS[raw];
|
|
221
|
+
if (!p)
|
|
222
|
+
throw usage(`unknown preset "${raw}" (known: ${[...Object.keys(exports.CRED_PRESETS), ...OAUTH2_PRESETS].join(', ')})`);
|
|
223
|
+
add('hosts', p.hosts);
|
|
224
|
+
add('positions', p.positions);
|
|
225
|
+
out.presetDescription ?? (out.presetDescription = p.description);
|
|
226
|
+
out.preset ?? (out.preset = raw);
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
case 'host':
|
|
230
|
+
for (const h of raw.split(',').map((x) => x.trim().toLowerCase()).filter(Boolean)) {
|
|
231
|
+
if (!/^[a-z0-9.-]+(:\d+)?$/.test(h))
|
|
232
|
+
throw usage(`not a host: "${h}"`);
|
|
233
|
+
add('hosts', [h]);
|
|
234
|
+
}
|
|
235
|
+
break;
|
|
236
|
+
case 'header': {
|
|
237
|
+
const colon = raw.indexOf(':');
|
|
238
|
+
const hname = colon > 0 ? raw.slice(0, colon).trim() : '';
|
|
239
|
+
const template = colon > 0 ? raw.slice(colon + 1).trim() : '';
|
|
240
|
+
if (!hname || template.split('{v}').length !== 2) {
|
|
241
|
+
throw usage(`header= takes 'Name: template' with one {v}, e.g. header='Authorization: Bearer {v}'`);
|
|
242
|
+
}
|
|
243
|
+
if (FORBIDDEN_HEADERS.has(hname.toLowerCase()) || hname.toLowerCase().startsWith('proxy-')) {
|
|
244
|
+
throw usage(`header ${hname} may not carry a credential`);
|
|
245
|
+
}
|
|
246
|
+
add('positions', [{ kind: 'header', name: hname, template }]);
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
case 'basic':
|
|
250
|
+
if (!raw || raw.includes(':'))
|
|
251
|
+
throw usage('basic= takes the fixed username (no colon); the value is the password');
|
|
252
|
+
add('positions', [{ kind: 'basic', username: raw }]);
|
|
253
|
+
break;
|
|
254
|
+
case 'query':
|
|
255
|
+
if (!raw)
|
|
256
|
+
throw usage('query= takes the parameter name');
|
|
257
|
+
add('positions', [{ kind: 'query', param: raw }]);
|
|
258
|
+
break;
|
|
259
|
+
case 'body':
|
|
260
|
+
if (!raw)
|
|
261
|
+
throw usage('body= takes the top-level JSON or form field');
|
|
262
|
+
add('positions', [{ kind: 'body', field: raw }]);
|
|
263
|
+
break;
|
|
264
|
+
case 'path':
|
|
265
|
+
if (eq < 0 || yesNo('path', raw))
|
|
266
|
+
add('positions', [{ kind: 'path' }]);
|
|
267
|
+
break;
|
|
268
|
+
case 'use':
|
|
269
|
+
if (raw !== 'inject' && raw !== 'token_only' && raw !== 'sign')
|
|
270
|
+
throw usage(`use= takes inject, token_only or sign, not "${raw}"`);
|
|
271
|
+
out.use = raw;
|
|
272
|
+
break;
|
|
273
|
+
case 'signer': {
|
|
274
|
+
let v;
|
|
275
|
+
try {
|
|
276
|
+
v = JSON.parse(raw);
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
throw usage(`signer= takes JSON, e.g. signer='{"method":"sigv4","access_key_id":"AKIA…","region":"us-east-1","service":"s3"}'`);
|
|
280
|
+
}
|
|
281
|
+
const m = v?.method;
|
|
282
|
+
if (m !== 'sigv4' && m !== 'hmac' && m !== 'jwt' && m !== 'wallet')
|
|
283
|
+
throw usage('signer method is sigv4, hmac, jwt or wallet');
|
|
284
|
+
out.signer = v;
|
|
285
|
+
break;
|
|
286
|
+
}
|
|
287
|
+
case 'token': {
|
|
288
|
+
let v;
|
|
289
|
+
try {
|
|
290
|
+
v = JSON.parse(raw);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
throw usage(`token= takes the token request as JSON: {"url","encoding","fields","take",…}`);
|
|
294
|
+
}
|
|
295
|
+
out.tokenRequest = checkTokenRequest(v);
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
case 'writeback':
|
|
299
|
+
out.writeback = yesNo('writeback', raw);
|
|
300
|
+
break;
|
|
301
|
+
case 'token_url':
|
|
302
|
+
case 'client_id':
|
|
303
|
+
case 'client_secret':
|
|
304
|
+
case 'scope':
|
|
305
|
+
case 'api_host': {
|
|
306
|
+
if (!raw)
|
|
307
|
+
throw usage(`${key}= takes a value`);
|
|
308
|
+
const o = (out.oauth2 ?? (out.oauth2 = {}));
|
|
309
|
+
if (key === 'token_url')
|
|
310
|
+
o.tokenUrl = raw;
|
|
311
|
+
else if (key === 'client_id')
|
|
312
|
+
o.clientId = raw;
|
|
313
|
+
else if (key === 'client_secret')
|
|
314
|
+
o.clientSecretEntry = checkCredName(raw);
|
|
315
|
+
else if (key === 'scope')
|
|
316
|
+
o.scope = raw;
|
|
317
|
+
else {
|
|
318
|
+
for (const h of raw.split(',').map((x) => x.trim().toLowerCase()).filter(Boolean)) {
|
|
319
|
+
if (!/^[a-z0-9.-]+(:\d+)?$/.test(h))
|
|
320
|
+
throw usage(`not a host: "${h}"`);
|
|
321
|
+
o.apiHosts = [...(o.apiHosts ?? []), h];
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
case 'reveal':
|
|
327
|
+
out.allowReveal = yesNo('reveal', raw);
|
|
328
|
+
break;
|
|
329
|
+
case 'expires':
|
|
330
|
+
out.expiresAt = raw ? parseExpiry(raw) : null;
|
|
331
|
+
break;
|
|
332
|
+
case 'desc':
|
|
333
|
+
out.description = raw || null;
|
|
334
|
+
break;
|
|
335
|
+
default:
|
|
336
|
+
throw usage(`unknown key "${key}" (keys: ${exports.CRED_KEYS.join(', ')})`);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return out;
|
|
340
|
+
}
|
|
341
|
+
/** The shape sealed requires of a token request (sealed/internal/credentials), checked before anything is signed. */
|
|
342
|
+
function checkTokenRequest(v) {
|
|
343
|
+
const t = v;
|
|
344
|
+
let url;
|
|
345
|
+
try {
|
|
346
|
+
url = typeof t?.url === 'string' ? new URL(t.url) : undefined;
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
url = undefined;
|
|
350
|
+
}
|
|
351
|
+
if (!t || !url || url.protocol !== 'https:')
|
|
352
|
+
throw usage('token= needs "url", an https token endpoint');
|
|
353
|
+
if (t.encoding !== undefined && t.encoding !== 'form' && t.encoding !== 'json')
|
|
354
|
+
throw usage('token= "encoding" is form or json');
|
|
355
|
+
if (!t.fields || typeof t.fields !== 'object' || Object.values(t.fields).some((x) => typeof x !== 'string')) {
|
|
356
|
+
throw usage('token= needs "fields": an object of field → template ({v} is this value, {cred:<name>} another entry)');
|
|
357
|
+
}
|
|
358
|
+
if (!Array.isArray(t.take) || !t.take.length || t.take.some((x) => !x || typeof x.field !== 'string' || !Array.isArray(x.hosts) || !Array.isArray(x.positions))) {
|
|
359
|
+
throw usage('token= needs "take": [{ "field", "name"?, "hosts", "positions", "expires_in_field"? }, …]');
|
|
360
|
+
}
|
|
361
|
+
return t;
|
|
362
|
+
}
|
|
363
|
+
/** The token request an OAuth 2.0 preset stands for. */
|
|
364
|
+
function oauth2Template(name, o) {
|
|
365
|
+
if (!o.preset)
|
|
366
|
+
throw usage(`token_url=, client_id=, client_secret=, scope= and api_host= go with preset=oauth2-refresh or preset=oauth2-client`);
|
|
367
|
+
let url;
|
|
368
|
+
try {
|
|
369
|
+
url = o.tokenUrl ? new URL(o.tokenUrl) : undefined;
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
url = undefined;
|
|
373
|
+
}
|
|
374
|
+
if (!url || url.protocol !== 'https:')
|
|
375
|
+
throw new errors_1.CliError('BAD_FLAG', `${o.preset} needs token_url=, the provider's https token endpoint`, { remedy: OAUTH2_USAGE });
|
|
376
|
+
if (!o.clientId)
|
|
377
|
+
throw new errors_1.CliError('BAD_FLAG', `${o.preset} needs client_id=`, { remedy: OAUTH2_USAGE });
|
|
378
|
+
if (!o.apiHosts?.length)
|
|
379
|
+
throw new errors_1.CliError('BAD_FLAG', `${o.preset} needs api_host=, where the agent uses the access token`, { remedy: OAUTH2_USAGE });
|
|
380
|
+
const refresh = o.preset === 'oauth2-refresh';
|
|
381
|
+
if (!refresh && o.clientSecretEntry)
|
|
382
|
+
throw new errors_1.CliError('BAD_FLAG', 'with oauth2-client the value you enter is the client secret; drop client_secret=', { remedy: OAUTH2_USAGE });
|
|
383
|
+
const fields = refresh
|
|
384
|
+
? { grant_type: 'refresh_token', refresh_token: '{v}', client_id: o.clientId }
|
|
385
|
+
: { grant_type: 'client_credentials', client_id: o.clientId, client_secret: '{v}' };
|
|
386
|
+
if (o.clientSecretEntry)
|
|
387
|
+
fields.client_secret = `{cred:${o.clientSecretEntry}}`;
|
|
388
|
+
if (o.scope)
|
|
389
|
+
fields.scope = o.scope;
|
|
390
|
+
return {
|
|
391
|
+
use: 'token_only',
|
|
392
|
+
// A provider that rotates refresh tokens retires the old one at once:
|
|
393
|
+
// the new one must outlive a restart.
|
|
394
|
+
writeback: refresh,
|
|
395
|
+
tokenRequest: {
|
|
396
|
+
url: o.tokenUrl,
|
|
397
|
+
encoding: 'form',
|
|
398
|
+
fields,
|
|
399
|
+
// A scope the owner sets is fixed; with none, the agent may ask for one.
|
|
400
|
+
params: o.scope ? [] : ['scope'],
|
|
401
|
+
take: [{ field: 'access_token', name, hosts: o.apiHosts, positions: [{ kind: 'header', name: 'Authorization', template: 'Bearer {v}' }], expires_in_field: 'expires_in' }],
|
|
402
|
+
...(refresh ? { rotate_field: 'refresh_token' } : {}),
|
|
403
|
+
},
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
/** Check a name against the placeholder grammar sealed enforces; remedy is the usage shown when it fails. */
|
|
407
|
+
function checkCredName(name, remedy = SET_USAGE) {
|
|
408
|
+
if (!name || !NAME_RE.test(name)) {
|
|
409
|
+
throw usage(name ? `not a credential name: "${name}" (lowercase letters, digits, . _ -; up to 63)` : 'missing <name>', remedy);
|
|
410
|
+
}
|
|
411
|
+
return name;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* The entry a patch describes. With `base` (the stored entry of that name)
|
|
415
|
+
* the patch changes it: `host=` replaces the hosts, any position key replaces
|
|
416
|
+
* the positions, everything else is kept.
|
|
417
|
+
*/
|
|
418
|
+
function applyCredPatch(name, patch, base) {
|
|
419
|
+
const out = base ? { ...base, name } : { name, hosts: [], positions: [] };
|
|
420
|
+
if (patch.hosts)
|
|
421
|
+
out.hosts = [...new Set(patch.hosts)];
|
|
422
|
+
if (patch.positions)
|
|
423
|
+
out.positions = patch.positions;
|
|
424
|
+
if (patch.use)
|
|
425
|
+
out.use = patch.use;
|
|
426
|
+
if (patch.signer)
|
|
427
|
+
out.signer = patch.signer;
|
|
428
|
+
if (patch.oauth2) {
|
|
429
|
+
if (patch.tokenRequest)
|
|
430
|
+
throw usage('give either token= or an oauth2 preset, not both');
|
|
431
|
+
const t = oauth2Template(name, patch.oauth2);
|
|
432
|
+
out.use = t.use;
|
|
433
|
+
out.writeback = t.writeback;
|
|
434
|
+
out.tokenRequest = t.tokenRequest;
|
|
435
|
+
}
|
|
436
|
+
if (patch.tokenRequest)
|
|
437
|
+
out.tokenRequest = patch.tokenRequest;
|
|
438
|
+
if (patch.writeback !== undefined)
|
|
439
|
+
out.writeback = patch.writeback;
|
|
440
|
+
if (patch.allowReveal !== undefined)
|
|
441
|
+
out.allowReveal = patch.allowReveal;
|
|
442
|
+
if (patch.expiresAt === null)
|
|
443
|
+
delete out.expiresAt;
|
|
444
|
+
else if (patch.expiresAt !== undefined)
|
|
445
|
+
out.expiresAt = patch.expiresAt;
|
|
446
|
+
if (patch.description === null)
|
|
447
|
+
delete out.description;
|
|
448
|
+
else if (patch.description !== undefined)
|
|
449
|
+
out.description = patch.description;
|
|
450
|
+
if (!out.description && patch.presetDescription)
|
|
451
|
+
out.description = patch.presetDescription;
|
|
452
|
+
const use = out.use ?? 'inject';
|
|
453
|
+
if (use !== 'sign')
|
|
454
|
+
delete out.signer;
|
|
455
|
+
if (use === 'sign' && !out.signer)
|
|
456
|
+
throw usage(`${name} with use=sign needs signer=<json>`);
|
|
457
|
+
const method = out.signer?.method;
|
|
458
|
+
const needsHosts = use === 'inject' || method === 'sigv4' || method === 'hmac' || method === 'jwt';
|
|
459
|
+
const needsPositions = use === 'inject' || method === 'jwt';
|
|
460
|
+
if (needsHosts && !out.hosts.length)
|
|
461
|
+
throw usage(`${name} needs at least one host= (or a preset=)`);
|
|
462
|
+
if (needsPositions && !out.positions.length)
|
|
463
|
+
throw usage(`${name} needs a position: header=, basic=, query=, body= or path=yes (or a preset=)`);
|
|
464
|
+
return out;
|
|
465
|
+
}
|
|
466
|
+
function positionText(p) {
|
|
467
|
+
switch (p.kind) {
|
|
468
|
+
case 'header': return `header ${p.name}: ${p.template}`;
|
|
469
|
+
case 'basic': return `basic ${p.username}:{v}`;
|
|
470
|
+
case 'query': return `query ${p.param}={v}`;
|
|
471
|
+
case 'path': return 'path';
|
|
472
|
+
case 'body': return `body ${p.field}`;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
function dateText(unix) {
|
|
476
|
+
return new Date(unix * 1000).toISOString().replace('T', ' ').replace(/\.\d+Z$/, 'Z');
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* One block per credential the agent uses (what it is for, where it may go,
|
|
480
|
+
* how it may be used), then the model keys, which sealed uses itself. With
|
|
481
|
+
* `model` (what the running agent says), which model key is in use.
|
|
482
|
+
*/
|
|
483
|
+
function renderCredentials(defs, version, logins, model) {
|
|
484
|
+
const keys = defs.filter((d) => d.inference);
|
|
485
|
+
const forAgent = defs.filter((d) => !d.inference);
|
|
486
|
+
// The set's version is the compare-and-swap counter: --json carries it;
|
|
487
|
+
// the owner reads the entries.
|
|
488
|
+
void version;
|
|
489
|
+
const lines = forAgent.length || keys.length ? [] : ['no credentials'];
|
|
490
|
+
for (const d of forAgent) {
|
|
491
|
+
if (lines.length)
|
|
492
|
+
lines.push('');
|
|
493
|
+
lines.push(`${d.name} → [[credential:${d.name}]]${d.description ? ` ${d.description}` : ''}`);
|
|
494
|
+
lines.push(` hosts ${d.hosts.join(', ') || '—'}`);
|
|
495
|
+
lines.push(` positions ${d.positions.map(positionText).join(' · ') || '—'}`);
|
|
496
|
+
const flags = [
|
|
497
|
+
d.use !== 'inject' ? `use ${d.use}` : '',
|
|
498
|
+
d.signer ? `signs ${d.signer.method}${d.signer.method === 'sigv4' ? ` (${d.signer.access_key_id}, ${d.signer.region}/${d.signer.service})` : ''}` : '',
|
|
499
|
+
d.allow_reveal ? 'reveal allowed' : '',
|
|
500
|
+
d.writeback ? 'writeback' : '',
|
|
501
|
+
d.token_request ? `token request → ${d.token_request.url}${d.token_request.rotate_field ? ' (rotates)' : ''}` : '',
|
|
502
|
+
d.expires_at ? `expires ${dateText(d.expires_at)}` : '',
|
|
503
|
+
].filter(Boolean);
|
|
504
|
+
if (flags.length)
|
|
505
|
+
lines.push(` ${flags.join(' · ')}`);
|
|
506
|
+
if (d.mcp && logins !== undefined) {
|
|
507
|
+
const st = logins?.[d.name];
|
|
508
|
+
lines.push(` connected ${logins === null ? 'unknown — the agent is not running'
|
|
509
|
+
: st?.loggedInAt ? dateText(st.loggedInAt)
|
|
510
|
+
: `not yet — ${(0, errors_1.agentCmd)('cred', `connect ${d.name}`)}`}`);
|
|
511
|
+
}
|
|
512
|
+
for (const t of d.token_request?.take ?? []) {
|
|
513
|
+
const derived = derivedName(d.name, t);
|
|
514
|
+
lines.push(` gives [[credential:${derived}]] on ${t.hosts.join(', ') || '—'} (${t.positions.map(positionText).join(' · ') || '—'})`);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
if (keys.length || model !== undefined)
|
|
518
|
+
lines.push(...renderModelKeys(keys, model).slice(lines.length ? 0 : 1));
|
|
519
|
+
return lines;
|
|
520
|
+
}
|
|
521
|
+
/** The model keys, and which one the framework uses. */
|
|
522
|
+
function renderModelKeys(keys, model) {
|
|
523
|
+
const lines = ['', "model keys (the agent's settings choose which one is used)"];
|
|
524
|
+
const inUse = model && model !== 'old' ? model : undefined;
|
|
525
|
+
const width = Math.max(0, ...keys.map((d) => d.name.length));
|
|
526
|
+
for (const d of keys) {
|
|
527
|
+
const p = d.inference.provider;
|
|
528
|
+
const state = !inUse ? '' : inUse.source === 'credentials' && inUse.provider === p ? 'in use' : 'kept, not in use';
|
|
529
|
+
lines.push(` ${d.name.padEnd(width)} ${state}`.trimEnd());
|
|
530
|
+
}
|
|
531
|
+
if (model === null)
|
|
532
|
+
lines.push(' in use: unknown — the agent is not running');
|
|
533
|
+
else if (model === 'old')
|
|
534
|
+
lines.push(" in use: unknown — the agent's image predates model keys in cred (a reset moves it to the current image)");
|
|
535
|
+
// LEGACY(model-key): the key that came with the create/reset request.
|
|
536
|
+
else if (inUse?.source === 'deploy')
|
|
537
|
+
lines.push(` in use: the ${inUse.provider} key given at create/reset (${(0, errors_1.agentCmd)('cred', 'set model')} replaces it)`);
|
|
538
|
+
else if (inUse?.source === 'none')
|
|
539
|
+
lines.push(` in use: none — add one: ${(0, errors_1.agentCmd)('cred', `set model provider=${inUse.provider || '0g-compute'}`)}`);
|
|
540
|
+
if (inUse?.issue)
|
|
541
|
+
lines.push(` ${printable(inUse.issue)}`);
|
|
542
|
+
return lines;
|
|
543
|
+
}
|
|
544
|
+
/** What the running agent says about its model key (see {@link ModelKeyState}). */
|
|
545
|
+
async function modelKeyState(cred, sealId, at) {
|
|
546
|
+
const loaded = await cred.loaded(sealId, at).catch(() => undefined);
|
|
547
|
+
if (!loaded)
|
|
548
|
+
return { state: null, logins: null };
|
|
549
|
+
const logins = {};
|
|
550
|
+
for (const e of Array.isArray(loaded.entries) ? loaded.entries : []) {
|
|
551
|
+
if (e.status === 'awaiting_login')
|
|
552
|
+
logins[e.name] = { awaiting: true };
|
|
553
|
+
else if (e.logged_in_at)
|
|
554
|
+
logins[e.name] = { loggedInAt: e.logged_in_at };
|
|
555
|
+
}
|
|
556
|
+
return { state: loaded.model ?? 'old', logins };
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* The provider a `model` subcommand means: `provider=`, or `model.<id>`;
|
|
560
|
+
* else the one the agent's settings use; with none there, the one provider
|
|
561
|
+
* the set holds a key for, or 0g-compute when it holds none.
|
|
562
|
+
*/
|
|
563
|
+
async function modelProviderOf(ag, sealId, name, args, defs) {
|
|
564
|
+
let provider = name.startsWith(Credentials_1.MODEL_KEY_PREFIX) ? name.slice(Credentials_1.MODEL_KEY_PREFIX.length) : undefined;
|
|
565
|
+
for (const a of args) {
|
|
566
|
+
const m = /^provider=(.*)$/.exec(a);
|
|
567
|
+
if (!m)
|
|
568
|
+
throw usage(`unknown argument "${a}"`, MODEL_USAGE);
|
|
569
|
+
if (provider !== undefined && provider !== m[1])
|
|
570
|
+
throw usage(`${name} and provider=${m[1]} name two providers`, MODEL_USAGE);
|
|
571
|
+
provider = m[1];
|
|
572
|
+
}
|
|
573
|
+
if (provider === undefined) {
|
|
574
|
+
const { settings } = await ag.agent.getSettings(sealId);
|
|
575
|
+
if (settings?.provider)
|
|
576
|
+
return settings.provider;
|
|
577
|
+
const stored = defs.filter((d) => d.inference).map((d) => d.inference.provider);
|
|
578
|
+
if (stored.length > 1)
|
|
579
|
+
throw usage(`the agent's settings name no provider and keys for ${stored.join(', ')} are kept: give provider=`, MODEL_USAGE);
|
|
580
|
+
provider = stored[0] ?? '0g-compute';
|
|
581
|
+
}
|
|
582
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(provider) || !NAME_RE.test((0, Credentials_1.modelKeyName)(provider)))
|
|
583
|
+
throw usage(`not a provider id: "${provider}"`, MODEL_USAGE);
|
|
584
|
+
return provider;
|
|
585
|
+
}
|
|
586
|
+
const MODEL_WAIT_MS = 120000;
|
|
587
|
+
const MODEL_POLL_MS = 2000;
|
|
588
|
+
function pause(ms, signal) {
|
|
589
|
+
return new Promise((resolve) => {
|
|
590
|
+
const t = setTimeout(resolve, ms);
|
|
591
|
+
signal?.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
/** What became of a model key pushed to the running agent, once it says. */
|
|
595
|
+
async function modelApplied(cred, sealId, provider, valueHash, io, at) {
|
|
596
|
+
const until = Date.now() + MODEL_WAIT_MS;
|
|
597
|
+
for (;;) {
|
|
598
|
+
// The agent applies the key after it took the set.
|
|
599
|
+
await pause(MODEL_POLL_MS, io.signal);
|
|
600
|
+
const m = (await cred.loaded(sealId, at).catch(() => undefined))?.model;
|
|
601
|
+
if (m?.source === 'credentials' && m.provider === provider && m.value_hash?.toLowerCase() === valueHash.toLowerCase())
|
|
602
|
+
return 'in use now';
|
|
603
|
+
if (m?.issue)
|
|
604
|
+
return `kept, but not in use: ${printable(m.issue)}`;
|
|
605
|
+
if (m?.provider && m.provider !== provider)
|
|
606
|
+
return `kept — the agent's settings use ${m.provider}; this key is used once they switch (${(0, errors_1.agentCmd)('settings', `provider=${provider}`)})`;
|
|
607
|
+
if (Date.now() >= until || io.signal?.aborted)
|
|
608
|
+
return `kept; not confirmed in use yet — ${(0, errors_1.agentCmd)('cred')} shows which key is in use`;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Where this machine notes the model key it stored for an agent and
|
|
613
|
+
* provider: the stored value is sealed to the agent (a fresh encryption each
|
|
614
|
+
* time), so only this note tells the same key apart. A hash salted with the
|
|
615
|
+
* agent and provider, never the key (config.ts, model-key-marks.json).
|
|
616
|
+
*/
|
|
617
|
+
function modelKeyMarkOf(sealId, provider, value) {
|
|
618
|
+
const seal = sealId.toLowerCase();
|
|
619
|
+
return { markKey: `${seal}:${provider}`, keyMark: (0, viem_1.keccak256)((0, viem_1.toBytes)(`agentdna-model-key-mark\n${seal}\n${provider}\n${value}`)) };
|
|
620
|
+
}
|
|
621
|
+
/** `cred <agent> set model …`: the value is asked for, as any other. */
|
|
622
|
+
async function modelSetOp(ag, sealId, provider, defs, io, at) {
|
|
623
|
+
const cred = ag.credentials;
|
|
624
|
+
const name = (0, Credentials_1.modelKeyName)(provider);
|
|
625
|
+
const { state } = await modelKeyState(cred, sealId, at);
|
|
626
|
+
if (state === 'old') {
|
|
627
|
+
throw new errors_1.CliError('INFERENCE_PROVIDER_UNSUPPORTED', "this agent's image does not take model keys from cred", {
|
|
628
|
+
remedy: `reset the agent (it starts on the current image), then repeat; until then a reset with the ${provider} key changes it`,
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
const value = (await (0, modelkey_1.pickModelKey)(provider, keyPromptOf(io)));
|
|
632
|
+
// The same key this machine stored last, still the one in the set: nothing to write.
|
|
633
|
+
const { markKey, keyMark } = modelKeyMarkOf(sealId, provider, value);
|
|
634
|
+
const had = (0, config_1.loadModelKeyMarks)()[markKey];
|
|
635
|
+
const stored = defs.find((d) => d.name === name);
|
|
636
|
+
if (had && stored && had.keyMark === keyMark && had.valueHash.toLowerCase() === stored.value_hash.toLowerCase()) {
|
|
637
|
+
if (io.json)
|
|
638
|
+
return (0, envelope_1.emitOk)({ sealId, name, provider, unchanged: true, valueHash: stored.value_hash });
|
|
639
|
+
io.out(`unchanged ${name}: the agent's credential set already holds this key`);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
// From here on nothing is asked: the set, then the wait for the agent.
|
|
643
|
+
return quietOf(io)(async () => {
|
|
644
|
+
const out = await cred.setModelKey(sealId, provider, value, at).catch(conflict);
|
|
645
|
+
(0, config_1.recordModelKeyMark)(markKey, { valueHash: out.valueHash, keyMark });
|
|
646
|
+
if (io.json)
|
|
647
|
+
return (0, envelope_1.emitOk)({ sealId, version: out.version, name, provider, valueHash: out.valueHash, pushWarning: out.pushWarning ?? null });
|
|
648
|
+
io.out(`${stored ? 'changed' : 'added'} ${name}`);
|
|
649
|
+
if (out.pushWarning)
|
|
650
|
+
return io.out(`stored, but not applied to the running agent: ${out.pushWarning} — it applies on the next boot`);
|
|
651
|
+
// LEGACY(model-key): the parenthesis goes with the images that read only the request.
|
|
652
|
+
if (state === null)
|
|
653
|
+
return io.out('the agent is not running: it takes the key when it starts on a current image (an image from before model keys in cred skips it and keeps the key given at create/reset)');
|
|
654
|
+
io.out(`waiting for the running agent to take it (up to ${MODEL_WAIT_MS / 60000} minutes)…`);
|
|
655
|
+
io.out(await modelApplied(cred, sealId, provider, out.valueHash, io, at));
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
/** `cred <agent> rm model …`. */
|
|
659
|
+
async function modelRmOp(ag, sealId, provider, defs, io, at) {
|
|
660
|
+
const cred = ag.credentials;
|
|
661
|
+
const name = (0, Credentials_1.modelKeyName)(provider);
|
|
662
|
+
if (!defs.some((d) => d.name === name))
|
|
663
|
+
throw new errors_1.CliError('BAD_FLAG', `no model key for ${provider}`, { remedy: 'cred <agent>' });
|
|
664
|
+
const { state } = await modelKeyState(cred, sealId, at);
|
|
665
|
+
const inUse = !!state && state !== 'old' && state.source === 'credentials' && state.provider === provider;
|
|
666
|
+
const prompt = keyPromptOf(io);
|
|
667
|
+
if (inUse && prompt.interactive && !await prompt.confirm(`${name} is the key the agent uses: without another ${provider} key it cannot call its model. Remove it?`, false)) {
|
|
668
|
+
return io.out('kept');
|
|
669
|
+
}
|
|
670
|
+
const out = await cred.removeModelKey(sealId, provider, at).catch(conflict);
|
|
671
|
+
if (io.json)
|
|
672
|
+
return (0, envelope_1.emitOk)({ sealId, version: out.version, removed: name, pushWarning: out.pushWarning ?? null });
|
|
673
|
+
io.out(`removed ${name}. Revoke it at the provider too: removing it here does not.`);
|
|
674
|
+
if (inUse) {
|
|
675
|
+
// LEGACY(model-key): "goes back to the key given at create/reset" holds only while keys come with the request.
|
|
676
|
+
io.out(`it was in use: the agent goes back to the ${provider} key given at create/reset, if it has one; without one it cannot call its model until there is a key (${(0, errors_1.agentCmd)('cred', `set model provider=${provider}`)})`);
|
|
677
|
+
}
|
|
678
|
+
if (out.pushWarning)
|
|
679
|
+
io.out(`the running agent did not take it: ${out.pushWarning} — it keeps the key until its next boot`);
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* A provider switch in the settings: the set must hold a key for the new
|
|
683
|
+
* provider, or the agent would refuse the switch. Asks for one (Enter takes
|
|
684
|
+
* the key login saved) and stores it, unless the set holds one already.
|
|
685
|
+
* `unsupported`: the running agent's image, or the attestor, predates model
|
|
686
|
+
* keys in the set (a reset with the key does it there).
|
|
687
|
+
*/
|
|
688
|
+
async function ensureModelKey(ag, sealId, provider, io, at) {
|
|
689
|
+
const cred = ag.credentials;
|
|
690
|
+
const { state } = await modelKeyState(cred, sealId, at);
|
|
691
|
+
if (state === 'old')
|
|
692
|
+
return 'unsupported';
|
|
693
|
+
// LEGACY(model-key): the key given with the create/reset request is for
|
|
694
|
+
// that provider: nothing to add.
|
|
695
|
+
if (state?.deploy_provider === provider)
|
|
696
|
+
return 'kept';
|
|
697
|
+
// An attestor that keeps no credential sets: the reset path too.
|
|
698
|
+
const cur = await cred.get(sealId).catch((e) => {
|
|
699
|
+
if (/HTTP 404/.test(e instanceof Error ? e.message : String(e)))
|
|
700
|
+
return undefined;
|
|
701
|
+
throw e;
|
|
702
|
+
});
|
|
703
|
+
if (!cur)
|
|
704
|
+
return 'unsupported';
|
|
705
|
+
const name = (0, Credentials_1.modelKeyName)(provider);
|
|
706
|
+
if (cur.definitions.some((d) => d.name === name))
|
|
707
|
+
return 'kept';
|
|
708
|
+
io.out(`the agent has no ${provider} model key yet`);
|
|
709
|
+
const value = (await (0, modelkey_1.pickModelKey)(provider, keyPromptOf(io)));
|
|
710
|
+
const out = await cred.setModelKey(sealId, provider, value, at).catch(conflict);
|
|
711
|
+
const { markKey, keyMark } = modelKeyMarkOf(sealId, provider, value);
|
|
712
|
+
(0, config_1.recordModelKeyMark)(markKey, { valueHash: out.valueHash, keyMark });
|
|
713
|
+
io.out(`added ${name}${out.pushWarning ? `; not applied to the running agent: ${out.pushWarning}` : ''}`);
|
|
714
|
+
if (state === null)
|
|
715
|
+
io.out(`the agent is not running: on an image from before model keys in cred, the switch takes a reset with the ${provider} key`);
|
|
716
|
+
return 'added';
|
|
717
|
+
}
|
|
718
|
+
/** The name sealed gives a value a token request keeps (sealed/internal/credentials/token.go). */
|
|
719
|
+
function derivedName(entry, t) {
|
|
720
|
+
const n = t.name || `${entry}.${t.field}`;
|
|
721
|
+
return n.startsWith('derived:') ? n : `derived:${n}`;
|
|
722
|
+
}
|
|
723
|
+
/** Pending requests, the agent's own words kept apart from what sealed knows. */
|
|
724
|
+
function renderPending(list) {
|
|
725
|
+
const open = list.filter((p) => p.status === 'pending');
|
|
726
|
+
if (!open.length)
|
|
727
|
+
return ['nothing waiting'];
|
|
728
|
+
const lines = [];
|
|
729
|
+
for (const p of open) {
|
|
730
|
+
lines.push(`${printable(p.auth_req_id.slice(0, 10))} ${printable(p.op)} ${printable(p.name)} (the request lapses ${dateText(p.expires_at)})`);
|
|
731
|
+
lines.push(...factLines(p));
|
|
732
|
+
if (p.reason)
|
|
733
|
+
lines.push(` the agent says: ${printable(JSON.stringify(p.reason))}`);
|
|
734
|
+
lines.push(` answer: ${answerHint(p)}`);
|
|
735
|
+
}
|
|
736
|
+
return lines;
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Text that came from the agent (or through it), made safe to print: control
|
|
740
|
+
* characters are shown escaped, so nothing it wrote can move the cursor or
|
|
741
|
+
* rewrite what the owner reads.
|
|
742
|
+
*/
|
|
743
|
+
function printable(v) {
|
|
744
|
+
// Control characters, format characters (bidi overrides and the like),
|
|
745
|
+
// spaces other than the plain one, and letters that draw as blanks, which
|
|
746
|
+
// could make a line read differently from what it holds.
|
|
747
|
+
// eslint-disable-next-line no-control-regex
|
|
748
|
+
return String(v).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u115f\u1160\u3164\uffa0\u2800]|\p{Cf}|[^\P{Zs} ]/gu, (c) => `\\u${c.codePointAt(0).toString(16).padStart(4, '0')}`);
|
|
749
|
+
}
|
|
750
|
+
/** What sealed knows about a request, without the empty fields. */
|
|
751
|
+
function factLines(p) {
|
|
752
|
+
const f = (p.facts ?? {});
|
|
753
|
+
const out = [];
|
|
754
|
+
if (typeof f.source === 'string' && f.source)
|
|
755
|
+
out.push(` entry set by ${printable(f.source)}${typeof f.from === 'string' && f.from ? `, from ${printable(f.from)}` : ''}`);
|
|
756
|
+
if (Array.isArray(f.hosts) && f.hosts.length)
|
|
757
|
+
out.push(` hosts ${f.hosts.map(printable).join(', ')}`);
|
|
758
|
+
if (typeof f.expires_at === 'number' && f.expires_at > 0)
|
|
759
|
+
out.push(` entry expires ${dateText(f.expires_at)}`);
|
|
760
|
+
if (typeof f.why === 'string' && f.why)
|
|
761
|
+
out.push(` why ${printable(f.why)}`);
|
|
762
|
+
if (f.params && typeof f.params === 'object') {
|
|
763
|
+
for (const [k, v] of Object.entries(f.params))
|
|
764
|
+
out.push(` ${printable(k).padEnd(10)} ${printable(v)} (asked by the agent)`);
|
|
765
|
+
}
|
|
766
|
+
// The agent's own parameters, labelled as such: never laid out like what
|
|
767
|
+
// sealed knows.
|
|
768
|
+
for (const [k, v] of Object.entries(p.params ?? {}))
|
|
769
|
+
out.push(` the agent's ${printable(k)}: ${printable(v)}`);
|
|
770
|
+
return out;
|
|
771
|
+
}
|
|
772
|
+
function answerHint(p) {
|
|
773
|
+
if (p.op === 'login')
|
|
774
|
+
return `${(0, errors_1.agentCmd)('cred', `connect ${p.name} ${printable(p.params?.url ?? '<mcp-url>')}`)} (or deny)`;
|
|
775
|
+
if (p.op === 'add')
|
|
776
|
+
return `${(0, errors_1.agentCmd)('cred', `set ${p.name}${p.params?.preset ? ` preset=${printable(p.params.preset)}` : ' …'}`)} (or deny)`;
|
|
777
|
+
return (0, errors_1.agentCmd)('cred', 'approve | deny');
|
|
778
|
+
}
|
|
779
|
+
function renderAudit(recs) {
|
|
780
|
+
if (!recs.length)
|
|
781
|
+
return ['no credential use recorded'];
|
|
782
|
+
const where = (r) => (r.method && r.host ? `${r.method} ${r.host}` : r.host ?? '');
|
|
783
|
+
const counted = recs.filter((r) => r.count);
|
|
784
|
+
const listed = recs.filter((r) => !r.count);
|
|
785
|
+
const lines = counted.map((r) => printable(`${r.op} ${(r.names ?? []).join(',')} ${where(r)} ${r.result} ×${r.count} (${r.first ?? '?'} … ${r.ts})`));
|
|
786
|
+
if (counted.length && listed.length)
|
|
787
|
+
lines.push('');
|
|
788
|
+
for (const r of listed)
|
|
789
|
+
lines.push(printable([r.ts, r.op, (r.names ?? []).join(','), where(r), r.result].filter(Boolean).join(' ')));
|
|
790
|
+
return lines;
|
|
791
|
+
}
|
|
792
|
+
/** Entry names last read per agent (by sealId), for completion in the shell. */
|
|
793
|
+
const credNames = new Map();
|
|
794
|
+
/** The entry names last read for an agent in this process; none before a read. */
|
|
795
|
+
function cachedCredNames(sealId) {
|
|
796
|
+
return credNames.get(sealId.toLowerCase()) ?? [];
|
|
797
|
+
}
|
|
798
|
+
/** io.quiet, or the stretch as it is. */
|
|
799
|
+
const quietOf = (io) => io.quiet ?? ((f) => f());
|
|
800
|
+
/** The model key prompt of an operation: its own, or a script's. */
|
|
801
|
+
function keyPromptOf(io) {
|
|
802
|
+
return io.keyPrompt ?? { interactive: false, out: io.out, secret: io.secret, confirm: async (_q, def) => def };
|
|
803
|
+
}
|
|
804
|
+
/** A yes/no question on the terminal; Enter answers `def`. */
|
|
805
|
+
async function readConfirm(question, def) {
|
|
806
|
+
const rl = (0, node_readline_1.createInterface)({ input: process.stdin, output: process.stderr });
|
|
807
|
+
try {
|
|
808
|
+
const a = (await new Promise((resolve, reject) => {
|
|
809
|
+
// Ctrl-C (or Ctrl-D, which closes it) cancels the question and the
|
|
810
|
+
// command, as at readSecret; the close after an answer changes nothing.
|
|
811
|
+
rl.on('SIGINT', () => reject((0, errors_1.cancelled)()));
|
|
812
|
+
rl.on('close', () => reject((0, errors_1.cancelled)()));
|
|
813
|
+
rl.question(`${question} [${def ? 'Y/n' : 'y/N'}] `, resolve);
|
|
814
|
+
})).trim().toLowerCase();
|
|
815
|
+
return a ? a.startsWith('y') : def;
|
|
816
|
+
}
|
|
817
|
+
finally {
|
|
818
|
+
rl.close();
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* The model key prompt of a one-shot command: a person at a terminal is
|
|
823
|
+
* asked; a script (stdin piped, `--json`) is not. `readPipe`: a script may
|
|
824
|
+
* pipe the key in (`cred set`, whose value is read from stdin); otherwise its
|
|
825
|
+
* stdin is left alone and the key on this machine is used.
|
|
826
|
+
*/
|
|
827
|
+
function commandKeyPrompt(json, out, opts) {
|
|
828
|
+
const interactive = !!process.stdin.isTTY && !json;
|
|
829
|
+
return {
|
|
830
|
+
interactive,
|
|
831
|
+
out,
|
|
832
|
+
secret: (prompt) => (interactive ? readSecret(prompt) : opts.readPipe && !process.stdin.isTTY ? readSecret(prompt) : Promise.resolve('')),
|
|
833
|
+
confirm: readConfirm,
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
function conflict(e) {
|
|
837
|
+
if (e instanceof Credentials_1.CredentialsConflictError) {
|
|
838
|
+
throw new errors_1.CliError('CREDENTIALS_CONFLICT', e.message, {
|
|
839
|
+
remedy: 're-run the same command to apply your change on top of the current version',
|
|
840
|
+
details: { currentVersion: e.currentVersion, ownerEpoch: e.ownerEpoch },
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
throw e;
|
|
844
|
+
}
|
|
845
|
+
/** `disconnect` (and `rm` of a connection): revoke at the server when it can be, then remove. */
|
|
846
|
+
async function disconnectOp(cred, sealId, name, io, at) {
|
|
847
|
+
const out = await cred.disconnect(sealId, name, at).catch(conflict);
|
|
848
|
+
if (io.json)
|
|
849
|
+
return (0, envelope_1.emitOk)({ sealId, version: out.version, disconnected: name, revoked: out.revoked, changed: !!out.changed, note: out.note ?? null, pushWarning: out.pushWarning ?? null });
|
|
850
|
+
io.out(`disconnected ${name}; ${out.changed ? out.note : out.revoked ? 'its tokens are revoked at the server' : `not revoked at the server: ${out.note ?? 'unknown'}`}`);
|
|
851
|
+
if (out.pushWarning) {
|
|
852
|
+
io.out(`the running agent did not take it: ${out.pushWarning}`);
|
|
853
|
+
if (!out.forgotten)
|
|
854
|
+
io.out(`the agent still holds the login until its next boot: revoke the app's access at the service, and restart the agent`);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
/** Match an id prefix against the pending list; with no id, the only request waiting. */
|
|
858
|
+
function pickPending(list, raw) {
|
|
859
|
+
const open = list.filter((p) => p.status === 'pending');
|
|
860
|
+
if (!raw) {
|
|
861
|
+
if (open.length === 1)
|
|
862
|
+
return open[0];
|
|
863
|
+
throw new errors_1.CliError('BAD_FLAG', open.length ? `${open.length} requests are waiting — give one's id: ${open.map((p) => `${p.auth_req_id.slice(0, 10)} (${p.op} ${p.name})`).join(', ')}` : 'nothing is waiting', {
|
|
864
|
+
remedy: 'cred <agent> pending',
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
const want = raw.toLowerCase();
|
|
868
|
+
if (!/^0x[0-9a-f]{4,64}$/.test(want))
|
|
869
|
+
throw new errors_1.CliError('BAD_FLAG', `not a request id: "${raw}"`, { remedy: 'cred <agent> approve|deny [<id>] (ids: cred <agent> pending)' });
|
|
870
|
+
const hits = list.filter((p) => p.status === 'pending' && p.auth_req_id.toLowerCase().startsWith(want));
|
|
871
|
+
if (hits.length !== 1) {
|
|
872
|
+
throw new errors_1.CliError('BAD_FLAG', hits.length ? `${raw} matches ${hits.length} requests — add more hex` : `no pending request ${raw}`, {
|
|
873
|
+
remedy: 'cred <agent> pending',
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
return hits[0];
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* Run one `cred <agent> …` subcommand. `agentUrl` is the running container's
|
|
880
|
+
* base when the caller already knows it; otherwise the SDK reads it from the
|
|
881
|
+
* deployment row.
|
|
882
|
+
*/
|
|
883
|
+
async function credOp(ag, sealId, args, io, agentUrl) {
|
|
884
|
+
const [sub = 'ls', ...rest] = args;
|
|
885
|
+
// Every read of the set leaves its names for completion.
|
|
886
|
+
const cred = Object.create(ag.credentials);
|
|
887
|
+
cred.get = async (seal) => {
|
|
888
|
+
const cur = await ag.credentials.get(seal);
|
|
889
|
+
credNames.set(seal.toLowerCase(), cur.definitions.map((d) => d.name));
|
|
890
|
+
return cur;
|
|
891
|
+
};
|
|
892
|
+
// …and every write it makes keeps them current.
|
|
893
|
+
const named = (seal, change) => credNames.set(seal.toLowerCase(), change(cachedCredNames(seal)));
|
|
894
|
+
cred.put = async (seal, entries, opts) => {
|
|
895
|
+
const out = await ag.credentials.put(seal, entries, opts);
|
|
896
|
+
named(seal, () => entries.map((e) => e.name));
|
|
897
|
+
return out;
|
|
898
|
+
};
|
|
899
|
+
cred.remove = async (seal, name, opts) => {
|
|
900
|
+
const out = await ag.credentials.remove(seal, name, opts);
|
|
901
|
+
named(seal, (names) => names.filter((n) => n !== name));
|
|
902
|
+
return out;
|
|
903
|
+
};
|
|
904
|
+
cred.setModelKey = async (seal, provider, value, opts) => {
|
|
905
|
+
const out = await ag.credentials.setModelKey(seal, provider, value, opts);
|
|
906
|
+
named(seal, (names) => [...new Set([...names, (0, Credentials_1.modelKeyName)(provider)])]);
|
|
907
|
+
return out;
|
|
908
|
+
};
|
|
909
|
+
const at = agentUrl ? { agentUrl } : undefined;
|
|
910
|
+
switch (sub) {
|
|
911
|
+
case 'presets':
|
|
912
|
+
if (io.json)
|
|
913
|
+
return (0, envelope_1.emitOk)({ presets: exports.CRED_PRESETS });
|
|
914
|
+
for (const l of renderPresets())
|
|
915
|
+
io.out(l);
|
|
916
|
+
return;
|
|
917
|
+
case 'ls':
|
|
918
|
+
case 'list': {
|
|
919
|
+
const cur = await cred.get(sealId);
|
|
920
|
+
// Whether a login entry's login is done, and which model key is in
|
|
921
|
+
// use, is the running agent's to say.
|
|
922
|
+
const { state, logins } = await modelKeyState(cred, sealId, at);
|
|
923
|
+
const shownLogins = cur.definitions.some((d) => d.mcp) ? logins : undefined;
|
|
924
|
+
if (io.json) {
|
|
925
|
+
return (0, envelope_1.emitOk)({ sealId, version: cur.version, ownerEpoch: cur.ownerEpoch, credentials: cur.definitions,
|
|
926
|
+
...(shownLogins !== undefined ? { logins: shownLogins } : {}), modelInUse: state === 'old' ? null : state });
|
|
927
|
+
}
|
|
928
|
+
for (const l of renderCredentials(cur.definitions, cur.version, shownLogins, state))
|
|
929
|
+
io.out(l);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
case 'set': {
|
|
933
|
+
if (rest[0] === 'model' || rest[0]?.startsWith(Credentials_1.MODEL_KEY_PREFIX)) {
|
|
934
|
+
const cur = await cred.get(sealId);
|
|
935
|
+
return modelSetOp(ag, sealId, await modelProviderOf(ag, sealId, rest[0], rest.slice(1), cur.definitions), cur.definitions, io, at);
|
|
936
|
+
}
|
|
937
|
+
// Grammar first, before anything is read or signed.
|
|
938
|
+
const name = checkCredName(rest[0]);
|
|
939
|
+
const patch = parseCredArgs(rest.slice(1));
|
|
940
|
+
const cur = await cred.get(sealId);
|
|
941
|
+
const stored = cur.definitions.find((d) => d.name === name);
|
|
942
|
+
const entry = applyCredPatch(name, patch, stored ? (0, Credentials_1.inputOf)(stored) : undefined);
|
|
943
|
+
const preset = patch.preset ? exports.CRED_PRESETS[patch.preset] : undefined;
|
|
944
|
+
if (preset && !stored && !io.json)
|
|
945
|
+
io.out(`create it at ${preset.create} — ${preset.tip}`);
|
|
946
|
+
const typed = await io.secret(stored ? `${name} value (Enter keeps the stored one, Ctrl-C cancels): ` : `${name} value (Ctrl-C cancels): `);
|
|
947
|
+
if (typed)
|
|
948
|
+
entry.value = typed;
|
|
949
|
+
else if (!stored)
|
|
950
|
+
throw new errors_1.CliError('BAD_FLAG', `${name} needs a value (pipe it in, or type it at the prompt)`, { remedy: SET_USAGE });
|
|
951
|
+
else if (rest.length === 1) {
|
|
952
|
+
// Enter kept the value and no option changed: nothing to write.
|
|
953
|
+
if (io.json)
|
|
954
|
+
return (0, envelope_1.emitOk)({ sealId, version: cur.version, name, unchanged: true, pushWarning: null });
|
|
955
|
+
io.out(`${name} unchanged — it keeps its value and options`);
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
const others = cur.definitions.filter((d) => d.name !== name).map(Credentials_1.inputOf);
|
|
959
|
+
const out = await cred.put(sealId, [...others, entry], { baseVersion: cur.version, ...at }).catch(conflict);
|
|
960
|
+
if (io.json)
|
|
961
|
+
return (0, envelope_1.emitOk)({ sealId, version: out.version, name, pushWarning: out.pushWarning ?? null });
|
|
962
|
+
const gives = (entry.tokenRequest?.take ?? []).map((t) => `[[credential:${derivedName(name, t)}]]`);
|
|
963
|
+
io.out(gives.length && entry.use === 'token_only'
|
|
964
|
+
? `${stored ? 'changed' : 'added'} ${name}; the agent asks for a token request on ${name} and then uses ${gives.join(', ')}`
|
|
965
|
+
: `${stored ? 'changed' : 'added'} ${name}; the agent writes [[credential:${name}]] where the key goes`);
|
|
966
|
+
io.out(out.pushWarning ? `stored, but not applied to the running agent: ${out.pushWarning} — it applies on the next boot` : 'applied to the running agent');
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
case 'rm': {
|
|
970
|
+
const [name] = rest;
|
|
971
|
+
if (!name)
|
|
972
|
+
throw new errors_1.CliError('BAD_FLAG', 'missing <name>', { remedy: 'cred <agent> rm <name>' });
|
|
973
|
+
if (name === 'model' || name.startsWith(Credentials_1.MODEL_KEY_PREFIX)) {
|
|
974
|
+
const cur = await cred.get(sealId);
|
|
975
|
+
return modelRmOp(ag, sealId, await modelProviderOf(ag, sealId, name, rest.slice(1), cur.definitions), cur.definitions, io, at);
|
|
976
|
+
}
|
|
977
|
+
const cur = await cred.get(sealId);
|
|
978
|
+
const def = cur.definitions.find((d) => d.name === name);
|
|
979
|
+
if (!def)
|
|
980
|
+
throw new errors_1.CliError('BAD_FLAG', `no credential named ${name}`, { remedy: 'cred <agent>' });
|
|
981
|
+
// A connection is revoked at its server first, as `disconnect` does.
|
|
982
|
+
if (def.mcp)
|
|
983
|
+
return disconnectOp(cred, sealId, name, io, at);
|
|
984
|
+
const out = await cred.remove(sealId, name, at).catch(conflict);
|
|
985
|
+
if (io.json)
|
|
986
|
+
return (0, envelope_1.emitOk)({ sealId, version: out.version, removed: name, pushWarning: out.pushWarning ?? null });
|
|
987
|
+
io.out(`removed ${name}. Revoke it at its provider too: removing it here does not.`);
|
|
988
|
+
if (out.pushWarning)
|
|
989
|
+
io.out(`the running agent did not take it: ${out.pushWarning} — the agent can use ${name} until its next boot`);
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
case 'disconnect': {
|
|
993
|
+
const [name] = rest;
|
|
994
|
+
if (!name)
|
|
995
|
+
throw new errors_1.CliError('BAD_FLAG', 'missing <name>', { remedy: 'cred <agent> disconnect <name>' });
|
|
996
|
+
const def = (await cred.get(sealId)).definitions.find((d) => d.name === name);
|
|
997
|
+
if (!def?.mcp)
|
|
998
|
+
throw new errors_1.CliError('BAD_FLAG', def ? `${name} is not a connection; remove it with rm` : `no connection named ${name}`, { remedy: def ? `cred <agent> rm ${name}` : 'cred <agent>' });
|
|
999
|
+
return disconnectOp(cred, sealId, name, io, at);
|
|
1000
|
+
}
|
|
1001
|
+
case 'reveal': {
|
|
1002
|
+
const [name, onOff] = rest;
|
|
1003
|
+
if (!name || !onOff)
|
|
1004
|
+
throw new errors_1.CliError('BAD_FLAG', 'usage: cred <agent> reveal <name> on|off', { remedy: 'cred <agent> reveal <name> on|off' });
|
|
1005
|
+
const allow = yesNo('reveal', onOff);
|
|
1006
|
+
const out = await cred.setAllowReveal(sealId, name, allow, at).catch((e) => {
|
|
1007
|
+
if (e instanceof Error && /is a signing key/.test(e.message)) {
|
|
1008
|
+
throw new errors_1.CliError('BAD_FLAG', e.message.replace(/^credentials: /, ''), { remedy: 'cred <agent>' });
|
|
1009
|
+
}
|
|
1010
|
+
return conflict(e);
|
|
1011
|
+
});
|
|
1012
|
+
if (io.json)
|
|
1013
|
+
return (0, envelope_1.emitOk)({ sealId, version: out.version, name, allowReveal: allow, pushWarning: out.pushWarning ?? null });
|
|
1014
|
+
io.out(`${name}: the agent ${allow ? 'may read the value itself' : 'must ask you to read the value'}`);
|
|
1015
|
+
if (out.pushWarning)
|
|
1016
|
+
io.out(`the running agent did not take it: ${out.pushWarning} — it applies on the next boot`);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
case 'pending': {
|
|
1020
|
+
const list = await cred.pending(sealId, at);
|
|
1021
|
+
if (io.json)
|
|
1022
|
+
return (0, envelope_1.emitOk)({ sealId, pending: list.filter((p) => p.status === 'pending') });
|
|
1023
|
+
for (const l of renderPending(list))
|
|
1024
|
+
io.out(l);
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
case 'approve':
|
|
1028
|
+
case 'deny': {
|
|
1029
|
+
const base = agentUrl ?? (await cred.agentUrl(sealId));
|
|
1030
|
+
const item = pickPending(await cred.pending(sealId, { agentUrl: base }), rest[0]);
|
|
1031
|
+
if (sub === 'approve' && item.op !== 'reveal') {
|
|
1032
|
+
// Adding a credential or connecting is done, not approved.
|
|
1033
|
+
throw new errors_1.CliError('BAD_FLAG', `a request to ${item.op} ${item.name} is answered by doing it`, {
|
|
1034
|
+
remedy: item.op === 'login' ? `cred <agent> connect ${item.name} ${printable(item.params?.url ?? '<mcp-url>')}` : `cred <agent> set ${item.name} …`,
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
if (sub === 'approve')
|
|
1038
|
+
await cred.approveOnce(sealId, item.auth_req_id, { agentUrl: base });
|
|
1039
|
+
else
|
|
1040
|
+
await cred.deny(sealId, item.auth_req_id, { agentUrl: base });
|
|
1041
|
+
if (io.json)
|
|
1042
|
+
return (0, envelope_1.emitOk)({ sealId, authReqId: item.auth_req_id, decision: sub === 'approve' ? 'once' : 'deny' });
|
|
1043
|
+
io.out(sub === 'approve'
|
|
1044
|
+
? `approved once: ${item.op} ${item.name}. The agent gets it when it sends the request again.`
|
|
1045
|
+
: `denied: ${item.op} ${item.name}`);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
case 'connect': {
|
|
1049
|
+
const name = checkCredName(rest[0], CONNECT_USAGE);
|
|
1050
|
+
const cur = await cred.get(sealId);
|
|
1051
|
+
const stored = cur.definitions.find((d) => d.name === name);
|
|
1052
|
+
// An existing connection is connected again as it is defined: with no
|
|
1053
|
+
// url, or its own url and no options, its client and scopes are kept.
|
|
1054
|
+
const mcpUrl = rest[1] ?? stored?.mcp?.url;
|
|
1055
|
+
const reconnect = !!stored?.mcp && stored.mcp.url === mcpUrl && rest.length <= 2;
|
|
1056
|
+
let parsed;
|
|
1057
|
+
try {
|
|
1058
|
+
parsed = mcpUrl ? new URL(mcpUrl) : undefined;
|
|
1059
|
+
}
|
|
1060
|
+
catch {
|
|
1061
|
+
parsed = undefined;
|
|
1062
|
+
}
|
|
1063
|
+
if (!parsed || parsed.protocol !== 'https:' || parsed.username || parsed.password) {
|
|
1064
|
+
throw new errors_1.CliError('BAD_FLAG', 'connect needs the MCP server\'s https URL', { remedy: 'cred <agent> connect linear https://mcp.linear.app/mcp' });
|
|
1065
|
+
}
|
|
1066
|
+
const mcp = { url: mcpUrl };
|
|
1067
|
+
for (const arg of rest.slice(2)) {
|
|
1068
|
+
const [k, v = ''] = arg.split(/=(.*)/s);
|
|
1069
|
+
if (k === 'client_id' && v)
|
|
1070
|
+
mcp.client_id = v;
|
|
1071
|
+
else if (k === 'client_secret_entry' && v)
|
|
1072
|
+
mcp.client_secret_entry = checkCredName(v, CONNECT_USAGE);
|
|
1073
|
+
else if (k === 'scope' && v)
|
|
1074
|
+
mcp.scopes = v.split(',').map((x) => x.trim()).filter(Boolean);
|
|
1075
|
+
else
|
|
1076
|
+
throw new errors_1.CliError('BAD_FLAG', `unknown connect option "${arg}"`, { remedy: 'client_id=… client_secret_entry=<entry> scope=a,b' });
|
|
1077
|
+
}
|
|
1078
|
+
const host = parsed.host.toLowerCase();
|
|
1079
|
+
const want = {
|
|
1080
|
+
name, hosts: [host], positions: [{ kind: 'header', name: 'Authorization', template: 'Bearer {v}' }],
|
|
1081
|
+
description: `MCP server ${mcpUrl}`, mcp,
|
|
1082
|
+
};
|
|
1083
|
+
if (stored && !stored.mcp)
|
|
1084
|
+
throw new errors_1.CliError('BAD_FLAG', `${name} is already a credential that is not a connection`, { remedy: 'pick another name, or cred <agent> rm ' + name });
|
|
1085
|
+
const base = agentUrl ?? (await cred.agentUrl(sealId));
|
|
1086
|
+
const same = reconnect || (stored && JSON.stringify((0, Credentials_1.definitionOf)((0, Credentials_1.inputOf)(stored), '')) === JSON.stringify((0, Credentials_1.definitionOf)({ ...want, description: stored.description }, '')));
|
|
1087
|
+
if (!same) {
|
|
1088
|
+
const others = cur.definitions.filter((d) => d.name !== name).map(Credentials_1.inputOf);
|
|
1089
|
+
const out = await cred.put(sealId, [...others, want], { baseVersion: cur.version, agentUrl: base }).catch(conflict);
|
|
1090
|
+
if (out.pushWarning) {
|
|
1091
|
+
throw new errors_1.CliError('UNKNOWN', `the connection is stored, but the running agent did not take it: ${out.pushWarning}`, {
|
|
1092
|
+
remedy: 'start the agent, then run the same connect command again',
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
const before = (await cred.loaded(sealId, { agentUrl: base }).catch(() => undefined))?.entries.find((e) => e.name === name);
|
|
1097
|
+
const { authorizeUrl } = await cred.connect(sealId, name, { agentUrl: base }).catch(async (e) => {
|
|
1098
|
+
// An image from before connections has no login route: not a
|
|
1099
|
+
// half-made connection left behind — one defined just now is taken
|
|
1100
|
+
// out again.
|
|
1101
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1102
|
+
if (!(/HTTP 404\b/.test(msg) && /no route/i.test(msg)))
|
|
1103
|
+
throw e;
|
|
1104
|
+
let left = '';
|
|
1105
|
+
if (!same && !stored) {
|
|
1106
|
+
left = await cred.remove(sealId, name, { agentUrl: base }).then(() => ` (${name} was not kept)`, () => ` (${name} stays defined, not connected: \`${(0, errors_1.agentCmd)('cred', `rm ${name}`)}\` removes it)`);
|
|
1107
|
+
}
|
|
1108
|
+
else if (!same) {
|
|
1109
|
+
left = ` (${name} keeps the definition just stored; it connects with the same command after the reset)`;
|
|
1110
|
+
}
|
|
1111
|
+
throw new errors_1.CliError('RUNTIME_TOO_OLD', `this agent's runtime cannot connect a login yet — it comes with a newer image${left}`, {
|
|
1112
|
+
remedy: (0, errors_1.lifecycleTo)('reset', 'move it to the current image, then connect again'),
|
|
1113
|
+
});
|
|
1114
|
+
});
|
|
1115
|
+
if (io.json)
|
|
1116
|
+
return (0, envelope_1.emitOk)({ sealId, name, authorizeUrl });
|
|
1117
|
+
io.out(`Open this link and log in to connect ${host} to the agent (valid 10 minutes):`);
|
|
1118
|
+
io.out('');
|
|
1119
|
+
io.out(` ${printable(authorizeUrl)}`);
|
|
1120
|
+
io.out('');
|
|
1121
|
+
if (!io.wait) {
|
|
1122
|
+
io.out(`When you have finished in the browser, \`${(0, errors_1.agentCmd)('cred')}\` lists ${name}; the agent uses [[credential:${name}]] as its bearer token for ${host}.`);
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
io.out(`waiting for the connection to complete (${io.signal ? 'Ctrl-C or Esc' : 'Ctrl-C'} stops waiting, not the login)…`);
|
|
1126
|
+
return quietOf(io)(async () => {
|
|
1127
|
+
for (const deadline = Date.now() + 10 * 60000; Date.now() < deadline;) {
|
|
1128
|
+
await new Promise((r) => {
|
|
1129
|
+
if (io.signal?.aborted)
|
|
1130
|
+
return r();
|
|
1131
|
+
const t = setTimeout(r, 3000);
|
|
1132
|
+
io.signal?.addEventListener('abort', () => { clearTimeout(t); r(); }, { once: true });
|
|
1133
|
+
});
|
|
1134
|
+
if (io.signal?.aborted) {
|
|
1135
|
+
io.out(`stopped waiting; the login goes on in the browser, and ${(0, errors_1.agentCmd)('cred')} shows ${name} connected once it is done`);
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
const now = (await cred.loaded(sealId, { agentUrl: base }).catch(() => undefined))?.entries.find((e) => e.name === name);
|
|
1139
|
+
if (now?.logged_in_at && now.logged_in_at !== before?.logged_in_at) {
|
|
1140
|
+
io.out(`connected: the agent uses [[credential:${name}]] as its bearer token for ${host}`);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
io.out(`not completed within 10 minutes; start again with the same command`);
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
case 'log': {
|
|
1148
|
+
const n = Number(rest[0]) || 50;
|
|
1149
|
+
const all = await cred.audit(sealId, at).catch((e) => {
|
|
1150
|
+
// An image from before the credential log has no route for it.
|
|
1151
|
+
if (/HTTP 404\b/.test(e instanceof Error ? e.message : String(e))) {
|
|
1152
|
+
throw new errors_1.CliError('RUNTIME_TOO_OLD', "this agent's runtime has no credential log yet — it comes with a newer image", {
|
|
1153
|
+
remedy: (0, errors_1.lifecycleTo)('reset', 'move it to the current image'),
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
throw e;
|
|
1157
|
+
});
|
|
1158
|
+
// Counted records (sealed's own inference key) head the log; the last
|
|
1159
|
+
// n of the rest follow.
|
|
1160
|
+
const recs = [...all.filter((r) => r.count), ...all.filter((r) => !r.count).slice(-n)];
|
|
1161
|
+
if (io.json)
|
|
1162
|
+
return (0, envelope_1.emitOk)({ sealId, audit: recs });
|
|
1163
|
+
for (const l of renderAudit(recs))
|
|
1164
|
+
io.out(l);
|
|
1165
|
+
return;
|
|
1166
|
+
}
|
|
1167
|
+
default:
|
|
1168
|
+
throw new errors_1.CliError('BAD_FLAG', `unknown cred subcommand "${sub}"`, { remedy: exports.CRED_USAGE });
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* In an agent's session: put each request the agent is waiting on in front of
|
|
1173
|
+
* the owner as it comes up, take the answer, and return what to tell the
|
|
1174
|
+
* agent so it carries on — sent as the owner's next message. A request the
|
|
1175
|
+
* owner leaves for later goes into `later` and is not offered again in this
|
|
1176
|
+
* session (`/cred pending` still lists it).
|
|
1177
|
+
*/
|
|
1178
|
+
async function answerPending(ag, sealId, io, opts) {
|
|
1179
|
+
const cred = ag.credentials;
|
|
1180
|
+
const at = opts.agentUrl ? { agentUrl: opts.agentUrl } : undefined;
|
|
1181
|
+
// An agent that cannot be asked (not running yet, say) has nothing to decide.
|
|
1182
|
+
const open = (await cred.pending(sealId, at).catch(() => [])).filter((p) => p.status === 'pending' && !opts.later.has(p.auth_req_id));
|
|
1183
|
+
if (!open.length)
|
|
1184
|
+
return [];
|
|
1185
|
+
const tell = [];
|
|
1186
|
+
for (const p of open) {
|
|
1187
|
+
try {
|
|
1188
|
+
// Read again for each request: an answer to the one before may have
|
|
1189
|
+
// changed them.
|
|
1190
|
+
const defs = (await cred.get(sealId)).definitions;
|
|
1191
|
+
// Whatever the agent printed before is not carried into the prompt: a
|
|
1192
|
+
// soft terminal reset (margins, modes, character sets, attributes) and
|
|
1193
|
+
// the default colours and palette back (OSC 104, 110-112).
|
|
1194
|
+
io.raw?.('\x1b[!p\x1b[0m\x1b]104\x1b\\\x1b]110\x1b\\\x1b]111\x1b\\\x1b]112\x1b\\');
|
|
1195
|
+
io.out('');
|
|
1196
|
+
// The agent's words first, so that what follows them, up to the
|
|
1197
|
+
// prompt, is the CLI's own.
|
|
1198
|
+
if (p.reason)
|
|
1199
|
+
io.out(`the agent says: ${printable(JSON.stringify(p.reason))}`);
|
|
1200
|
+
io.out(`⚑ the agent asks to ${p.op === 'reveal' ? `read the value of ${p.name}` : p.op === 'login' ? `be connected to ${printable(p.params?.url ?? 'an MCP server')} as ${p.name}` : `get a credential named ${p.name}`}`);
|
|
1201
|
+
for (const l of factLines(p))
|
|
1202
|
+
io.out(l);
|
|
1203
|
+
const later = () => {
|
|
1204
|
+
opts.later.add(p.auth_req_id);
|
|
1205
|
+
io.out(` left for later — ${(0, errors_1.agentCmd)('cred', 'pending')} lists it`);
|
|
1206
|
+
};
|
|
1207
|
+
const refuse = async () => {
|
|
1208
|
+
await cred.deny(sealId, p.auth_req_id, at);
|
|
1209
|
+
tell.push(`[cred] I refused your request to ${p.op} ${p.name}.`);
|
|
1210
|
+
};
|
|
1211
|
+
if (p.op === 'reveal') {
|
|
1212
|
+
// "Always" is for the owner's own entries; a derived token is allowed
|
|
1213
|
+
// through the entry it came from.
|
|
1214
|
+
const owned = defs.some((d) => d.name === p.name);
|
|
1215
|
+
const a = (await io.ask(` read ${p.name}? [y] allow once${owned ? ' [a] always allow' : ''} [n] refuse [Enter] later: `)).trim().toLowerCase();
|
|
1216
|
+
if (a === 'y') {
|
|
1217
|
+
await cred.approveOnce(sealId, p.auth_req_id, at);
|
|
1218
|
+
tell.push(`[cred] I approved your request to read ${p.name}, this once. Send the same reveal request again.`);
|
|
1219
|
+
}
|
|
1220
|
+
else if (a === 'a' && owned) {
|
|
1221
|
+
const out = await cred.setAllowReveal(sealId, p.name, true, at);
|
|
1222
|
+
if (out.pushWarning) {
|
|
1223
|
+
io.out(` stored, but the running agent did not take it: ${out.pushWarning} — it applies on the next boot`);
|
|
1224
|
+
tell.push(`[cred] I allowed you to read ${p.name} without asking; it applies once you are restarted.`);
|
|
1225
|
+
}
|
|
1226
|
+
else
|
|
1227
|
+
tell.push(`[cred] You may read ${p.name} without asking from now on. Send the same reveal request again.`);
|
|
1228
|
+
}
|
|
1229
|
+
else if (a === 'n')
|
|
1230
|
+
await refuse();
|
|
1231
|
+
else
|
|
1232
|
+
later();
|
|
1233
|
+
}
|
|
1234
|
+
else if (p.op === 'add') {
|
|
1235
|
+
// An existing entry is the owner's to change, with `set` itself: the
|
|
1236
|
+
// agent's request does not move it.
|
|
1237
|
+
if (defs.some((d) => d.name === p.name)) {
|
|
1238
|
+
io.out(` ${p.name} is already set; to change it, run: ${(0, errors_1.agentCmd)('cred', `set ${p.name} …`)}`);
|
|
1239
|
+
const a = (await io.ask(` [n] refuse [Enter] later: `)).trim().toLowerCase();
|
|
1240
|
+
if (a === 'n')
|
|
1241
|
+
await refuse();
|
|
1242
|
+
else
|
|
1243
|
+
later();
|
|
1244
|
+
continue;
|
|
1245
|
+
}
|
|
1246
|
+
const a = (await io.ask(` add ${p.name}? [s] set it now [n] refuse [Enter] later: `)).trim().toLowerCase();
|
|
1247
|
+
// Checked again as the answer comes: an entry set meanwhile is not
|
|
1248
|
+
// the agent's request to change.
|
|
1249
|
+
if (a === 's' && (await cred.get(sealId)).definitions.some((d) => d.name === p.name)) {
|
|
1250
|
+
io.out(` ${p.name} was set meanwhile; to change it, run: ${(0, errors_1.agentCmd)('cred', `set ${p.name} …`)}`);
|
|
1251
|
+
later();
|
|
1252
|
+
}
|
|
1253
|
+
else if (a === 's') {
|
|
1254
|
+
let args = p.params?.preset ? [`preset=${p.params.preset}`] : [];
|
|
1255
|
+
if (!args.length) {
|
|
1256
|
+
const how = (await io.ask(` how may ${p.name} be used? (preset=<name>, or host=… header='Name: … {v}' …; cred presets lists them): `)).trim();
|
|
1257
|
+
args = opts.tokenize(how);
|
|
1258
|
+
}
|
|
1259
|
+
await credOp(ag, sealId, ['set', p.name, ...args], io, opts.agentUrl);
|
|
1260
|
+
tell.push(`[cred] I added the credential ${p.name}; it is in GET /credentials now.`);
|
|
1261
|
+
}
|
|
1262
|
+
else if (a === 'n')
|
|
1263
|
+
await refuse();
|
|
1264
|
+
else
|
|
1265
|
+
later();
|
|
1266
|
+
}
|
|
1267
|
+
else if (p.op === 'login') {
|
|
1268
|
+
const url = p.params?.url;
|
|
1269
|
+
// An existing connection is the owner's to point elsewhere, with
|
|
1270
|
+
// `connect` itself: the agent's request does not change its server.
|
|
1271
|
+
const existing = defs.find((d) => d.name === p.name)?.mcp?.url;
|
|
1272
|
+
if (url && existing && existing !== url) {
|
|
1273
|
+
io.out(` ${p.name} is connected to ${printable(existing)}; the agent asks for ${printable(url)}.`);
|
|
1274
|
+
io.out(` To change it, run: ${(0, errors_1.agentCmd)('cred', `connect ${p.name} <url>`)}`);
|
|
1275
|
+
const a = (await io.ask(` [n] refuse [Enter] later: `)).trim().toLowerCase();
|
|
1276
|
+
if (a === 'n')
|
|
1277
|
+
await refuse();
|
|
1278
|
+
else
|
|
1279
|
+
later();
|
|
1280
|
+
continue;
|
|
1281
|
+
}
|
|
1282
|
+
let host = '';
|
|
1283
|
+
try {
|
|
1284
|
+
const u = url ? new URL(url) : undefined;
|
|
1285
|
+
if (u && u.protocol === 'https:' && !u.username && !u.password)
|
|
1286
|
+
host = u.host;
|
|
1287
|
+
}
|
|
1288
|
+
catch {
|
|
1289
|
+
host = '';
|
|
1290
|
+
}
|
|
1291
|
+
const a = host ? (await io.ask(` connect ${p.name} to ${printable(host)}? [c] connect now [n] refuse [Enter] later: `)).trim().toLowerCase() : '';
|
|
1292
|
+
const moved = async () => {
|
|
1293
|
+
const now = (await cred.get(sealId)).definitions.find((d) => d.name === p.name)?.mcp?.url;
|
|
1294
|
+
return !!now && now !== url;
|
|
1295
|
+
};
|
|
1296
|
+
if (a === 'c' && url && (await moved())) {
|
|
1297
|
+
io.out(` ${p.name} was connected elsewhere meanwhile; to change it, run: ${(0, errors_1.agentCmd)('cred', `connect ${p.name} <url>`)}`);
|
|
1298
|
+
later();
|
|
1299
|
+
}
|
|
1300
|
+
else if (a === 'c' && url) {
|
|
1301
|
+
const before = (await cred.loaded(sealId, at)).entries.find((e) => e.name === p.name)?.logged_in_at;
|
|
1302
|
+
await credOp(ag, sealId, ['connect', p.name, url], { ...io, wait: false }, opts.agentUrl);
|
|
1303
|
+
io.out(' waiting for the connection to complete (Esc stops waiting, not the login)…');
|
|
1304
|
+
const deadline = Date.now() + (opts.loginWaitMs ?? 10 * 60000);
|
|
1305
|
+
let done = false;
|
|
1306
|
+
while (!done && Date.now() < deadline && !opts.signal?.aborted) {
|
|
1307
|
+
await new Promise((r) => setTimeout(r, opts.pollMs ?? 3000));
|
|
1308
|
+
const now = (await cred.loaded(sealId, at).catch(() => undefined))?.entries.find((e) => e.name === p.name)?.logged_in_at;
|
|
1309
|
+
done = !!now && now !== before;
|
|
1310
|
+
}
|
|
1311
|
+
if (done) {
|
|
1312
|
+
io.out(` connected: the agent uses [[credential:${p.name}]]`);
|
|
1313
|
+
tell.push(`[cred] I connected you: ${p.name} is in GET /credentials now.`);
|
|
1314
|
+
}
|
|
1315
|
+
else
|
|
1316
|
+
later();
|
|
1317
|
+
}
|
|
1318
|
+
else if (a === 'n')
|
|
1319
|
+
await refuse();
|
|
1320
|
+
else
|
|
1321
|
+
later();
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
catch (e) {
|
|
1325
|
+
// Cancelled (Ctrl-C or Esc at a question): this request and the ones
|
|
1326
|
+
// after it wait; the answers already given still go to the agent.
|
|
1327
|
+
if ((0, errors_1.isCancelled)(e)) {
|
|
1328
|
+
for (const q of open.slice(open.indexOf(p)))
|
|
1329
|
+
opts.later.add(q.auth_req_id);
|
|
1330
|
+
io.out(` left for later — ${(0, errors_1.agentCmd)('cred', 'pending')} lists them`);
|
|
1331
|
+
return tell;
|
|
1332
|
+
}
|
|
1333
|
+
// One request that could not be answered does not lose the answers
|
|
1334
|
+
// to the others: it is left for later and the owner is told why.
|
|
1335
|
+
io.out(` could not answer: ${printable(e instanceof Error ? e.message : String(e))}`);
|
|
1336
|
+
opts.later.add(p.auth_req_id);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
return tell;
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* The `cred` subcommands that take no agent: `pending` (counts across every
|
|
1343
|
+
* agent the wallet owns), `notify`, and `presets` (no wallet needed: `ag`
|
|
1344
|
+
* may be undefined for it). Returns false for anything else.
|
|
1345
|
+
*/
|
|
1346
|
+
async function credOwnerOp(ag, args, io) {
|
|
1347
|
+
const [sub, arg] = args;
|
|
1348
|
+
if (sub === 'presets') {
|
|
1349
|
+
if (io.json)
|
|
1350
|
+
(0, envelope_1.emitOk)({ presets: exports.CRED_PRESETS });
|
|
1351
|
+
else
|
|
1352
|
+
for (const l of renderPresets())
|
|
1353
|
+
io.out(l);
|
|
1354
|
+
return true;
|
|
1355
|
+
}
|
|
1356
|
+
if (!ag)
|
|
1357
|
+
return false;
|
|
1358
|
+
if (sub === 'pending') {
|
|
1359
|
+
// The attestor keeps each agent's count from its status reports.
|
|
1360
|
+
const rows = (await ag.credentials.pendingCounts()).filter((r) => r.pending > 0);
|
|
1361
|
+
if (io.json) {
|
|
1362
|
+
(0, envelope_1.emitOk)({ agents: rows });
|
|
1363
|
+
return true;
|
|
1364
|
+
}
|
|
1365
|
+
if (!rows.length)
|
|
1366
|
+
io.out('nothing waiting on any of your agents');
|
|
1367
|
+
for (const r of rows)
|
|
1368
|
+
io.out(`${r.agent_id ?? r.seal_id.slice(0, 12)} ${r.pending} waiting (cred ${r.agent_id ?? r.seal_id} pending)`);
|
|
1369
|
+
return true;
|
|
1370
|
+
}
|
|
1371
|
+
if (sub === 'notify') {
|
|
1372
|
+
let out;
|
|
1373
|
+
if (arg === undefined)
|
|
1374
|
+
out = await ag.credentials.notifyAddress();
|
|
1375
|
+
else if (/^(off|none|stop)$/i.test(arg))
|
|
1376
|
+
out = await ag.credentials.setNotifyAddress(null);
|
|
1377
|
+
else if (/^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/.test(arg))
|
|
1378
|
+
out = await ag.credentials.setNotifyAddress(arg);
|
|
1379
|
+
else
|
|
1380
|
+
throw new errors_1.CliError('BAD_FLAG', `not an email address: "${arg}"`, { remedy: 'cred notify you@example.com | cred notify off' });
|
|
1381
|
+
if (io.json) {
|
|
1382
|
+
(0, envelope_1.emitOk)(out);
|
|
1383
|
+
return true;
|
|
1384
|
+
}
|
|
1385
|
+
io.out(out.email ? `credential requests are emailed to ${out.email}` : 'no notification address set');
|
|
1386
|
+
if (!out.enabled)
|
|
1387
|
+
io.out('note: this attestor does not send email; check `cred pending` instead');
|
|
1388
|
+
return true;
|
|
1389
|
+
}
|
|
1390
|
+
return false;
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Read a value without echoing it: all of stdin when it is piped, otherwise
|
|
1394
|
+
* a raw-mode prompt on the terminal that shows `*` per character.
|
|
1395
|
+
*/
|
|
1396
|
+
async function readSecret(prompt) {
|
|
1397
|
+
const stdin = process.stdin;
|
|
1398
|
+
if (!stdin.isTTY) {
|
|
1399
|
+
const chunks = [];
|
|
1400
|
+
for await (const c of stdin)
|
|
1401
|
+
chunks.push(c);
|
|
1402
|
+
return Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, '');
|
|
1403
|
+
}
|
|
1404
|
+
process.stderr.write(prompt);
|
|
1405
|
+
stdin.setRawMode(true);
|
|
1406
|
+
stdin.resume();
|
|
1407
|
+
return new Promise((resolve, reject) => {
|
|
1408
|
+
let buf = '';
|
|
1409
|
+
const done = () => {
|
|
1410
|
+
stdin.off('data', onData);
|
|
1411
|
+
stdin.setRawMode(false);
|
|
1412
|
+
stdin.pause();
|
|
1413
|
+
process.stderr.write('\n');
|
|
1414
|
+
};
|
|
1415
|
+
const onData = (d) => {
|
|
1416
|
+
for (const ch of d.toString('utf8')) {
|
|
1417
|
+
if (ch === '\r' || ch === '\n') {
|
|
1418
|
+
done();
|
|
1419
|
+
resolve(buf);
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
if (ch === '\u0003' || ch === '\u0004') {
|
|
1423
|
+
done();
|
|
1424
|
+
reject((0, errors_1.cancelled)());
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
if (ch === '\u007f' || ch === '\b') {
|
|
1428
|
+
if (buf) {
|
|
1429
|
+
buf = [...buf].slice(0, -1).join('');
|
|
1430
|
+
process.stderr.write('\b \b');
|
|
1431
|
+
}
|
|
1432
|
+
continue;
|
|
1433
|
+
}
|
|
1434
|
+
if (ch < ' ')
|
|
1435
|
+
continue;
|
|
1436
|
+
buf += ch;
|
|
1437
|
+
process.stderr.write('*');
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
stdin.on('data', onData);
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
//# sourceMappingURL=credentials.js.map
|