@jini-ai/core 0.6.22 → 0.7.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 (61) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/approval.d.ts +49 -3
  3. package/dist/approval.js +47 -10
  4. package/dist/batch-tool-inputs.d.ts +13 -0
  5. package/dist/batch-tool-inputs.js +37 -6
  6. package/dist/contracts/cards.d.ts +382 -0
  7. package/dist/contracts/cards.js +2 -0
  8. package/dist/contracts/content-types.d.ts +32 -0
  9. package/dist/contracts/content-types.js +3 -0
  10. package/dist/contracts/credentials.d.ts +402 -0
  11. package/dist/contracts/credentials.js +2 -0
  12. package/dist/contracts/hosted-mcp/config.d.ts +253 -0
  13. package/dist/contracts/hosted-mcp/config.js +2 -0
  14. package/dist/contracts/hosted-mcp/record.d.ts +198 -0
  15. package/dist/contracts/hosted-mcp/record.js +2 -0
  16. package/dist/contracts/hosted-mcp/vocabulary.d.ts +14 -0
  17. package/dist/contracts/hosted-mcp/vocabulary.js +2 -0
  18. package/dist/contracts/hosted-mcp.d.ts +5 -0
  19. package/dist/contracts/hosted-mcp.js +2 -0
  20. package/dist/contracts/mail/adapter-module.d.ts +31 -0
  21. package/dist/contracts/mail/adapter-module.js +2 -0
  22. package/dist/contracts/mail/engine-contracts.d.ts +130 -0
  23. package/dist/contracts/mail/engine-contracts.js +2 -0
  24. package/dist/contracts/mail/ports.d.ts +93 -0
  25. package/dist/contracts/mail/ports.js +3 -0
  26. package/dist/contracts/mail/provider.d.ts +84 -0
  27. package/dist/contracts/mail/provider.js +2 -0
  28. package/dist/contracts/mail.d.ts +128 -0
  29. package/dist/contracts/mail.js +3 -0
  30. package/dist/contracts/oauth/details.d.ts +46 -0
  31. package/dist/contracts/oauth/details.js +2 -0
  32. package/dist/contracts/oauth/flow.d.ts +253 -0
  33. package/dist/contracts/oauth/flow.js +2 -0
  34. package/dist/contracts/oauth.d.ts +139 -0
  35. package/dist/contracts/oauth.js +2 -0
  36. package/dist/contracts/vault/ports.d.ts +34 -0
  37. package/dist/contracts/vault/ports.js +2 -0
  38. package/dist/contracts/vault/records.d.ts +149 -0
  39. package/dist/contracts/vault/records.js +2 -0
  40. package/dist/contracts/vault/vendor-credential-sets.d.ts +75 -0
  41. package/dist/contracts/vault/vendor-credential-sets.js +7 -0
  42. package/dist/contracts/vault.d.ts +14 -0
  43. package/dist/contracts/vault.js +2 -0
  44. package/dist/index.d.ts +2 -0
  45. package/dist/index.js +1 -0
  46. package/dist/primitives/http.d.ts +2 -0
  47. package/dist/settings/agent-value-write-tools.d.ts +3 -1
  48. package/dist/settings/agent-value-write-tools.js +11 -4
  49. package/dist/settings/tool-registrations.js +1 -1
  50. package/dist/surface-cards.d.ts +2 -0
  51. package/dist/surface-cards.js +2 -0
  52. package/dist/teardown.d.ts +30 -0
  53. package/dist/teardown.js +43 -0
  54. package/dist/text/descriptor-i18n.d.ts +24 -0
  55. package/dist/text/descriptor-i18n.js +65 -0
  56. package/dist/text/index.d.ts +2 -0
  57. package/dist/text/index.js +1 -0
  58. package/dist/tool-metadata-types.d.ts +6 -0
  59. package/dist/user-facing-error.d.ts +28 -1
  60. package/dist/user-facing-error.js +87 -4
  61. package/package.json +44 -2
@@ -0,0 +1,149 @@
1
+ import type { SealedSecret } from '../vault.js';
2
+ /** @agent-note Types only. The runtime parts come from the host; this area usually from `@jini-ai/platform`. */
3
+ /** `custom` remains readable/replaceable until each workspace activates its data migration. */
4
+ export type VaultKind = "site-assistant" | "personal-execution" | "media-provider" | "publish-peer" | "database-destination" | "vendor" | "source-control" | "mcp-env" | "mcp-auth" | "api-connection" | "custom";
5
+ export type CredentialType = "vendor" | "custom";
6
+ /** Required metadata on every active vendor-kind credential. Subtype is immutable after create. */
7
+ export type CredentialMeta = VaultMeta & {
8
+ credentialType: CredentialType;
9
+ worksFor: string[];
10
+ };
11
+ export type VaultJson = null | boolean | number | string | VaultJson[] | {
12
+ [key: string]: VaultJson;
13
+ };
14
+ export type VaultMeta = {
15
+ [key: string]: VaultJson;
16
+ };
17
+ export type VaultOptions = Record<string, never>;
18
+ /** Expected ownership is supplied by the caller, never reconstructed from an untrusted row. */
19
+ export interface VaultContext {
20
+ workspaceId: string;
21
+ kind: VaultKind;
22
+ ownerKey: string;
23
+ principalId: string | null;
24
+ /** Host-canonicalized endpoint/resource binding; null for credentials without such a binding. */
25
+ binding: string | null;
26
+ }
27
+ export interface VaultIdentity extends VaultContext {
28
+ id: string;
29
+ }
30
+ export interface VaultRecord extends VaultIdentity {
31
+ provider: string | null;
32
+ label: string;
33
+ isDefault: boolean;
34
+ revision: number;
35
+ sealed: SealedSecret | null;
36
+ last4: string | null;
37
+ tokenLength: number | null;
38
+ meta: VaultMeta;
39
+ createdAt: string;
40
+ updatedAt: string;
41
+ }
42
+ export type VaultSummary = Omit<VaultRecord, "sealed"> & {
43
+ configured: boolean;
44
+ };
45
+ /** Unspecified placement lets the repo auto-default a group's first row; false opts out.
46
+ * Persisted records and read models always contain a concrete boolean.
47
+ */
48
+ export type VaultPutRecord = Omit<VaultRecord, "isDefault"> & {
49
+ isDefault?: boolean | undefined;
50
+ };
51
+ export interface VaultQuery {
52
+ workspaceId: string;
53
+ kind: VaultKind;
54
+ ownerKey: string;
55
+ principalId: string | null;
56
+ provider?: string | null | undefined;
57
+ }
58
+ /** A default belongs to one exact group; omitted provider never means all providers. */
59
+ export interface VaultDefaultQuery extends VaultQuery {
60
+ provider: string | null;
61
+ }
62
+ /** Singleton lookup ignores provider/default; omitted owner/principal leave that dimension unfiltered.
63
+ * Hosts enforce singleton cardinality for their kind/scope. No binding is inferred by the service.
64
+ */
65
+ export interface VaultSingletonQuery {
66
+ workspaceId: string;
67
+ kind: VaultKind;
68
+ ownerKey?: string | undefined;
69
+ principalId?: string | null | undefined;
70
+ }
71
+ /** Ordered CAS operations; default side effects affect later operations' revisions. */
72
+ export type VaultBatchOp = {
73
+ put: {
74
+ record: VaultPutRecord;
75
+ expectedRevision: number | null;
76
+ };
77
+ } | {
78
+ delete: {
79
+ workspaceId: string;
80
+ id: string;
81
+ expectedRevision: number;
82
+ };
83
+ } | {
84
+ patchMeta: {
85
+ workspaceId: string;
86
+ id: string;
87
+ expectedRevision: number;
88
+ patch: VaultMeta;
89
+ updatedAt: string;
90
+ };
91
+ };
92
+ export type VaultBatchResult = VaultRecord | boolean;
93
+ export interface VaultCopyResult {
94
+ kind: VaultKind;
95
+ id: string;
96
+ status: "copied" | "skipped" | "failed";
97
+ last4?: string;
98
+ reasonCode?: VaultErrorCode | "source-needs-upgrade" | "source-missing" | "target-exists" | "kind-not-copyable" | "requires-mcp-configuration" | "copy-failed";
99
+ }
100
+ export type VaultMetaParser = (input: {
101
+ meta: unknown;
102
+ provider?: string | null | undefined;
103
+ }, options?: VaultOptions) => VaultMeta;
104
+ export type VaultMetaParsers = Readonly<Record<VaultKind, VaultMetaParser>>;
105
+ /** CAS is mandatory: null creates only; a number replaces/deletes only that revision.
106
+ * Defaults group by workspace/kind/owner/principal/provider. Every default change increments
107
+ * revision; promotion uses updatedAt descending, then id descending (binary UTF-8 order).
108
+ * All writes must join a host transaction when the adapter supports transaction composition.
109
+ */
110
+ export interface VaultRepoPort {
111
+ find(input: {
112
+ workspaceId: string;
113
+ id: string;
114
+ }, options?: VaultOptions): Promise<VaultRecord | null>;
115
+ /** Indexed exact-group lookup; returns at most one row without listing its siblings.
116
+ * Optional for compatibility with pre-C1 ports; both built-in adapters implement it.
117
+ */
118
+ findDefault?(input: VaultDefaultQuery, options?: VaultOptions): Promise<VaultRecord | null>;
119
+ /** Optional additions keep older injected ports source-compatible; built-in adapters implement both. */
120
+ findOne?(input: VaultSingletonQuery, options?: VaultOptions): Promise<VaultRecord | null>;
121
+ /** All operations commit together or throw with no published changes. Default side effects
122
+ * follow operation order; a delete carries full expected ownership.
123
+ * SQL joins the host transaction: callers must propagate failures to roll that transaction back.
124
+ * @example await repo.applyBatch!({ ops: [{ put: { record, expectedRevision: null } }] });
125
+ */
126
+ applyBatch?(input: {
127
+ ops: readonly VaultBatchOp[];
128
+ }, options?: VaultOptions): Promise<VaultBatchResult[]>;
129
+ list(input: VaultQuery, options?: VaultOptions): Promise<VaultRecord[]>;
130
+ put(input: {
131
+ record: VaultPutRecord;
132
+ expectedRevision: number | null;
133
+ }, options?: VaultOptions): Promise<VaultRecord>;
134
+ /** Service-validated patch: top-level keys are plain JSON-path identifiers. */
135
+ patchMeta(input: {
136
+ workspaceId: string;
137
+ id: string;
138
+ expectedRevision: number;
139
+ patch: VaultMeta;
140
+ updatedAt: string;
141
+ }, options?: VaultOptions): Promise<VaultRecord>;
142
+ delete(input: {
143
+ workspaceId: string;
144
+ id: string;
145
+ expectedRevision: number;
146
+ }, options?: VaultOptions): Promise<boolean>;
147
+ }
148
+ export type VaultErrorCode = "conflict" | "context" | "invalid-meta" | "invalid-record";
149
+ //# sourceMappingURL=records.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=records.js.map
@@ -0,0 +1,75 @@
1
+ /** @agent-note Types only. The runtime parts come from the host; this area usually from `@jini-ai/platform`. */
2
+ /** Host-neutral credential records and workspace-scoped repository contracts.
3
+ * insert/update clear other defaults in the same vendor group; deleting a default promotes
4
+ * the most recently updated remaining row. Summaries never include sealed payloads.
5
+ */
6
+ import type { SealedSecret } from "../vault.js";
7
+ export interface VendorCredentialSetRecord {
8
+ readonly workspaceId: string;
9
+ readonly id: string;
10
+ /** Open string so plugin hosts can declare vendors beyond the built-in validators. */
11
+ readonly vendorId: string;
12
+ /** Optional only for historical DTO producers; unified vault metadata requires this subtype. */
13
+ readonly credentialType?: "vendor";
14
+ /** Explicit compatibility IDs, independent of label; omitted by historical DTO producers. */
15
+ readonly worksFor?: readonly string[];
16
+ readonly label: string;
17
+ readonly sealed: SealedSecret;
18
+ /** Last four secret characters for recognition, stored in clear; a suffix alone is not the token. */
19
+ readonly tokenTail: string;
20
+ /** At most one default per (workspaceId, vendorId), maintained by the store/repository write path. */
21
+ readonly isDefault: boolean;
22
+ /** Only a verified public login belongs here; null until verification populates it. */
23
+ readonly accountLabel: string | null;
24
+ readonly createdAt: string;
25
+ readonly updatedAt: string;
26
+ }
27
+ export interface VendorCredentialSetSummary {
28
+ readonly id: string;
29
+ readonly vendorId: string;
30
+ /** Optional for compatibility with historical summaries. */
31
+ readonly credentialType?: "vendor";
32
+ readonly worksFor?: readonly string[];
33
+ readonly label: string;
34
+ readonly configured: true;
35
+ readonly isDefault: boolean;
36
+ readonly tokenTail: string;
37
+ readonly accountLabel: string | null;
38
+ readonly createdAt: string;
39
+ readonly updatedAt: string;
40
+ }
41
+ export interface VendorCredentialSetRepoPort {
42
+ insert(record: VendorCredentialSetRecord): Promise<void>;
43
+ /** Full-row replacement supports rename and secret rotation; label uniqueness can still reject it. */
44
+ update(record: VendorCredentialSetRecord): Promise<void>;
45
+ findById(input: {
46
+ workspaceId: string;
47
+ id: string;
48
+ }): Promise<VendorCredentialSetRecord | null>;
49
+ findDefaultByVendor(input: {
50
+ workspaceId: string;
51
+ vendorId: string;
52
+ }): Promise<VendorCredentialSetRecord | null>;
53
+ /** Lets the store recognize a group's first row and choose a promotion candidate before deletion. */
54
+ listByVendor(input: {
55
+ workspaceId: string;
56
+ vendorId: string;
57
+ }): Promise<VendorCredentialSetRecord[]>;
58
+ /** Intentionally unpaginated for a human-managed connection list, rather than a bulk credential inventory. */
59
+ listByWorkspace(input: {
60
+ workspaceId: string;
61
+ }): Promise<VendorCredentialSetRecord[]>;
62
+ /** Missing (workspaceId, id) is a no-op so repeated deletes remain idempotent. */
63
+ delete(input: {
64
+ workspaceId: string;
65
+ id: string;
66
+ }): Promise<void>;
67
+ /** Target only accountLabel: verification must not rewrite sealed/default/tail/updatedAt state.
68
+ * A missing row is a no-op, as with delete. */
69
+ updateAccountLabel(input: {
70
+ workspaceId: string;
71
+ id: string;
72
+ accountLabel: string;
73
+ }): Promise<void>;
74
+ }
75
+ //# sourceMappingURL=vendor-credential-sets.d.ts.map
@@ -0,0 +1,7 @@
1
+ /** @agent-note Types only. The runtime parts come from the host; this area usually from `@jini-ai/platform`. */
2
+ /** Host-neutral credential records and workspace-scoped repository contracts.
3
+ * insert/update clear other defaults in the same vendor group; deleting a default promotes
4
+ * the most recently updated remaining row. Summaries never include sealed payloads.
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=vendor-credential-sets.js.map
@@ -0,0 +1,14 @@
1
+ /** @agent-note Types only. The runtime parts come from the host; this area usually from `@jini-ai/platform`. */
2
+ /** Persisted envelope: base64 ciphertext followed by the GCM tag, plus a base64 IV. */
3
+ export interface SealedSecret {
4
+ keyId: string;
5
+ /** Base64 of encrypted bytes followed by the 16-byte authentication tag. */
6
+ ciphertext: string;
7
+ /** Base64 of the 12-byte IV. */
8
+ nonce: string;
9
+ alg: string;
10
+ }
11
+ export type * from './vault/ports.js';
12
+ export type * from './vault/vendor-credential-sets.js';
13
+ export type * from './vault/records.js';
14
+ //# sourceMappingURL=vault.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=vault.js.map
package/dist/index.d.ts CHANGED
@@ -8,10 +8,12 @@ export type { PackDisposalFailure } from './pack-lifecycle.js';
8
8
  export { disposePacks, registerPackTools } from './pack-lifecycle.js';
9
9
  export * from './redact.js';
10
10
  export * from './user-facing-error.js';
11
+ export { onTeardown, runTeardownSteps, type TeardownHost, type TeardownStep } from './teardown.js';
11
12
  export * from './api-token-auth.js';
12
13
  export * from './origin-validation.js';
13
14
  export * from './principal.js';
14
15
  export * from './surface-exchanges.js';
16
+ export type * from './surface-cards.js';
15
17
  export type { AuthorizationDecision, RunRef, SurfaceEmission, SurfaceEmitter, ToolAuthorizationContext, ToolDescriptor, ToolExecutionContext, ToolExecutionOptions, ToolApprovalDecision, ToolHandler, ToolPolicy, ToolRegistration, ToolRegistry, } from './tool-registry.js';
16
18
  export { createToolRegistrationScope, toolRegistryRevision, createToolRegistry, isReadOnlyTool, toolDiscoveryMetadata, ToolInputError } from './tool-registry.js';
17
19
  export * from './tool-tokens.js';
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { createDaemon } from './daemon.js';
6
6
  export { disposePacks, registerPackTools } from './pack-lifecycle.js';
7
7
  export * from './redact.js';
8
8
  export * from './user-facing-error.js';
9
+ export { onTeardown, runTeardownSteps } from './teardown.js';
9
10
  export * from './api-token-auth.js';
10
11
  export * from './origin-validation.js';
11
12
  export * from './principal.js';
@@ -14,6 +14,8 @@ export type HttpRequest = {
14
14
  signal?: AbortSignal;
15
15
  /** Caller byte ceilings are bounded by the client policy, never a way to widen its cap. */
16
16
  maxResponseBytes?: number;
17
+ /** Binary consumers can omit the decoded text representation. */
18
+ bodyAs?: "bytes";
17
19
  } & ({
18
20
  idleTimeoutMs: number; /** Legacy alias for the socket idle budget. */
19
21
  timeoutMs?: number;
@@ -5,7 +5,7 @@ import type { SettingsToolDeps } from "./tool-registrations.js";
5
5
  import { type SettingsWriteServiceDeps } from "./write-service.js";
6
6
  export type SettingsValueWriteToolId = "settings_set_value" | "settings_clear_value";
7
7
  /** Host-only port. This request is never an agent input and only the host's authenticated
8
- * human transport or a persisted human identity grant may answer it. Model input never authorizes it. */
8
+ * human transport may answer it. Model input and remembered grants never authorize access changes. */
9
9
  export interface SettingsWriteConfirmation {
10
10
  ctx: ToolExecutionContext;
11
11
  toolId: SettingsValueWriteToolId;
@@ -13,6 +13,8 @@ export interface SettingsWriteConfirmation {
13
13
  key: string;
14
14
  scope: "workspace" | "user";
15
15
  previous: JsonValue | null;
16
+ /** The addressed override's revision, fixed before asking; 0 means no stored row. */
17
+ expectedRevisionSeq: number;
16
18
  value?: JsonValue;
17
19
  reason: string;
18
20
  }
@@ -1,7 +1,7 @@
1
1
  import { adaptLegacyAuthorize, ForbiddenError as PermissionDeniedError, requireToolPermission } from "../tool-permissions.js";
2
2
  import { ToolInputError } from "../tool-registry.js";
3
3
  import { AGENT_WRITE_CONFIRMATION_SETTINGS, AGENT_WRITE_DENIED_SETTINGS, findAgentWriteRule } from "./agent-write-denylist.js";
4
- import { DefinitionNotFoundError, DefinitionTombstonedError, ForbiddenError, ScopeNotAllowedError, ValueValidationFailedError } from "./errors.js";
4
+ import { DefinitionNotFoundError, DefinitionTombstonedError, ForbiddenError, ScopeNotAllowedError, SettingsRevisionConflictError, ValueValidationFailedError } from "./errors.js";
5
5
  import { getEffective, resolveDefinitionRaw, validateValueAgainstSchema } from "./settings.js";
6
6
  import { SCOPE_BIT } from "./types.js";
7
7
  import { clear, deriveRequiredPermission, set } from "./write-service.js";
@@ -73,6 +73,8 @@ async function resolveTarget(deps, target, isSet) {
73
73
  throw new DefinitionNotFoundError(`setting '${name}' was not found`);
74
74
  if (definition.status === "tombstone")
75
75
  throw new DefinitionTombstonedError(`setting '${name}' has been tombstoned`);
76
+ if (definition.secret)
77
+ throw new ToolInputError({ message: `${isSet ? "settings_set_value" : "settings_clear_value"}: '${definition.namespace}.${definition.key}' is a secret setting. Use its dedicated credential-entry or sign-in tool. Nothing was changed.` });
76
78
  const scopeAllowed = (definition.scopes & SCOPE_BIT[target.scope]) !== 0;
77
79
  if (!scopeAllowed)
78
80
  throw new ScopeNotAllowedError(name);
@@ -113,6 +115,8 @@ function writePolicy(deps, toolId, target, definition) {
113
115
  }
114
116
  /** Maps expected caller-fixable errors; infrastructure failures remain untouched. O(1). */
115
117
  function rethrowWriteError(error, toolId, target, permission) {
118
+ if (error instanceof SettingsRevisionConflictError)
119
+ throw new ToolInputError({ message: `${toolId}: this setting changed before the approved change could be saved. Read it again and request a new confirmation. Nothing was changed by this call.` }, { cause: error });
116
120
  if (error instanceof DefinitionNotFoundError || error instanceof DefinitionTombstonedError)
117
121
  throw new ToolInputError({ message: `${toolId}: ${error.message}. Call settings_list_definitions to see valid keys.` }, { cause: error });
118
122
  if (error instanceof ScopeNotAllowedError)
@@ -168,7 +172,7 @@ async function confirmProtectedWrite(deps, request, prepared, options) {
168
172
  const isSet = toolId === "settings_set_value";
169
173
  if (!deps.confirmWrite)
170
174
  throw new ToolInputError({ message: `${toolId}: '${rule.namespace}.${rule.key}' requires a human confirmation card: ${rule.reason}. The owner can change it in Settings.` });
171
- const confirmed = await deps.confirmWrite({ ctx, toolId, namespace: rule.namespace, key: rule.key, scope: target.scope, previous: structuredClone(previous), ...(isSet ? { value: structuredClone(target.value) } : {}), reason: rule.reason }, options);
175
+ const confirmed = await deps.confirmWrite({ ctx, toolId, namespace: definition.namespace, key: definition.key, scope: target.scope, previous: structuredClone(previous), expectedRevisionSeq: layer === null ? 0 : layer.seq, ...(isSet ? { value: structuredClone(target.value) } : {}), reason: rule.reason }, options);
172
176
  if (confirmed !== true)
173
177
  throw new ToolInputError({ message: `${toolId}: the human did not confirm the change. Nothing was changed.` });
174
178
  const current = await resolveTarget(deps, target, isSet);
@@ -184,11 +188,14 @@ async function applyWrite(deps, request, prepared) {
184
188
  // Resolved coordinates preserve host validators even when the request named an alias.
185
189
  const input = { namespace: definition.namespace, key: definition.key, scope: target.scope, workspaceId: deps.workspaceId, callerPrincipalId: ctx.principal.id, authWorkspaceId: deps.workspaceId };
186
190
  const key = `${target.namespace}.${target.key}`;
191
+ // The post-card read gives a readable stale-card refusal; this transactional guard also closes
192
+ // the race while a host validator awaits between that read and the ledger write.
193
+ const options = prepared.rule ? { expectedRevisionSeq: prepared.layer?.seq ?? 0 } : {};
187
194
  if (toolId === "settings_set_value") {
188
- const result = await (deps.setValue ?? set)({ deps: writeDeps, input: { ...input, value: target.value } });
195
+ const result = await (deps.setValue ?? set)({ deps: writeDeps, input: { ...input, value: target.value } }, options);
189
196
  return { key, scope: target.scope, previous, value: result.value, revisionSeq: result.revisionSeq };
190
197
  }
191
- await clear({ deps: writeDeps, input });
198
+ await clear({ deps: writeDeps, input }, options);
192
199
  const effective = await getEffective({ repo: deps.settingsRepo }, { namespace: definition.namespace, key: definition.key, scopeContext: { workspaceId: deps.workspaceId, principalId: ctx.principal.id } });
193
200
  return { key, scope: target.scope, previous, effective: effective?.value ?? null };
194
201
  }
@@ -122,7 +122,7 @@ async function describeDefinitionForAgent(routeDeps, rules, def) {
122
122
  /** Mirrors the write handler's refusals: live target, not denied, confirmable when protected,
123
123
  * and writable at workspace or user scope. O(1). */
124
124
  function isAgentWritable(facts) {
125
- if (!facts.resolved || facts.resolved.status === "tombstone" || facts.denied)
125
+ if (!facts.resolved || facts.resolved.status === "tombstone" || facts.resolved.secret || facts.denied)
126
126
  return false;
127
127
  if (facts.confirmationRequired && !facts.canConfirm)
128
128
  return false;
@@ -0,0 +1,2 @@
1
+ export type * from './contracts/cards.js';
2
+ //# sourceMappingURL=surface-cards.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=surface-cards.js.map
@@ -0,0 +1,30 @@
1
+ /** A cleanup step may be synchronous or asynchronous; failures are reported after all steps run. */
2
+ export type TeardownStep = () => unknown;
3
+ /** Injected lifecycle registration; core has no dependency on a particular test runner or host. */
4
+ export interface TeardownHost {
5
+ after(fn: () => unknown): void;
6
+ }
7
+ /**
8
+ * Attempt every step in reverse registration order. Preserve a single failure's identity;
9
+ * report several as an AggregateError only after attempting the remaining cleanup.
10
+ * @param requiredArgs Steps owned by one lifecycle context; the input array is not mutated.
11
+ * @returns Resolves after cleanup, or rejects with the collected failure(s).
12
+ * @complexity O(n) time and space for n registered steps, excluding each step's own work.
13
+ * @example await runTeardownSteps({ steps: [closeDatabase, closeServer] });
14
+ */
15
+ export declare function runTeardownSteps({ steps }: {
16
+ steps: readonly TeardownStep[];
17
+ }, _options?: {}): Promise<void>;
18
+ /**
19
+ * Queue a step on the host's single cleanup hook. Hosts that stop at the first throwing hook
20
+ * still attempt every registered resource cleanup before this hook reports a failure.
21
+ * @param requiredArgs Lifecycle host and a step to run when that host finishes.
22
+ * @returns Nothing; registers one hook on first use, then appends to that host's queue.
23
+ * @complexity O(1) registration; cleanup is O(n) time/space for n registered steps.
24
+ * @example onTeardown({ t: context, step: closeServer });
25
+ */
26
+ export declare function onTeardown({ t, step }: {
27
+ t: TeardownHost;
28
+ step: TeardownStep;
29
+ }, _options?: {}): void;
30
+ //# sourceMappingURL=teardown.d.ts.map
@@ -0,0 +1,43 @@
1
+ const queues = new WeakMap();
2
+ /**
3
+ * Attempt every step in reverse registration order. Preserve a single failure's identity;
4
+ * report several as an AggregateError only after attempting the remaining cleanup.
5
+ * @param requiredArgs Steps owned by one lifecycle context; the input array is not mutated.
6
+ * @returns Resolves after cleanup, or rejects with the collected failure(s).
7
+ * @complexity O(n) time and space for n registered steps, excluding each step's own work.
8
+ * @example await runTeardownSteps({ steps: [closeDatabase, closeServer] });
9
+ */
10
+ export async function runTeardownSteps({ steps }, _options = {}) {
11
+ const failures = [];
12
+ for (const step of [...steps].reverse()) {
13
+ try {
14
+ await step();
15
+ }
16
+ catch (error) {
17
+ failures.push(error);
18
+ }
19
+ }
20
+ if (failures.length === 1)
21
+ throw failures[0];
22
+ if (failures.length > 1)
23
+ throw new AggregateError(failures, "test teardown failed", { cause: failures[0] });
24
+ }
25
+ /**
26
+ * Queue a step on the host's single cleanup hook. Hosts that stop at the first throwing hook
27
+ * still attempt every registered resource cleanup before this hook reports a failure.
28
+ * @param requiredArgs Lifecycle host and a step to run when that host finishes.
29
+ * @returns Nothing; registers one hook on first use, then appends to that host's queue.
30
+ * @complexity O(1) registration; cleanup is O(n) time/space for n registered steps.
31
+ * @example onTeardown({ t: context, step: closeServer });
32
+ */
33
+ export function onTeardown({ t, step }, _options = {}) {
34
+ const queued = queues.get(t);
35
+ if (queued) {
36
+ queued.push(step);
37
+ return;
38
+ }
39
+ const steps = [step];
40
+ queues.set(t, steps);
41
+ t.after(() => runTeardownSteps({ steps }));
42
+ }
43
+ //# sourceMappingURL=teardown.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @file The optional `i18n` block a plugin descriptor carries so its own person-facing text (labels,
3
+ * help, guidance) renders in the viewer's language without core naming the plugin's strings.
4
+ *
5
+ * Shape: `{ "<locale>": { "<English source text>": "<translation>" } }`. Keyed by the exact English
6
+ * string the descriptor declares, so the admin looks a string up by the text it already has and falls
7
+ * back to that English when a locale or a string has no entry. A key that matches no descriptor string
8
+ * is harmless (never shown), so a reworded English string only loses its translation, never the host.
9
+ *
10
+ * Shared by every descriptor parser that has person-facing text (deploy targets,
11
+ * `@jini-ai/devops/deploy`'s `parseDeployTargetsFile`; a host's own descriptor parsers).
12
+ */
13
+ /** Locale → English source text → translation. */
14
+ export type DescriptorI18n = Readonly<Record<string, Readonly<Record<string, string>>>>;
15
+ /**
16
+ * A descriptor's `i18n` block (absent = English only), or the reason it is invalid.
17
+ *
18
+ * @complexity O(l·e) in locales times entries, both capped.
19
+ */
20
+ export declare function parseDescriptorI18n({ value, at }: {
21
+ readonly value: unknown;
22
+ readonly at: string;
23
+ }, _optional?: Record<string, never>): DescriptorI18n | undefined | string;
24
+ //# sourceMappingURL=descriptor-i18n.d.ts.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @file The optional `i18n` block a plugin descriptor carries so its own person-facing text (labels,
3
+ * help, guidance) renders in the viewer's language without core naming the plugin's strings.
4
+ *
5
+ * Shape: `{ "<locale>": { "<English source text>": "<translation>" } }`. Keyed by the exact English
6
+ * string the descriptor declares, so the admin looks a string up by the text it already has and falls
7
+ * back to that English when a locale or a string has no entry. A key that matches no descriptor string
8
+ * is harmless (never shown), so a reworded English string only loses its translation, never the host.
9
+ *
10
+ * Shared by every descriptor parser that has person-facing text (deploy targets,
11
+ * `@jini-ai/devops/deploy`'s `parseDeployTargetsFile`; a host's own descriptor parsers).
12
+ */
13
+ /** A BCP 47-shaped tag as the admin's locales spell them (`es`, `pt-BR`, `zh-TW`). */
14
+ const LOCALE_PATTERN = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
15
+ const MAX_LOCALES = 64;
16
+ const MAX_ENTRIES_PER_LOCALE = 200;
17
+ /** Matches the longest descriptor string (a help text). */
18
+ const MAX_SOURCE_LENGTH = 500;
19
+ /** Translations run longer than their English source. */
20
+ const MAX_TRANSLATION_LENGTH = 2000;
21
+ /**
22
+ * A descriptor's `i18n` block (absent = English only), or the reason it is invalid.
23
+ *
24
+ * @complexity O(l·e) in locales times entries, both capped.
25
+ */
26
+ export function parseDescriptorI18n({ value, at }, _optional = {}) {
27
+ if (value === undefined)
28
+ return undefined;
29
+ if (!isPlainObject(value))
30
+ return `${at} must map locales to translations`;
31
+ const locales = Object.entries(value);
32
+ if (locales.length > MAX_LOCALES)
33
+ return `${at} must declare at most ${MAX_LOCALES} locales`;
34
+ const parsed = {};
35
+ for (const [locale, entries] of locales) {
36
+ if (!LOCALE_PATTERN.test(locale))
37
+ return `${at} has an invalid locale '${locale}'`;
38
+ const translations = parseLocaleTranslations({ entries, at: `${at}.${locale}` });
39
+ if (typeof translations === "string")
40
+ return translations;
41
+ parsed[locale] = translations;
42
+ }
43
+ return parsed;
44
+ }
45
+ function isPlainObject(value) {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+ /** Validate one locale's bounded dictionary, retaining the first invalid entry's reason. */
49
+ function parseLocaleTranslations(input, _options = {}) {
50
+ const { entries, at } = input;
51
+ if (!isPlainObject(entries))
52
+ return `${at} must map English text to its translation`;
53
+ const pairs = Object.entries(entries);
54
+ if (pairs.length > MAX_ENTRIES_PER_LOCALE)
55
+ return `${at} must declare at most ${MAX_ENTRIES_PER_LOCALE} strings`;
56
+ for (const [source, translation] of pairs) {
57
+ if (source.trim() === "" || source.length > MAX_SOURCE_LENGTH)
58
+ return `${at} keys must be non-empty English text of at most ${MAX_SOURCE_LENGTH} characters`;
59
+ if (typeof translation !== "string" || translation.trim() === "" || translation.length > MAX_TRANSLATION_LENGTH) {
60
+ return `${at} translations must be non-empty strings of at most ${MAX_TRANSLATION_LENGTH} characters`;
61
+ }
62
+ }
63
+ return Object.fromEntries(pairs);
64
+ }
65
+ //# sourceMappingURL=descriptor-i18n.js.map
@@ -3,4 +3,6 @@ export type { SanitizeTextOptions } from './sanitize-untrusted-text.js';
3
3
  export { escapeHtml, escapeXml } from "./escape.js";
4
4
  export { trimChars, trimCharsEnd, trimCharsStart } from "../primitives/trim-chars.js";
5
5
  export { captureLineTail } from "./line-tail.js";
6
+ export { parseDescriptorI18n } from "./descriptor-i18n.js";
7
+ export type { DescriptorI18n } from "./descriptor-i18n.js";
6
8
  //# sourceMappingURL=index.d.ts.map
@@ -2,4 +2,5 @@ export { sanitizeUntrustedText, stripControlSequences } from './sanitize-untrust
2
2
  export { escapeHtml, escapeXml } from "./escape.js";
3
3
  export { trimChars, trimCharsEnd, trimCharsStart } from "../primitives/trim-chars.js";
4
4
  export { captureLineTail } from "./line-tail.js";
5
+ export { parseDescriptorI18n } from "./descriptor-i18n.js";
5
6
  //# sourceMappingURL=index.js.map
@@ -9,6 +9,12 @@ export interface ToolApprovalMetadata {
9
9
  export interface ToolMetadata<A extends ToolApprovalMetadata = ToolApprovalMetadata> {
10
10
  /** Human-facing action name and optional button verb; presentation only, never authority. */
11
11
  readonly title?: string;
12
+ /** Public federation provenance only; credentials, complete URLs and command arguments are excluded. */
13
+ readonly mcpSource?: {
14
+ readonly id: string;
15
+ readonly host: string;
16
+ readonly pluginId?: string;
17
+ };
12
18
  /** Plain-language consequence shown before approval; never used to classify or authorize. */
13
19
  readonly summary?: string;
14
20
  readonly actionVerb?: string;
@@ -1,5 +1,5 @@
1
1
  import { type SecretRedactionOptions } from './redact.js';
2
- /** Sanitized explanation and copyable evidence. Missing boundary metadata stays explicitly unavailable. */
2
+ /** Sanitized explanation and copyable evidence. Missing boundary metadata is omitted from the copyable evidence. */
3
3
  export interface UserFacingError {
4
4
  readonly message: string;
5
5
  readonly action: string;
@@ -24,6 +24,7 @@ export interface UserFacingErrorOptions extends SecretRedactionOptions {
24
24
  * Redacts complete fields before bounding them; uses an existing ERR ID before a boundary fallback.
25
25
  * No I/O, logging, clock, randomness or input mutation. Core handles hostile/circular causes.
26
26
  * @complexity O(n) diagnostic serialization plus core redaction over all input characters; bounded output.
27
+ * @overallScore 98 — callers own disclosure; public ID shapes do not override credential or exact-secret rules.
27
28
  */
28
29
  export declare function formatUserFacingError(requiredArgs: {
29
30
  message: string;
@@ -31,4 +32,30 @@ export declare function formatUserFacingError(requiredArgs: {
31
32
  step: string;
32
33
  cause: unknown;
33
34
  }, optionalArgs?: UserFacingErrorOptions): UserFacingError;
35
+ /** Approved host vocabulary only. Keys are static route segments or slash-delimited operation suffixes; prefix an override key with an HTTP method and a space to restrict it. */
36
+ export interface RequestFailureVocabulary {
37
+ readonly nouns: Readonly<Record<string, {
38
+ readonly singular: string;
39
+ readonly plural: string;
40
+ }>>;
41
+ readonly operations?: Readonly<Record<string, RequestFailureDescription>>;
42
+ }
43
+ export interface RequestFailureDescription {
44
+ readonly message: string;
45
+ readonly action: string;
46
+ readonly step: string;
47
+ }
48
+ /**
49
+ * Describe a failed request using only host-approved words; path values and query strings never render.
50
+ * A registered template is preferred; operation identifiers are the fallback for non-HTTP mappers.
51
+ * This is pure and does not infer a cause, retry a write or assume POST means creation.
52
+ * @complexity O(n + k*n) time for n bounded route tokens and k host override suffixes; O(n) space.
53
+ * @overallScore 98 — the host owns vocabulary accuracy; unknown contexts retain a safe request fallback.
54
+ */
55
+ export declare function describeRequestFailure({ method, route, operation, vocabulary }: {
56
+ method?: string;
57
+ route?: string;
58
+ operation?: string;
59
+ vocabulary: RequestFailureVocabulary;
60
+ }, _optionalArgs?: Record<string, never>): RequestFailureDescription;
34
61
  //# sourceMappingURL=user-facing-error.d.ts.map