@lushly-dev/afd-client 2.4.0 → 3.0.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 (57) hide show
  1. package/README.md +51 -10
  2. package/dist/client-errors.d.ts +22 -1
  3. package/dist/client-errors.d.ts.map +1 -1
  4. package/dist/client-errors.js +76 -2
  5. package/dist/client-errors.js.map +1 -1
  6. package/dist/client.d.ts +50 -7
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +237 -16
  9. package/dist/client.js.map +1 -1
  10. package/dist/direct-approval.d.ts +12 -4
  11. package/dist/direct-approval.d.ts.map +1 -1
  12. package/dist/direct-approval.js +23 -6
  13. package/dist/direct-approval.js.map +1 -1
  14. package/dist/direct-timeout.d.ts.map +1 -1
  15. package/dist/direct-timeout.js +1 -0
  16. package/dist/direct-timeout.js.map +1 -1
  17. package/dist/direct-transport.d.ts.map +1 -1
  18. package/dist/direct-transport.js +24 -7
  19. package/dist/direct-transport.js.map +1 -1
  20. package/dist/direct-types.d.ts +46 -9
  21. package/dist/direct-types.d.ts.map +1 -1
  22. package/dist/direct.d.ts +10 -11
  23. package/dist/direct.d.ts.map +1 -1
  24. package/dist/direct.js +65 -13
  25. package/dist/direct.js.map +1 -1
  26. package/dist/handoff.d.ts.map +1 -1
  27. package/dist/handoff.js +1 -0
  28. package/dist/handoff.js.map +1 -1
  29. package/dist/index.d.ts +4 -4
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -2
  32. package/dist/index.js.map +1 -1
  33. package/dist/result-parsing.d.ts +11 -3
  34. package/dist/result-parsing.d.ts.map +1 -1
  35. package/dist/result-parsing.js +37 -4
  36. package/dist/result-parsing.js.map +1 -1
  37. package/dist/result-state.d.ts +98 -0
  38. package/dist/result-state.d.ts.map +1 -0
  39. package/dist/result-state.js +91 -0
  40. package/dist/result-state.js.map +1 -0
  41. package/dist/streamable-http-transport.d.ts +11 -1
  42. package/dist/streamable-http-transport.d.ts.map +1 -1
  43. package/dist/streamable-http-transport.js +152 -2
  44. package/dist/streamable-http-transport.js.map +1 -1
  45. package/dist/streamable-http.d.ts +1 -1
  46. package/dist/streamable-http.d.ts.map +1 -1
  47. package/dist/streamable-http.js.map +1 -1
  48. package/dist/transport.d.ts.map +1 -1
  49. package/dist/transport.js +9 -3
  50. package/dist/transport.js.map +1 -1
  51. package/dist/types.d.ts +28 -1
  52. package/dist/types.d.ts.map +1 -1
  53. package/dist/unknown-tool.d.ts +13 -4
  54. package/dist/unknown-tool.d.ts.map +1 -1
  55. package/dist/unknown-tool.js +1 -1
  56. package/dist/unknown-tool.js.map +1 -1
  57. package/package.json +9 -5
package/dist/index.js CHANGED
@@ -16,8 +16,8 @@
16
16
  * @packageDocumentation
17
17
  */
18
18
  export { createClient, McpClient, SERVER_DEADLINE_MARGIN_MS, } from './client.js';
19
- export { HttpStatusError, JsonRpcResponseError, NotConnectedError, RequestTimeoutError, } from './client-errors.js';
20
- export { createDirectClient, DirectClient, DirectTransport, isUnknownToolError, } from './direct.js';
19
+ export { HttpStatusError, JsonRpcResponseError, NotConnectedError, RequestTimeoutError, SESSION_LIMIT_REACHED, SessionLimitError, } from './client-errors.js';
20
+ export { createDirectClient, DirectClient, DirectTransport, isUnknownToolError, loadingResultState, normalizeResultState, } from './direct.js';
21
21
  // Built-in protocol handlers
22
22
  export { builtinHandlers, sseHandler, websocketHandler } from './handlers.js';
23
23
  // Handoff protocol handlers and utilities
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAYH,OAAO,EACN,YAAY,EACZ,SAAS,EAET,yBAAyB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,mBAAmB,GACnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAGN,kBAAkB,EAIlB,YA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,EAUlB,kBAAkB;AAClB,sCAAsC;AACtC,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EAEpB,oBAAoB;AAGpB,4BAA4B;AAC5B,uBAAuB,EACvB,yBAAyB,GACzB,MAAM,cAAc,CAAC;AACtB,OAAO,EACN,uBAAuB,EACvB,uBAAuB,GAEvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,YAAY,EAAkB,MAAM,gBAAgB,CAAC"}
@@ -5,12 +5,13 @@ export declare function parseTextContent(result: McpToolCallResult): unknown;
5
5
  export declare function isCommandResult(value: unknown): value is CommandResult;
6
6
  export declare function createBatchFailure<T>(commands: BatchCommand[], startedAt: string, error: CommandError, reasoning: string): BatchResult<T>;
7
7
  /**
8
- * The error for a batch or pipeline whose request got no result: it timed out or the connection
9
- * failed after the request may have reached the server, so some or all commands may have run.
8
+ * The error for a call, batch or pipeline whose request got no result: it timed out, the server
9
+ * returned a 5xx or `-32603`, or the connection failed after the request may have reached the
10
+ * server, so the command (or some or all commands) may have run.
10
11
  *
11
12
  * @param cause - The request error, already converted with `toCommandError()`
12
13
  */
13
- export declare function outcomeUnknownError(cause: CommandError, operation: 'batch' | 'pipeline'): CommandError;
14
+ export declare function outcomeUnknownError(cause: CommandError, operation: 'call' | 'batch' | 'pipeline'): CommandError;
14
15
  /**
15
16
  * A failed batch whose outcome is unknown. It reports no per-command statuses: `results` is
16
17
  * empty and every summary count except `total` is zero, because no command is known to have
@@ -24,4 +25,11 @@ export declare function createUnknownOutcomeBatch<T>(commands: BatchCommand[], s
24
25
  export declare function createUnknownOutcomePipeline<T>(request: PipelineRequest, error: CommandError): PipelineResult<T>;
25
26
  export declare function createPipelineFailure<T>(request: PipelineRequest, error?: CommandError): PipelineResult<T>;
26
27
  export { isBatchResult, isPipelineResult };
28
+ /**
29
+ * A result as `spec/recovery.md` rule 7 says a reader sees it: every error's `recovery` that does
30
+ * not match the schema is dropped, on the result, on each batch item and on each pipeline step,
31
+ * and the rest of each error is kept. The wire is untrusted, so a `recovery` an agent may follow
32
+ * passes the same check as one built in code.
33
+ */
34
+ export declare function withReadableRecoveries<R>(result: R): R;
27
35
  //# sourceMappingURL=result-parsing.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"result-parsing.d.ts","sourceRoot":"","sources":["../src/result-parsing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAEvE,wBAAgB,cAAc,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAKhE;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAOnE;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAOtE;AAED,wBAAgB,kBAAkB,CAAC,CAAC,EACnC,QAAQ,EAAE,YAAY,EAAE,EACxB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,YAAY,EACnB,SAAS,EAAE,MAAM,GACf,WAAW,CAAC,CAAC,CAAC,CAoBhB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAClC,KAAK,EAAE,YAAY,EACnB,SAAS,EAAE,OAAO,GAAG,UAAU,GAC7B,YAAY,CAQd;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,CAAC,EAC1C,QAAQ,EAAE,YAAY,EAAE,EACxB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,YAAY,GACjB,WAAW,CAAC,CAAC,CAAC,CAKhB;AAED;;;GAGG;AACH,wBAAgB,4BAA4B,CAAC,CAAC,EAC7C,OAAO,EAAE,eAAe,EACxB,KAAK,EAAE,YAAY,GACjB,cAAc,CAAC,CAAC,CAAC,CAKnB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,CAAC,CAAC,CAAC,CAKnB;AAED,wBAAgB,qBAAqB,CAAC,CAAC,EACtC,OAAO,EAAE,eAAe,EACxB,KAAK,CAAC,EAAE,YAAY,GAClB,cAAc,CAAC,CAAC,CAAC,CAyBnB;AAED,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,CAAC;AAE3C;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,CAkBtD"}
@@ -1,4 +1,4 @@
1
- import { isBatchResult, isPipelineResult } from '@lushly-dev/afd-core';
1
+ import { isBatchResult, isCommandError, isPipelineResult, withReadableRecovery, } from '@lushly-dev/afd-core';
2
2
  export function getTextContent(result) {
3
3
  return result.content
4
4
  .filter((content) => content.type === 'text')
@@ -42,18 +42,28 @@ export function createBatchFailure(commands, startedAt, error, reasoning) {
42
42
  };
43
43
  }
44
44
  /**
45
- * The error for a batch or pipeline whose request got no result: it timed out or the connection
46
- * failed after the request may have reached the server, so some or all commands may have run.
45
+ * The error for a call, batch or pipeline whose request got no result: it timed out, the server
46
+ * returned a 5xx or `-32603`, or the connection failed after the request may have reached the
47
+ * server, so the command (or some or all commands) may have run.
47
48
  *
48
49
  * @param cause - The request error, already converted with `toCommandError()`
49
50
  */
50
51
  export function outcomeUnknownError(cause, operation) {
52
+ if (operation === 'call') {
53
+ return {
54
+ code: 'OUTCOME_UNKNOWN',
55
+ message: `No command result was received (${cause.message}). The server may have run the command.`,
56
+ suggestion: 'Check the effect of the command before retrying: running it again can repeat a write that already happened.',
57
+ retryable: false,
58
+ details: { ...cause.details, cause: cause.code },
59
+ };
60
+ }
51
61
  return {
52
62
  code: 'OUTCOME_UNKNOWN',
53
63
  message: `No ${operation} result was received (${cause.message}). The server may have run some or all of its commands.`,
54
64
  suggestion: `Check the effect of each command before retrying: running the ${operation} again can repeat writes that already happened.`,
55
65
  retryable: false,
56
- details: { cause: cause.code, ...cause.details },
66
+ details: { ...cause.details, cause: cause.code },
57
67
  };
58
68
  }
59
69
  /**
@@ -104,4 +114,27 @@ export function createPipelineFailure(request, error) {
104
114
  };
105
115
  }
106
116
  export { isBatchResult, isPipelineResult };
117
+ /**
118
+ * A result as `spec/recovery.md` rule 7 says a reader sees it: every error's `recovery` that does
119
+ * not match the schema is dropped, on the result, on each batch item and on each pipeline step,
120
+ * and the rest of each error is kept. The wire is untrusted, so a `recovery` an agent may follow
121
+ * passes the same check as one built in code.
122
+ */
123
+ export function withReadableRecoveries(result) {
124
+ if (typeof result !== 'object' || result === null)
125
+ return result;
126
+ const record = result;
127
+ const read = (value) => (isCommandError(value) ? withReadableRecovery(value) : value);
128
+ const items = (list) => Array.isArray(list)
129
+ ? list.map((item) => typeof item === 'object' && item !== null && 'error' in item
130
+ ? { ...item, error: read(item.error) }
131
+ : item)
132
+ : list;
133
+ return {
134
+ ...record,
135
+ ...('error' in record ? { error: read(record.error) } : {}),
136
+ ...('results' in record ? { results: items(record.results) } : {}),
137
+ ...('steps' in record ? { steps: items(record.steps) } : {}),
138
+ };
139
+ }
107
140
  //# sourceMappingURL=result-parsing.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"result-parsing.js","sourceRoot":"","sources":["../src/result-parsing.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAEvE,MAAM,UAAU,cAAc,CAAC,MAAyB;IACvD,OAAO,MAAM,CAAC,OAAO;SACnB,MAAM,CAAC,CAAC,OAAO,EAA6C,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC;SACvF,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;SAC9B,IAAI,CAAC,EAAE,CAAC,CAAC;AACZ,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,MAAyB;IACzD,MAAM,IAAI,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;IACpC,IAAI,CAAC;QACJ,OAAO,IAA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C,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAC/F,MAAM,KAAK,GAAG,CAAC,IAAa,EAAE,EAAE,CAC/B,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;QAClB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAClB,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,OAAO,IAAI,IAAI;YAC3D,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,IAAI,CAAE,IAA2B,CAAC,KAAK,CAAC,EAAE;YAC9D,CAAC,CAAC,IAAI,CACP;QACF,CAAC,CAAC,IAAI,CAAC;IACT,OAAO;QACN,GAAG,MAAM;QACT,GAAG,CAAC,OAAO,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3D,GAAG,CAAC,SAAS,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClE,GAAG,CAAC,OAAO,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACvD,CAAC;AACR,CAAC"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @fileoverview Browser-safe result-state normalisation for AFD command results.
3
+ *
4
+ * Turns a `CommandResult<T>` (or pending `null`/`undefined`) into a discriminated
5
+ * view-model state (`loading`, `ready`, `empty`, or `error`) without dropping any
6
+ * `CommandResult` field (`confidence`, `reasoning`, `sources`, `plan`, `alternatives`,
7
+ * `warnings`, `suggestions`, `metadata`, `undoCommand`, `undoArgs`, or `result`).
8
+ *
9
+ * Module-graph rule: type-only imports only so `@lushly-dev/afd-client/direct` stays
10
+ * browser-safe and within its minified bundle budget.
11
+ */
12
+ import type { CommandError, CommandResult } from '@lushly-dev/afd-core';
13
+ import type { UnknownToolFailureResult } from './unknown-tool.js';
14
+ /**
15
+ * UX, metadata, and undo fields preserved from `CommandResult<T>` across every settled state.
16
+ */
17
+ export type ResultEnvelopeFields<T = unknown> = Pick<CommandResult<T>, 'confidence' | 'reasoning' | 'sources' | 'plan' | 'alternatives' | 'warnings' | 'suggestions' | 'metadata' | 'undoCommand' | 'undoArgs'>;
18
+ /** Pending state before a command result settles. */
19
+ export interface LoadingResultState<T = unknown> {
20
+ readonly status: 'loading';
21
+ /** Previous settled state when refreshing in place, if supplied. */
22
+ readonly previous?: SettledResultState<T>;
23
+ }
24
+ /** Settled success state with non-empty data. */
25
+ export interface ReadyResultState<T = unknown> extends ResultEnvelopeFields<T> {
26
+ readonly status: 'ready';
27
+ readonly data: T;
28
+ readonly result: CommandResult<T>;
29
+ }
30
+ /** Settled success state whose data is empty (`null`, `undefined`, `[]`, or `isEmpty() === true`). */
31
+ export interface EmptyResultState<T = unknown> extends ResultEnvelopeFields<T> {
32
+ readonly status: 'empty';
33
+ readonly data: T | undefined;
34
+ readonly result: CommandResult<T>;
35
+ }
36
+ /** Settled failure state with normalised error fields and all preserved result metadata. */
37
+ export interface ErrorResultState<T = unknown> extends ResultEnvelopeFields<T> {
38
+ readonly status: 'error';
39
+ /** Machine-readable error code (`'UNKNOWN_ERROR'` if absent on a malformed failure). */
40
+ readonly code: string;
41
+ /** Human-readable error message (`'Command failed'` if absent on a malformed failure). */
42
+ readonly message: string;
43
+ /** Actionable recovery suggestion from `error.suggestion`, when non-empty. */
44
+ readonly suggestion?: string;
45
+ /** Whether retrying the same request may succeed (`false` when unset). */
46
+ readonly retryable: boolean;
47
+ /** Structured technical details from `error.details`, when present. */
48
+ readonly details?: Record<string, unknown>;
49
+ /** Underlying enumerable cause from `error.cause`, when present. */
50
+ readonly cause?: CommandError['cause'];
51
+ /** Original `CommandError` from `result.error`, when present. */
52
+ readonly error?: CommandError;
53
+ /** Optional data payload carried on a failure (for example, `UnknownToolError`). */
54
+ readonly data?: unknown;
55
+ readonly result: CommandResult<T> | UnknownToolFailureResult;
56
+ }
57
+ /** Any settled state produced from a `CommandResult<T>`. */
58
+ export type SettledResultState<T = unknown> = ReadyResultState<T> | EmptyResultState<T> | ErrorResultState<T>;
59
+ /** Discriminated UI state produced by {@link normalizeResultState} and {@link loadingResultState}. */
60
+ export type NormalizedResultState<T = unknown> = LoadingResultState<T> | SettledResultState<T>;
61
+ /** Status discriminant of {@link NormalizedResultState}. */
62
+ export type ResultStateStatus = NormalizedResultState['status'];
63
+ /** Options for {@link normalizeResultState}. */
64
+ export interface NormalizeResultOptions<T = unknown> {
65
+ /**
66
+ * Custom predicate deciding whether a successful result represents an empty state.
67
+ * Defaults to `data === undefined || data === null || (Array.isArray(data) && data.length === 0)`.
68
+ * For enveloped lists (such as `{ items: T[], total: number }`), pass
69
+ * `{ isEmpty: (data) => !data || data.items.length === 0 }`.
70
+ *
71
+ * Because a custom predicate may classify `data: undefined` as `'ready'`, passing `isEmpty`
72
+ * widens the returned state's `T` to `T | undefined`.
73
+ */
74
+ isEmpty?: (data: T | undefined, result: CommandResult<T>) => boolean;
75
+ /** Previous settled state carried when `result` is `null` or `undefined`. */
76
+ previous?: SettledResultState<T | undefined>;
77
+ }
78
+ /**
79
+ * Create a `'loading'` result state, optionally preserving the previous settled state
80
+ * for in-place refresh UIs.
81
+ */
82
+ export declare function loadingResultState<T = unknown>(previous?: SettledResultState<T>): LoadingResultState<T>;
83
+ /**
84
+ * Normalise a `CommandResult<T>` (including `DirectClient.call<T>()` results, or pending
85
+ * `null`/`undefined`) into a discriminated `loading`, `ready`, `empty`, or `error` state
86
+ * while preserving every `CommandResult` field.
87
+ */
88
+ export declare function normalizeResultState<T>(result: CommandResult<T> | UnknownToolFailureResult, options?: {
89
+ previous?: SettledResultState<T>;
90
+ isEmpty?: undefined;
91
+ }): SettledResultState<T>;
92
+ export declare function normalizeResultState<T>(result: CommandResult<T> | UnknownToolFailureResult, options: NormalizeResultOptions<T>): SettledResultState<T | undefined>;
93
+ export declare function normalizeResultState<T>(result: CommandResult<T> | UnknownToolFailureResult | null | undefined, options?: {
94
+ previous?: SettledResultState<T>;
95
+ isEmpty?: undefined;
96
+ }): NormalizedResultState<T>;
97
+ export declare function normalizeResultState<T>(result: CommandResult<T> | UnknownToolFailureResult | null | undefined, options: NormalizeResultOptions<T>): NormalizedResultState<T | undefined>;
98
+ //# sourceMappingURL=result-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-state.d.ts","sourceRoot":"","sources":["../src/result-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAElE;;GAEG;AACH,MAAM,MAAM,oBAAoB,CAAC,CAAC,GAAG,OAAO,IAAI,IAAI,CACnD,aAAa,CAAC,CAAC,CAAC,EACd,YAAY,GACZ,WAAW,GACX,SAAS,GACT,MAAM,GACN,cAAc,GACd,UAAU,GACV,aAAa,GACb,UAAU,GACV,aAAa,GACb,UAAU,CACZ,CAAC;AAEF,qDAAqD;AACrD,MAAM,WAAW,kBAAkB,CAAC,CAAC,GAAG,OAAO;IAC9C,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,oEAAoE;IACpE,QAAQ,CAAC,QAAQ,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,CAAC;CAC1C;AAED,iDAAiD;AACjD,MAAM,WAAW,gBAAgB,CAAC,CAAC,GAAG,OAAO,CAAE,SAAQ,oBAAoB,CAAC,CAAC,CAAC;IAC7E,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IACjB,QAAQ,CA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,CAAC,CAAC,GAAG,wBAAwB,GAAG,IAAI,GAAG,SAAS,EACtE,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE,kBAAkB,CAAC,CAAC,CAAC,CAAC;IAAC,OAAO,CAAC,EAAE,SAAS,CAAA;CAAE,GACjE,qBAAqB,CAAC,CAAC,CAAC,CAAC;AAC5B,wBAAgB,oBAAoB,CAAC,CAAC,EACrC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,wBAAwB,GAAG,IAAI,GAAG,SAAS,EACtE,OAAO,EAAE,sBAAsB,CAAC,CAAC,CAAC,GAChC,qBAAqB,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC"}
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @fileoverview Browser-safe result-state normalisation for AFD command results.
3
+ *
4
+ * Turns a `CommandResult<T>` (or pending `null`/`undefined`) into a discriminated
5
+ * view-model state (`loading`, `ready`, `empty`, or `error`) without dropping any
6
+ * `CommandResult` field (`confidence`, `reasoning`, `sources`, `plan`, `alternatives`,
7
+ * `warnings`, `suggestions`, `metadata`, `undoCommand`, `undoArgs`, or `result`).
8
+ *
9
+ * Module-graph rule: type-only imports only so `@lushly-dev/afd-client/direct` stays
10
+ * browser-safe and within its minified bundle budget.
11
+ */
12
+ const DEFAULT_ERROR_CODE = 'UNKNOWN_ERROR';
13
+ const DEFAULT_ERROR_MESSAGE = 'Command failed';
14
+ function defaultIsEmpty(data) {
15
+ return data === undefined || data === null || (Array.isArray(data) && data.length === 0);
16
+ }
17
+ function extractEnvelopeFields(result) {
18
+ return {
19
+ ...(result.confidence !== undefined && { confidence: result.confidence }),
20
+ ...(result.reasoning !== undefined && { reasoning: result.reasoning }),
21
+ ...(result.sources !== undefined && { sources: result.sources }),
22
+ ...(result.plan !== undefined && { plan: result.plan }),
23
+ ...(result.alternatives !== undefined && { alternatives: result.alternatives }),
24
+ ...(result.warnings !== undefined && { warnings: result.warnings }),
25
+ ...(result.suggestions !== undefined && { suggestions: result.suggestions }),
26
+ ...(result.metadata !== undefined && { metadata: result.metadata }),
27
+ ...(result.undoCommand !== undefined && { undoCommand: result.undoCommand }),
28
+ ...(result.undoArgs !== undefined && { undoArgs: result.undoArgs }),
29
+ };
30
+ }
31
+ /**
32
+ * Create a `'loading'` result state, optionally preserving the previous settled state
33
+ * for in-place refresh UIs.
34
+ */
35
+ export function loadingResultState(previous) {
36
+ return previous !== undefined ? { status: 'loading', previous } : { status: 'loading' };
37
+ }
38
+ export function normalizeResultState(result, options) {
39
+ if (result === null || result === undefined) {
40
+ return loadingResultState(options?.previous);
41
+ }
42
+ const envelope = extractEnvelopeFields(result);
43
+ if (result.success !== true) {
44
+ const rawError = result.error;
45
+ const errorObj = typeof rawError === 'object' && rawError !== null ? rawError : undefined;
46
+ const code = typeof errorObj?.code === 'string' && errorObj.code.trim().length > 0
47
+ ? errorObj.code
48
+ : DEFAULT_ERROR_CODE;
49
+ const message = typeof errorObj?.message === 'string' && errorObj.message.trim().length > 0
50
+ ? errorObj.message
51
+ : DEFAULT_ERROR_MESSAGE;
52
+ const suggestion = typeof errorObj?.suggestion === 'string' && errorObj.suggestion.trim().length > 0
53
+ ? errorObj.suggestion
54
+ : undefined;
55
+ const hasEnumerableCause = errorObj !== undefined &&
56
+ Object.prototype.propertyIsEnumerable.call(errorObj, 'cause') &&
57
+ errorObj.cause !== undefined;
58
+ return {
59
+ status: 'error',
60
+ code,
61
+ message,
62
+ ...(suggestion !== undefined && { suggestion }),
63
+ retryable: errorObj?.retryable === true,
64
+ ...(errorObj?.details !== undefined && { details: errorObj.details }),
65
+ ...(hasEnumerableCause && { cause: errorObj.cause }),
66
+ ...(errorObj !== undefined && { error: errorObj }),
67
+ ...(result.data !== undefined && { data: result.data }),
68
+ ...envelope,
69
+ result,
70
+ };
71
+ }
72
+ const successResult = result;
73
+ const isEmpty = options?.isEmpty
74
+ ? options.isEmpty(successResult.data, successResult)
75
+ : defaultIsEmpty(successResult.data);
76
+ if (isEmpty) {
77
+ return {
78
+ status: 'empty',
79
+ data: successResult.data,
80
+ ...envelope,
81
+ result: successResult,
82
+ };
83
+ }
84
+ return {
85
+ status: 'ready',
86
+ data: successResult.data,
87
+ ...envelope,
88
+ result: successResult,
89
+ };
90
+ }
91
+ //# sourceMappingURL=result-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-state.js","sourceRoot":"","sources":["../src/result-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AA6FH,MAAM,kBAAkB,GAAG,eAAe,CAAC;AAC3C,MAAM,qBAAqB,GAAG,gBAAgB,CAAC;AAE/C,SAAS,cAAc,CAAC,IAAa;IACpC,OAAO,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;AAC1F,CAAC;AAED,SAAS,qBAAqB,CAAI,MAAwB;IACzD,OAAO;QACN,GAAG,CAAC,MAAM,CAAC,UAAU,KAAK,SAAS,IAAI,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;QACzE,GAAG,CAAC,MAAM,CAAC,SAAS,KAAK,SAAS,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC;QACtE,GAAG,CAAC,MAAM,CAAC,OAAO,KAAK,SAAS,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;QAChE,GAAG,CAAC,MAAM,CAAC,IAAI,KAAK,SAAS,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;QACvD,GAAG,CAAC,MAAM,CAAC,YAAY,KAAK,SAAS,IAAI,EAAE,YAAY,EAAE,MAAM,CAAC,YAAY,EAAE,CAAC;QAC/E,GAAG,CAAC,MAAM,CAAC,QAAQ,KAAK,SAAS,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC;QACnE,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AQ;YACX,MAAM;SACN,CAAC;IACH,CAAC;IAED,MAAM,aAAa,GAAG,MAA0B,CAAC;IACjD,MAAM,OAAO,GAAG,OAAO,EAAE,OAAO;QAC/B,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,EAAE,aAAa,CAAC;QACpD,CAAC,CAAC,cAAc,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAEtC,IAAI,OAAO,EAAE,CAAC;QACb,OAAO;YACN,MAAM,EAAE,OAAO;YACf,IAAI,EAAE,aAAa,CAAC,IAAI;YACxB,GAAG,QAAQ;YACX,MAAM,EAAE,aAAa;SACrB,CAAC;IACH,CAAC;IAED,OAAO;QACN,MAAM,EAAE,OAAO;QACf,IAAI,EAAE,aAAa,CAAC,IAAI;QACxB,GAAG,QAAQ;QACX,MAAM,EAAE,aAAa;KACrB,CAAC;AACH,CAAC"}
@@ -10,7 +10,7 @@
10
10
  * (`initialize`, `tools/list`, `tools/call`) onto the SDK client. `initialize` is answered
11
11
  * locally from what negotiation learned: there is no handshake on the modern protocol.
12
12
  */
13
- import type { McpRequest, McpResponse } from '@lushly-dev/afd-core';
13
+ import type { McpRequest, McpResponse, ServerContract } from '@lushly-dev/afd-core';
14
14
  import type { Transport } from './transport.js';
15
15
  import type { ElicitationHandler } from './types.js';
16
16
  /** How the transport negotiates the protocol revision. */
@@ -25,6 +25,8 @@ export interface StreamableHttpTransportOptions {
25
25
  mode?: StreamableHttpMode;
26
26
  /** Answers form elicitations; without it the client declares no elicitation capability. */
27
27
  onElicitation?: ElicitationHandler;
28
+ /** Declare the MCP Tasks extension (`io.modelcontextprotocol/tasks`) on modern requests. */
29
+ tasks?: boolean;
28
30
  /**
29
31
  * The `fetch` every request goes through. A host that does not trust the server uses it to limit
30
32
  * what it reads, since the SDK reads a response whole and holds an event stream open with no deadline.
@@ -39,9 +41,17 @@ export declare class StreamableHttpTransport implements Transport {
39
41
  private messageHandler;
40
42
  private errorHandler;
41
43
  private closeHandler;
44
+ private readonly pendingTasks;
45
+ private handshakeMeta;
46
+ private serverContract;
42
47
  constructor(url: string, options: StreamableHttpTransportOptions);
43
48
  connect(signal?: AbortSignal): Promise<void>;
44
49
  disconnect(): void;
50
+ /**
51
+ * The AFD contract advertised by the server in `_meta["dev.afd/contract"]` on
52
+ * `server/discover` or `initialize` (`spec/tool-strategies.md#contract-advertisement`, #1927).
53
+ */
54
+ getServerContract(): ServerContract | undefined;
45
55
  /** The negotiated protocol revision, such as `2026-07-28` or `2025-11-25`. */
46
56
  get protocolVersion(): string | undefined;
47
57
  /** `modern` for 2026-07-28 and later, `legacy` for the `initialize` handshake. */
@@ -1 +1 @@
1
- {"version":3,"file":"streamable-http-transport.d.ts","sourceRoot":"","sources":["../src/streamable-http-transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAuB,UAAU,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAOzF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,0DAA0D;AAC1D,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAE9D,kDAAkD;AAClD,eAAO,MAAM,uBAAuB,eAAe,CAAC;AAQpD,MAAM,WAAW,8BAA8B;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,0EAA0E;IAC1E,IAAI,CAAC,EAAE,kBAAkB,CAAC;IAC1B,2FAA2F;IAC3F,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACrB;AAyBD,qBAAa,uBAAwB,YAAW,SAAS;IAQvD,QAAQ,CAAC,GAAG,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AAG,SAAS,CAEjD;IAEK,IAAI,CAAC,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,CAsE1E;IAED,WAAW,IAAI,OAAO,CAErB;IAED,SAAS,CAAC,OAAO,EAAE,CAAC,QAAQ,EAAE,WAAW,KAAK,IAAI,GAAG,IAAI,CAExD;IAED,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,GAAG,IAAI,CAE7C;IAED,OAAO,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI,CAEjC;IAED,OAAO,CAAC,gBAAgB;CAaxB"}
@@ -19,6 +19,45 @@ export const MODERN_PROTOCOL_VERSION = '2026-07-28';
19
19
  * through its signal.
20
20
  */
21
21
  const NO_SDK_TIMEOUT = 2_147_483_647;
22
+ const TASKS_EXTENSION_ID = 'io.modelcontextprotocol/tasks';
23
+ const TASK_SENTINEL = '__afd_mcp_task__';
24
+ const AFD_CONTRACT_META_KEY = 'dev.afd/contract';
25
+ function isPlainRecord(value) {
26
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
27
+ }
28
+ /**
29
+ * Browser-safe parser for `_meta["dev.afd/contract"]` (`spec/tool-strategies.md#contract-advertisement`,
30
+ * rules 3 and 4). Kept inline so `@lushly-dev/afd-client/streamable-http` adds no runtime dependency
31
+ * on `@lushly-dev/afd-core`.
32
+ */
33
+ function parseContractFromMeta(meta) {
34
+ if (!isPlainRecord(meta))
35
+ return undefined;
36
+ const raw = meta[AFD_CONTRACT_META_KEY];
37
+ if (!isPlainRecord(raw))
38
+ return undefined;
39
+ if (typeof raw.version !== 'string' || raw.version.length === 0)
40
+ return undefined;
41
+ if (!isPlainRecord(raw.profiles))
42
+ return undefined;
43
+ const entries = [];
44
+ for (const id of Object.keys(raw.profiles).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
45
+ const entry = raw.profiles[id];
46
+ if (!isPlainRecord(entry))
47
+ continue;
48
+ if (typeof entry.version !== 'string' || entry.version.length === 0)
49
+ continue;
50
+ entries.push([id, { version: entry.version }]);
51
+ }
52
+ return { version: raw.version, profiles: Object.fromEntries(entries) };
53
+ }
54
+ const PASS_THROUGH_SCHEMA = {
55
+ '~standard': {
56
+ version: 1,
57
+ vendor: 'afd',
58
+ validate: (value) => ({ value }),
59
+ },
60
+ };
22
61
  /**
23
62
  * The tool result for an `input_required` answer the client cannot fulfil: an `INPUT_REQUIRED`
24
63
  * failure carrying what the server asked.
@@ -48,6 +87,9 @@ export class StreamableHttpTransport {
48
87
  messageHandler = null;
49
88
  errorHandler = null;
50
89
  closeHandler = null;
90
+ pendingTasks = new Map();
91
+ handshakeMeta;
92
+ serverContract;
51
93
  constructor(url, options) {
52
94
  this.url = url;
53
95
  this.options = options;
@@ -57,8 +99,13 @@ export class StreamableHttpTransport {
57
99
  this.disconnect();
58
100
  const mode = this.options.mode ?? 'auto';
59
101
  const onElicitation = this.options.onElicitation;
102
+ const capabilities = {};
103
+ if (onElicitation)
104
+ capabilities.elicitation = { form: {} };
105
+ if (this.options.tasks)
106
+ capabilities.extensions = { [TASKS_EXTENSION_ID]: {} };
60
107
  const client = new Client({ name: this.options.clientName, version: this.options.clientVersion }, {
61
- capabilities: onElicitation ? { elicitation: { form: {} } } : {},
108
+ capabilities: capabilities,
62
109
  versionNegotiation: { mode: mode === 'modern' ? { pin: MODERN_PROTOCOL_VERSION } : mode },
63
110
  // Without a handler, an input_required answer is returned to `send` as is.
64
111
  ...(!onElicitation && { inputRequired: { autoFulfill: false } }),
@@ -76,6 +123,35 @@ export class StreamableHttpTransport {
76
123
  ...(this.options.headers && { requestInit: { headers: this.options.headers } }),
77
124
  ...(this.options.fetch && { fetch: this.options.fetch }),
78
125
  });
126
+ // Capture handshake `_meta` on the wire before the SDK processes it: `@modelcontextprotocol/client`
127
+ // v2.4.0 discards `InitializeResult._meta` during legacy negotiation (#1927).
128
+ let capturedHandshakeMeta;
129
+ let sdkOnMessage = transport.onmessage;
130
+ Object.defineProperty(transport, 'onmessage', {
131
+ configurable: true,
132
+ enumerable: true,
133
+ get: () => sdkOnMessage,
134
+ set: (handler) => {
135
+ if (!handler) {
136
+ sdkOnMessage = handler;
137
+ return;
138
+ }
139
+ sdkOnMessage = (message) => {
140
+ const msg = message;
141
+ if (!capturedHandshakeMeta &&
142
+ msg &&
143
+ typeof msg === 'object' &&
144
+ 'result' in msg &&
145
+ isPlainRecord(msg.result) &&
146
+ isPlainRecord(msg.result._meta) &&
147
+ ('supportedVersions' in msg.result ||
148
+ ('protocolVersion' in msg.result && 'serverInfo' in msg.result))) {
149
+ capturedHandshakeMeta = msg.result._meta;
150
+ }
151
+ handler(message);
152
+ };
153
+ },
154
+ });
79
155
  client.onerror = (error) => {
80
156
  if (this.client === client)
81
157
  this.errorHandler?.(error);
@@ -84,6 +160,8 @@ export class StreamableHttpTransport {
84
160
  if (this.client !== client || !this.connected)
85
161
  return;
86
162
  this.connected = false;
163
+ this.handshakeMeta = undefined;
164
+ this.serverContract = undefined;
87
165
  this.closeHandler?.();
88
166
  };
89
167
  this.client = client;
@@ -102,6 +180,48 @@ export class StreamableHttpTransport {
102
180
  await client.close().catch(() => { });
103
181
  throw new Error('Transport disconnected');
104
182
  }
183
+ if (this.options.tasks) {
184
+ // The MCP SDK v2.4.0 rev2026 codec rejects `resultType: 'task'` on `tools/call`.
185
+ // Intercept it on the transport boundary and carry it to `send()` via a private token.
186
+ const deliver = transport.onmessage;
187
+ transport.onmessage = (message) => {
188
+ const msg = message;
189
+ if (msg &&
190
+ typeof msg === 'object' &&
191
+ 'result' in msg &&
192
+ msg.result &&
193
+ typeof msg.result === 'object') {
194
+ if (msg.result.resultType === 'task') {
195
+ const token = crypto.randomUUID();
196
+ this.pendingTasks.set(token, msg.result);
197
+ deliver?.({
198
+ jsonrpc: '2.0',
199
+ id: msg.id,
200
+ result: {
201
+ resultType: 'complete',
202
+ content: [],
203
+ _meta: { [TASK_SENTINEL]: token },
204
+ },
205
+ });
206
+ return;
207
+ }
208
+ const meta = msg.result._meta;
209
+ if (meta && typeof meta === 'object' && TASK_SENTINEL in meta) {
210
+ const { [TASK_SENTINEL]: _stripped, ...restMeta } = meta;
211
+ deliver?.({
212
+ ...msg,
213
+ result: { ...msg.result, _meta: restMeta },
214
+ });
215
+ return;
216
+ }
217
+ }
218
+ deliver?.(message);
219
+ };
220
+ }
221
+ const discoverMeta = client.getDiscoverResult?.()?._meta;
222
+ const resolvedHandshakeMeta = capturedHandshakeMeta ?? (isPlainRecord(discoverMeta) ? discoverMeta : undefined);
223
+ this.handshakeMeta = resolvedHandshakeMeta;
224
+ this.serverContract = parseContractFromMeta(resolvedHandshakeMeta);
105
225
  this.connected = true;
106
226
  }
107
227
  disconnect() {
@@ -109,10 +229,20 @@ export class StreamableHttpTransport {
109
229
  const wasConnected = this.connected;
110
230
  this.client = null;
111
231
  this.connected = false;
232
+ this.handshakeMeta = undefined;
233
+ this.serverContract = undefined;
234
+ this.pendingTasks.clear();
112
235
  client?.close().catch(() => { });
113
236
  if (wasConnected)
114
237
  this.closeHandler?.();
115
238
  }
239
+ /**
240
+ * The AFD contract advertised by the server in `_meta["dev.afd/contract"]` on
241
+ * `server/discover` or `initialize` (`spec/tool-strategies.md#contract-advertisement`, #1927).
242
+ */
243
+ getServerContract() {
244
+ return this.connected ? this.serverContract : undefined;
245
+ }
116
246
  /** The negotiated protocol revision, such as `2026-07-28` or `2025-11-25`. */
117
247
  get protocolVersion() {
118
248
  return this.client?.getNegotiatedProtocolVersion();
@@ -140,9 +270,28 @@ export class StreamableHttpTransport {
140
270
  ...options,
141
271
  ...(!this.options.onElicitation && { allowInputRequired: true }),
142
272
  }));
143
- result = called.resultType === 'input_required' ? inputRequiredResult(called) : called;
273
+ const taskToken = called._meta?.[TASK_SENTINEL];
274
+ if (typeof taskToken === 'string') {
275
+ const taskResult = this.pendingTasks.get(taskToken);
276
+ this.pendingTasks.delete(taskToken);
277
+ result = taskResult ?? called;
278
+ }
279
+ else {
280
+ result = called.resultType === 'input_required' ? inputRequiredResult(called) : called;
281
+ }
144
282
  break;
145
283
  }
284
+ case 'tasks/get':
285
+ case 'tasks/update':
286
+ case 'tasks/cancel':
287
+ // Resources (spec/mcp-resources.md, R3 and R4), such as an MCP Apps `ui://` view.
288
+ case 'resources/list':
289
+ case 'resources/read':
290
+ // The Skills extension (spec/mcp-resources.md, S3 and S4).
291
+ case 'skills/list':
292
+ case 'skills/get':
293
+ result = await client.request({ method: request.method, params: request.params }, PASS_THROUGH_SCHEMA, options);
294
+ break;
146
295
  default:
147
296
  return {
148
297
  jsonrpc: '2.0',
@@ -194,6 +343,7 @@ export class StreamableHttpTransport {
194
343
  version: client.getServerVersion()?.version ?? '',
195
344
  },
196
345
  ...(instructions && { instructions }),
346
+ ...(this.handshakeMeta && { _meta: this.handshakeMeta }),
197
347
  };
198
348
  }
199
349
  }