@taskyon/tyclient 0.5.0 → 0.5.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../taskyon/src/utils/jsonSchema.ts","../../taskyon/src/types/tools.ts","../../taskyon/src/types/node.ts","../../taskyon/src/utils/encoding.ts","../../taskyon/src/core/createTasks.ts","../../taskyon/src/types/toolApi.ts","../../taskyon/src/types/messages.ts","../../taskyon/src/types/apiTypes.ts","../../taskyon/src/utils/frpBus.ts","../../taskyon/src/api/index.ts","../src/index.ts"],"names":["z"],"mappings":";;;AAGA,IAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,CAAK,CAAC,QAAA,EAAU,QAAA,EAAU,SAAA,EAAW,SAAA,EAAW,QAAA,EAAU,OAAA,EAAS,MAAM,CAAC,CAAA;AAGnG,IAAM,WAAA,GAAsC,CAAA,CAAE,IAAA,CAAK,MAAM,mBAAmB,CAAA;AAG5E,IAAM,wBAA0D,CAAA,CAAE,IAAA;AAAA,EAAK,MACrE,EAAE,KAAA,CAAM,CAAC,EAAE,OAAA,EAAQ,EAAG,WAAW,CAAC;AACpC,CAAA;AAEA,IAAM,mBAAA,GAAsB,EAAE,YAAA,CAAa;AAAA,EACzC,GAAA,EAAK,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EACzB,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC1B,OAAA,EAAS,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC7B,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC9B,IAAA,EAAM,CAAA,CAAE,KAAA,CAAM,CAAC,cAAA,EAAgB,CAAA,CAAE,KAAA,CAAM,cAAc,CAAC,CAAC,CAAA,CAAE,QAAA,EAAS;AAAA,EAClE,KAAA,EAAO,CAAA,CAAE,GAAA,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um = z.enum(['string', 'number', 'integer', 'boolean', 'object', 'array', 'null'])\n\n// This inline transform removes keys with undefined values.\nconst JSONSchema7: z.ZodType<JSONSchema7> = z.lazy(() => JSONSchemaObjectRaw)\n\n// A JSONSchema can be a boolean or an object.\nconst JSONSchema7Definition: z.ZodType<JSONSchema7Definition> = z.lazy(() =>\n z.union([z.boolean(), JSONSchema7]),\n)\n\nconst JSONSchemaObjectRaw = z.strictObject({\n $id: z.string().optional(),\n $ref: z.string().optional(),\n $schema: z.string().optional(),\n $comment: z.string().optional(),\n type: z.union([JSONSchemaEnum, z.array(JSONSchemaEnum)]).optional(),\n const: z.any().optional(),\n enum: z.any().optional(),\n multipleOf: z.number().optional(),\n maximum: z.number().optional(),\n exclusiveMaximum: z.number().optional(),\n minimum: z.number().optional(),\n exclusiveMinimum: z.number().optional(),\n maxLength: z.number().optional(),\n minLength: z.number().optional(),\n pattern: z.string().optional(),\n items: z.lazy(() => z.union([JSONSchema7Definition, z.array(JSONSchema7Definition)]).optional()),\n additionalItems: z.lazy(() => JSONSchema7Definition.optional()),\n contains: z.lazy(() => JSONSchema7Definition.optional()),\n maxItems: z.number().optional(),\n minItems: z.number().optional(),\n uniqueItems: z.boolean().optional(),\n maxProperties: z.number().optional(),\n minProperties: z.number().optional(),\n required: z.array(z.string()).optional(),\n properties: z.lazy(() => z.record(z.string(), JSONSchema7Definition).optional()),\n patternProperties: z.lazy(() => z.record(z.string(), JSONSchema7Definition).optional()),\n additionalProperties: z.lazy(() => JSONSchema7Definition.optional()),\n unevaluatedProperties: z.lazy(() => JSONSchema7Definition.optional()),\n dependencies: z.lazy(() =>\n z.record(z.string(), z.union([JSONSchema7Definition, z.array(z.string())])).optional(),\n ),\n propertyNames: z.lazy(() => JSONSchema7Definition.optional()),\n if: z.lazy(() => JSONSchema7Definition.optional()),\n then: z.lazy(() => JSONSchema7Definition.optional()),\n else: z.lazy(() => JSONSchema7Definition.optional()),\n allOf: z.lazy(() => z.array(z.lazy(() => JSONSchema7Definition)).optional()),\n anyOf: z.lazy(() => z.array(z.lazy(() => JSONSchema7Definition)).optional()),\n oneOf: z.lazy(() => z.array(z.lazy(() => JSONSchema7Definition)).optional()),\n not: z.lazy(() => JSONSchema7Definition.optional()),\n format: z.string().optional(),\n contentMediaType: z.string().optional(),\n contentEncoding: z.string().optional(),\n definitions: z\n .record(\n z.string(),\n z.lazy(() => JSONSchema7Definition),\n )\n .optional(),\n // support Draft‑2019+ $defs\n // this is required, because the \"json-schema-to-ts\" library uses $defs and\n // we can not validate those schemas without it.\n $defs: z\n .record(\n z.string(),\n z.lazy(() => JSONSchema7Definition),\n )\n .optional(),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.any().optional(),\n readOnly: z.boolean().optional(),\n writeOnly: z.boolean().optional(),\n examples: z.array(z.any()).optional(),\n nullable: z.boolean().optional(),\n})\n\n// Extend the raw object first, then transform.\nconst JSONSchemaReferenceSchema: z.ZodType<JSONSchema7> = JSONSchemaObjectRaw.extend({\n $id: z.string(),\n})\n\nexport { JSONSchema7Definition, JSONSchemaReferenceSchema, JSONSchema7 }\n","import z from 'zod'\nimport { JSONSchema7 } from '../utils/jsonSchema'\n\nexport const taskMarker = '*TY_TASKRESULT*'\n\nconst FunctionName = z.string().refine((val) => /^[a-zA-Z0-9_-]+$/.test(val), {\n error: ({ input }) => {\n const msg = typeof input === 'string' ? input : JSON.stringify(input)\n return `The function/tool name ${msg} contains illegal characters. It has to fulfill '^[a-zA-Z0-9_-]+$'`\n },\n})\ntype FunctionName = z.infer<typeof FunctionName>\n\nexport const ParamType = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), z.unknown()),\n z.array(z.unknown()),\n z.null(),\n // We are also allowing undefined calls to the functions, even though this is not allowed in jsonschema.\n // But we are sometimes calling our functions manually and this way we can also call them without parameters.\n z.undefined(),\n])\nexport type ParamType = z.infer<typeof ParamType>\nexport const FunctionArguments = z.record(z.string(), ParamType).meta({\n description: 'arguments of the function',\n})\nexport type FunctionArguments = z.infer<typeof FunctionArguments>\n\n/* here we are essentiall declaring the taskyon API */\nexport const FunctionCall = z.object({\n name: FunctionName,\n arguments: FunctionArguments,\n})\nexport type FunctionCall = z.infer<typeof FunctionCall>\n\nexport const ToolBase = z.object({\n description: z.string().meta({\n description: 'A short description about the tool so that an LLM knows when to use it.',\n }),\n longDescription: z.string().optional().meta({\n description: 'An optional longer description for more complicated operations with this tool.',\n }),\n name: FunctionName.meta({\n description: 'Name of the tool. Has to fulfill: /^[a-zA-Z0-9_-]+$/',\n }),\n renderOptions: z\n .object({\n hideChat: z\n .boolean()\n .describe(\n \"hide the tool in the UI chat. Useful if the function is used very often and we don't want it to clutter the chatWindow\",\n ),\n hideLlm: z.boolean(\n 'HideLlm will hide the tool from an LLM inside chatCompletion. This is mainly useful for tools like \"chatCompletion\" which the llm doesn\\'t need to see in the chatCompletion.',\n ),\n })\n .partial()\n .optional(),\n parameters: JSONSchema7.meta({\n description: 'A JSON schema object describing the parameters of the function.',\n }).readonly(),\n code: z\n .string()\n .optional()\n .describe(\n `The functionality of the tool as javascript code. If a function description doesn't include any code,\nTaskyon will automatically call a postMessage event with the parameters to the parent window\nwith the function name.`,\n ),\n})\nexport type ToolBase = z.infer<typeof ToolBase> // this reflects json schema: https://json-schema.org/specification-links\n","import z from 'zod'\nimport type { Expand } from '../utils/tsHelpers'\nimport { FunctionCall, ToolBase } from './tools'\n\nexport const Annotation = z.union([\n z.object({\n type: z.literal('url_citation'),\n url_citation: z\n .object({\n end_index: z.number(),\n start_index: z.number(),\n title: z.string(),\n url: z.string(),\n content: z.string(),\n })\n .partial()\n .optional(),\n }),\n z.object({\n type: z.literal('file'),\n content: z\n .object({\n text: z.string(),\n type: z.string(),\n })\n .array()\n .optional(),\n }),\n])\n\nexport type Annotation = z.infer<typeof Annotation>\n\nconst MessageContent = z.object({\n type: z.literal('message'),\n data: z.string(),\n ann: Annotation.array().optional(),\n})\nconst StructuredContent = z.object({\n type: z.literal('structured'),\n data: z.unknown(),\n})\nconst ToolCallContent = z.object({ type: z.literal('functioncall'), data: FunctionCall })\nconst UploadedFilesContent = z.object({\n type: z.literal('files'),\n data: z.array(z.string()),\n})\nconst ToolResultContent = z.object({ type: z.literal('toolresult'), data: z.unknown() })\nconst ToolDefinition = z.object({ type: z.literal('tooldefinition'), data: ToolBase })\nconst ErrorContent = z.object({ type: z.literal('error'), data: z.unknown() }).meta({\n description: 'Gets created if any error occurs during task processing.',\n})\nconst Return = z.object({ type: z.literal('return'), data: z.string() }).describe(\n `A Termination task always indicates the end of an autonomous task chat execution.\nEvery Leaf task which is not a Termination task can potentially continue to be executed...\n\nWe can indicate the reason for termination here as well...`,\n)\n\n// TODO: I am not sure, if we need this here...\nconst ChatCompletionContent = z.union([MessageContent, ToolResultContent, ErrorContent])\nexport type ChatCompletionContent = z.infer<typeof ChatCompletionContent>\n\nexport const TaskContent = z.union([\n MessageContent.strict(),\n ToolResultContent.strict(),\n ToolDefinition.strict(),\n ErrorContent.strict(),\n StructuredContent.strict(),\n ToolCallContent.strict(),\n // TODO: replace with a \"context\" function which can also be a link to a URL for example or maybe a search string for other tasks...\n // we can declare function for a lot of these things this way :)\n UploadedFilesContent.strict(),\n Return.strict(),\n])\n\nexport type TaskContent = z.infer<typeof TaskContent>\n\nexport const TaskNode = z.object({\n // TODO: get rid of \"role\" and put it into chatCompletion only...\n // we don't need it in the rest of the app, I think.. we might be able to indicate that a task was\n // \"automatically\" created by using a notation in \"authorID\" e.g. something like.\n // \"pubKey:gen\" if the task was automatically generated && pubKey if it wasn't\n // OR: we could simply check the parents & priors of tasks. if tasks have a parent, they were generated\n // by a function. user-generated message should not have a parent...\n role: z.enum(['system', 'user', 'assistant', 'function']),\n name: z.string().optional().meta({\n description: 'An optional name for the task',\n }),\n content: TaskContent.describe(\n `This is the actual content of the task. This is the actual content which is process at each step.\nFor example this is, what an LLM would actually get to see. There are only a few different ways\nof how content can be structured. `,\n ),\n label: z.array(z.string()).optional(),\n parentID: z.string().optional().meta({\n description: 'The ID of the parent task which created this subtask on a lower stack level',\n }),\n priorID: z.string().optional().meta({\n description: 'The ID of the previous task in the same stack level.',\n }),\n // TODO: validate this ID using our content address creation functions\n id: z.string(),\n authorId: z.string().optional(),\n created_at: z.number().optional(),\n acl: z.string().array().optional()\n .describe(`A number of public keys which act as access control lists (ACL).\nThey are given certain as a list of public keys + type of ownership.\n [\"pubkey:owner\", \"pubkey:editor1\", \"pubkey:editor2\"]\n\n The value is optional. If no ACL is specified, the task is \"public\" and\n can for example be freely exchange in p2p settings.\n\nTODO: define onwership types..`),\n sig: z.string().optional().meta({\n description:\n 'A signature from the author of the Task. It is created from the entire content of the tasj except for the signature itself.',\n }),\n})\nexport type TaskNode = z.infer<typeof TaskNode>\n\nexport const partialTaskDraft = TaskNode.partial().required({ role: true, content: true }).meta({\n description:\n 'This is just a subset of the task properties which can be used to define new tasks in various places.',\n})\nexport type partialTaskDraft = z.infer<typeof partialTaskDraft>\n\n// If you want to map them to { label, value } for q-select:\nexport const taskTypeOptions = TaskContent.options.map((opt) => {\n // each option is a ZodObject with a `type` literal\n return opt.shape.type._zod.def.values[0]!\n})\n\n// TODO: the goal should be to slowly replace this state by the \"result of the task\"\n// E.g. when a task had an error, this would be represented in the task result as an \"error\"\nconst TaskState = z.enum(['Open', 'Queued', 'In Progress', 'Completed', 'Cancelled', 'Error'])\n .describe(`The task state indicates on what is happening with the task: for example\nit shows whether a task flow is seen as \"completed\" or whether its waiting\nto be further processed... E.g. there could be a task with no results, which stil counts as \"completed\"`)\nexport type TaskState = z.infer<typeof TaskState>\n\n// Now pull out the tooldefinition variant and fully expand it:\n/*type ToolDefinitionNode = ExpandRecursively<\n Omit<TaskNode, 'content'> & {\n content: Extract<TaskNode['content'], { type: 'tooldefinition' }>\n }\n>*/\n\n/*type ToolDefinitionNode = TaskNode extends { content: infer C }\n ? C extends { type: 'tooldefinition' }\n ? Expand<Omit<TaskNode, 'content'> & { content: C }>\n : never\n : never*/\n\n// 2. Generic extractor by content.type\nexport type TaskNodeType<K extends TaskNode['content']['type']> = TaskNode extends {\n content: infer C\n}\n ? C extends { type: K }\n ? Expand<Omit<TaskNode, 'content'> & { content: C }>\n : never\n : never\n/*\n// 3. Example usages\ntype ToolDefNode = TaskNodeType<\"tooldefinition\">\ntype MessageNode = TaskNodeType<\"message\">\ntype ToolResultNode = TaskNodeType<\"toolresult\">\n*/\n\nexport type TaskGetter = (input: string) => Promise<TaskNode | null>\n\nexport type FileMapping = {\n id: string\n name?: string\n size?: number\n // filename in opfs\n opfs?: string\n openAIFileId?: string\n // TODO: we're not sure if we need a file path?\n type: string\n // sometimes, for very small files, it might make sense to attach the data here directly?\n data?: string\n}\n\nexport interface TaskTreeNode {\n task: TaskNode\n children: TaskTreeNode[][]\n}\n","export function uint8ArrayToBase64UrlSafe(data: Uint8Array | ArrayBuffer) {\n const u8 = data instanceof Uint8Array ? data : new Uint8Array(data)\n let binary = ''\n for (let i = 0; i < u8.length; i++) {\n binary += String.fromCharCode(u8[i]!)\n }\n return btoa(binary)\n .replace(/\\+/g, '-') // Convert '+' to '-'\n .replace(/\\//g, '_') // Convert '/' to '_'\n .replace(/=+$/, '') // Remove trailing '='\n}\n\nexport function base64UrlToUint8Array(base64UrlString: unknown): Uint8Array<ArrayBuffer> {\n if (typeof base64UrlString !== 'string') {\n throw new TypeError('Expected base64UrlString to be a string')\n }\n const padding = '='.repeat((4 - (base64UrlString.length % 4)) % 4)\n const base64 = base64UrlString.replace(/-/g, '+').replace(/_/g, '/') + padding\n\n const binaryString = atob(base64)\n const len = binaryString.length\n const arr = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n arr[i] = binaryString.charCodeAt(i)\n }\n // re-wrap ensures it's `ArrayBuffer`, not `ArrayBufferLike`\n return new Uint8Array(arr)\n}\n\nexport async function sha256UrlSafeHash(obj: unknown) {\n const json = JSON.stringify(obj)\n const encoder = new TextEncoder()\n const data = encoder.encode(json)\n\n const hashBuffer = await crypto.subtle.digest('SHA-256', data)\n return uint8ArrayToBase64UrlSafe(hashBuffer)\n}\n\nexport async function sha256UrlSafeHashFromFile(file: File): Promise<string> {\n const buffer = await file.arrayBuffer()\n const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)\n return uint8ArrayToBase64UrlSafe(hashBuffer)\n}\n","import type z from 'zod'\nimport type { partialTaskDraft } from '../types/node'\nimport { TaskNode } from '../types/node'\nimport { sha256UrlSafeHash } from '../utils/encoding'\n\nconst TaskWithoutId = TaskNode.omit({ id: true }).strip()\nexport type TaskWithoutId = z.infer<typeof TaskWithoutId>\n\nfunction normalizeObj<T extends Record<string, unknown>>(task: T): T {\n // deep clone plain JSON-compatible values\n const clone: T = JSON.parse(JSON.stringify(task))\n\n // enforce alphabetical key order\n const sorted = Object.keys(clone)\n .sort()\n .reduce((acc, key) => {\n acc[key as keyof T] = clone[key as keyof T]\n return acc\n }, {} as T)\n\n return sorted\n}\n\nasync function taskContentHash(\n task: partialTaskDraft,\n): Promise<{ hash: string; normalized: TaskWithoutId }> {\n if (typeof crypto === 'undefined' || !crypto.subtle) {\n throw new Error(\n 'crypto.subtle is not available in this environment, We can currently not generate task IDs!!',\n )\n }\n\n console.log('generating new hash ID for task')\n // we need to verify that our task is of type TaskNode without ID and we do this using Zod :)\n // we also want to make sure, that we only strip away anything which isn't official\n // part of our tasknode..\n const taskWithoutId = TaskWithoutId.parse(task)\n const normalized = normalizeObj(taskWithoutId)\n // generate this hash ID to check of there are any duplicate tasks or anything like that...\n const hash = await sha256UrlSafeHash(normalized)\n return { hash, normalized }\n}\n\nexport async function ensureValidTaskId(task: partialTaskDraft): Promise<TaskNode> {\n const { hash, normalized } = await taskContentHash(task)\n if (task.id && hash !== task.id) {\n throw new Error(\n `Not able to create new task as id doesn't match content. Expected: ${hash} got: ${task.id}.`,\n )\n }\n return { ...normalized, id: hash } as TaskNode\n}\n\n// the following function can be used to calculate Ids for an entire\n// chain.\nexport const forgeTaskChain = async (tasks: partialTaskDraft[][]) => {\n const flattened: TaskNode[] = []\n for (const tl of tasks) {\n let lastTaskId: string | undefined = undefined\n for (const t of tl) {\n const task = await createTaskNode({ ...t, priorID: lastTaskId }, { createMeta: 'missing' })\n lastTaskId = task.id\n flattened.push(task)\n }\n }\n return flattened\n}\n\nfunction addTaskNodeMeta(\n options: { createMeta?: 'missing' | 'overwrite' | undefined },\n task: partialTaskDraft,\n): partialTaskDraft {\n const next = { ...task }\n if (options.createMeta === 'overwrite') {\n next.created_at = Date.now()\n }\n if (options.createMeta !== undefined && !next.created_at) {\n next.created_at = Date.now()\n }\n return next\n}\n\nexport const createTaskNode = async (\n task: partialTaskDraft,\n options: {\n createMeta?: 'missing' | 'overwrite' | undefined\n } = { createMeta: 'missing' },\n): Promise<TaskNode> => {\n // if task already has an id, do nothing and only ensure, that the id is valid!\n if (!task.id) {\n // TODO: add task signature and other metadata here as well\n const newTask = addTaskNodeMeta(options, task)\n return ensureValidTaskId(newTask)\n }\n return ensureValidTaskId(task)\n}\n","import type { JSONSchema, FromSchema } from 'json-schema-to-ts'\nimport z from 'zod'\nimport type { WithRequired } from '../utils/tsHelpers'\nimport { partialTaskDraft, type TaskNode } from './node'\nimport type { FunctionCall } from './tools'\nimport { ToolBase, taskMarker } from './tools'\n\n/**\n * Represents the context passed to tools within the Taskyon system.\n *\n * @property taskChain - The sequence of TaskNode objects representing the current chain of tasks.\n * @property getSecret - Retrieves a secret value by name. If `askNew` is `true`, prompts for a new secret if it doesn't exist.\n * If `askNew` is a string, uses the string as a custom message or hint when prompting for the secret.\n * @param name - The name of the secret to retrieve.\n * @param askNew - If `true`, prompts for a new secret if not found. If a string, uses it as a hint or message when prompting.\n * @returns A promise resolving to the secret value, or `undefined` if not found.\n *\n * @property setSecret - Stores a secret value by name.\n * @param name - The name of the secret to store.\n * @param value - The secret value to store.\n * @returns A promise that resolves when the secret is stored.\n * @property stopSignal - An AbortSignal that can be used to detect if the tool should stop execution.\n * @property toolId - The unique identifier for the tool instance.\n */\nexport type toolContext = {\n taskChain: TaskNode[]\n getSecret: (name: string, askNew: boolean | string, saveNew?: boolean) => Promise<string | null>\n setSecret: (name: string, value: string) => Promise<void>\n stopSignal: AbortSignal\n toolId: string\n messagePort?: MessagePort // optional message port for communication\n}\n\n// TODO: make all of this generic functions in order to get better typescript checking\nconst internalToolFunctionSchema = z.custom<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (params: any, context: toolContext) => unknown // unknown also includes Promise<unknown>\n>((val) => typeof val === 'function', {\n message: 'Expected a function that accepts any arguments and returns unknown or Promise<unknown>',\n})\nexport type internalToolFunctionSchema = z.infer<typeof internalToolFunctionSchema>\n\nconst InternalTool = ToolBase.extend({\n // TODO: take away he \"optional\" from this type here...\n function: internalToolFunctionSchema.optional(),\n}).meta({\n description: 'Internal tool definition, which has access to the taskyon system',\n})\nexport type InternalTool = z.infer<typeof InternalTool>\n\nexport type ClientTool = WithRequired<InternalTool, 'function'>\n\n// Create a helper function to preserve schema types\nexport function createTool<T, SCHEMA extends Readonly<JSONSchema>, PARAMS = FromSchema<SCHEMA>>(\n tool: T & {\n parameters: SCHEMA\n function?: (params: PARAMS, context: toolContext) => unknown\n } & Omit<InternalTool, 'function' | 'parameters'>,\n): T {\n console.log('create tool', tool.name)\n return tool\n}\n\n// TODO: automatically type the FunctionCall correctly using the\n// json definition from a tool :)\nexport function toolCall<T extends FunctionCall['arguments']>(\n f: { arguments: T } & FunctionCall,\n): partialTaskDraft & { content: { type: 'functioncall'; data: FunctionCall } } {\n return {\n role: 'function',\n content: {\n type: 'functioncall',\n data: f,\n },\n }\n}\n\nexport const taskResult = z.object({\n taskResultMarker: z.literal(taskMarker).default(taskMarker).meta({\n description:\n 'we use this marker in order to indicate that the result should be added as new tasks!',\n }),\n taskChainList: z.array(z.array(partialTaskDraft)),\n})\nexport type taskResult = z.infer<typeof taskResult>\n\nexport function makeTaskResult(\n tasks: partialTaskDraft | partialTaskDraft[] | partialTaskDraft[][],\n): taskResult {\n let tasksArray: partialTaskDraft[][]\n if (Array.isArray(tasks)) {\n if (Array.isArray(tasks[0])) {\n // Already a 2D array\n tasksArray = tasks as partialTaskDraft[][]\n } else {\n // 1D array, wrap in another array\n tasksArray = [tasks as partialTaskDraft[]]\n }\n } else {\n // 0D, wrap in 2D array\n tasksArray = [[tasks]]\n }\n tasks = tasksArray\n return {\n taskResultMarker: taskMarker,\n taskChainList: tasks,\n }\n}\n","import z from 'zod'\nimport { FunctionArguments } from './tools'\n\nconst RemoteFunctionBase = z.object({\n functionName: z.string().meta({\n description: 'the name of the function',\n }),\n})\n\nexport const RemoteFunctionCall = RemoteFunctionBase.extend({\n type: z.literal('functionCall').meta({\n description: 'Field to indicate what kind of a message we have here.',\n }),\n arguments: FunctionArguments.optional().meta({\n description: 'the arguments for the function as a json object',\n }),\n}).meta({\n description:\n 'This type is used for sending messages with function calls between windows. E.g. from iframe to parent',\n})\nexport type RemoteFunctionCall = z.infer<typeof RemoteFunctionCall>\n\nexport const RemoteFunctionResponse = RemoteFunctionBase.extend({\n type: z.literal('functionResponse').meta({\n description: 'Field to indicate what kind of a message we have here.',\n }),\n response: z.unknown().optional().meta({\n description: 'response of a FunctionCall, e.g. through postMessage with iframes.',\n }),\n error: z\n .unknown()\n .optional()\n .meta({ description: 'if an error occurs in the remote function, we can use this property' }),\n}).meta({\n description:\n 'This type is used for sending messages with the result of a remote function call between windows. E.g. from parent to taskyon iframe',\n})\nexport type RemoteFunctionResponse = z.infer<typeof RemoteFunctionResponse>\n","import { z } from 'zod'\nimport { sha256UrlSafeHashFromFile } from '../utils/encoding'\nimport type { ByType } from '../utils/tsHelpers'\nimport { RemoteFunctionCall, RemoteFunctionResponse } from './messages'\nimport { partialTaskDraft, TaskNode } from './node'\nimport { ToolBase } from './tools'\n\n// TODO: most of the messages here should have an equivalent encrypted version!\n\n// TODO: merge this with \"taskCreated\" message!\nexport const EncryptedTasks = z.object({\n type: z.literal('addTasks'),\n data: z.instanceof(Uint8Array<ArrayBuffer>) as z.ZodType<Uint8Array<ArrayBuffer>>,\n info: z.string(),\n ids: z.array(z.string()),\n})\n\nexport const RequestTask = z.object({\n type: z.literal('requestTask'),\n id: z.string(),\n})\n\nexport const TaskCreated = z.object({\n type: z.literal('taskCreated'),\n task: TaskNode.optional(),\n // TODO: add optional encrypted task!\n ids: z.array(z.string()).optional(),\n info: z.string().optional(),\n})\n\nconst TaskMessage = z\n .object({\n type: z.literal('task').meta({\n description: 'Field to indicate what kind of a message we have here.',\n }),\n task: partialTaskDraft,\n // TODO: we don't need this anymore.. any functioncall task is one that should be \"executed\"\n execute: z.boolean().default(false).meta({\n description: 'should the task be queued for execution?',\n }),\n /* TODO: this needs to be captured in the frontend somehow!\n // but we first add it to the tasks and get back a content ID in the backend.\n // so not sure yet how to do this...The backend soehow would have to communicate this to the frontend..\n // maybe we could do this through teh \"back-channel?\"*/\n show: z.boolean().default(false).meta({\n description: 'select the task in the GUI',\n }),\n })\n .meta({\n description:\n 'With this message type we can send tasks to taskyon from outside, e.g. a parent to a taskyon iframe',\n })\n\n// merge this with \"TaskMessage\"\nconst TaskChainMessage = z.object({\n type: z.literal('tasks').meta({\n description: 'Field to indicate what kind of a message we have here.',\n }),\n execute: z.boolean().default(false),\n tasks: partialTaskDraft.array(),\n show: z.boolean().default(false).meta({\n description: 'select the last task in the GUI',\n }),\n})\n\nconst FunctionDescriptionMessage = ToolBase.extend({\n type: z.literal('functionDescription').meta({\n description: 'Field to indicate that this is a function description message.',\n }),\n})\n\nconst TyReadyMessage = z.object({ type: z.literal('taskyonReady') }).meta({\n description: 'simple message which signals, that our API is ready!',\n})\n\nexport const BaseMessage = z.object({\n origin: z.string().optional(),\n peerId: z.string().optional(),\n})\n\nconst TyStatusMessage = z\n .object({\n type: z.literal('status'),\n data: z.object({\n type: z.literal('newtool'),\n id: z.string().meta({ description: 'id of new tool' }),\n }),\n })\n .meta({ description: 'A list of status message for taskyon' })\n\nexport const TaskWorkerMessage = z.discriminatedUnion('type', [\n z.object({ ...BaseMessage.shape, ...RemoteFunctionCall.shape }),\n z.object({ ...BaseMessage.shape, ...RemoteFunctionResponse.shape }),\n])\nexport type TaskWorkerMessage = z.infer<typeof TaskWorkerMessage>\n\n// File message\nexport const FileMessage = z.object({\n type: z.literal('file'),\n id: z.string(),\n name: z.string(),\n mime: z.string(),\n size: z.number(),\n store: z.enum(['memory', 'opfs']).optional(),\n file: z.file(), // only supported over MessageChannel for now\n})\nexport type FileMessage = z.infer<typeof FileMessage>\n\nexport const TyP2P = z.discriminatedUnion('type', [EncryptedTasks, RequestTask, TaskCreated])\nexport type TyP2P = z.infer<typeof TyP2P>\n\nexport const TyBusMessage = z.discriminatedUnion('type', [\n ...TyP2P.options,\n z.object({ ...BaseMessage.shape, ...TyStatusMessage.shape }),\n ...TaskWorkerMessage.options,\n])\n\nexport const TaskyonMessage = z.discriminatedUnion('type', [\n // TODO: can we unify the task message with the SyncApi?\n ...TyBusMessage.options,\n z.object({ ...BaseMessage.shape, ...TaskMessage.shape }),\n z.object({ ...BaseMessage.shape, ...TaskChainMessage.shape }),\n z.object({ ...BaseMessage.shape, ...FunctionDescriptionMessage.shape }),\n z.object({ ...BaseMessage.shape, ...TyReadyMessage.shape }),\n z.object({ ...BaseMessage.shape, ...FileMessage.shape }),\n])\n\n// If you want to map them to { label, value } for q-select:\n/*export const messageTypes = TaskyonMessage.options.map((opt) => {\n // each option is a ZodObject with a `type` literal\n return opt.shape.type._zod.def.values[0]!\n})*/\n\nexport type TaskyonMessage = z.infer<typeof TaskyonMessage>\nexport type messageTypes = TaskyonMessage['type']\n\nexport const sendFile =\n (send: (msg: ByType<'file', TaskyonMessage>) => void) => async (file: File) => {\n const id = await sha256UrlSafeHashFromFile(file)\n send({\n type: 'file',\n id,\n name: file.name,\n mime: file.type,\n size: file.size,\n file,\n })\n return id\n }\n","// frpBus.ts\nimport type { z } from 'zod'\n\n/**\n * Functional Reactive Programming (FRP) Bus\n * A simple implementation of an FRP bus using streams and operators.\n * This is a basic implementation and can be extended with more operators as needed.\n */\nexport type Observer<T> = (value: T) => void | Promise<void>\nexport type Unsubscribe = () => void\n\nexport interface Stream<T> {\n (observer: Observer<T>): Unsubscribe\n unsubscribeAll(this: void): void\n filter(this: void, predicate: (value: T) => boolean): Stream<T>\n narrow<U extends T>(this: void, predicate: (value: T) => value is U): Stream<U>\n map<V>(this: void, fn: (value: T) => V): Stream<V>\n wait(this: void, opts: { timeoutMs?: number; signal?: AbortSignal }): Promise<T>\n}\n\nexport type frpBus<T> = {\n stream: Stream<T>\n emit: <U extends T>(value: U) => void\n}\n\n// Creates a simple stream with an \"emit\" function\nexport function createStream<T>(): frpBus<T> {\n const observers: Observer<T>[] = []\n\n const stream = (observer: Observer<T>): Unsubscribe => {\n observers.push(observer)\n return () => {\n const idx = observers.indexOf(observer)\n if (idx >= 0) observers.splice(idx, 1)\n }\n }\n\n stream.unsubscribeAll = () => {\n observers.length = 0\n }\n\n // TODO: if we use a filter like that... how can we make sure, that we unsubscribe from the original\n // stream, if we unsubscrbe from the new stream (unsub)? we might want to have multiple\n // streams subscribing on the filtered, so we can't jsut do it from the last \"unsub\" in the chain...\n // maybe add an \"unsubchain\" or something like that?\n stream.narrow = <U extends T>(pred: (m: T) => m is U) => {\n const newStream = createStream<U>()\n /*const unsub = */ stream((v) => {\n if (pred(v)) newStream.emit(v)\n })\n return newStream.stream\n }\n stream.map = <V>(fn: (value: T) => V): Stream<V> => {\n const newStream = createStream<V>()\n stream((v) => newStream.emit(fn(v)))\n return newStream.stream\n }\n stream.filter = stream.narrow<T>\n stream.wait = ((opts) =>\n new Promise<T>((resolve, reject) => {\n if (opts?.signal?.aborted) {\n const err = new Error('Aborted')\n err.name = 'AbortError'\n reject(err)\n return\n }\n\n let done = false\n let timeout: ReturnType<typeof setTimeout> | undefined\n let unsub: Unsubscribe = () => {}\n\n const finish = (err?: Error, value?: T) => {\n if (done) return\n done = true\n unsub()\n clearTimeout(timeout)\n opts?.signal?.removeEventListener('abort', onAbort)\n if (err) reject(err)\n else resolve(value!)\n }\n\n const onAbort = () => {\n const err = new Error('Aborted')\n err.name = 'AbortError'\n finish(err)\n }\n\n opts?.signal?.addEventListener('abort', onAbort)\n if (opts?.timeoutMs)\n timeout = setTimeout(\n () => finish(new Error(`Timeout after ${opts.timeoutMs}ms`)),\n opts.timeoutMs,\n )\n\n const observer = (value: T) => finish(undefined, value)\n unsub = stream(observer)\n })) as Stream<T>['wait']\n\n return {\n stream,\n emit: (v: T) => {\n ;[...observers].forEach((o) => void o(v))\n },\n }\n}\n\n// extract stream type frm existing stream\nexport type extractStreamType<Type> = Type extends Stream<infer X> ? X : never\n\nexport type Port<Tx, Rx = Tx> = {\n send: frpBus<Tx>['emit']\n receive: frpBus<Rx>['stream']\n // stricter connect signature: intersection forces compile-time failure when constraints don't hold\n connect: <Tx, Rx extends oTx, oTx, oRx extends Tx>(\n this: Port<Tx, Rx>,\n other: Port<oTx, oRx>,\n ) => Unsubscribe\n}\n\nexport type DuplexChannel<Tx, Rx> = { x: Port<Tx, Rx>; y: Port<Rx, Tx> }\n\nconst connectChannels = <Tx, Rx, oTx, oRx>(x: Port<Tx, Rx>, y: Port<oTx, oRx>): Unsubscribe => {\n const unsubX = x.receive((msg) => y.send(msg as unknown as oTx))\n const unsubY = y.receive((msg) => x.send(msg as unknown as Tx))\n\n // Return a function that disconnects both subscriptions\n return () => {\n unsubX()\n unsubY()\n }\n}\n\nconst makePort = <Tx, Rx = Tx>(\n send: frpBus<Tx>['emit'],\n receive: frpBus<Rx>['stream'],\n): Port<Tx, Rx> => {\n const self: Port<Tx, Rx> = {\n send,\n receive,\n connect: (other) => connectChannels(self, other),\n }\n return self\n}\n\nexport const createChannelsFromStreams = <Str1, Str2 = Str1>(\n outS: frpBus<Str1>,\n inS: frpBus<Str2>,\n): DuplexChannel<Str1, Str2> => ({\n x: makePort(outS.emit, inS.stream),\n y: makePort(inS.emit, outS.stream),\n})\n\nexport const createDuplexChannel = <Str1, Str2 = Str1>(): DuplexChannel<Str1, Str2> =>\n createChannelsFromStreams(createStream<Str1>(), createStream<Str2>())\n\nexport function MessageChannelBridge<Tx, Rx = Tx>(dport: Port<Tx, Rx>, mport: MessagePort) {\n const unsub = dport.receive((msg) => mport.postMessage(msg))\n mport.onmessage = (msg) => dport.send(msg.data)\n\n const destroy = () => {\n unsub()\n mport.close()\n }\n\n return { destroy }\n}\n\n/* TODO: adapt this by createing a port which\nexport function portMap<A, B>(\n source: Port<A>,\n fnIn: (value: A) => B,\n fnOut: (value: B) => A,\n): { port: Port<B>; destroy: () => void } {\n const { a: inner, b: outer } = createDuplexChannel<B>()\n\n // Upstream ➜ child (apply the filter)\n const unsubUp = source.receive((m) => {\n inner.send(fnIn(m)) // safe: guard proved it’s TChild\n })\n\n // Child ➜ upstream (no filtering needed)\n const unsubDown = inner.receive((m) => source.send(fnOut(m)))\n\n const destroy = () => {\n unsubUp()\n unsubDown()\n }\n\n return { port: outer, destroy }\n}*/\n\nexport function mapPort<pTx, pRx, cTx extends pTx, cRx extends pRx>(\n port: Port<pTx, pRx>,\n transformTx: (msg: pTx) => cTx,\n transformRx: (msg: pRx) => cRx,\n): { port: Port<cTx, cRx>; destroy: () => void } {\n const { x: filtered, y: internal } = createDuplexChannel<cTx, cRx>()\n\n // Upstream ➜ child (apply the filter)\n const unsubUp = port.receive((m) => {\n internal.send(transformRx(m)) // safe: guard proved it’s TChild\n })\n\n // Child ➜ upstream (no filtering needed)\n const unsubDown = internal.receive((m) => {\n port.send(transformTx(m)) // safe: guard proved it’s TChild\n })\n\n const destroy = () => {\n unsubUp()\n unsubDown()\n }\n\n return { port: filtered, destroy }\n}\n\nexport function createPortFilter<pTx, pRx, cTx extends pTx, cRx extends pRx>(\n port: Port<pTx, pRx>,\n filterTx: (msg: pTx) => msg is cTx,\n filterRx: (msg: pRx) => msg is cRx,\n): { port: Port<cTx, cRx>; destroy: () => void } {\n const { x: filtered, y: internal } = createDuplexChannel<cTx, cRx>()\n\n // Upstream ➜ child (apply the filter)\n const unsubUp = port.receive((m) => {\n if (filterRx(m)) internal.send(m) // safe: guard proved it’s TChild\n })\n\n // Child ➜ upstream (no filtering needed)\n const unsubDown = internal.receive((m) => {\n if (filterTx(m)) port.send(m) // safe: guard proved it’s TChild\n })\n\n const destroy = () => {\n unsubUp()\n unsubDown()\n }\n\n return { port: filtered, destroy }\n}\n\n// lets through messages which are in a list of types...\nexport function createTypeFilteredPort<\n pTx, // Parent Transmit type\n pRx extends { type: string }, // Parent Receive type (the superset union)\n K extends pRx['type'], // An array of keys from the union's 'type' property\n>(\n parent: Port<pTx, pRx>,\n allowedTypes: readonly K[],\n): { port: Port<pTx, Extract<pRx, { type: K }>>; destroy: () => void } {\n // Use a Set for efficient O(1) lookups inside the guard.\n const typeSet = new Set(allowedTypes)\n\n // Define the new, narrower child message type using TypeScript's Extract utility.\n // This extracts all members from the `pRx` union whose `type` property matches one\n // of the strings in the `allowedTypes` array (`T[number]`).\n type cRx = Extract<pRx, { type: K }>\n // Reuse the generic filtered-port helper with a custom type guard.\n return createPortFilter(\n parent,\n (msg): msg is pTx => true,\n (msg): msg is cRx => typeSet.has(msg.type as K),\n )\n}\n\n/** Generic message → handler router (sync or async) */\nexport function createPortApi<\n R,\n Schema extends z.ZodType<{ type: string }>, // your Zod schema\n Msg extends z.infer<Schema>, // union type + discriminator\n Tx,\n Rx = Tx,\n>(\n port: Port<Tx, Rx>,\n schema: Schema,\n handlers: {\n [K in Msg['type']]?: (m: Extract<Msg, { type: K }>) => R | Promise<R>\n },\n defaultHandler?: (m: unknown) => void,\n errorHandler?: (m: unknown) => void,\n) {\n port.receive((raw) => {\n const parsed = schema.safeParse(raw)\n if (!parsed.success) {\n console.error('Invalid message:', parsed.error, raw)\n return\n }\n\n const msg = parsed.data as Msg\n const handle = handlers[msg.type as Msg['type']]\n if (!handle) {\n if (defaultHandler) defaultHandler(msg)\n return\n }\n\n // 1️⃣ Re-narrow the union to the specific variant for this handler\n type Specific = Extract<Msg, { type: typeof msg.type }>\n\n // 2️⃣ Call the handler; Promise.resolve normalises sync/async, catch logs errors\n void Promise.resolve(handle(msg as Specific)).catch((error) => {\n if (errorHandler) errorHandler(error)\n })\n })\n}\n\n/**\n * Merges streams of different types into a single stream emitting a union type.\n * Usage: merge(streamA, streamB) → Stream<A | B>\n */\nexport function merge<T extends unknown[]>(\n ...sources: { [K in keyof T]: Stream<T[K]> }\n): Stream<T[number]> {\n const { stream, emit } = createStream<T[number]>()\n\n sources.forEach((source) => {\n void source((value) => emit(value)) // Full type safety\n })\n\n return stream\n}\n\nexport function requireSubscribers<T>(source: Stream<T>, min: number = 1): Stream<T> {\n const { stream, emit } = createStream<T>()\n let subscriberCount = 0\n\n // Subscribe to the source stream\n void source((value) => {\n if (subscriberCount < min) {\n throw new Error(`Not enough subscribers: got ${subscriberCount}, need at least ${min}`)\n }\n emit(value)\n })\n\n const subscribe = (observer: Observer<T>) => {\n subscriberCount++\n const unsubscribe = stream(observer)\n return () => {\n subscriberCount--\n void Promise.resolve(unsubscribe).then((resolvedUnsubscribe) => resolvedUnsubscribe())\n }\n }\n subscribe.unsubscribeAll = () => {\n stream.unsubscribeAll()\n subscriberCount = 0\n }\n subscribe.narrow = stream.narrow\n subscribe.filter = stream.narrow<T>\n subscribe.wait = stream.wait\n subscribe.map = stream.map\n\n return subscribe\n}\n\nexport function streamProcedureCall<T extends unknown[], R>(timeoutMs?: number) {\n const { stream, emit } = createStream<{\n args: T\n respond: (result: R) => void\n }>()\n\n const emitFunc: (...args: T) => Promise<R> = (...args) => {\n return new Promise<R>((resolve, reject) => {\n let responded = false\n let timeout: ReturnType<typeof setTimeout> | undefined\n // Set up timeout for default or error\n if (timeoutMs !== undefined) {\n timeout = setTimeout(() => {\n if (!responded) {\n responded = true\n // TODO: add default response here...\n reject(new Error('No response within timeout'))\n }\n }, timeoutMs)\n }\n console.log('Emitting args:', args)\n emit({\n args,\n respond: (result: R) => {\n if (!responded) {\n responded = true\n if (timeout) clearTimeout(timeout)\n resolve(result)\n }\n },\n })\n })\n }\n\n return { emitFunc, stream: requireSubscribers(stream, 1) }\n}\n\n// ---- MessagePort <-> FRP bridge ------------------------------------------\n\nexport interface PortBridge<T> {\n /** Stream that mirrors everything coming from the external port */\n stream: Stream<T>\n /** Post into the bus (will also be forwarded to the external port) */\n emit: (value: T) => void\n /** Give this to the iframe (or whatever) */\n port: MessagePort\n /** Cleanup listener, subscription & ports */\n destroy: () => void\n}\n\n/**\n * Creates a MessageChannel and wires one side into a new FRP stream.\n * - Anything the iframe posts arrives on `stream`\n * - Anything you `emit` (or any subscriber emits back into this stream) is posted out to the iframe\n */\nexport function createMessagePortBridge<T>(): PortBridge<T> {\n const { stream, emit } = createStream<T>()\n const { port1, port2 } = new MessageChannel()\n\n // Internal (hidden) side\n port2.start()\n const onMsg = (e: MessageEvent<T>) => emit(e.data)\n port2.addEventListener('message', onMsg)\n\n // Forward stream values out to the external side\n const unsub: Unsubscribe | Promise<Unsubscribe> = stream((v) => {\n // Structured clone is required; assume T is cloneable.\n port2.postMessage(v)\n })\n\n const destroy = () => {\n unsub()\n port2.removeEventListener('message', onMsg)\n port1.close()\n port2.close()\n }\n\n return { stream, emit, port: port1, destroy }\n}\n\nexport function createMessagePortAdapter<T>(stream: Stream<T>) {\n const { port1, port2 } = new MessageChannel()\n\n // Internal (hidden) side\n port2.start()\n // Forward stream values out to the external side\n const unsub: Unsubscribe = stream((v) => {\n // Structured clone is required; assume T is cloneable.\n port2.postMessage(v)\n })\n\n const destroy = () => {\n unsub()\n port1.close()\n port2.close()\n }\n\n return { port: port1, destroy }\n}\n\n// ---- Simple IFrame <-> FRP adapter ---------------------------------------\n\nexport function iframeBridge(\n iframe: HTMLIFrameElement,\n origin: string | null = null, // pass null to skip origin check\n) {\n const win = iframe.contentWindow\n if (!win) throw new Error('iframe has no contentWindow')\n\n const inferred = iframe.src ? new URL(iframe.src, window.location.href).origin : 'null' // about:srcdoc\n const expectedOrigin = origin === undefined ? inferred : origin\n const checkOrigin = expectedOrigin !== null\n\n const { stream, emit } = createStream<unknown>()\n\n const onMessage = (ev: MessageEvent<unknown>) => {\n if (ev.source !== win) return\n if (checkOrigin && ev.origin !== expectedOrigin) return\n emit(ev.data)\n }\n window.addEventListener('message', onMessage)\n\n const post = (msg: unknown) => {\n // If iframe navigated, silently drop\n if (iframe.contentWindow === win) {\n win.postMessage(msg, expectedOrigin ?? '*')\n }\n }\n\n const destroy = () => window.removeEventListener('message', onMessage)\n\n return { stream, emit: post, destroy }\n}\n\n// ---- IFrame Multiplexer --------------------------------------------------\n\nexport type BusMsg<I extends string | number | symbol = string> = { id: I; payload: unknown }\n\nexport type TaskMessageStream = Stream<BusMsg>\n\ninterface Entry {\n ref: WeakRef<HTMLIFrameElement>\n post: (m: unknown) => void\n}\n\n// TODO: add a \"bus\" to the iframe...\n/**\n * Create a multiplexer for bidirectional messaging between the host window\n * and multiple managed iframes. Each iframe is registered under an identifier,\n * and incoming `postMessage` events are routed to a typed stream keyed by id.\n *\n * Features:\n * - `attachIframe(id, iframe, origin?)`: register an iframe with a unique id.\n * - Tracks the iframe with a `WeakRef`, cleaned up automatically if removed.\n * - Determines expected origin from the iframe's `src` unless overridden.\n * - `send(id, msg)`: post a message to the iframe associated with `id`.\n * - Messages are dropped if the iframe is disconnected or garbage collected.\n * - `all$`: a reactive stream of all incoming messages of the form `{ id, payload }`.\n * - Automatic garbage collection:\n * - Uses `WeakRef` + `WeakMap` to avoid leaks.\n * - Periodically sweeps stale entries after `sweepEvery` attaches.\n * - Falls back to manual `gc()` to force a sweep.\n * - `detachId(id)`: manually detach an iframe by id.\n * - `destroy()`: stop listening to window `message` events and clear state.\n *\n * Notes:\n * - `winToId` is a `WeakMap` → iframe window references do not prevent GC.\n * - Origins:\n * - If the iframe has `srcdoc` or `about:srcdoc`, origin is `\"null\"` and messages\n * are sent with target `\"*\"`.\n * - Otherwise the origin is inferred from the iframe `src` or overridden via `origin`.\n *\n * @param sweepEvery number of iframe attaches before scheduling a GC sweep (default: 5).\n * @returns API object: `{ all$, send, attachIframe, detachId, gc, destroy }`.\n */\nexport function createIframeMux<I extends string | number | symbol = string>(sweepEvery = 5) {\n const { stream: all$, emit } = createStream<BusMsg<I>>()\n\n const winToId = new WeakMap<Window, I>()\n const idToEntry = new Map<I, Entry>()\n let attachCountSinceSweep = 0\n\n const onMessage = (ev: MessageEvent) => {\n const id = winToId.get(ev.source as Window)\n if (!id) return\n emit({ id, payload: ev.data })\n }\n window.addEventListener('message', onMessage)\n\n const attachIframe = (id: I, iframe: HTMLIFrameElement, origin?: string) => {\n const win = iframe.contentWindow\n if (!win) throw new Error('iframe has no contentWindow')\n\n winToId.set(win, id)\n\n // Infer origin unless caller overrides. srcdoc/about:srcdoc => \"null\"\n const inferred =\n iframe.src && iframe.src !== 'about:srcdoc'\n ? new URL(iframe.src, window.location.href).origin\n : 'null'\n\n const expected = origin ?? inferred\n const postTarget = expected === 'null' ? '*' : expected\n\n const entry: Entry = {\n ref: new WeakRef(iframe),\n post: (msg: unknown) => {\n const el = entry.ref.deref()\n if (!el || el.contentWindow !== win) return // silently drop\n win.postMessage(msg, postTarget)\n },\n }\n\n idToEntry.set(id, entry)\n\n if (++attachCountSinceSweep >= sweepEvery) {\n attachCountSinceSweep = 0\n scheduleSweep()\n }\n }\n\n const send = (id: I, msg: unknown) => {\n const e = idToEntry.get(id)\n if (!e) return\n const el = e.ref.deref()\n if (!el || !el.isConnected) {\n detachId(id)\n return\n }\n e.post(msg)\n }\n\n const detachId = (id: I) => {\n idToEntry.delete(id)\n // winToId is a WeakMap → GC will clean it up\n }\n\n const sweep = () => {\n for (const [id, e] of idToEntry) {\n const el = e.ref.deref()\n if (!el || !el.isConnected) detachId(id)\n }\n }\n\n const scheduleSweep = () => {\n if ('requestIdleCallback' in window) {\n window.requestIdleCallback(sweep, { timeout: 200 })\n } else {\n setTimeout(sweep, 0)\n }\n }\n\n const gc = sweep\n\n const destroy = () => {\n window.removeEventListener('message', onMessage)\n idToEntry.clear()\n // WeakMaps auto-GC\n }\n\n return { all$, send, attachIframe, detachId, gc, destroy }\n}\n\nexport type IframeMultiPlexer<I extends string | number | symbol = string> = ReturnType<\n typeof createIframeMux<I>\n>\n","// TODO: we want to reduce dependencies to this file here!\n// TODO: maybe move the \"Api\" into its own package?\nimport { forgeTaskChain } from '../core/createTasks'\nimport type { chatCompletionParams } from '../tools/chatCompletionTool'\nimport type { TaskyonMessage } from '../types/apiTypes'\nimport type { TaskNode } from '../types/node'\nimport { partialTaskDraft } from '../types/node'\nimport { createTool, makeTaskResult, toolCall } from '../types/toolApi'\nimport { type Port } from '../utils/frpBus'\nimport type { ByType } from '../utils/tsHelpers'\n\nexport { llmSettings, TyToolchainConfig } from '../types/profiles'\nexport { BaseMessage, TyP2P, TaskyonMessage } from '../types/apiTypes'\nexport type { ClientTool } from '../types/toolApi'\nexport type { FunctionCall } from '../types/tools'\nexport {\n createDuplexChannel, // utils/frpbus\n createPortApi, // utis/frpbus\n MessageChannelBridge,\n} from '../utils/frpBus'\n\nexport { createTool, makeTaskResult, toolCall, partialTaskDraft }\nexport type { Port }\nexport type processTasksOpts = {\n timeoutMs?: number\n signal?: AbortSignal\n quitCondition?: (t: TaskNode) => boolean\n}\n\nexport const createChatCompletionTask = (args: chatCompletionParams) =>\n toolCall<chatCompletionParams>({ name: 'chatCompletion', arguments: args })\n\nexport const processTasks =\n <T extends { type: string }>(tyPort: Port<T | TaskyonMessage>) =>\n async (taskList: partialTaskDraft[][], opts: processTasksOpts) => {\n const tasks = await forgeTaskChain(taskList)\n\n tyPort.send({\n type: 'tasks',\n tasks: tasks,\n execute: true,\n show: true, // we want to show this task in our GUI as a succesful test\n origin: 'Taskyon Diagnostics',\n })\n\n const initialIds = tasks.map((t) => t.id)\n const subTasks = new Set<string>(initialIds)\n\n // filter for all subtasks\n const subTasksCreated = tyPort.receive\n .narrow((m): m is ByType<'taskCreated', TaskyonMessage> & { task: { id: string } } => {\n console.log('api received', m)\n /*const valid =\n m.type === 'taskCreated' && 'task' in m && !!m.task?.id && subTasks.has(m.task?.parentID)*/\n //console.log(valid)\n if (\n m.type === 'taskCreated' &&\n 'task' in m &&\n !!m.task?.id &&\n !!m.task?.parentID &&\n subTasks.has(m.task?.parentID)\n ) {\n subTasks.add(m.task?.id)\n return true\n }\n return false\n })\n .map((msg) => msg.task)\n\n const condition = opts.quitCondition\n ? subTasksCreated.filter(opts.quitCondition)\n : subTasksCreated.filter((t) => t.content.type === 'message')\n\n const unsub = condition((m) => console.log('received matching message on port:', m))\n const lastMsg = await condition.wait(opts)\n console.log('finished processin all tasks!')\n unsub()\n return lastMsg\n }\n","// we can compile this file to js to js using \"yarn build:lib\"\n\nimport type { FunctionCall, Port } from '@taskyon/taskyon/api'\nimport {\n // from frp bux with only very few dependencies\n createDuplexChannel, // utis/frpbus\n MessageChannelBridge, // utils/frpbus\n\n // \"processTasks\" currently has the following dependencies:\n // - immer\n processTasks, // types/apiTypes\n type ClientTool,\n type TaskyonMessage,\n} from '@taskyon/taskyon/api'\n// TODO: move this into some other part as well.. maybe into \"GUI\" types or somthing like that?\nimport type {\n partialTyConfiguration,\n TaskyonGuiMessage,\n} from '../../../src/modules/taskyon/apiTypes'\nimport { sendFile } from '../../taskyon/src/types/apiTypes'\nexport {\n createChatCompletionTask,\n createTool, // toolApi\n makeTaskResult, // toolApi\n processTasks, // api/index, types/apiTypes\n toolCall, // toolApi\n type partialTaskDraft,\n} from '@taskyon/taskyon/api'\nexport type { ClientTool, partialTyConfiguration, TaskyonGuiMessage, TaskyonMessage }\n\nfunction safeClone<T>(data: T): T {\n try {\n return structuredClone(data)\n } catch {\n return JSON.parse(JSON.stringify(data))\n }\n}\n\nconst waitForApiChannel = (iframe: HTMLIFrameElement): Promise<MessagePort> => {\n return new Promise<MessagePort>((resolve) => {\n let stopped = false\n\n const tryConnect = () => {\n if (stopped) return\n\n const channel = new MessageChannel()\n const targetOrigin = new URL(iframe.src, location.href).origin || '*' // '' for about:blank/file:\n console.log('tyclient establishing iframe communication to', targetOrigin)\n\n // self‑destructing listener – removed automatically after it fires once\n const handleFirst: (ev: MessageEvent) => void = (ev) => {\n console.log('tyclient received first message from taskyon!', ev)\n stopped = true\n\n channel.port1.removeEventListener('message', handleFirst) // ⬅️ unsubscribe\n clearTimeout(retryTimer) // stop retry loop\n resolve(channel.port1) // hand over the port\n }\n\n channel.port1.addEventListener('message', handleFirst, { once: true })\n channel.port1.start() // ← wake the port so it can receive\n\n try {\n iframe.contentWindow?.postMessage({ type: 'initPort' }, targetOrigin, [channel.port2])\n } catch {\n /* DataCloneError can happen on FF if the iframe isn’t ready yet; ignore */\n }\n\n // retry after 200 ms if handshake hasn’t happened\n const retryTimer = setTimeout(() => {\n if (!stopped) {\n channel.port1.close() // avoid leaking unused ports\n channel.port2.close()\n tryConnect()\n }\n }, 200)\n }\n\n tryConnect()\n })\n}\n\nasync function handleFunctionExecution(\n args: FunctionCall['arguments'],\n tool: ClientTool,\n stopSignal: AbortSignal,\n) {\n // with this we make sure, that we can also handle async functions :)\n const result = await tool.function(args, {\n taskChain: [],\n getSecret: (name) => {\n console.log('tyclient get secret name', name)\n return Promise.resolve('N/A')\n },\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setSecret: (name, _value) => {\n console.log('tyclient set secret name', name)\n return Promise.resolve()\n },\n stopSignal,\n toolId: 'N/A',\n })\n\n return result\n}\n\nexport interface TyClient {\n processTasks: ReturnType<typeof processTasks>\n port: Port<TaskyonGuiMessage, TaskyonGuiMessage>\n sendFile: (file: File) => Promise<string>\n}\n\nexport async function initializeTaskyon(options: {\n name?: string\n persist?: boolean\n tools: ClientTool[]\n configuration: partialTyConfiguration\n}): Promise<TyClient> {\n console.log('initialize taskyon tyclient...')\n\n const toolMap = options.tools.reduce<Record<string, ClientTool>>((p, c) => {\n p[c.name] = c\n return p\n }, {})\n\n const taskyon = document.getElementById('taskyon') as HTMLIFrameElement\n\n const controller = new AbortController()\n const { x: clientSidePort, y: towardsIframe } = createDuplexChannel<\n TaskyonGuiMessage,\n TaskyonGuiMessage\n >()\n\n if (taskyon !== null && taskyon.tagName === 'IFRAME' && taskyon.contentWindow !== null) {\n console.log('make sure, we can ')\n // TODO: detect disconnect and reconnect!\n const iframeMessagePort = await waitForApiChannel(taskyon)\n MessageChannelBridge(towardsIframe, iframeMessagePort)\n const send = (msg: TaskyonGuiMessage) => {\n console.log('tyclient sending', msg)\n clientSidePort.send(safeClone(msg))\n }\n\n console.log('tyclient send our configuration!')\n send({\n type: 'configurationMessage',\n conf: options.configuration,\n persist: options.persist,\n origin: window.location.origin,\n peerId: options?.name,\n })\n\n console.log('tyclient sending our functions!')\n options.tools.forEach((t) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { function: _toolfunc, ...fdescr } = t\n send({\n type: 'functionDescription',\n ...fdescr,\n })\n })\n\n console.log('tyclient set up function listener!')\n\n clientSidePort.receive((msg) => console.log('tyclient received message', msg))\n clientSidePort.receive.narrow((msg) => msg.type === 'functionCall')(async (msg) => {\n const tool = toolMap[msg.functionName]\n if (tool) {\n const res = await handleFunctionExecution(msg.arguments ?? {}, tool, controller.signal)\n send({ type: 'functionResponse', functionName: tool.name, response: res })\n console.log('tyclient tool send functionResponse to iframe', res, tool)\n }\n })\n }\n\n return {\n processTasks: processTasks(clientSidePort),\n port: clientSidePort,\n sendFile: (file: File) => sendFile(clientSidePort.send)(file),\n }\n}\n"]}
1
+ {"version":3,"sources":["../../taskyon/src/utils/jsonSchema.ts","../../taskyon/src/types/tools.ts","../../taskyon/src/types/node.ts","../../taskyon/src/utils/encoding.ts","../../taskyon/src/core/createTasks.ts","../../taskyon/src/types/toolApi.ts","../../taskyon/src/types/messages.ts","../../taskyon/src/types/apiTypes.ts","../../taskyon/src/utils/frpBus.ts","../../taskyon/src/api/index.ts","../src/index.ts"],"names":["z","options"],"mappings":";;;AAGA,IAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,CAAK,CAAC,QAAA,EAAU,QAAA,EAAU,SAAA,EAAW,SAAA,EAAW,QAAA,EAAU,OAAA,EAAS,MAAM,CAAC,CAAA;AAGnG,IAAM,WAAA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AA,KAKR;AACJ,MAAA,IAAA,CAAK;AAAA,QACH,IAAA,EAAM,sBAAA;AAAA,QACN,MAAMA,QAAAA,CAAQ,aAAA;AAAA,QACd,SAASA,QAAAA,CAAQ,OAAA;AAAA,QACjB,MAAA,EAAQ,OAAO,QAAA,CAAS,MAAA;AAAA,QACxB,QAAQA,QAAAA,EAAS;AAAA,OAClB,CAAA;AAAA,IACH;AAAA,GACF;AACF","file":"tyclient.mjs","sourcesContent":["import { z } from 'zod'\nimport type { JSONSchema7, JSONSchema7Definition } from 'json-schema'\n\nconst JSONSchemaEnum = z.enum(['string', 'number', 'integer', 'boolean', 'object', 'array', 'null'])\n\n// This inline transform removes keys with undefined values.\nconst JSONSchema7: z.ZodType<JSONSchema7> = z.lazy(() => JSONSchemaObjectRaw)\n\n// A JSONSchema can be a boolean or an object.\nconst JSONSchema7Definition: z.ZodType<JSONSchema7Definition> = z.lazy(() =>\n z.union([z.boolean(), JSONSchema7]),\n)\n\nconst JSONSchemaObjectRaw = z.strictObject({\n $id: z.string().optional(),\n $ref: z.string().optional(),\n $schema: z.string().optional(),\n $comment: z.string().optional(),\n type: z.union([JSONSchemaEnum, z.array(JSONSchemaEnum)]).optional(),\n const: z.any().optional(),\n enum: z.any().optional(),\n multipleOf: z.number().optional(),\n maximum: z.number().optional(),\n exclusiveMaximum: z.number().optional(),\n minimum: z.number().optional(),\n exclusiveMinimum: z.number().optional(),\n maxLength: z.number().optional(),\n minLength: z.number().optional(),\n pattern: z.string().optional(),\n items: z.lazy(() => z.union([JSONSchema7Definition, z.array(JSONSchema7Definition)]).optional()),\n additionalItems: z.lazy(() => JSONSchema7Definition.optional()),\n contains: z.lazy(() => JSONSchema7Definition.optional()),\n maxItems: z.number().optional(),\n minItems: z.number().optional(),\n uniqueItems: z.boolean().optional(),\n maxProperties: z.number().optional(),\n minProperties: z.number().optional(),\n required: z.array(z.string()).optional(),\n properties: z.lazy(() => z.record(z.string(), JSONSchema7Definition).optional()),\n patternProperties: z.lazy(() => z.record(z.string(), JSONSchema7Definition).optional()),\n additionalProperties: z.lazy(() => JSONSchema7Definition.optional()),\n unevaluatedProperties: z.lazy(() => JSONSchema7Definition.optional()),\n dependencies: z.lazy(() =>\n z.record(z.string(), z.union([JSONSchema7Definition, z.array(z.string())])).optional(),\n ),\n propertyNames: z.lazy(() => JSONSchema7Definition.optional()),\n if: z.lazy(() => JSONSchema7Definition.optional()),\n then: z.lazy(() => JSONSchema7Definition.optional()),\n else: z.lazy(() => JSONSchema7Definition.optional()),\n allOf: z.lazy(() => z.array(z.lazy(() => JSONSchema7Definition)).optional()),\n anyOf: z.lazy(() => z.array(z.lazy(() => JSONSchema7Definition)).optional()),\n oneOf: z.lazy(() => z.array(z.lazy(() => JSONSchema7Definition)).optional()),\n not: z.lazy(() => JSONSchema7Definition.optional()),\n format: z.string().optional(),\n contentMediaType: z.string().optional(),\n contentEncoding: z.string().optional(),\n definitions: z\n .record(\n z.string(),\n z.lazy(() => JSONSchema7Definition),\n )\n .optional(),\n // support Draft‑2019+ $defs\n // this is required, because the \"json-schema-to-ts\" library uses $defs and\n // we can not validate those schemas without it.\n $defs: z\n .record(\n z.string(),\n z.lazy(() => JSONSchema7Definition),\n )\n .optional(),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.any().optional(),\n readOnly: z.boolean().optional(),\n writeOnly: z.boolean().optional(),\n examples: z.array(z.any()).optional(),\n nullable: z.boolean().optional(),\n})\n\n// Extend the raw object first, then transform.\nconst JSONSchemaReferenceSchema: z.ZodType<JSONSchema7> = JSONSchemaObjectRaw.extend({\n $id: z.string(),\n})\n\nexport { JSONSchema7Definition, JSONSchemaReferenceSchema, JSONSchema7 }\n","import z from 'zod'\nimport { JSONSchema7 } from '../utils/jsonSchema'\n\nexport const taskMarker = '*TY_TASKRESULT*'\n\nconst FunctionName = z.string().refine((val) => /^[a-zA-Z0-9_-]+$/.test(val), {\n error: ({ input }) => {\n const msg = typeof input === 'string' ? input : JSON.stringify(input)\n return `The function/tool name ${msg} contains illegal characters. It has to fulfill '^[a-zA-Z0-9_-]+$'`\n },\n})\ntype FunctionName = z.infer<typeof FunctionName>\n\nexport const ParamType = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), z.unknown()),\n z.array(z.unknown()),\n z.null(),\n // We are also allowing undefined calls to the functions, even though this is not allowed in jsonschema.\n // But we are sometimes calling our functions manually and this way we can also call them without parameters.\n z.undefined(),\n])\nexport type ParamType = z.infer<typeof ParamType>\nexport const FunctionArguments = z.record(z.string(), ParamType).meta({\n description: 'arguments of the function',\n})\nexport type FunctionArguments = z.infer<typeof FunctionArguments>\n\n/* here we are essentiall declaring the taskyon API */\nexport const FunctionCall = z.object({\n name: FunctionName,\n arguments: FunctionArguments,\n})\nexport type FunctionCall = z.infer<typeof FunctionCall>\n\nexport const ToolBase = z.object({\n description: z.string().meta({\n description: 'A short description about the tool so that an LLM knows when to use it.',\n }),\n longDescription: z.string().optional().meta({\n description: 'An optional longer description for more complicated operations with this tool.',\n }),\n name: FunctionName.meta({\n description: 'Name of the tool. Has to fulfill: /^[a-zA-Z0-9_-]+$/',\n }),\n renderOptions: z\n .object({\n hideChat: z\n .boolean()\n .describe(\n \"hide the tool in the UI chat. Useful if the function is used very often and we don't want it to clutter the chatWindow\",\n ),\n hideLlm: z.boolean(\n 'HideLlm will hide the tool from an LLM inside chatCompletion. This is mainly useful for tools like \"chatCompletion\" which the llm doesn\\'t need to see in the chatCompletion.',\n ),\n })\n .partial()\n .optional(),\n parameters: JSONSchema7.meta({\n description: 'A JSON schema object describing the parameters of the function.',\n }).readonly(),\n code: z\n .string()\n .optional()\n .describe(\n `The functionality of the tool as javascript code. If a function description doesn't include any code,\nTaskyon will automatically call a postMessage event with the parameters to the parent window\nwith the function name.`,\n ),\n})\nexport type ToolBase = z.infer<typeof ToolBase> // this reflects json schema: https://json-schema.org/specification-links\n","import z from 'zod'\nimport type { Expand } from '../utils/tsHelpers'\nimport { FunctionCall, ToolBase } from './tools'\n\nexport const Annotation = z.union([\n z\n .object({\n type: z.literal('url'),\n id: z.string(),\n end_index: z.number(),\n start_index: z.number(),\n title: z.string(),\n url: z.string(),\n content: z.string(),\n })\n .partial()\n .required({ type: true }),\n z\n .object({\n type: z.literal('document'),\n text: z.string().optional(),\n content: z.string().optional(),\n })\n .partial()\n .required({ type: true }),\n])\n\nexport type Annotation = z.infer<typeof Annotation>\n\nconst MessageContent = z.object({\n type: z.literal('message'),\n data: z.string(),\n ann: Annotation.array().optional(),\n})\nconst StructuredContent = z.object({\n type: z.literal('structured'),\n data: z.unknown(),\n})\nconst ToolCallContent = z.object({ type: z.literal('functioncall'), data: FunctionCall })\nconst UploadedFilesContent = z.object({\n type: z.literal('files'),\n data: z.array(z.string()),\n})\nconst ToolResultContent = z.object({ type: z.literal('toolresult'), data: z.unknown() })\nconst ToolDefinition = z.object({ type: z.literal('tooldefinition'), data: ToolBase })\nconst ErrorContent = z.object({ type: z.literal('error'), data: z.unknown() }).meta({\n description: 'Gets created if any error occurs during task processing.',\n})\nconst Return = z.object({ type: z.literal('return'), data: z.string() }).describe(\n `A Termination task always indicates the end of an autonomous task chat execution.\nEvery Leaf task which is not a Termination task can potentially continue to be executed...\n\nWe can indicate the reason for termination here as well...`,\n)\n\n// TODO: I am not sure, if we need this here...\nconst ChatCompletionContent = z.union([MessageContent, ToolResultContent, ErrorContent])\nexport type ChatCompletionContent = z.infer<typeof ChatCompletionContent>\n\nexport const TaskContent = z.union([\n MessageContent.strict(),\n ToolResultContent.strict(),\n ToolDefinition.strict(),\n ErrorContent.strict(),\n StructuredContent.strict(),\n ToolCallContent.strict(),\n // TODO: replace with a \"context\" function which can also be a link to a URL for example or maybe a search string for other tasks...\n // we can declare function for a lot of these things this way :)\n UploadedFilesContent.strict(),\n Return.strict(),\n])\n\nexport type TaskContent = z.infer<typeof TaskContent>\nexport type TaskContentType = TaskContent extends { type: infer T } ? T : never\n\nexport const TaskNode = z.object({\n // TODO: get rid of \"role\" and put it into chatCompletion only...\n // we don't need it in the rest of the app, I think.. we might be able to indicate that a task was\n // \"automatically\" created by using a notation in \"authorID\" e.g. something like.\n // \"pubKey:gen\" if the task was automatically generated && pubKey if it wasn't\n // OR: we could simply check the parents & priors of tasks. if tasks have a parent, they were generated\n // by a function. user-generated message should not have a parent...\n role: z.enum(['system', 'user', 'assistant', 'function']),\n name: z.string().optional().meta({\n description: 'An optional name for the task',\n }),\n content: TaskContent.describe(\n `This is the actual content of the task. This is the actual content which is process at each step.\nFor example this is, what an LLM would actually get to see. There are only a few different ways\nof how content can be structured. `,\n ),\n label: z.array(z.string()).optional(),\n parentID: z.string().optional().meta({\n description: 'The ID of the parent task which created this subtask on a lower stack level',\n }),\n priorID: z.string().optional().meta({\n description: 'The ID of the previous task in the same stack level.',\n }),\n // TODO: validate this ID using our content address creation functions\n id: z.string(),\n authorId: z.string().optional(),\n created_at: z.number().optional(),\n acl: z.string().array().optional()\n .describe(`A number of public keys which act as access control lists (ACL).\nThey are given certain as a list of public keys + type of ownership.\n [\"pubkey:owner\", \"pubkey:editor1\", \"pubkey:editor2\"]\n\n The value is optional. If no ACL is specified, the task is \"public\" and\n can for example be freely exchange in p2p settings.\n\nTODO: define onwership types..`),\n sig: z.string().optional().meta({\n description:\n 'A signature from the author of the Task. It is created from the entire content of the tasj except for the signature itself.',\n }),\n})\nexport type TaskNode = z.infer<typeof TaskNode>\n\nexport const partialTaskDraft = TaskNode.partial().required({ role: true, content: true }).meta({\n description:\n 'This is just a subset of the task properties which can be used to define new tasks in various places.',\n})\nexport type partialTaskDraft = z.infer<typeof partialTaskDraft>\n\n// If you want to map them to { label, value } for q-select:\nexport const taskTypeOptions = TaskContent.options.map((opt) => {\n // each option is a ZodObject with a `type` literal\n return opt.shape.type._zod.def.values[0]!\n})\n\n// TODO: the goal should be to slowly replace this state by the \"result of the task\"\n// E.g. when a task had an error, this would be represented in the task result as an \"error\"\nconst TaskState = z.enum(['Open', 'Queued', 'In Progress', 'Completed', 'Cancelled', 'Error'])\n .describe(`The task state indicates on what is happening with the task: for example\nit shows whether a task flow is seen as \"completed\" or whether its waiting\nto be further processed... E.g. there could be a task with no results, which stil counts as \"completed\"`)\nexport type TaskState = z.infer<typeof TaskState>\n\n// Now pull out the tooldefinition variant and fully expand it:\n/*type ToolDefinitionNode = ExpandRecursively<\n Omit<TaskNode, 'content'> & {\n content: Extract<TaskNode['content'], { type: 'tooldefinition' }>\n }\n>*/\n\n/*type ToolDefinitionNode = TaskNode extends { content: infer C }\n ? C extends { type: 'tooldefinition' }\n ? Expand<Omit<TaskNode, 'content'> & { content: C }>\n : never\n : never*/\n\n// 2. Generic extractor by content.type\nexport type TaskNodeType<K extends TaskNode['content']['type']> = TaskNode extends {\n content: infer C\n}\n ? C extends { type: K }\n ? Expand<Omit<TaskNode, 'content'> & { content: C }>\n : never\n : never\n/*\n// 3. Example usages\ntype ToolDefNode = TaskNodeType<\"tooldefinition\">\ntype MessageNode = TaskNodeType<\"message\">\ntype ToolResultNode = TaskNodeType<\"toolresult\">\n*/\n\nexport type TaskGetter = (input: string) => Promise<TaskNode | null>\n\nexport type FileMapping = {\n id: string\n name?: string\n size?: number\n // filename in opfs\n opfs?: string\n openAIFileId?: string\n // TODO: we're not sure if we need a file path?\n type: string\n // sometimes, for very small files, it might make sense to attach the data here directly?\n data?: string\n}\n\nexport interface TaskTreeNode {\n task: TaskNode\n children: TaskTreeNode[][]\n}\n","export function uint8ArrayToBase64UrlSafe(data: Uint8Array | ArrayBuffer) {\n const u8 = data instanceof Uint8Array ? data : new Uint8Array(data)\n let binary = ''\n for (let i = 0; i < u8.length; i++) {\n binary += String.fromCharCode(u8[i]!)\n }\n return btoa(binary)\n .replace(/\\+/g, '-') // Convert '+' to '-'\n .replace(/\\//g, '_') // Convert '/' to '_'\n .replace(/=+$/, '') // Remove trailing '='\n}\n\nexport function base64UrlToUint8Array(base64UrlString: unknown): Uint8Array<ArrayBuffer> {\n if (typeof base64UrlString !== 'string') {\n throw new TypeError('Expected base64UrlString to be a string')\n }\n const padding = '='.repeat((4 - (base64UrlString.length % 4)) % 4)\n const base64 = base64UrlString.replace(/-/g, '+').replace(/_/g, '/') + padding\n\n const binaryString = atob(base64)\n const len = binaryString.length\n const arr = new Uint8Array(len)\n for (let i = 0; i < len; i++) {\n arr[i] = binaryString.charCodeAt(i)\n }\n // re-wrap ensures it's `ArrayBuffer`, not `ArrayBufferLike`\n return new Uint8Array(arr)\n}\n\nexport async function sha256UrlSafeHash(obj: unknown) {\n const json = JSON.stringify(obj)\n const encoder = new TextEncoder()\n const data = encoder.encode(json)\n\n const hashBuffer = await crypto.subtle.digest('SHA-256', data)\n return uint8ArrayToBase64UrlSafe(hashBuffer)\n}\n\nexport async function sha256UrlSafeHashFromFile(file: File): Promise<string> {\n const buffer = await file.arrayBuffer()\n const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)\n return uint8ArrayToBase64UrlSafe(hashBuffer)\n}\n","import type z from 'zod'\nimport type { partialTaskDraft } from '../types/node'\nimport { TaskNode } from '../types/node'\nimport { sha256UrlSafeHash } from '../utils/encoding'\n\nconst TaskWithoutId = TaskNode.omit({ id: true }).strip()\nexport type TaskWithoutId = z.infer<typeof TaskWithoutId>\n\nfunction normalizeObj<T extends Record<string, unknown>>(task: T): T {\n // deep clone plain JSON-compatible values\n const clone: T = JSON.parse(JSON.stringify(task))\n\n // enforce alphabetical key order\n const sorted = Object.keys(clone)\n .sort()\n .reduce((acc, key) => {\n acc[key as keyof T] = clone[key as keyof T]\n return acc\n }, {} as T)\n\n return sorted\n}\n\nasync function taskContentHash(\n task: partialTaskDraft,\n): Promise<{ hash: string; normalized: TaskWithoutId }> {\n if (typeof crypto === 'undefined' || !crypto.subtle) {\n throw new Error(\n 'crypto.subtle is not available in this environment, We can currently not generate task IDs!!',\n )\n }\n\n console.log('generating new hash ID for task')\n // we need to verify that our task is of type TaskNode without ID and we do this using Zod :)\n // we also want to make sure, that we only strip away anything which isn't official\n // part of our tasknode..\n const taskWithoutId = TaskWithoutId.parse(task)\n const normalized = normalizeObj(taskWithoutId)\n // generate this hash ID to check of there are any duplicate tasks or anything like that...\n const hash = await sha256UrlSafeHash(normalized)\n return { hash, normalized }\n}\n\nexport async function ensureValidTaskId(task: partialTaskDraft): Promise<TaskNode> {\n const { hash, normalized } = await taskContentHash(task)\n if (task.id && hash !== task.id) {\n throw new Error(\n `Not able to create new task as id doesn't match content. Expected: ${hash} got: ${task.id}.`,\n )\n }\n return { ...normalized, id: hash } as TaskNode\n}\n\n// the following function can be used to calculate Ids for an entire\n// chain.\nexport const forgeTaskChain = async (tasks: partialTaskDraft[][]) => {\n const flattened: TaskNode[] = []\n for (const tl of tasks) {\n let lastTaskId: string | undefined = undefined\n for (const t of tl) {\n const task = await createTaskNode({ ...t, priorID: lastTaskId }, { createMeta: 'missing' })\n lastTaskId = task.id\n flattened.push(task)\n }\n }\n return flattened\n}\n\nfunction addTaskNodeMeta(\n options: { createMeta?: 'missing' | 'overwrite' | undefined },\n task: partialTaskDraft,\n): partialTaskDraft {\n const next = { ...task }\n if (options.createMeta === 'overwrite') {\n next.created_at = Date.now()\n }\n if (options.createMeta !== undefined && !next.created_at) {\n next.created_at = Date.now()\n }\n return next\n}\n\nexport const createTaskNode = async (\n task: partialTaskDraft,\n options: {\n createMeta?: 'missing' | 'overwrite' | undefined\n } = { createMeta: 'missing' },\n): Promise<TaskNode> => {\n // if task already has an id, do nothing and only ensure, that the id is valid!\n if (!task.id) {\n // TODO: add task signature and other metadata here as well\n const newTask = addTaskNodeMeta(options, task)\n return ensureValidTaskId(newTask)\n }\n return ensureValidTaskId(task)\n}\n","import type { JSONSchema, FromSchema } from 'json-schema-to-ts'\nimport z from 'zod'\nimport type { WithRequired } from '../utils/tsHelpers'\nimport { partialTaskDraft, type TaskNode } from './node'\nimport type { FunctionCall } from './tools'\nimport { ToolBase, taskMarker } from './tools'\n\n/**\n * Represents the context passed to tools within the Taskyon system.\n *\n * @property taskChain - The sequence of TaskNode objects representing the current chain of tasks.\n * @property getSecret - Retrieves a secret value by name. If `askNew` is `true`, prompts for a new secret if it doesn't exist.\n * If `askNew` is a string, uses the string as a custom message or hint when prompting for the secret.\n * @param name - The name of the secret to retrieve.\n * @param askNew - If `true`, prompts for a new secret if not found. If a string, uses it as a hint or message when prompting.\n * @returns A promise resolving to the secret value, or `undefined` if not found.\n *\n * @property setSecret - Stores a secret value by name.\n * @param name - The name of the secret to store.\n * @param value - The secret value to store.\n * @returns A promise that resolves when the secret is stored.\n * @property stopSignal - An AbortSignal that can be used to detect if the tool should stop execution.\n * @property toolId - The unique identifier for the tool instance.\n */\nexport type toolContext = {\n taskChain: TaskNode[]\n getSecret: (name: string, askNew: boolean | string, saveNew?: boolean) => Promise<string | null>\n setSecret: (name: string, value: string) => Promise<void>\n stopSignal: AbortSignal\n toolId: string\n messagePort?: MessagePort // optional message port for communication\n}\n\n// TODO: make all of this generic functions in order to get better typescript checking\nconst internalToolFunctionSchema = z.custom<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (params: any, context: toolContext) => unknown // unknown also includes Promise<unknown>\n>((val) => typeof val === 'function', {\n message: 'Expected a function that accepts any arguments and returns unknown or Promise<unknown>',\n})\nexport type internalToolFunctionSchema = z.infer<typeof internalToolFunctionSchema>\n\nconst InternalTool = ToolBase.extend({\n // TODO: take away he \"optional\" from this type here...\n function: internalToolFunctionSchema.optional(),\n}).meta({\n description: 'Internal tool definition, which has access to the taskyon system',\n})\nexport type InternalTool = z.infer<typeof InternalTool>\n\nexport type ClientTool = WithRequired<InternalTool, 'function'>\n\n// Create a helper function to preserve schema types\nexport function createTool<\n T,\n SCHEMA extends Readonly<JSONSchema>,\n PARAMS = FromSchema<SCHEMA, { keepDefaultedPropertiesOptional: true }>,\n>(\n tool: T & {\n parameters: SCHEMA\n function?: (params: PARAMS, context: toolContext) => unknown\n } & Omit<InternalTool, 'function' | 'parameters'>,\n): T {\n console.log('create tool', tool.name)\n return tool\n}\n\n// TODO: automatically type the FunctionCall correctly using the\n// json definition from a tool :)\nexport function toolCall<T extends FunctionCall['arguments']>(\n f: { arguments: T } & FunctionCall,\n): partialTaskDraft & { content: { type: 'functioncall'; data: FunctionCall } } {\n return {\n role: 'function',\n content: {\n type: 'functioncall',\n data: f,\n },\n }\n}\n\nexport const taskResult = z.object({\n taskResultMarker: z.literal(taskMarker).default(taskMarker).meta({\n description:\n 'we use this marker in order to indicate that the result should be added as new tasks!',\n }),\n taskChainList: z.array(z.array(partialTaskDraft)),\n})\nexport type taskResult = z.infer<typeof taskResult>\n\nexport function makeTaskResult(\n tasks: partialTaskDraft | partialTaskDraft[] | partialTaskDraft[][],\n): taskResult {\n let tasksArray: partialTaskDraft[][]\n if (Array.isArray(tasks)) {\n if (Array.isArray(tasks[0])) {\n // Already a 2D array\n tasksArray = tasks as partialTaskDraft[][]\n } else {\n // 1D array, wrap in another array\n tasksArray = [tasks as partialTaskDraft[]]\n }\n } else {\n // 0D, wrap in 2D array\n tasksArray = [[tasks]]\n }\n tasks = tasksArray\n return {\n taskResultMarker: taskMarker,\n taskChainList: tasks,\n }\n}\n","import z from 'zod'\nimport { FunctionArguments } from './tools'\n\nconst RemoteFunctionBase = z.object({\n functionName: z.string().meta({\n description: 'the name of the function',\n }),\n})\n\nexport const RemoteFunctionCall = RemoteFunctionBase.extend({\n type: z.literal('functionCall').meta({\n description: 'Field to indicate what kind of a message we have here.',\n }),\n arguments: FunctionArguments.optional().meta({\n description: 'the arguments for the function as a json object',\n }),\n}).meta({\n description:\n 'This type is used for sending messages with function calls between windows. E.g. from iframe to parent',\n})\nexport type RemoteFunctionCall = z.infer<typeof RemoteFunctionCall>\n\nexport const RemoteFunctionResponse = RemoteFunctionBase.extend({\n type: z.literal('functionResponse').meta({\n description: 'Field to indicate what kind of a message we have here.',\n }),\n response: z.unknown().optional().meta({\n description: 'response of a FunctionCall, e.g. through postMessage with iframes.',\n }),\n error: z\n .unknown()\n .optional()\n .meta({ description: 'if an error occurs in the remote function, we can use this property' }),\n}).meta({\n description:\n 'This type is used for sending messages with the result of a remote function call between windows. E.g. from parent to taskyon iframe',\n})\nexport type RemoteFunctionResponse = z.infer<typeof RemoteFunctionResponse>\n","import { z } from 'zod'\nimport { sha256UrlSafeHashFromFile } from '../utils/encoding'\nimport type { ByType } from '../utils/tsHelpers'\nimport { RemoteFunctionCall, RemoteFunctionResponse } from './messages'\nimport { partialTaskDraft, TaskNode } from './node'\nimport { ToolBase } from './tools'\n\n// TODO: most of the messages here should have an equivalent encrypted version!\n\n// TODO: merge this with \"taskCreated\" message!\nexport const EncryptedTasks = z.object({\n type: z.literal('addTasks'),\n data: z.instanceof(Uint8Array<ArrayBuffer>) as z.ZodType<Uint8Array<ArrayBuffer>>,\n info: z.string(),\n ids: z.array(z.string()),\n})\n\nexport const RequestTask = z.object({\n type: z.literal('requestTask'),\n id: z.string(),\n})\n\nexport const TaskCreated = z.object({\n type: z.literal('taskCreated'),\n task: TaskNode.optional(),\n // TODO: add optional encrypted task!\n ids: z.array(z.string()).optional(),\n info: z.string().optional(),\n})\n\nconst TaskMessage = z\n .object({\n type: z.literal('task').meta({\n description: 'Field to indicate what kind of a message we have here.',\n }),\n task: partialTaskDraft,\n // TODO: we don't need this anymore.. any functioncall task is one that should be \"executed\"\n execute: z.boolean().default(false).meta({\n description: 'should the task be queued for execution?',\n }),\n /* TODO: this needs to be captured in the frontend somehow!\n // but we first add it to the tasks and get back a content ID in the backend.\n // so not sure yet how to do this...The backend soehow would have to communicate this to the frontend..\n // maybe we could do this through teh \"back-channel?\"*/\n show: z.boolean().default(false).meta({\n description: 'select the task in the GUI',\n }),\n })\n .meta({\n description:\n 'With this message type we can send tasks to taskyon from outside, e.g. a parent to a taskyon iframe',\n })\n\n// merge this with \"TaskMessage\"\nconst TaskChainMessage = z.object({\n type: z.literal('tasks').meta({\n description: 'Field to indicate what kind of a message we have here.',\n }),\n execute: z.boolean().default(false),\n tasks: partialTaskDraft.array(),\n show: z.boolean().default(false).meta({\n description: 'select the last task in the GUI',\n }),\n})\n\nconst FunctionDescriptionMessage = ToolBase.extend({\n type: z.literal('functionDescription').meta({\n description: 'Field to indicate that this is a function description message.',\n }),\n})\n\nconst TyReadyMessage = z.object({ type: z.literal('taskyonReady') }).meta({\n description: 'simple message which signals, that our API is ready!',\n})\n\nexport const BaseMessage = z.object({\n origin: z.string().optional(),\n peerId: z.string().optional(),\n})\n\nconst TyStatusMessage = z\n .object({\n type: z.literal('status'),\n data: z.object({\n type: z.literal('newtool'),\n id: z.string().meta({ description: 'id of new tool' }),\n }),\n })\n .meta({ description: 'A list of status message for taskyon' })\n\nexport const TaskWorkerMessage = z.discriminatedUnion('type', [\n z.object({ ...BaseMessage.shape, ...RemoteFunctionCall.shape }),\n z.object({ ...BaseMessage.shape, ...RemoteFunctionResponse.shape }),\n])\nexport type TaskWorkerMessage = z.infer<typeof TaskWorkerMessage>\n\n// File message\nexport const FileMessage = z.object({\n type: z.literal('file'),\n id: z.string(),\n name: z.string(),\n mime: z.string(),\n size: z.number(),\n store: z.enum(['memory', 'opfs']).optional(),\n file: z.file(), // only supported over MessageChannel for now\n})\nexport type FileMessage = z.infer<typeof FileMessage>\n\nexport const TyP2P = z.discriminatedUnion('type', [EncryptedTasks, RequestTask, TaskCreated])\nexport type TyP2P = z.infer<typeof TyP2P>\n\nexport const TyBusMessage = z.discriminatedUnion('type', [\n ...TyP2P.options,\n z.object({ ...BaseMessage.shape, ...TyStatusMessage.shape }),\n ...TaskWorkerMessage.options,\n])\n\nexport const TaskyonMessage = z.discriminatedUnion('type', [\n // TODO: can we unify the task message with the SyncApi?\n ...TyBusMessage.options,\n z.object({ ...BaseMessage.shape, ...TaskMessage.shape }),\n z.object({ ...BaseMessage.shape, ...TaskChainMessage.shape }),\n z.object({ ...BaseMessage.shape, ...FunctionDescriptionMessage.shape }),\n z.object({ ...BaseMessage.shape, ...TyReadyMessage.shape }),\n z.object({ ...BaseMessage.shape, ...FileMessage.shape }),\n])\n\n// If you want to map them to { label, value } for q-select:\n/*export const messageTypes = TaskyonMessage.options.map((opt) => {\n // each option is a ZodObject with a `type` literal\n return opt.shape.type._zod.def.values[0]!\n})*/\n\nexport type TaskyonMessage = z.infer<typeof TaskyonMessage>\nexport type messageTypes = TaskyonMessage['type']\n\nexport const sendFile =\n (send: (msg: ByType<'file', TaskyonMessage>) => void) => async (file: File) => {\n const id = await sha256UrlSafeHashFromFile(file)\n send({\n type: 'file',\n id,\n name: file.name,\n mime: file.type,\n size: file.size,\n file,\n })\n return id\n }\n","// frpBus.ts\nimport type { z } from 'zod'\n\n/**\n * Functional Reactive Programming (FRP) Bus\n * A simple implementation of an FRP bus using streams and operators.\n * This is a basic implementation and can be extended with more operators as needed.\n */\nexport type Observer<T> = (value: T) => void | Promise<void>\nexport type Unsubscribe = () => void\n\nexport interface Stream<T> {\n (observer: Observer<T>): Unsubscribe\n unsubscribeAll(this: void): void\n filter(this: void, predicate: (value: T) => boolean): Stream<T>\n narrow<U extends T>(this: void, predicate: (value: T) => value is U): Stream<U>\n map<V>(this: void, fn: (value: T) => V): Stream<V>\n wait(this: void, opts: { timeoutMs?: number; signal?: AbortSignal }): Promise<T>\n}\n\nexport type frpBus<T> = {\n stream: Stream<T>\n emit: <U extends T>(value: U) => void\n}\n\n// Creates a simple stream with an \"emit\" function\nexport function createStream<T>(): frpBus<T> {\n const observers: Observer<T>[] = []\n\n const stream = (observer: Observer<T>): Unsubscribe => {\n observers.push(observer)\n return () => {\n const idx = observers.indexOf(observer)\n if (idx >= 0) observers.splice(idx, 1)\n }\n }\n\n stream.unsubscribeAll = () => {\n observers.length = 0\n }\n\n // TODO: if we use a filter like that... how can we make sure, that we unsubscribe from the original\n // stream, if we unsubscrbe from the new stream (unsub)? we might want to have multiple\n // streams subscribing on the filtered, so we can't jsut do it from the last \"unsub\" in the chain...\n // maybe add an \"unsubchain\" or something like that?\n stream.narrow = <U extends T>(pred: (m: T) => m is U) => {\n const newStream = createStream<U>()\n /*const unsub = */ stream((v) => {\n if (pred(v)) newStream.emit(v)\n })\n return newStream.stream\n }\n stream.map = <V>(fn: (value: T) => V): Stream<V> => {\n const newStream = createStream<V>()\n stream((v) => newStream.emit(fn(v)))\n return newStream.stream\n }\n stream.filter = stream.narrow<T>\n stream.wait = ((opts) =>\n new Promise<T>((resolve, reject) => {\n if (opts?.signal?.aborted) {\n const err = new Error('Aborted')\n err.name = 'AbortError'\n reject(err)\n return\n }\n\n let done = false\n let timeout: ReturnType<typeof setTimeout> | undefined\n let unsub: Unsubscribe = () => {}\n\n const finish = (err?: Error, value?: T) => {\n if (done) return\n done = true\n unsub()\n clearTimeout(timeout)\n opts?.signal?.removeEventListener('abort', onAbort)\n if (err) reject(err)\n else resolve(value!)\n }\n\n const onAbort = () => {\n const err = new Error('Aborted')\n err.name = 'AbortError'\n finish(err)\n }\n\n opts?.signal?.addEventListener('abort', onAbort)\n if (opts?.timeoutMs)\n timeout = setTimeout(\n () => finish(new Error(`Timeout after ${opts.timeoutMs}ms`)),\n opts.timeoutMs,\n )\n\n const observer = (value: T) => finish(undefined, value)\n unsub = stream(observer)\n })) as Stream<T>['wait']\n\n return {\n stream,\n emit: (v: T) => {\n ;[...observers].forEach((o) => void o(v))\n },\n }\n}\n\n// extract stream type frm existing stream\nexport type extractStreamType<Type> = Type extends Stream<infer X> ? X : never\n\nexport type Port<Tx, Rx = Tx> = {\n send: frpBus<Tx>['emit']\n receive: frpBus<Rx>['stream']\n // stricter connect signature: intersection forces compile-time failure when constraints don't hold\n connect: <Tx, Rx extends oTx, oTx, oRx extends Tx>(\n this: Port<Tx, Rx>,\n other: Port<oTx, oRx>,\n ) => Unsubscribe\n}\n\nexport type DuplexChannel<Tx, Rx> = { x: Port<Tx, Rx>; y: Port<Rx, Tx> }\n\nconst connectChannels = <Tx, Rx, oTx, oRx>(x: Port<Tx, Rx>, y: Port<oTx, oRx>): Unsubscribe => {\n const unsubX = x.receive((msg) => y.send(msg as unknown as oTx))\n const unsubY = y.receive((msg) => x.send(msg as unknown as Tx))\n\n // Return a function that disconnects both subscriptions\n return () => {\n unsubX()\n unsubY()\n }\n}\n\nconst makePort = <Tx, Rx = Tx>(\n send: frpBus<Tx>['emit'],\n receive: frpBus<Rx>['stream'],\n): Port<Tx, Rx> => {\n const self: Port<Tx, Rx> = {\n send,\n receive,\n connect: (other) => connectChannels(self, other),\n }\n return self\n}\n\nexport const createChannelsFromStreams = <Str1, Str2 = Str1>(\n outS: frpBus<Str1>,\n inS: frpBus<Str2>,\n): DuplexChannel<Str1, Str2> => ({\n x: makePort(outS.emit, inS.stream),\n y: makePort(inS.emit, outS.stream),\n})\n\nexport const createDuplexChannel = <Str1, Str2 = Str1>(): DuplexChannel<Str1, Str2> =>\n createChannelsFromStreams(createStream<Str1>(), createStream<Str2>())\n\nexport function MessageChannelBridge<Tx, Rx = Tx>(dport: Port<Tx, Rx>, mport: MessagePort) {\n const unsub = dport.receive((msg) => mport.postMessage(msg))\n mport.onmessage = (msg) => dport.send(msg.data)\n\n const destroy = () => {\n unsub()\n mport.close()\n }\n\n return { destroy }\n}\n\n/* TODO: adapt this by createing a port which\nexport function portMap<A, B>(\n source: Port<A>,\n fnIn: (value: A) => B,\n fnOut: (value: B) => A,\n): { port: Port<B>; destroy: () => void } {\n const { a: inner, b: outer } = createDuplexChannel<B>()\n\n // Upstream ➜ child (apply the filter)\n const unsubUp = source.receive((m) => {\n inner.send(fnIn(m)) // safe: guard proved it’s TChild\n })\n\n // Child ➜ upstream (no filtering needed)\n const unsubDown = inner.receive((m) => source.send(fnOut(m)))\n\n const destroy = () => {\n unsubUp()\n unsubDown()\n }\n\n return { port: outer, destroy }\n}*/\n\nexport function mapPort<pTx, pRx, cTx extends pTx, cRx extends pRx>(\n port: Port<pTx, pRx>,\n transformTx: (msg: pTx) => cTx,\n transformRx: (msg: pRx) => cRx,\n): { port: Port<cTx, cRx>; destroy: () => void } {\n const { x: filtered, y: internal } = createDuplexChannel<cTx, cRx>()\n\n // Upstream ➜ child (apply the filter)\n const unsubUp = port.receive((m) => {\n internal.send(transformRx(m)) // safe: guard proved it’s TChild\n })\n\n // Child ➜ upstream (no filtering needed)\n const unsubDown = internal.receive((m) => {\n port.send(transformTx(m)) // safe: guard proved it’s TChild\n })\n\n const destroy = () => {\n unsubUp()\n unsubDown()\n }\n\n return { port: filtered, destroy }\n}\n\nexport function createPortFilter<pTx, pRx, cTx extends pTx, cRx extends pRx>(\n port: Port<pTx, pRx>,\n filterTx: (msg: pTx) => msg is cTx,\n filterRx: (msg: pRx) => msg is cRx,\n): { port: Port<cTx, cRx>; destroy: () => void } {\n const { x: filtered, y: internal } = createDuplexChannel<cTx, cRx>()\n\n // Upstream ➜ child (apply the filter)\n const unsubUp = port.receive((m) => {\n if (filterRx(m)) internal.send(m) // safe: guard proved it’s TChild\n })\n\n // Child ➜ upstream (no filtering needed)\n const unsubDown = internal.receive((m) => {\n if (filterTx(m)) port.send(m) // safe: guard proved it’s TChild\n })\n\n const destroy = () => {\n unsubUp()\n unsubDown()\n }\n\n return { port: filtered, destroy }\n}\n\n// lets through messages which are in a list of types...\nexport function createTypeFilteredPort<\n pTx, // Parent Transmit type\n pRx extends { type: string }, // Parent Receive type (the superset union)\n K extends pRx['type'], // An array of keys from the union's 'type' property\n>(\n parent: Port<pTx, pRx>,\n allowedTypes: readonly K[],\n): { port: Port<pTx, Extract<pRx, { type: K }>>; destroy: () => void } {\n // Use a Set for efficient O(1) lookups inside the guard.\n const typeSet = new Set(allowedTypes)\n\n // Define the new, narrower child message type using TypeScript's Extract utility.\n // This extracts all members from the `pRx` union whose `type` property matches one\n // of the strings in the `allowedTypes` array (`T[number]`).\n type cRx = Extract<pRx, { type: K }>\n // Reuse the generic filtered-port helper with a custom type guard.\n return createPortFilter(\n parent,\n (msg): msg is pTx => true,\n (msg): msg is cRx => typeSet.has(msg.type as K),\n )\n}\n\n/** Generic message → handler router (sync or async) */\nexport function createPortApi<\n R,\n Schema extends z.ZodType<{ type: string }>, // your Zod schema\n Msg extends z.infer<Schema>, // union type + discriminator\n Tx,\n Rx = Tx,\n>(\n port: Port<Tx, Rx>,\n schema: Schema,\n handlers: {\n [K in Msg['type']]?: (m: Extract<Msg, { type: K }>) => R | Promise<R>\n },\n defaultHandler?: (m: unknown) => void,\n errorHandler?: (m: unknown) => void,\n) {\n port.receive((raw) => {\n const parsed = schema.safeParse(raw)\n if (!parsed.success) {\n console.error('Invalid message:', parsed.error, raw)\n return\n }\n\n const msg = parsed.data as Msg\n const handle = handlers[msg.type as Msg['type']]\n if (!handle) {\n if (defaultHandler) defaultHandler(msg)\n return\n }\n\n // 1️⃣ Re-narrow the union to the specific variant for this handler\n type Specific = Extract<Msg, { type: typeof msg.type }>\n\n // 2️⃣ Call the handler; Promise.resolve normalises sync/async, catch logs errors\n void Promise.resolve(handle(msg as Specific)).catch((error) => {\n if (errorHandler) errorHandler(error)\n })\n })\n}\n\n/**\n * Merges streams of different types into a single stream emitting a union type.\n * Usage: merge(streamA, streamB) → Stream<A | B>\n */\nexport function merge<T extends unknown[]>(\n ...sources: { [K in keyof T]: Stream<T[K]> }\n): Stream<T[number]> {\n const { stream, emit } = createStream<T[number]>()\n\n sources.forEach((source) => {\n void source((value) => emit(value)) // Full type safety\n })\n\n return stream\n}\n\nexport function requireSubscribers<T>(source: Stream<T>, min: number = 1): Stream<T> {\n const { stream, emit } = createStream<T>()\n let subscriberCount = 0\n\n // Subscribe to the source stream\n void source((value) => {\n if (subscriberCount < min) {\n throw new Error(`Not enough subscribers: got ${subscriberCount}, need at least ${min}`)\n }\n emit(value)\n })\n\n const subscribe = (observer: Observer<T>) => {\n subscriberCount++\n const unsubscribe = stream(observer)\n return () => {\n subscriberCount--\n void Promise.resolve(unsubscribe).then((resolvedUnsubscribe) => resolvedUnsubscribe())\n }\n }\n subscribe.unsubscribeAll = () => {\n stream.unsubscribeAll()\n subscriberCount = 0\n }\n subscribe.narrow = stream.narrow\n subscribe.filter = stream.narrow<T>\n subscribe.wait = stream.wait\n subscribe.map = stream.map\n\n return subscribe\n}\n\nexport function streamProcedureCall<T extends unknown[], R>(timeoutMs?: number) {\n const { stream, emit } = createStream<{\n args: T\n respond: (result: R) => void\n }>()\n\n const emitFunc: (...args: T) => Promise<R> = (...args) => {\n return new Promise<R>((resolve, reject) => {\n let responded = false\n let timeout: ReturnType<typeof setTimeout> | undefined\n // Set up timeout for default or error\n if (timeoutMs !== undefined) {\n timeout = setTimeout(() => {\n if (!responded) {\n responded = true\n // TODO: add default response here...\n reject(new Error('No response within timeout'))\n }\n }, timeoutMs)\n }\n console.log('Emitting args:', args)\n emit({\n args,\n respond: (result: R) => {\n if (!responded) {\n responded = true\n if (timeout) clearTimeout(timeout)\n resolve(result)\n }\n },\n })\n })\n }\n\n return { emitFunc, stream: requireSubscribers(stream, 1) }\n}\n\n// ---- MessagePort <-> FRP bridge ------------------------------------------\n\nexport interface PortBridge<T> {\n /** Stream that mirrors everything coming from the external port */\n stream: Stream<T>\n /** Post into the bus (will also be forwarded to the external port) */\n emit: (value: T) => void\n /** Give this to the iframe (or whatever) */\n port: MessagePort\n /** Cleanup listener, subscription & ports */\n destroy: () => void\n}\n\n/**\n * Creates a MessageChannel and wires one side into a new FRP stream.\n * - Anything the iframe posts arrives on `stream`\n * - Anything you `emit` (or any subscriber emits back into this stream) is posted out to the iframe\n */\nexport function createMessagePortBridge<T>(): PortBridge<T> {\n const { stream, emit } = createStream<T>()\n const { port1, port2 } = new MessageChannel()\n\n // Internal (hidden) side\n port2.start()\n const onMsg = (e: MessageEvent<T>) => emit(e.data)\n port2.addEventListener('message', onMsg)\n\n // Forward stream values out to the external side\n const unsub: Unsubscribe | Promise<Unsubscribe> = stream((v) => {\n // Structured clone is required; assume T is cloneable.\n port2.postMessage(v)\n })\n\n const destroy = () => {\n unsub()\n port2.removeEventListener('message', onMsg)\n port1.close()\n port2.close()\n }\n\n return { stream, emit, port: port1, destroy }\n}\n\nexport function createMessagePortAdapter<T>(stream: Stream<T>) {\n const { port1, port2 } = new MessageChannel()\n\n // Internal (hidden) side\n port2.start()\n // Forward stream values out to the external side\n const unsub: Unsubscribe = stream((v) => {\n // Structured clone is required; assume T is cloneable.\n port2.postMessage(v)\n })\n\n const destroy = () => {\n unsub()\n port1.close()\n port2.close()\n }\n\n return { port: port1, destroy }\n}\n\n// ---- Simple IFrame <-> FRP adapter ---------------------------------------\n\nexport function iframeBridge(\n iframe: HTMLIFrameElement,\n origin: string | null = null, // pass null to skip origin check\n) {\n const win = iframe.contentWindow\n if (!win) throw new Error('iframe has no contentWindow')\n\n const inferred = iframe.src ? new URL(iframe.src, window.location.href).origin : 'null' // about:srcdoc\n const expectedOrigin = origin === undefined ? inferred : origin\n const checkOrigin = expectedOrigin !== null\n\n const { stream, emit } = createStream<unknown>()\n\n const onMessage = (ev: MessageEvent<unknown>) => {\n if (ev.source !== win) return\n if (checkOrigin && ev.origin !== expectedOrigin) return\n emit(ev.data)\n }\n window.addEventListener('message', onMessage)\n\n const post = (msg: unknown) => {\n // If iframe navigated, silently drop\n if (iframe.contentWindow === win) {\n win.postMessage(msg, expectedOrigin ?? '*')\n }\n }\n\n const destroy = () => window.removeEventListener('message', onMessage)\n\n return { stream, emit: post, destroy }\n}\n\n// ---- IFrame Multiplexer --------------------------------------------------\n\nexport type BusMsg<I extends string | number | symbol = string> = { id: I; payload: unknown }\n\nexport type TaskMessageStream = Stream<BusMsg>\n\ninterface Entry {\n ref: WeakRef<HTMLIFrameElement>\n post: (m: unknown) => void\n}\n\n// TODO: add a \"bus\" to the iframe...\n/**\n * Create a multiplexer for bidirectional messaging between the host window\n * and multiple managed iframes. Each iframe is registered under an identifier,\n * and incoming `postMessage` events are routed to a typed stream keyed by id.\n *\n * Features:\n * - `attachIframe(id, iframe, origin?)`: register an iframe with a unique id.\n * - Tracks the iframe with a `WeakRef`, cleaned up automatically if removed.\n * - Determines expected origin from the iframe's `src` unless overridden.\n * - `send(id, msg)`: post a message to the iframe associated with `id`.\n * - Messages are dropped if the iframe is disconnected or garbage collected.\n * - `all$`: a reactive stream of all incoming messages of the form `{ id, payload }`.\n * - Automatic garbage collection:\n * - Uses `WeakRef` + `WeakMap` to avoid leaks.\n * - Periodically sweeps stale entries after `sweepEvery` attaches.\n * - Falls back to manual `gc()` to force a sweep.\n * - `detachId(id)`: manually detach an iframe by id.\n * - `destroy()`: stop listening to window `message` events and clear state.\n *\n * Notes:\n * - `winToId` is a `WeakMap` → iframe window references do not prevent GC.\n * - Origins:\n * - If the iframe has `srcdoc` or `about:srcdoc`, origin is `\"null\"` and messages\n * are sent with target `\"*\"`.\n * - Otherwise the origin is inferred from the iframe `src` or overridden via `origin`.\n *\n * @param sweepEvery number of iframe attaches before scheduling a GC sweep (default: 5).\n * @returns API object: `{ all$, send, attachIframe, detachId, gc, destroy }`.\n */\nexport function createIframeMux<I extends string | number | symbol = string>(sweepEvery = 5) {\n const { stream: all$, emit } = createStream<BusMsg<I>>()\n\n const winToId = new WeakMap<Window, I>()\n const idToEntry = new Map<I, Entry>()\n let attachCountSinceSweep = 0\n\n const onMessage = (ev: MessageEvent) => {\n const id = winToId.get(ev.source as Window)\n if (!id) return\n emit({ id, payload: ev.data })\n }\n window.addEventListener('message', onMessage)\n\n const attachIframe = (id: I, iframe: HTMLIFrameElement, origin?: string) => {\n const win = iframe.contentWindow\n if (!win) throw new Error('iframe has no contentWindow')\n\n winToId.set(win, id)\n\n // Infer origin unless caller overrides. srcdoc/about:srcdoc => \"null\"\n const inferred =\n iframe.src && iframe.src !== 'about:srcdoc'\n ? new URL(iframe.src, window.location.href).origin\n : 'null'\n\n const expected = origin ?? inferred\n const postTarget = expected === 'null' ? '*' : expected\n\n const entry: Entry = {\n ref: new WeakRef(iframe),\n post: (msg: unknown) => {\n const el = entry.ref.deref()\n if (!el || el.contentWindow !== win) return // silently drop\n win.postMessage(msg, postTarget)\n },\n }\n\n idToEntry.set(id, entry)\n\n if (++attachCountSinceSweep >= sweepEvery) {\n attachCountSinceSweep = 0\n scheduleSweep()\n }\n }\n\n const send = (id: I, msg: unknown) => {\n const e = idToEntry.get(id)\n if (!e) return\n const el = e.ref.deref()\n if (!el || !el.isConnected) {\n detachId(id)\n return\n }\n e.post(msg)\n }\n\n const detachId = (id: I) => {\n idToEntry.delete(id)\n // winToId is a WeakMap → GC will clean it up\n }\n\n const sweep = () => {\n for (const [id, e] of idToEntry) {\n const el = e.ref.deref()\n if (!el || !el.isConnected) detachId(id)\n }\n }\n\n const scheduleSweep = () => {\n if ('requestIdleCallback' in window) {\n window.requestIdleCallback(sweep, { timeout: 200 })\n } else {\n setTimeout(sweep, 0)\n }\n }\n\n const gc = sweep\n\n const destroy = () => {\n window.removeEventListener('message', onMessage)\n idToEntry.clear()\n // WeakMaps auto-GC\n }\n\n return { all$, send, attachIframe, detachId, gc, destroy }\n}\n\nexport type IframeMultiPlexer<I extends string | number | symbol = string> = ReturnType<\n typeof createIframeMux<I>\n>\n","// TODO: we want to reduce dependencies to this file here!\n// TODO: maybe move the \"Api\" into its own package?\nimport { forgeTaskChain } from '../core/createTasks'\nimport type { chatCompletionParams } from '../tools/chatCompletionTool'\nimport type { TaskyonMessage } from '../types/apiTypes'\nimport type { TaskContentType, TaskNode } from '../types/node'\nimport { partialTaskDraft } from '../types/node'\nimport { createTool, makeTaskResult, toolCall } from '../types/toolApi'\nimport { type Port } from '../utils/frpBus'\nimport type { ByType } from '../utils/tsHelpers'\n\nexport { BaseMessage, TaskyonMessage, TyP2P } from '../types/apiTypes'\nexport { llmSettings, TyToolchainConfig } from '../types/profiles'\nexport type { ClientTool } from '../types/toolApi'\nexport type { FunctionCall } from '../types/tools'\nexport {\n createDuplexChannel, // utils/frpbus\n createPortApi, // utis/frpbus\n MessageChannelBridge,\n} from '../utils/frpBus'\n\nexport { createTool, makeTaskResult, partialTaskDraft, toolCall }\nexport type { Port }\nexport type processTasksOpts = {\n timeoutMs?: number\n signal?: AbortSignal\n show?: boolean\n}\n\nexport const createChatCompletionTask = (args: chatCompletionParams) =>\n toolCall<chatCompletionParams>({ name: 'chatCompletion', arguments: args })\n\nexport const sendTasks =\n <T extends { type: string }>(tyPort: Port<T | TaskyonMessage>) =>\n async (taskList: partialTaskDraft[][], opts: processTasksOpts) => {\n const tasks = await forgeTaskChain(taskList)\n\n tyPort.send({\n type: 'tasks',\n tasks: tasks,\n execute: true,\n show: opts.show ?? true, // we want to show this task in our GUI as a succesful test\n origin: window.origin,\n })\n\n const initialIds = tasks.map((t) => t.id)\n const subTasks = new Set<string>(initialIds)\n\n // filter for all subtasks\n const subTaskStream = tyPort.receive\n .narrow((m): m is ByType<'taskCreated', TaskyonMessage> & { task: { id: string } } => {\n console.log('api received', m)\n /*const valid =\n m.type === 'taskCreated' && 'task' in m && !!m.task?.id && subTasks.has(m.task?.parentID)*/\n //console.log(valid)\n if (\n m.type === 'taskCreated' &&\n 'task' in m &&\n !!m.task?.id &&\n !!m.task?.parentID &&\n subTasks.has(m.task?.parentID)\n ) {\n subTasks.add(m.task?.id)\n return true\n }\n return false\n })\n .map((msg) => msg.task)\n\n return { initialIds, subTaskStream }\n }\n\n// we make the opts mandatory on purpose so that poeple thing about\n// some sort of quitcondition.\nexport const processTasks = <T extends { type: string }>(tyPort: Port<T | TaskyonMessage>) => {\n const send = sendTasks<T>(tyPort)\n return async (\n taskList: partialTaskDraft[][],\n quitCondition: ((t: TaskNode) => boolean) | TaskContentType | TaskContentType[],\n opts: processTasksOpts,\n ) => {\n const { subTaskStream } = await send(taskList, opts)\n const condition =\n typeof quitCondition === 'string'\n ? subTaskStream.filter((t) => t.content.type === quitCondition)\n : typeof quitCondition === 'object' && Array.isArray(quitCondition)\n ? subTaskStream.filter((t) => quitCondition.includes(t.content.type))\n : subTaskStream.filter(quitCondition)\n\n const unsub = condition((m) => console.log('received matching message on port:', m))\n const lastMsg = await condition.wait(opts)\n console.log('finished processin all tasks!')\n unsub()\n return lastMsg\n }\n}\n","// we can compile this file to js to js using \"yarn build:lib\"\n\nimport type { FunctionCall, Port } from '@taskyon/taskyon/api'\nimport { sendTasks } from '@taskyon/taskyon/api'\nimport {\n // from frp bux with only very few dependencies\n createDuplexChannel, // utis/frpbus\n MessageChannelBridge, // utils/frpbus\n\n // \"processTasks\" currently has the following dependencies:\n // - immer\n processTasks, // types/apiTypes\n type ClientTool,\n type TaskyonMessage,\n} from '@taskyon/taskyon/api'\n// TODO: move this into some other part as well.. maybe into \"GUI\" types or somthing like that?\nimport type {\n partialTyConfiguration,\n TaskyonGuiMessage,\n} from '../../../src/modules/taskyon/apiTypes'\nimport { sendFile } from '../../taskyon/src/types/apiTypes'\nexport {\n createChatCompletionTask,\n createTool, // toolApi\n makeTaskResult, // toolApi\n processTasks, // api/index, types/apiTypes\n toolCall, // toolApi\n type partialTaskDraft,\n} from '@taskyon/taskyon/api'\nexport type { ClientTool, partialTyConfiguration, TaskyonGuiMessage, TaskyonMessage }\n\nfunction safeClone<T>(data: T): T {\n try {\n return structuredClone(data)\n } catch {\n return JSON.parse(JSON.stringify(data))\n }\n}\n\nconst waitForApiChannel = (iframe: HTMLIFrameElement): Promise<MessagePort> => {\n return new Promise<MessagePort>((resolve) => {\n let stopped = false\n\n const tryConnect = () => {\n if (stopped) return\n\n const channel = new MessageChannel()\n const targetOrigin = new URL(iframe.src, location.href).origin || '*' // '' for about:blank/file:\n //console.log('tyclient establishing iframe communication to', targetOrigin)\n\n // self‑destructing listener – removed automatically after it fires once\n const handleFirst: (ev: MessageEvent) => void = (ev) => {\n console.log('tyclient received first message from taskyon!', ev)\n stopped = true\n\n channel.port1.removeEventListener('message', handleFirst) // ⬅️ unsubscribe\n clearTimeout(retryTimer) // stop retry loop\n resolve(channel.port1) // hand over the port\n }\n\n channel.port1.addEventListener('message', handleFirst, { once: true })\n channel.port1.start() // ← wake the port so it can receive\n\n try {\n iframe.contentWindow?.postMessage({ type: 'initPort' }, targetOrigin, [channel.port2])\n } catch {\n /* DataCloneError can happen on FF if the iframe isn’t ready yet; ignore */\n }\n\n // retry after 200 ms if handshake hasn’t happened\n const retryTimer = setTimeout(() => {\n if (!stopped) {\n channel.port1.close() // avoid leaking unused ports\n channel.port2.close()\n tryConnect()\n }\n }, 200)\n }\n\n tryConnect()\n })\n}\n\nasync function handleFunctionExecution(\n args: FunctionCall['arguments'],\n tool: ClientTool,\n stopSignal: AbortSignal,\n) {\n // with this we make sure, that we can also handle async functions :)\n const result = await tool.function(args, {\n taskChain: [],\n getSecret: (name) => {\n console.log('tyclient get secret name', name)\n return Promise.resolve('N/A')\n },\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setSecret: (name, _value) => {\n console.log('tyclient set secret name', name)\n return Promise.resolve()\n },\n stopSignal,\n toolId: 'N/A',\n })\n\n return result\n}\n\nexport interface TyClient {\n sendTasks: ReturnType<typeof sendTasks>\n waitForTaskResult: ReturnType<typeof processTasks>\n port: Port<TaskyonGuiMessage, TaskyonGuiMessage>\n sendFile: (file: File) => Promise<string>\n reconfigure: (options: {\n name?: string\n persist?: boolean\n tools: ClientTool[]\n configuration: partialTyConfiguration\n }) => void\n}\n\nexport async function initializeTaskyon(options: {\n name?: string\n persist?: boolean\n tools: ClientTool[]\n configuration: partialTyConfiguration\n iframeId?: string\n}): Promise<TyClient> {\n console.log('initialize taskyon tyclient...')\n\n const toolMap = options.tools.reduce<Record<string, ClientTool>>((p, c) => {\n p[c.name] = c\n return p\n }, {})\n\n const taskyon = document.getElementById(options.iframeId ?? 'taskyon') as HTMLIFrameElement\n\n const controller = new AbortController()\n const { x: clientSidePort, y: towardsIframe } = createDuplexChannel<\n TaskyonGuiMessage,\n TaskyonGuiMessage\n >()\n\n if (!taskyon || taskyon.tagName !== 'IFRAME' || taskyon.contentWindow === null)\n throw new Error(`we could not find the taskyon iframe with id: ${options.iframeId}`)\n\n console.log('make sure, we can ')\n // TODO: detect disconnect and reconnect!\n const iframeMessagePort = await waitForApiChannel(taskyon)\n MessageChannelBridge(towardsIframe, iframeMessagePort)\n const send = (msg: TaskyonGuiMessage) => {\n console.log('tyclient sending', msg)\n clientSidePort.send(safeClone(msg))\n }\n\n console.log('tyclient send our configuration!')\n send({\n type: 'configurationMessage',\n conf: options.configuration,\n persist: options.persist,\n origin: window.location.origin,\n peerId: options?.name,\n })\n\n console.log('tyclient sending our functions!')\n options.tools.forEach((t) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { function: _toolfunc, ...fdescr } = t\n send({\n type: 'functionDescription',\n ...fdescr,\n })\n })\n\n console.log('tyclient set up function listener!')\n\n clientSidePort.receive((msg) => console.log('tyclient received message', msg))\n clientSidePort.receive.narrow((msg) => msg.type === 'functionCall')(async (msg) => {\n const tool = toolMap[msg.functionName]\n if (tool) {\n const res = await handleFunctionExecution(msg.arguments ?? {}, tool, controller.signal)\n send({ type: 'functionResponse', functionName: tool.name, response: res })\n console.log('tyclient tool send functionResponse to iframe', res, tool)\n }\n })\n\n return {\n sendTasks: sendTasks(clientSidePort),\n waitForTaskResult: processTasks(clientSidePort),\n port: clientSidePort,\n sendFile: (file: File) => sendFile(clientSidePort.send)(file),\n reconfigure: (options: {\n name?: string\n persist?: boolean\n tools: ClientTool[]\n configuration: partialTyConfiguration\n }) => {\n send({\n type: 'configurationMessage',\n conf: options.configuration,\n persist: options.persist,\n origin: window.location.origin,\n peerId: options?.name,\n })\n },\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@taskyon/tyclient",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "license": "MIT",
5
5
  "main": "./dist/tyclient.js",
6
6
  "module": "./dist/tyclient.mjs",