workcell 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +4 -2
- package/bin/board.mjs +1 -1
- package/bin/workcell.js +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,11 @@ As versões seguem o [versionamento semântico](https://semver.org/lang/pt-BR/).
|
|
|
4
4
|
estiver na 0.x, uma MINOR pode trazer mudança incompatível; a configuração muda só com uma
|
|
5
5
|
`schemaVersion` nova e o `workcell migrate`.
|
|
6
6
|
|
|
7
|
+
## 0.2.1
|
|
8
|
+
|
|
9
|
+
- Sem mudança no motor: é a mesma 0.2.0, agora publicada pelo workflow `release`, em estágio no
|
|
10
|
+
npm (`npm stage publish`, com provenance) e liberada com a aprovação de um mantenedor.
|
|
11
|
+
|
|
7
12
|
## 0.2.0 (primeira publicação no npm)
|
|
8
13
|
|
|
9
14
|
- Envelope do lote com HTML restrito, normalização e hash do texto aprovado.
|
package/README.md
CHANGED
|
@@ -124,8 +124,10 @@ build` gera o `dist/` (testes), o `bin/board.mjs` (o servidor do board, minifica
|
|
|
124
124
|
|
|
125
125
|
1. Suba a versão no `package.json` e registre a mudança no [CHANGELOG](CHANGELOG.md), num PR.
|
|
126
126
|
2. Depois do merge, crie a tag na `main` e envie: `git tag v0.3.0 && git push origin v0.3.0`.
|
|
127
|
-
3. O workflow `release` confere a tag contra o `package.json`, roda os gates e
|
|
128
|
-
trusted publishing, com procedência (provenance).
|
|
127
|
+
3. O workflow `release` confere a tag contra o `package.json`, roda os gates e põe a versão em
|
|
128
|
+
estágio no npm pelo trusted publishing, com procedência (provenance).
|
|
129
|
+
4. Um mantenedor aprova com 2FA, no npmjs.com ou com `npm stage list` e `npm stage approve <id>`.
|
|
130
|
+
Só então a versão fica pública: o trusted publisher só tem a permissão de estágio.
|
|
129
131
|
|
|
130
132
|
## Licença
|
|
131
133
|
|
package/bin/board.mjs
CHANGED
|
@@ -218,7 +218,7 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
218
218
|
- "app": Tool callable by the app from this server only`),csp:h.never().optional(),permissions:h.never().optional()}),o5=h.object({mimeTypes:h.array(h.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),a5=h.object({method:h.literal("ui/download-file"),params:h.object({contents:h.array(h.union([vy,yy])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),s5=h.object({method:h.literal("ui/message"),params:h.object({role:h.literal("user").describe('Message role, currently only "user" is supported.'),content:h.array(wo).describe("Message content blocks (text, image, etc.).")})}),c5=h.object({method:h.literal("ui/notifications/sandbox-resource-ready"),params:h.object({html:h.string().describe("HTML content to load into the inner iframe."),sandbox:h.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:jy.optional().describe("CSP configuration from resource metadata."),permissions:Oy.optional().describe("Sandbox permissions from resource metadata.")})}),u5=h.object({method:h.literal("ui/notifications/tool-result"),params:Dn.describe("Standard MCP tool execution result.")}),lz=h.object({toolInfo:h.object({id:bo.optional().describe("JSON-RPC id of the tools/call request."),tool:wf.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:p4.optional().describe("Current color theme preference."),styles:v4.optional().describe("Style configuration for theming the app."),displayMode:Bs.optional().describe("How the UI is currently displayed."),availableDisplayModes:h.array(Bs).optional().describe("Display modes the host supports."),containerDimensions:h.union([h.object({height:h.number().describe("Fixed container height in pixels.")}),h.object({maxHeight:h.union([h.number(),h.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(h.union([h.object({width:h.number().describe("Fixed container width in pixels.")}),h.object({maxWidth:h.union([h.number(),h.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
219
219
|
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:h.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:h.string().optional().describe("User's timezone in IANA format."),userAgent:h.string().optional().describe("Host application identifier."),platform:h.union([h.literal("web"),h.literal("desktop"),h.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:h.object({touch:h.boolean().optional().describe("Whether the device supports touch input."),hover:h.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:h.object({top:h.number().describe("Top safe area inset in pixels."),right:h.number().describe("Right safe area inset in pixels."),bottom:h.number().describe("Bottom safe area inset in pixels."),left:h.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),l5=h.object({method:h.literal("ui/notifications/host-context-changed"),params:lz.describe("Partial context update containing only changed fields.")}),d5=h.object({method:h.literal("ui/update-model-context"),params:h.object({content:h.array(wo).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:h.record(h.string(),h.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),f5=h.object({method:h.literal("ui/initialize"),params:h.object({appInfo:As.describe("App identification (name and version)."),appCapabilities:_4.describe("Features and capabilities this app provides."),protocolVersion:h.string().describe("Protocol version this app supports.")})}),p5=h.object({protocolVersion:h.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:As.describe("Host application identification and version."),hostCapabilities:y4.describe("Features and capabilities provided by the host."),hostContext:lz.describe("Rich context about the host environment.")}).passthrough();var uz="ui/resourceUri",Of="text/html;profile=mcp-app";function dz(e,t,n,i){let r=n._meta,o=r.ui,a=r[uz],s=r;return o?.resourceUri&&!a?s={...r,[uz]:o.resourceUri}:a&&!o?.resourceUri&&(s={...r,ui:{...o,resourceUri:a}}),e.registerTool(t,{...n,_meta:s},i)}function fz(e,t,n,i,r){return e.registerResource(t,n,{mimeType:Of,...i},r)}var mj=R$(x$(),1),hj=R$(pj(),1);function N2(){let e=new mj.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,hj.default)(e),e}var gp=class{constructor(t){this._ajv=t??N2()}getValidator(t){let n="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var vp=class{constructor(t){this._server=t}requestStream(t,n,i){return this._server.requestStream(t,n,i)}createMessageStream(t,n){let i=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!i?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let r=t.messages[t.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],a=o.some(l=>l.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],u=c.some(l=>l.type==="tool_use");if(a){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},So,n)}elicitInputStream(t,n){let i=this._server.getClientCapabilities(),r=t.mode??"form";switch(r){case"url":{if(!i?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!i?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=r==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:o},Io,n)}async getTask(t,n){return this._server.getTask({taskId:t},n)}async getTaskResult(t,n,i){return this._server.getTaskResult({taskId:t},n,i)}async listTasks(t,n){return this._server.listTasks(t?{cursor:t}:void 0,n)}async cancelTask(t,n){return this._server.cancelTask({taskId:t},n)}};function gj(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function vj(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var yp=class extends Vs{constructor(t,n){super(n),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(qs.options.map((i,r)=>[i,r])),this.isMessageIgnored=(i,r)=>{let o=this._loggingLevels.get(r);return o?this.LOG_LEVEL_SEVERITY.get(i)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new gp,this.setRequestHandler(ly,i=>this._oninitialize(i)),this.setNotificationHandler(dy,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(_y,async(i,r)=>{let o=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=i.params,s=qs.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new vp(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Py(this._capabilities,t)}setRequestHandler(t,n){let r=Fr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=lo(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(c,u)=>{let l=qr(Un,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new M(q.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,f=await Promise.resolve(n(c,u));if(d.task){let m=qr(xo,f);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new M(q.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let p=qr(Dn,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new M(q.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(t,s)}return super.setRequestHandler(t,n)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){vj(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&gj(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let n=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:f0.includes(n)?n:iy,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Es)}async createMessage(t,n){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let i=t.messages[t.messages.length-1],r=Array.isArray(i.content)?i.content:[i.content],o=r.some(u=>u.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(o){if(r.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(r.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},Sf,n):this.request({method:"sampling/createMessage",params:t},So,n)}async elicitInput(t,n){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let r=t;return this.request({method:"elicitation/create",params:r},Io,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let r=t.mode==="form"?t:{...t,mode:"form"},o=await this.request({method:"elicitation/create",params:r},Io,n);if(o.action==="accept"&&o.content&&r.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(r.requestedSchema)(o.content);if(!s.valid)throw new M(q.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof M?a:new M(q.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(t,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},n)}async listRoots(t,n){return this.request({method:"roots/list",params:t},$y,n)}async sendLoggingMessage(t,n){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,n))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var _j=Symbol.for("mcp.completable");function j$(e){return!!e&&typeof e=="object"&&_j in e}function $j(e){return e[_j]?.complete}var yj;(function(e){e.Completable="McpCompletable"})(yj||(yj={}));var A2=/^[A-Za-z0-9._-]{1,128}$/;function C2(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!A2.test(e)){let n=e.split("").filter(i=>!/[A-Za-z0-9._-]/.test(i)).filter((i,r,o)=>o.indexOf(i)===r);return t.push(`Tool name contains invalid characters: ${n.map(i=>`"${i}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function R2(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let n of t)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function O$(e){let t=C2(e);return R2(e,t.warnings),t.isValid}var _p=class{constructor(t){this._mcpServer=t}registerToolTask(t,n,i){let r={taskSupport:"required",...n.execution};if(r.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,r,n._meta,i)}};Ps();Ps();function D2(e,t){let n=0,i=[e];for(;i.length>0;){let r=i.pop();if(!(r===null||typeof r!="object"))if(Array.isArray(r))for(let o of r){if(++n>t)return n;o!==null&&typeof o=="object"&&i.push(o)}else for(let o in r){if(!Object.prototype.hasOwnProperty.call(r,o))continue;if(++n>t)return n;let a=r[o];a!==null&&typeof a=="object"&&i.push(a)}}return n}function U2(e){if(!(e===void 0||e===1/0)){if(typeof e!="number"||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var $p=class{constructor(t,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new yp(t,n),this._maxToolInputElements=U2(n?.maxToolInputElements),n?.capabilities?.tools&&this.setToolRequestHandlers(),n?.capabilities?.resources&&this.setResourceRequestHandlers(),n?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new _p(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(an(Ls)),this.server.assertCanSetRequestHandler(an(Un)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ls,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,n])=>{let i={name:t,title:n.title,description:n.description,inputSchema:(()=>{let r=uo(n.inputSchema);return r?Iy(r,{strictUnions:!0,pipeStrategy:"input"}):M2})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let r=uo(n.outputSchema);r&&(i.outputSchema=Iy(r,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(Un,async(t,n)=>{try{let i=this._registeredTools[t.params.name];if(!i)throw new M(q.InvalidParams,`Tool ${t.params.name} not found`);if(!i.enabled)throw new M(q.InvalidParams,`Tool ${t.params.name} disabled`);let r=!!t.params.task,o=i.execution?.taskSupport,a="createTask"in i.handler;if((o==="required"||o==="optional")&&!a)throw new M(q.InternalError,`Tool ${t.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!r)throw new M(q.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!r&&a)return await this.handleAutomaticTaskPolling(i,t,n);let s=await this.validateToolInput(i,t.params.arguments,t.params.name),c=await this.executeToolHandler(i,s,n);return r||await this.validateToolOutput(i,c,t.params.name),c}catch(i){if(i instanceof M&&i.code===q.UrlElicitationRequired)throw i;return this.createToolError(i instanceof Error?i.message:String(i))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,n,i){if(this._maxToolInputElements!==void 0&&D2(n,this._maxToolInputElements)>this._maxToolInputElements)throw new M(q.InvalidParams,`Invalid arguments for tool ${i}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!t.inputSchema)return;let o=uo(t.inputSchema)??t.inputSchema,a=await jd(o,n??{});if(!a.success){let s="error"in a?a.error:"Unknown error",c=Od(s);throw new M(q.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${c}`)}return a.data}async validateToolOutput(t,n,i){if(!t.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new M(q.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let r=uo(t.outputSchema),o=await jd(r,n.structuredContent);if(!o.success){let a="error"in o?o.error:"Unknown error",s=Od(a);throw new M(q.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${s}`)}}async executeToolHandler(t,n,i){let r=t.handler;if("createTask"in r){if(!i.taskStore)throw new Error("No task store provided.");let a={...i,taskStore:i.taskStore};if(t.inputSchema){let s=r;return await Promise.resolve(s.createTask(n,a))}else{let s=r;return await Promise.resolve(s.createTask(a))}}if(t.inputSchema){let a=r;return await Promise.resolve(a(n,i))}else{let a=r;return await Promise.resolve(a(i))}}async handleAutomaticTaskPolling(t,n,i){if(!i.taskStore)throw new Error("No task store provided for task-capable tool.");let r=await this.validateToolInput(t,n.params.arguments,n.params.name),o=t.handler,a={...i,taskStore:i.taskStore},s=r?await Promise.resolve(o.createTask(r,a)):await Promise.resolve(o.createTask(a)),c=s.task.taskId,u=s.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await i.taskStore.getTask(c);if(!d)throw new M(q.InternalError,`Task ${c} not found during polling`);u=d}return await i.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(an(If)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(If,async t=>{switch(t.params.ref.type){case"ref/prompt":return z0(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return T0(t),this.handleResourceCompletion(t,t.params.ref);default:throw new M(q.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,n){let i=this._registeredPrompts[n.name];if(!i)throw new M(q.InvalidParams,`Prompt ${n.name} not found`);if(!i.enabled)throw new M(q.InvalidParams,`Prompt ${n.name} disabled`);if(!i.argsSchema)return xc;let o=Fr(i.argsSchema)?.[t.params.argument.name];if(!j$(o))return xc;let a=$j(o);if(!a)return xc;let s=await a(t.params.argument.value,t.params.context);return xj(s)}async handleResourceCompletion(t,n){let i=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===n.uri);if(!i){if(this._registeredResources[n.uri])return xc;throw new M(q.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let r=i.resourceTemplate.completeCallback(t.params.argument.name);if(!r)return xc;let o=await r(t.params.argument.value,t.params.context);return xj(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(an(_f)),this.server.assertCanSetRequestHandler(an($f)),this.server.assertCanSetRequestHandler(an(bf)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_f,async(t,n)=>{let i=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),r=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let a=await o.resourceTemplate.listCallback(n);for(let s of a.resources)r.push({...o.metadata,...s})}return{resources:[...i,...r]}}),this.server.setRequestHandler($f,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,i])=>({name:n,uriTemplate:i.resourceTemplate.uriTemplate.toString(),...i.metadata}))})),this.server.setRequestHandler(bf,async(t,n)=>{let i=new URL(t.params.uri),r=this._registeredResources[i.toString()];if(r){if(!r.enabled)throw new M(q.InvalidParams,`Resource ${i} disabled`);return r.readCallback(i,n)}for(let o of Object.values(this._registeredResourceTemplates)){let a=o.resourceTemplate.uriTemplate.match(i.toString());if(a)return o.readCallback(i,a,n)}throw new M(q.InvalidParams,`Resource ${i} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(an(xf)),this.server.assertCanSetRequestHandler(an(kf)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(xf,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,n])=>({name:t,title:n.title,description:n.description,arguments:n.argsSchema?Z2(n.argsSchema):void 0}))})),this.server.setRequestHandler(kf,async(t,n)=>{let i=this._registeredPrompts[t.params.name];if(!i)throw new M(q.InvalidParams,`Prompt ${t.params.name} not found`);if(!i.enabled)throw new M(q.InvalidParams,`Prompt ${t.params.name} disabled`);if(i.argsSchema){let r=uo(i.argsSchema),o=await jd(r,t.params.arguments??{});if(!o.success){let c="error"in o?o.error:"Unknown error",u=Od(c);throw new M(q.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${u}`)}let a=o.data,s=i.callback;return await Promise.resolve(s(a,n))}else{let r=i.callback;return await Promise.resolve(r(n))}}),this._promptHandlersInitialized=!0)}resource(t,n,...i){let r;typeof i[0]=="object"&&(r=i.shift());let o=i[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let a=this._createRegisteredResource(t,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let a=this._createRegisteredResourceTemplate(t,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,n,i,r){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(t,i.title,n,i,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let o=this._createRegisteredResourceTemplate(t,i.title,n,i,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(t,n,i,r,o){let a={name:t,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==i&&(delete this._registeredResources[i],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=a,a}_createRegisteredResourceTemplate(t,n,i,r,o){let a={resourceTemplate:i,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==t&&(delete this._registeredResourceTemplates[t],u.name&&(this._registeredResourceTemplates[u.name]=a)),typeof u.title<"u"&&(a.title=u.title),typeof u.template<"u"&&(a.resourceTemplate=u.template),typeof u.metadata<"u"&&(a.metadata=u.metadata),typeof u.callback<"u"&&(a.readCallback=u.callback),typeof u.enabled<"u"&&(a.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=a;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!i.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(t,n,i,r,o){let a={title:n,description:i,argsSchema:r===void 0?void 0:On(r),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==t&&(delete this._registeredPrompts[t],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=On(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=a,r&&Object.values(r).some(c=>{let u=c instanceof Cn?c._def?.innerType:c;return j$(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,n,i,r,o,a,s,c,u){O$(t);let l={title:n,description:i,inputSchema:bj(r),outputSchema:bj(o),annotations:a,execution:s,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&O$(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=On(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=On(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let i,r,o,a;if(typeof n[0]=="string"&&(i=n.shift()),n.length>1){let c=n[0];if(E$(c))r=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!E$(n[0])&&(a=n.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=n.shift()}}let s=n[0];return this._createRegisteredTool(t,void 0,i,r,o,a,{taskSupport:"forbidden"},void 0,s)}registerTool(t,n,i){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:r,description:o,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=n;return this._createRegisteredTool(t,r,o,a,s,c,{taskSupport:"forbidden"},u,i)}prompt(t,...n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let i;typeof n[0]=="string"&&(i=n.shift());let r;n.length>1&&(r=n.shift());let o=n[0],a=this._createRegisteredPrompt(t,void 0,i,r,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(t,n,i){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:r,description:o,argsSchema:a}=n,s=this._createRegisteredPrompt(t,r,o,a,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,n){return this.server.sendLoggingMessage(t,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var M2={type:"object",properties:{}};function kj(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function wj(e){return"_def"in e||"_zod"in e||kj(e)}function E$(e){return typeof e!="object"||e===null||wj(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(kj)}function bj(e){if(e){if(E$(e))return On(e);if(!wj(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function Z2(e){let t=Fr(e);return t?Object.entries(t).map(([n,i])=>{let r=CS(i),o=RS(i);return{name:n,description:r,required:!o}}):[]}function an(e){let n=Fr(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=lo(n);if(typeof i=="string")return i;throw new Error("Schema method literal must be a string")}function xj(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var xc={completion:{values:[],hasMore:!1}};import Ij from"node:process";var L2=10*1024*1024,bp=class{constructor(t){this._maxBufferSize=t?.maxBufferSize??L2}append(t){if((this._buffer?.length??0)+t.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
220
220
|
`);if(t===-1)return null;let n=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),q2(n)}clear(){this._buffer=void 0}};function q2(e){return uy.parse(JSON.parse(e))}function Sj(e){return JSON.stringify(e)+`
|
|
221
|
-
`}var xp=class{constructor(t=Ij.stdin,n=Ij.stdout,i){this._stdin=t,this._stdout=n,this._started=!1,this._ondata=r=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=r=>{this.onerror?.(r)},this._readBuffer=new bp({maxBufferSize:i?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(n=>{let i=Sj(t);this._stdout.write(i)?n():this._stdout.once("drain",n)})}};var zj="0.2.
|
|
221
|
+
`}var xp=class{constructor(t=Ij.stdin,n=Ij.stdout,i){this._stdin=t,this._stdout=n,this._started=!1,this._ondata=r=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=r=>{this.onerror?.(r)},this._readBuffer=new bp({maxBufferSize:i?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(n=>{let i=Sj(t);this._stdout.write(i)?n():this._stdout.once("drain",n)})}};var zj="0.2.1";import{createHash as Pj,randomUUID as F2}from"node:crypto";var sn=class extends Error{},kc=class extends Error{};async function Tj(e,t){let n=e.refs.get(t)??t,i=e.items.get(n)??[...e.items.values()].find(s=>Object.values(s.keys).includes(t));if(i)return i;let r=/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(n)?await e.store.readItem(n):void 0,o=r?void 0:Object.entries(await e.store.readKeys()).find(([s])=>s.slice(s.indexOf(":")+1)===t),a=r??(o?await e.store.readItem(o[1]):void 0);return a&&(e.items.set(a.id,a),e.loaded.set(a.id,a.writes.length)),a}async function kp(e,t){let n=await Tj(e,t);if(n)return n;if(/^local-\d+$/.test(t))throw new sn(`o board n\xE3o tem o item ${t}`);let i=await Tj(e,Ko(e.source,t));if(i)return i;let r={id:Ko(e.source,t),keys:{[e.source]:t},writes:[]};return e.items.set(r.id,r),r}function V2(e){return e.attrs.issue??e.attrs.from}var N$=e=>e.op==="create_issue"||e.op==="create_subtask",jj=new Set(["a-subir","pendente"]);function Oj(e){return Object.values(e.writes[0]?.targets??{}).some(t=>jj.has(t.status))}async function B2(e,t,n){let i=t.fields.find(a=>a.name==="summary"&&a.kind==="text");if(!i||i.kind!=="text")return;let o=(await e.store.listItems()).find(a=>a.parent===n&&a.writes[0]?.op===t.op&&a.writes[0]?.html.summary===i.text&&(Object.keys(a.keys).length>0||Oj(a)));if(o)return e.items.set(o.id,o),e.loaded.set(o.id,o.writes.length),o}async function H2(e,t,n){let i=(await e.store.listItems()).find(r=>r.writes.some(o=>o.batch===t&&o.batchIndex===n));if(i)return e.items.has(i.id)||(e.items.set(i.id,i),e.loaded.set(i.id,i.writes.length)),e.items.get(i.id)}async function J2(e,t,n,i,r){let o=await H2(e,i,r);return o||(n&&t.op==="create_subtask"?B2(e,t,n):void 0)}async function K2(e,t,n,i,r){let o=V2(t);if(o)return kp(e,o);let a=t.attrs.parent?(await kp(e,t.attrs.parent)).id:void 0,s=await J2(e,t,a,i,r);if(s)return t.attrs.ref&&e.refs.set(t.attrs.ref,s.id),s;let c={id:`new-${F2()}`,keys:{},writes:[],station:n,...t.attrs.ref?{ref:t.attrs.ref}:{},...a?{parent:a}:{}};return e.items.set(c.id,c),t.attrs.ref&&e.refs.set(t.attrs.ref,c.id),c}function W2(e,t,n,i,r){return{project:n.project,issueType:o=>n.issueTypes[o]??o,subtaskType:n.subtaskType,status:o=>n.states[o]??o,key:o=>{let a=e.items.get(e.refs.get(o)??o)??[...e.items.values()].find(c=>Object.values(c.keys).includes(o));if(!a)throw new kc(`o item ${o} n\xE3o est\xE1 no board`);let s=a.keys[t];if(s)return s;if(i.has(a.id)){let c=`<chave de ${a.ref??a.id} no ${t}>`;return r[c]=a.id,c}throw new kc(`aguardando a issue de ${a.id} no ${n.displayName}`)}}}function G2(e,t,n,i,r,o){let a=e.manifest.targets[t],s=i.targets[t][r],c={fields:s.fields,hashes:s.hashes};if(s.notCovered)return{status:"pendente",reason:s.notCovered,...c};let u=ob(a.type);if(!u)throw new sn(`o destino ${t} \xE9 de um tipo sem adaptador: ${a.type}`);try{let l={},d=u.buildCall(n.op,n.attrs,s.fields,W2(e,t,a,o,l)),f=a.ops[n.op]??d.tool,p=Object.keys(l).length?{placeholders:l}:{};return{status:"a-subir",...c,call:{tool:f,args:d.args,...d.note?{note:d.note}:{},...p}}}catch(l){if(!(l instanceof kc))throw l;return{status:"a-subir",reason:l.message,...c}}}function X2(e,t,n){let i=new Set(e.stations[t].tools);for(let r of n.lote.writes)for(let[o,a]of Object.entries(e.targets)){let s=a.ops[r.op];if(!s||!i.has(s))throw new sn(`a m\xE1quina da esta\xE7\xE3o ${t} n\xE3o pode fazer ${r.op} (linha ${r.line}) no ${o}`)}}function Y2(e,t,n){e.station=n,t.op==="transition_issue"&&(e.state=t.attrs.state)}async function Ej(e,t,n){let i=t.stations[n.station];if(!i)throw new sn(`a esta\xE7\xE3o ${n.station} n\xE3o existe nesta f\xE1brica`);let r=Jp(n.lote,t);X2(t,n.station,r);let o=Object.entries(t.targets).find(([,d])=>d.source)?.[0]??Object.keys(t.targets)[0],a={store:e,manifest:t,source:o,items:new Map,refs:new Map,loaded:new Map},c=(await kp(a,n.issue)).changedAtSource?[`a issue ${n.issue} mudou na origem desde a \xFAltima escrita da f\xE1brica: diga isso \xE0 pessoa antes de pedir o aval`]:[],u=Pj("sha256").update(JSON.stringify([n.station,n.issue,n.lote]),"utf8").digest("hex"),l={ctx:a,render:r,input:n,batch:u,replaced:new Map,created:new Set,stamp:_b(t.factory,n.station,i),result:{items:[],calls:[],waiting:[],skipped:[],warnings:c}};for(let[d,f]of r.lote.writes.entries())await nq(l,f,d);for(let d of a.items.values())await aq(e,d,a.loaded.get(d.id)??0,l.replaced.get(d.id)??[]);return l.result.items=[...a.items.keys()],l.result}function Q2(e,t,n,i){let r=t.writes.find(a=>a.batch===e.batch&&a.batchIndex===i);if(r)return r;let o=N$(n)&&Object.keys(t.keys).length===0&&Oj(t)?t.writes[0]:void 0;return o&&e.result.warnings.push(`a cria\xE7\xE3o de ${t.id} j\xE1 estava no board por subir: o lote a refaz no lugar em vez de criar outra`),o}function eq(e,t,n,i,r,o){let a=N$(n)?t.keys[r]:void 0;if(a){e.result.skipped.push({write:i+1,item:t.id,target:r,key:a});return}let s=o?.targets[r];if(s&&!jj.has(s.status)){e.result.warnings.push(`a escrita ${i+1} deste lote j\xE1 foi enviada para ${r}${s.sentAt?` em ${s.sentAt}`:""}; o mesmo lote n\xE3o sai de novo (para enviar de novo, mude o lote)`);return}let c=G2(e.ctx,r,n,e.render,i,e.created);return c.call?e.result.calls.push({write:i+1,item:t.id,target:r,...c.call}):e.result.waiting.push({write:i+1,item:t.id,target:r,reason:c.reason??""}),tq(s,c)}function tq(e,t){return!e?.approval||JSON.stringify(Object.values(e.hashes))!==JSON.stringify(Object.values(t.hashes))?t:{...t,approval:e.approval}}async function rq(e,t){for(let n of["issue","parent","from","to"]){let i=t.attrs[n];i!==void 0&&!e.refs.has(i)&&await kp(e,i)}}async function nq(e,t,n){let{ctx:i,input:r}=e,o=await K2(i,t,r.station,e.batch,n);await rq(i,t);let a=Q2(e,o,t,n),s={};for(let l of Object.keys(i.manifest.targets)){let d=eq(e,o,t,n,l,a);d&&(s[l]=d)}if(N$(t)&&(Object.keys(s).length||a)&&e.created.add(o.id),Object.keys(s).length===0)return;let c={at:r.at,station:r.station,stamp:e.stamp,op:t.op,html:e.render.html[n],targets:{...a?.targets,...s},batch:e.batch,batchIndex:n},u=iq(o.id,c,Object.keys(s));a?(o.writes[o.writes.indexOf(a)]=u,e.replaced.set(o.id,[...e.replaced.get(o.id)??[],{old:a,next:u}])):o.writes.push(u),Y2(o,t,r.station)}function iq(e,t,n){let i={...t.targets};for(let r of n){let o=i[r],a=[e,r,t.at,t.station,t.op,t.batch??null,t.batchIndex??null,t.html,o.fields,o.call?.args??null];i[r]={...o,id:Pj("sha256").update(JSON.stringify(a),"utf8").digest("hex")}}return{...t,targets:i}}var oq=(e,t)=>e.batch!==void 0?e.batch===t.batch&&e.batchIndex===t.batchIndex:e.at===t.at&&e.op===t.op&&e.station===t.station;async function aq(e,t,n,i){await e.updateItem(t.id,o=>{if(!o)return t;let a=o.writes.map(s=>i.find(c=>oq(c.old,s))?.next??s);return{...o,...t,keys:{...o.keys,...t.keys},writes:[...a,...t.writes.slice(n)]}});let r=Object.entries(t.keys).map(([o,a])=>[`${o}:${a}`,t.id]);r.length&&await e.addKeys(Object.fromEntries(r))}function Nj(e){let t=[`Lote gravado no board (${e.items.length} ${e.items.length===1?"item":"itens"}).`];return t.push(...e.warnings.map(n=>`Aten\xE7\xE3o: ${n}.`)),e.skipped.length&&t.push("J\xE1 existem no destino e n\xE3o s\xE3o criadas de novo:",...e.skipped.map(n=>`- escrita ${n.write} (${n.item}): ${n.key} no ${n.target}`)),e.calls.length?t.push("Agora chame cada ferramenta abaixo, na ordem, com os argumentos exatamente como est\xE3o: n\xE3o converta nem reescreva texto. Troque s\xF3 os marcadores <...>: a chave de um item pela chave que a chamada que o criou devolveu, e o id da transi\xE7\xE3o pelo que a leitura de transi\xE7\xF5es mostrar.",JSON.stringify(e.calls,null,2)):t.push("Nenhuma chamada a destino externo agora."),e.waiting.length&&t.push("Escritas que ficam no board para subir depois:",...e.waiting.map(n=>`- escrita ${n.write} (${n.item}) no ${n.target}: ${n.reason}`)),t.join(`
|
|
222
222
|
`)}var sq=200,cq={state:"",name:"Na origem"},Aj=["pendente","a-subir","sincronizado-a-mao","enviado"],Rj={"a-subir":"a subir",pendente:"pendente",enviado:"enviado","sincronizado-a-mao":"sincronizado \xE0 m\xE3o"},Dj=["a-subir","pendente"];function uq(e){let t={};for(let n of e.writes)for(let[i,r]of Object.entries(n.targets)){let o=t[i];(o===void 0||Aj.indexOf(r.status)<Aj.indexOf(o))&&(t[i]=r.status)}return t}function Uj(e){if(e.source?.summary)return e.source.summary;let t=e.writes.find(n=>typeof n.html.summary=="string")?.html.summary;return typeof t=="string"&&t!==""?t:e.id}function lq(e){return[e.source?.readAt??"",...e.writes.map(t=>t.at)].reduce((t,n)=>n>t?n:t,"")}function Mj(e,t,n,i){let r=Object.entries(t.fields).map(([s,c])=>`${s}:
|
|
223
223
|
${Array.isArray(c)?c.join(", "):c}`),a=(i.stampFormats[n]??`
|
|
224
224
|
|