@jini-ai/mcp 0.7.3-next.1 → 0.7.3-next.3

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 (77) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +15 -0
  3. package/dist/agent-install/owned-json-install.d.ts +1 -1
  4. package/dist/client/client.js +1 -1
  5. package/dist/client/css-url-refs.d.ts +3 -1
  6. package/dist/client/css-url-refs.js +1 -1
  7. package/dist/external/access-review.d.ts +46 -0
  8. package/dist/external/access-review.js +175 -0
  9. package/dist/external/agent-tools.d.ts +72 -0
  10. package/dist/external/agent-tools.js +218 -0
  11. package/dist/external/built-in-connections.d.ts +17 -0
  12. package/dist/external/built-in-connections.js +15 -0
  13. package/dist/external/external-mcp-host-copy.d.ts +14 -0
  14. package/dist/external/external-mcp-host-copy.js +8 -0
  15. package/dist/external/operations-tools.d.ts +69 -0
  16. package/dist/external/operations-tools.js +96 -0
  17. package/dist/external/save-form.d.ts +105 -0
  18. package/dist/external/save-form.js +260 -0
  19. package/dist/external/save-input.d.ts +41 -0
  20. package/dist/external/save-input.js +149 -0
  21. package/dist/external/tool-registrations.d.ts +130 -0
  22. package/dist/external/tool-registrations.js +299 -0
  23. package/dist/federation/bootstrap.d.ts +18 -0
  24. package/dist/federation/bootstrap.js +2 -2
  25. package/dist/federation/external-mcp-admissions.d.ts +19 -0
  26. package/dist/federation/external-mcp-admissions.js +30 -0
  27. package/dist/federation/external-mcp-probe.d.ts +86 -0
  28. package/dist/federation/external-mcp-probe.js +75 -0
  29. package/dist/federation/hosted/external-mcp-repo.d.ts +108 -0
  30. package/dist/federation/hosted/external-mcp-repo.js +210 -0
  31. package/dist/federation/hosted/external-mcp-repo.writes.d.ts +75 -0
  32. package/dist/federation/hosted/external-mcp-repo.writes.js +131 -0
  33. package/dist/federation/hosted/store-credentials.d.ts +6 -1
  34. package/dist/federation/hosted/store-credentials.js +2 -2
  35. package/dist/federation/hosted/store-input.d.ts +11 -3
  36. package/dist/federation/hosted/store-input.js +5 -5
  37. package/dist/federation/hosted/store-oauth-fields.d.ts +10 -2
  38. package/dist/federation/hosted/store-oauth-fields.js +7 -7
  39. package/dist/federation/hosted/store-view.d.ts +6 -1
  40. package/dist/federation/hosted/store-view.js +2 -2
  41. package/dist/federation/hosted/store.js +7 -7
  42. package/dist/federation/hosted/store.memory.d.ts +2 -0
  43. package/dist/federation/hosted/store.memory.js +6 -2
  44. package/dist/federation/index.d.ts +2 -0
  45. package/dist/federation/index.js +2 -0
  46. package/dist/federation/registrations.js +73 -56
  47. package/dist/federation/roster-change.d.ts +63 -0
  48. package/dist/federation/roster-change.js +68 -0
  49. package/dist/federation/runtime.d.ts +140 -0
  50. package/dist/federation/runtime.js +118 -0
  51. package/dist/react/external-mcp/ExternalMcpAdmissionsBanner.d.ts +42 -0
  52. package/dist/react/external-mcp/ExternalMcpAdmissionsBanner.js +80 -0
  53. package/dist/react/external-mcp/ExternalMcpPanelSections.d.ts +50 -0
  54. package/dist/react/external-mcp/ExternalMcpPanelSections.js +35 -0
  55. package/dist/react/external-mcp/ExternalMcpSettingsPanel.d.ts +446 -0
  56. package/dist/react/external-mcp/ExternalMcpSettingsPanel.hooks.d.ts +135 -0
  57. package/dist/react/external-mcp/ExternalMcpSettingsPanel.hooks.js +122 -0
  58. package/dist/react/external-mcp/ExternalMcpSettingsPanel.js +63 -0
  59. package/dist/react/external-mcp/ExternalMcpSourceRow.d.ts +40 -0
  60. package/dist/react/external-mcp/ExternalMcpSourceRow.js +100 -0
  61. package/dist/react/external-mcp/hooks/external-mcp-form.rules.d.ts +58 -0
  62. package/dist/react/external-mcp/hooks/external-mcp-form.rules.js +209 -0
  63. package/dist/react/external-mcp/hooks/external-mcp-source-actions.d.ts +115 -0
  64. package/dist/react/external-mcp/hooks/external-mcp-source-actions.js +152 -0
  65. package/dist/react/external-mcp/hooks/use-external-mcp-admissions.hooks.d.ts +166 -0
  66. package/dist/react/external-mcp/hooks/use-external-mcp-admissions.hooks.js +209 -0
  67. package/dist/react/external-mcp/hooks/use-external-mcp.hooks.d.ts +132 -0
  68. package/dist/react/external-mcp/hooks/use-external-mcp.hooks.js +37 -0
  69. package/dist/server/tool-arguments.d.ts +5 -1
  70. package/dist/server/tool-arguments.js +13 -9
  71. package/dist/server/tool-protocol.js +7 -5
  72. package/dist/server/tools/tool-catalog-tools.js +6 -3
  73. package/dist/tools/ask-choice/custom-answer.d.ts +77 -0
  74. package/dist/tools/ask-choice/custom-answer.js +113 -0
  75. package/dist/tools/ask-choice/index.d.ts +2 -0
  76. package/dist/tools/ask-choice/index.js +1 -0
  77. package/package.json +122 -7
@@ -0,0 +1,132 @@
1
+ import type { AdminExternalMcpServer, AdminExternalMcpServerInput } from "@jini-ai/core/contracts/site/cms-external-mcp";
2
+ export { describeStoredCredentials, toAccessTokenWriteBody } from "./external-mcp-form.rules.js";
3
+ export interface ExternalMcpController {
4
+ dependencies: {
5
+ port: {
6
+ fetchSources: () => Promise<{
7
+ id: string;
8
+ label?: string;
9
+ trust?: string;
10
+ enabled?: boolean;
11
+ fields: Record<string, string>;
12
+ status?: "idle" | "testing" | "connected" | "error";
13
+ statusMessage?: string;
14
+ }[]>;
15
+ addSource: (input: {
16
+ fields: Record<string, string>;
17
+ trust?: string;
18
+ }) => Promise<{
19
+ ok: boolean;
20
+ source?: Awaited<ReturnType<ExternalMcpController["dependencies"]["port"]["fetchSources"]>>[number];
21
+ message?: string;
22
+ }>;
23
+ removeSource: (id: string) => Promise<boolean>;
24
+ updateSource: (id: string, patch: {
25
+ label?: string;
26
+ enabled?: boolean;
27
+ fields?: Record<string, string>;
28
+ }) => Promise<Awaited<ReturnType<ExternalMcpController["dependencies"]["port"]["fetchSources"]>>[number] | null>;
29
+ testSource: (id: string | undefined) => Promise<{
30
+ ok: boolean;
31
+ message?: string;
32
+ latencyMs?: number;
33
+ }>;
34
+ };
35
+ };
36
+ /** Set once any write succeeds — federation only re-reads the roster at daemon boot. */
37
+ restartRequired: boolean;
38
+ }
39
+ export interface ExternalMcpPort {
40
+ listExternalMcpServers: () => Promise<{
41
+ servers: AdminExternalMcpServer[];
42
+ }>;
43
+ saveExternalMcpServer: (required: {
44
+ serverId: string;
45
+ body: AdminExternalMcpServerInput & {
46
+ expectedVersion?: number;
47
+ };
48
+ }) => Promise<{
49
+ server: AdminExternalMcpServer;
50
+ }>;
51
+ deleteExternalMcpServer: (required: {
52
+ serverId: string;
53
+ }) => Promise<{
54
+ removed: true;
55
+ restartRequired: true;
56
+ }>;
57
+ probeExternalMcpServer: (required: {
58
+ serverId: string;
59
+ }) => Promise<{
60
+ tools: readonly unknown[];
61
+ }>;
62
+ }
63
+ type SourceConfigItem = Awaited<ReturnType<ExternalMcpController["dependencies"]["port"]["fetchSources"]>>[number];
64
+ export declare function useExternalMcp({ hooks, deps }: {
65
+ hooks: {
66
+ useAdminLocaleHook: () => string;
67
+ useSerialWrites: () => {
68
+ run: <T>(required: {
69
+ task: () => Promise<T>;
70
+ }, optional?: {
71
+ key?: string;
72
+ }) => Promise<T>;
73
+ };
74
+ };
75
+ deps: {
76
+ port: ExternalMcpPort;
77
+ credentialText: (required: {
78
+ id: "set" | "saved" | "connected" | "unreachable";
79
+ locale: string;
80
+ }) => string;
81
+ formatCredentialHint: (required: {
82
+ hint: NonNullable<AdminExternalMcpServer["accessTokenHint"]>;
83
+ locale: string;
84
+ }) => string;
85
+ formatCredentialHints: (required: {
86
+ hints: AdminExternalMcpServer["envTokenHints"];
87
+ locale: string;
88
+ }) => string;
89
+ translateCredentialMessage: (required: {
90
+ message: string;
91
+ locale: string;
92
+ }) => string;
93
+ credentialDraftError: (required: {
94
+ value: string;
95
+ }, optional: {
96
+ locale: string;
97
+ required: boolean;
98
+ }) => string | null;
99
+ describeApiError: (required: {
100
+ e: unknown;
101
+ fallback: string;
102
+ }) => string;
103
+ VERSION_CONFLICT_MESSAGE: string;
104
+ isVersionConflict: (required: {
105
+ error: unknown;
106
+ }) => boolean;
107
+ translate: (required: {
108
+ locale: string;
109
+ key: string;
110
+ }) => string;
111
+ mergeSourceUpdate: (required: {
112
+ previous: SourceConfigItem | undefined;
113
+ patch: {
114
+ label?: string;
115
+ enabled?: boolean;
116
+ fields?: Record<string, string>;
117
+ };
118
+ }) => {
119
+ fields: Record<string, string>;
120
+ enabled: boolean;
121
+ label?: string;
122
+ };
123
+ resolveExternalMcpEffectiveAuthMode: (fields: Record<string, string>) => string;
124
+ resolveExternalMcpEffectiveTransport: (fields: Record<string, string>) => string;
125
+ validateExternalMcpOAuthIdentity: (fields: Record<string, string>, optional: {
126
+ t: (key: string) => string;
127
+ }) => string | null;
128
+ now: () => number;
129
+ };
130
+ }, _optional?: {}): ExternalMcpController;
131
+ export declare function bindExternalMcp({ hooks, deps }: Parameters<typeof useExternalMcp>[0], _optional?: {}): (_required: Record<string, never>, _optional?: {}) => ExternalMcpController;
132
+ //# sourceMappingURL=use-external-mcp.hooks.d.ts.map
@@ -0,0 +1,37 @@
1
+ import { useCallback, useMemo, useRef, useState } from "react";
2
+ import { fetchSources, addSource, removeSource, updateSource, testSource } from "./external-mcp-source-actions.js";
3
+ export { describeStoredCredentials, toAccessTokenWriteBody } from "./external-mcp-form.rules.js";
4
+ export function useExternalMcp({ hooks, deps }, _optional = {}) {
5
+ const { port } = deps;
6
+ const { useAdminLocaleHook, useSerialWrites } = hooks;
7
+ const [restartRequired, setRestartRequired] = useState(false);
8
+ // `updateSource` receives a PARTIAL patch, but the write route replaces the whole row, so the
9
+ // last-known field values are kept here to merge against. Without this, toggling `enabled` would
10
+ // blank out `command` and the allowlist.
11
+ const lastKnown = useRef(new Map());
12
+ // Serializes `updateSource` writes per id, through `useSerialWrites`' keyed lanes — see that
13
+ // method's own doc for the race this closes.
14
+ const writes = useSerialWrites();
15
+ // Same bound translator `ExternalMcpToolPicker.tsx` uses for this dictionary (Phase 2C) — reused
16
+ // here rather than re-resolving the locale a second way, so `testSource`'s unreachable-server
17
+ // fallback below stays word-for-word identical to the picker's own copy in every locale, not just
18
+ // English.
19
+ // The credential-safety contract now owns probe fallback copy; other tab copy still uses
20
+ // the same dictionary translator as the picker, with the injected locale resolved once.
21
+ const locale = useAdminLocaleHook();
22
+ const t = useCallback((key) => deps.translate({ locale: locale, key: key }), [locale]);
23
+ const dependencies = useMemo(() => ({ port: {
24
+ fetchSources: () => fetchSources({ deps, port, locale, lastKnown }),
25
+ addSource: input => addSource({ input, deps, port, locale, lastKnown, setRestartRequired, t }),
26
+ removeSource: id => removeSource({ id, port, lastKnown, setRestartRequired }),
27
+ updateSource: (id, patch) => updateSource({ id, patch, deps, port, locale, lastKnown, setRestartRequired, writes, t }),
28
+ testSource: id => testSource({ id, deps, port, locale, t }),
29
+ } }), [t, writes, locale, port]);
30
+ return { dependencies, restartRequired };
31
+ }
32
+ export function bindExternalMcp({ hooks, deps }, _optional = {}) {
33
+ return function useBoundExternalMcp(_required, _optional = {}) {
34
+ return useExternalMcp({ hooks, deps });
35
+ };
36
+ }
37
+ //# sourceMappingURL=use-external-mcp.hooks.js.map
@@ -40,7 +40,11 @@ export declare function resolveMcpToolName({ name }: {
40
40
  isRegistered?: (name: string) => boolean;
41
41
  }): string;
42
42
  /** True for a plain JSON object (not `null`, not an array). */
43
- export declare function isRecord(value: unknown): value is Record<string, unknown>;
43
+ export declare function isRecord(required: {
44
+ value: unknown;
45
+ }, _optional?: Record<string, never>): required is {
46
+ value: Record<string, unknown>;
47
+ };
44
48
  /** Normalize the transport envelope, then existing aliases, integer fields and gateway input.
45
49
  * @returns A detached argument object; malformed or ambiguous input throws a repair instruction.
46
50
  * @complexity O(k + a + i + n) for argument/alias/input keys and encoded JSON characters.
@@ -12,7 +12,8 @@ export function resolveMcpToolName({ name }, { isRegistered } = {}) {
12
12
  return name.startsWith('mcp__jini__') ? name.slice('mcp__jini__'.length) : name;
13
13
  }
14
14
  /** True for a plain JSON object (not `null`, not an array). */
15
- export function isRecord(value) {
15
+ export function isRecord(required, _optional = {}) {
16
+ const { value } = required;
16
17
  return typeof value === 'object' && value !== null && !Array.isArray(value);
17
18
  }
18
19
  /**
@@ -42,8 +43,8 @@ const CANONICAL_INTEGER = /^(?:0|[1-9]\d{0,14})$/;
42
43
  */
43
44
  function coerceIntegerStrings({ args, properties }) {
44
45
  for (const [key, value] of Object.entries(args)) {
45
- const property = properties[key];
46
- if (typeof value !== 'string' || !isRecord(property) || property.type !== 'integer')
46
+ const property = { value: properties[key] };
47
+ if (typeof value !== 'string' || !isRecord(property) || property.value.type !== 'integer')
47
48
  continue;
48
49
  if (CANONICAL_INTEGER.test(value))
49
50
  args[key] = Number(value);
@@ -54,10 +55,11 @@ function coerceIntegerStrings({ args, properties }) {
54
55
  * @throws Error when `input` is not a JSON object, or already holds one of the keys being folded.
55
56
  */
56
57
  function foldExtraKeysIntoInput({ args, extraKeys }) {
57
- const input = Object.hasOwn(args, 'input') ? args.input : {};
58
- if (!isRecord(input)) {
58
+ const checked = { value: Object.hasOwn(args, 'input') ? args.input : {} };
59
+ if (!isRecord(checked)) {
59
60
  throw new Error("put the tool's own arguments inside `input`; replace `input` with a JSON object");
60
61
  }
62
+ const input = checked.value;
61
63
  if (extraKeys.some((key) => Object.hasOwn(input, key))) {
62
64
  throw new Error("put the tool's own arguments inside `input`");
63
65
  }
@@ -75,9 +77,10 @@ function assertNoMisplacedInputKey({ args, schema }) {
75
77
  if (schema.additionalProperties !== false || schema.patternProperties)
76
78
  return;
77
79
  const properties = schema.properties ?? {};
78
- if (!isRecord(args.input) || Object.hasOwn(properties, 'input'))
80
+ const input = { value: args.input };
81
+ if (!isRecord(input) || Object.hasOwn(properties, 'input'))
79
82
  return;
80
- const misplaced = Object.keys(args.input).find((key) => Object.hasOwn(properties, key));
83
+ const misplaced = Object.keys(input.value).find((key) => Object.hasOwn(properties, key));
81
84
  if (misplaced !== undefined)
82
85
  throw new Error(`move \`input.${misplaced}\` to top-level \`${misplaced}\``);
83
86
  }
@@ -103,9 +106,10 @@ function argumentSource({ tool, rawArgs }) {
103
106
  * @complexity O(k + a + i + n) for argument/alias/input keys and encoded JSON characters.
104
107
  */
105
108
  export function normalizeToolArguments({ tool, rawArgs }, _options = {}) {
106
- if (!isRecord(rawArgs))
109
+ const checked = { value: rawArgs };
110
+ if (!isRecord(checked))
107
111
  throw new Error('replace `arguments` with a JSON object');
108
- const args = argumentSource({ tool, rawArgs });
112
+ const args = argumentSource({ tool, rawArgs: checked.value });
109
113
  const properties = tool.inputSchema.properties ?? {};
110
114
  applyAliases({ args, aliases: tool.argumentNormalization?.aliases ?? {} });
111
115
  coerceIntegerStrings({ args, properties });
@@ -85,9 +85,10 @@ export function daemonCallOptions({ ctx }, _options = {}) {
85
85
  * this identical envelope shape one layer up, kept consistent here rather than reinvented.
86
86
  */
87
87
  function isMcpContentEnvelope(payload) {
88
- if (!isRecord(payload))
88
+ const checked = { value: payload };
89
+ if (!isRecord(checked))
89
90
  return false;
90
- const content = payload['content'];
91
+ const content = checked.value['content'];
91
92
  return Array.isArray(content) && content.every(block => isPassthroughContentBlock({ block }));
92
93
  }
93
94
  /** A payload is an error when it flags itself so or reports a failed batch outcome. */
@@ -113,7 +114,7 @@ export function okResult({ payload }) {
113
114
  const isError = isErrorPayload({ payload });
114
115
  if (isMcpContentEnvelope(payload)) {
115
116
  return { content: payload.content,
116
- ...(isRecord(payload.structuredContent) ? { structuredContent: payload.structuredContent } : {}),
117
+ ...(isRecord({ value: payload.structuredContent }) ? { structuredContent: payload.structuredContent } : {}),
117
118
  ...(isError ? { isError: true } : {}) };
118
119
  }
119
120
  // Compact on the wire: indentation made nested results ~2.5x larger for the model to read. A view
@@ -193,9 +194,10 @@ async function normalizeCallArguments({ tool, rawArgs }, _options = {}) {
193
194
  if (!tool.argumentNormalization?.schemaInput)
194
195
  return { args, notes: [] };
195
196
  const normalized = await normalizeToolInput({ input: args, registration: { descriptor: { id: tool.name, inputSchema: tool.inputSchema } } });
196
- if (!isRecord(normalized.input))
197
+ const input = { value: normalized.input };
198
+ if (!isRecord(input))
197
199
  throw new Error('normalization must produce one input object');
198
- return { args: normalized.input, notes: normalized.notes };
200
+ return { args: input.value, notes: normalized.notes };
199
201
  }
200
202
  /** Format a refused normalization with the same bounded contract used by schema validation.
201
203
  * Registry tools need the full contract to repair aliases; MCP-local wrapper diagnostics keep
@@ -25,9 +25,11 @@ const READ_ANNOTATIONS = {
25
25
  * Unknown risk remains unclassified and therefore cannot claim a read-only annotation.
26
26
  * @complexity O(1); no effects. The schema is checked by the publication boundary.
27
27
  */
28
- function describedDescriptor({ id, data }) {
29
- if (!isRecord(data) || data.id !== id)
28
+ function describedDescriptor({ id, data: raw }) {
29
+ const checked = { value: raw };
30
+ if (!isRecord(checked) || checked.value.id !== id)
30
31
  throw new Error('daemon returned a mismatched tool descriptor');
32
+ const data = checked.value;
31
33
  return {
32
34
  id,
33
35
  ...(typeof data.description === 'string' ? { description: data.description } : {}),
@@ -147,7 +149,8 @@ export const describeToolTool = {
147
149
  const data = await getDaemonJson({ baseUrl: ctx.baseUrl, route: `/api/tools/${encodeURIComponent(id)}` }, daemonCallOptions({ ctx }));
148
150
  // A host that publishes validates the daemon's answer (a mismatch is an error, as before); one that does not
149
151
  // passes an answer that is not this tool's descriptor through unchanged, with nothing to say about calling it.
150
- if (ctx.publishTool === undefined && !(isRecord(data) && data.id === id))
152
+ const checked = { value: data };
153
+ if (ctx.publishTool === undefined && !(isRecord(checked) && checked.value.id === id))
151
154
  return data;
152
155
  const descriptor = describedDescriptor({ id, data });
153
156
  return { ...data, ...(await callInstructions({ descriptor, ctx })) };
@@ -0,0 +1,77 @@
1
+ import type { SurfaceField } from '@jini-ai/core/contracts/cards';
2
+ import type { AskChoiceExchangeStore, AskChoiceQuestion } from './types.js';
3
+ /**
4
+ * @file The "Something else" choice on an ask-choice card: one extra option plus a text box, so
5
+ * the operator can give an answer the model did not list.
6
+ *
7
+ * The typed words always reach the model as `freeText`, never as a fake option value: a picked
8
+ * single-select "Something else" becomes the exchange's typed answer (the same path as a reply
9
+ * typed in the chat box), and a ticked multi-select one is stripped from `selections` and its
10
+ * words are added next to the real picks.
11
+ *
12
+ * The host injects every visible word ({@link CustomAnswerCopy}); the option value and the text
13
+ * box's param name are fixed here because the answer splitting below depends on them.
14
+ */
15
+ /** The extra option's submitted value. Never shown to the model; stripped before the answer is classified. */
16
+ export declare const CUSTOM_CHOICE_VALUE = "__somethingElse";
17
+ /** The text box's param name in the form's callback. */
18
+ export declare const CUSTOM_ANSWER_PARAM = "customAnswer";
19
+ /** Host wording for the extra option, its text box, and the model note. */
20
+ export interface CustomAnswerCopy {
21
+ /** The extra option's label (e.g. "Something else"). */
22
+ readonly choiceLabel: string;
23
+ /** The text box's label (kept for screen readers even when the host hides it visually). */
24
+ readonly answerLabel: string;
25
+ readonly answerPlaceholder: string;
26
+ /** Model note when the operator ticked options and also wrote their own answer. */
27
+ readonly withPicksNote: string;
28
+ }
29
+ /** Adds "Something else" to each choice field and one text box after them.
30
+ * Returns the fields unchanged when a model option already uses the reserved value.
31
+ * @complexity O(n) in offered options; pure.
32
+ */
33
+ export declare function addCustomAnswerFields({ fields, copy }: {
34
+ fields: readonly SurfaceField[];
35
+ copy: Pick<CustomAnswerCopy, 'choiceLabel' | 'answerLabel' | 'answerPlaceholder'>;
36
+ }, _options?: {}): SurfaceField[];
37
+ /** What one delivered answer said under "Something else", kept for {@link mergeCustomAnswer}. */
38
+ export interface CustomAnswerSplit {
39
+ readonly freeText?: string;
40
+ /** Real multi-select picks to restore when a single-select "Something else" took the typed path. */
41
+ readonly selections?: readonly string[];
42
+ }
43
+ type AnswerParams = Record<string, unknown>;
44
+ /** Rewrites one delivered form answer so the exchange classifies it, and keeps the typed words aside.
45
+ * Typed words count only when "Something else" was picked; otherwise they are dropped.
46
+ * @complexity O(s + m) in selections and offered options; pure.
47
+ */
48
+ export declare function splitCustomAnswer({ params, question }: {
49
+ params: AnswerParams;
50
+ question: AskChoiceQuestion | undefined;
51
+ }, _options?: {}): {
52
+ params: AnswerParams;
53
+ split: CustomAnswerSplit;
54
+ };
55
+ /** Folds the kept words into the classified result; only a submitted answer is changed.
56
+ * `note` is the host's {@link CustomAnswerCopy.withPicksNote}.
57
+ * @complexity O(1); pure.
58
+ */
59
+ export declare function mergeCustomAnswer({ result, split, note }: {
60
+ result: unknown;
61
+ split: CustomAnswerSplit;
62
+ note: string;
63
+ }, _options?: {}): unknown;
64
+ /** One tool call's "Something else" state: the shown question and what the answer said. */
65
+ export interface CustomAnswerCall {
66
+ question?: AskChoiceQuestion;
67
+ split: CustomAnswerSplit;
68
+ }
69
+ /** Wraps an exchange store so each delivered answer is split before it is classified.
70
+ * @complexity O(1) wiring; per answer see {@link splitCustomAnswer}.
71
+ */
72
+ export declare function customAnswerExchanges({ exchanges, call }: {
73
+ exchanges: AskChoiceExchangeStore;
74
+ call: CustomAnswerCall;
75
+ }, _options?: {}): AskChoiceExchangeStore;
76
+ export {};
77
+ //# sourceMappingURL=custom-answer.d.ts.map
@@ -0,0 +1,113 @@
1
+ import { SURFACE_TYPED_ANSWER_PARAM } from '@jini-ai/core';
2
+ /**
3
+ * @file The "Something else" choice on an ask-choice card: one extra option plus a text box, so
4
+ * the operator can give an answer the model did not list.
5
+ *
6
+ * The typed words always reach the model as `freeText`, never as a fake option value: a picked
7
+ * single-select "Something else" becomes the exchange's typed answer (the same path as a reply
8
+ * typed in the chat box), and a ticked multi-select one is stripped from `selections` and its
9
+ * words are added next to the real picks.
10
+ *
11
+ * The host injects every visible word ({@link CustomAnswerCopy}); the option value and the text
12
+ * box's param name are fixed here because the answer splitting below depends on them.
13
+ */
14
+ /** The extra option's submitted value. Never shown to the model; stripped before the answer is classified. */
15
+ export const CUSTOM_CHOICE_VALUE = '__somethingElse';
16
+ /** The text box's param name in the form's callback. */
17
+ export const CUSTOM_ANSWER_PARAM = 'customAnswer';
18
+ /** Adds "Something else" to each choice field and one text box after them.
19
+ * Returns the fields unchanged when a model option already uses the reserved value.
20
+ * @complexity O(n) in offered options; pure.
21
+ */
22
+ export function addCustomAnswerFields({ fields, copy }, _options = {}) {
23
+ const choiceFields = fields.filter((field) => field.kind === 'enum' || field.kind === 'multi-enum');
24
+ const taken = choiceFields.some((field) => field.options.some((option) => option.value === CUSTOM_CHOICE_VALUE));
25
+ if (choiceFields.length === 0 || taken)
26
+ return [...fields];
27
+ const custom = { value: CUSTOM_CHOICE_VALUE, label: copy.choiceLabel };
28
+ const withOption = fields.map((field) => field.kind === 'enum' || field.kind === 'multi-enum' ? { ...field, options: [...field.options, custom] } : field);
29
+ // Required only for the radio: the renderer cannot read a checkbox group's state.
30
+ const single = fields.some((field) => field.kind === 'enum' && field.name === 'choice');
31
+ const textBox = {
32
+ kind: 'string',
33
+ name: CUSTOM_ANSWER_PARAM,
34
+ label: copy.answerLabel,
35
+ placeholder: copy.answerPlaceholder,
36
+ required: false,
37
+ ...(single ? { requiredWhen: { field: 'choice', in: [CUSTOM_CHOICE_VALUE] } } : {}),
38
+ };
39
+ return [...withOption, textBox];
40
+ }
41
+ /** Rewrites one delivered form answer so the exchange classifies it, and keeps the typed words aside.
42
+ * Typed words count only when "Something else" was picked; otherwise they are dropped.
43
+ * @complexity O(s + m) in selections and offered options; pure.
44
+ */
45
+ export function splitCustomAnswer({ params, question }, _options = {}) {
46
+ if (!Object.hasOwn(params, CUSTOM_ANSWER_PARAM))
47
+ return { params, split: {} };
48
+ const { [CUSTOM_ANSWER_PARAM]: raw, ...rest } = params;
49
+ const text = typeof raw === 'string' ? raw.trim() : '';
50
+ const pickedSingle = rest.choice === CUSTOM_CHOICE_VALUE;
51
+ const { params: cleaned, pickedMulti } = withoutMultiCustomPick({ params: rest });
52
+ if (!text || !(pickedSingle || pickedMulti))
53
+ return { params: cleaned, split: {} };
54
+ if (!pickedSingle)
55
+ return { params: cleaned, split: { freeText: text } };
56
+ return typedCustomAnswer({ params: cleaned, text, question });
57
+ }
58
+ /** Removes the "Something else" pick from multi-select selections and reports whether it was there.
59
+ * @complexity O(s) in selections; pure.
60
+ */
61
+ function withoutMultiCustomPick({ params }, _options = {}) {
62
+ const selections = Array.isArray(params.selections) ? params.selections : undefined;
63
+ const pickedMulti = selections?.includes(CUSTOM_CHOICE_VALUE) === true;
64
+ const realSelections = selections?.filter((value) => value !== CUSTOM_CHOICE_VALUE);
65
+ return { params: realSelections ? { ...params, selections: realSelections } : params, pickedMulti };
66
+ }
67
+ /** A picked single-select "Something else" becomes the exchange's typed answer.
68
+ * The typed path skips option checks, so only multi-select picks really offered are restored.
69
+ * @complexity O(s + m) in selections and offered options; pure.
70
+ */
71
+ function typedCustomAnswer({ params, text, question }, _options = {}) {
72
+ const { choice: _custom, selections, ...typed } = params;
73
+ const offered = new Set(question?.multiSelect?.options.map((option) => option.value));
74
+ const keep = Array.isArray(selections) && selections.every((value) => typeof value === 'string' && offered.has(value))
75
+ ? selections : undefined;
76
+ return { params: { ...typed, [SURFACE_TYPED_ANSWER_PARAM]: text }, split: { freeText: text, ...(keep ? { selections: keep } : {}) } };
77
+ }
78
+ /** Folds the kept words into the classified result; only a submitted answer is changed.
79
+ * `note` is the host's {@link CustomAnswerCopy.withPicksNote}.
80
+ * @complexity O(1); pure.
81
+ */
82
+ export function mergeCustomAnswer({ result, split, note }, _options = {}) {
83
+ const answer = result;
84
+ if (split.freeText === undefined || answer?.submitted !== true)
85
+ return result;
86
+ if (answer.freeText !== undefined)
87
+ return split.selections ? { ...answer, selections: split.selections } : result;
88
+ return { ...answer, freeText: split.freeText, note };
89
+ }
90
+ /** Wraps an exchange store so each delivered answer is split before it is classified.
91
+ * @complexity O(1) wiring; per answer see {@link splitCustomAnswer}.
92
+ */
93
+ export function customAnswerExchanges({ exchanges, call }, _options = {}) {
94
+ return {
95
+ open: (args) => {
96
+ const exchange = exchanges.open(args);
97
+ return {
98
+ id: exchange.id,
99
+ send: (sendArgs) => exchange.send(sendArgs),
100
+ close: (closeArgs) => exchange.close(closeArgs),
101
+ receive: async (receiveArgs) => {
102
+ const message = await exchange.receive(receiveArgs);
103
+ if (message.status !== 'received')
104
+ return message;
105
+ const { params, split } = splitCustomAnswer({ params: message.params, question: call.question });
106
+ call.split = split;
107
+ return { status: 'received', params };
108
+ },
109
+ };
110
+ },
111
+ };
112
+ }
113
+ //# sourceMappingURL=custom-answer.js.map
@@ -2,6 +2,8 @@ import type { AskChoiceCall, AskChoiceExchange, AskChoiceExchangeStore, AskChoic
2
2
  export type * from './types.js';
3
3
  export { ASK_CHOICE_INPUT_SCHEMA } from './schema.js';
4
4
  export { createAskChoiceAnswerTicketStore } from './pending.js';
5
+ export type { CustomAnswerCall, CustomAnswerCopy, CustomAnswerSplit } from './custom-answer.js';
6
+ export { addCustomAnswerFields, CUSTOM_ANSWER_PARAM, CUSTOM_CHOICE_VALUE, customAnswerExchanges, mergeCustomAnswer, splitCustomAnswer, } from './custom-answer.js';
5
7
  /** Existing callback wire keys; the tool's identity is supplied by the host. */
6
8
  export declare const ASK_CHOICE_ANSWER_TICKET_PARAM = "__askChoiceAnswerTicket";
7
9
  /** Run a trusted host question through the same abort, delivery, validation and cleanup lifecycle
@@ -2,6 +2,7 @@ import { matchesOptions, parseQuestion, QuestionShapeError } from './question.js
2
2
  import { ASK_CHOICE_INPUT_SCHEMA, ASK_CHOICE_INVOCATION_SCHEMA } from './schema.js';
3
3
  export { ASK_CHOICE_INPUT_SCHEMA } from './schema.js';
4
4
  export { createAskChoiceAnswerTicketStore } from './pending.js';
5
+ export { addCustomAnswerFields, CUSTOM_ANSWER_PARAM, CUSTOM_CHOICE_VALUE, customAnswerExchanges, mergeCustomAnswer, splitCustomAnswer, } from './custom-answer.js';
5
6
  /** Existing callback wire keys; the tool's identity is supplied by the host. */
6
7
  export const ASK_CHOICE_ANSWER_TICKET_PARAM = '__askChoiceAnswerTicket';
7
8
  const SURFACE_EXCHANGE_ID_PARAM = '__exchangeId';