@ekanos/sdk 0.25.0 → 0.27.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 (62) hide show
  1. package/README.md +9 -11
  2. package/api-report.md +27 -6
  3. package/dist/components/base-activation-dialog.js +2 -2
  4. package/dist/components/base-activation-dialog.js.map +1 -1
  5. package/dist/components/base-activation-form.js +1 -1
  6. package/dist/components/base-activation-form.js.map +1 -1
  7. package/dist/components/base-marketplace-tile.js +2 -2
  8. package/dist/components/base-marketplace-tile.js.map +1 -1
  9. package/dist/components/index.d.ts +1 -0
  10. package/dist/components/index.js +1 -0
  11. package/dist/components/index.js.map +1 -1
  12. package/dist/components/oauth-activation-form.d.ts +8 -0
  13. package/dist/components/oauth-activation-form.js +10 -4
  14. package/dist/components/oauth-activation-form.js.map +1 -1
  15. package/dist/components/widgets/ai-prompt-chip.js +3 -3
  16. package/dist/components/widgets/ai-prompt-chip.js.map +1 -1
  17. package/dist/components/widgets/widget-ask-bar.js +1 -1
  18. package/dist/components/widgets/widget-ask-bar.js.map +1 -1
  19. package/dist/components/widgets/widget-ask-presentation.d.ts +35 -0
  20. package/dist/components/widgets/widget-ask-presentation.js +35 -0
  21. package/dist/components/widgets/widget-ask-presentation.js.map +1 -0
  22. package/dist/components/widgets/widget-state-components.d.ts +6 -1
  23. package/dist/components/widgets/widget-state-components.js +9 -9
  24. package/dist/components/widgets/widget-state-components.js.map +1 -1
  25. package/dist/components/widgets/widget.d.ts +4 -4
  26. package/dist/components/widgets/widget.js +43 -31
  27. package/dist/components/widgets/widget.js.map +1 -1
  28. package/dist/context/types.d.ts +1 -1
  29. package/dist/context/types.js.map +1 -1
  30. package/dist/contract/derive-contract.js +16 -10
  31. package/dist/contract/derive-contract.js.map +1 -1
  32. package/dist/contract/types.d.ts +1 -1
  33. package/dist/contract/types.js.map +1 -1
  34. package/dist/experience/client.d.ts +76 -0
  35. package/dist/experience/client.js +103 -2
  36. package/dist/experience/client.js.map +1 -1
  37. package/dist/experience/runtime.d.ts +16 -0
  38. package/dist/experience/runtime.js.map +1 -1
  39. package/dist/experience/sdk-instances.d.ts +11 -0
  40. package/dist/experience/sdk-instances.js +47 -0
  41. package/dist/experience/sdk-instances.js.map +1 -0
  42. package/dist/hooks/index.d.ts +1 -1
  43. package/dist/hooks/index.js.map +1 -1
  44. package/dist/hooks/partner-oauth.d.ts +15 -2
  45. package/dist/hooks/partner-oauth.js +3 -0
  46. package/dist/hooks/partner-oauth.js.map +1 -1
  47. package/dist/index.d.ts +1 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/integration/index.d.ts +4 -2
  50. package/dist/integration/index.js +4 -1
  51. package/dist/integration/index.js.map +1 -1
  52. package/dist/testing/mock-context.d.ts +21 -2
  53. package/dist/testing/mock-context.js +102 -45
  54. package/dist/testing/mock-context.js.map +1 -1
  55. package/dist/types/workspace-target.d.ts +1 -1
  56. package/dist/types/workspace-target.js.map +1 -1
  57. package/dist/version.d.ts +7 -0
  58. package/dist/version.js +8 -0
  59. package/dist/version.js.map +1 -0
  60. package/eslint.design-preset.mjs +6 -4
  61. package/eslint.design-rules.mjs +218 -9
  62. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"derive-contract.js","sourceRoot":"","sources":["../../src/contract/derive-contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,UAAU,EACV,YAAY,EACZ,qBAAqB,EACrB,cAAc,GACf,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EACL,uBAAuB,GAIxB,MAAM,SAAS,CAAC;AAOjB,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AA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CAAC,CAAC;IACjD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n type Contract,\n type ContractEvent,\n type ContractOperation,\n type JsonSchema,\n compatLine,\n sealContract,\n validateAgainstSchema,\n verifyContract,\n} from '@ekanos/integration-schema';\n\nimport { synthesizeExample } from './synthesize-example';\nimport { toJsonSchema } from './to-json-schema';\nimport {\n ContractDerivationError,\n type ContractDiagnostic,\n type DeriveContractOptions,\n type DeriveContractResult,\n} from './types';\n\ntype Loose = Record<string, unknown>;\ntype Effect = 'read' | 'write';\ntype Sensitivity = 'public' | 'internal' | 'pii' | 'financial';\ntype Classification = { effect?: Effect; sensitivity?: Sensitivity };\n\nfunction isRecord(value: unknown): value is Loose {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction asRecordOf<T>(value: unknown): Record<string, T> {\n return isRecord(value) ? (value as Record<string, T>) : {};\n}\n\nfunction inferConnection(definition: Loose): Contract['connection'] {\n const declared = isRecord(definition.connection) ? definition.connection : {};\n const oauth = isRecord(definition.oauth) ? definition.oauth : null;\n const provider = oauth && isRecord(oauth.provider) ? oauth.provider : null;\n const proposes = isRecord(definition.proposes) ? definition.proposes : {};\n\n const auth =\n (declared.auth as Contract['connection']['auth'] | undefined) ??\n (oauth ? 'oauth2' : 'none');\n const scopes =\n (declared.scopes as string[] | undefined) ??\n (provider && Array.isArray(provider.scopes)\n ? (provider.scopes as string[])\n : []);\n const fromModel =\n proposes.credentialModel === 'user'\n ? ['user']\n : proposes.credentialModel === 'source'\n ? ['source']\n : proposes.scope === 'user'\n ? ['user']\n : ['team'];\n const levels =\n (declared.levels as Contract['connection']['levels'] | undefined) ??\n (fromModel as Contract['connection']['levels']);\n return { levels, auth, scopes };\n}\n\nfunction opaqueReasonFor(\n input: { opaque: boolean; reason?: string },\n output: { opaque: boolean; reason?: string },\n): string | undefined {\n const parts: string[] = [];\n if (input.opaque) parts.push(`input: ${input.reason ?? 'opaque'}`);\n if (output.opaque) parts.push(`output: ${output.reason ?? 'opaque'}`);\n return parts.length > 0 ? parts.join('; ') : undefined;\n}\n\n/**\n * Derive and seal the contract artifact from a `defineIntegration` result.\n * Non-throwing: returns diagnostics beside the contract (a contract that\n * fails its own `verifyContract` is reported as error diagnostics).\n */\nexport function analyzeContract(\n rawDefinition: unknown,\n options: DeriveContractOptions,\n): DeriveContractResult {\n const definition = isRecord(rawDefinition) ? rawDefinition : {};\n const diagnostics: ContractDiagnostic[] = [];\n const line = compatLine(options.contractVersion);\n const slug = String(definition.slug ?? '');\n const proposes = isRecord(definition.proposes) ? definition.proposes : {};\n const toolClassifications = asRecordOf<Classification>(proposes.tools);\n const actionClassifications = asRecordOf<Classification>(proposes.actions);\n const previousSince = new Map(\n (options.previous?.operations ?? []).map((op) => [op.id, op.since]),\n );\n\n const classify = (\n key: string,\n declared: Classification,\n proposed: Classification | undefined,\n ): { effect: Effect; sensitivity: Sensitivity } => {\n const effect = declared.effect ?? proposed?.effect;\n if (!effect) {\n diagnostics.push({\n rule: 'contract/effect-undeclared',\n severity: 'warn',\n operation: key,\n message: 'no effect declared; treated as a write (fail safe).',\n });\n }\n return {\n effect: effect ?? 'write',\n sensitivity: declared.sensitivity ?? proposed?.sensitivity ?? 'internal',\n };\n };\n\n const build = (\n kind: 'tool' | 'action',\n name: string,\n parts: {\n description: unknown;\n input: { schema: JsonSchema; opaque: boolean; reason?: string };\n outputSchema: unknown;\n authoredExample: unknown;\n classification: { effect: Effect; sensitivity: Sensitivity };\n },\n ): ContractOperation => {\n const key = `${kind}/${name}`;\n const id = `${slug}@${line}/${kind}/${name}`;\n if (\n typeof parts.description !== 'string' ||\n parts.description.length === 0\n ) {\n diagnostics.push({\n rule: 'contract/description-missing',\n severity: 'error',\n operation: key,\n message: 'a description is required.',\n });\n }\n\n let output: { schema: JsonSchema; opaque: boolean; reason?: string };\n if (parts.outputSchema === undefined) {\n output = {\n schema: {},\n opaque: true,\n reason: `the ${kind} declares no runtime output schema`,\n };\n diagnostics.push({\n rule: 'contract/output-schema-missing',\n severity: options.requireOutputSchemas ? 'error' : 'warn',\n operation: key,\n message: `no output schema; the output is opaque and an experience cannot bind to ${key}. Declare ${kind === 'tool' ? '`output`' : '`output`'} as a zod schema.`,\n });\n } else {\n output = toJsonSchema(parts.outputSchema, 'output');\n if (output.opaque) {\n diagnostics.push({\n rule: 'contract/output-opaque',\n severity: options.requireOutputSchemas ? 'error' : 'warn',\n operation: key,\n message: `output is opaque: ${output.reason}.`,\n });\n }\n }\n if (parts.input.opaque) {\n diagnostics.push({\n rule: 'contract/input-opaque',\n severity: 'warn',\n operation: key,\n message: `input is opaque: ${parts.input.reason}.`,\n });\n }\n\n let outputExample: unknown =\n parts.authoredExample ?? options.examples?.[key];\n if (outputExample === undefined && !output.opaque) {\n if (parts.classification.effect === 'read') {\n diagnostics.push({\n rule: 'contract/example-missing',\n severity: 'error',\n operation: key,\n message:\n 'a read operation needs an outputExample (author one or run `ekanos contract --record`).',\n });\n } else {\n outputExample = synthesizeExample(output.schema);\n diagnostics.push({\n rule: 'contract/example-synthesized',\n severity: 'warn',\n operation: key,\n message:\n 'no outputExample; a placeholder was synthesized from the schema.',\n });\n }\n }\n if (outputExample !== undefined && !output.opaque) {\n const problems = validateAgainstSchema(output.schema, outputExample);\n if (problems.length > 0) {\n diagnostics.push({\n rule: 'contract/example-invalid',\n severity: 'error',\n operation: key,\n message: `outputExample does not satisfy output: ${problems[0]}`,\n });\n }\n }\n\n const reason = opaqueReasonFor(parts.input, output);\n const since = previousSince.get(id) ?? options.packageVersion;\n return {\n id,\n kind,\n name,\n description:\n typeof parts.description === 'string' ? parts.description : '',\n effect: parts.classification.effect,\n sensitivity: parts.classification.sensitivity,\n input: parts.input.schema,\n output: output.schema,\n opaque: { input: parts.input.opaque, output: output.opaque },\n ...(reason ? { opaqueReason: reason } : {}),\n ...(outputExample !== undefined && !output.opaque\n ? { outputExample }\n : {}),\n since,\n } as ContractOperation;\n };\n\n const operations: ContractOperation[] = [];\n\n for (const [name, raw] of Object.entries(\n asRecordOf<Loose>(definition.actions),\n )) {\n const input = toJsonSchema(raw.input, 'input');\n operations.push(\n build('action', name, {\n description: raw.description,\n input,\n outputSchema: raw.output,\n authoredExample: raw.outputExample,\n classification: classify(\n `action/${name}`,\n {\n effect: raw.effect as Effect | undefined,\n sensitivity: raw.sensitivity as Sensitivity | undefined,\n },\n actionClassifications[name],\n ),\n }),\n );\n }\n\n const tools = Array.isArray(definition.tools)\n ? (definition.tools as Loose[])\n : [];\n for (const tool of tools) {\n const name = String(tool.name);\n const parameters = isRecord(tool.parameters)\n ? (tool.parameters as JsonSchema)\n : ({ type: 'object', properties: {} } as JsonSchema);\n operations.push(\n build('tool', name, {\n description: tool.description,\n input: { schema: parameters, opaque: false },\n outputSchema: tool.output,\n authoredExample: tool.outputExample,\n classification: classify(`tool/${name}`, {}, toolClassifications[name]),\n }),\n );\n }\n\n const events: ContractEvent[] = [];\n for (const raw of Array.isArray(definition.agentEvents)\n ? (definition.agentEvents as Loose[])\n : []) {\n const converted =\n raw.payloadSchema === undefined\n ? null\n : toJsonSchema(raw.payloadSchema, 'output');\n if (!converted || converted.opaque) {\n diagnostics.push({\n rule: 'contract/event-schema-missing',\n severity: 'warn',\n operation: String(raw.id),\n message: `event payload is opaque${converted?.reason ? `: ${converted.reason}` : ''}.`,\n });\n }\n events.push({\n name: String(raw.id),\n payload: converted?.schema ?? {},\n opaque: converted?.opaque ?? true,\n ...(raw.examplePayload !== undefined\n ? { payloadExample: raw.examplePayload }\n : {}),\n });\n }\n\n const contract = sealContract({\n schemaVersion: 1,\n integration: slug,\n packageVersion: options.packageVersion,\n contractVersion: options.contractVersion,\n compatLine: line,\n connection: inferConnection(definition),\n ...(definition.health ? { health: true } : {}),\n operations,\n events,\n });\n\n const { problems } = verifyContract(contract);\n for (const problem of problems) {\n // Example problems were already reported with a friendlier rule.\n if (problem.rule === 'contract.output-example-invalid') continue;\n if (\n problem.rule === 'contract.output-example' &&\n diagnostics.some(\n (d) =>\n d.rule === 'contract/example-missing' &&\n d.operation === problem.operation?.replace(/^[^/]*\\//, ''),\n )\n ) {\n continue;\n }\n diagnostics.push({\n rule:\n problem.rule === 'contract.output-example'\n ? 'contract/example-missing'\n : 'contract/not-sealable',\n severity: 'error',\n message: problem.message,\n ...(problem.operation ? { operation: problem.operation } : {}),\n });\n }\n\n return { contract, diagnostics };\n}\n\n/**\n * `deriveContract(definition, { packageVersion, contractVersion, previous? })`:\n * the sealed `Contract`; throws `ContractDerivationError` when an error\n * diagnostic exists. Use `analyzeContract` to read warnings too.\n */\nexport function deriveContract(\n definition: unknown,\n options: DeriveContractOptions,\n): Contract {\n const { contract, diagnostics } = analyzeContract(definition, options);\n if (diagnostics.some((d) => d.severity === 'error')) {\n throw new ContractDerivationError(diagnostics);\n }\n return contract;\n}\n"]}
1
+ {"version":3,"file":"derive-contract.js","sourceRoot":"","sources":["../../src/contract/derive-contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,UAAU,EACV,wBAAwB,EACxB,wBAAwB,EACxB,YAAY,EACZ,qBAAqB,EACrB,cAAc,GACf,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EACL,uBAAuB,GAIxB,MAAM,SAAS,CAAC;AAOjB,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,UAAU,CAAI,KAAc;IACnC,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,KAA2B,CAAC,CAAC,CAAC,EAAE,CAAC;AAC7D,CAAC;AAED;;;;;GAKG;AACH,SAAS,eAAe,CAAC,UAAiB;;IACxC,MAAM,QAAQ,GAAG,QAAQ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AAyB;YAC1C,WAAW,CAAC,IAAI,CACd,CAAC,CAAC,EAAE,EAAE,kBACJ,CAAC,CAAC,IAAI,KAAK,0BAA0B;gBACrC,CAAC,CAAC,SAAS,MAAK,MAAA,OAAO,CAAC,SAAS,0CAAE,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAA,GAAA,CAC7D,EACD,CAAC;YACD,SAAS;QACX,CAAC;QACD,WAAW,CAAC,IAAI,iBACd,IAAI,EACF,OAAO,CAAC,IAAI,KAAK,yBAAyB;gBACxC,CAAC,CAAC,0BAA0B;gBAC5B,CAAC,CAAC,uBAAuB,EAC7B,QAAQ,EAAE,OAAO,EACjB,OAAO,EAAE,OAAO,CAAC,OAAO,IACrB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAC9D,CAAC;IACL,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAC5B,UAAmB,EACnB,OAA8B;IAE9B,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,GAAG,eAAe,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IACvE,IAAI,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC,EAAE,CAAC;QACpD,MAAM,IAAI,uBAAuB,CAAC,WAAW,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n type Contract,\n type ContractEvent,\n type ContractOperation,\n type JsonSchema,\n compatLine,\n connectionLevelsMismatch,\n declaredCredentialLevels,\n sealContract,\n validateAgainstSchema,\n verifyContract,\n} from '@ekanos/integration-schema';\n\nimport { synthesizeExample } from './synthesize-example';\nimport { toJsonSchema } from './to-json-schema';\nimport {\n ContractDerivationError,\n type ContractDiagnostic,\n type DeriveContractOptions,\n type DeriveContractResult,\n} from './types';\n\ntype Loose = Record<string, unknown>;\ntype Effect = 'read' | 'write';\ntype Sensitivity = 'public' | 'internal' | 'pii' | 'financial';\ntype Classification = { effect?: Effect; sensitivity?: Sensitivity };\n\nfunction isRecord(value: unknown): value is Loose {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction asRecordOf<T>(value: unknown): Record<string, T> {\n return isRecord(value) ? (value as Record<string, T>) : {};\n}\n\n/**\n * The contract's connection. `levels`: an explicit `connection.levels` wins;\n * else the levels the credentials declare (`oauth.level`,\n * `oauthConnections[id].level`, `activation.credentials[].level`); else, when\n * none states one, the old inference from `proposes`.\n */\nfunction inferConnection(definition: Loose): Contract['connection'] {\n const declared = isRecord(definition.connection) ? definition.connection : {};\n const oauth = isRecord(definition.oauth) ? definition.oauth : null;\n const provider = oauth && isRecord(oauth.provider) ? oauth.provider : null;\n\n const auth =\n (declared.auth as Contract['connection']['auth'] | undefined) ??\n (oauth ? 'oauth2' : 'none');\n const scopes =\n (declared.scopes as string[] | undefined) ??\n (provider && Array.isArray(provider.scopes)\n ? (provider.scopes as string[])\n : []);\n const levels =\n (declared.levels as Contract['connection']['levels'] | undefined) ??\n declaredCredentialLevels(definition);\n return { levels, auth, scopes };\n}\n\nfunction opaqueReasonFor(\n input: { opaque: boolean; reason?: string },\n output: { opaque: boolean; reason?: string },\n): string | undefined {\n const parts: string[] = [];\n if (input.opaque) parts.push(`input: ${input.reason ?? 'opaque'}`);\n if (output.opaque) parts.push(`output: ${output.reason ?? 'opaque'}`);\n return parts.length > 0 ? parts.join('; ') : undefined;\n}\n\n/**\n * Derive and seal the contract artifact from a `defineIntegration` result.\n * Non-throwing: returns diagnostics beside the contract (a contract that\n * fails its own `verifyContract` is reported as error diagnostics).\n */\nexport function analyzeContract(\n rawDefinition: unknown,\n options: DeriveContractOptions,\n): DeriveContractResult {\n const definition = isRecord(rawDefinition) ? rawDefinition : {};\n const diagnostics: ContractDiagnostic[] = [];\n const line = compatLine(options.contractVersion);\n const slug = String(definition.slug ?? '');\n const proposes = isRecord(definition.proposes) ? definition.proposes : {};\n const toolClassifications = asRecordOf<Classification>(proposes.tools);\n const actionClassifications = asRecordOf<Classification>(proposes.actions);\n const previousSince = new Map(\n (options.previous?.operations ?? []).map((op) => [op.id, op.since]),\n );\n\n const classify = (\n key: string,\n declared: Classification,\n proposed: Classification | undefined,\n ): { effect: Effect; sensitivity: Sensitivity } => {\n const effect = declared.effect ?? proposed?.effect;\n if (!effect) {\n diagnostics.push({\n rule: 'contract/effect-undeclared',\n severity: 'warn',\n operation: key,\n message: 'no effect declared; treated as a write (fail safe).',\n });\n }\n return {\n effect: effect ?? 'write',\n sensitivity: declared.sensitivity ?? proposed?.sensitivity ?? 'internal',\n };\n };\n\n const build = (\n kind: 'tool' | 'action',\n name: string,\n parts: {\n description: unknown;\n input: { schema: JsonSchema; opaque: boolean; reason?: string };\n outputSchema: unknown;\n authoredExample: unknown;\n classification: { effect: Effect; sensitivity: Sensitivity };\n },\n ): ContractOperation => {\n const key = `${kind}/${name}`;\n const id = `${slug}@${line}/${kind}/${name}`;\n if (\n typeof parts.description !== 'string' ||\n parts.description.length === 0\n ) {\n diagnostics.push({\n rule: 'contract/description-missing',\n severity: 'error',\n operation: key,\n message: 'a description is required.',\n });\n }\n\n let output: { schema: JsonSchema; opaque: boolean; reason?: string };\n if (parts.outputSchema === undefined) {\n output = {\n schema: {},\n opaque: true,\n reason: `the ${kind} declares no runtime output schema`,\n };\n diagnostics.push({\n rule: 'contract/output-schema-missing',\n severity: options.requireOutputSchemas ? 'error' : 'warn',\n operation: key,\n message: `no output schema; the output is opaque and an experience cannot bind to ${key}. Declare ${kind === 'tool' ? '`output`' : '`output`'} as a zod schema.`,\n });\n } else {\n output = toJsonSchema(parts.outputSchema, 'output');\n if (output.opaque) {\n diagnostics.push({\n rule: 'contract/output-opaque',\n severity: options.requireOutputSchemas ? 'error' : 'warn',\n operation: key,\n message: `output is opaque: ${output.reason}.`,\n });\n }\n }\n if (parts.input.opaque) {\n diagnostics.push({\n rule: 'contract/input-opaque',\n severity: 'warn',\n operation: key,\n message: `input is opaque: ${parts.input.reason}.`,\n });\n }\n\n let outputExample: unknown =\n parts.authoredExample ?? options.examples?.[key];\n if (outputExample === undefined && !output.opaque) {\n if (parts.classification.effect === 'read') {\n diagnostics.push({\n rule: 'contract/example-missing',\n severity: 'error',\n operation: key,\n message:\n 'a read operation needs an outputExample (author one or run `ekanos contract --record`).',\n });\n } else {\n outputExample = synthesizeExample(output.schema);\n diagnostics.push({\n rule: 'contract/example-synthesized',\n severity: 'warn',\n operation: key,\n message:\n 'no outputExample; a placeholder was synthesized from the schema.',\n });\n }\n }\n if (outputExample !== undefined && !output.opaque) {\n const problems = validateAgainstSchema(output.schema, outputExample);\n if (problems.length > 0) {\n diagnostics.push({\n rule: 'contract/example-invalid',\n severity: 'error',\n operation: key,\n message: `outputExample does not satisfy output: ${problems[0]}`,\n });\n }\n }\n\n const reason = opaqueReasonFor(parts.input, output);\n const since = previousSince.get(id) ?? options.packageVersion;\n return {\n id,\n kind,\n name,\n description:\n typeof parts.description === 'string' ? parts.description : '',\n effect: parts.classification.effect,\n sensitivity: parts.classification.sensitivity,\n input: parts.input.schema,\n output: output.schema,\n opaque: { input: parts.input.opaque, output: output.opaque },\n ...(reason ? { opaqueReason: reason } : {}),\n ...(outputExample !== undefined && !output.opaque\n ? { outputExample }\n : {}),\n since,\n } as ContractOperation;\n };\n\n const operations: ContractOperation[] = [];\n\n for (const [name, raw] of Object.entries(\n asRecordOf<Loose>(definition.actions),\n )) {\n const input = toJsonSchema(raw.input, 'input');\n operations.push(\n build('action', name, {\n description: raw.description,\n input,\n outputSchema: raw.output,\n authoredExample: raw.outputExample,\n classification: classify(\n `action/${name}`,\n {\n effect: raw.effect as Effect | undefined,\n sensitivity: raw.sensitivity as Sensitivity | undefined,\n },\n actionClassifications[name],\n ),\n }),\n );\n }\n\n const tools = Array.isArray(definition.tools)\n ? (definition.tools as Loose[])\n : [];\n for (const tool of tools) {\n const name = String(tool.name);\n const parameters = isRecord(tool.parameters)\n ? (tool.parameters as JsonSchema)\n : ({ type: 'object', properties: {} } as JsonSchema);\n operations.push(\n build('tool', name, {\n description: tool.description,\n input: { schema: parameters, opaque: false },\n outputSchema: tool.output,\n authoredExample: tool.outputExample,\n classification: classify(`tool/${name}`, {}, toolClassifications[name]),\n }),\n );\n }\n\n const events: ContractEvent[] = [];\n for (const raw of Array.isArray(definition.agentEvents)\n ? (definition.agentEvents as Loose[])\n : []) {\n const converted =\n raw.payloadSchema === undefined\n ? null\n : toJsonSchema(raw.payloadSchema, 'output');\n if (!converted || converted.opaque) {\n diagnostics.push({\n rule: 'contract/event-schema-missing',\n severity: 'warn',\n operation: String(raw.id),\n message: `event payload is opaque${converted?.reason ? `: ${converted.reason}` : ''}.`,\n });\n }\n events.push({\n name: String(raw.id),\n payload: converted?.schema ?? {},\n opaque: converted?.opaque ?? true,\n ...(raw.examplePayload !== undefined\n ? { payloadExample: raw.examplePayload }\n : {}),\n });\n }\n\n const levelsMismatch = connectionLevelsMismatch(definition);\n if (levelsMismatch) {\n diagnostics.push({\n rule: 'contract/levels-mismatch',\n severity: 'warn',\n message: `connection.levels [${levelsMismatch.explicit.join(', ')}] disagrees with the levels the credentials declare [${levelsMismatch.declared.join(', ')}]; the contract states connection.levels. Remove it to derive the levels from the credentials, or make the two agree.`,\n });\n }\n\n const contract = sealContract({\n schemaVersion: 1,\n integration: slug,\n packageVersion: options.packageVersion,\n contractVersion: options.contractVersion,\n compatLine: line,\n connection: inferConnection(definition),\n ...(definition.health ? { health: true } : {}),\n operations,\n events,\n });\n\n const { problems } = verifyContract(contract);\n for (const problem of problems) {\n // Example problems were already reported with a friendlier rule.\n if (problem.rule === 'contract.output-example-invalid') continue;\n if (\n problem.rule === 'contract.output-example' &&\n diagnostics.some(\n (d) =>\n d.rule === 'contract/example-missing' &&\n d.operation === problem.operation?.replace(/^[^/]*\\//, ''),\n )\n ) {\n continue;\n }\n diagnostics.push({\n rule:\n problem.rule === 'contract.output-example'\n ? 'contract/example-missing'\n : 'contract/not-sealable',\n severity: 'error',\n message: problem.message,\n ...(problem.operation ? { operation: problem.operation } : {}),\n });\n }\n\n return { contract, diagnostics };\n}\n\n/**\n * `deriveContract(definition, { packageVersion, contractVersion, previous? })`:\n * the sealed `Contract`; throws `ContractDerivationError` when an error\n * diagnostic exists. Use `analyzeContract` to read warnings too.\n */\nexport function deriveContract(\n definition: unknown,\n options: DeriveContractOptions,\n): Contract {\n const { contract, diagnostics } = analyzeContract(definition, options);\n if (diagnostics.some((d) => d.severity === 'error')) {\n throw new ContractDerivationError(diagnostics);\n }\n return contract;\n}\n"]}
@@ -2,7 +2,7 @@ import type { Contract } from '@ekanos/integration-schema';
2
2
  export type DiagnosticSeverity = 'error' | 'warn' | 'info';
3
3
  /** One thing deriveContract noticed. Stable `rule` ids so gates can key on them. */
4
4
  export interface ContractDiagnostic {
5
- rule: 'contract/effect-undeclared' | 'contract/output-schema-missing' | 'contract/output-opaque' | 'contract/input-opaque' | 'contract/example-missing' | 'contract/example-synthesized' | 'contract/example-invalid' | 'contract/event-schema-missing' | 'contract/description-missing' | 'contract/not-sealable';
5
+ rule: 'contract/effect-undeclared' | 'contract/output-schema-missing' | 'contract/output-opaque' | 'contract/input-opaque' | 'contract/example-missing' | 'contract/example-synthesized' | 'contract/example-invalid' | 'contract/event-schema-missing' | 'contract/description-missing' | 'contract/levels-mismatch' | 'contract/not-sealable';
6
6
  severity: DiagnosticSeverity;
7
7
  message: string;
8
8
  /** `tool/<name>`, `action/<name>` or an event name. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/contract/types.ts"],"names":[],"mappings":"AAiDA,qFAAqF;AACrF,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAEhD,YAAY,WAAiC;QAC3C,KAAK,CACH,WAAW;aACR,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;aACrC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,CAAC;aAClE,IAAI,CAAC,IAAI,CAAC,CACd,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF","sourcesContent":["import type { Contract } from '@ekanos/integration-schema';\n\nexport type DiagnosticSeverity = 'error' | 'warn' | 'info';\n\n/** One thing deriveContract noticed. Stable `rule` ids so gates can key on them. */\nexport interface ContractDiagnostic {\n rule:\n | 'contract/effect-undeclared'\n | 'contract/output-schema-missing'\n | 'contract/output-opaque'\n | 'contract/input-opaque'\n | 'contract/example-missing'\n | 'contract/example-synthesized'\n | 'contract/example-invalid'\n | 'contract/event-schema-missing'\n | 'contract/description-missing'\n | 'contract/not-sealable';\n severity: DiagnosticSeverity;\n message: string;\n /** `tool/<name>`, `action/<name>` or an event name. */\n operation?: string;\n}\n\nexport interface DeriveContractOptions {\n /** The project's `package.json` version. */\n packageVersion: string;\n /** The authored `ekanos.json` `contract.version`. */\n contractVersion: string;\n /** The committed `contract.json`, to carry `since` forward. */\n previous?: Contract | null;\n /**\n * Recorded output examples keyed `tool/<name>` / `action/<name>`\n * (`contracts/examples/<kind>-<name>.json`). An authored `outputExample`\n * on the definition wins over these.\n */\n examples?: Readonly<Record<string, unknown>>;\n /**\n * Treat a missing output schema as an error rather than an opaque-output\n * warning. `ekanos contract` sets it for integrations an experience binds.\n */\n requireOutputSchemas?: boolean;\n}\n\nexport interface DeriveContractResult {\n /** Sealed. Present even when `diagnostics` hold errors (the unsealable case aside). */\n contract: Contract;\n diagnostics: ContractDiagnostic[];\n}\n\n/** Thrown by `deriveContract` when `analyzeContract` reports an error diagnostic. */\nexport class ContractDerivationError extends Error {\n readonly diagnostics: ContractDiagnostic[];\n constructor(diagnostics: ContractDiagnostic[]) {\n super(\n diagnostics\n .filter((d) => d.severity === 'error')\n .map((d) => `${d.operation ? `${d.operation}: ` : ''}${d.message}`)\n .join('\\n'),\n );\n this.name = 'ContractDerivationError';\n this.diagnostics = diagnostics;\n }\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/contract/types.ts"],"names":[],"mappings":"AAkDA,qFAAqF;AACrF,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAEhD,YAAY,WAAiC;QAC3C,KAAK,CACH,WAAW;aACR,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;aACrC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,CAAC;aAClE,IAAI,CAAC,IAAI,CAAC,CACd,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF","sourcesContent":["import type { Contract } from '@ekanos/integration-schema';\n\nexport type DiagnosticSeverity = 'error' | 'warn' | 'info';\n\n/** One thing deriveContract noticed. Stable `rule` ids so gates can key on them. */\nexport interface ContractDiagnostic {\n rule:\n | 'contract/effect-undeclared'\n | 'contract/output-schema-missing'\n | 'contract/output-opaque'\n | 'contract/input-opaque'\n | 'contract/example-missing'\n | 'contract/example-synthesized'\n | 'contract/example-invalid'\n | 'contract/event-schema-missing'\n | 'contract/description-missing'\n | 'contract/levels-mismatch'\n | 'contract/not-sealable';\n severity: DiagnosticSeverity;\n message: string;\n /** `tool/<name>`, `action/<name>` or an event name. */\n operation?: string;\n}\n\nexport interface DeriveContractOptions {\n /** The project's `package.json` version. */\n packageVersion: string;\n /** The authored `ekanos.json` `contract.version`. */\n contractVersion: string;\n /** The committed `contract.json`, to carry `since` forward. */\n previous?: Contract | null;\n /**\n * Recorded output examples keyed `tool/<name>` / `action/<name>`\n * (`contracts/examples/<kind>-<name>.json`). An authored `outputExample`\n * on the definition wins over these.\n */\n examples?: Readonly<Record<string, unknown>>;\n /**\n * Treat a missing output schema as an error rather than an opaque-output\n * warning. `ekanos contract` sets it for integrations an experience binds.\n */\n requireOutputSchemas?: boolean;\n}\n\nexport interface DeriveContractResult {\n /** Sealed. Present even when `diagnostics` hold errors (the unsealable case aside). */\n contract: Contract;\n diagnostics: ContractDiagnostic[];\n}\n\n/** Thrown by `deriveContract` when `analyzeContract` reports an error diagnostic. */\nexport class ContractDerivationError extends Error {\n readonly diagnostics: ContractDiagnostic[];\n constructor(diagnostics: ContractDiagnostic[]) {\n super(\n diagnostics\n .filter((d) => d.severity === 'error')\n .map((d) => `${d.operation ? `${d.operation}: ` : ''}${d.message}`)\n .join('\\n'),\n );\n this.name = 'ContractDerivationError';\n this.diagnostics = diagnostics;\n }\n}\n"]}
@@ -9,6 +9,31 @@ export declare function ExperienceRuntimeProvider(props: {
9
9
  export declare function useExperienceRuntime(): ExperienceRuntime;
10
10
  /** Integration metadata (provenance, run mode) for badges; never for branching logic. */
11
11
  export declare function useIntegrationInfo(): IntegrationInfo[];
12
+ /**
13
+ * The URL of one of this experience's own pages, by page `id`, for a widget
14
+ * header's "View all" link; null when the experience declares no such page or
15
+ * the runtime cannot say. The base path comes from the host or the harness,
16
+ * never from the experience.
17
+ *
18
+ * ```tsx
19
+ * const href = useExperiencePageHref('review');
20
+ * ```
21
+ */
22
+ export declare function useExperiencePageHref(page: string): string | null;
23
+ /**
24
+ * A callback that starts connecting one of this experience's integrations,
25
+ * for a not-connected state; null when the runtime cannot connect. Pair it
26
+ * with a `not_connected` refusal from `useOperation`:
27
+ *
28
+ * ```tsx
29
+ * const connect = useConnectIntegration('news');
30
+ * <Widget.Inactive reason="not-connected" action={connect ? { label: 'Connect', onClick: connect } : undefined} />
31
+ * ```
32
+ *
33
+ * `integration` is the name `ekanos.json` declares. In the host it opens the
34
+ * in-place connect frame; in the harness it opens the Connect tab.
35
+ */
36
+ export declare function useConnectIntegration(integration: string): (() => void) | null;
12
37
  export interface UseOperationOptions {
13
38
  enabled?: boolean;
14
39
  /** Milliseconds a result stays fresh. Default 30s. */
@@ -28,6 +53,57 @@ export interface UseOperationResult<T> {
28
53
  * a runtime refusal.
29
54
  */
30
55
  export declare function useOperation<S extends IntegrationName, K extends ReadOperationKey<S>>(integration: S, op: K, ...args: [...InputArgs<OperationInput<S, K>>, options?: UseOperationOptions]): UseOperationResult<OperationOutput<S, K>>;
56
+ export interface UseInfiniteOperationOptions<I, O, C extends string = 'cursor'> {
57
+ /**
58
+ * The operation's input without the cursor. The hook adds the cursor under
59
+ * {@link UseInfiniteOperationOptions.cursorParam} for every page after the
60
+ * first; the first page is requested without one.
61
+ */
62
+ input?: Omit<I, C>;
63
+ /**
64
+ * Read the next cursor off a page. Return `null` or `undefined` when there
65
+ * is no next page: `hasNextPage` is then false.
66
+ */
67
+ getNextCursor: (page: O) => string | null | undefined;
68
+ /** The input key that carries the cursor. Default `cursor`. */
69
+ cursorParam?: C;
70
+ enabled?: boolean;
71
+ /** Milliseconds a result stays fresh. Default 30s. */
72
+ staleTime?: number;
73
+ }
74
+ export interface UseInfiniteOperationResult<O> {
75
+ /** Every page fetched so far, in order. Flatten it yourself: `pages.flatMap(...)`. */
76
+ pages: O[];
77
+ error: OperationError | undefined;
78
+ /** True until the first page arrives. */
79
+ isPending: boolean;
80
+ isFetching: boolean;
81
+ isFetchingNextPage: boolean;
82
+ hasNextPage: boolean;
83
+ /** Fetches the page after the last one; a no-op without a next page. */
84
+ fetchNextPage: () => Promise<unknown>;
85
+ /** Refetches every loaded page from the first. */
86
+ refetch: () => Promise<unknown>;
87
+ }
88
+ /**
89
+ * Read a cursor-paginated operation one page at a time. Like
90
+ * {@link useOperation}, only READ operations type-check, and it goes through
91
+ * the same runtime on the `http` channel.
92
+ *
93
+ * ```tsx
94
+ * const posts = useInfiniteOperation('sanity', 'tool/list_posts', {
95
+ * input: { limit: 20 },
96
+ * getNextCursor: (page) => page.nextCursor,
97
+ * });
98
+ * const rows = posts.pages.flatMap((page) => page.posts);
99
+ * ```
100
+ *
101
+ * Under `ekanos dev` with fixtures, every call returns the same authored
102
+ * fixture whatever the cursor, so drive `hasNextPage` from the fixture's own
103
+ * cursor field: leave it out (or `null`) to see one page, or set it to see
104
+ * "Load more" and the same page again.
105
+ */
106
+ export declare function useInfiniteOperation<S extends IntegrationName, K extends ReadOperationKey<S>, C extends string = 'cursor'>(integration: S, op: K, options: UseInfiniteOperationOptions<OperationInput<S, K>, OperationOutput<S, K>, C>): UseInfiniteOperationResult<OperationOutput<S, K>>;
31
107
  export interface UseOperationMutationOptions {
32
108
  /**
33
109
  * What a successful write refreshes: this integration's reads (default), every
@@ -7,14 +7,17 @@ import { createContext, createElement, use } from 'react';
7
7
  * ```tsx
8
8
  * const headlines = useOperation('news', 'tool/get_headlines', { limit: 10 });
9
9
  * const save = useOperationMutation('news', 'tool/save_idea');
10
+ * const more = useInfiniteOperation('news', 'tool/list_ideas', { getNextCursor });
10
11
  * ```
11
12
  *
12
- * Both go through the {@link ExperienceRuntime} the host or the harness
13
+ * All three go through the {@link ExperienceRuntime} the host or the harness
13
14
  * supplies via {@link ExperienceRuntimeProvider}. They need a React Query
14
15
  * `QueryClientProvider` above them, as every `@ekanos/sdk/hooks` hook does.
15
16
  */
16
- import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
17
+ import { useInfiniteQuery, useMutation, useQuery, useQueryClient, } from '@tanstack/react-query';
18
+ import { duplicateSdkMessage, otherSdkInstances, registerSdkInstance, } from './sdk-instances.js';
17
19
  const RuntimeContext = createContext(null);
20
+ const THIS_INSTANCE = registerSdkInstance(RuntimeContext);
18
21
  export function ExperienceRuntimeProvider(props) {
19
22
  return createElement(RuntimeContext, { value: props.runtime }, props.children);
20
23
  }
@@ -22,6 +25,13 @@ export function ExperienceRuntimeProvider(props) {
22
25
  export function useExperienceRuntime() {
23
26
  const runtime = use(RuntimeContext);
24
27
  if (!runtime) {
28
+ const others = otherSdkInstances(THIS_INSTANCE);
29
+ if (others.length > 0) {
30
+ // `use` may run in a loop: it reads each other copy's context, which
31
+ // proves whether a provider from that copy sits above this component.
32
+ const foreignProvider = others.some((instance) => use(instance.context) !== null);
33
+ throw new Error(duplicateSdkMessage(THIS_INSTANCE, others, foreignProvider));
34
+ }
25
35
  throw new Error('useOperation needs an <ExperienceRuntimeProvider>. Under `ekanos dev` and in the host one is mounted for you; in a unit test wrap the widget in one.');
26
36
  }
27
37
  return runtime;
@@ -30,6 +40,43 @@ export function useExperienceRuntime() {
30
40
  export function useIntegrationInfo() {
31
41
  return useExperienceRuntime().integrations();
32
42
  }
43
+ /**
44
+ * The URL of one of this experience's own pages, by page `id`, for a widget
45
+ * header's "View all" link; null when the experience declares no such page or
46
+ * the runtime cannot say. The base path comes from the host or the harness,
47
+ * never from the experience.
48
+ *
49
+ * ```tsx
50
+ * const href = useExperiencePageHref('review');
51
+ * ```
52
+ */
53
+ export function useExperiencePageHref(page) {
54
+ var _a, _b;
55
+ var _c;
56
+ return (_c = (_b = (_a = useExperienceRuntime()).pageHref) === null || _b === void 0 ? void 0 : _b.call(_a, page)) !== null && _c !== void 0 ? _c : null;
57
+ }
58
+ /**
59
+ * A callback that starts connecting one of this experience's integrations,
60
+ * for a not-connected state; null when the runtime cannot connect. Pair it
61
+ * with a `not_connected` refusal from `useOperation`:
62
+ *
63
+ * ```tsx
64
+ * const connect = useConnectIntegration('news');
65
+ * <Widget.Inactive reason="not-connected" action={connect ? { label: 'Connect', onClick: connect } : undefined} />
66
+ * ```
67
+ *
68
+ * `integration` is the name `ekanos.json` declares. In the host it opens the
69
+ * in-place connect frame; in the harness it opens the Connect tab.
70
+ */
71
+ export function useConnectIntegration(integration) {
72
+ const runtime = useExperienceRuntime();
73
+ if (!runtime.connect)
74
+ return null;
75
+ return () => {
76
+ var _a;
77
+ (_a = runtime.connect) === null || _a === void 0 ? void 0 : _a.call(runtime, integration);
78
+ };
79
+ }
33
80
  /** A refused call surfaced through React Query: carries the typed refusal. */
34
81
  class OperationCallError extends Error {
35
82
  constructor(error) {
@@ -91,6 +138,60 @@ function splitArgs(args) {
91
138
  }
92
139
  return [args[0], undefined];
93
140
  }
141
+ /**
142
+ * Read a cursor-paginated operation one page at a time. Like
143
+ * {@link useOperation}, only READ operations type-check, and it goes through
144
+ * the same runtime on the `http` channel.
145
+ *
146
+ * ```tsx
147
+ * const posts = useInfiniteOperation('sanity', 'tool/list_posts', {
148
+ * input: { limit: 20 },
149
+ * getNextCursor: (page) => page.nextCursor,
150
+ * });
151
+ * const rows = posts.pages.flatMap((page) => page.posts);
152
+ * ```
153
+ *
154
+ * Under `ekanos dev` with fixtures, every call returns the same authored
155
+ * fixture whatever the cursor, so drive `hasNextPage` from the fixture's own
156
+ * cursor field: leave it out (or `null`) to see one page, or set it to see
157
+ * "Load more" and the same page again.
158
+ */
159
+ export function useInfiniteOperation(integration, op, options) {
160
+ var _a;
161
+ var _b, _c, _d, _e, _f;
162
+ const runtime = useExperienceRuntime();
163
+ const cursorParam = (_b = options.cursorParam) !== null && _b !== void 0 ? _b : 'cursor';
164
+ const input = (_c = options.input) !== null && _c !== void 0 ? _c : {};
165
+ const query = useInfiniteQuery({
166
+ queryKey: [QUERY_ROOT, integration, op, input, { cursorParam }, 'pages'],
167
+ enabled: (_d = options.enabled) !== null && _d !== void 0 ? _d : true,
168
+ staleTime: (_e = options.staleTime) !== null && _e !== void 0 ? _e : 30000,
169
+ queryFn: async ({ pageParam }) => {
170
+ const result = await runtime.call({
171
+ integration,
172
+ op,
173
+ input: pageParam === null ? input : Object.assign(Object.assign({}, input), { [cursorParam]: pageParam }),
174
+ channel: 'http',
175
+ });
176
+ if (!result.ok)
177
+ throw new OperationCallError(result);
178
+ return result.data;
179
+ },
180
+ initialPageParam: null,
181
+ getNextPageParam: (lastPage) => { var _a; return (_a = options.getNextCursor(lastPage)) !== null && _a !== void 0 ? _a : null; },
182
+ retry: false,
183
+ });
184
+ return {
185
+ pages: (_f = (_a = query.data) === null || _a === void 0 ? void 0 : _a.pages) !== null && _f !== void 0 ? _f : [],
186
+ error: query.error ? toOperationError(query.error) : undefined,
187
+ isPending: query.isPending,
188
+ isFetching: query.isFetching,
189
+ isFetchingNextPage: query.isFetchingNextPage,
190
+ hasNextPage: query.hasNextPage,
191
+ fetchNextPage: query.fetchNextPage,
192
+ refetch: query.refetch,
193
+ };
194
+ }
94
195
  /**
95
196
  * Run a WRITE operation, an `action/<name>` or a write `tool/<name>`, as the
96
197
  * person's own click: it runs directly, with their authority, and is audited.
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/experience/client.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAkB,aAAa,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE1E;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAkB9E,MAAM,cAAc,GAAG,aAAa,CAA2B,IAAI,CAAC,CAAC;AAErE,MAAM,UAAU,yBAAyB,CAAC,KAGzC;IACC,OAAO,aAAa,CAClB,cAAc,EACd,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,EACxB,KAAK,CAAC,QAAQ,CACf,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,oBAAoB;IAClC,MAAM,OAAO,GAAG,GAAG,CAAC,cAAc,CAAC,CAAC;IACpC,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,sJAAsJ,CACvJ,CAAC;IACJ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use } from 'react';\n\n/**\n * `@ekanos/sdk/experience/client` — the hooks an experience widget uses to\n * reach an integration.\n *\n * ```tsx\n * const headlines = useOperation('news', 'tool/get_headlines', { limit: 10 });\n * const save = useOperationMutation('news', 'tool/save_idea');\n * ```\n *\n * Both go through the {@link ExperienceRuntime} the host or the harness\n * supplies via {@link ExperienceRuntimeProvider}. They need a React Query\n * `QueryClientProvider` above them, as every `@ekanos/sdk/hooks` hook does.\n */\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport type {\n ApprovalToken,\n ExperienceRuntime,\n IntegrationInfo,\n} from './runtime';\nimport type {\n InputArgs,\n OperationError,\n OperationInput,\n OperationOutput,\n OperationResult,\n ReadOperationKey,\n IntegrationName,\n WriteOperationKey,\n} from './types';\n\nconst RuntimeContext = createContext<ExperienceRuntime | null>(null);\n\nexport function ExperienceRuntimeProvider(props: {\n runtime: ExperienceRuntime;\n children?: ReactNode;\n}) {\n return createElement(\n RuntimeContext,\n { value: props.runtime },\n props.children,\n );\n}\n\n/** The runtime from the nearest provider; throws a pointed error without one. */\nexport function useExperienceRuntime(): ExperienceRuntime {\n const runtime = use(RuntimeContext);\n if (!runtime) {\n throw new Error(\n 'useOperation needs an <ExperienceRuntimeProvider>. Under `ekanos dev` and in the host one is mounted for you; in a unit test wrap the widget in one.',\n );\n }\n\n return runtime;\n}\n\n/** Integration metadata (provenance, run mode) for badges; never for branching logic. */\nexport function useIntegrationInfo(): IntegrationInfo[] {\n return useExperienceRuntime().integrations();\n}\n\n/** A refused call surfaced through React Query: carries the typed refusal. */\nclass OperationCallError extends Error {\n readonly reason: OperationError['reason'];\n\n constructor(error: OperationError) {\n super(error.message);\n this.name = 'OperationCallError';\n this.reason = error.reason;\n }\n}\n\nfunction toOperationError(error: unknown): OperationError {\n if (error instanceof OperationCallError) {\n return { reason: error.reason, message: error.message };\n }\n\n return {\n reason: 'execution_failed',\n message: error instanceof Error ? error.message : 'The operation failed.',\n };\n}\n\nconst QUERY_ROOT = 'ekanos-operation';\n\nexport interface UseOperationOptions {\n enabled?: boolean;\n /** Milliseconds a result stays fresh. Default 30s. */\n staleTime?: number;\n refetchInterval?: number;\n}\n\nexport interface UseOperationResult<T> {\n data: T | undefined;\n error: OperationError | undefined;\n isPending: boolean;\n isFetching: boolean;\n refetch: () => Promise<unknown>;\n}\n\n/**\n * Read an operation. Only READ operations type-check here; a write is a\n * compile error (use {@link useOperationMutation}) and, if forced through,\n * a runtime refusal.\n */\nexport function useOperation<\n S extends IntegrationName,\n K extends ReadOperationKey<S>,\n>(\n integration: S,\n op: K,\n ...args: [...InputArgs<OperationInput<S, K>>, options?: UseOperationOptions]\n): UseOperationResult<OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const [input, options] = splitArgs(args);\n\n const query = useQuery({\n queryKey: [QUERY_ROOT, integration, op, input ?? null],\n enabled: options?.enabled ?? true,\n staleTime: options?.staleTime ?? 30_000,\n refetchInterval: options?.refetchInterval,\n queryFn: async () => {\n const result = await runtime.call({\n integration,\n op,\n input: input ?? {},\n channel: 'http',\n });\n if (!result.ok) throw new OperationCallError(result);\n\n return result.data as OperationOutput<S, K>;\n },\n retry: false,\n });\n\n return {\n data: query.data,\n error: query.error ? toOperationError(query.error) : undefined,\n isPending: query.isPending,\n isFetching: query.isFetching,\n refetch: query.refetch,\n };\n}\n\nfunction splitArgs(\n args: readonly unknown[],\n): [unknown, UseOperationOptions | undefined] {\n // `(input?, options?)`: options is recognisable as the trailing object with\n // an option key only when two args are given; one arg is always the input.\n if (args.length >= 2) {\n return [args[0], args[1] as UseOperationOptions | undefined];\n }\n\n return [args[0], undefined];\n}\n\nexport interface UseOperationMutationOptions {\n /**\n * What a successful write refreshes: this integration's reads (default), every\n * operation query, or nothing.\n */\n invalidate?: 'integration' | 'all' | false;\n}\n\nexport interface MutateOptions {\n /** A token a runtime minted earlier; normally absent, a person's click needs none. */\n approval?: ApprovalToken;\n}\n\nexport interface UseOperationMutationResult<I, O> {\n /** Resolves with the typed result; a refusal is `{ ok: false, reason }`, never a throw. */\n mutate: (input: I, options?: MutateOptions) => Promise<OperationResult<O>>;\n isPending: boolean;\n data: OperationResult<O> | undefined;\n reset: () => void;\n}\n\n/**\n * Run a WRITE operation, an `action/<name>` or a write `tool/<name>`, as the\n * person's own click: it runs directly, with their authority, and is audited.\n * To ask for a second click, make the operation's input require\n * `confirmed: z.literal(true)`; the runtime asks the person and the promise\n * resolves once they answer (`write_not_approved` when they cancel). Workflows\n * and agents do not use this path; they go through their own approval gate.\n */\nexport function useOperationMutation<\n S extends IntegrationName,\n K extends WriteOperationKey<S>,\n>(\n integration: S,\n op: K,\n options?: UseOperationMutationOptions,\n): UseOperationMutationResult<OperationInput<S, K>, OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const queryClient = useQueryClient();\n const invalidate = options?.invalidate ?? 'integration';\n\n const mutation = useMutation({\n mutationFn: async (variables: {\n input: unknown;\n approval?: ApprovalToken;\n }) =>\n runtime.call({\n integration,\n op,\n input: variables.input,\n channel: 'interactive',\n ...(variables.approval ? { approval: variables.approval } : {}),\n }),\n onSuccess: async (result) => {\n if (!result.ok || invalidate === false) return;\n await queryClient.invalidateQueries({\n queryKey:\n invalidate === 'all' ? [QUERY_ROOT] : [QUERY_ROOT, integration],\n });\n },\n });\n\n return {\n mutate: async (input, mutateOptions) =>\n (await mutation.mutateAsync({\n input,\n ...(mutateOptions?.approval\n ? { approval: mutateOptions.approval }\n : {}),\n })) as OperationResult<OperationOutput<S, K>>,\n isPending: mutation.isPending,\n data: mutation.data as OperationResult<OperationOutput<S, K>> | undefined,\n reset: mutation.reset,\n };\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/experience/client.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAkB,aAAa,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE1E;;;;;;;;;;;;;GAaG;AACH,OAAO,EACL,gBAAgB,EAChB,W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CAAC,CAAC,CAAC,UAAU,EAAE,WAAW,CAAC;aAClE,CAAC,CAAC;QACL,CAAC;KACF,CAAC,CAAC;IAEH,OAAO;QACL,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CACrC,CAAC,MAAM,QAAQ,CAAC,WAAW,iBACzB,KAAK,IACF,CAAC,CAAA,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,QAAQ;YACzB,CAAC,CAAC,EAAE,QAAQ,EAAE,aAAa,CAAC,QAAQ,EAAE;YACtC,CAAC,CAAC,EAAE,CAAC,EACP,CAA2C;QAC/C,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,IAAI,EAAE,QAAQ,CAAC,IAA0D;QACzE,KAAK,EAAE,QAAQ,CAAC,KAAK;KACtB,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport { type ReactNode, createContext, createElement, use } from 'react';\n\n/**\n * `@ekanos/sdk/experience/client` — the hooks an experience widget uses to\n * reach an integration.\n *\n * ```tsx\n * const headlines = useOperation('news', 'tool/get_headlines', { limit: 10 });\n * const save = useOperationMutation('news', 'tool/save_idea');\n * const more = useInfiniteOperation('news', 'tool/list_ideas', { getNextCursor });\n * ```\n *\n * All three go through the {@link ExperienceRuntime} the host or the harness\n * supplies via {@link ExperienceRuntimeProvider}. They need a React Query\n * `QueryClientProvider` above them, as every `@ekanos/sdk/hooks` hook does.\n */\nimport {\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n} from '@tanstack/react-query';\n\nimport type {\n ApprovalToken,\n ExperienceRuntime,\n IntegrationInfo,\n} from './runtime';\nimport {\n duplicateSdkMessage,\n otherSdkInstances,\n registerSdkInstance,\n} from './sdk-instances';\nimport type {\n InputArgs,\n OperationError,\n OperationInput,\n OperationOutput,\n OperationResult,\n ReadOperationKey,\n IntegrationName,\n WriteOperationKey,\n} from './types';\n\nconst RuntimeContext = createContext<ExperienceRuntime | null>(null);\n\nconst THIS_INSTANCE = registerSdkInstance(RuntimeContext);\n\nexport function ExperienceRuntimeProvider(props: {\n runtime: ExperienceRuntime;\n children?: ReactNode;\n}) {\n return createElement(\n RuntimeContext,\n { value: props.runtime },\n props.children,\n );\n}\n\n/** The runtime from the nearest provider; throws a pointed error without one. */\nexport function useExperienceRuntime(): ExperienceRuntime {\n const runtime = use(RuntimeContext);\n if (!runtime) {\n const others = otherSdkInstances(THIS_INSTANCE);\n if (others.length > 0) {\n // `use` may run in a loop: it reads each other copy's context, which\n // proves whether a provider from that copy sits above this component.\n const foreignProvider = others.some(\n (instance) => use(instance.context) !== null,\n );\n throw new Error(\n duplicateSdkMessage(THIS_INSTANCE, others, foreignProvider),\n );\n }\n throw new Error(\n 'useOperation needs an <ExperienceRuntimeProvider>. Under `ekanos dev` and in the host one is mounted for you; in a unit test wrap the widget in one.',\n );\n }\n\n return runtime;\n}\n\n/** Integration metadata (provenance, run mode) for badges; never for branching logic. */\nexport function useIntegrationInfo(): IntegrationInfo[] {\n return useExperienceRuntime().integrations();\n}\n\n/**\n * The URL of one of this experience's own pages, by page `id`, for a widget\n * header's \"View all\" link; null when the experience declares no such page or\n * the runtime cannot say. The base path comes from the host or the harness,\n * never from the experience.\n *\n * ```tsx\n * const href = useExperiencePageHref('review');\n * ```\n */\nexport function useExperiencePageHref(page: string): string | null {\n return useExperienceRuntime().pageHref?.(page) ?? null;\n}\n\n/**\n * A callback that starts connecting one of this experience's integrations,\n * for a not-connected state; null when the runtime cannot connect. Pair it\n * with a `not_connected` refusal from `useOperation`:\n *\n * ```tsx\n * const connect = useConnectIntegration('news');\n * <Widget.Inactive reason=\"not-connected\" action={connect ? { label: 'Connect', onClick: connect } : undefined} />\n * ```\n *\n * `integration` is the name `ekanos.json` declares. In the host it opens the\n * in-place connect frame; in the harness it opens the Connect tab.\n */\nexport function useConnectIntegration(\n integration: string,\n): (() => void) | null {\n const runtime = useExperienceRuntime();\n\n if (!runtime.connect) return null;\n\n return () => {\n runtime.connect?.(integration);\n };\n}\n\n/** A refused call surfaced through React Query: carries the typed refusal. */\nclass OperationCallError extends Error {\n readonly reason: OperationError['reason'];\n\n constructor(error: OperationError) {\n super(error.message);\n this.name = 'OperationCallError';\n this.reason = error.reason;\n }\n}\n\nfunction toOperationError(error: unknown): OperationError {\n if (error instanceof OperationCallError) {\n return { reason: error.reason, message: error.message };\n }\n\n return {\n reason: 'execution_failed',\n message: error instanceof Error ? error.message : 'The operation failed.',\n };\n}\n\nconst QUERY_ROOT = 'ekanos-operation';\n\nexport interface UseOperationOptions {\n enabled?: boolean;\n /** Milliseconds a result stays fresh. Default 30s. */\n staleTime?: number;\n refetchInterval?: number;\n}\n\nexport interface UseOperationResult<T> {\n data: T | undefined;\n error: OperationError | undefined;\n isPending: boolean;\n isFetching: boolean;\n refetch: () => Promise<unknown>;\n}\n\n/**\n * Read an operation. Only READ operations type-check here; a write is a\n * compile error (use {@link useOperationMutation}) and, if forced through,\n * a runtime refusal.\n */\nexport function useOperation<\n S extends IntegrationName,\n K extends ReadOperationKey<S>,\n>(\n integration: S,\n op: K,\n ...args: [...InputArgs<OperationInput<S, K>>, options?: UseOperationOptions]\n): UseOperationResult<OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const [input, options] = splitArgs(args);\n\n const query = useQuery({\n queryKey: [QUERY_ROOT, integration, op, input ?? null],\n enabled: options?.enabled ?? true,\n staleTime: options?.staleTime ?? 30_000,\n refetchInterval: options?.refetchInterval,\n queryFn: async () => {\n const result = await runtime.call({\n integration,\n op,\n input: input ?? {},\n channel: 'http',\n });\n if (!result.ok) throw new OperationCallError(result);\n\n return result.data as OperationOutput<S, K>;\n },\n retry: false,\n });\n\n return {\n data: query.data,\n error: query.error ? toOperationError(query.error) : undefined,\n isPending: query.isPending,\n isFetching: query.isFetching,\n refetch: query.refetch,\n };\n}\n\nfunction splitArgs(\n args: readonly unknown[],\n): [unknown, UseOperationOptions | undefined] {\n // `(input?, options?)`: options is recognisable as the trailing object with\n // an option key only when two args are given; one arg is always the input.\n if (args.length >= 2) {\n return [args[0], args[1] as UseOperationOptions | undefined];\n }\n\n return [args[0], undefined];\n}\n\nexport interface UseInfiniteOperationOptions<\n I,\n O,\n C extends string = 'cursor',\n> {\n /**\n * The operation's input without the cursor. The hook adds the cursor under\n * {@link UseInfiniteOperationOptions.cursorParam} for every page after the\n * first; the first page is requested without one.\n */\n input?: Omit<I, C>;\n /**\n * Read the next cursor off a page. Return `null` or `undefined` when there\n * is no next page: `hasNextPage` is then false.\n */\n getNextCursor: (page: O) => string | null | undefined;\n /** The input key that carries the cursor. Default `cursor`. */\n cursorParam?: C;\n enabled?: boolean;\n /** Milliseconds a result stays fresh. Default 30s. */\n staleTime?: number;\n}\n\nexport interface UseInfiniteOperationResult<O> {\n /** Every page fetched so far, in order. Flatten it yourself: `pages.flatMap(...)`. */\n pages: O[];\n error: OperationError | undefined;\n /** True until the first page arrives. */\n isPending: boolean;\n isFetching: boolean;\n isFetchingNextPage: boolean;\n hasNextPage: boolean;\n /** Fetches the page after the last one; a no-op without a next page. */\n fetchNextPage: () => Promise<unknown>;\n /** Refetches every loaded page from the first. */\n refetch: () => Promise<unknown>;\n}\n\n/**\n * Read a cursor-paginated operation one page at a time. Like\n * {@link useOperation}, only READ operations type-check, and it goes through\n * the same runtime on the `http` channel.\n *\n * ```tsx\n * const posts = useInfiniteOperation('sanity', 'tool/list_posts', {\n * input: { limit: 20 },\n * getNextCursor: (page) => page.nextCursor,\n * });\n * const rows = posts.pages.flatMap((page) => page.posts);\n * ```\n *\n * Under `ekanos dev` with fixtures, every call returns the same authored\n * fixture whatever the cursor, so drive `hasNextPage` from the fixture's own\n * cursor field: leave it out (or `null`) to see one page, or set it to see\n * \"Load more\" and the same page again.\n */\nexport function useInfiniteOperation<\n S extends IntegrationName,\n K extends ReadOperationKey<S>,\n C extends string = 'cursor',\n>(\n integration: S,\n op: K,\n options: UseInfiniteOperationOptions<\n OperationInput<S, K>,\n OperationOutput<S, K>,\n C\n >,\n): UseInfiniteOperationResult<OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const cursorParam: string = options.cursorParam ?? 'cursor';\n const input = options.input ?? {};\n\n const query = useInfiniteQuery({\n queryKey: [QUERY_ROOT, integration, op, input, { cursorParam }, 'pages'],\n enabled: options.enabled ?? true,\n staleTime: options.staleTime ?? 30_000,\n queryFn: async ({ pageParam }) => {\n const result = await runtime.call({\n integration,\n op,\n input:\n pageParam === null ? input : { ...input, [cursorParam]: pageParam },\n channel: 'http',\n });\n if (!result.ok) throw new OperationCallError(result);\n\n return result.data as OperationOutput<S, K>;\n },\n initialPageParam: null as string | null,\n getNextPageParam: (lastPage: OperationOutput<S, K>) =>\n options.getNextCursor(lastPage) ?? null,\n retry: false,\n });\n\n return {\n pages: query.data?.pages ?? [],\n error: query.error ? toOperationError(query.error) : undefined,\n isPending: query.isPending,\n isFetching: query.isFetching,\n isFetchingNextPage: query.isFetchingNextPage,\n hasNextPage: query.hasNextPage,\n fetchNextPage: query.fetchNextPage,\n refetch: query.refetch,\n };\n}\n\nexport interface UseOperationMutationOptions {\n /**\n * What a successful write refreshes: this integration's reads (default), every\n * operation query, or nothing.\n */\n invalidate?: 'integration' | 'all' | false;\n}\n\nexport interface MutateOptions {\n /** A token a runtime minted earlier; normally absent, a person's click needs none. */\n approval?: ApprovalToken;\n}\n\nexport interface UseOperationMutationResult<I, O> {\n /** Resolves with the typed result; a refusal is `{ ok: false, reason }`, never a throw. */\n mutate: (input: I, options?: MutateOptions) => Promise<OperationResult<O>>;\n isPending: boolean;\n data: OperationResult<O> | undefined;\n reset: () => void;\n}\n\n/**\n * Run a WRITE operation, an `action/<name>` or a write `tool/<name>`, as the\n * person's own click: it runs directly, with their authority, and is audited.\n * To ask for a second click, make the operation's input require\n * `confirmed: z.literal(true)`; the runtime asks the person and the promise\n * resolves once they answer (`write_not_approved` when they cancel). Workflows\n * and agents do not use this path; they go through their own approval gate.\n */\nexport function useOperationMutation<\n S extends IntegrationName,\n K extends WriteOperationKey<S>,\n>(\n integration: S,\n op: K,\n options?: UseOperationMutationOptions,\n): UseOperationMutationResult<OperationInput<S, K>, OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const queryClient = useQueryClient();\n const invalidate = options?.invalidate ?? 'integration';\n\n const mutation = useMutation({\n mutationFn: async (variables: {\n input: unknown;\n approval?: ApprovalToken;\n }) =>\n runtime.call({\n integration,\n op,\n input: variables.input,\n channel: 'interactive',\n ...(variables.approval ? { approval: variables.approval } : {}),\n }),\n onSuccess: async (result) => {\n if (!result.ok || invalidate === false) return;\n await queryClient.invalidateQueries({\n queryKey:\n invalidate === 'all' ? [QUERY_ROOT] : [QUERY_ROOT, integration],\n });\n },\n });\n\n return {\n mutate: async (input, mutateOptions) =>\n (await mutation.mutateAsync({\n input,\n ...(mutateOptions?.approval\n ? { approval: mutateOptions.approval }\n : {}),\n })) as OperationResult<OperationOutput<S, K>>,\n isPending: mutation.isPending,\n data: mutation.data as OperationResult<OperationOutput<S, K>> | undefined,\n reset: mutation.reset,\n };\n}\n"]}
@@ -59,4 +59,20 @@ export interface ExperienceRuntime {
59
59
  */
60
60
  call(request: OperationCallRequest): Promise<OperationResult<unknown>>;
61
61
  integrations(): IntegrationInfo[];
62
+ /**
63
+ * The URL of one of this experience's own pages, by page `id`, or null when
64
+ * the experience declares no such page. The host and the harness each know
65
+ * their own base path; an experience never builds one. Optional so an older
66
+ * runtime still satisfies the interface: `useExperiencePageHref` answers
67
+ * null when it is absent.
68
+ */
69
+ pageHref?(page: string): string | null;
70
+ /**
71
+ * Start connecting one of this experience's integrations, by the name
72
+ * `ekanos.json` declares. The host opens its in-place connect frame; the
73
+ * harness opens its Connect tab. Returns false when the integration is not
74
+ * one of this experience's. Optional: `useConnectIntegration` answers null
75
+ * when it is absent.
76
+ */
77
+ connect?(integration: string): boolean;
62
78
  }
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/experience/runtime.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,yBAAyB,GAI1B,MAAM,SAAS,CAAC","sourcesContent":["/**\n * `@ekanos/sdk/experience/runtime` — the ONE seam between an experience and\n * an integration.\n *\n * An experience calls operations through an {@link ExperienceRuntime} and\n * through nothing else: no import of integration code, no `fetch` to an\n * integration route. The local harness implements it over its own\n * `/__ekanos/api/ops/run`; the host implements it over its experience route,\n * `/api/experiences/<experience>/slots/…?account=<team>`, with the team's own\n * connection to each integration (no install). Both answer with the same {@link OperationResult} and the same\n * refusal reasons, so an experience behaves identically in either.\n *\n * Isomorphic and dependency-free: types only (plus the re-exports below).\n */\nimport type { OperationResult } from '@ekanos/integration-schema';\n\nexport {\n OPERATION_REFUSAL_REASONS,\n type OperationError,\n type OperationRefusalReason,\n type OperationResult,\n} from './types';\n\n/**\n * The channel a call arrives on; writes are judged by it. `http` and `rsc` are\n * reads (a write there is `write_refused_on_channel`). `interactive` is a\n * person's own click in a widget or page: `useOperationMutation` uses it, and\n * the write runs directly. `workflow` writes sit behind the workflow's\n * approval step.\n */\nexport type OperationChannel = 'http' | 'rsc' | 'workflow' | 'interactive';\n\n/**\n * Proof that a person approved one write. Opaque to the experience. A widget\n * or page write does not need one: the person's click is the authorization.\n * Kept for runtimes that mint a token for a held write.\n */\nexport interface ApprovalToken {\n readonly id: string;\n}\n\nexport interface OperationCallRequest {\n /** The integration name from `ekanos.json` `integrations` (its slug). */\n integration: string;\n /** `tool/<name>` or `action/<name>`. The version is the one `ekanos.json` pins. */\n op: string;\n input: unknown;\n channel: OperationChannel;\n approval?: ApprovalToken;\n}\n\nexport type IntegrationProvenance = 'registry' | 'local';\n\n/** What a runtime can say about an integration (for UI badges, never for widgets' logic). */\nexport interface IntegrationInfo {\n name: string;\n version: string;\n provenance: IntegrationProvenance;\n bindingMode?: string;\n runMode?: 'fixtures' | 'live';\n}\n\nexport interface ExperienceRuntime {\n /**\n * Run one operation. A write on `interactive` runs directly; if the\n * operation requires `confirmed: z.literal(true)` in its input, the runtime\n * asks the person first, so the call may take as long as they take to answer\n * (`write_not_approved` when they cancel). Never throws for a\n * refusal: those are `{ ok: false, reason }`. A rejected promise means the\n * runtime itself is broken.\n */\n call(request: OperationCallRequest): Promise<OperationResult<unknown>>;\n integrations(): IntegrationInfo[];\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/experience/runtime.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,yBAAyB,GAI1B,MAAM,SAAS,CAAC","sourcesContent":["/**\n * `@ekanos/sdk/experience/runtime` — the ONE seam between an experience and\n * an integration.\n *\n * An experience calls operations through an {@link ExperienceRuntime} and\n * through nothing else: no import of integration code, no `fetch` to an\n * integration route. The local harness implements it over its own\n * `/__ekanos/api/ops/run`; the host implements it over its experience route,\n * `/api/experiences/<experience>/slots/…?account=<team>`, with the team's own\n * connection to each integration (no install). Both answer with the same {@link OperationResult} and the same\n * refusal reasons, so an experience behaves identically in either.\n *\n * Isomorphic and dependency-free: types only (plus the re-exports below).\n */\nimport type { OperationResult } from '@ekanos/integration-schema';\n\nexport {\n OPERATION_REFUSAL_REASONS,\n type OperationError,\n type OperationRefusalReason,\n type OperationResult,\n} from './types';\n\n/**\n * The channel a call arrives on; writes are judged by it. `http` and `rsc` are\n * reads (a write there is `write_refused_on_channel`). `interactive` is a\n * person's own click in a widget or page: `useOperationMutation` uses it, and\n * the write runs directly. `workflow` writes sit behind the workflow's\n * approval step.\n */\nexport type OperationChannel = 'http' | 'rsc' | 'workflow' | 'interactive';\n\n/**\n * Proof that a person approved one write. Opaque to the experience. A widget\n * or page write does not need one: the person's click is the authorization.\n * Kept for runtimes that mint a token for a held write.\n */\nexport interface ApprovalToken {\n readonly id: string;\n}\n\nexport interface OperationCallRequest {\n /** The integration name from `ekanos.json` `integrations` (its slug). */\n integration: string;\n /** `tool/<name>` or `action/<name>`. The version is the one `ekanos.json` pins. */\n op: string;\n input: unknown;\n channel: OperationChannel;\n approval?: ApprovalToken;\n}\n\nexport type IntegrationProvenance = 'registry' | 'local';\n\n/** What a runtime can say about an integration (for UI badges, never for widgets' logic). */\nexport interface IntegrationInfo {\n name: string;\n version: string;\n provenance: IntegrationProvenance;\n bindingMode?: string;\n runMode?: 'fixtures' | 'live';\n}\n\nexport interface ExperienceRuntime {\n /**\n * Run one operation. A write on `interactive` runs directly; if the\n * operation requires `confirmed: z.literal(true)` in its input, the runtime\n * asks the person first, so the call may take as long as they take to answer\n * (`write_not_approved` when they cancel). Never throws for a\n * refusal: those are `{ ok: false, reason }`. A rejected promise means the\n * runtime itself is broken.\n */\n call(request: OperationCallRequest): Promise<OperationResult<unknown>>;\n integrations(): IntegrationInfo[];\n /**\n * The URL of one of this experience's own pages, by page `id`, or null when\n * the experience declares no such page. The host and the harness each know\n * their own base path; an experience never builds one. Optional so an older\n * runtime still satisfies the interface: `useExperiencePageHref` answers\n * null when it is absent.\n */\n pageHref?(page: string): string | null;\n /**\n * Start connecting one of this experience's integrations, by the name\n * `ekanos.json` declares. The host opens its in-place connect frame; the\n * harness opens its Connect tab. Returns false when the integration is not\n * one of this experience's. Optional: `useConnectIntegration` answers null\n * when it is absent.\n */\n connect?(integration: string): boolean;\n}\n"]}
@@ -0,0 +1,11 @@
1
+ import type { Context } from 'react';
2
+ import type { ExperienceRuntime } from './runtime.js';
3
+ export interface SdkInstance {
4
+ version: string;
5
+ /** This copy's context object: the identity of the instance. */
6
+ context: Context<ExperienceRuntime | null>;
7
+ }
8
+ export declare function registerSdkInstance(context: Context<ExperienceRuntime | null>): SdkInstance;
9
+ /** Every registered copy other than `self`. */
10
+ export declare function otherSdkInstances(self: SdkInstance): SdkInstance[];
11
+ export declare function duplicateSdkMessage(self: SdkInstance, others: readonly SdkInstance[], foreignProvider: boolean): string;
@@ -0,0 +1,47 @@
1
+ import { SDK_VERSION } from '../version.js';
2
+ /**
3
+ * Every evaluated copy of `@ekanos/sdk/experience/client` in this JavaScript
4
+ * realm, so a missing provider can be told apart from a provider mounted by a
5
+ * different copy of the SDK.
6
+ *
7
+ * Two copies happen when a package manager resolves `@ekanos/sdk` more than
8
+ * once — under pnpm, one variant per `zod` it is peered with. The harness then
9
+ * mounts its provider from one copy while the experience's hooks read the
10
+ * other's context: a different object, so the hook sees no provider at all.
11
+ *
12
+ * Nothing here runs for its side effect alone: `client.tsx` calls
13
+ * {@link registerSdkInstance} at module top level, and that module is always
14
+ * evaluated when a hook from it is used, so the narrow `sideEffects` list
15
+ * cannot drop the registration.
16
+ */
17
+ const REGISTRY_KEY = Symbol.for('ekanos.sdk.instances');
18
+ function registry() {
19
+ var _a;
20
+ const holder = globalThis;
21
+ (_a = holder[REGISTRY_KEY]) !== null && _a !== void 0 ? _a : (holder[REGISTRY_KEY] = new Set());
22
+ return holder[REGISTRY_KEY];
23
+ }
24
+ export function registerSdkInstance(context) {
25
+ const instance = { version: SDK_VERSION, context };
26
+ registry().add(instance);
27
+ return instance;
28
+ }
29
+ /** Every registered copy other than `self`. */
30
+ export function otherSdkInstances(self) {
31
+ return [...registry()].filter((instance) => instance !== self);
32
+ }
33
+ export function duplicateSdkMessage(self, others, foreignProvider) {
34
+ const versions = [self, ...others]
35
+ .map((instance, index) => index === 0
36
+ ? `${instance.version} (this hook)`
37
+ : `${instance.version} (another copy)`)
38
+ .join(', ');
39
+ return (`useOperation found ${others.length + 1} copies of @ekanos/sdk loaded at once: ${versions}. ` +
40
+ (foreignProvider
41
+ ? 'An <ExperienceRuntimeProvider> IS mounted above this component, but from a different copy, so this copy cannot see it. '
42
+ : 'A provider mounted by one copy is invisible to hooks from another. ') +
43
+ 'This is a dependency-resolution problem, not a code problem: usually the workspace resolves zod at two versions and pnpm builds one @ekanos/sdk per zod. ' +
44
+ 'Run "pnpm why @ekanos/sdk" (or "npm ls @ekanos/sdk") to see both, then give every package the same zod range ' +
45
+ '(or pin one with "overrides": { "zod": "<one version>" } — "pnpm.overrides" in package.json, or "overrides" in pnpm-workspace.yaml) and reinstall.');
46
+ }
47
+ //# sourceMappingURL=sdk-instances.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file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QAC7F,CAAC,eAAe;YACd,CAAC,CAAC,yHAAyH;YAC3H,CAAC,CAAC,qEAAqE,CAAC;QAC1E,2JAA2J;QAC3J,+GAA+G;QAC/G,oJAAoJ,CACrJ,CAAC;AACJ,CAAC","sourcesContent":["import type { Context } from 'react';\n\nimport { SDK_VERSION } from '../version';\nimport type { ExperienceRuntime } from './runtime';\n\n/**\n * Every evaluated copy of `@ekanos/sdk/experience/client` in this JavaScript\n * realm, so a missing provider can be told apart from a provider mounted by a\n * different copy of the SDK.\n *\n * Two copies happen when a package manager resolves `@ekanos/sdk` more than\n * once — under pnpm, one variant per `zod` it is peered with. The harness then\n * mounts its provider from one copy while the experience's hooks read the\n * other's context: a different object, so the hook sees no provider at all.\n *\n * Nothing here runs for its side effect alone: `client.tsx` calls\n * {@link registerSdkInstance} at module top level, and that module is always\n * evaluated when a hook from it is used, so the narrow `sideEffects` list\n * cannot drop the registration.\n */\nconst REGISTRY_KEY = Symbol.for('ekanos.sdk.instances');\n\nexport interface SdkInstance {\n version: string;\n /** This copy's context object: the identity of the instance. */\n context: Context<ExperienceRuntime | null>;\n}\n\ntype Registry = Set<SdkInstance>;\n\nfunction registry(): Registry {\n const holder = globalThis as typeof globalThis & {\n [REGISTRY_KEY]?: Registry;\n };\n holder[REGISTRY_KEY] ??= new Set();\n\n return holder[REGISTRY_KEY];\n}\n\nexport function registerSdkInstance(\n context: Context<ExperienceRuntime | null>,\n): SdkInstance {\n const instance: SdkInstance = { version: SDK_VERSION, context };\n registry().add(instance);\n\n return instance;\n}\n\n/** Every registered copy other than `self`. */\nexport function otherSdkInstances(self: SdkInstance): SdkInstance[] {\n return [...registry()].filter((instance) => instance !== self);\n}\n\nexport function duplicateSdkMessage(\n self: SdkInstance,\n others: readonly SdkInstance[],\n foreignProvider: boolean,\n): string {\n const versions = [self, ...others]\n .map((instance, index) =>\n index === 0\n ? `${instance.version} (this hook)`\n : `${instance.version} (another copy)`,\n )\n .join(', ');\n\n return (\n `useOperation found ${others.length + 1} copies of @ekanos/sdk loaded at once: ${versions}. ` +\n (foreignProvider\n ? 'An <ExperienceRuntimeProvider> IS mounted above this component, but from a different copy, so this copy cannot see it. '\n : 'A provider mounted by one copy is invisible to hooks from another. ') +\n 'This is a dependency-resolution problem, not a code problem: usually the workspace resolves zod at two versions and pnpm builds one @ekanos/sdk per zod. ' +\n 'Run \"pnpm why @ekanos/sdk\" (or \"npm ls @ekanos/sdk\") to see both, then give every package the same zod range ' +\n '(or pin one with \"overrides\": { \"zod\": \"<one version>\" } — \"pnpm.overrides\" in package.json, or \"overrides\" in pnpm-workspace.yaml) and reinstall.'\n );\n}\n"]}
@@ -23,7 +23,7 @@ export type { FetchIntegrationStorageOptions } from './fetch-integration-storage
23
23
  export { oauthWidgetGateOptionsFor, useOAuthConnectionStatus, useOAuthWidgetGate, } from './use-oauth-connection-status.js';
24
24
  export type { ConnectionCheckAction, ConnectionCheckResult, OAuthErrorParam, OAuthWidgetGateOptions, UseOAuthConnectionStatusOptions, } from './use-oauth-connection-status.js';
25
25
  export { createPartnerConnectionCheck, partnerOAuthConnectPath, partnerOAuthErrorParam, partnerOAuthStatusUrl, } from './partner-oauth.js';
26
- export type { PartnerOAuthPathOptions } from './partner-oauth.js';
26
+ export type { PartnerOAuthPathOptions, PartnerOAuthStatusOptions, } from './partner-oauth.js';
27
27
  export { useIntegrationAction, integrationActionUrl, IntegrationActionError, } from './use-integration-action.js';
28
28
  export type { UseIntegrationActionOptions, IntegrationActionErrorCode, IntegrationActionErrorDetails, } from './use-integration-action.js';
29
29
  export { WidgetEventProvider, useWidgetEventBus } from './widget-event-context.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,4CAA4C;AAC5C,OAAO,EACL,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAU7E,kDAAkD;AAClD,mEAAmE;AACnE,qEAAqE;AACrE,OAAO,EACL,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,6BAA6B,CAAC;AAGrC,0BAA0B;AAC1B,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,+BAA+B,CAAC;AASvC,+CAA+C;AAC/C,2EAA2E;AAC3E,6EAA6E;AAC7E,qEAAqE;AACrE,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,EACvB,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AAGzB,8BAA8B;AAC9B,2EAA2E;AAC3E,2EAA2E;AAC3E,0EAA0E;AAC1E,wDAAwD;AACxD,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAOlC,mBAAmB;AACnB,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAQtD,wBAAwB;AACxB,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AAEjC,sEAAsE;AACtE,wEAAwE;AACxE,sDAAsD;AACtD,OAAO,EACL,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,6BAA6B,CAAC;AAErC,qEAAqE;AACrE,kEAAkE;AAClE,OAAO,EACL,iCAAiC,EACjC,iBAAiB,GAClB,MAAM,uCAAuC,CAAC","sourcesContent":["/**\n * @ekanos/sdk/hooks — client-side hooks.\n *\n * Import from client components only. The SDK OWNS these implementations;\n * `@kit/integrations-core/hooks` re-exports them for first-party code, so\n * there is one source of truth with two consumption paths\n * so there is one source of truth with two consumption paths.\n *\n * Server seam: nothing here imports a server module. The activation hooks\n * reach the host's `'use server'` actions ONLY through the\n * `IntegrationActivationProvider` injection seam\n * (activation-actions-context.tsx) — that is what keeps this entrypoint free\n * of `server-only` in a partner's module graph.\n *\n * Surface discipline: additions require an entry in\n * api-report.md, regenerated by `pnpm --filter @ekanos/sdk api-report`.\n */\n\n// Activation (host-injected server actions)\nexport {\n useActivateIntegration,\n useDeactivateIntegration,\n} from './use-activate-integration';\nexport { IntegrationActivationProvider } from './activation-actions-context';\nexport type {\n ActivateIntegrationAction,\n ActivateIntegrationInput,\n DeactivateIntegrationAction,\n DeactivateIntegrationInput,\n IntegrationActionResult,\n IntegrationActivationActions,\n} from './activation-actions-context';\n\n// Generic client-side storage bridge (host route:\n// GET /api/integrations/[slug]/storage). Serves only keys declared\n// `clientReadable: true`; a key that did not opt in reads as absent.\nexport {\n fetchIntegrationStorage,\n integrationStorageUrl,\n} from './fetch-integration-storage';\nexport type { FetchIntegrationStorageOptions } from './fetch-integration-storage';\n\n// OAuth connection status\nexport {\n oauthWidgetGateOptionsFor,\n useOAuthConnectionStatus,\n useOAuthWidgetGate,\n} from './use-oauth-connection-status';\nexport type {\n ConnectionCheckAction,\n ConnectionCheckResult,\n OAuthErrorParam,\n OAuthWidgetGateOptions,\n UseOAuthConnectionStatusOptions,\n} from './use-oauth-connection-status';\n\n// Hosted partner OAuth transport (host routes:\n// GET /api/integrations/[slug]/oauth/{connect,callback,status}). A partner\n// passes `connectPath: partnerOAuthConnectPath(slug)` to OAuthActivationForm\n// and `createPartnerConnectionCheck(slug)` as its `checkConnection`.\nexport {\n createPartnerConnectionCheck,\n partnerOAuthConnectPath,\n partnerOAuthErrorParam,\n partnerOAuthStatusUrl,\n} from './partner-oauth';\nexport type { PartnerOAuthPathOptions } from './partner-oauth';\n\n// Widget actions (host route:\n// POST /api/integrations/[slug]/actions/[actionName]). Invokes a partner's\n// declared `actions[name]` handler directly from a widget — deterministic,\n// no assistant round trip. `TInput`/`TOutput` are supplied by the caller;\n// see the module doc comment for the typing discipline.\nexport {\n useIntegrationAction,\n integrationActionUrl,\n IntegrationActionError,\n} from './use-integration-action';\nexport type {\n UseIntegrationActionOptions,\n IntegrationActionErrorCode,\n IntegrationActionErrorDetails,\n} from './use-integration-action';\n\n// Widget Event Bus\nexport { WidgetEventProvider, useWidgetEventBus } from './widget-event-context';\nexport { useWidgetEvents } from './use-widget-events';\nexport type {\n PublishEventInput,\n WidgetEvent,\n WidgetEventFilter,\n WidgetEventSubscriber,\n} from './widget-event-types';\n\n// Widget Ask-Bar Bridge\nexport {\n AskAssistantProvider,\n useAskAssistant,\n useRegisterAskAssistant,\n} from './ask-assistant-context';\n\n// Client-side fetch (host routes: none — this mediates a widget's own\n// vendor calls, mirroring `ctx.fetch` on the server). Default outside a\n// provider is a plain `globalThis.fetch` passthrough.\nexport {\n IntegrationFetchProvider,\n useIntegrationFetch,\n} from './integration-fetch-context';\n\n// Activation data (the credential half of the client-fetch pattern).\n// Default outside a provider is `null` — no host mounts this yet.\nexport {\n IntegrationActivationDataProvider,\n useActivationData,\n} from './integration-activation-data-context';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,4CAA4C;AAC5C,OAAO,EACL,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAU7E,kDAAkD;AAClD,mEAAmE;AACnE,qEAAqE;AACrE,OAAO,EACL,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,6BAA6B,CAAC;AAGrC,0BAA0B;AAC1B,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,+BAA+B,CAAC;AASvC,+CAA+C;AAC/C,2EAA2E;AAC3E,6EAA6E;AAC7E,qEAAqE;AACrE,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,EACvB,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AAMzB,8BAA8B;AAC9B,2EAA2E;AAC3E,2EAA2E;AAC3E,0EAA0E;AAC1E,wDAAwD;AACxD,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAOlC,mBAAmB;AACnB,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAQtD,wBAAwB;AACxB,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,uBAAuB,GACxB,MAAM,yBAAyB,CAAC;AAEjC,sEAAsE;AACtE,wEAAwE;AACxE,sDAAsD;AACtD,OAAO,EACL,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,6BAA6B,CAAC;AAErC,qEAAqE;AACrE,kEAAkE;AAClE,OAAO,EACL,iCAAiC,EACjC,iBAAiB,GAClB,MAAM,uCAAuC,CAAC","sourcesContent":["/**\n * @ekanos/sdk/hooks — client-side hooks.\n *\n * Import from client components only. The SDK OWNS these implementations;\n * `@kit/integrations-core/hooks` re-exports them for first-party code, so\n * there is one source of truth with two consumption paths\n * so there is one source of truth with two consumption paths.\n *\n * Server seam: nothing here imports a server module. The activation hooks\n * reach the host's `'use server'` actions ONLY through the\n * `IntegrationActivationProvider` injection seam\n * (activation-actions-context.tsx) — that is what keeps this entrypoint free\n * of `server-only` in a partner's module graph.\n *\n * Surface discipline: additions require an entry in\n * api-report.md, regenerated by `pnpm --filter @ekanos/sdk api-report`.\n */\n\n// Activation (host-injected server actions)\nexport {\n useActivateIntegration,\n useDeactivateIntegration,\n} from './use-activate-integration';\nexport { IntegrationActivationProvider } from './activation-actions-context';\nexport type {\n ActivateIntegrationAction,\n ActivateIntegrationInput,\n DeactivateIntegrationAction,\n DeactivateIntegrationInput,\n IntegrationActionResult,\n IntegrationActivationActions,\n} from './activation-actions-context';\n\n// Generic client-side storage bridge (host route:\n// GET /api/integrations/[slug]/storage). Serves only keys declared\n// `clientReadable: true`; a key that did not opt in reads as absent.\nexport {\n fetchIntegrationStorage,\n integrationStorageUrl,\n} from './fetch-integration-storage';\nexport type { FetchIntegrationStorageOptions } from './fetch-integration-storage';\n\n// OAuth connection status\nexport {\n oauthWidgetGateOptionsFor,\n useOAuthConnectionStatus,\n useOAuthWidgetGate,\n} from './use-oauth-connection-status';\nexport type {\n ConnectionCheckAction,\n ConnectionCheckResult,\n OAuthErrorParam,\n OAuthWidgetGateOptions,\n UseOAuthConnectionStatusOptions,\n} from './use-oauth-connection-status';\n\n// Hosted partner OAuth transport (host routes:\n// GET /api/integrations/[slug]/oauth/{connect,callback,status}). A partner\n// passes `connectPath: partnerOAuthConnectPath(slug)` to OAuthActivationForm\n// and `createPartnerConnectionCheck(slug)` as its `checkConnection`.\nexport {\n createPartnerConnectionCheck,\n partnerOAuthConnectPath,\n partnerOAuthErrorParam,\n partnerOAuthStatusUrl,\n} from './partner-oauth';\nexport type {\n PartnerOAuthPathOptions,\n PartnerOAuthStatusOptions,\n} from './partner-oauth';\n\n// Widget actions (host route:\n// POST /api/integrations/[slug]/actions/[actionName]). Invokes a partner's\n// declared `actions[name]` handler directly from a widget — deterministic,\n// no assistant round trip. `TInput`/`TOutput` are supplied by the caller;\n// see the module doc comment for the typing discipline.\nexport {\n useIntegrationAction,\n integrationActionUrl,\n IntegrationActionError,\n} from './use-integration-action';\nexport type {\n UseIntegrationActionOptions,\n IntegrationActionErrorCode,\n IntegrationActionErrorDetails,\n} from './use-integration-action';\n\n// Widget Event Bus\nexport { WidgetEventProvider, useWidgetEventBus } from './widget-event-context';\nexport { useWidgetEvents } from './use-widget-events';\nexport type {\n PublishEventInput,\n WidgetEvent,\n WidgetEventFilter,\n WidgetEventSubscriber,\n} from './widget-event-types';\n\n// Widget Ask-Bar Bridge\nexport {\n AskAssistantProvider,\n useAskAssistant,\n useRegisterAskAssistant,\n} from './ask-assistant-context';\n\n// Client-side fetch (host routes: none — this mediates a widget's own\n// vendor calls, mirroring `ctx.fetch` on the server). Default outside a\n// provider is a plain `globalThis.fetch` passthrough.\nexport {\n IntegrationFetchProvider,\n useIntegrationFetch,\n} from './integration-fetch-context';\n\n// Activation data (the credential half of the client-fetch pattern).\n// Default outside a provider is `null` — no host mounts this yet.\nexport {\n IntegrationActivationDataProvider,\n useActivationData,\n} from './integration-activation-data-context';\n"]}